[GRASS-SVN] r68374 - in grass/trunk/gui: scripts wxpython wxpython/animation wxpython/core wxpython/datacatalog wxpython/dbmgr wxpython/docs/wxgui_sphinx wxpython/gcp wxpython/gmodeler wxpython/gui_core wxpython/iclass wxpython/icons wxpython/iscatt wxpython/lmgr wxpython/location_wizard wxpython/mapdisp wxpython/mapswipe wxpython/mapwin wxpython/modules wxpython/nviz wxpython/psmap wxpython/rdigit wxpython/rlisetup wxpython/timeline wxpython/tools wxpython/tplot wxpython/vdigit wxpython/vnet wxpython/web_services wxpython/wxplot

svn_grass at osgeo.org svn_grass at osgeo.org
Tue May 3 12:04:42 PDT 2016


Author: martinl
Date: 2016-05-03 12:04:42 -0700 (Tue, 03 May 2016)
New Revision: 68374

Modified:
   grass/trunk/gui/scripts/d.wms.py
   grass/trunk/gui/wxpython/animation/anim.py
   grass/trunk/gui/wxpython/animation/controller.py
   grass/trunk/gui/wxpython/animation/data.py
   grass/trunk/gui/wxpython/animation/dialogs.py
   grass/trunk/gui/wxpython/animation/frame.py
   grass/trunk/gui/wxpython/animation/g.gui.animation.py
   grass/trunk/gui/wxpython/animation/mapwindow.py
   grass/trunk/gui/wxpython/animation/nviztask.py
   grass/trunk/gui/wxpython/animation/provider.py
   grass/trunk/gui/wxpython/animation/temporal_manager.py
   grass/trunk/gui/wxpython/animation/toolbars.py
   grass/trunk/gui/wxpython/animation/utils.py
   grass/trunk/gui/wxpython/core/__init__.py
   grass/trunk/gui/wxpython/core/debug.py
   grass/trunk/gui/wxpython/core/gcmd.py
   grass/trunk/gui/wxpython/core/gconsole.py
   grass/trunk/gui/wxpython/core/giface.py
   grass/trunk/gui/wxpython/core/globalvar.py
   grass/trunk/gui/wxpython/core/gthread.py
   grass/trunk/gui/wxpython/core/layerlist.py
   grass/trunk/gui/wxpython/core/menutree.py
   grass/trunk/gui/wxpython/core/render.py
   grass/trunk/gui/wxpython/core/settings.py
   grass/trunk/gui/wxpython/core/toolboxes.py
   grass/trunk/gui/wxpython/core/treemodel.py
   grass/trunk/gui/wxpython/core/units.py
   grass/trunk/gui/wxpython/core/utils.py
   grass/trunk/gui/wxpython/core/workspace.py
   grass/trunk/gui/wxpython/core/ws.py
   grass/trunk/gui/wxpython/datacatalog/catalog.py
   grass/trunk/gui/wxpython/datacatalog/frame.py
   grass/trunk/gui/wxpython/datacatalog/g.gui.datacatalog.py
   grass/trunk/gui/wxpython/datacatalog/toolbars.py
   grass/trunk/gui/wxpython/datacatalog/tree.py
   grass/trunk/gui/wxpython/dbmgr/__init__.py
   grass/trunk/gui/wxpython/dbmgr/base.py
   grass/trunk/gui/wxpython/dbmgr/dialogs.py
   grass/trunk/gui/wxpython/dbmgr/g.gui.dbmgr.py
   grass/trunk/gui/wxpython/dbmgr/manager.py
   grass/trunk/gui/wxpython/dbmgr/sqlbuilder.py
   grass/trunk/gui/wxpython/dbmgr/vinfo.py
   grass/trunk/gui/wxpython/docs/wxgui_sphinx/conf.py
   grass/trunk/gui/wxpython/gcp/__init__.py
   grass/trunk/gui/wxpython/gcp/g.gui.gcp.py
   grass/trunk/gui/wxpython/gcp/manager.py
   grass/trunk/gui/wxpython/gcp/mapdisplay.py
   grass/trunk/gui/wxpython/gcp/statusbar.py
   grass/trunk/gui/wxpython/gcp/toolbars.py
   grass/trunk/gui/wxpython/gis_set.py
   grass/trunk/gui/wxpython/gis_set_error.py
   grass/trunk/gui/wxpython/gmodeler/__init__.py
   grass/trunk/gui/wxpython/gmodeler/dialogs.py
   grass/trunk/gui/wxpython/gmodeler/frame.py
   grass/trunk/gui/wxpython/gmodeler/g.gui.gmodeler.py
   grass/trunk/gui/wxpython/gmodeler/giface.py
   grass/trunk/gui/wxpython/gmodeler/menudata.py
   grass/trunk/gui/wxpython/gmodeler/model.py
   grass/trunk/gui/wxpython/gmodeler/preferences.py
   grass/trunk/gui/wxpython/gmodeler/toolbars.py
   grass/trunk/gui/wxpython/gui_core/__init__.py
   grass/trunk/gui/wxpython/gui_core/dialogs.py
   grass/trunk/gui/wxpython/gui_core/forms.py
   grass/trunk/gui/wxpython/gui_core/ghelp.py
   grass/trunk/gui/wxpython/gui_core/goutput.py
   grass/trunk/gui/wxpython/gui_core/gselect.py
   grass/trunk/gui/wxpython/gui_core/mapdisp.py
   grass/trunk/gui/wxpython/gui_core/menu.py
   grass/trunk/gui/wxpython/gui_core/preferences.py
   grass/trunk/gui/wxpython/gui_core/prompt.py
   grass/trunk/gui/wxpython/gui_core/pyedit.py
   grass/trunk/gui/wxpython/gui_core/pystc.py
   grass/trunk/gui/wxpython/gui_core/query.py
   grass/trunk/gui/wxpython/gui_core/simplelmgr.py
   grass/trunk/gui/wxpython/gui_core/toolbars.py
   grass/trunk/gui/wxpython/gui_core/treeview.py
   grass/trunk/gui/wxpython/gui_core/vselect.py
   grass/trunk/gui/wxpython/gui_core/widgets.py
   grass/trunk/gui/wxpython/iclass/__init__.py
   grass/trunk/gui/wxpython/iclass/dialogs.py
   grass/trunk/gui/wxpython/iclass/digit.py
   grass/trunk/gui/wxpython/iclass/frame.py
   grass/trunk/gui/wxpython/iclass/g.gui.iclass.py
   grass/trunk/gui/wxpython/iclass/plots.py
   grass/trunk/gui/wxpython/iclass/statistics.py
   grass/trunk/gui/wxpython/iclass/toolbars.py
   grass/trunk/gui/wxpython/icons/__init__.py
   grass/trunk/gui/wxpython/icons/icon.py
   grass/trunk/gui/wxpython/iscatt/__init__.py
   grass/trunk/gui/wxpython/iscatt/controllers.py
   grass/trunk/gui/wxpython/iscatt/core_c.py
   grass/trunk/gui/wxpython/iscatt/dialogs.py
   grass/trunk/gui/wxpython/iscatt/frame.py
   grass/trunk/gui/wxpython/iscatt/iscatt_core.py
   grass/trunk/gui/wxpython/iscatt/plots.py
   grass/trunk/gui/wxpython/iscatt/toolbars.py
   grass/trunk/gui/wxpython/lmgr/__init__.py
   grass/trunk/gui/wxpython/lmgr/frame.py
   grass/trunk/gui/wxpython/lmgr/giface.py
   grass/trunk/gui/wxpython/lmgr/layertree.py
   grass/trunk/gui/wxpython/lmgr/menudata.py
   grass/trunk/gui/wxpython/lmgr/pyshell.py
   grass/trunk/gui/wxpython/lmgr/toolbars.py
   grass/trunk/gui/wxpython/location_wizard/__init__.py
   grass/trunk/gui/wxpython/location_wizard/base.py
   grass/trunk/gui/wxpython/location_wizard/dialogs.py
   grass/trunk/gui/wxpython/location_wizard/wizard.py
   grass/trunk/gui/wxpython/mapdisp/__init__.py
   grass/trunk/gui/wxpython/mapdisp/frame.py
   grass/trunk/gui/wxpython/mapdisp/gprint.py
   grass/trunk/gui/wxpython/mapdisp/main.py
   grass/trunk/gui/wxpython/mapdisp/statusbar.py
   grass/trunk/gui/wxpython/mapdisp/test_mapdisp.py
   grass/trunk/gui/wxpython/mapdisp/toolbars.py
   grass/trunk/gui/wxpython/mapswipe/__init__.py
   grass/trunk/gui/wxpython/mapswipe/dialogs.py
   grass/trunk/gui/wxpython/mapswipe/frame.py
   grass/trunk/gui/wxpython/mapswipe/g.gui.mapswipe.py
   grass/trunk/gui/wxpython/mapswipe/mapwindow.py
   grass/trunk/gui/wxpython/mapswipe/toolbars.py
   grass/trunk/gui/wxpython/mapwin/__init__.py
   grass/trunk/gui/wxpython/mapwin/analysis.py
   grass/trunk/gui/wxpython/mapwin/base.py
   grass/trunk/gui/wxpython/mapwin/buffered.py
   grass/trunk/gui/wxpython/mapwin/decorations.py
   grass/trunk/gui/wxpython/mapwin/graphics.py
   grass/trunk/gui/wxpython/modules/__init__.py
   grass/trunk/gui/wxpython/modules/colorrules.py
   grass/trunk/gui/wxpython/modules/extensions.py
   grass/trunk/gui/wxpython/modules/histogram.py
   grass/trunk/gui/wxpython/modules/import_export.py
   grass/trunk/gui/wxpython/modules/mapsets_picker.py
   grass/trunk/gui/wxpython/modules/mcalc_builder.py
   grass/trunk/gui/wxpython/modules/vclean.py
   grass/trunk/gui/wxpython/modules/vkrige.py
   grass/trunk/gui/wxpython/nviz/__init__.py
   grass/trunk/gui/wxpython/nviz/animation.py
   grass/trunk/gui/wxpython/nviz/main.py
   grass/trunk/gui/wxpython/nviz/mapwindow.py
   grass/trunk/gui/wxpython/nviz/preferences.py
   grass/trunk/gui/wxpython/nviz/tools.py
   grass/trunk/gui/wxpython/nviz/workspace.py
   grass/trunk/gui/wxpython/nviz/wxnviz.py
   grass/trunk/gui/wxpython/psmap/__init__.py
   grass/trunk/gui/wxpython/psmap/dialogs.py
   grass/trunk/gui/wxpython/psmap/frame.py
   grass/trunk/gui/wxpython/psmap/g.gui.psmap.py
   grass/trunk/gui/wxpython/psmap/instructions.py
   grass/trunk/gui/wxpython/psmap/menudata.py
   grass/trunk/gui/wxpython/psmap/toolbars.py
   grass/trunk/gui/wxpython/psmap/utils.py
   grass/trunk/gui/wxpython/rdigit/__init__.py
   grass/trunk/gui/wxpython/rdigit/controller.py
   grass/trunk/gui/wxpython/rdigit/dialogs.py
   grass/trunk/gui/wxpython/rdigit/toolbars.py
   grass/trunk/gui/wxpython/rlisetup/__init__.py
   grass/trunk/gui/wxpython/rlisetup/frame.py
   grass/trunk/gui/wxpython/rlisetup/functions.py
   grass/trunk/gui/wxpython/rlisetup/g.gui.rlisetup.py
   grass/trunk/gui/wxpython/rlisetup/sampling_frame.py
   grass/trunk/gui/wxpython/rlisetup/wizard.py
   grass/trunk/gui/wxpython/timeline/__init__.py
   grass/trunk/gui/wxpython/timeline/frame.py
   grass/trunk/gui/wxpython/timeline/g.gui.timeline.py
   grass/trunk/gui/wxpython/tools/build_modules_xml.py
   grass/trunk/gui/wxpython/tools/update_menudata.py
   grass/trunk/gui/wxpython/tplot/__init__.py
   grass/trunk/gui/wxpython/tplot/frame.py
   grass/trunk/gui/wxpython/tplot/g.gui.tplot.py
   grass/trunk/gui/wxpython/vdigit/__init__.py
   grass/trunk/gui/wxpython/vdigit/dialogs.py
   grass/trunk/gui/wxpython/vdigit/g.gui.vdigit.py
   grass/trunk/gui/wxpython/vdigit/main.py
   grass/trunk/gui/wxpython/vdigit/mapwindow.py
   grass/trunk/gui/wxpython/vdigit/preferences.py
   grass/trunk/gui/wxpython/vdigit/toolbars.py
   grass/trunk/gui/wxpython/vdigit/wxdigit.py
   grass/trunk/gui/wxpython/vdigit/wxdisplay.py
   grass/trunk/gui/wxpython/vnet/__init__.py
   grass/trunk/gui/wxpython/vnet/dialogs.py
   grass/trunk/gui/wxpython/vnet/toolbars.py
   grass/trunk/gui/wxpython/vnet/vnet_core.py
   grass/trunk/gui/wxpython/vnet/vnet_data.py
   grass/trunk/gui/wxpython/vnet/vnet_utils.py
   grass/trunk/gui/wxpython/vnet/widgets.py
   grass/trunk/gui/wxpython/web_services/__init__.py
   grass/trunk/gui/wxpython/web_services/cap_interface.py
   grass/trunk/gui/wxpython/web_services/dialogs.py
   grass/trunk/gui/wxpython/web_services/widgets.py
   grass/trunk/gui/wxpython/wxgui.py
   grass/trunk/gui/wxpython/wxplot/__init__.py
   grass/trunk/gui/wxpython/wxplot/base.py
   grass/trunk/gui/wxpython/wxplot/dialogs.py
   grass/trunk/gui/wxpython/wxplot/histogram.py
   grass/trunk/gui/wxpython/wxplot/profile.py
   grass/trunk/gui/wxpython/wxplot/scatter.py
Log:
wxGUI: apply pep8
       (autopep8 --in-place --aggressive --recursive --experimental --jobs 4)


Modified: grass/trunk/gui/scripts/d.wms.py
===================================================================
--- grass/trunk/gui/scripts/d.wms.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/scripts/d.wms.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -20,7 +20,7 @@
 #% keyword: raster
 #% keyword: import
 #% keyword: WMS
-#% keyword: WMTS 
+#% keyword: WMTS
 #% keyword: OnEarth
 #%end
 
@@ -66,8 +66,8 @@
 #%option
 #% key: srs
 #% type: integer
-#% description: EPSG code of requested source projection 
-#% answer:4326 
+#% description: EPSG code of requested source projection
+#% answer:4326
 #% guisection: Request
 #%end
 
@@ -161,19 +161,20 @@
 from grass.script import core as grass
 
 sys.path.append(os.path.join(os.getenv("GISBASE"), "etc", "r.in.wms"))
-                
+
+
 def GetRegion():
     """!Parse region from GRASS_REGION env var.
     """
     region = os.environ["GRASS_REGION"]
-    conv_reg_vals = {'east' : 'e',
-                     'north' : 'n',
-                     'west' : 'w',
-                     'south' : 's',
-                     'rows' : 'rows',
-                     'cols' : 'cols',
-                     'e-w resol' : 'ewres',
-                     'n-s resol' : 'nsres'}
+    conv_reg_vals = {'east': 'e',
+                     'north': 'n',
+                     'west': 'w',
+                     'south': 's',
+                     'rows': 'rows',
+                     'cols': 'cols',
+                     'e-w resol': 'ewres',
+                     'n-s resol': 'nsres'}
 
     keys_to_convert = conv_reg_vals.keys()
 
@@ -183,12 +184,13 @@
     for r in region:
         r = r.split(':')
         r[0] = r[0].strip()
-        
+
         if r[0] in keys_to_convert:
             conv_region[conv_reg_vals[r[0]]] = float(r[1])
 
     return conv_region
 
+
 def main():
     options['region'] = GetRegion()
 
@@ -200,8 +202,8 @@
         grass.debug("Using GDAL WMS driver")
         from wms_gdal_drv import WMSGdalDrv
         wms = WMSGdalDrv()
-    
-    temp_map = wms.GetMap(options, flags) 
+
+    temp_map = wms.GetMap(options, flags)
     os.rename(temp_map, os.environ["GRASS_RENDER_FILE"])
 
     return 0

Modified: grass/trunk/gui/wxpython/animation/anim.py
===================================================================
--- grass/trunk/gui/wxpython/animation/anim.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/anim.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -21,6 +21,7 @@
 
 class Animation(wx.EvtHandler):
     """Animation class specifies which frame to show at which instance."""
+
     def __init__(self):
         wx.EvtHandler.__init__(self)
 
@@ -103,7 +104,9 @@
         if not self.IsActive():
             return
         self.currentIndex = 0
-        self.callbackEndAnimation(self.currentIndex, self.GetFrame(self.currentIndex))
+        self.callbackEndAnimation(
+            self.currentIndex, self.GetFrame(
+                self.currentIndex))
 
     def _arrivedToEnd(self):
         """Decides which action to do after animation end (stop, repeat)."""
@@ -132,7 +135,9 @@
         if not self.IsActive():
             return
 
-        self.callbackUpdateFrame(self.currentIndex, self.GetFrame(self.currentIndex))
+        self.callbackUpdateFrame(
+            self.currentIndex, self.GetFrame(
+                self.currentIndex))
         if self.orientation == Orientation.FORWARD:
             self.currentIndex += 1
             if self.currentIndex == self.count:
@@ -147,7 +152,9 @@
         if not self.IsActive():
             return
         self.currentIndex = index
-        self.callbackUpdateFrame(self.currentIndex, self.GetFrame(self.currentIndex))
+        self.callbackUpdateFrame(
+            self.currentIndex, self.GetFrame(
+                self.currentIndex))
 
     def PreviousFrameIndex(self):
         if not self.IsActive():
@@ -173,7 +180,7 @@
             if self.currentIndex == -1:
                 self.currentIndex = 0
 
-#def test():
+# def test():
 #    import wx
 #    app = wx.PySimpleApp()
 #    a = Animation()
@@ -187,5 +194,5 @@
 #    app.MainLoop()
 #
 #
-#if __name__ == '__main__':
+# if __name__ == '__main__':
 #    test()

Modified: grass/trunk/gui/wxpython/animation/controller.py
===================================================================
--- grass/trunk/gui/wxpython/animation/controller.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/controller.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -29,7 +29,9 @@
 
 
 class AnimationController(wx.EvtHandler):
-    def __init__(self, frame, sliders, animations, mapwindows, provider, bitmapPool, mapFilesPool):
+
+    def __init__(self, frame, sliders, animations, mapwindows,
+                 provider, bitmapPool, mapFilesPool):
         wx.EvtHandler.__init__(self)
 
         self.mapwindows = mapwindows
@@ -50,10 +52,13 @@
         self.bitmapProvider = provider
         for anim, win in zip(self.animations, self.mapwindows):
             anim.SetCallbackUpdateFrame(
-                lambda index, dataId, win=win: self.UpdateFrame(index, win, dataId))
+                lambda index, dataId, win=win: self.UpdateFrame(
+                    index, win, dataId))
             anim.SetCallbackEndAnimation(
-                lambda index, dataId, win=win: self.UpdateFrameEnd(index, win, dataId))
-            anim.SetCallbackOrientationChanged(self.OrientationChangedInReverseMode)
+                lambda index, dataId, win=win: self.UpdateFrameEnd(
+                    index, win, dataId))
+            anim.SetCallbackOrientationChanged(
+                self.OrientationChangedInReverseMode)
 
         for slider in self.sliders.values():
             slider.SetCallbackSliderChanging(self.SliderChanging)
@@ -199,8 +204,12 @@
         # if self.timer.IsRunning():
         #     running = True
         self.EndAnimation()
-        dlg = EditDialog(parent=self.frame, evalFunction=self.EvaluateInput,
-                         animationData=self.animationData, maxAnimations=len(self.animations))
+        dlg = EditDialog(
+            parent=self.frame,
+            evalFunction=self.EvaluateInput,
+            animationData=self.animationData,
+            maxAnimations=len(
+                self.animations))
         dlg.CenterOnParent()
         if dlg.ShowModal() == wx.ID_CANCEL:
             dlg.Destroy()
@@ -220,8 +229,10 @@
                 break
 
         if not found:
-            GMessage(parent=self.frame,
-                     message=_("Maximum number of animations is %s.") % len(self.animations))
+            GMessage(
+                parent=self.frame,
+                message=_("Maximum number of animations is %s.") %
+                len(self.animations))
             return
 
         # running = False
@@ -232,9 +243,13 @@
 
         animData = AnimationData()
         # number of active animations
-        animationIndex = len([anim for anim in self.animations if anim.IsActive()])
+        animationIndex = len(
+            [anim for anim in self.animations if anim.IsActive()])
         animData.SetDefaultValues(windowIndex, animationIndex)
-        dlg = InputDialog(parent=self.frame, mode='add', animationData=animData)
+        dlg = InputDialog(
+            parent=self.frame,
+            mode='add',
+            animationData=animData)
         dlg.CenterOnParent()
         if dlg.ShowModal() == wx.ID_CANCEL:
             dlg.Destroy()
@@ -242,11 +257,14 @@
         dlg.Destroy()
         # check compatibility
         if animData.windowIndex in indices:
-            GMessage(parent=self.frame, message=_("More animations are using one window."
-                                                  " Please select different window for each animation."))
+            GMessage(
+                parent=self.frame, message=_(
+                    "More animations are using one window."
+                    " Please select different window for each animation."))
             return
         try:
-            temporalMode, tempManager = self.EvaluateInput(self.animationData + [animData])
+            temporalMode, tempManager = self.EvaluateInput(
+                self.animationData + [animData])
         except GException as e:
             GError(parent=self.frame, message=e.value, showTraceback=False)
             return
@@ -299,9 +317,13 @@
             if anim.viewMode == '2d':
                 anim.cmdMatrix = layerListToCmdsMatrix(anim.layerList)
             else:
-                anim.cmdMatrix = [(cmd,) for cmd in anim.GetNvizCommands()['commands']]
+                anim.cmdMatrix = [(cmd,)
+                                  for cmd in anim.GetNvizCommands()
+                                  ['commands']]
         self._updateSlider(timeLabels=timeLabels)
-        self._updateAnimations(activeIndices=indices, mapNamesDict=mapNamesDict)
+        self._updateAnimations(
+            activeIndices=indices,
+            mapNamesDict=mapNamesDict)
         wx.Yield()
         self._updateBitmapData()
         # if running:
@@ -331,30 +353,34 @@
                 if i not in activeIndices:
                     self.animations[i].SetActive(False)
                     continue
-                anim = [anim for anim in self.animationData if anim.windowIndex == i][0]
+                anim = [anim for anim in self.animationData
+                        if anim.windowIndex == i][0]
                 w, h = self.mapwindows[i].GetClientSize()
                 regions = anim.GetRegions(w, h)
-                self.animations[i].SetFrames([HashCmds(cmdList, region)
-                                              for cmdList, region in zip(anim.cmdMatrix, regions)])
+                self.animations[i].SetFrames(
+                    [HashCmds(cmdList, region) for cmdList,
+                     region in zip(anim.cmdMatrix, regions)])
                 self.animations[i].SetActive(True)
         else:
             for i in range(len(self.animations)):
                 if i not in activeIndices:
                     self.animations[i].SetActive(False)
                     continue
-                anim = [anim for anim in self.animationData if anim.windowIndex == i][0]
+                anim = [anim for anim in self.animationData
+                        if anim.windowIndex == i][0]
                 w, h = self.mapwindows[i].GetClientSize()
                 regions = anim.GetRegions(w, h)
-                identifiers = sampleCmdMatrixAndCreateNames(anim.cmdMatrix,
-                                                            mapNamesDict[anim.firstStdsNameType[0]],
-                                                            regions)
+                identifiers = sampleCmdMatrixAndCreateNames(
+                    anim.cmdMatrix, mapNamesDict[
+                        anim.firstStdsNameType[0]], regions)
                 self.animations[i].SetFrames(identifiers)
                 self.animations[i].SetActive(True)
 
     def _updateWindows(self, activeIndices):
         # add or remove window
         for windowIndex in range(len(self.animations)):
-            if not self.frame.IsWindowShown(windowIndex) and windowIndex in activeIndices:
+            if not self.frame.IsWindowShown(
+                    windowIndex) and windowIndex in activeIndices:
                 self.frame.AddWindow(windowIndex)
             elif self.frame.IsWindowShown(windowIndex) and windowIndex not in activeIndices:
                 self.frame.RemoveWindow(windowIndex)
@@ -370,18 +396,27 @@
             else:
                 self._load3DData(animData)
             self._loadLegend(animData)
-        color = UserSettings.Get(group='animation', key='bgcolor', subkey='color')
-        cpus = UserSettings.Get(group='animation', key='nprocs', subkey='value')
+        color = UserSettings.Get(
+            group='animation',
+            key='bgcolor',
+            subkey='color')
+        cpus = UserSettings.Get(
+            group='animation',
+            key='nprocs',
+            subkey='value')
         self.bitmapProvider.Load(nprocs=cpus, bgcolor=color)
         # clear pools
         self.bitmapPool.Clear()
         self.mapFilesPool.Clear()
 
     def _set2DData(self, animationData):
-        opacities = [layer.opacity for layer in animationData.layerList if layer.active]
+        opacities = [
+            layer.opacity for layer in animationData.layerList
+            if layer.active]
         w, h = self.mapwindows[animationData.GetWindowIndex()].GetClientSize()
         regions = animationData.GetRegions(w, h)
-        self.bitmapProvider.SetCmds(animationData.cmdMatrix, opacities, regions)
+        self.bitmapProvider.SetCmds(
+            animationData.cmdMatrix, opacities, regions)
 
     def _load3DData(self, animationData):
         nviz = animationData.GetNvizCommands()
@@ -390,7 +425,8 @@
     def _loadLegend(self, animationData):
         if animationData.legendCmd:
             try:
-                bitmap = self.bitmapProvider.LoadOverlay(animationData.legendCmd)
+                bitmap = self.bitmapProvider.LoadOverlay(
+                    animationData.legendCmd)
                 try:
                     from PIL import Image
                     for param in animationData.legendCmd:
@@ -400,7 +436,9 @@
                             break
                 except ImportError:
                     x, y = 0, 0
-                self.mapwindows[animationData.windowIndex].SetOverlay(bitmap, x, y)
+                self.mapwindows[
+                    animationData.windowIndex].SetOverlay(
+                    bitmap, x, y)
             except GException:
                 GError(message=_("Failed to display legend."))
         else:
@@ -433,7 +471,8 @@
 
         if temporalMode == TemporalMode.NONTEMPORAL:
             if len(mapCount) > 1:
-                raise GException(_("Inconsistent number of maps, please check input data."))
+                raise GException(
+                    _("Inconsistent number of maps, please check input data."))
         elif temporalMode == TemporalMode.TEMPORAL:
             tempManager = TemporalManager()
             # these raise GException:
@@ -449,8 +488,14 @@
     def Reload(self):
         self.EndAnimation()
 
-        color = UserSettings.Get(group='animation', key='bgcolor', subkey='color')
-        cpus = UserSettings.Get(group='animation', key='nprocs', subkey='value')
+        color = UserSettings.Get(
+            group='animation',
+            key='bgcolor',
+            subkey='color')
+        cpus = UserSettings.Get(
+            group='animation',
+            key='nprocs',
+            subkey='value')
         self.bitmapProvider.Load(nprocs=cpus, bgcolor=color, force=True)
 
         self.EndAnimation()
@@ -477,7 +522,8 @@
             timeLabels, mapNamesDict = self.temporalManager.GetLabelsAndMaps()
             frameCount = len(timeLabels)
         else:
-            frameCount = self.animationData[0].mapCount  # should be the same for all
+            frameCount = self.animationData[
+                0].mapCount  # should be the same for all
 
         animWinSize = []
         animWinPos = []
@@ -492,11 +538,19 @@
                 animWinIndex.append(i)
 
         images = []
-        busy = wx.BusyInfo(message=_("Preparing export, please wait..."), parent=self.frame)
+        busy = wx.BusyInfo(
+            message=_("Preparing export, please wait..."),
+            parent=self.frame)
         wx.Yield()
         lastBitmaps = {}
-        fgcolor = UserSettings.Get(group='animation', key='font', subkey='fgcolor')
-        bgcolor = UserSettings.Get(group='animation', key='font', subkey='bgcolor')
+        fgcolor = UserSettings.Get(
+            group='animation',
+            key='font',
+            subkey='fgcolor')
+        bgcolor = UserSettings.Get(
+            group='animation',
+            key='font',
+            subkey='bgcolor')
         for frameIndex in range(frameCount):
             image = wx.EmptyImage(*size)
             image.Replace(0, 0, 0, 255, 255, 255)
@@ -514,7 +568,7 @@
                 else:
                     bitmap = self.bitmapProvider.GetBitmap(frameId)
                     lastBitmaps[i] = bitmap
-                
+
                 im = wx.ImageFromBitmap(lastBitmaps[i])
 
                 # add legend if used
@@ -523,7 +577,8 @@
                     legendBitmap = self.bitmapProvider.LoadOverlay(legend)
                     x, y = self.mapwindows[i].GetOverlayPos()
                     legImage = wx.ImageFromBitmap(legendBitmap)
-                    # not so nice result, can we handle the transparency otherwise?
+                    # not so nice result, can we handle the transparency
+                    # otherwise?
                     legImage.ConvertAlphaToMask()
                     im.Paste(legImage, x, y)
 
@@ -540,19 +595,24 @@
                 elif decoration['name'] == 'time':
                     timeLabel = timeLabels[frameIndex]
                     if timeLabel[1]:  # interval
-                        text = _("%(from)s %(dash)s %(to)s") % \
-                                {'from': timeLabel[0], 'dash': u"\u2013", 'to': timeLabel[1]}
+                        text = _("%(from)s %(dash)s %(to)s") % {
+                            'from': timeLabel[0],
+                            'dash': u"\u2013", 'to': timeLabel[1]}
                     else:
                         if self.temporalManager.GetTemporalType() == TemporalType.ABSOLUTE:
                             text = timeLabel[0]
                         else:
                             text = _("%(start)s %(unit)s") % \
-                                    {'start': timeLabel[0], 'unit': timeLabel[2]}
+                                {'start': timeLabel[0], 'unit': timeLabel[2]}
 
-                    decImage = RenderText(text, decoration['font'], bgcolor, fgcolor).ConvertToImage()
+                    decImage = RenderText(
+                        text, decoration['font'],
+                        bgcolor, fgcolor).ConvertToImage()
                 elif decoration['name'] == 'text':
                     text = decoration['text']
-                    decImage = RenderText(text, decoration['font'], bgcolor, fgcolor).ConvertToImage()
+                    decImage = RenderText(
+                        text, decoration['font'],
+                        bgcolor, fgcolor).ConvertToImage()
 
                 image.Paste(decImage, x, y)
 
@@ -566,8 +626,11 @@
         wx.Yield()
         try:
             if exportInfo['method'] == 'sequence':
-                filename = os.path.join(exportInfo['directory'],
-                                        exportInfo['prefix'] + '.' + exportInfo['format'].lower())
+                filename = os.path.join(
+                    exportInfo['directory'],
+                    exportInfo['prefix'] +
+                    '.' +
+                    exportInfo['format'].lower())
                 writeIms(filename=filename, images=pilImages)
             elif exportInfo['method'] == 'gif':
                 writeGif(filename=exportInfo['file'], images=pilImages,

Modified: grass/trunk/gui/wxpython/animation/data.py
===================================================================
--- grass/trunk/gui/wxpython/animation/data.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/data.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -32,6 +32,7 @@
 
 
 class AnimationData(object):
+
     def __init__(self):
         self._name = None
         self._windowIndex = 0
@@ -209,17 +210,22 @@
     def GetZoomRegionValue(self):
         return self._zoomRegionValue
 
-    zoomRegionValue = property(fset=SetZoomRegionValue, fget=GetZoomRegionValue)
+    zoomRegionValue = property(
+        fset=SetZoomRegionValue,
+        fget=GetZoomRegionValue)
 
     def GetRegions(self, width, height):
         self._computeRegions(width, height, self._mapCount, self._startRegion,
                              self._endRegion, self._zoomRegionValue)
         return self._regions
 
-    def _computeRegions(self, width, height, count, startRegion, endRegion=None, zoomValue=None):
+    def _computeRegions(
+            self, width, height, count, startRegion, endRegion=None,
+            zoomValue=None):
         """Computes regions based on start region and end region or zoom value
         for each of the animation frames."""
-        currRegion = dict(gcore.region())  # cast to dict, otherwise deepcopy error
+        currRegion = dict(
+            gcore.region())  # cast to dict, otherwise deepcopy error
         del currRegion['cells']
         del currRegion['cols']
         del currRegion['rows']
@@ -237,15 +243,24 @@
             self._regions = regions
             return
 
-        startRegionDict = parse_key_val(gcore.read_command('g.region', flags='gu',
-                                                                 region=startRegion),
-                                              val_type=float)
+        startRegionDict = parse_key_val(
+            gcore.read_command(
+                'g.region',
+                flags='gu',
+                region=startRegion),
+            val_type=float)
         if endRegion:
-            endRegionDict = parse_key_val(gcore.read_command('g.region', flags='gu',
-                                                                   region=endRegion),
-                                                val_type=float)
+            endRegionDict = parse_key_val(
+                gcore.read_command(
+                    'g.region',
+                    flags='gu',
+                    region=endRegion),
+                val_type=float)
             for key in ('n', 's', 'e', 'w'):
-                values = interpolate(startRegionDict[key], endRegionDict[key], self._mapCount)
+                values = interpolate(
+                    startRegionDict[key],
+                    endRegionDict[key],
+                    self._mapCount)
                 for value, region in zip(values, regions):
                     region[key] = value
 
@@ -259,7 +274,7 @@
                 # handle cases when north < south and similarly EW
                 if regions[i]['n'] < regions[i]['s'] or \
                    regions[i]['e'] < regions[i]['w']:
-                        regions[i] = regions[i - 1]
+                    regions[i] = regions[i - 1]
 
         for region in regions:
             mapwidth = abs(region['e'] - region['w'])
@@ -276,6 +291,7 @@
 class AnimLayer(Layer):
     """Animation layer allows adding either space-time dataset
     or series of maps."""
+
     def __init__(self):
         Layer.__init__(self)
         self._mapTypes.extend(['strds', 'stvds', 'str3ds'])
@@ -284,7 +300,8 @@
     def SetName(self, name):
         if not self.hidden:
             if self._mapType is None:
-                raise ValueError("To set layer name, the type of layer must be specified.")
+                raise ValueError(
+                    "To set layer name, the type of layer must be specified.")
             if self._mapType in ('strds', 'stvds', 'str3ds'):
                 try:
                     name = validateTimeseriesName(name, self._mapType)

Modified: grass/trunk/gui/wxpython/animation/dialogs.py
===================================================================
--- grass/trunk/gui/wxpython/animation/dialogs.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/dialogs.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -48,6 +48,7 @@
 
 
 class SpeedDialog(wx.Dialog):
+
     def __init__(self, parent, title=_("Adjust speed of animation"),
                  temporalMode=None, minimumDuration=0, timeGranularity=None,
                  initialSpeed=200):
@@ -75,7 +76,9 @@
     def GetTimeGranularity(self):
         return self._timeGranularity
 
-    timeGranularity = property(fset=SetTimeGranularity, fget=GetTimeGranularity)
+    timeGranularity = property(
+        fset=SetTimeGranularity,
+        fget=GetTimeGranularity)
 
     def SetTemporalMode(self, mode):
         self._temporalMode = mode
@@ -97,20 +100,37 @@
         box = wx.StaticBoxSizer(self.nontemporalBox, wx.VERTICAL)
         gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
 
-        labelDuration = wx.StaticText(self, id=wx.ID_ANY, label=_("Frame duration:"))
+        labelDuration = wx.StaticText(
+            self, id=wx.ID_ANY, label=_("Frame duration:"))
         labelUnits = wx.StaticText(self, id=wx.ID_ANY, label=_("ms"))
-        self.spinDuration = wx.SpinCtrl(self, id=wx.ID_ANY, min=self.minimumDuration,
-                                        max=10000, initial=self.defaultSpeed)
+        self.spinDuration = wx.SpinCtrl(
+            self,
+            id=wx.ID_ANY,
+            min=self.minimumDuration,
+            max=10000,
+            initial=self.defaultSpeed)
         # TODO total time
 
-        gridSizer.Add(item=labelDuration, pos=(0, 0), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
-        gridSizer.Add(item=self.spinDuration, pos=(0, 1), flag = wx.ALIGN_CENTER)
-        gridSizer.Add(item=labelUnits, pos=(0, 2), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
+        gridSizer.Add(
+            item=labelDuration, pos=(0, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
+        gridSizer.Add(item=self.spinDuration, pos=(0, 1), flag=wx.ALIGN_CENTER)
+        gridSizer.Add(
+            item=labelUnits, pos=(0, 2),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
         gridSizer.AddGrowableCol(0)
 
-        box.Add(item=gridSizer, proportion=1, border=5, flag=wx.ALL | wx.EXPAND)
+        box.Add(
+            item=gridSizer,
+            proportion=1,
+            border=5,
+            flag=wx.ALL | wx.EXPAND)
         self.nontemporalSizer = gridSizer
-        mainSizer.Add(item=box, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
+        mainSizer.Add(
+            item=box,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
         #
         # temporal mode
         #
@@ -119,25 +139,45 @@
         box = wx.StaticBoxSizer(self.temporalBox, wx.VERTICAL)
         gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
 
-        labelTimeUnit = wx.StaticText(self, id=wx.ID_ANY, label=_("Time unit:"))
-        labelDuration = wx.StaticText(self, id=wx.ID_ANY, label=_("Duration of time unit:"))
+        labelTimeUnit = wx.StaticText(
+            self, id=wx.ID_ANY, label=_("Time unit:"))
+        labelDuration = wx.StaticText(
+            self, id=wx.ID_ANY, label=_("Duration of time unit:"))
         labelUnits = wx.StaticText(self, id=wx.ID_ANY, label=_("ms"))
-        self.spinDurationTemp = wx.SpinCtrl(self, id=wx.ID_ANY, min=self.minimumDuration,
-                                            max=10000, initial=self.defaultSpeed)
+        self.spinDurationTemp = wx.SpinCtrl(
+            self, id=wx.ID_ANY, min=self.minimumDuration, max=10000,
+            initial=self.defaultSpeed)
         self.choiceUnits = wx.Choice(self, id=wx.ID_ANY)
 
         # TODO total time
 
-        gridSizer.Add(item=labelTimeUnit, pos=(0, 0), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
-        gridSizer.Add(item=self.choiceUnits, pos=(0, 1), flag = wx.ALIGN_CENTER | wx.EXPAND)
-        gridSizer.Add(item=labelDuration, pos=(1, 0), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
-        gridSizer.Add(item=self.spinDurationTemp, pos=(1, 1), flag = wx.ALIGN_CENTER | wx.EXPAND)
-        gridSizer.Add(item=labelUnits, pos=(1, 2), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
+        gridSizer.Add(
+            item=labelTimeUnit, pos=(0, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
+        gridSizer.Add(item=self.choiceUnits, pos=(0, 1),
+                      flag=wx.ALIGN_CENTER | wx.EXPAND)
+        gridSizer.Add(
+            item=labelDuration, pos=(1, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
+        gridSizer.Add(
+            item=self.spinDurationTemp, pos=(
+                1, 1), flag=wx.ALIGN_CENTER | wx.EXPAND)
+        gridSizer.Add(
+            item=labelUnits, pos=(1, 2),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
         gridSizer.AddGrowableCol(1)
 
         self.temporalSizer = gridSizer
-        box.Add(item=gridSizer, proportion=1, border=5, flag=wx.ALL | wx.EXPAND)
-        mainSizer.Add(item=box, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
+        box.Add(
+            item=gridSizer,
+            proportion=1,
+            border=5,
+            flag=wx.ALL | wx.EXPAND)
+        mainSizer.Add(
+            item=box,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
 
         self.btnOk = wx.Button(self, wx.ID_OK)
         self.btnApply = wx.Button(self, wx.ID_APPLY)
@@ -162,7 +202,8 @@
         mainSizer.Fit(self)
 
     def _setTemporalMode(self):
-        self.nontemporalBox.Enable(self.temporalMode == TemporalMode.NONTEMPORAL)
+        self.nontemporalBox.Enable(
+            self.temporalMode == TemporalMode.NONTEMPORAL)
         self.temporalBox.Enable(self.temporalMode == TemporalMode.TEMPORAL)
         for child in self.temporalSizer.GetChildren():
             child.GetWindow().Enable(self.temporalMode == TemporalMode.TEMPORAL)
@@ -172,7 +213,13 @@
         self.Layout()
 
     def _fillUnitChoice(self, choiceWidget):
-        timeUnitsChoice = [_("year"), _("month"), _("day"), _("hour"), _("minute"), _("second")]
+        timeUnitsChoice = [
+            _("year"),
+            _("month"),
+            _("day"),
+            _("hour"),
+            _("minute"),
+            _("second")]
         timeUnits = ["years", "months", "days", "hours", "minutes", "seconds"]
         for item, cdata in zip(timeUnitsChoice, timeUnits):
             choiceWidget.Append(item, cdata)
@@ -236,7 +283,8 @@
             ms = value * seconds2 / float(seconds1)
             # minimumDuration set to 0, too restrictive
             if ms < self.minimumDuration:
-                GMessage(parent=self, message=_("Animation speed is too high."))
+                GMessage(parent=self, message=_(
+                    "Animation speed is too high."))
                 return
             self.lastAppliedValueTemp = self.spinDurationTemp.GetValue()
         else:
@@ -267,6 +315,7 @@
 
 
 class InputDialog(wx.Dialog):
+
     def __init__(self, parent, mode, animationData):
         wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY,
                            style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
@@ -284,9 +333,19 @@
     def _layout(self):
         self.notebook = wx.Notebook(parent=self, style=wx.BK_DEFAULT)
         sizer = wx.BoxSizer(wx.VERTICAL)
-        self.notebook.AddPage(self._createGeneralPage(self.notebook), _("General"))
-        self.notebook.AddPage(self._createAdvancedPage(self.notebook), _("Advanced"))
-        sizer.Add(self.notebook, proportion=1, flag=wx.ALL | wx.EXPAND, border=3)
+        self.notebook.AddPage(
+            self._createGeneralPage(
+                self.notebook),
+            _("General"))
+        self.notebook.AddPage(
+            self._createAdvancedPage(
+                self.notebook),
+            _("Advanced"))
+        sizer.Add(
+            self.notebook,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=3)
 
         # buttons
         self.btnOk = wx.Button(self, wx.ID_OK)
@@ -308,17 +367,24 @@
         panel = wx.Panel(parent=parent)
         mainSizer = wx.BoxSizer(wx.VERTICAL)
 
-        self.windowChoice = wx.Choice(panel, id=wx.ID_ANY,
-                                      choices=[_("top left"), _("top right"),
-                                               _("bottom left"), _("bottom right")])
+        self.windowChoice = wx.Choice(
+            panel,
+            id=wx.ID_ANY,
+            choices=[
+                _("top left"),
+                _("top right"),
+                _("bottom left"),
+                _("bottom right")])
         self.windowChoice.SetSelection(self.animationData.windowIndex)
 
-        self.nameCtrl = wx.TextCtrl(panel, id=wx.ID_ANY, value=self.animationData.name)
+        self.nameCtrl = wx.TextCtrl(
+            panel, id=wx.ID_ANY, value=self.animationData.name)
 
         self.nDChoice = wx.Choice(panel, id=wx.ID_ANY)
         mode = self.animationData.viewMode
         index = 0
-        for i, (viewMode, viewModeName) in enumerate(self.animationData.viewModes):
+        for i, (viewMode, viewModeName) in enumerate(
+                self.animationData.viewModes):
             self.nDChoice.Append(viewModeName, clientData=viewMode)
             if mode == viewMode:
                 index = i
@@ -328,28 +394,61 @@
         self.nDChoice.Bind(wx.EVT_CHOICE, self.OnViewMode)
 
         gridSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
-        gridSizer.Add(item=wx.StaticText(panel, id=wx.ID_ANY, label=_("Name:")),
-                      flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=wx.StaticText(
+                panel,
+                id=wx.ID_ANY,
+                label=_("Name:")),
+            flag=wx.ALIGN_CENTER_VERTICAL)
         gridSizer.Add(item=self.nameCtrl, proportion=1, flag=wx.EXPAND)
-        gridSizer.Add(item=wx.StaticText(panel, id=wx.ID_ANY, label=_("Window position:")),
-                      flag=wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item=self.windowChoice, proportion=1, flag=wx.ALIGN_RIGHT)
-        gridSizer.Add(item=wx.StaticText(panel, id=wx.ID_ANY, label=_("View mode:")),
-                      flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=wx.StaticText(
+                panel,
+                id=wx.ID_ANY,
+                label=_("Window position:")),
+            flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=self.windowChoice,
+            proportion=1,
+            flag=wx.ALIGN_RIGHT)
+        gridSizer.Add(
+            item=wx.StaticText(
+                panel,
+                id=wx.ID_ANY,
+                label=_("View mode:")),
+            flag=wx.ALIGN_CENTER_VERTICAL)
         gridSizer.Add(item=self.nDChoice, proportion=1, flag=wx.ALIGN_RIGHT)
         gridSizer.AddGrowableCol(0, 1)
         gridSizer.AddGrowableCol(1, 1)
-        mainSizer.Add(item=gridSizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
-        label = _("For 3D animation, please select only one space-time dataset\n"
-                  "or one series of map layers.")
+        mainSizer.Add(
+            item=gridSizer,
+            proportion=0,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+        label = _(
+            "For 3D animation, please select only one space-time dataset\n"
+            "or one series of map layers.")
         self.warning3DLayers = wx.StaticText(panel, label=label)
-        self.warning3DLayers.SetForegroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_GRAYTEXT))
-        mainSizer.Add(item=self.warning3DLayers, proportion=0, flag=wx.EXPAND | wx.LEFT, border=5)
+        self.warning3DLayers.SetForegroundColour(
+            wx.SystemSettings_GetColour(wx.SYS_COLOUR_GRAYTEXT))
+        mainSizer.Add(
+            item=self.warning3DLayers,
+            proportion=0,
+            flag=wx.EXPAND | wx.LEFT,
+            border=5)
 
         self.dataPanel = self._createDataPanel(panel)
         self.threeDPanel = self._create3DPanel(panel)
-        mainSizer.Add(item=self.dataPanel, proportion=1, flag=wx.EXPAND | wx.ALL, border=3)
-        mainSizer.Add(item=self.threeDPanel, proportion=0, flag=wx.EXPAND | wx.ALL, border=3)
+        mainSizer.Add(
+            item=self.dataPanel,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=3)
+        mainSizer.Add(
+            item=self.threeDPanel,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=3)
 
         panel.SetSizer(mainSizer)
         mainSizer.Fit(panel)
@@ -364,7 +463,11 @@
                                                  layerList=self._layerList,
                                                  modal=True)
         self.simpleLmgr.SetMinSize((globalvar.DIALOG_GSELECT_SIZE[0], 80))
-        slmgrSizer.Add(self.simpleLmgr, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
+        slmgrSizer.Add(
+            self.simpleLmgr,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
 
         self.legend = wx.CheckBox(panel, label=_("Show raster legend"))
         self.legend.SetValue(bool(self.animationData.legendCmd))
@@ -375,7 +478,11 @@
         hbox = wx.BoxSizer(wx.HORIZONTAL)
         hbox.Add(item=self.legend, proportion=1, flag=wx.ALIGN_CENTER_VERTICAL)
         hbox.Add(item=self.legendBtn, proportion=0, flag=wx.LEFT, border=5)
-        slmgrSizer.Add(item=hbox, proportion=0, flag=wx.EXPAND | wx.ALL, border=3)
+        slmgrSizer.Add(
+            item=hbox,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=3)
 
         panel.SetSizerAndFit(slmgrSizer)
         panel.SetAutoLayout(True)
@@ -389,29 +496,48 @@
         dataBoxSizer = wx.StaticBoxSizer(dataStBox, wx.VERTICAL)
 
         # workspace file
-        self.fileSelector = \
-            filebrowse.FileBrowseButton(parent=panel, id=wx.ID_ANY,
-                                        size=globalvar.DIALOG_GSELECT_SIZE,
-                                        labelText=_("Workspace file:"),
-                                        dialogTitle=_("Choose workspace file to "
-                                                      "import 3D view parameters"),
-                                        buttonText=_('Browse'),
-                                        startDirectory=os.getcwd(), fileMode=0,
-                                        fileMask="GRASS Workspace File (*.gxw)|*.gxw")
+        self.fileSelector = filebrowse.FileBrowseButton(
+            parent=panel,
+            id=wx.ID_ANY,
+            size=globalvar.DIALOG_GSELECT_SIZE,
+            labelText=_("Workspace file:"),
+            dialogTitle=_(
+                "Choose workspace file to "
+                "import 3D view parameters"),
+            buttonText=_('Browse'),
+            startDirectory=os.getcwd(),
+            fileMode=0,
+            fileMask="GRASS Workspace File (*.gxw)|*.gxw")
         if self.animationData.workspaceFile:
             self.fileSelector.SetValue(self.animationData.workspaceFile)
-        self.paramLabel = wx.StaticText(panel, wx.ID_ANY, label=_("Parameter for animation:"))
-        self.paramChoice = wx.Choice(panel, id=wx.ID_ANY, choices=self.animationData.nvizParameters)
+        self.paramLabel = wx.StaticText(
+            panel, wx.ID_ANY, label=_("Parameter for animation:"))
+        self.paramChoice = wx.Choice(
+            panel, id=wx.ID_ANY, choices=self.animationData.nvizParameters)
         self.paramChoice.SetStringSelection(self.animationData.nvizParameter)
 
         hbox = wx.BoxSizer(wx.HORIZONTAL)
-        hbox.Add(item=self.fileSelector, proportion=1, flag=wx.EXPAND | wx.ALIGN_CENTER)
-        dataBoxSizer.Add(item=hbox, proportion=0, flag=wx.EXPAND | wx.ALL, border=3)
+        hbox.Add(
+            item=self.fileSelector,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALIGN_CENTER)
+        dataBoxSizer.Add(
+            item=hbox,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=3)
 
         hbox = wx.BoxSizer(wx.HORIZONTAL)
-        hbox.Add(item=self.paramLabel, proportion=1, flag=wx.ALIGN_CENTER_VERTICAL)
+        hbox.Add(
+            item=self.paramLabel,
+            proportion=1,
+            flag=wx.ALIGN_CENTER_VERTICAL)
         hbox.Add(item=self.paramChoice, proportion=1, flag=wx.EXPAND)
-        dataBoxSizer.Add(item=hbox, proportion=0, flag=wx.EXPAND | wx.ALL, border=3)
+        dataBoxSizer.Add(
+            item=hbox,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=3)
 
         panel.SetSizerAndFit(dataBoxSizer)
         panel.SetAutoLayout(True)
@@ -422,7 +548,9 @@
         panel = wx.Panel(parent=parent)
 
         mainSizer = wx.BoxSizer(wx.VERTICAL)
-        box = wx.StaticBox(parent=panel, label=" %s " % _("Animate region change (2D view only)"))
+        box = wx.StaticBox(
+            parent=panel, label=" %s " %
+            _("Animate region change (2D view only)"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
 
         gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
@@ -431,12 +559,17 @@
         self.stRegion = Select(parent=panel, type='region', size=(200, -1))
         if self.animationData.startRegion:
             self.stRegion.SetValue(self.animationData.startRegion)
-        gridSizer.Add(self.stRegion, pos=(0, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
+        gridSizer.Add(
+            self.stRegion, pos=(0, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
 
-        self.endRegRadio = wx.RadioButton(panel, label=_("End region:"), style=wx.RB_GROUP)
+        self.endRegRadio = wx.RadioButton(
+            panel, label=_("End region:"), style=wx.RB_GROUP)
         gridSizer.Add(self.endRegRadio, pos=(1, 0), flag=wx.EXPAND)
         self.endRegion = Select(parent=panel, type='region', size=(200, -1))
-        gridSizer.Add(self.endRegion, pos=(1, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
+        gridSizer.Add(
+            self.endRegion, pos=(1, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
         self.zoomRadio = wx.RadioButton(panel, label=_("Zoom value:"))
         self.zoomRadio.SetToolTipString(_("N-S/E-W distances in map units used to "
                                           "gradually reduce region."))
@@ -451,7 +584,9 @@
         zoomSizer.Add(wx.StaticText(panel, label=_("E-W:")), proportion=0,
                       flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT, border=3)
         zoomSizer.Add(self.zoomEW, proportion=1, flag=wx.LEFT, border=3)
-        gridSizer.Add(zoomSizer, pos=(2, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
+        gridSizer.Add(
+            zoomSizer, pos=(2, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
         if self.animationData.endRegion:
             self.endRegRadio.SetValue(True)
             self.zoomRadio.SetValue(False)
@@ -463,8 +598,12 @@
             self.zoomNS.SetValue(str(zoom[0]))
             self.zoomEW.SetValue(str(zoom[1]))
 
-        self.endRegRadio.Bind(wx.EVT_RADIOBUTTON, lambda evt: self._enableRegionWidgets())
-        self.zoomRadio.Bind(wx.EVT_RADIOBUTTON, lambda evt: self._enableRegionWidgets())
+        self.endRegRadio.Bind(
+            wx.EVT_RADIOBUTTON,
+            lambda evt: self._enableRegionWidgets())
+        self.zoomRadio.Bind(
+            wx.EVT_RADIOBUTTON,
+            lambda evt: self._enableRegionWidgets())
         self._enableRegionWidgets()
 
         gridSizer.AddGrowableCol(1)
@@ -512,8 +651,8 @@
         if self._tmpLegendCmd or self.animationData.legendCmd:
             return
         cmd = ['d.legend', 'at=5,50,2,5']
-        GUI(parent=self, modal=True).ParseCommand(cmd=cmd,
-                                                  completed=(self.GetOptData, '', ''))
+        GUI(parent=self, modal=True).ParseCommand(
+            cmd=cmd, completed=(self.GetOptData, '', ''))
 
     def OnLegendProperties(self, event):
         """Set options for legend"""
@@ -524,8 +663,8 @@
         else:
             cmd = ['d.legend', 'at=5,50,2,5']
 
-        GUI(parent=self, modal=True).ParseCommand(cmd=cmd,
-                                                  completed=(self.GetOptData, '', ''))
+        GUI(parent=self, modal=True).ParseCommand(
+            cmd=cmd, completed=(self.GetOptData, '', ''))
 
     def GetOptData(self, dcmd, layer, params, propwin):
         """Process decoration layer data"""
@@ -583,8 +722,9 @@
                 self.animationData.endRegion = self.endRegion.GetValue()
                 self.animationData.zoomRegionValue = None
             else:
-                self.animationData.zoomRegionValue = (float(self.zoomNS.GetValue()),
-                                                      float(self.zoomEW.GetValue()))
+                self.animationData.zoomRegionValue = (
+                    float(self.zoomNS.GetValue()),
+                    float(self.zoomEW.GetValue()))
                 self.animationData.endRegion = None
         else:
             self.animationData.startRegion = None
@@ -596,10 +736,14 @@
             self._update()
             self.EndModal(wx.ID_OK)
         except (GException, ValueError, IOError) as e:
-            GError(message=str(e), showTraceback=False, caption=_("Invalid input"))
+            GError(
+                message=str(e),
+                showTraceback=False,
+                caption=_("Invalid input"))
 
 
 class EditDialog(wx.Dialog):
+
     def __init__(self, parent, evalFunction, animationData, maxAnimations):
         wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY,
                            style=wx.DEFAULT_DIALOG_STYLE)
@@ -613,13 +757,19 @@
 
     def _layout(self):
         mainSizer = wx.BoxSizer(wx.VERTICAL)
-        box = wx.StaticBox (parent=self, id=wx.ID_ANY, label=" %s " % _("List of animations"))
+        box = wx.StaticBox(
+            parent=self,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("List of animations"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridBagSizer = wx.GridBagSizer (hgap=5, vgap=5)
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
         gridBagSizer.AddGrowableCol(0)
         # gridBagSizer.AddGrowableCol(1,1)
 
-        self.listbox = wx.ListBox(self, id=wx.ID_ANY, choices=[], style=wx.LB_SINGLE | wx.LB_NEEDED_SB)
+        self.listbox = wx.ListBox(
+            self, id=wx.ID_ANY, choices=[],
+            style=wx.LB_SINGLE | wx.LB_NEEDED_SB)
         self.listbox.Bind(wx.EVT_LISTBOX_DCLICK, self.OnEdit)
 
         self.addButton = wx.Button(self, id=wx.ID_ANY, label=_("Add"))
@@ -631,15 +781,19 @@
 
         self._updateListBox()
 
-        gridBagSizer.Add(self.listbox, pos=(0, 0), span = (3, 1),
-                         flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+        gridBagSizer.Add(self.listbox, pos=(0, 0), span=(3, 1),
+                         flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
         gridBagSizer.Add(self.addButton, pos=(0, 1),
-                         flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+                         flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
         gridBagSizer.Add(self.editButton, pos=(1, 1),
-                         flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+                         flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
         gridBagSizer.Add(self.removeButton, pos=(2, 1),
-                         flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
-        sizer.Add(gridBagSizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+                         flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+        sizer.Add(
+            gridBagSizer,
+            proportion=0,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
         mainSizer.Add(item=sizer, proportion=0,
                       flag=wx.EXPAND | wx.ALL, border=5)
 
@@ -677,7 +831,10 @@
     def OnAdd(self, event):
         windowIndex = self._getNextIndex()
         if windowIndex is None:
-            GMessage(self, message=_("Maximum number of animations is %d.") % self.maxAnimations)
+            GMessage(
+                self,
+                message=_("Maximum number of animations is %d.") %
+                self.maxAnimations)
             return
         animData = AnimationData()
         # number of active animations
@@ -724,8 +881,10 @@
     def OnOk(self, event):
         indices = set([anim.windowIndex for anim in self.animationData])
         if len(indices) != len(self.animationData):
-            GError(parent=self, message=_("More animations are using one window."
-                                          " Please select different window for each animation."))
+            GError(
+                parent=self, message=_(
+                    "More animations are using one window."
+                    " Please select different window for each animation."))
             return
         try:
             temporalMode, tempManager = self.eval(self.animationData)
@@ -738,9 +897,14 @@
 
 
 class ExportDialog(wx.Dialog):
+
     def __init__(self, parent, temporal, timeTick):
-        wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=_("Export animation"),
-                           style=wx.DEFAULT_DIALOG_STYLE)
+        wx.Dialog.__init__(
+            self,
+            parent=parent,
+            id=wx.ID_ANY,
+            title=_("Export animation"),
+            style=wx.DEFAULT_DIALOG_STYLE)
         self.decorations = []
 
         self.temporal = temporal
@@ -756,8 +920,12 @@
         notebook = wx.Notebook(self, id=wx.ID_ANY)
         mainSizer = wx.BoxSizer(wx.VERTICAL)
 
-        notebook.AddPage(page=self._createExportFormatPanel(notebook), text=_("Format"))
-        notebook.AddPage(page=self._createDecorationsPanel(notebook), text=_("Decorations"))
+        notebook.AddPage(
+            page=self._createExportFormatPanel(notebook),
+            text=_("Format"))
+        notebook.AddPage(
+            page=self._createDecorationsPanel(notebook),
+            text=_("Decorations"))
         mainSizer.Add(item=notebook, proportion=0,
                       flag=wx.EXPAND | wx.ALL | wx.ALIGN_RIGHT, border=5)
 
@@ -789,8 +957,16 @@
     def _createDecorationsPanel(self, notebook):
         panel = wx.Panel(notebook, id=wx.ID_ANY)
         sizer = wx.BoxSizer(wx.VERTICAL)
-        sizer.Add(self._createDecorationsList(panel), proportion=0, flag=wx.ALL | wx.EXPAND, border=10)
-        sizer.Add(self._createDecorationsProperties(panel), proportion=0, flag=wx.ALL | wx.EXPAND, border=10)
+        sizer.Add(
+            self._createDecorationsList(panel),
+            proportion=0,
+            flag=wx.ALL | wx.EXPAND,
+            border=10)
+        sizer.Add(
+            self._createDecorationsProperties(panel),
+            proportion=0,
+            flag=wx.ALL | wx.EXPAND,
+            border=10)
         panel.SetSizer(sizer)
         sizer.Fit(panel)
         return panel
@@ -805,7 +981,7 @@
         self.listbox.Bind(wx.EVT_LISTBOX, self.OnSelectionChanged)
 
         gridBagSizer.Add(self.listbox, pos=(0, 0), span=(4, 1),
-                         flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+                         flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
 
         buttonNames = ['time', 'image', 'text']
         buttonLabels = [_("Add time stamp"), _("Add image"), _("Add text")]
@@ -813,13 +989,34 @@
         for buttonName, buttonLabel in zip(buttonNames, buttonLabels):
             if buttonName == 'time' and self.temporal == TemporalMode.NONTEMPORAL:
                 continue
-            btn = wx.Button(panel, id=wx.ID_ANY, name=buttonName, label=buttonLabel)
-            btn.Bind(wx.EVT_BUTTON, lambda evt, temp=buttonName: self.OnAddDecoration(evt, temp))
-            gridBagSizer.Add(btn, pos=(i, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+            btn = wx.Button(
+                panel,
+                id=wx.ID_ANY,
+                name=buttonName,
+                label=buttonLabel)
+            btn.Bind(
+                wx.EVT_BUTTON,
+                lambda evt,
+                temp=buttonName: self.OnAddDecoration(
+                    evt,
+                    temp))
+            gridBagSizer.Add(
+                btn,
+                pos=(
+                    i,
+                    1),
+                flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+                border=0)
             i += 1
         removeButton = wx.Button(panel, id=wx.ID_ANY, label=_("Remove"))
         removeButton.Bind(wx.EVT_BUTTON, self.OnRemove)
-        gridBagSizer.Add(removeButton, pos=(i, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+        gridBagSizer.Add(
+            removeButton,
+            pos=(
+                i,
+                1),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+            border=0)
 
         return gridBagSizer
 
@@ -828,66 +1025,118 @@
         # inform label
         self.informBox = wx.BoxSizer(wx.HORIZONTAL)
         if self.temporal == TemporalMode.TEMPORAL:
-            label = _("Add time stamp, image or text decoration by one of the buttons above.")
+            label = _(
+                "Add time stamp, image or text decoration by one of the buttons above.")
         else:
             label = _("Add image or text decoration by one of the buttons above.")
 
         label = wx.StaticText(panel, id=wx.ID_ANY, label=label)
         label.Wrap(400)
-        self.informBox.Add(label, proportion=1, flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, border=5)
-        self.hidevbox.Add(self.informBox, proportion=0, flag=wx.EXPAND | wx.BOTTOM, border=5)
+        self.informBox.Add(
+            label,
+            proportion=1,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT,
+            border=5)
+        self.hidevbox.Add(
+            self.informBox,
+            proportion=0,
+            flag=wx.EXPAND | wx.BOTTOM,
+            border=5)
 
         # font
         self.fontBox = wx.BoxSizer(wx.HORIZONTAL)
-        self.fontBox.Add(wx.StaticText(panel, id=wx.ID_ANY, label=_("Font settings:")),
-                         proportion=0, flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, border=5)
-        self.sampleLabel = wx.StaticText(panel, id=wx.ID_ANY, label=_("Sample text"))
+        self.fontBox.Add(
+            wx.StaticText(
+                panel,
+                id=wx.ID_ANY,
+                label=_("Font settings:")),
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT,
+            border=5)
+        self.sampleLabel = wx.StaticText(
+            panel, id=wx.ID_ANY, label=_("Sample text"))
         self.fontBox.Add(self.sampleLabel, proportion=1,
                          flag=wx.ALIGN_CENTER | wx.RIGHT | wx.LEFT, border=5)
         fontButton = wx.Button(panel, id=wx.ID_ANY, label=_("Set font"))
         fontButton.Bind(wx.EVT_BUTTON, self.OnFont)
-        self.fontBox.Add(fontButton, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
-        self.hidevbox.Add(self.fontBox, proportion=0, flag=wx.EXPAND | wx.BOTTOM, border=5)
+        self.fontBox.Add(
+            fontButton,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL)
+        self.hidevbox.Add(
+            self.fontBox,
+            proportion=0,
+            flag=wx.EXPAND | wx.BOTTOM,
+            border=5)
 
         # image
         self.imageBox = wx.BoxSizer(wx.HORIZONTAL)
         filetype, ltype = GetImageHandlers(wx.EmptyImage(10, 10))
-        self.browse = filebrowse.FileBrowseButton(parent=panel, id=wx.ID_ANY, fileMask=filetype,
-                                                  labelText=_("Image file:"),
-                                                  dialogTitle=_('Choose image file'),
-                                                  buttonText=_('Browse'),
-                                                  startDirectory=os.getcwd(), fileMode=wx.FD_OPEN,
-                                                  changeCallback=self.OnSetImage)
+        self.browse = filebrowse.FileBrowseButton(
+            parent=panel, id=wx.ID_ANY, fileMask=filetype,
+            labelText=_("Image file:"),
+            dialogTitle=_('Choose image file'),
+            buttonText=_('Browse'),
+            startDirectory=os.getcwd(),
+            fileMode=wx.FD_OPEN, changeCallback=self.OnSetImage)
         self.imageBox.Add(self.browse, proportion=1, flag=wx.EXPAND)
-        self.hidevbox.Add(self.imageBox, proportion=0, flag=wx.EXPAND | wx.BOTTOM, border=5)
+        self.hidevbox.Add(
+            self.imageBox,
+            proportion=0,
+            flag=wx.EXPAND | wx.BOTTOM,
+            border=5)
         # text
         self.textBox = wx.BoxSizer(wx.HORIZONTAL)
-        self.textBox.Add(wx.StaticText(panel, id=wx.ID_ANY, label=_("Text:")),
-                         proportion=0, flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, border=5)
+        self.textBox.Add(
+            wx.StaticText(
+                panel,
+                id=wx.ID_ANY,
+                label=_("Text:")),
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT,
+            border=5)
         self.textCtrl = wx.TextCtrl(panel, id=wx.ID_ANY)
         self.textCtrl.Bind(wx.EVT_TEXT, self.OnText)
         self.textBox.Add(self.textCtrl, proportion=1, flag=wx.EXPAND)
         self.hidevbox.Add(self.textBox, proportion=0, flag=wx.EXPAND)
 
         self.posBox = self._positionWidget(panel)
-        self.hidevbox.Add(self.posBox, proportion=0, flag=wx.EXPAND | wx.TOP, border=5)
+        self.hidevbox.Add(
+            self.posBox,
+            proportion=0,
+            flag=wx.EXPAND | wx.TOP,
+            border=5)
         return self.hidevbox
 
     def _positionWidget(self, panel):
         grid = wx.GridBagSizer(vgap=5, hgap=5)
-        label = wx.StaticText(panel, id=wx.ID_ANY, label=_("Placement as percentage of"
-                              " screen coordinates (X: 0, Y: 0 is top left):"))
+        label = wx.StaticText(
+            panel, id=wx.ID_ANY, label=_(
+                "Placement as percentage of"
+                " screen coordinates (X: 0, Y: 0 is top left):"))
         label.Wrap(400)
-        self.spinX = wx.SpinCtrl(panel, id=wx.ID_ANY, min=0, max=100, initial=10)
-        self.spinY = wx.SpinCtrl(panel, id=wx.ID_ANY, min=0, max=100, initial=10)
-        self.spinX.Bind(wx.EVT_SPINCTRL, lambda evt, temp='X': self.OnPosition(evt, temp))
-        self.spinY.Bind(wx.EVT_SPINCTRL, lambda evt, temp='Y': self.OnPosition(evt, temp))
+        self.spinX = wx.SpinCtrl(
+            panel, id=wx.ID_ANY, min=0, max=100, initial=10)
+        self.spinY = wx.SpinCtrl(
+            panel, id=wx.ID_ANY, min=0, max=100, initial=10)
+        self.spinX.Bind(
+            wx.EVT_SPINCTRL,
+            lambda evt,
+            temp='X': self.OnPosition(
+                evt,
+                temp))
+        self.spinY.Bind(
+            wx.EVT_SPINCTRL,
+            lambda evt,
+            temp='Y': self.OnPosition(
+                evt,
+                temp))
 
-        grid.Add(label, pos=(0, 0), span = (1, 4), flag = wx.EXPAND)
+        grid.Add(label, pos=(0, 0), span=(1, 4), flag=wx.EXPAND)
         grid.Add(wx.StaticText(panel, id=wx.ID_ANY, label=_("X:")), pos=(1, 0),
-                 flag = wx.ALIGN_CENTER_VERTICAL)
+                 flag=wx.ALIGN_CENTER_VERTICAL)
         grid.Add(wx.StaticText(panel, id=wx.ID_ANY, label=_("Y:")), pos=(1, 2),
-                 flag = wx.ALIGN_CENTER_VERTICAL)
+                 flag=wx.ALIGN_CENTER_VERTICAL)
         grid.Add(self.spinX, pos=(1, 1))
         grid.Add(self.spinY, pos=(1, 3))
 
@@ -901,12 +1150,28 @@
         choices = [_("image sequence"), _("animated GIF"), _("SWF"), _("AVI")]
         self.formatChoice = wx.Choice(parent=panel, id=wx.ID_ANY,
                                       choices=choices)
-        self.formatChoice.Bind(wx.EVT_CHOICE, lambda event: self.ChangeFormat(event.GetSelection()))
-        hSizer.Add(item=wx.StaticText(panel, id=wx.ID_ANY, label=_("Export to:")),
-                   proportion=0, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=2)
-        hSizer.Add(item=self.formatChoice, proportion=1,
-                   flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND | wx.ALL, border=2)
-        borderSizer.Add(item=hSizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=3)
+        self.formatChoice.Bind(
+            wx.EVT_CHOICE,
+            lambda event: self.ChangeFormat(
+                event.GetSelection()))
+        hSizer.Add(
+            item=wx.StaticText(
+                panel,
+                id=wx.ID_ANY,
+                label=_("Export to:")),
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=2)
+        hSizer.Add(
+            item=self.formatChoice,
+            proportion=1,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND | wx.ALL,
+            border=2)
+        borderSizer.Add(
+            item=hSizer,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=3)
 
         helpSizer = wx.BoxSizer(wx.HORIZONTAL)
         helpSizer.AddStretchSpacer(1)
@@ -917,92 +1182,138 @@
 
         # panel for image sequence
         imSeqPanel = wx.Panel(parent=panel, id=wx.ID_ANY)
-        prefixLabel = wx.StaticText(imSeqPanel, id=wx.ID_ANY, label=_("File prefix:"))
-        self.prefixCtrl = wx.TextCtrl(imSeqPanel, id=wx.ID_ANY, value=_("animation_"))
-        formatLabel = wx.StaticText(imSeqPanel, id=wx.ID_ANY, label=_("File format:"))
+        prefixLabel = wx.StaticText(
+            imSeqPanel, id=wx.ID_ANY, label=_("File prefix:"))
+        self.prefixCtrl = wx.TextCtrl(
+            imSeqPanel, id=wx.ID_ANY, value=_("animation_"))
+        formatLabel = wx.StaticText(
+            imSeqPanel, id=wx.ID_ANY, label=_("File format:"))
         imageTypes = ['PNG', 'JPEG', 'GIF', 'TIFF', 'PPM', 'BMP']
         self.imSeqFormatChoice = wx.Choice(imSeqPanel, choices=imageTypes)
         self.imSeqFormatChoice.SetSelection(0)
-        self.dirBrowse = filebrowse.DirBrowseButton(parent=imSeqPanel, id=wx.ID_ANY,
-                                                    labelText=_("Directory:"),
-                                                    dialogTitle=_("Choose directory for export"),
-                                                    buttonText=_("Browse"),
-                                                    startDirectory=os.getcwd())
+        self.dirBrowse = filebrowse.DirBrowseButton(
+            parent=imSeqPanel, id=wx.ID_ANY, labelText=_("Directory:"),
+            dialogTitle=_("Choose directory for export"),
+            buttonText=_("Browse"),
+            startDirectory=os.getcwd())
 
         dirGridSizer = wx.GridBagSizer(hgap=5, vgap=5)
-        dirGridSizer.Add(prefixLabel, pos=(0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        dirGridSizer.Add(self.prefixCtrl, pos=(0, 1), flag = wx.EXPAND)
-        dirGridSizer.Add(formatLabel, pos=(1, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        dirGridSizer.Add(self.imSeqFormatChoice, pos=(1, 1), flag = wx.EXPAND)
-        dirGridSizer.Add(self.dirBrowse, pos=(2, 0), flag = wx.EXPAND, span = (1, 2))
+        dirGridSizer.Add(
+            prefixLabel, pos=(0, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL)
+        dirGridSizer.Add(self.prefixCtrl, pos=(0, 1), flag=wx.EXPAND)
+        dirGridSizer.Add(
+            formatLabel, pos=(1, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL)
+        dirGridSizer.Add(self.imSeqFormatChoice, pos=(1, 1), flag=wx.EXPAND)
+        dirGridSizer.Add(
+            self.dirBrowse, pos=(
+                2, 0), flag=wx.EXPAND, span=(
+                1, 2))
         dirGridSizer.AddGrowableCol(1)
         imSeqPanel.SetSizer(dirGridSizer)
         dirGridSizer.Fit(imSeqPanel)
 
-        self.formatPanelSizer.Add(item=imSeqPanel, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
+        self.formatPanelSizer.Add(
+            item=imSeqPanel,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
         self.formatPanels.append(imSeqPanel)
 
         # panel for gif
         gifPanel = wx.Panel(parent=panel, id=wx.ID_ANY)
 
-        self.gifBrowse = filebrowse.FileBrowseButton(parent=gifPanel, id=wx.ID_ANY,
-                                                     fileMask="GIF file (*.gif)|*.gif",
-                                                     labelText=_("GIF file:"),
-                                                     dialogTitle=_("Choose file to save animation"),
-                                                     buttonText=_("Browse"),
-                                                     startDirectory=os.getcwd(), fileMode=wx.FD_SAVE)
+        self.gifBrowse = filebrowse.FileBrowseButton(
+            parent=gifPanel,
+            id=wx.ID_ANY,
+            fileMask="GIF file (*.gif)|*.gif",
+            labelText=_("GIF file:"),
+            dialogTitle=_("Choose file to save animation"),
+            buttonText=_("Browse"),
+            startDirectory=os.getcwd(),
+            fileMode=wx.FD_SAVE)
         gifGridSizer = wx.GridBagSizer(hgap=5, vgap=5)
         gifGridSizer.AddGrowableCol(0)
-        gifGridSizer.Add(self.gifBrowse, pos=(0, 0), flag = wx.EXPAND)
+        gifGridSizer.Add(self.gifBrowse, pos=(0, 0), flag=wx.EXPAND)
         gifPanel.SetSizer(gifGridSizer)
         gifGridSizer.Fit(gifPanel)
 
-        self.formatPanelSizer.Add(item=gifPanel, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
+        self.formatPanelSizer.Add(
+            item=gifPanel,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
         self.formatPanels.append(gifPanel)
 
         # panel for swf
         swfPanel = wx.Panel(parent=panel, id=wx.ID_ANY)
-        self.swfBrowse = filebrowse.FileBrowseButton(parent=swfPanel, id=wx.ID_ANY,
-                                                     fileMask="SWF file (*.swf)|*.swf",
-                                                     labelText=_("SWF file:"),
-                                                     dialogTitle=_("Choose file to save animation"),
-                                                     buttonText=_("Browse"),
-                                                     startDirectory=os.getcwd(), fileMode=wx.FD_SAVE)
+        self.swfBrowse = filebrowse.FileBrowseButton(
+            parent=swfPanel,
+            id=wx.ID_ANY,
+            fileMask="SWF file (*.swf)|*.swf",
+            labelText=_("SWF file:"),
+            dialogTitle=_("Choose file to save animation"),
+            buttonText=_("Browse"),
+            startDirectory=os.getcwd(),
+            fileMode=wx.FD_SAVE)
         swfGridSizer = wx.GridBagSizer(hgap=5, vgap=5)
         swfGridSizer.AddGrowableCol(0)
-        swfGridSizer.Add(self.swfBrowse, pos=(0, 0), flag = wx.EXPAND)
+        swfGridSizer.Add(self.swfBrowse, pos=(0, 0), flag=wx.EXPAND)
         swfPanel.SetSizer(swfGridSizer)
         swfGridSizer.Fit(swfPanel)
 
-        self.formatPanelSizer.Add(item=swfPanel, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
+        self.formatPanelSizer.Add(
+            item=swfPanel,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
         self.formatPanels.append(swfPanel)
 
         # panel for avi
         aviPanel = wx.Panel(parent=panel, id=wx.ID_ANY)
         ffmpeg = gcore.find_program('ffmpeg', '--help')
         if not ffmpeg:
-            warning = _("Program 'ffmpeg' was not found.\nPlease install it first "
-                        "and make sure\nit's in the PATH variable.")
+            warning = _(
+                "Program 'ffmpeg' was not found.\nPlease install it first "
+                "and make sure\nit's in the PATH variable.")
             warningLabel = wx.StaticText(parent=aviPanel, label=warning)
             warningLabel.SetForegroundColour(wx.RED)
-        self.aviBrowse = filebrowse.FileBrowseButton(parent=aviPanel, id=wx.ID_ANY,
-                                                     fileMask="AVI file (*.avi)|*.avi",
-                                                     labelText=_("AVI file:"),
-                                                     dialogTitle=_("Choose file to save animation"),
-                                                     buttonText=_("Browse"),
-                                                     startDirectory=os.getcwd(), fileMode=wx.FD_SAVE)
-        encodingLabel = wx.StaticText(parent=aviPanel, id=wx.ID_ANY, label=_("Video codec:"))
-        self.encodingText = wx.TextCtrl(parent=aviPanel, id=wx.ID_ANY, value='mpeg4')
-        optionsLabel = wx.StaticText(parent=aviPanel, label=_("Additional options:"))
+        self.aviBrowse = filebrowse.FileBrowseButton(
+            parent=aviPanel,
+            id=wx.ID_ANY,
+            fileMask="AVI file (*.avi)|*.avi",
+            labelText=_("AVI file:"),
+            dialogTitle=_("Choose file to save animation"),
+            buttonText=_("Browse"),
+            startDirectory=os.getcwd(),
+            fileMode=wx.FD_SAVE)
+        encodingLabel = wx.StaticText(
+            parent=aviPanel,
+            id=wx.ID_ANY,
+            label=_("Video codec:"))
+        self.encodingText = wx.TextCtrl(
+            parent=aviPanel, id=wx.ID_ANY, value='mpeg4')
+        optionsLabel = wx.StaticText(
+            parent=aviPanel, label=_("Additional options:"))
         self.optionsText = wx.TextCtrl(parent=aviPanel)
-        self.optionsText.SetToolTipString(_("Consider adding '-sameq' or '-qscale 1' "
-                                            "if not satisfied with video quality. "
-                                            "Options depend on ffmpeg version."))
+        self.optionsText.SetToolTipString(
+            _(
+                "Consider adding '-sameq' or '-qscale 1' "
+                "if not satisfied with video quality. "
+                "Options depend on ffmpeg version."))
         aviGridSizer = wx.GridBagSizer(hgap=5, vgap=5)
-        aviGridSizer.Add(self.aviBrowse, pos=(0, 0), span = (1, 2), flag = wx.EXPAND)
-        aviGridSizer.Add(encodingLabel, pos=(1, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        aviGridSizer.Add(self.encodingText, pos=(1, 1), flag = wx.EXPAND)
-        aviGridSizer.Add(optionsLabel, pos=(2, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+        aviGridSizer.Add(
+            self.aviBrowse, pos=(
+                0, 0), span=(
+                1, 2), flag=wx.EXPAND)
+        aviGridSizer.Add(
+            encodingLabel, pos=(1, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL)
+        aviGridSizer.Add(self.encodingText, pos=(1, 1), flag=wx.EXPAND)
+        aviGridSizer.Add(
+            optionsLabel, pos=(2, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL)
         aviGridSizer.Add(self.optionsText, pos=(2, 1), flag=wx.EXPAND)
         if not ffmpeg:
             aviGridSizer.Add(warningLabel, pos=(3, 0), span=(1, 2),
@@ -1012,14 +1323,28 @@
         aviPanel.SetSizer(aviGridSizer)
         aviGridSizer.Fit(aviPanel)
 
-        self.formatPanelSizer.Add(item=aviPanel, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
+        self.formatPanelSizer.Add(
+            item=aviPanel,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
         self.formatPanels.append(aviPanel)
 
         fpsSizer = wx.BoxSizer(wx.HORIZONTAL)
         fps = 1000 / self.timeTick
-        fpsSizer.Add(wx.StaticText(panel, id=wx.ID_ANY, label=_("Current frame rate: %.2f fps") % fps),
-                     proportion=1, flag=wx.EXPAND)
-        borderSizer.Add(fpsSizer, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
+        fpsSizer.Add(
+            wx.StaticText(
+                panel,
+                id=wx.ID_ANY,
+                label=_("Current frame rate: %.2f fps") %
+                fps),
+            proportion=1,
+            flag=wx.EXPAND)
+        borderSizer.Add(
+            fpsSizer,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5)
 
         panel.SetSizer(borderSizer)
         borderSizer.Fit(panel)
@@ -1078,7 +1403,13 @@
             imageInfo = {'name': name, 'file': '', 'pos': [10, 10]}
             self.decorations.append(imageInfo)
         elif name == 'text':
-            textInfo = {'name': name, 'font': self.GetFont(), 'text': '', 'pos': [10, 10]}
+            textInfo = {
+                'name': name,
+                'font': self.GetFont(),
+                'text': '',
+                'pos': [
+                    10,
+                    10]}
             self.decorations.append(textInfo)
 
         self._updateListBox()
@@ -1135,18 +1466,26 @@
             if decor['name'] == 'image':
                 if not os.path.exists(decor['file']):
                     if decor['file']:
-                        GError(parent=self, message=_("File %s not found.") % decor['file'])
+                        GError(
+                            parent=self,
+                            message=_("File %s not found.") %
+                            decor['file'])
                     else:
-                        GError(parent=self, message=_("Decoration image file is missing."))
+                        GError(parent=self,
+                               message=_("Decoration image file is missing."))
                     return
 
         if self.formatChoice.GetSelection() == 0:
             name = self.dirBrowse.GetValue()
             if not os.path.exists(name):
                 if name:
-                    GError(parent=self, message=_("Directory %s not found.") % name)
+                    GError(
+                        parent=self,
+                        message=_("Directory %s not found.") %
+                        name)
                 else:
-                    GError(parent=self, message=_("Export directory is missing."))
+                    GError(parent=self, message=_(
+                        "Export directory is missing."))
                 return
         elif self.formatChoice.GetSelection() == 1:
             if not self.gifBrowse.GetValue():
@@ -1191,7 +1530,10 @@
 
     def _updateListBox(self):
         self.listbox.Clear()
-        names = {'time': _("Time stamp"), 'image': _("Image"), 'text': _("Text")}
+        names = {
+            'time': _("Time stamp"),
+            'image': _("Image"),
+            'text': _("Text")}
         for decor in self.decorations:
             self.listbox.Append(names[decor['name']], clientData=decor)
 
@@ -1208,11 +1550,13 @@
     """Simple layer manager for animation tool.
     Allows adding space-time dataset or series of maps.
     """
+
     def __init__(self, parent, layerList,
                  lmgrStyle=SIMPLE_LMGR_RASTER | SIMPLE_LMGR_VECTOR |
                  SIMPLE_LMGR_TB_TOP | SIMPLE_LMGR_STDS,
                  toolbarCls=AnimSimpleLmgrToolbar, modal=True):
-        SimpleLayerManager.__init__(self, parent, layerList, lmgrStyle, toolbarCls, modal)
+        SimpleLayerManager.__init__(
+            self, parent, layerList, lmgrStyle, toolbarCls, modal)
         self._3dActivated = False
 
     def OnAddStds(self, event):
@@ -1225,7 +1569,8 @@
         event.Skip()
 
     def SetStdsProperties(self, layer):
-        dlg = AddTemporalLayerDialog(parent=self, layer=layer, volume=self._3dActivated)
+        dlg = AddTemporalLayerDialog(
+            parent=self, layer=layer, volume=self._3dActivated)
         # first get hidden property, it's altered afterwards
         hidden = layer.hidden
         dlg.CenterOnParent()
@@ -1235,7 +1580,9 @@
                 signal = self.layerAdded
             else:
                 signal = self.cmdChanged
-            signal.emit(index=self._layerList.GetLayerIndex(layer), layer=layer)
+            signal.emit(
+                index=self._layerList.GetLayerIndex(layer),
+                layer=layer)
         else:
             if hidden:
                 self._layerList.RemoveLayer(layer)
@@ -1246,9 +1593,8 @@
     def _layerChangeProperties(self, layer):
         """Opens new module dialog or recycles it."""
         if not hasattr(layer, 'maps'):
-            GUI(parent=self, giface=None,
-                modal=self._modal).ParseCommand(cmd=layer.cmd,
-                                                completed=(self.GetOptData, layer, ''))
+            GUI(parent=self, giface=None, modal=self._modal).ParseCommand(
+                cmd=layer.cmd, completed=(self.GetOptData, layer, ''))
         else:
             self.SetStdsProperties(layer)
 
@@ -1261,6 +1607,7 @@
 
 class AddTemporalLayerDialog(wx.Dialog):
     """Dialog for adding space-time dataset/ map series."""
+
     def __init__(self, parent, layer, volume=False,
                  title=_("Add space-time dataset layer")):
         wx.Dialog.__init__(self, parent=parent, title=title)
@@ -1271,12 +1618,19 @@
         self._cmd = None
 
         self.tselect = Select(parent=self, type='strds')
-        iconTheme = UserSettings.Get(group='appearance', key='iconTheme', subkey='type')
-        bitmapPath = os.path.join(globalvar.ICONDIR, iconTheme, 'layer-open.png')
+        iconTheme = UserSettings.Get(
+            group='appearance',
+            key='iconTheme',
+            subkey='type')
+        bitmapPath = os.path.join(
+            globalvar.ICONDIR,
+            iconTheme,
+            'layer-open.png')
         if os.path.isfile(bitmapPath) and os.path.getsize(bitmapPath):
             bitmap = wx.Bitmap(name=bitmapPath)
         else:
-            bitmap = wx.ArtProvider.GetBitmap(id=wx.ART_MISSING_IMAGE, client=wx.ART_TOOLBAR)
+            bitmap = wx.ArtProvider.GetBitmap(
+                id=wx.ART_MISSING_IMAGE, client=wx.ART_TOOLBAR)
         self.addManyMapsButton = wx.BitmapButton(self, bitmap=bitmap)
         self.addManyMapsButton.Bind(wx.EVT_BUTTON, self._onAddMaps)
 
@@ -1330,11 +1684,16 @@
         typeSizer.Add(self.tchoice)
         bodySizer.Add(typeSizer, flag=wx.EXPAND | wx.BOTTOM, border=5)
 
-        selectSizer.Add(self.tselect, flag=wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, border=5)
+        selectSizer.Add(self.tselect, flag=wx.RIGHT |
+                        wx.ALIGN_CENTER_VERTICAL, border=5)
         selectSizer.Add(self.addManyMapsButton, flag=wx.EXPAND)
         bodySizer.Add(selectSizer, flag=wx.BOTTOM, border=5)
         bodySizer.Add(self.editBtn, flag=wx.BOTTOM, border=5)
-        mainSizer.Add(bodySizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)
+        mainSizer.Add(
+            bodySizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=10)
 
         btnSizer = wx.StdDialogButtonSizer()
         btnSizer.AddButton(self.okBtn)
@@ -1401,8 +1760,9 @@
 
     def _onAddMaps(self, event):
         dlg = MapLayersDialog(self, title=_("Select raster/vector maps."))
-        dlg.applyAddingMapLayers.connect(lambda mapLayers:
-                                         self.tselect.SetValue(','.join(mapLayers)))
+        dlg.applyAddingMapLayers.connect(
+            lambda mapLayers: self.tselect.SetValue(
+                ','.join(mapLayers)))
         if self._mapType == 'raster':
             index = 0
         elif self._mapType == 'vector':
@@ -1422,12 +1782,13 @@
     def _onProperties(self, event):
         self._checkInput()
         if self._cmd:
-            GUI(parent=self, show=True, modal=True).ParseCommand(cmd=self._cmd,
-                                                                 completed=(self._getOptData, '', ''))
+            GUI(parent=self, show=True, modal=True).ParseCommand(
+                cmd=self._cmd, completed=(self._getOptData, '', ''))
 
     def _checkInput(self):
         if not self.tselect.GetValue():
-            GMessage(parent=self, message=_("Please select maps or dataset first."))
+            GMessage(parent=self, message=_(
+                "Please select maps or dataset first."))
             return
 
         if not self._cmd:
@@ -1455,15 +1816,18 @@
 
 class PreferencesDialog(PreferencesBaseDialog):
     """Animation preferences dialog"""
+
     def __init__(self, parent, giface, title=_("Animation Tool settings"),
                  settings=UserSettings):
-        PreferencesBaseDialog.__init__(self, parent=parent, giface=giface, title=title,
-                                       settings=settings, size=(-1, 270))
+        PreferencesBaseDialog.__init__(
+            self, parent=parent, giface=giface, title=title, settings=settings,
+            size=(-1, 270))
         self.formatChanged = Signal('PreferencesDialog.formatChanged')
 
         self._timeFormats = ['%Y-%m-%d %H:%M:%S',  # 2013-12-29 11:16:26
                              '%Y-%m-%d',  # 2013-12-29
-                             '%c',  # Sun Dec 29 11:16:26 2013 (locale-dependent)
+                             '%c',
+                             # Sun Dec 29 11:16:26 2013 (locale-dependent)
                              '%x',  # 12/29/13 (locale-dependent)
                              '%X',  # 11:16:26 (locale-dependent)
                              '%b %d, %Y',  # Dec 29, 2013
@@ -1493,60 +1857,103 @@
         gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
 
         row = 0
-        gridSizer.Add(item=wx.StaticText(parent=panel,
-                                         label=_("Background color:")),
-                      flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
-        color = csel.ColourSelect(parent=panel,
-                                  colour=UserSettings.Get(group='animation',
-                                                          key='bgcolor', subkey='color'),
-                                  size=globalvar.DIALOG_COLOR_SIZE)
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                label=_("Background color:")),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                row,
+                0))
+        color = csel.ColourSelect(
+            parent=panel,
+            colour=UserSettings.Get(
+                group='animation',
+                key='bgcolor',
+                subkey='color'),
+            size=globalvar.DIALOG_COLOR_SIZE)
         color.SetName('GetColour')
         self.winId['animation:bgcolor:color'] = color.GetId()
 
         gridSizer.Add(item=color, pos=(row, 1), flag=wx.ALIGN_RIGHT)
 
         row += 1
-        gridSizer.Add(item=wx.StaticText(parent=panel,
-                                         label=_("Number of parallel processes:")),
-                      flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
-        # when running for the first time, set nprocs based on the number of processes
-        if UserSettings.Get(group='animation', key='nprocs', subkey='value') == -1:
-            UserSettings.Set(group='animation', key='nprocs', subkey='value', value=getCpuCount())
-        nprocs = wx.SpinCtrl(parent=panel,
-                             initial=UserSettings.Get(group='animation', key='nprocs', subkey='value'))
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                label=_("Number of parallel processes:")),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                row,
+                0))
+        # when running for the first time, set nprocs based on the number of
+        # processes
+        if UserSettings.Get(group='animation', key='nprocs',
+                            subkey='value') == -1:
+            UserSettings.Set(
+                group='animation',
+                key='nprocs',
+                subkey='value',
+                value=getCpuCount())
+        nprocs = wx.SpinCtrl(
+            parent=panel,
+            initial=UserSettings.Get(
+                group='animation',
+                key='nprocs',
+                subkey='value'))
         nprocs.SetName('GetValue')
         self.winId['animation:nprocs:value'] = nprocs.GetId()
 
         gridSizer.Add(item=nprocs, pos=(row, 1), flag=wx.ALIGN_RIGHT)
 
         row += 1
-        gridSizer.Add(item=wx.StaticText(parent=panel,
-                                         label=_("Text foreground color:")),
-                      flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
-        color = csel.ColourSelect(parent=panel,
-                                  colour=UserSettings.Get(group='animation',
-                                                          key='font', subkey='fgcolor'),
-                                  size=globalvar.DIALOG_COLOR_SIZE)
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                label=_("Text foreground color:")),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                row,
+                0))
+        color = csel.ColourSelect(
+            parent=panel,
+            colour=UserSettings.Get(
+                group='animation',
+                key='font',
+                subkey='fgcolor'),
+            size=globalvar.DIALOG_COLOR_SIZE)
         color.SetName('GetColour')
         self.winId['animation:font:fgcolor'] = color.GetId()
 
         gridSizer.Add(item=color, pos=(row, 1), flag=wx.ALIGN_RIGHT)
 
         row += 1
-        gridSizer.Add(item=wx.StaticText(parent=panel,
-                                         label=_("Text background color:")),
-                      flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
-        color = csel.ColourSelect(parent=panel,
-                                  colour=UserSettings.Get(group='animation',
-                                                          key='font', subkey='bgcolor'),
-                                  size=globalvar.DIALOG_COLOR_SIZE)
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                label=_("Text background color:")),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                row,
+                0))
+        color = csel.ColourSelect(
+            parent=panel,
+            colour=UserSettings.Get(
+                group='animation',
+                key='font',
+                subkey='bgcolor'),
+            size=globalvar.DIALOG_COLOR_SIZE)
         color.SetName('GetColour')
         self.winId['animation:font:bgcolor'] = color.GetId()
 
         gridSizer.Add(item=color, pos=(row, 1), flag=wx.ALIGN_RIGHT)
 
         gridSizer.AddGrowableCol(1)
-        sizer.Add(item=gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=3)
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=3)
         border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=3)
         panel.SetSizer(border)
 
@@ -1563,47 +1970,77 @@
         gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
 
         row = 0
-        gridSizer.Add(item=wx.StaticText(parent=panel,
-                                         label=_("Absolute time format:")),
-                      flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                label=_("Absolute time format:")),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                row,
+                0))
         self.tempFormat = wx.ComboBox(parent=panel, name='GetValue')
         self.tempFormat.SetItems(self._timeFormats)
         self.tempFormat.SetValue(self._initFormat)
         self.winId['animation:temporal:format'] = self.tempFormat.GetId()
         gridSizer.Add(item=self.tempFormat, pos=(row, 1), flag=wx.ALIGN_RIGHT)
         self.infoTimeLabel = wx.StaticText(parent=panel)
-        self.tempFormat.Bind(wx.EVT_COMBOBOX, lambda evt: self._setTimeFormat(self.tempFormat.GetValue()))
-        self.tempFormat.Bind(wx.EVT_TEXT, lambda evt: self._setTimeFormat(self.tempFormat.GetValue()))
-        self.tempFormat.SetToolTipString(_("Click and then press key up or down to preview "
-                                           "different date and time formats. "
-                                           "Type custom format string."))
+        self.tempFormat.Bind(
+            wx.EVT_COMBOBOX,
+            lambda evt: self._setTimeFormat(
+                self.tempFormat.GetValue()))
+        self.tempFormat.Bind(
+            wx.EVT_TEXT, lambda evt: self._setTimeFormat(
+                self.tempFormat.GetValue()))
+        self.tempFormat.SetToolTipString(
+            _(
+                "Click and then press key up or down to preview "
+                "different date and time formats. "
+                "Type custom format string."))
         row += 1
         gridSizer.Add(item=self.infoTimeLabel, pos=(row, 0), span=(1, 2),
                       flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
         self._setTimeFormat(self.tempFormat.GetValue())
 
         row += 1
-        link = wx.HyperlinkCtrl(panel, id=wx.ID_ANY, label=_("Learn more about formatting options"),
-                                url="http://docs.python.org/2/library/datetime.html#"
-                                "strftime-and-strptime-behavior")
-        link.SetNormalColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_GRAYTEXT))
-        link.SetVisitedColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_GRAYTEXT))
+        link = wx.HyperlinkCtrl(
+            panel, id=wx.ID_ANY,
+            label=_("Learn more about formatting options"),
+            url="http://docs.python.org/2/library/datetime.html#"
+            "strftime-and-strptime-behavior")
+        link.SetNormalColour(
+            wx.SystemSettings_GetColour(
+                wx.SYS_COLOUR_GRAYTEXT))
+        link.SetVisitedColour(
+            wx.SystemSettings_GetColour(
+                wx.SYS_COLOUR_GRAYTEXT))
         gridSizer.Add(item=link, pos=(row, 0), span=(1, 2),
                       flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
 
         row += 2
-        noDataCheck = wx.CheckBox(panel, label=_("Display instances with no data"))
-        noDataCheck.SetToolTipString(_("When animating instant-based data which have irregular timestamps "
-                                       "you can display 'no data frame' (checked option) or "
-                                       "keep last frame."))
-        noDataCheck.SetValue(self.settings.Get(group='animation', key='temporal',
-                                               subkey=['nodata', 'enable']))
+        noDataCheck = wx.CheckBox(
+            panel, label=_("Display instances with no data"))
+        noDataCheck.SetToolTipString(
+            _(
+                "When animating instant-based data which have irregular timestamps "
+                "you can display 'no data frame' (checked option) or "
+                "keep last frame."))
+        noDataCheck.SetValue(
+            self.settings.Get(
+                group='animation',
+                key='temporal',
+                subkey=[
+                    'nodata',
+                    'enable']))
         self.winId['animation:temporal:nodata:enable'] = noDataCheck.GetId()
         gridSizer.Add(item=noDataCheck, pos=(row, 0), span=(1, 2),
                       flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
 
         gridSizer.AddGrowableCol(1)
-        sizer.Add(item=gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=3)
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=3)
         border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=3)
         panel.SetSizer(border)
 

Modified: grass/trunk/gui/wxpython/animation/frame.py
===================================================================
--- grass/trunk/gui/wxpython/animation/frame.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/frame.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -47,6 +47,7 @@
 
 
 class AnimationFrame(wx.Frame):
+
     def __init__(self, parent, giface, title=_("GRASS GIS Animation tool"),
                  rasters=None, timeseries=None):
         wx.Frame.__init__(self, parent, title=title,
@@ -55,26 +56,35 @@
         self.SetClientSize(self.GetSize())
         self.iconsize = (16, 16)
 
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass_map.ico'), wx.BITMAP_TYPE_ICO))
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass_map.ico'),
+                wx.BITMAP_TYPE_ICO))
 
         # Make sure the temporal database exists
         tgis.init()
 
-        # create temporal directory and ensure it's deleted after programs ends (stored in MAPSET/.tmp/)
+        # create temporal directory and ensure it's deleted after programs ends
+        # (stored in MAPSET/.tmp/)
         global TMP_DIR
         TMP_DIR = gcore.tempdir()
 
         self.animations = [Animation() for i in range(MAX_COUNT)]
         self.windows = []
-        self.animationPanel = AnimationsPanel(self, self.windows, initialCount=MAX_COUNT)
+        self.animationPanel = AnimationsPanel(
+            self, self.windows, initialCount=MAX_COUNT)
         bitmapPool = BitmapPool()
         mapFilesPool = MapFilesPool()
 
         self._progressDlg = None
         self._progressDlgMax = None
 
-        self.provider = BitmapProvider(bitmapPool=bitmapPool,
-                                       mapFilesPool=mapFilesPool, tempDir=TMP_DIR)
+        self.provider = BitmapProvider(
+            bitmapPool=bitmapPool,
+            mapFilesPool=mapFilesPool,
+            tempDir=TMP_DIR)
         self.animationSliders = {}
         self.animationSliders['nontemporal'] = SimpleAnimationSlider(self)
         self.animationSliders['temporal'] = TimeAnimationSlider(self)
@@ -91,7 +101,8 @@
             self.provider.renderingStarted.connect(self._showRenderingProgress)
             self.provider.renderingContinues.connect(self._updateProgress)
             self.provider.renderingFinished.connect(self._closeProgress)
-            self.provider.compositionStarted.connect(self._showRenderingProgress)
+            self.provider.compositionStarted.connect(
+                self._showRenderingProgress)
             self.provider.compositionContinues.connect(self._updateProgress)
             self.provider.compositionFinished.connect(self._closeProgress)
 
@@ -126,9 +137,12 @@
                           Floatable(False).BestSize((-1, -1)).
                           CloseButton(False).DestroyOnClose(True).Layer(0))
         for name, slider in self.animationSliders.iteritems():
-            self._mgr.AddPane(slider, wx.aui.AuiPaneInfo().PaneBorder(False).Name('slider_' + name).
-                              Layer(1).CaptionVisible(False).BestSize(slider.GetBestSize()).
-                              DestroyOnClose(True).CloseButton(False).Bottom())
+            self._mgr.AddPane(
+                slider,
+                wx.aui.AuiPaneInfo().PaneBorder(False).Name(
+                    'slider_' +
+                    name). Layer(1).CaptionVisible(False).BestSize(
+                    slider.GetBestSize()). DestroyOnClose(True).CloseButton(False).Bottom())
             self._mgr.GetPane('slider_' + name).Hide()
 
     def _addToolbar(self, name):
@@ -159,7 +173,8 @@
                               BottomDockable(True).TopDockable(True).
                               CloseButton(False).Layer(2).Row(1).
                               BestSize((self.toolbars['animationToolbar'].GetBestSize())))
-            self.controller.SetAnimationToolbar(self.toolbars['animationToolbar'])
+            self.controller.SetAnimationToolbar(
+                self.toolbars['animationToolbar'])
         elif name == 'miscToolbar':
             self.toolbars[name] = MiscToolbar(self)
             self._mgr.AddPane(self.toolbars[name],
@@ -245,9 +260,10 @@
             else:
                 win.Show()
         else:  # start
-            win = SpeedDialog(self, temporalMode=self.controller.GetTemporalMode(),
-                              timeGranularity=self.controller.GetTimeGranularity(),
-                              initialSpeed=self.controller.timeTick)
+            win = SpeedDialog(
+                self, temporalMode=self.controller.GetTemporalMode(),
+                timeGranularity=self.controller.GetTimeGranularity(),
+                initialSpeed=self.controller.timeTick)
             win.CenterOnParent()
             self.dialogs['speed'] = win
             win.speedChanged.connect(self.ChangeSpeed)
@@ -260,13 +276,14 @@
         self.controller.Reload()
 
     def _showRenderingProgress(self, count):
-        # the message is not really visible, it's there for the initial dlg size
-        self._progressDlg = wx.ProgressDialog(title=_("Loading data"),
-                                              message="Loading data started, please be patient.",
-                                              maximum=count,
-                                              parent=self,
-                                              style=wx.PD_CAN_ABORT | wx.PD_APP_MODAL |
-                                              wx.PD_AUTO_HIDE | wx.PD_SMOOTH)
+        # the message is not really visible, it's there for the initial dlg
+        # size
+        self._progressDlg = wx.ProgressDialog(
+            title=_("Loading data"),
+            message="Loading data started, please be patient.",
+            maximum=count,
+            parent=self,
+            style=wx.PD_CAN_ABORT | wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_SMOOTH)
         self._progressDlgMax = count
 
     def _updateProgress(self, current, text):
@@ -296,7 +313,8 @@
         if not self.dialogs['preferences']:
             dlg = PreferencesDialog(parent=self, giface=self._giface)
             self.dialogs['preferences'] = dlg
-            dlg.formatChanged.connect(lambda: self.controller.UpdateAnimations())
+            dlg.formatChanged.connect(
+                lambda: self.controller.UpdateAnimations())
             dlg.CenterOnParent()
 
         self.dialogs['preferences'].ShowModal()
@@ -308,7 +326,7 @@
 
     def OnCloseWindow(self, event):
         if self.controller.timer.IsRunning():
-                self.controller.timer.Stop()
+            self.controller.timer.Stop()
         CleanUp(TMP_DIR)()
         self.Destroy()
 
@@ -321,6 +339,7 @@
 
 
 class AnimationsPanel(wx.Panel):
+
     def __init__(self, parent, windows, initialCount=4):
         wx.Panel.__init__(self, parent, id=wx.ID_ANY, style=wx.NO_BORDER)
         self.shown = []
@@ -361,6 +380,7 @@
 
 
 class AnimationSliderBase(wx.Panel):
+
     def __init__(self, parent):
         wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)
         self.label1 = wx.StaticText(self, id=wx.ID_ANY)
@@ -449,6 +469,7 @@
 
 
 class SimpleAnimationSlider(AnimationSliderBase):
+
     def __init__(self, parent):
         AnimationSliderBase.__init__(self, parent)
 
@@ -461,7 +482,11 @@
                  flag=wx.ALIGN_CENTER | wx.LEFT, border=5)
         hbox.Add(item=self.label1, proportion=0,
                  flag=wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT, border=5)
-        hbox.Add(item=self.slider, proportion=1, flag=wx.ALIGN_CENTER | wx.EXPAND, border=0)
+        hbox.Add(
+            item=self.slider,
+            proportion=1,
+            flag=wx.ALIGN_CENTER | wx.EXPAND,
+            border=0)
         self.SetSizerAndFit(hbox)
 
     def _setFrames(self, count):
@@ -483,6 +508,7 @@
 
 
 class TimeAnimationSlider(AnimationSliderBase):
+
     def __init__(self, parent):
         AnimationSliderBase.__init__(self, parent)
         self.timeLabels = []
@@ -510,7 +536,11 @@
         vbox.Add(item=hbox, proportion=0, flag=wx.EXPAND, border=0)
 
         hbox = wx.BoxSizer(wx.HORIZONTAL)
-        hbox.Add(item=self.slider, proportion=1, flag=wx.ALIGN_CENTER | wx.EXPAND, border=0)
+        hbox.Add(
+            item=self.slider,
+            proportion=1,
+            flag=wx.ALIGN_CENTER | wx.EXPAND,
+            border=0)
         vbox.Add(item=hbox, proportion=0, flag=wx.EXPAND, border=0)
 
         self._setTemporalType()
@@ -572,8 +602,10 @@
         start = self.timeLabels[index][0]
         if self.timeLabels[index][1]:  # interval
             if self.temporalType == TemporalType.ABSOLUTE:
-                label = _("%(from)s %(dash)s %(to)s") % \
-                    {'from': start, 'dash': u"\u2013", 'to': self.timeLabels[index][1]}
+                label = _("%(from)s %(dash)s %(to)s") % {
+                    'from': start,
+                    'dash': u"\u2013",
+                    'to': self.timeLabels[index][1]}
             else:
                 label = _("to %(to)s") % {'to': self.timeLabels[index][1]}
         else:

Modified: grass/trunk/gui/wxpython/animation/g.gui.animation.py
===================================================================
--- grass/trunk/gui/wxpython/animation/g.gui.animation.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/g.gui.animation.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -64,7 +64,7 @@
 
     from grass.script.setup import set_gui_path
     set_gui_path()
-    
+
     from core.globalvar import CheckWxVersion
     from core.utils import _
     from core.giface import StandaloneGrassInterface
@@ -133,7 +133,8 @@
     frame.Show()
     if len(layerList) >= 1:
         # CallAfter added since it was crashing with wxPython 3 gtk
-        wx.CallAfter(frame.SetAnimations, [layerList] + [None] * (MAX_COUNT - 1))
+        wx.CallAfter(frame.SetAnimations,
+                     [layerList] + [None] * (MAX_COUNT - 1))
     app.MainLoop()
 
 if __name__ == '__main__':

Modified: grass/trunk/gui/wxpython/animation/mapwindow.py
===================================================================
--- grass/trunk/gui/wxpython/animation/mapwindow.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/mapwindow.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -35,10 +35,11 @@
     SaveToFile(self, file_name, file_type) method.
 
     """
+
     def __init__(self, *args, **kwargs):
         # make sure the NO_FULL_REPAINT_ON_RESIZE style flag is set.
-        kwargs['style'] = kwargs.setdefault('style', wx.NO_FULL_REPAINT_ON_RESIZE) | \
-            wx.NO_FULL_REPAINT_ON_RESIZE
+        kwargs['style'] = kwargs.setdefault(
+            'style', wx.NO_FULL_REPAINT_ON_RESIZE) | wx.NO_FULL_REPAINT_ON_RESIZE
         wx.Window.__init__(self, *args, **kwargs)
 
         Debug.msg(2, "BufferedWindow.__init__()")
@@ -50,8 +51,8 @@
         self.OnSize(None)
 
     def Draw(self, dc):
-        ## just here as a place holder.
-        ## This method should be over-ridden when subclassed
+        # just here as a place holder.
+        # This method should be over-ridden when subclassed
         pass
 
     def OnPaint(self, event):
@@ -74,9 +75,9 @@
         # event.Skip()
 
     def SaveToFile(self, FileName, FileType=wx.BITMAP_TYPE_PNG):
-        ## This will save the contents of the buffer
-        ## to the specified file. See the wxWindows docs for
-        ## wx.Bitmap::SaveFile for the details
+        # This will save the contents of the buffer
+        # to the specified file. See the wxWindows docs for
+        # wx.Bitmap::SaveFile for the details
         self._Buffer.SaveFile(FileName, FileType)
 
     def UpdateDrawing(self):
@@ -98,6 +99,7 @@
 
 
 class AnimationWindow(BufferedWindow):
+
     def __init__(self, parent, id=wx.ID_ANY,
                  style=wx.DEFAULT_FRAME_STYLE | wx.FULL_REPAINT_ON_RESIZE |
                  wx.BORDER_RAISED):
@@ -145,8 +147,15 @@
             bitmap = wx.BitmapFromImage(im)
             if self._overlay:
                 im = wx.ImageFromBitmap(self.bitmap_overlay)
-                im.Rescale(im.GetWidth() * params['scale'], im.GetHeight() * params['scale'])
-                self._setOverlay(wx.BitmapFromImage(im), xperc=self.perc[0], yperc=self.perc[1])
+                im.Rescale(
+                    im.GetWidth() *
+                    params['scale'],
+                    im.GetHeight() *
+                    params['scale'])
+                self._setOverlay(
+                    wx.BitmapFromImage(im),
+                    xperc=self.perc[0],
+                    yperc=self.perc[1])
         else:
             self.x = 0
             self.y = 0

Modified: grass/trunk/gui/wxpython/animation/nviztask.py
===================================================================
--- grass/trunk/gui/wxpython/animation/nviztask.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/nviztask.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -28,6 +28,7 @@
 
 
 class NvizTask:
+
     def __init__(self):
         self.task = None
         self.filename = None
@@ -48,7 +49,9 @@
         # pprint(gxwXml.nviz_state)
 
         if not gxwXml.nviz_state:
-            raise GException(_("No 3d view information in workspace file <%s>.") % self.filename)
+            raise GException(
+                _("No 3d view information in workspace file <%s>.") %
+                self.filename)
 
         self._getExtent(gxwXml)
         self._processState(gxwXml.nviz_state)
@@ -58,8 +61,8 @@
         for display in root.displays:
             if display['viewMode'] == '3d':
                 self.region['w'], self.region['s'],\
-                self.region['e'], self.region['n'],\
-                self.region['b'], self.region['t'] = display['extent']
+                    self.region['e'], self.region['n'],\
+                    self.region['b'], self.region['t'] = display['extent']
                 self.region['tbres'] = display['tbres']
 
     def _processLayers(self, layers):
@@ -69,18 +72,22 @@
 
             if not layer['nviz']:
                 continue
-            layerName, found = GetLayerNameFromCmd(layer['cmd'], fullyQualified=False,
-                                                   param='map')
+            layerName, found = GetLayerNameFromCmd(
+                layer['cmd'], fullyQualified=False, param='map')
             if not found:
                 continue
 
             if 'surface' in layer['nviz']:
-                self._processSurface(layer['nviz']['surface'], mapName=layerName)
+                self._processSurface(
+                    layer['nviz']['surface'],
+                    mapName=layerName)
             if 'volume' in layer['nviz']:
                 self._processVolume(layer['nviz']['volume'], mapName=layerName)
             if 'vector' in layer['nviz']:
                 if 'points' in layer['nviz']['vector']:
-                    self._processPoints(layer['nviz']['vector']['points'], mapName=layerName)
+                    self._processPoints(
+                        layer['nviz']['vector']['points'],
+                        mapName=layerName)
 
     def _processSurface(self, surface, mapName):
         self._setMultiTaskParam('elevation_map', mapName)
@@ -88,8 +95,8 @@
         # attributes like color, shine, transparency
         attributes = ('color', 'shine', 'transp')  # mask missing
         parameters = (('color_map', 'color'),
-                     ('shininess_map', 'shininess_value'),
-                     ('transparency_map', 'transparency_value'))
+                      ('shininess_map', 'shininess_value'),
+                      ('transparency_map', 'transparency_value'))
         for attr, params in zip(attributes, parameters):
             mapname = None
             const = None
@@ -117,7 +124,9 @@
         value = surface['draw']['wire-color']['value']
         self._setMultiTaskParam('wire_color', value)
         # resolution
-        for mode1, mode2 in zip(('coarse', 'fine'), ('resolution_coarse', 'resolution_fine')):
+        for mode1, mode2 in zip(
+                ('coarse', 'fine'),
+                ('resolution_coarse', 'resolution_fine')):
             value = surface['draw']['resolution'][mode1]
             self._setMultiTaskParam(mode2, value)
 
@@ -135,11 +144,16 @@
                 self._setMultiTaskParam('vpoint_' + attrib, str(val))
         if 'height' in points:
             height = points['height']['value']
-            self._setMultiTaskParam('vpoint_position', '0,0,{h}'.format(h=height))
+            self._setMultiTaskParam(
+                'vpoint_position',
+                '0,0,{h}'.format(
+                    h=height))
         if 'marker' in points:
-            marker = list(UserSettings.Get(group='nviz', key='vector',
-                                           subkey=['points', 'marker'],
-                                           settings_type='internal'))[points['marker']['value']]
+            marker = list(
+                UserSettings.Get(
+                    group='nviz', key='vector', subkey=[
+                        'points', 'marker'], settings_type='internal'))[
+                points['marker']['value']]
             self._setMultiTaskParam('vpoint_marker', marker)
         if 'mode' in points:
             if points['mode']['type'] == '3d':
@@ -160,10 +174,11 @@
             self._setMultiTaskParam('volume_resolution', res_value)
             for isosurface in isosurfaces:
                 attributes = ('topo', 'color', 'shine', 'transp')
-                parameters = ((None, 'isosurf_level'),
-                              ('isosurf_color_map', 'isosurf_color_value'),
-                              ('isosurf_shininess_map', 'isosurf_shininess_value'),
-                              ('isosurf_transparency_map', 'isosurf_transparency_value'))
+                parameters = (
+                    (None, 'isosurf_level'),
+                    ('isosurf_color_map', 'isosurf_color_value'),
+                    ('isosurf_shininess_map', 'isosurf_shininess_value'),
+                    ('isosurf_transparency_map', 'isosurf_transparency_value'))
                 for attr, params in zip(attributes, parameters):
                     mapname = None
                     const = None
@@ -182,8 +197,10 @@
                         self._setMultiTaskParam(params[0], mapname)
                     else:
                         if attr == 'topo':
-                            # TODO: we just assume it's the first volume, what to do else?
-                            self._setMultiTaskParam(params[1], '1:' + str(const))
+                            # TODO: we just assume it's the first volume, what
+                            # to do else?
+                            self._setMultiTaskParam(
+                                params[1], '1:' + str(const))
                         else:
                             self._setMultiTaskParam(params[1], const)
                 if isosurface['inout']['value']:
@@ -194,12 +211,15 @@
             res_value = volume['draw']['resolution']['slice']['value']
             self._setMultiTaskParam('volume_resolution', res_value)
             for slice_ in slices:
-                self._setMultiTaskParam('slice_transparency', slice_['transp']['value'])
+                self._setMultiTaskParam(
+                    'slice_transparency', slice_['transp']['value'])
                 axis = slice_['position']['axis']
                 self._setMultiTaskParam('slice', '1:' + 'xyz'[axis])
                 pos = slice_['position']
-                coords = pos['x1'], pos['x2'], pos['y1'], pos['y2'], pos['z1'], pos['z2']
-                self._setMultiTaskParam('slice_position', ','.join([str(c) for c in coords]))
+                coords = pos['x1'], pos['x2'], pos[
+                    'y1'], pos['y2'], pos['z1'], pos['z2']
+                self._setMultiTaskParam('slice_position', ','.join(
+                    [str(c) for c in coords]))
 
         # position
         pos = []
@@ -212,19 +232,25 @@
     def _processState(self, state):
         color = state['view']['background']['color']
         self.task.set_param('bgcolor', self._join(color, delim=':'))
-        self.task.set_param('position', self._join((state['view']['position']['x'],
-                                                    state['view']['position']['y'])))
+        self.task.set_param(
+            'position', self._join(
+                (state['view']['position']['x'],
+                 state['view']['position']['y'])))
         self.task.set_param('height', state['iview']['height']['value'])
         self.task.set_param('perspective', state['view']['persp']['value'])
         self.task.set_param('twist', state['view']['twist']['value'])
         # TODO: fix zexag
         self.task.set_param('zexag', state['view']['z-exag']['value'])
-        self.task.set_param('focus', self._join((state['iview']['focus']['x'],
-                                                 state['iview']['focus']['y'],
-                                                 state['iview']['focus']['z'])))
-        self.task.set_param('light_position', self._join((state['light']['position']['x'],
-                                                          state['light']['position']['y'],
-                                                          state['light']['position']['z'] / 100.)))
+        self.task.set_param(
+            'focus', self._join(
+                (state['iview']['focus']['x'],
+                 state['iview']['focus']['y'],
+                 state['iview']['focus']['z'])))
+        self.task.set_param(
+            'light_position', self._join(
+                (state['light']['position']['x'],
+                 state['light']['position']['y'],
+                 state['light']['position']['z'] / 100.)))
         color = state['light']['color'][:3]
         self.task.set_param('light_color', self._join(color, delim=':'))
         self.task.set_param('light_brightness', int(state['light']['bright']))
@@ -262,7 +288,8 @@
         if hasattr(layer, 'maps'):
             series = layer.maps
         else:
-            raise GException(_("No map series nor space-time dataset is added."))
+            raise GException(
+                _("No map series nor space-time dataset is added."))
 
         for value in series:
             self.task.set_param(paramName, value)
@@ -273,7 +300,10 @@
                 self.task.set_param('isosurf_color_map', '')
             self.task.set_flag('overwrite', True)
             self.task.set_param('output', 'tobechanged')
-            cmd = self.task.get_cmd(ignoreErrors=False, ignoreRequired=False, ignoreDefault=True)
+            cmd = self.task.get_cmd(
+                ignoreErrors=False,
+                ignoreRequired=False,
+                ignoreDefault=True)
             commands.append(cmd)
 
         return commands
@@ -283,7 +313,10 @@
             return None
         self.task.set_flag('overwrite', True)
         self.task.set_param('output', 'tobechanged')
-        cmd = self.task.get_cmd(ignoreErrors=False, ignoreRequired=False, ignoreDefault=True)
+        cmd = self.task.get_cmd(
+            ignoreErrors=False,
+            ignoreRequired=False,
+            ignoreDefault=True)
         return gtask.cmdlist_to_tuple(cmd)
 
     def GetRegion(self):
@@ -298,7 +331,8 @@
     cmds = nviz.GetCommandSeries(['aspect', 'elevation'], 'color_map')
     for cmd in cmds:
         print cmd
-        returncode, message = RunCommand(getErrorMsg=True, prog=cmd[0], **cmd[1])
+        returncode, message = RunCommand(
+            getErrorMsg=True, prog=cmd[0], **cmd[1])
         print returncode, message
 
 

Modified: grass/trunk/gui/wxpython/animation/provider.py
===================================================================
--- grass/trunk/gui/wxpython/animation/provider.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/provider.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -44,13 +44,15 @@
     There is one instance of this class in the application.
     It handles both 2D and 3D animations.
     """
+
     def __init__(self, bitmapPool, mapFilesPool, tempDir,
                  imageWidth=640, imageHeight=480):
 
         self._bitmapPool = bitmapPool
         self._mapFilesPool = mapFilesPool
         self.imageWidth = imageWidth  # width of the image to render with d.rast or d.vect
-        self.imageHeight = imageHeight  # height of the image to render with d.rast or d.vect
+        # height of the image to render with d.rast or d.vect
+        self.imageHeight = imageHeight
         self._tempDir = tempDir
 
         self._uniqueCmds = []
@@ -70,7 +72,8 @@
         self.renderingStarted = Signal('BitmapProvider.renderingStarted')
         self.compositionStarted = Signal('BitmapProvider.compositionStarted')
         self.renderingContinues = Signal('BitmapProvider.renderingContinues')
-        self.compositionContinues = Signal('BitmapProvider.compositionContinues')
+        self.compositionContinues = Signal(
+            'BitmapProvider.compositionContinues')
         self.renderingFinished = Signal('BitmapProvider.renderingFinished')
         self.compositionFinished = Signal('BitmapProvider.compositionFinished')
         self.mapsLoaded = Signal('BitmapProvider.mapsLoaded')
@@ -89,7 +92,9 @@
         :param opacities: list of opacity values
         :param regions: list of regions
         """
-        Debug.msg(2, "BitmapProvider.SetCmds: {n} lists".format(n=len(cmdsForComposition)))
+        Debug.msg(
+            2, "BitmapProvider.SetCmds: {n} lists".format(
+                n=len(cmdsForComposition)))
         self._cmdsForComposition.extend(cmdsForComposition)
         self._opacities.extend(opacities)
         self._regions.extend(regions)
@@ -102,7 +107,9 @@
         :param cmds: list of commands m.nviz.image (cmd as a list)
         :param region: for 3D rendering
         """
-        Debug.msg(2, "BitmapProvider.SetCmds3D: {c} commands".format(c=len(cmds)))
+        Debug.msg(
+            2, "BitmapProvider.SetCmds3D: {c} commands".format(
+                c=len(cmds)))
         self._cmds3D = cmds
         self._regionFor3D = region
 
@@ -118,8 +125,8 @@
                     unique.append((tuple(cmd), None))
         unique = list(set(unique))
         self._uniqueCmds = [cmdAndRegion[0] for cmdAndRegion in unique]
-        self._regionsForUniqueCmds.extend([dict(cmdAndRegion[1]) if cmdAndRegion[1] else None
-                                           for cmdAndRegion in unique])
+        self._regionsForUniqueCmds.extend([dict(cmdAndRegion[1]) if cmdAndRegion[
+                                          1] else None for cmdAndRegion in unique])
 
     def Unload(self):
         """Unloads currently loaded data.
@@ -127,10 +134,12 @@
         """
         Debug.msg(2, "BitmapProvider.Unload")
         if self._cmdsForComposition:
-            for cmd, region in zip(self._uniqueCmds, self._regionsForUniqueCmds):
+            for cmd, region in zip(self._uniqueCmds,
+                                   self._regionsForUniqueCmds):
                 del self._mapFilesPool[HashCmd(cmd, region)]
 
-            for cmdList, region in zip(self._cmdsForComposition, self._regions):
+            for cmdList, region in zip(
+                    self._cmdsForComposition, self._regions):
                 del self._bitmapPool[HashCmds(cmdList, region)]
             self._uniqueCmds = []
             self._cmdsForComposition = []
@@ -151,12 +160,15 @@
         count = 0
         for cmd, region in zip(uniqueCmds, regions):
             filename = GetFileFromCmd(self._tempDir, cmd, region)
-            if not force and os.path.exists(filename) and \
-               self._mapFilesPool.GetSize(HashCmd(cmd, region)) == (self.imageWidth, self.imageHeight):
+            if not force and os.path.exists(filename) and self._mapFilesPool.GetSize(
+                    HashCmd(cmd, region)) == (self.imageWidth, self.imageHeight):
                 continue
             count += 1
 
-        Debug.msg(3, "BitmapProvider._dryRender: {c} files to be rendered".format(c=count))
+        Debug.msg(
+            3,
+            "BitmapProvider._dryRender: {c} files to be rendered".format(
+                c=count))
 
         return count
 
@@ -170,13 +182,17 @@
         """
         count = 0
         for cmdList, region in zip(cmdLists, regions):
-            if not force and HashCmds(cmdList, region) in self._bitmapPool and \
-                self._bitmapPool[HashCmds(cmdList, region)].GetSize() == (self.imageWidth,
-                                                                          self.imageHeight):
+            if not force and HashCmds(
+                    cmdList, region) in self._bitmapPool and self._bitmapPool[
+                    HashCmds(cmdList, region)].GetSize() == (
+                    self.imageWidth, self.imageHeight):
                 continue
             count += 1
 
-        Debug.msg(2, "BitmapProvider._dryCompose: {c} files to be composed".format(c=count))
+        Debug.msg(
+            2,
+            "BitmapProvider._dryCompose: {c} files to be composed".format(
+                c=count))
 
         return count
 
@@ -206,19 +222,33 @@
 
         # create no data bitmap
         if None not in self._bitmapPool or force:
-            self._bitmapPool[None] = createNoDataBitmap(self.imageWidth, self.imageHeight)
+            self._bitmapPool[None] = createNoDataBitmap(
+                self.imageWidth, self.imageHeight)
 
-        ok = self._renderer.Render(cmds, regions, regionFor3D=self._regionFor3D,
-                                   bgcolor=bgcolor, force=force, nprocs=nprocs)
+        ok = self._renderer.Render(
+            cmds,
+            regions,
+            regionFor3D=self._regionFor3D,
+            bgcolor=bgcolor,
+            force=force,
+            nprocs=nprocs)
         self.renderingFinished.emit()
         if not ok:
             self.mapsLoaded.emit()  # what to do here?
             return
         if self._cmdsForComposition:
-            count = self._dryCompose(self._cmdsForComposition, self._regions, force=force)
+            count = self._dryCompose(
+                self._cmdsForComposition,
+                self._regions,
+                force=force)
             self.compositionStarted.emit(count=count)
-            self._composer.Compose(self._cmdsForComposition, self._regions, self._opacities,
-                                   bgcolor=bgcolor, force=force, nprocs=nprocs)
+            self._composer.Compose(
+                self._cmdsForComposition,
+                self._regions,
+                self._opacities,
+                bgcolor=bgcolor,
+                force=force,
+                nprocs=nprocs)
             self.compositionFinished.emit()
         if self._cmds3D:
             for cmd in self._cmds3D:
@@ -247,7 +277,9 @@
 
     def WindowSizeChanged(self, width, height):
         """Sets size when size of related window changes."""
-        Debug.msg(5, "BitmapProvider.WindowSizeChanged: w={w}, h={h}".format(w=width, h=height))
+        Debug.msg(
+            5, "BitmapProvider.WindowSizeChanged: w={w}, h={h}".format(
+                w=width, h=height))
 
         self.imageWidth, self.imageHeight = width, height
 
@@ -271,7 +303,8 @@
 
         Debug.msg(1, "Render raster legend " + str(filename))
         cmdTuple = cmdlist_to_tuple(cmd)
-        returncode, stdout, messages = read2_command(cmdTuple[0], **cmdTuple[1])
+        returncode, stdout, messages = read2_command(
+            cmdTuple[0], **cmdTuple[1])
 
         if returncode == 0:
             return wx.BitmapFromImage(autoCropImageFromFile(filename))
@@ -282,6 +315,7 @@
 
 class BitmapRenderer:
     """Class which renderes 2D and 3D images to files."""
+
     def __init__(self, mapFilesPool, tempDir,
                  imageWidth, imageHeight):
         self._mapFilesPool = mapFilesPool
@@ -315,8 +349,8 @@
         filteredCmdList = []
         for cmd, region in zip(cmdList, regions):
             filename = GetFileFromCmd(self._tempDir, cmd, region)
-            if not force and os.path.exists(filename) and \
-               self._mapFilesPool.GetSize(HashCmd(cmd, region)) == (self.imageWidth, self.imageHeight):
+            if not force and os.path.exists(filename) and self._mapFilesPool.GetSize(
+                    HashCmd(cmd, region)) == (self.imageWidth, self.imageHeight):
                 # for reference counting
                 self._mapFilesPool[HashCmd(cmd, region)] = filename
                 continue
@@ -332,13 +366,27 @@
             q = Queue()
             # The separate render process
             if cmd[0] == 'm.nviz.image':
-                p = Process(target=RenderProcess3D,
-                            args=(self.imageWidth, self.imageHeight, self._tempDir,
-                                  cmd, regionFor3D, bgcolor, q))
+                p = Process(
+                    target=RenderProcess3D,
+                    args=(
+                        self.imageWidth,
+                        self.imageHeight,
+                        self._tempDir,
+                        cmd,
+                        regionFor3D,
+                        bgcolor,
+                        q))
             else:
-                p = Process(target=RenderProcess2D,
-                            args=(self.imageWidth, self.imageHeight, self._tempDir,
-                                  cmd, region, bgcolor, q))
+                p = Process(
+                    target=RenderProcess2D,
+                    args=(
+                        self.imageWidth,
+                        self.imageHeight,
+                        self._tempDir,
+                        cmd,
+                        region,
+                        bgcolor,
+                        q))
             p.start()
 
             queue_list.append(q)
@@ -351,16 +399,22 @@
                 for i in range(len(cmd_list)):
                     proc_list[i].join()
                     filename = queue_list[i].get()
-                    self._mapFilesPool[HashCmd(cmd_list[i][0], cmd_list[i][1])] = filename
-                    self._mapFilesPool.SetSize(HashCmd(cmd_list[i][0], cmd_list[i][1]),
-                                               (self.imageWidth, self.imageHeight))
+                    self._mapFilesPool[
+                        HashCmd(
+                            cmd_list[i][0],
+                            cmd_list[i][1])] = filename
+                    self._mapFilesPool.SetSize(
+                        HashCmd(cmd_list[i][0],
+                                cmd_list[i][1]),
+                        (self.imageWidth, self.imageHeight))
 
                 proc_count = 0
                 proc_list = []
                 queue_list = []
                 cmd_list = []
 
-            self.renderingContinues.emit(current=count, text=_("Rendering map layers"))
+            self.renderingContinues.emit(
+                current=count, text=_("Rendering map layers"))
             if self._stopRendering:
                 self._stopRendering = False
                 stopped = True
@@ -377,6 +431,7 @@
 
 class BitmapComposer:
     """Class which handles the composition of image files with g.pnmcomp."""
+
     def __init__(self, tempDir, mapFilesPool, bitmapPool,
                  imageWidth, imageHeight):
         self._mapFilesPool = mapFilesPool
@@ -411,11 +466,19 @@
 
         filteredCmdLists = []
         for cmdList, region in zip(cmdLists, regions):
-            if not force and HashCmds(cmdList, region) in self._bitmapPool and \
-                self._bitmapPool[HashCmds(cmdList, region)].GetSize() == (self.imageWidth,
-                                                                          self.imageHeight):
-                # TODO: find a better way than to assign the same to increase the reference
-                self._bitmapPool[HashCmds(cmdList, region)] = self._bitmapPool[HashCmds(cmdList, region)]
+            if not force and HashCmds(
+                    cmdList, region) in self._bitmapPool and self._bitmapPool[
+                    HashCmds(cmdList, region)].GetSize() == (
+                    self.imageWidth, self.imageHeight):
+                # TODO: find a better way than to assign the same to increase
+                # the reference
+                self._bitmapPool[
+                    HashCmds(
+                        cmdList,
+                        region)] = self._bitmapPool[
+                    HashCmds(
+                        cmdList,
+                        region)]
                 continue
             filteredCmdLists.append((cmdList, region))
 
@@ -444,19 +507,27 @@
                     proc_list[i].join()
                     filename = queue_list[i].get()
                     if filename is None:
-                        self._bitmapPool[HashCmds(cmd_lists[i][0], cmd_lists[i][1])] = \
-                            createNoDataBitmap(self.imageWidth, self.imageHeight,
-                                               text="Failed to render")
+                        self._bitmapPool[
+                            HashCmds(
+                                cmd_lists[i][0],
+                                cmd_lists[i][1])] = createNoDataBitmap(
+                            self.imageWidth,
+                            self.imageHeight,
+                            text="Failed to render")
                     else:
-                        self._bitmapPool[HashCmds(cmd_lists[i][0], cmd_lists[i][1])] = \
-                            wx.BitmapFromImage(wx.Image(filename))
+                        self._bitmapPool[
+                            HashCmds(
+                                cmd_lists[i][0],
+                                cmd_lists[i][1])] = wx.BitmapFromImage(
+                            wx.Image(filename))
                         os.remove(filename)
                 proc_count = 0
                 proc_list = []
                 queue_list = []
                 cmd_lists = []
 
-            self.compositionContinues.emit(current=count, text=_("Overlaying map layers"))
+            self.compositionContinues.emit(
+                current=count, text=_("Overlaying map layers"))
             if self._stopComposing:
                 self._stopComposing = False
                 break
@@ -469,7 +540,8 @@
             self._stopComposing = True
 
 
-def RenderProcess2D(imageWidth, imageHeight, tempDir, cmd, region, bgcolor, fileQueue):
+def RenderProcess2D(imageWidth, imageHeight, tempDir,
+                    cmd, region, bgcolor, fileQueue):
     """Render raster or vector files as ppm image and write the
        resulting ppm filename in the provided file queue
 
@@ -506,7 +578,8 @@
     fileQueue.put(filename)
 
 
-def RenderProcess3D(imageWidth, imageHeight, tempDir, cmd, region, bgcolor, fileQueue):
+def RenderProcess3D(imageWidth, imageHeight, tempDir,
+                    cmd, region, bgcolor, fileQueue):
     """Renders image with m.nviz.image and writes the
        resulting ppm filename in the provided file queue
 
@@ -530,7 +603,8 @@
     cmdTuple[1]['size'] = '%d,%d' % (imageWidth, imageHeight)
     # set format
     cmdTuple[1]['format'] = 'ppm'
-    cmdTuple[1]['bgcolor'] = bgcolor = ':'.join([str(part) for part in bgcolor])
+    cmdTuple[1]['bgcolor'] = bgcolor = ':'.join(
+        [str(part) for part in bgcolor])
     returncode, stdout, messages = read2_command(cmdTuple[0], **cmdTuple[1])
     if returncode != 0:
         gcore.warning("Rendering failed:\n" + messages)
@@ -542,7 +616,8 @@
     fileQueue.put(filename)
 
 
-def CompositeProcess(imageWidth, imageHeight, tempDir, cmdList, region, opacities, bgcolor, fileQueue):
+def CompositeProcess(imageWidth, imageHeight, tempDir,
+                     cmdList, region, opacities, bgcolor, fileQueue):
     """Performs the composition of image ppm files and writes the
        resulting ppm filename in the provided file queue
 
@@ -569,15 +644,11 @@
 
     opacities = [str(op) for op in opacities]
     bgcolor = ':'.join([str(part) for part in bgcolor])
-    returncode, stdout, messages = read2_command('g.pnmcomp',
-                                                 overwrite=True,
-                                                 input='%s' % ",".join(reversed(maps)),
-                                                 mask='%s' % ",".join(reversed(masks)),
-                                                 opacity='%s' % ",".join(reversed(opacities)),
-                                                 bgcolor=bgcolor,
-                                                 width=imageWidth,
-                                                 height=imageHeight,
-                                                 output=filename)
+    returncode, stdout, messages = read2_command(
+        'g.pnmcomp', overwrite=True, input='%s' % ",".join(reversed(maps)),
+        mask='%s' % ",".join(reversed(masks)),
+        opacity='%s' % ",".join(reversed(opacities)),
+        bgcolor=bgcolor, width=imageWidth, height=imageHeight, output=filename)
 
     if returncode != 0:
         gcore.warning("Rendering composite failed:\n" + messages)
@@ -592,6 +663,7 @@
     """Base class storing map files/bitmaps (emulates dictionary).
     Counts the references to know which files/bitmaps to delete.
     """
+
     def __init__(self):
         self.dictionary = {}
         self.referenceCount = {}
@@ -605,14 +677,16 @@
             self.referenceCount[key] = 1
         else:
             self.referenceCount[key] += 1
-        Debug.msg(5, 'DictRefCounter.__setitem__: +1 for key {k}'.format(k=key))
+        Debug.msg(
+            5, 'DictRefCounter.__setitem__: +1 for key {k}'.format(k=key))
 
     def __contains__(self, key):
         return key in self.dictionary
 
     def __delitem__(self, key):
         self.referenceCount[key] -= 1
-        Debug.msg(5, 'DictRefCounter.__delitem__: -1 for key {k}'.format(k=key))
+        Debug.msg(
+            5, 'DictRefCounter.__delitem__: -1 for key {k}'.format(k=key))
 
     def keys(self):
         return self.dictionary.keys()
@@ -629,6 +703,7 @@
 
 class MapFilesPool(DictRefCounter):
     """Stores rendered images as files."""
+
     def __init__(self):
         DictRefCounter.__init__(self)
         self.size = {}
@@ -658,12 +733,14 @@
 
 class BitmapPool(DictRefCounter):
     """Class storing bitmaps (emulates dictionary)"""
+
     def __init__(self):
         DictRefCounter.__init__(self)
 
 
 class CleanUp:
     """Responsible for cleaning up the files."""
+
     def __init__(self, tempDir):
         self._tempDir = tempDir
 
@@ -672,9 +749,13 @@
         if os.path.exists(self._tempDir):
             try:
                 shutil.rmtree(self._tempDir)
-                Debug.msg(5, 'CleanUp: removed directory {t}'.format(t=self._tempDir))
+                Debug.msg(
+                    5, 'CleanUp: removed directory {t}'.format(
+                        t=self._tempDir))
             except OSError:
-                gcore.warning(_("Directory {t} not removed.").format(t=self._tempDir))
+                gcore.warning(
+                    _("Directory {t} not removed.").format(
+                        t=self._tempDir))
 
 
 def _setEnvironment(width, height, filename, transparent, bgcolor):
@@ -686,20 +767,22 @@
     :param transparent: use transparency
     :param bgcolor: background color as a tuple of 3 values 0 to 255
     """
-    Debug.msg(5, "_setEnvironment: width={w}, height={h}, "
-                 "filename={f}, transparent={t}, bgcolor={b}".format(w=width,
-                                                                     h=height,
-                                                                     f=filename,
-                                                                     t=transparent,
-                                                                     b=bgcolor))
+    Debug.msg(
+        5,
+        "_setEnvironment: width={w}, height={h}, "
+        "filename={f}, transparent={t}, bgcolor={b}".format(
+            w=width,
+            h=height,
+            f=filename,
+            t=transparent,
+            b=bgcolor))
 
     os.environ['GRASS_RENDER_WIDTH'] = str(width)
     os.environ['GRASS_RENDER_HEIGHT'] = str(height)
     driver = UserSettings.Get(group='display', key='driver', subkey='type')
     os.environ['GRASS_RENDER_IMMEDIATE'] = driver
-    os.environ['GRASS_RENDER_BACKGROUNDCOLOR'] = '{r:02x}{g:02x}{b:02x}'.format(r=bgcolor[0],
-                                                                         g=bgcolor[1],
-                                                                         b=bgcolor[2])
+    os.environ['GRASS_RENDER_BACKGROUNDCOLOR'] = '{r:02x}{g:02x}{b:02x}'.format(
+        r=bgcolor[0], g=bgcolor[1], b=bgcolor[2])
     os.environ['GRASS_RENDER_TRUECOLOR'] = "TRUE"
     if transparent:
         os.environ['GRASS_RENDER_TRANSPARENT'] = "TRUE"
@@ -717,9 +800,8 @@
     :param imageWidth: image width
     :param imageHeight: image height
     """
-    Debug.msg(4, "createNoDataBitmap: w={w}, h={h}, text={t}".format(w=imageWidth,
-                                                                     h=imageHeight,
-                                                                     t=text))
+    Debug.msg(4, "createNoDataBitmap: w={w}, h={h}, text={t}".format(
+        w=imageWidth, h=imageHeight, t=text))
     bitmap = wx.EmptyBitmap(imageWidth, imageHeight)
     dc = wx.MemoryDC()
     dc.SelectObject(bitmap)
@@ -780,13 +862,19 @@
     prov = BitmapProvider(bPool, mapFilesPool, tempDir,
                           imageWidth=640, imageHeight=480)
     prov.renderingStarted.connect(
-        lambda count: sys.stdout.write("Total number of maps: {c}\n".format(c=count)))
+        lambda count: sys.stdout.write(
+            "Total number of maps: {c}\n".format(
+                c=count)))
     prov.renderingContinues.connect(
-        lambda current, text: sys.stdout.write("Current number: {c}\n".format(c=current)))
-    prov.compositionStarted.connect(
-        lambda count: sys.stdout.write("Composition: total number of maps: {c}\n".format(c=count)))
+        lambda current, text: sys.stdout.write(
+            "Current number: {c}\n".format(
+                c=current)))
+    prov.compositionStarted.connect(lambda count: sys.stdout.write(
+        "Composition: total number of maps: {c}\n".format(c=count)))
     prov.compositionContinues.connect(
-        lambda current, text: sys.stdout.write("Composition: Current number: {c}\n".format(c=current)))
+        lambda current, text: sys.stdout.write(
+            "Composition: Current number: {c}\n".format(
+                c=current)))
     prov.mapsLoaded.connect(
         lambda: sys.stdout.write("Maps loading finished\n"))
     cmdMatrix = layerListToCmdsMatrix(layerList)
@@ -797,7 +885,11 @@
 
     for key in bPool.keys():
         if key is not None:
-            bPool[key].SaveFile(os.path.join(tempDir, key + '.png'), wx.BITMAP_TYPE_PNG)
+            bPool[key].SaveFile(
+                os.path.join(
+                    tempDir,
+                    key + '.png'),
+                wx.BITMAP_TYPE_PNG)
 #    prov.Unload()
 #    prov.SetCmds(cmdMatrix, [l.opacity for l in layerList])
 #    prov.Load(bgcolor=(13, 156, 230))

Modified: grass/trunk/gui/wxpython/animation/temporal_manager.py
===================================================================
--- grass/trunk/gui/wxpython/animation/temporal_manager.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/temporal_manager.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -40,6 +40,7 @@
 
 class TemporalManager(object):
     """Class for temporal data processing."""
+
     def __init__(self):
         self.timeseriesList = []
         self.timeseriesInfo = {}
@@ -69,7 +70,11 @@
         :param timeseries: name of timeseries (with or without mapset)
         :param etype: element type (strds, stvds)
         """
-        self._gatherInformation(timeseries, etype, self.timeseriesList, self.timeseriesInfo)
+        self._gatherInformation(
+            timeseries,
+            etype,
+            self.timeseriesList,
+            self.timeseriesInfo)
 
     def EvaluateInputData(self):
         """Checks if all timeseries are compatible (raises GException).
@@ -116,7 +121,8 @@
             for infoDict in self.timeseriesInfo.values():
                 units.add(infoDict['unit'])
             if len(units) > 1:
-                message = _("It is not allowed to display data with different units (%s).") % ','.join(units)
+                message = _(
+                    "It is not allowed to display data with different units (%s).") % ','.join(units)
                 return False, message
 
         # check for interval x point
@@ -127,9 +133,10 @@
             else:
                 point += 1
         if bool(interval) == bool(point):
-            message = _("You are going to display data with different "
-                        "temporal types of maps (interval and point)."
-                        " It is recommended to use data of one temporal type to avoid confusion.")
+            message = _(
+                "You are going to display data with different "
+                "temporal types of maps (interval and point)."
+                " It is recommended to use data of one temporal type to avoid confusion.")
             return True, message  # warning
 
         return True, None
@@ -139,7 +146,8 @@
         """
         if self.dataMode == DataMode.SIMPLE:
             gran = self.timeseriesInfo[self.timeseriesList[0]]['granularity']
-            if 'unit' in self.timeseriesInfo[self.timeseriesList[0]]:  # relative:
+            if 'unit' in self.timeseriesInfo[
+                    self.timeseriesList[0]]:  # relative:
                 granNum = gran
                 unit = self.timeseriesInfo[self.timeseriesList[0]]['unit']
                 if self.granularityMode == GranularityMode.ONE_UNIT:
@@ -187,13 +195,13 @@
         # combine all timeLabels and fill missing maps with None
         # BUT this does not work properly if the datasets have
         # no temporal overlap! We would need to sample all datasets
-        # by a temporary dataset, I don't know how it would work with point data
+        # by a temporary dataset, I don't know how it would work with point
+        # data
         if self.temporalType == TemporalType.ABSOLUTE:
             timestamps = sorted(list(labelListSet), key=lambda x: x[0])
         else:
             timestamps = sorted(list(labelListSet), key=lambda x: x[0])
 
-
         newMapLists = []
         for mapList, labelList in zip(mapLists, labelLists):
             newMapList = [None] * len(timestamps)
@@ -210,22 +218,29 @@
 
         if self.temporalType == TemporalType.ABSOLUTE:
             # ('1996-01-01 00:00:00', '1997-01-01 00:00:00', 'year'),
-            formatString = UserSettings.Get(group='animation', key='temporal', subkey='format')
-            timestamps = [(datetime.datetime.strftime(st, formatString),
-                          datetime.datetime.strftime(end, formatString)
-                          if end is not None else None, unit) for (st, end, unit) in timestamps]
+            formatString = UserSettings.Get(
+                group='animation', key='temporal', subkey='format')
+            timestamps = [
+                (datetime.datetime.strftime(
+                    st, formatString), datetime.datetime.strftime(
+                    end, formatString) if end is not None else None, unit) for (
+                    st, end, unit) in timestamps]
         else:
             # ('15', '16', u'years'),
-            timestamps = [(str(st), end if end is None else str(end), unit) for st, end, unit in timestamps]
+            timestamps = [(str(st), end if end is None else str(end), unit)
+                          for st, end, unit in timestamps]
         return timestamps, mapDict
 
     def _getLabelsAndMaps(self, timeseries):
         """Returns time labels and map names (done by sampling)
         for both interval and point data.
         """
-        sp = tgis.dataset_factory(self.timeseriesInfo[timeseries]['etype'], timeseries)
+        sp = tgis.dataset_factory(
+            self.timeseriesInfo[timeseries]['etype'], timeseries)
         if sp.is_in_db() is False:
-            raise GException(_("Space time dataset <%s> not found.") % timeseries)
+            raise GException(
+                _("Space time dataset <%s> not found.") %
+                timeseries)
         sp.select()
 
         listOfMaps = []
@@ -307,7 +322,8 @@
                 end = tgis.string_to_datetime(end)
                 end = tgis.datetime_to_grass_datetime_string(end)
             grassLabels.append((start, end, unit))
-            if '00:00:00' not in start or (end is not None and '00:00:00' not in end):
+            if '00:00:00' not in start or (
+                    end is not None and '00:00:00' not in end):
                 isTime = True
         if not isTime:
             for i, (start, end, unit) in enumerate(grassLabels):
@@ -327,7 +343,8 @@
         maps = sp.get_registered_maps_as_objects()
 
         if not sp.check_temporal_topology(maps):
-            raise GException(_("Topology of Space time dataset %s is invalid." % id))
+            raise GException(
+                _("Topology of Space time dataset %s is invalid." % id))
 
         timeseriesList.append(id)
         infoDict[id] = {}
@@ -364,12 +381,22 @@
     print '///////////////////////////'
     gran = temp.GetGranularity()
     print "granularity: " + str(gran)
-    pprint (temp.GetLabelsAndMaps())
+    pprint(temp.GetLabelsAndMaps())
 
 
 def createAbsoluteInterval():
-    grass.run_command('g.region', s=0, n=80, w=0, e=120, b=0, t=50, res=10, res3=10,
-                      flags='p3', quiet=True)
+    grass.run_command(
+        'g.region',
+        s=0,
+        n=80,
+        w=0,
+        e=120,
+        b=0,
+        t=50,
+        res=10,
+        res3=10,
+        flags='p3',
+        quiet=True)
 
     grass.mapcalc(exp="prec_1 = rand(0, 550)", overwrite=True)
     grass.mapcalc(exp="prec_2 = rand(0, 450)", overwrite=True)
@@ -414,17 +441,37 @@
                       maps='prec_1,prec_2,prec_3,prec_4,prec_5,prec_6,'
                       'temp_1,temp_2,temp_3,temp_4,temp_5,temp_6')
     for name, fname in zip((name1, name2), (n1, n2)):
-        grass.run_command('t.create', overwrite=True, type='strds',
-                          temporaltype='absolute', output=name,
-                          title="A test with input files", descr="A test with input files")
-        grass.run_command('t.register', flags='i', input=name, file=fname, overwrite=True)
+        grass.run_command(
+            't.create',
+            overwrite=True,
+            type='strds',
+            temporaltype='absolute',
+            output=name,
+            title="A test with input files",
+            descr="A test with input files")
+        grass.run_command(
+            't.register',
+            flags='i',
+            input=name,
+            file=fname,
+            overwrite=True)
 
     return name1, name2
 
 
 def createRelativeInterval():
-    grass.run_command('g.region', s=0, n=80, w=0, e=120, b=0, t=50, res=10, res3=10,
-                      flags='p3', quiet=True)
+    grass.run_command(
+        'g.region',
+        s=0,
+        n=80,
+        w=0,
+        e=120,
+        b=0,
+        t=50,
+        res=10,
+        res3=10,
+        flags='p3',
+        quiet=True)
 
     grass.mapcalc(exp="prec_1 = rand(0, 550)", overwrite=True)
     grass.mapcalc(exp="prec_2 = rand(0, 450)", overwrite=True)
@@ -469,16 +516,37 @@
                       maps='prec_1,prec_2,prec_3,prec_4,prec_5,prec_6,'
                       'temp_1,temp_2,temp_3,temp_4,temp_5,temp_6')
     for name, fname in zip((name1, name2), (n1, n2)):
-        grass.run_command('t.create', overwrite=True, type='strds',
-                          temporaltype='relative', output=name,
-                          title="A test with input files", descr="A test with input files")
-        grass.run_command('t.register', flags='i', input=name, file=fname, unit="years", overwrite=True)
+        grass.run_command(
+            't.create',
+            overwrite=True,
+            type='strds',
+            temporaltype='relative',
+            output=name,
+            title="A test with input files",
+            descr="A test with input files")
+        grass.run_command(
+            't.register',
+            flags='i',
+            input=name,
+            file=fname,
+            unit="years",
+            overwrite=True)
     return name1, name2
 
 
 def createAbsolutePoint():
-    grass.run_command('g.region', s=0, n=80, w=0, e=120, b=0, t=50, res=10, res3=10,
-                      flags='p3', quiet=True)
+    grass.run_command(
+        'g.region',
+        s=0,
+        n=80,
+        w=0,
+        e=120,
+        b=0,
+        t=50,
+        res=10,
+        res3=10,
+        flags='p3',
+        quiet=True)
 
     grass.mapcalc(exp="prec_1 = rand(0, 550)", overwrite=True)
     grass.mapcalc(exp="prec_2 = rand(0, 450)", overwrite=True)
@@ -499,17 +567,37 @@
     )
     fd.close()
     name = 'abspoint'
-    grass.run_command('t.create', overwrite=True, type='strds',
-                      temporaltype='absolute', output=name,
-                      title="A test with input files", descr="A test with input files")
+    grass.run_command(
+        't.create',
+        overwrite=True,
+        type='strds',
+        temporaltype='absolute',
+        output=name,
+        title="A test with input files",
+        descr="A test with input files")
 
-    grass.run_command('t.register', flags='i', input=name, file=n1, overwrite=True)
+    grass.run_command(
+        't.register',
+        flags='i',
+        input=name,
+        file=n1,
+        overwrite=True)
     return name
 
 
 def createRelativePoint():
-    grass.run_command('g.region', s=0, n=80, w=0, e=120, b=0, t=50, res=10, res3=10,
-                      flags='p3', quiet=True)
+    grass.run_command(
+        'g.region',
+        s=0,
+        n=80,
+        w=0,
+        e=120,
+        b=0,
+        t=50,
+        res=10,
+        res3=10,
+        flags='p3',
+        quiet=True)
 
     grass.mapcalc(exp="prec_1 = rand(0, 550)", overwrite=True)
     grass.mapcalc(exp="prec_2 = rand(0, 450)", overwrite=True)
@@ -530,11 +618,21 @@
     )
     fd.close()
     name = 'relpoint'
-    grass.run_command('t.create', overwrite=True, type='strds',
-                      temporaltype='relative', output=name,
-                      title="A test with input files", descr="A test with input files")
+    grass.run_command(
+        't.create',
+        overwrite=True,
+        type='strds',
+        temporaltype='relative',
+        output=name,
+        title="A test with input files",
+        descr="A test with input files")
 
-    grass.run_command('t.register', unit="day", input=name, file=n1, overwrite=True)
+    grass.run_command(
+        't.register',
+        unit="day",
+        input=name,
+        file=n1,
+        overwrite=True)
     return name
 
 if __name__ == '__main__':

Modified: grass/trunk/gui/wxpython/animation/toolbars.py
===================================================================
--- grass/trunk/gui/wxpython/animation/toolbars.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/toolbars.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -25,35 +25,55 @@
 from animation.anim import ReplayMode
 
 ganimIcons = {
-    'speed': MetaIcon(img='move', label=_("Change animation speed")),
-    'playForward': MetaIcon(img='execute', label=_("Play forward")),
-    'playBack': MetaIcon(img='player-back', label=_("Play back")),
-    'stop': MetaIcon(img='player-stop', label=_("Stop")),
-    'pause': MetaIcon(img='player-pause', label=_("Pause")),
-    'oneDirectionReplay': MetaIcon(img='redraw', label=_("Repeat")),
-    'bothDirectionReplay': MetaIcon(img='player-repeat-back-forward',
-                                    label=_("Play back and forward")),
-    'addAnimation': MetaIcon(img='layer-add', label=_("Add new animation"),
-                             desc=_("Add new animation")),
-    'editAnimation': MetaIcon(img='layer-more', label=_("Add, edit or remove animation"),
-                              desc=_("Add, edit or remove animation")),
-    'exportAnimation': MetaIcon(img='layer-export', label=_("Export animation"),
-                                desc=_("Export animation"))
-}
+    'speed': MetaIcon(
+        img='move',
+        label=_("Change animation speed")),
+    'playForward': MetaIcon(
+        img='execute',
+        label=_("Play forward")),
+    'playBack': MetaIcon(
+        img='player-back',
+        label=_("Play back")),
+    'stop': MetaIcon(
+        img='player-stop',
+        label=_("Stop")),
+    'pause': MetaIcon(
+        img='player-pause',
+        label=_("Pause")),
+    'oneDirectionReplay': MetaIcon(
+        img='redraw',
+        label=_("Repeat")),
+    'bothDirectionReplay': MetaIcon(
+        img='player-repeat-back-forward',
+        label=_("Play back and forward")),
+    'addAnimation': MetaIcon(
+        img='layer-add',
+        label=_("Add new animation"),
+        desc=_("Add new animation")),
+    'editAnimation': MetaIcon(
+        img='layer-more',
+        label=_("Add, edit or remove animation"),
+        desc=_("Add, edit or remove animation")),
+    'exportAnimation': MetaIcon(
+        img='layer-export',
+        label=_("Export animation"),
+        desc=_("Export animation"))}
 
 SIMPLE_LMGR_STDS = 256
 
 
 simpleLmgrIcons = {
-    'addSeries': MetaIcon(img='mapset-add',
-                          label=_("Add space-time dataset or series of map layers"),
-                          desc=_("Add space-time dataset or series of map layers for animation")),
+    'addSeries': MetaIcon(
+        img='mapset-add',
+        label=_("Add space-time dataset or series of map layers"),
+        desc=_("Add space-time dataset or series of map layers for animation")),
 }
 
 
 class MainToolbar(BaseToolbar):
     """Main toolbar (data management)
     """
+
     def __init__(self, parent):
         """Main toolbar constructor
         """
@@ -69,20 +89,21 @@
         # BaseIcons are a set of often used icons. It is possible
         # to reuse icons in ./trunk/gui/icons/grass or add new ones there.
         icons = ganimIcons
-        return self._getToolbarData((("addAnimation", icons["addAnimation"],
-                                      self.parent.OnAddAnimation),
-                                     ("editAnimation", icons["editAnimation"],
-                                      self.parent.OnEditAnimation),
-                                     ("reload", BaseIcons["render"],
-                                      self.parent.Reload),
-                                     ("exportAnimation", icons["exportAnimation"],
-                                      self.parent.OnExportAnimation)
-                                     ))
+        return self._getToolbarData(
+            (("addAnimation", icons["addAnimation"],
+              self.parent.OnAddAnimation),
+             ("editAnimation", icons["editAnimation"],
+              self.parent.OnEditAnimation),
+             ("reload", BaseIcons["render"],
+              self.parent.Reload),
+             ("exportAnimation", icons["exportAnimation"],
+              self.parent.OnExportAnimation)))
 
 
 class AnimationToolbar(BaseToolbar):
     """Animation toolbar (to control animation)
     """
+
     def __init__(self, parent):
         """Animation toolbar constructor
         """
@@ -101,26 +122,23 @@
         # BaseIcons are a set of often used icons. It is possible
         # to reuse icons in ./trunk/gui/icons/grass or add new ones there.
         icons = ganimIcons
-        return self._getToolbarData((("playBack", icons["playBack"],
-                                      self.OnPlayBack),
-                                     ("playForward", icons["playForward"],
-                                      self.OnPlayForward),
-                                     ("pause", icons["pause"],
-                                      self.OnPause,
-                                      wx.ITEM_CHECK),
-                                     ("stop", icons["stop"],
-                                      self.OnStop),
-                                     (None, ),
-                                     ("oneDirectionReplay", icons["oneDirectionReplay"],
-                                      self.OnOneDirectionReplay,
-                                      wx.ITEM_CHECK),
-                                     ("bothDirectionReplay", icons["bothDirectionReplay"],
-                                      self.OnBothDirectionReplay,
-                                      wx.ITEM_CHECK),
-                                     (None, ),
-                                     ("adjustSpeed", icons['speed'],
-                                      self.parent.OnAdjustSpeed)
-                                     ))
+        return self._getToolbarData(
+            (("playBack", icons["playBack"],
+              self.OnPlayBack),
+             ("playForward", icons["playForward"],
+              self.OnPlayForward),
+             ("pause", icons["pause"],
+              self.OnPause, wx.ITEM_CHECK),
+             ("stop", icons["stop"],
+              self.OnStop),
+             (None,),
+             ("oneDirectionReplay", icons["oneDirectionReplay"],
+              self.OnOneDirectionReplay, wx.ITEM_CHECK),
+             ("bothDirectionReplay", icons["bothDirectionReplay"],
+              self.OnBothDirectionReplay, wx.ITEM_CHECK),
+             (None,),
+             ("adjustSpeed", icons['speed'],
+              self.parent.OnAdjustSpeed)))
 
     def OnPlayForward(self, event):
         self.PlayForward()
@@ -171,7 +189,8 @@
 
         # if not self.GetToolState(self.oneDirectionReplay) and \
         #    not self.GetToolState(self.bothDirectionReplay):
-        #     self.EnableTool(self.playBack, False) # assuming that stop rewinds to the beginning
+        # self.EnableTool(self.playBack, False) # assuming that stop rewinds to
+        # the beginning
 
     def OnOneDirectionReplay(self, event):
         if event.IsChecked():
@@ -204,6 +223,7 @@
 class MiscToolbar(BaseToolbar):
     """Toolbar with miscellaneous tools related to app
     """
+
     def __init__(self, parent):
         """Toolbar constructor
         """
@@ -228,6 +248,7 @@
     """Simple layer manager toolbar for animation tool.
     Allows adding space-time dataset or series of maps.
     """
+
     def __init__(self, parent, lmgrStyle):
         SimpleLmgrToolbar.__init__(self, parent, lmgrStyle)
 

Modified: grass/trunk/gui/wxpython/animation/utils.py
===================================================================
--- grass/trunk/gui/wxpython/animation/utils.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/utils.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -66,7 +66,9 @@
         if nameShort in trastDict[mapset]:
             return timeseries
         else:
-            raise GException(_("Space time dataset <%s> not found.") % timeseries)
+            raise GException(
+                _("Space time dataset <%s> not found.") %
+                timeseries)
 
     mapsets = tgis.get_tgis_c_library_interface().available_mapsets()
     for mapset in mapsets:
@@ -200,7 +202,8 @@
             raise GException(_("The number of maps to animate has to be "
                                "the same for each map series."))
 
-        if timeseriesList and list(count)[0] != list(timeseriesInfo['count'])[0]:
+        if timeseriesList and list(count)[0] != list(
+                timeseriesInfo['count'])[0]:
             raise GException(_("The number of maps to animate has to be "
                                "the same as the number of maps in temporal dataset."))
 
@@ -260,7 +263,13 @@
 def WxImageToPil(image):
     """Converts wx.Image to PIL image"""
     pilImage = Image.new('RGB', (image.GetWidth(), image.GetHeight()))
-    getattr(pilImage, "frombytes", getattr(pilImage, "fromstring"))(image.GetData())
+    getattr(
+        pilImage,
+        "frombytes",
+        getattr(
+            pilImage,
+            "fromstring"))(
+        image.GetData())
     return pilImage
 
 
@@ -318,9 +327,12 @@
                         if mapLayer:
                             try:
                                 idx = cmd.index('layer')
-                                cmd[idx] = 'layer={layer}'.format(layer=mapLayer)
+                                cmd[idx] = 'layer={layer}'.format(
+                                    layer=mapLayer)
                             except ValueError:
-                                cmd.append('layer={layer}'.format(layer=mapLayer))
+                                cmd.append(
+                                    'layer={layer}'.format(
+                                        layer=mapLayer))
                         cmds.append(cmd[:])
                     cmdsForComposition.append(cmds)
         else:

Modified: grass/trunk/gui/wxpython/core/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/core/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -13,4 +13,4 @@
     'utils',
     'globalvar',
     'giface',
-    ]
+]

Modified: grass/trunk/gui/wxpython/core/debug.py
===================================================================
--- grass/trunk/gui/wxpython/core/debug.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/debug.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -10,7 +10,7 @@
 from core.debug import Debug
 Debug.msg (3, 'debug message')
 @endcode
-         
+
 (C) 2007-2009, 2011 by the GRASS Development Team
 
 This program is free software under the GNU General Public License
@@ -24,16 +24,18 @@
 
 import grass.script as grass
 
+
 class DebugMsg:
     """wxGUI debugging
-    
+
         g.gisenv set=WX_DEBUG=[0-5]
 
     """
+
     def __init__(self):
         # default level
         self.debuglevel = 0
-        
+
         self.SetLevel()
 
     def SetLevel(self):
@@ -42,11 +44,14 @@
         try:
             self.debuglevel = int(grass.gisenv().get('WX_DEBUG', 0))
             if self.debuglevel < 0 or self.debuglevel > 5:
-                raise ValueError(_("Wx debug level {}.").format(self.debuglevel))
+                raise ValueError(
+                    _("Wx debug level {}.").format(
+                        self.debuglevel))
         except ValueError as e:
             self.debuglevel = 0
-            sys.stderr.write(_("WARNING: Ignoring unsupported wx debug level (must be >=0 and <=5). {}\n").format(e))
-        
+            sys.stderr.write(
+                _("WARNING: Ignoring unsupported wx debug level (must be >=0 and <=5). {}\n").format(e))
+
     def msg(self, level, message, *args):
         """Print debug message
 
@@ -57,13 +62,13 @@
         # self.SetLevel()
         if self.debuglevel > 0 and level > 0 and level <= self.debuglevel:
             if args:
-                sys.stderr.write("GUI D%d/%d: " % (level, self.debuglevel) + \
-                    message % args + os.linesep)
+                sys.stderr.write("GUI D%d/%d: " % (level, self.debuglevel) +
+                                 message % args + os.linesep)
             else:
-                sys.stderr.write("GUI D%d/%d: " % (level, self.debuglevel) + \
-                                     message + os.linesep)
-            sys.stderr.flush() # force flush (required for MS Windows)
-        
+                sys.stderr.write("GUI D%d/%d: " % (level, self.debuglevel) +
+                                 message + os.linesep)
+            sys.stderr.flush()  # force flush (required for MS Windows)
+
     def GetLevel(self):
         """Return current GUI debug level"""
         return self.debuglevel

Modified: grass/trunk/gui/wxpython/core/gcmd.py
===================================================================
--- grass/trunk/gui/wxpython/core/gcmd.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/gcmd.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -46,14 +46,18 @@
 
 from grass.script import core as grass
 
-from core       import globalvar
+from core import globalvar
 from core.debug import Debug
 
 # cannot import from the core.utils module to avoid cross dependencies
 try:
     # intended to be used also outside this module
     import gettext
-    _ = gettext.translation('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale')).ugettext
+    _ = gettext.translation(
+        'grasswxpy',
+        os.path.join(
+            os.getenv("GISBASE"),
+            'locale')).ugettext
 except IOError:
     # using no translation silently
     def null_gettext(string):
@@ -63,38 +67,41 @@
 
 def DecodeString(string):
     """Decode string using system encoding
-    
+
     :param string: string to be decoded
-    
+
     :return: decoded string
     """
     if not string:
         return string
-    
+
     if _enc:
         Debug.msg(5, "DecodeString(): enc=%s" % _enc)
         return string.decode(_enc)
-    
+
     return string
 
+
 def EncodeString(string):
     """Return encoded string using system locales
-    
+
     :param string: string to be encoded
-    
+
     :return: encoded string
     """
     if not string:
         return string
-    
+
     if _enc:
         Debug.msg(5, "EncodeString(): enc=%s" % _enc)
         return string.encode(_enc)
-    
+
     return string
 
+
 class GError:
-    def __init__(self, message, parent = None, caption = None, showTraceback = True):
+
+    def __init__(self, message, parent=None, caption=None, showTraceback=True):
         """Show error message window
 
         :param message: error message
@@ -109,43 +116,49 @@
         if exc_traceback:
             exception = traceback.format_exc()
             reason = exception.splitlines()[-1].split(':', 1)[-1].strip()
-        
+
         if Debug.GetLevel() > 0 and exc_traceback:
             sys.stderr.write(exception)
-        
+
         if showTraceback and exc_traceback:
-            wx.MessageBox(parent = parent,
-                          message = message + '\n\n%s: %s\n\n%s' % \
-                              (_('Reason'),
-                               reason, exception),
-                          caption = caption,
-                          style = style)
+            wx.MessageBox(parent=parent,
+                          message=message + '\n\n%s: %s\n\n%s' %
+                          (_('Reason'),
+                           reason, exception),
+                          caption=caption,
+                          style=style)
         else:
-            wx.MessageBox(parent = parent,
-                          message = message,
-                          caption = caption,
-                          style = style)
+            wx.MessageBox(parent=parent,
+                          message=message,
+                          caption=caption,
+                          style=style)
 
+
 class GWarning:
-    def __init__(self, message, parent = None):
+
+    def __init__(self, message, parent=None):
         caption = _('Warning')
         style = wx.OK | wx.ICON_WARNING | wx.CENTRE
-        wx.MessageBox(parent = parent,
-                      message = message,
-                      caption = caption,
-                      style = style)
-        
+        wx.MessageBox(parent=parent,
+                      message=message,
+                      caption=caption,
+                      style=style)
+
+
 class GMessage:
-    def __init__(self, message, parent = None):
+
+    def __init__(self, message, parent=None):
         caption = _('Message')
         style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE
-        wx.MessageBox(parent = parent,
-                      message = message,
-                      caption = caption,
-                      style = style)
+        wx.MessageBox(parent=parent,
+                      message=message,
+                      caption=caption,
+                      style=style)
 
+
 class GException(Exception):
-    def __init__(self, value = ''):
+
+    def __init__(self, value=''):
         self.value = value
 
     def __str__(self):
@@ -154,8 +167,10 @@
     def __unicode__(self):
         return self.value
 
+
 class Popen(subprocess.Popen):
     """Subclass subprocess.Popen"""
+
     def __init__(self, args, **kwargs):
         if subprocess.mswindows:
             args = map(EncodeString, args)
@@ -190,14 +205,14 @@
                             args[i] = k + v
 
         subprocess.Popen.__init__(self, args, **kwargs)
-        
-    def recv(self, maxsize = None):
+
+    def recv(self, maxsize=None):
         return self._recv('stdout', maxsize)
-    
-    def recv_err(self, maxsize = None):
+
+    def recv_err(self, maxsize=None):
         return self._recv('stderr', maxsize)
 
-    def send_recv(self, input = '', maxsize = None):
+    def send_recv(self, input='', maxsize=None):
         return self.send(input), self.recv(maxsize), self.recv_err(maxsize)
 
     def get_conn_maxsize(self, which, maxsize):
@@ -206,7 +221,7 @@
         elif maxsize < 1:
             maxsize = 1
         return getattr(self, which), maxsize
-    
+
     def _close(self, which):
         getattr(self, which).close()
         setattr(self, which, None)
@@ -219,7 +234,7 @@
             return (0 != win32api.TerminateProcess(handle, 0))
         else:
             try:
-                os.kill(-self.pid, signal.SIGTERM) # kill whole group
+                os.kill(-self.pid, signal.SIGTERM)  # kill whole group
             except OSError:
                 pass
 
@@ -244,7 +259,7 @@
             conn, maxsize = self.get_conn_maxsize(which, maxsize)
             if conn is None:
                 return None
-            
+
             try:
                 x = msvcrt.get_osfhandle(conn.fileno())
                 (read, nAvail, nMessage) = PeekNamedPipe(x, 0)
@@ -258,7 +273,7 @@
                 if why[0] in (109, errno.ESHUTDOWN):
                     return self._close(which)
                 raise
-            
+
             if self.universal_newlines:
                 read = self._translate_newlines(read)
             return read
@@ -274,7 +289,7 @@
             try:
                 written = os.write(self.stdin.fileno(), input)
             except OSError as why:
-                if why[0] == errno.EPIPE: #broken pipe
+                if why[0] == errno.EPIPE:  # broken pipe
                     return self._close('stdin')
                 raise
 
@@ -284,20 +299,20 @@
             conn, maxsize = self.get_conn_maxsize(which, maxsize)
             if conn is None:
                 return None
-            
+
             flags = fcntl.fcntl(conn, fcntl.F_GETFL)
             if not conn.closed:
-                fcntl.fcntl(conn, fcntl.F_SETFL, flags| os.O_NONBLOCK)
-            
+                fcntl.fcntl(conn, fcntl.F_SETFL, flags | os.O_NONBLOCK)
+
             try:
                 if not select.select([conn], [], [], 0)[0]:
                     return ''
-                
+
                 r = conn.read(maxsize)
-                
+
                 if not r:
                     return self._close(which)
-    
+
                 if self.universal_newlines:
                     r = self._translate_newlines(r)
                 return r
@@ -307,10 +322,11 @@
 
 message = "Other end disconnected!"
 
-def recv_some(p, t = .1, e = 1, tr = 5, stderr = 0):
+
+def recv_some(p, t=.1, e=1, tr=5, stderr=0):
     if tr < 1:
         tr = 1
-    x = time.time()+t
+    x = time.time() + t
     y = []
     r = ''
     pr = p.recv
@@ -326,9 +342,10 @@
         elif r:
             y.append(r)
         else:
-            time.sleep(max((x-time.time())/tr, 0))
+            time.sleep(max((x - time.time()) / tr, 0))
     return ''.join(y)
-    
+
+
 def send_all(p, data):
     while len(data):
         sent = p.send(data)
@@ -336,6 +353,7 @@
             raise Exception(message)
         data = buffer(data, sent)
 
+
 class Command:
     """Run command in separate thread. Used for commands launched
     on the background.
@@ -352,9 +370,10 @@
         else:
             print 'FAILURE (%d)' % cmd.returncode
     """
-    def __init__ (self, cmd, stdin = None,
-                  verbose = None, wait = True, rerr = False,
-                  stdout = None, stderr = None):
+
+    def __init__(self, cmd, stdin=None,
+                 verbose=None, wait=True, rerr=False,
+                 stdout=None, stderr=None):
         """
         :param cmd: command given as list
         :param stdin: standard input stream
@@ -391,7 +410,7 @@
         self.cmdThread = CommandThread(cmd, stdin,
                                        stdout, stderr)
         self.cmdThread.start()
-        
+
         if wait:
             self.cmdThread.join()
             if self.cmdThread.module:
@@ -404,33 +423,39 @@
             self.returncode = None
 
         if self.returncode is not None:
-            Debug.msg (3, "Command(): cmd='%s', wait=%s, returncode=%d, alive=%s" % \
-                           (' '.join(cmd), wait, self.returncode, self.cmdThread.isAlive()))
+            Debug.msg(
+                3, "Command(): cmd='%s', wait=%s, returncode=%d, alive=%s" %
+                (' '.join(cmd), wait, self.returncode, self.cmdThread.isAlive()))
             if rerr is not None and self.returncode != 0:
-                if rerr is False: # GUI dialog
-                    raise GException("%s '%s'%s%s%s %s%s" % \
-                                         (_("Execution failed:"),
-                                          ' '.join(self.cmd),
-                                          os.linesep, os.linesep,
-                                          _("Details:"),
-                                          os.linesep,
-                                          _("Error: ") + self.__GetError()))
-                elif rerr == sys.stderr: # redirect message to sys
-                    stderr.write("Execution failed: '%s'" % (' '.join(self.cmd)))
-                    stderr.write("%sDetails:%s%s" % (os.linesep,
-                                                     _("Error: ") + self.__GetError(),
-                                                     os.linesep))
+                if rerr is False:  # GUI dialog
+                    raise GException("%s '%s'%s%s%s %s%s" %
+                                     (_("Execution failed:"),
+                                      ' '.join(self.cmd),
+                                      os.linesep, os.linesep,
+                                      _("Details:"),
+                                      os.linesep,
+                                      _("Error: ") + self.__GetError()))
+                elif rerr == sys.stderr:  # redirect message to sys
+                    stderr.write("Execution failed: '%s'" %
+                                 (' '.join(self.cmd)))
+                    stderr.write(
+                        "%sDetails:%s%s" %
+                        (os.linesep,
+                         _("Error: ") +
+                            self.__GetError(),
+                            os.linesep))
             else:
-                pass # nop
+                pass  # nop
         else:
-            Debug.msg (3, "Command(): cmd='%s', wait=%s, returncode=?, alive=%s" % \
-                           (' '.join(cmd), wait, self.cmdThread.isAlive()))
+            Debug.msg(
+                3, "Command(): cmd='%s', wait=%s, returncode=?, alive=%s" %
+                (' '.join(cmd), wait, self.cmdThread.isAlive()))
 
         if verbose_orig:
             os.environ["GRASS_VERBOSE"] = verbose_orig
         elif "GRASS_VERBOSE" in os.environ:
             del os.environ["GRASS_VERBOSE"]
-            
+
     def __ReadOutput(self, stream):
         """Read stream and return list of lines
 
@@ -449,7 +474,7 @@
             lineList.append(line)
 
         return lineList
-                    
+
     def __ReadErrOutput(self):
         """Read standard error output and return list of lines"""
         return self.__ReadOutput(self.cmdThread.module.stderr)
@@ -465,27 +490,27 @@
         else:
             lines = self.cmdThread.error.strip('%s' % os.linesep). \
                 split('%s' % os.linesep)
-        
+
         msg = []
 
-        type    = None
+        type = None
         content = ""
         for line in lines:
             if len(line) == 0:
                 continue
-            if 'GRASS_' in line: # error or warning
-                if 'GRASS_INFO_WARNING' in line: # warning
+            if 'GRASS_' in line:  # error or warning
+                if 'GRASS_INFO_WARNING' in line:  # warning
                     type = "WARNING"
-                elif 'GRASS_INFO_ERROR' in line: # error
+                elif 'GRASS_INFO_ERROR' in line:  # error
                     type = "ERROR"
-                elif 'GRASS_INFO_END': # end of message
+                elif 'GRASS_INFO_END':  # end of message
                     msg.append((type, content))
                     type = None
                     content = ""
-                
+
                 if type:
                     content += line.split(':', 1)[1].strip()
-            else: # stderr
+            else:  # stderr
                 msg.append((None, line.strip()))
 
         return msg
@@ -494,53 +519,55 @@
         """Get error message or ''"""
         if not self.cmdThread.module:
             return _("Unable to exectute command: '%s'") % ' '.join(self.cmd)
-        
+
         for type, msg in self.__ProcessStdErr():
             if type == 'ERROR':
                 if _enc:
                     return unicode(msg, _enc)
                 return msg
-        
+
         return ''
-    
+
+
 class CommandThread(Thread):
     """Create separate thread for command. Used for commands launched
     on the background."""
-    def __init__ (self, cmd, env = None, stdin = None,
-                  stdout = sys.stdout, stderr = sys.stderr):
+
+    def __init__(self, cmd, env=None, stdin=None,
+                 stdout=sys.stdout, stderr=sys.stderr):
         """
         :param cmd: command (given as list)
         :param env: environmental variables
-        :param stdin: standard input stream 
+        :param stdin: standard input stream
         :param stdout: redirect standard output or None
         :param stderr: redirect standard error output or None
         """
         Thread.__init__(self)
-        
-        self.cmd    = cmd
-        self.stdin  = stdin
+
+        self.cmd = cmd
+        self.stdin = stdin
         self.stdout = stdout
         self.stderr = stderr
-        self.env    = env
-        
+        self.env = env
+
         self.module = None
-        self.error  = ''
-        
+        self.error = ''
+
         self._want_abort = False
         self.aborted = False
-        
+
         self.setDaemon(True)
-        
+
         # set message formatting
         self.message_format = os.getenv("GRASS_MESSAGE_FORMAT")
         os.environ["GRASS_MESSAGE_FORMAT"] = "gui"
-        
+
     def __del__(self):
         if self.message_format:
             os.environ["GRASS_MESSAGE_FORMAT"] = self.message_format
         else:
             del os.environ["GRASS_MESSAGE_FORMAT"]
-        
+
     def run(self):
         """Run command"""
         if len(self.cmd) == 0:
@@ -565,27 +592,27 @@
             args[0] = grass.get_real_command(args[0])
             if args[0].endswith('.py'):
                 args.insert(0, sys.executable)
- 
+
         try:
             self.module = Popen(args,
-                                stdin = subprocess.PIPE,
-                                stdout = subprocess.PIPE,
-                                stderr = subprocess.PIPE,
-                                shell = sys.platform == "win32",
-                                env = self.env)
-            
+                                stdin=subprocess.PIPE,
+                                stdout=subprocess.PIPE,
+                                stderr=subprocess.PIPE,
+                                shell=sys.platform == "win32",
+                                env=self.env)
+
         except OSError as e:
             self.error = str(e)
             print >> sys.stderr, e
             return 1
-        
-        if self.stdin: # read stdin if requested ...
+
+        if self.stdin:  # read stdin if requested ...
             self.module.stdin.write(self.stdin)
             self.module.stdin.close()
-            
+
         # redirect standard outputs...
         self._redirect_stream()
-        
+
     def _redirect_stream(self):
         """Redirect stream"""
         if self.stdout:
@@ -593,44 +620,45 @@
             out_fileno = self.module.stdout.fileno()
             if not subprocess.mswindows:
                 flags = fcntl.fcntl(out_fileno, fcntl.F_GETFL)
-                fcntl.fcntl(out_fileno, fcntl.F_SETFL, flags| os.O_NONBLOCK)
-                
+                fcntl.fcntl(out_fileno, fcntl.F_SETFL, flags | os.O_NONBLOCK)
+
         if self.stderr:
             # make module stdout/stderr non-blocking
             out_fileno = self.module.stderr.fileno()
             if not subprocess.mswindows:
                 flags = fcntl.fcntl(out_fileno, fcntl.F_GETFL)
-                fcntl.fcntl(out_fileno, fcntl.F_SETFL, flags| os.O_NONBLOCK)
-        
+                fcntl.fcntl(out_fileno, fcntl.F_SETFL, flags | os.O_NONBLOCK)
+
         # wait for the process to end, sucking in stuff until it does end
         while self.module.poll() is None:
-            if self._want_abort: # abort running process
+            if self._want_abort:  # abort running process
                 self.module.terminate()
                 self.aborted = True
-                return 
+                return
             if self.stdout:
-                line = recv_some(self.module, e = 0, stderr = 0)
+                line = recv_some(self.module, e=0, stderr=0)
                 self.stdout.write(line)
             if self.stderr:
-                line = recv_some(self.module, e = 0, stderr = 1)
+                line = recv_some(self.module, e=0, stderr=1)
                 self.stderr.write(line)
                 if len(line) > 0:
                     self.error = line
 
         # get the last output
         if self.stdout:
-            line = recv_some(self.module, e = 0, stderr = 0)
+            line = recv_some(self.module, e=0, stderr=0)
             self.stdout.write(line)
         if self.stderr:
-            line = recv_some(self.module, e = 0, stderr = 1)
+            line = recv_some(self.module, e=0, stderr=1)
             self.stderr.write(line)
             if len(line) > 0:
                 self.error = line
-            
+
     def abort(self):
         """Abort running process, used by main thread to signal an abort"""
         self._want_abort = True
-    
+
+
 def _formatMsg(text):
     """Format error messages for dialogs
     """
@@ -648,12 +676,13 @@
             return message
         else:
             message += line.strip() + '\n'
-    
+
     return message
 
-def RunCommand(prog, flags = "", overwrite = False, quiet = False,
-               verbose = False, parent = None, read = False,
-               parse = None, stdin = None, getErrorMsg = False, **kwargs):
+
+def RunCommand(prog, flags="", overwrite=False, quiet=False,
+               verbose=False, parent=None, read=False,
+               parse=None, stdin=None, getErrorMsg=False, **kwargs):
     """Run GRASS command
 
     :param prog: program to run
@@ -665,7 +694,7 @@
     :param stdin: stdin or None
     :param getErrorMsg: get error messages on failure
     :param kwargs: program parameters
-    
+
     :return: returncode (read == False and getErrorMsg == False)
     :return: returncode, messages (read == False and getErrorMsg == True)
     :return: stdout (read == True and getErrorMsg == False)
@@ -674,50 +703,50 @@
     """
     cmdString = ' '.join(grass.make_command(prog, flags, overwrite,
                                             quiet, verbose, **kwargs))
-    
+
     Debug.msg(1, "gcmd.RunCommand(): %s" % cmdString)
-    
+
     kwargs['stderr'] = subprocess.PIPE
-    
+
     if read:
         kwargs['stdout'] = subprocess.PIPE
-    
+
     if stdin:
         kwargs['stdin'] = subprocess.PIPE
 
     if parent:
         messageFormat = os.getenv('GRASS_MESSAGE_FORMAT', 'gui')
         os.environ['GRASS_MESSAGE_FORMAT'] = 'standard'
-    
+
     start = time.time()
-    
+
     ps = grass.start_command(prog, flags, overwrite, quiet, verbose, **kwargs)
-    
+
     if stdin:
         ps.stdin.write(stdin)
         ps.stdin.close()
         ps.stdin = None
-    
+
     stdout, stderr = map(DecodeString, ps.communicate())
-    
-    if parent: # restore previous settings
+
+    if parent:  # restore previous settings
         os.environ['GRASS_MESSAGE_FORMAT'] = messageFormat
-    
+
     ret = ps.returncode
-    Debug.msg(1, "gcmd.RunCommand(): get return code %d (%.6f sec)" % \
-                  (ret, (time.time() - start)))
-    
+    Debug.msg(1, "gcmd.RunCommand(): get return code %d (%.6f sec)" %
+              (ret, (time.time() - start)))
+
     if ret != 0:
         if stderr:
             Debug.msg(2, "gcmd.RunCommand(): error %s" % stderr)
         else:
             Debug.msg(2, "gcmd.RunCommand(): nothing to print ???")
-        
+
         if parent:
-            GError(parent = parent,
-                   caption = _("Error in %s") % prog,
-                   message = stderr)
-    
+            GError(parent=parent,
+                   caption=_("Error in %s") % prog,
+                   message=stderr)
+
     if not read:
         if not getErrorMsg:
             return ret
@@ -728,21 +757,22 @@
         Debug.msg(3, "gcmd.RunCommand(): return stdout\n'%s'" % stdout)
     else:
         Debug.msg(3, "gcmd.RunCommand(): return stdout = None")
-    
+
     if parse:
         stdout = parse(stdout)
-    
+
     if not getErrorMsg:
         return stdout
-    
+
     if read and getErrorMsg:
         return ret, stdout, _formatMsg(stderr)
-    
+
     return stdout, _formatMsg(stderr)
 
-def GetDefaultEncoding(forceUTF8 = False):
+
+def GetDefaultEncoding(forceUTF8=False):
     """Get default system encoding
-    
+
     :param bool forceUTF8: force 'UTF-8' if encoding is not defined
 
     :return: system encoding (can be None)
@@ -750,8 +780,8 @@
     enc = locale.getdefaultlocale()[1]
     if forceUTF8 and (enc is None or enc == 'UTF8'):
         return 'UTF-8'
-    
+
     Debug.msg(1, "GetSystemEncoding(): %s" % enc)
     return enc
 
-_enc = GetDefaultEncoding() # define as global variable
+_enc = GetDefaultEncoding()  # define as global variable

Modified: grass/trunk/gui/wxpython/core/gconsole.py
===================================================================
--- grass/trunk/gui/wxpython/core/gconsole.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/gconsole.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -33,7 +33,7 @@
 from wx.lib.newevent import NewEvent
 
 import grass.script as grass
-from   grass.script import task as gtask
+from grass.script import task as gtask
 
 from grass.pydispatch.signal import Signal
 
@@ -116,7 +116,8 @@
         os.environ['GRASS_MESSAGE_FORMAT'] = 'gui'
         while True:
             requestId, args, kwds = self.requestQ.get()
-            for key in ('callable', 'onDone', 'onPrepare', 'userData', 'addLayer', 'notification'):
+            for key in ('callable', 'onDone', 'onPrepare',
+                        'userData', 'addLayer', 'notification'):
                 if key in kwds:
                     vars()[key] = kwds[key]
                     del kwds[key]
@@ -191,7 +192,8 @@
                     argsColor[0] = ['r.colors',
                                     'map=%s' % mapName,
                                     'color=%s' % colorTable]
-                    self.requestCmdColor = vars()['callable'](*argsColor, **kwds)
+                    self.requestCmdColor = vars()['callable'](
+                        *argsColor, **kwds)
                     self.resultQ.put((requestId, self.requestCmdColor.run()))
 
             if self.receiver:
@@ -217,6 +219,7 @@
         if self.requestQ.empty():
             self._want_abort_all = False
 
+
 class GStdout:
     """GConsole standard output
 
@@ -228,6 +231,7 @@
     Copyright: (c) 2005-2007 Jean-Michel Fauth
     Licence:   GPL
     """
+
     def __init__(self, receiver):
         """
         :param receiver: event receiver (used in PostEvent)
@@ -261,6 +265,7 @@
     Copyright: (c) 2005-2007 Jean-Michel Fauth
     Licence:   GPL
     """
+
     def __init__(self, receiver):
         """
         :param receiver: event receiver (used in PostEvent)
@@ -334,6 +339,7 @@
 class GConsole(wx.EvtHandler):
     """
     """
+
     def __init__(self, guiparent=None, giface=None, ignoredCmdPattern=None):
         """
         :param guiparent: parent window for created GUI objects
@@ -404,9 +410,10 @@
         :param notification: form of notification
         """
         self.writeLog.emit(text=text, wrap=wrap,
-                          notification=notification)
+                           notification=notification)
 
-    def WriteCmdLog(self, text, pid=None, notification=Notification.MAKE_VISIBLE):
+    def WriteCmdLog(self, text, pid=None,
+                    notification=Notification.MAKE_VISIBLE):
         """Write message in selected style
 
         :param text: message to be printed
@@ -456,17 +463,17 @@
 
         # update history file
         self.UpdateHistoryFile(' '.join(command))
-        
+
         if command[0] in globalvar.grassCmd:
             # send GRASS command without arguments to GUI command interface
             # except ignored commands (event is emitted)
             if self._ignoredCmdPattern and \
-              re.compile(self._ignoredCmdPattern).search(' '.join(command)) and \
-              '--help' not in command and '--ui' not in command:
+                    re.compile(self._ignoredCmdPattern).search(' '.join(command)) and \
+                    '--help' not in command and '--ui' not in command:
                 event = gIgnoredCmdRun(cmd=command)
                 wx.PostEvent(self, event)
                 return
-            
+
             else:
                 # other GRASS commands (r|v|g|...)
                 try:
@@ -487,11 +494,16 @@
                                 p.get('element', '') == 'file' and \
                                 p.get('age', 'new') == 'old' and \
                                 p.get('value', '') == '-':
-                            GError(parent=self._guiparent,
-                                   message=_("Unable to run command:\n%(cmd)s\n\n"
-                                             "Option <%(opt)s>: read from standard input is not "
-                                             "supported by wxGUI") % {'cmd': ' '.join(command),
-                                                                      'opt': p.get('name', '')})
+                            GError(
+                                parent=self._guiparent,
+                                message=_(
+                                    "Unable to run command:\n%(cmd)s\n\n"
+                                    "Option <%(opt)s>: read from standard input is not "
+                                    "supported by wxGUI") % {
+                                    'cmd': ' '.join(command),
+                                    'opt': p.get(
+                                        'name',
+                                        '')})
                             return
 
                 if len(command) == 1:
@@ -501,27 +513,33 @@
                         pyFile = command[0]
                         if sys.platform == 'win32':
                             pyFile += '.py'
-                        pyPath = os.path.join(os.environ['GISBASE'], 'scripts', pyFile)
+                        pyPath = os.path.join(
+                            os.environ['GISBASE'], 'scripts', pyFile)
                         if not os.path.exists(pyPath):
-                            pyPath = os.path.join(os.environ['GRASS_ADDON_BASE'], 'scripts', pyFile)
+                            pyPath = os.path.join(
+                                os.environ['GRASS_ADDON_BASE'], 'scripts', pyFile)
                         if not os.path.exists(pyPath):
-                            GError(parent=self._guiparent,
-                                   message=_("Module <%s> not found.") % command[0])
-                        pymodule = imp.load_source(command[0].replace('.', '_'), pyPath)
+                            GError(
+                                parent=self._guiparent,
+                                message=_("Module <%s> not found.") %
+                                command[0])
+                        pymodule = imp.load_source(
+                            command[0].replace('.', '_'), pyPath)
                         pymain = inspect.getargspec(pymodule.main)
                         if pymain and 'giface' in pymain.args:
                             pymodule.main(self._giface)
                             return
-                    
+
                     if hasParams and command[0] != 'v.krige':
                         # no arguments given
                         try:
-                            GUI(parent=self._guiparent, giface=self._giface).ParseCommand(command)
+                            GUI(parent=self._guiparent,
+                                giface=self._giface).ParseCommand(command)
                         except GException as e:
                             print >> sys.stderr, e
-                        
+
                         return
-                
+
                 # activate computational region (set with g.region)
                 # for all non-display commands.
                 if compReg:
@@ -539,7 +557,8 @@
                                       notification=notification)
                 self.cmdOutputTimer.Start(50)
 
-                # deactivate computational region and return to display settings
+                # deactivate computational region and return to display
+                # settings
                 if compReg and tmpreg:
                     os.environ["GRASS_REGION"] = tmpreg
         else:
@@ -569,7 +588,7 @@
                     sfile.close()
                 except IOError:
                     pass
-            
+
             if len(command) == 1 and not skipInterface:
                 try:
                     task = gtask.parse_interface(command[0])
@@ -580,7 +599,8 @@
 
             if task:
                 # process GRASS command without argument
-                GUI(parent=self._guiparent, giface=self._giface).ParseCommand(command)
+                GUI(parent=self._guiparent,
+                    giface=self._giface).ParseCommand(command)
             else:
                 self.cmdThread.RunCmd(command,
                                       stdout=self.cmdStdOut,
@@ -631,8 +651,8 @@
                 stime = _("%d sec") % int(ctime)
             else:
                 mtime = int(ctime / 60)
-                stime = _("%(min)d min %(sec)d sec") % {'min': mtime,
-                                                        'sec': int(ctime - (mtime * 60))}
+                stime = _("%(min)d min %(sec)d sec") % {
+                    'min': mtime, 'sec': int(ctime - (mtime * 60))}
         except KeyError:
             # stopped deamon
             stime = _("unknown")
@@ -676,14 +696,17 @@
         name = task.get_name()
         for p in task.get_options()['params']:
             prompt = p.get('prompt', '')
-            if prompt in ('raster', 'vector', 'raster_3d') and p.get('value', None):
-                if p.get('age', 'old') == 'new' or \
-                        name in ('r.colors', 'r3.colors', 'v.colors', 'v.proj', 'r.proj'):
+            if prompt in (
+                    'raster', 'vector', 'raster_3d') and p.get(
+                    'value', None):
+                if p.get('age', 'old') == 'new' or name in (
+                        'r.colors', 'r3.colors', 'v.colors', 'v.proj', 'r.proj'):
                     # if multiple maps (e.g. r.series.interp), we need add each
                     if p.get('multiple', False):
                         lnames = p.get('value').split(',')
                         # in case multiple input (old) maps in r.colors
-                        # we don't want to rerender it multiple times! just once
+                        # we don't want to rerender it multiple times! just
+                        # once
                         if p.get('age', 'old') == 'old':
                             lnames = lnames[0:1]
                     else:
@@ -691,11 +714,13 @@
                     for lname in lnames:
                         if '@' not in lname:
                             lname += '@' + grass.gisenv()['MAPSET']
-                        if grass.find_file(lname, element=p.get('element'))['fullname']:
-                            self.mapCreated.emit(name=lname, ltype=prompt, add=event.addLayer)
+                        if grass.find_file(lname, element=p.get('element'))[
+                                'fullname']:
+                            self.mapCreated.emit(
+                                name=lname, ltype=prompt, add=event.addLayer)
         if name == 'r.mask':
             self.updateMap.emit()
-        
+
         event.Skip()
 
     def OnProcessPendingOutputWindowEvents(self, event):
@@ -703,7 +728,7 @@
 
     def UpdateHistoryFile(self, command):
         """Update history file
-        
+
         :param command: the command given as a string
         """
         env = grass.gisenv()
@@ -714,17 +739,16 @@
                                     '.bash_history')
             fileHistory = codecs.open(filePath, encoding='utf-8', mode='a')
         except IOError as e:
-            GError(_("Unable to write file '%(filePath)s'.\n\nDetails: %(error)s") % 
-                    {'filePath': filePath, 'error': e},
+            GError(_("Unable to write file '%(filePath)s'.\n\nDetails: %(error)s") %
+                   {'filePath': filePath, 'error': e},
                    parent=self._guiparent)
             return
-        
+
         try:
             fileHistory.write(command + os.linesep)
         finally:
             fileHistory.close()
-        
+
         # update wxGUI prompt
         if self._giface:
             self._giface.UpdateCmdHistory(command)
-        

Modified: grass/trunk/gui/wxpython/core/giface.py
===================================================================
--- grass/trunk/gui/wxpython/core/giface.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/giface.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -23,7 +23,7 @@
 from grass.pydispatch.signal import Signal
 
 # to disable Abstract class not referenced
-#pylint: disable=R0921
+# pylint: disable=R0921
 
 
 class Notification:
@@ -51,6 +51,7 @@
 
 
 class LayerList(object):
+
     def GetSelectedLayers(self, checkedOnly=True):
         """Returns list of selected layers.
 
@@ -116,6 +117,7 @@
 
         The GrassInterface process is not finished.
     """
+
     def RunCmd(self, *args, **kwargs):
         """Executes a command.
         """
@@ -131,7 +133,8 @@
         """
         raise NotImplementedError()
 
-    def WriteCmdLog(self, text, pid=None, notification=Notification.MAKE_VISIBLE):
+    def WriteCmdLog(self, text, pid=None,
+                    notification=Notification.MAKE_VISIBLE):
         """Writes message related to start or end of the command.
         """
         raise NotImplementedError()
@@ -202,6 +205,7 @@
 
 class StandaloneGrassInterface():
     """@implements GrassInterface"""
+
     def __init__(self):
 
         # Signal when some map is created or updated by a module.
@@ -242,11 +246,18 @@
         grass.percent(event.value, 100, 1)
         event.Skip()
 
-    def RunCmd(self, command, compReg=True, skipInterface=False,
-               onDone=None, onPrepare=None, userData=None, notification=Notification.MAKE_VISIBLE):
-        self._gconsole.RunCmd(command=command, compReg=compReg,
-                              skipInterface=skipInterface, onDone=onDone,
-                              onPrepare=onPrepare, userData=userData, notification=notification)
+    def RunCmd(
+            self, command, compReg=True, skipInterface=False, onDone=None,
+            onPrepare=None, userData=None,
+            notification=Notification.MAKE_VISIBLE):
+        self._gconsole.RunCmd(
+            command=command,
+            compReg=compReg,
+            skipInterface=skipInterface,
+            onDone=onDone,
+            onPrepare=onPrepare,
+            userData=userData,
+            notification=notification)
 
     def Help(self, entry):
         self._gconsole.RunCmd(['g.manual', 'entry=%s' % entry])
@@ -255,7 +266,8 @@
                  notification=Notification.HIGHLIGHT):
         self._write(grass.message, text)
 
-    def WriteCmdLog(self, text, pid=None, notification=Notification.MAKE_VISIBLE):
+    def WriteCmdLog(self, text, pid=None,
+                    notification=Notification.MAKE_VISIBLE):
         if pid:
             text = '(' + str(pid) + ') ' + text
         self._write(grass.message, text)

Modified: grass/trunk/gui/wxpython/core/globalvar.py
===================================================================
--- grass/trunk/gui/wxpython/core/globalvar.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/globalvar.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -19,12 +19,12 @@
     sys.exit("GRASS is not running. Exiting...")
 
 # path to python scripts
-ETCDIR   = os.path.join(os.getenv("GISBASE"), "etc")
-GUIDIR   = os.path.join(os.getenv("GISBASE"), "gui")
+ETCDIR = os.path.join(os.getenv("GISBASE"), "etc")
+GUIDIR = os.path.join(os.getenv("GISBASE"), "gui")
 WXGUIDIR = os.path.join(GUIDIR, "wxpython")
-ICONDIR  = os.path.join(GUIDIR, "icons")
-IMGDIR   = os.path.join(GUIDIR, "images")
-SYMBDIR  = os.path.join(IMGDIR, "symbols")
+ICONDIR = os.path.join(GUIDIR, "icons")
+IMGDIR = os.path.join(GUIDIR, "images")
+SYMBDIR = os.path.join(IMGDIR, "symbols")
 
 from core.debug import Debug
 
@@ -32,7 +32,11 @@
 try:
     # intended to be used also outside this module
     import gettext
-    _ = gettext.translation('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale')).ugettext
+    _ = gettext.translation(
+        'grasswxpy',
+        os.path.join(
+            os.getenv("GISBASE"),
+            'locale')).ugettext
 except IOError:
     # using no translation silently
     def null_gettext(string):
@@ -41,6 +45,7 @@
 
 from grass.script.core import get_commands
 
+
 def CheckWxVersion(version):
     """Check wx version"""
     ver = wx.__version__
@@ -49,7 +54,8 @@
 
     return True
 
-def CheckForWx(forceVersion = os.getenv('GRASS_WXVERSION', None)):
+
+def CheckForWx(forceVersion=os.getenv('GRASS_WXVERSION', None)):
     """Try to import wx module and check its version
 
     :param forceVersion: force wxPython version, eg. '2.8'
@@ -70,14 +76,16 @@
         version = wx.__version__
 
         if map(int, version.split('.')) < minVersion:
-            raise ValueError('Your wxPython version is %s.%s.%s.%s' % tuple(version.split('.')))
+            raise ValueError(
+                'Your wxPython version is %s.%s.%s.%s' %
+                tuple(version.split('.')))
 
     except ImportError as e:
         print >> sys.stderr, 'ERROR: wxGUI requires wxPython. %s' % str(e)
         sys.exit(1)
     except (ValueError, wxversion.VersionError) as e:
-        print >> sys.stderr, 'ERROR: wxGUI requires wxPython >= %d.%d.%d.%d. ' % tuple(minVersion) + \
-            '%s.' % (str(e))
+        print >> sys.stderr, 'ERROR: wxGUI requires wxPython >= %d.%d.%d.%d. ' % tuple(
+            minVersion) + '%s.' % (str(e))
         sys.exit(1)
     except locale.Error as e:
         print >> sys.stderr, "Unable to set locale:", e
@@ -106,7 +114,7 @@
     FN.FNB_NO_NAV_BUTTONS | \
     FN.FNB_NO_X_BUTTON
 
-FNPageColor = wx.Colour(125,200,175)
+FNPageColor = wx.Colour(125, 200, 175)
 
 """Dialog widget dimension"""
 DIALOG_SPIN_SIZE = (150, -1)
@@ -140,7 +148,7 @@
     BIN_EXT = SCT_EXT = ''
 
 
-def UpdateGRASSAddOnCommands(eList = None):
+def UpdateGRASSAddOnCommands(eList=None):
     """Update list of available GRASS AddOns commands to use when
     parsing string from the command line
 
@@ -155,7 +163,7 @@
         addonPath += os.pathsep + os.path.join(addonBase, 'bin')
         if sys.platform != 'win32':
             addonPath += os.pathsep + os.path.join(addonBase, 'scripts')
-    
+
     # remove commands first
     if eList:
         for ext in eList:
@@ -168,15 +176,15 @@
     for path in addonPath.split(os.pathsep):
         if not os.path.exists(path) or not os.path.isdir(path):
             continue
-        
+
         # check if addon is in the path
         if pathList and path not in pathList:
             os.environ['PATH'] = path + os.pathsep + os.environ['PATH']
-        
+
         for fname in os.listdir(path):
             if fname in ['docs', 'modules.xml']:
                 continue
-            if grassScripts: # win32
+            if grassScripts:  # win32
                 name, ext = os.path.splitext(fname)
                 if name not in grassCmd:
                     if ext not in [BIN_EXT, SCT_EXT]:
@@ -194,7 +202,7 @@
                     grassCmd.add(fname)
                     Debug.msg(3, "AddOn commands: %s", fname)
                     nCmd += 1
-    
+
     Debug.msg(1, "Number of GRASS AddOn commands: %d", nCmd)
 
 """@brief Collected GRASS-relared binaries/scripts"""
@@ -210,4 +218,5 @@
 wxPython3 = CheckWxVersion([3, 0, 0, 0])
 
 """@Add GUIDIR/scripts into path"""
-os.environ['PATH'] = os.path.join(GUIDIR, 'scripts') + os.pathsep + os.environ['PATH']
+os.environ['PATH'] = os.path.join(
+    GUIDIR, 'scripts') + os.pathsep + os.environ['PATH']

Modified: grass/trunk/gui/wxpython/core/gthread.py
===================================================================
--- grass/trunk/gui/wxpython/core/gthread.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/gthread.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -23,6 +23,7 @@
 
 from core.gconsole import EVT_CMD_DONE, wxCmdDone
 
+
 class gThread(threading.Thread, wx.EvtHandler):
     """Thread for various backends"""
     requestId = 0
@@ -65,8 +66,8 @@
         return gThread.requestId
 
     def GetId(self):
-         """Get id for next command"""
-         return gThread.requestId + 1
+        """Get id for next command"""
+        return gThread.requestId + 1
 
     def SetId(self, id):
         """Set starting id"""
@@ -95,14 +96,14 @@
 
             if self.terminate:
                 return
-            #except Exception as e:
+            # except Exception as e:
             #    exception  = e;
 
             self.resultQ.put((requestId, ret))
 
             event = wxCmdDone(ondone=vars()['ondone'],
                               kwds=kwds,
-                              args=args, #TODO expand args to kwds
+                              args=args,  # TODO expand args to kwds
                               ret=ret,
                               exception=exception,
                               userdata=vars()['userdata'],

Modified: grass/trunk/gui/wxpython/core/layerlist.py
===================================================================
--- grass/trunk/gui/wxpython/core/layerlist.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/layerlist.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -27,6 +27,7 @@
     a non GUI class (e.g. named LayerTree) which includes this API,
     should be used for Layer Manager.
     """
+
     def __init__(self):
         self._list = []
 
@@ -179,6 +180,7 @@
         ...
         ValueError: Map <blablabla> not found.
     """
+
     def __init__(self):
         self._mapType = None
         self._name = None
@@ -209,14 +211,20 @@
         """
         if not self.hidden:
             fullName = name.split('@')
-            if len(fullName) == 1 and self._mapType != 'rgb':  # skip checking rgb maps for now
+            if len(
+                    fullName) == 1 and self._mapType != 'rgb':  # skip checking rgb maps for now
                 if self._mapType is None:
-                    raise ValueError("To set layer name, the type of layer must be specified.")
+                    raise ValueError(
+                        "To set layer name, the type of layer must be specified.")
 
-                res = gcore.find_file(name=fullName,
-                                      element=self._internalTypes[self._mapType])
+                res = gcore.find_file(
+                    name=fullName,
+                    element=self._internalTypes[
+                        self._mapType])
                 if not res['mapset']:
-                    raise ValueError("Map <{name}> not found.".format(name=name))
+                    raise ValueError(
+                        "Map <{name}> not found.".format(
+                            name=name))
                 self._name = name + '@' + res['mapset']
             else:
                 self._name = name
@@ -249,7 +257,9 @@
         :param mapType: can be 'raster', 'vector', 'raster_3d'
         """
         if mapType not in self._mapTypes:
-            raise ValueError("Wrong map type used: {mtype}".format(mtype=mapType))
+            raise ValueError(
+                "Wrong map type used: {mtype}".format(
+                    mtype=mapType))
 
         self._mapType = mapType
 
@@ -268,7 +278,9 @@
         :param float opacity: value between 0 and 1
         """
         if not (0 <= opacity <= 1):
-            raise ValueError("Opacity value must be between 0 and 1, not {op}.".format(op=opacity))
+            raise ValueError(
+                "Opacity value must be between 0 and 1, not {op}.".format(
+                    op=opacity))
         self._opacity = opacity
 
     opacity = property(fget=GetOpacity, fset=SetOpacity)
@@ -302,6 +314,7 @@
 
 class LayerListToRendererConverter:
     """Help class for converting LayerList layers into renderer list (Map)"""
+
     def __init__(self, renderer):
         """
 

Modified: grass/trunk/gui/wxpython/core/menutree.py
===================================================================
--- grass/trunk/gui/wxpython/core/menutree.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/menutree.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -37,9 +37,9 @@
 import sys
 import copy
 try:
-    import xml.etree.ElementTree   as etree
+    import xml.etree.ElementTree as etree
 except ImportError:
-    import elementtree.ElementTree as etree # Python <= 2.4
+    import elementtree.ElementTree as etree  # Python <= 2.4
 
 import wx
 
@@ -55,11 +55,12 @@
 # TODO: change the system to remove strange derived classes
 class MenuTreeModelBuilder:
     """Abstract menu data class"""
+
     def __init__(self, filename, expandAddons=True):
 
-        self.menustyle = UserSettings.Get(group = 'appearance',
-                                          key = 'menustyle',
-                                          subkey = 'selection')
+        self.menustyle = UserSettings.Get(group='appearance',
+                                          key='menustyle',
+                                          subkey='selection')
 
         xmlTree = etree.parse(filename)
         if expandAddons:
@@ -89,14 +90,14 @@
             self.model.AppendNode(parent=node, label='', data=data)
         elif item.tag == 'menuitem':
             origLabel = _(item.find('label').text)
-            handler  = item.find('handler').text
-            desc     = item.find('help')  # optional
-            gcmd     = item.find('command')  # optional
-            keywords = item.find('keywords') # optional
-            shortcut = item.find('shortcut') # optional
-            wxId     = item.find('id')       # optional
-            icon     = item.find('icon')     # optional
-            if gcmd != None:
+            handler = item.find('handler').text
+            desc = item.find('help')  # optional
+            gcmd = item.find('command')  # optional
+            keywords = item.find('keywords')  # optional
+            shortcut = item.find('shortcut')  # optional
+            wxId = item.find('id')       # optional
+            icon = item.find('icon')     # optional
+            if gcmd is not None:
                 gcmd = gcmd.text
             else:
                 gcmd = ""
@@ -106,17 +107,17 @@
                 desc = ""
             if keywords is None or keywords.text is None:
                 keywords = ""
-            else:            
+            else:
                 keywords = keywords.text
-            if shortcut != None:
+            if shortcut is not None:
                 shortcut = shortcut.text
             else:
                 shortcut = ""
-            if wxId != None:
+            if wxId is not None:
                 wxId = eval('wx.' + wxId.text)
             else:
                 wxId = wx.ID_ANY
-            if icon != None:
+            if icon is not None:
                 icon = icon.text
             else:
                 icon = ''
@@ -126,8 +127,15 @@
                     label += '   [' + gcmd + ']'
                 elif self.menustyle == 2:
                     label = '      [' + gcmd + ']'
-            data = dict(label=origLabel, description=desc, handler=handler,
-                        command=gcmd, keywords=keywords, shortcut=shortcut, wxId=wxId, icon=icon)
+            data = dict(
+                label=origLabel,
+                description=desc,
+                handler=handler,
+                command=gcmd,
+                keywords=keywords,
+                shortcut=shortcut,
+                wxId=wxId,
+                icon=icon)
             self.model.AppendNode(parent=node, label=label, data=data)
         elif item.tag == 'menu':
             self._createMenu(item, node)
@@ -163,6 +171,7 @@
     def PrintCommands(self, fh):
         printCommands(self.model.root, fh, itemSep=' | ', menuSep=' > ')
 
+
 def removeSeparators(model, node=None):
     if not node:
         node = model.root
@@ -172,6 +181,7 @@
     else:
         model.RemoveNode(node)
 
+
 def printTree(node, fh, indent=0):
     if not node.label:
         return
@@ -180,6 +190,7 @@
     for child in node.children:
         printTree(node=child, fh=fh, indent=indent + 2)
 
+
 def printStrings(node, fh):
     # node.label  - with module in brackets
     # node.data['label'] - without module in brackets
@@ -193,6 +204,7 @@
     for child in node.children:
         printStrings(node=child, fh=fh)
 
+
 def printCommands(node, fh, itemSep, menuSep):
 
     def collectParents(node, parents):
@@ -217,21 +229,22 @@
 if __name__ == "__main__":
 
     action = 'strings'
-    menu   = 'manager'
+    menu = 'manager'
 
     for arg in sys.argv:
         if arg in ('strings', 'tree', 'commands', 'dump'):
-            action =  arg
+            action = arg
         elif arg in ('manager', 'module_tree', 'modeler', 'psmap'):
             menu = arg
 
     # FIXME: cross-dependencies
     if menu == 'manager':
-        from lmgr.menudata     import LayerManagerMenuData
-        from core.globalvar    import WXGUIDIR
+        from lmgr.menudata import LayerManagerMenuData
+        from core.globalvar import WXGUIDIR
         filename = os.path.join(WXGUIDIR, 'xml', 'menudata.xml')
         menudata = LayerManagerMenuData(filename)
-    # FIXME: since module descriptions are used again we have now the third copy of the same string (one is in modules)
+    # FIXME: since module descriptions are used again we have now the third
+    # copy of the same string (one is in modules)
     elif menu == 'module_tree':
         from lmgr.menudata import LayerManagerModuleTree
         from core.globalvar import WXGUIDIR

Modified: grass/trunk/gui/wxpython/core/render.py
===================================================================
--- grass/trunk/gui/wxpython/core/render.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/render.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -38,14 +38,15 @@
 from grass.pydispatch.signal import Signal
 from grass.exceptions import CalledModuleError
 
-from core          import utils
+from core import utils
 from core.utils import _
-from core.ws       import RenderWMSMgr
-from core.gcmd     import GException, GError, RunCommand
-from core.debug    import Debug
+from core.ws import RenderWMSMgr
+from core.gcmd import GException, GError, RunCommand
+from core.debug import Debug
 from core.settings import UserSettings
 from core.gthread import gThread
 
+
 class Layer(object):
     """Virtual class which stores information about layers (map layers and
     overlays) of the map composition.
@@ -53,8 +54,9 @@
     - For map layer use MapLayer class.
     - For overlays use Overlay class.
     """
-    def __init__(self, ltype, cmd, Map, name=None,
-                 active=True, hidden=False, opacity=1.0, mapfile=None, render=True):
+
+    def __init__(self, ltype, cmd, Map, name=None, active=True,
+                 hidden=False, opacity=1.0, mapfile=None, render=True):
         """Create new instance
 
         .. todo::
@@ -79,15 +81,17 @@
             else:
                 tempfile_sfx = ".ppm"
 
-            mapfile = tempfile.NamedTemporaryFile(suffix=tempfile_sfx, delete=False)
+            mapfile = tempfile.NamedTemporaryFile(
+                suffix=tempfile_sfx, delete=False)
             # we don't want it open, we just need the name
             self.mapfile = mapfile.name
             mapfile.close()
-            os.remove(self.mapfile) # remove empty file
-            
-        self.maskfile = self.mapfile.rsplit(".",1)[0] + ".pgm"
-        
-        # stores class which manages rendering instead of simple command - e.g. WMS
+            os.remove(self.mapfile)  # remove empty file
+
+        self.maskfile = self.mapfile.rsplit(".", 1)[0] + ".pgm"
+
+        # stores class which manages rendering instead of simple command - e.g.
+        # WMS
         self.renderMgr = None
 
         self.Map = Map
@@ -102,27 +106,27 @@
         else:
             self.cmd = cmdlist_to_tuple(cmd)
 
-        self.active  = active
-        self.hidden  = hidden
+        self.active = active
+        self.hidden = hidden
         self.opacity = opacity
 
         self.forceRender = render
 
-        Debug.msg (3, "Layer.__init__(): type=%s, cmd='%s', name=%s, " \
-                       "active=%d, opacity=%d, hidden=%d" % \
-                       (self.type, self.GetCmd(string=True), self.name,
-                        self.active, self.opacity, self.hidden))
+        Debug.msg(3, "Layer.__init__(): type=%s, cmd='%s', name=%s, "
+                  "active=%d, opacity=%d, hidden=%d" %
+                  (self.type, self.GetCmd(string=True), self.name,
+                   self.active, self.opacity, self.hidden))
 
     def __del__(self):
-        Debug.msg (3, "Layer.__del__(): layer=%s, cmd='%s'" %
-                   (self.name, self.GetCmd(string = True)))
+        Debug.msg(3, "Layer.__del__(): layer=%s, cmd='%s'" %
+                  (self.name, self.GetCmd(string=True)))
 
     def __str__(self):
         return self.GetCmd(string=True)
 
     def __repr__(self):
         return self.__str__()
-    
+
     def Render(self, env=None):
         """Render layer to image
 
@@ -136,19 +140,20 @@
         if self.type == 'raster_3d':
             return None
 
-        Debug.msg (3, "Layer.Render(): type=%s, name=%s, file=%s" % \
-                       (self.type, self.name, self.mapfile))
+        Debug.msg(3, "Layer.Render(): type=%s, name=%s, file=%s" %
+                  (self.type, self.name, self.mapfile))
 
         # prepare command for each layer
         layertypes = utils.command2ltype.values() + ['overlay', 'command']
 
         if self.type not in layertypes:
-            raise GException(_("<%(name)s>: layer type <%(type)s> is not supported") % \
-                                 {'type' : self.type, 'name' : self.name})
-        
+            raise GException(
+                _("<%(name)s>: layer type <%(type)s> is not supported") %
+                {'type': self.type, 'name': self.name})
+
         if not env:
             env = os.environ.copy()
-        
+
         # render layers
         try:
             if self.type == 'command':
@@ -161,19 +166,22 @@
             else:
                 self.renderMgr.Render(self.cmd, env)
         except GException:
-            sys.stderr.write(_("Command '%s' failed\n") % self.GetCmd(string = True))
+            sys.stderr.write(
+                _("Command '%s' failed\n") %
+                self.GetCmd(
+                    string=True))
             sys.stderr.write(_("Details: %s\n") % e)
-            
+
             # clean up after problems
             for f in [self.mapfile, self.maskfile]:
                 if not f:
                     continue
                 try_remove(f)
                 f = None
-        
+
         return self.mapfile
-    
-    def GetCmd(self, string = False):
+
+    def GetCmd(self, string=False):
         """Get GRASS command as list of string.
 
         :param string: get command as string if True otherwise as list
@@ -210,7 +218,7 @@
         """
         return self.opacity
 
-    def GetName(self, fullyQualified = True):
+    def GetName(self, fullyQualified=True):
         """Get map layer name
 
         :param bool fullyQualified: True to return fully qualified name
@@ -224,11 +232,11 @@
             return self.name
         else:
             if '@' in self.name:
-                return { 'name' : self.name.split('@')[0],
-                         'mapset' : self.name.split('@')[1] }
+                return {'name': self.name.split('@')[0],
+                        'mapset': self.name.split('@')[1]}
             else:
-                return { 'name' : self.name,
-                         'mapset' : '' }
+                return {'name': self.name,
+                        'mapset': ''}
 
     def IsActive(self):
         """Check if layer is activated for rendering"""
@@ -260,18 +268,18 @@
                     env['GRASS_RENDER_FILE_READ'] = 'FALSE'
                     env['GRASS_RENDER_TRANSPARENT'] = 'TRUE'
             self.renderMgr = renderMgr(self, env)
-        
+
         self.type = ltype
 
     def SetName(self, name):
         """Set layer name"""
         self.name = name
 
-    def SetActive(self, enable = True):
+    def SetActive(self, enable=True):
         """Active or deactive layer"""
         self.active = bool(enable)
 
-    def SetHidden(self, enable = False):
+    def SetHidden(self, enable=False):
         """Hide or show map layer in Layer Manager"""
         self.hidden = bool(enable)
 
@@ -292,7 +300,7 @@
                 self.cmd.append(cmdlist_to_tuple(c))
         else:
             self.cmd = cmdlist_to_tuple(cmd)
-        Debug.msg(3, "Layer.SetCmd(): cmd='%s'" % self.GetCmd(string = True))
+        Debug.msg(3, "Layer.SetCmd(): cmd='%s'" % self.GetCmd(string=True))
 
         # for re-rendering
         self.forceRender = True
@@ -309,12 +317,14 @@
         """Get render manager """
         return self.renderMgr
 
+
 class MapLayer(Layer):
+
     def __init__(self, *args, **kwargs):
         """Represents map layer in the map canvas
         """
         Layer.__init__(self, *args, **kwargs)
-        
+
     def GetMapset(self):
         """Get mapset of map layer
 
@@ -329,7 +339,9 @@
         except IndexError:
             return self.name
 
+
 class Overlay(Layer):
+
     def __init__(self, id, *args, **kwargs):
         """Represents overlay displayed in map canvas
 
@@ -337,42 +349,44 @@
         """
         Layer.__init__(self, ltype='overlay', *args, **kwargs)
         self.id = id
-        
+
+
 class RenderLayerMgr(wx.EvtHandler):
+
     def __init__(self, layer, env):
         """Render layer into image
 
         :param layer: Layer to be rendered
         """
         self.layer = layer
-         
+
         wx.EvtHandler.__init__(self)
         self.thread = gThread()
-        
+
         self.updateProgress = Signal('RenderLayerMgr.updateProgress')
-        
+
         self._startTime = None
         self._render_env = env
 
     def UpdateRenderEnv(self, env):
         self._render_env.update(env)
-        
+
     def Render(self, cmd, env):
         """Render layer
 
         :param cmd: display command given as tuple
         :param env: environmental variables used for rendering
         """
-        Debug.msg(1, "RenderLayerMgr.Render(%s): force=%d img=%s" % \
+        Debug.msg(1, "RenderLayerMgr.Render(%s): force=%d img=%s" %
                   (self.layer, self.layer.forceRender, self.layer.mapfile))
-        
+
         env_cmd = env.copy()
         env_cmd.update(self._render_env)
         env_cmd['GRASS_RENDER_FILE'] = self.layer.mapfile
 
         cmd_render = copy.deepcopy(cmd)
-        cmd_render[1]['quiet'] = True # be quiet
-        
+        cmd_render[1]['quiet'] = True  # be quiet
+
         self._startTime = time.time()
         self.thread.Run(callable=self._render, cmd=cmd_render, env=env_cmd,
                         ondone=self.OnRenderDone)
@@ -383,39 +397,41 @@
             return grass.run_command(cmd[0], env=env, **cmd[1])
         except CalledModuleError as e:
             return 1
-    
+
     def Abort(self):
         """Abort rendering process"""
         Debug.msg(1, "RenderLayerMgr({}).Abort()".format(self.layer))
         self.thread.Terminate()
-        
+
         # force rendering layer next time
         self.layer.forceRender = True
         self.thread.Terminate(False)
-        
+
     def IsDownloading(self):
         """Is downloading
 
         :return: always False
         """
         return False
-    
+
     def OnRenderDone(self, event):
         """Rendering done
 
         Emits updateProcess
         """
-        Debug.msg(1, "RenderLayerMgr.OnRenderDone(%s): ret=%d time=%f" % \
-                      (self.layer, event.ret, time.time() - self._startTime))
+        Debug.msg(1, "RenderLayerMgr.OnRenderDone(%s): ret=%d time=%f" %
+                  (self.layer, event.ret, time.time() - self._startTime))
         if event.ret != 0:
             try:
                 os.remove(self.layer.mapfile)
             except:
                 pass
-        
+
         self.updateProgress.emit(layer=self.layer)
-        
+
+
 class RenderMapMgr(wx.EvtHandler):
+
     def __init__(self, Map):
         """Render map layers as image composition
 
@@ -424,21 +440,21 @@
         wx.EvtHandler.__init__(self)
 
         self.Map = Map
-        
+
         self.updateMap = Signal('RenderMapMgr.updateMap')
         self.updateProgress = Signal('RenderMapMgr.updateProgress')
         self.renderDone = Signal('RenderMapMgr.renderDone')
         self.renderDone.connect(self.OnRenderDone)
-        
+
         # GRASS environment variable (for rendering)
-        self._render_env = {"GRASS_RENDER_BACKGROUNDCOLOR" : "000000",
-                            "GRASS_RENDER_FILE_COMPRESSION" : "0",
-                            "GRASS_RENDER_TRUECOLOR"       : "TRUE",
-                            "GRASS_RENDER_TRANSPARENT"     : "TRUE" }
-        
+        self._render_env = {"GRASS_RENDER_BACKGROUNDCOLOR": "000000",
+                            "GRASS_RENDER_FILE_COMPRESSION": "0",
+                            "GRASS_RENDER_TRUECOLOR": "TRUE",
+                            "GRASS_RENDER_TRANSPARENT": "TRUE"}
+
         self._init()
         self._rendering = False
-        
+
     def _init(self, env=None):
         """Init render manager
 
@@ -448,12 +464,12 @@
         self.progressInfo = None
         self._env = env
         self.layers = []
-        
+
         # re-render from scratch
         if os.path.exists(self.Map.mapfile):
             os.remove(self.Map.mapfile)
-        
-    def _renderLayers(self, env, force = False, overlaysOnly = False):
+
+    def _renderLayers(self, env, force=False, overlaysOnly=False):
         """Render all map layers into files
 
         :param dict env: environmental variables to be used for rendering process
@@ -467,7 +483,7 @@
             self.layers += self.Map.GetListOfLayers(active=True,
                                                     ltype='raster_3d',
                                                     except_ltype=True)
-        
+
         # reset progress
         self.ReportProgress()
 
@@ -479,11 +495,11 @@
                 layer.Render(env)
             else:
                 layer.GetRenderMgr().updateProgress.emit(layer=layer)
-        
+
         Debug.msg(1, "RenderMapMgr.Render(): %d layers to be rendered "
                   "(force=%d, all active layers -> %d)" % (nlayers, force,
                                                            len(self.layers)))
-        
+
         return nlayers
 
     def GetRenderEnv(self, windres=False):
@@ -495,42 +511,44 @@
         env['GRASS_REGION'] = self.Map.SetRegion(windres)
         env['GRASS_RENDER_WIDTH'] = str(self.Map.width)
         env['GRASS_RENDER_HEIGHT'] = str(self.Map.height)
-        if UserSettings.Get(group = 'display', key = 'driver', subkey = 'type') == 'png':
+        if UserSettings.Get(group='display', key='driver',
+                            subkey='type') == 'png':
             env['GRASS_RENDER_IMMEDIATE'] = 'png'
         else:
             env['GRASS_RENDER_IMMEDIATE'] = 'cairo'
 
         return env
-    
-    def Render(self, force = False, windres = False):
+
+    def Render(self, force=False, windres=False):
         """Render map composition
 
         :param bool force: force rendering all map layers in the composition
         :param windres: True for region resolution instead for map resolution
         """
         if self._rendering:
-            Debug.msg(1, "RenderMapMgr().Render(): cancelled (already rendering)")
+            Debug.msg(
+                1, "RenderMapMgr().Render(): cancelled (already rendering)")
             return
-        
+
         wx.BeginBusyCursor()
         self._rendering = True
-        
+
         env = self.GetRenderEnv(windres)
         self._init(env)
         if self._renderLayers(env, force, windres) == 0:
             self.renderDone.emit()
-        
+
     def OnRenderDone(self):
         """Rendering process done
 
         Make image composiotion, emits updateMap event.
         """
         stopTime = time.time()
-        
+
         maps = list()
         masks = list()
         opacities = list()
-        
+
         for layer in self.layers:
             if layer.GetType() == 'overlay':
                 continue
@@ -539,37 +557,37 @@
                 maps.append(layer.mapfile)
                 masks.append(layer.maskfile)
                 opacities.append(str(layer.opacity))
-        
+
         # run g.pngcomp to get composite image
-        bgcolor = ':'.join(map(str, UserSettings.Get(group = 'display', key = 'bgcolor',
-                                                     subkey = 'color')))
+        bgcolor = ':'.join(map(str, UserSettings.Get(
+            group='display', key='bgcolor', subkey='color')))
         startCompTime = time.time()
         if maps:
             ret, msg = RunCommand('g.pnmcomp',
-                                  getErrorMsg = True,
-                                  overwrite = True,
-                                  input = '%s' % ",".join(maps),
-                                  mask = '%s' % ",".join(masks),
-                                  opacity = '%s' % ",".join(opacities),
-                                  bgcolor = bgcolor,
-                                  width = self.Map.width,
-                                  height = self.Map.height,
-                                  output = self.Map.mapfile,
+                                  getErrorMsg=True,
+                                  overwrite=True,
+                                  input='%s' % ",".join(maps),
+                                  mask='%s' % ",".join(masks),
+                                  opacity='%s' % ",".join(opacities),
+                                  bgcolor=bgcolor,
+                                  width=self.Map.width,
+                                  height=self.Map.height,
+                                  output=self.Map.mapfile,
                                   env=self._env)
             if ret != 0:
                 self._rendering = False
                 if wx.IsBusy():
                     wx.EndBusyCursor()
                 raise GException(_("Rendering failed: %s" % msg))
-        
+
         stop = time.time()
-        Debug.msg (1, "RenderMapMgr.OnRenderDone() time=%f sec (comp: %f)" % \
-                   (stop - self._startTime, stop - startCompTime))
-        
+        Debug.msg(1, "RenderMapMgr.OnRenderDone() time=%f sec (comp: %f)" %
+                  (stop - self._startTime, stop - startCompTime))
+
         self._rendering = False
         if wx.IsBusy():
             wx.EndBusyCursor()
-        
+
         self.updateMap.emit()
 
     def Abort(self):
@@ -582,20 +600,20 @@
         if wx.IsBusy():
             wx.EndBusyCursor()
         self.updateProgress.emit(range=0, value=0, text=_("Rendering aborted"))
-        
+
     def ReportProgress(self, layer=None):
         """Calculates progress in rendering/downloading
         and emits signal to inform progress bar about progress.
 
         Emits renderDone event when progressVal is equal to range.
-        
+
         :param layer: Layer to be processed or None to reset
         """
         if self.progressInfo is None or layer is None:
-            self.progressInfo = {'progresVal' : 0,   # current progress value
-                                 'downloading' : [], # layers, which are downloading data
-                                 'rendered' : [],    # already rendered layers
-                                 'range' : len(self.layers)}
+            self.progressInfo = {'progresVal': 0,   # current progress value
+                                 'downloading': [],  # layers, which are downloading data
+                                 'rendered': [],    # already rendered layers
+                                 'range': len(self.layers)}
         else:
             if layer not in self.progressInfo['rendered']:
                 self.progressInfo['rendered'].append(layer)
@@ -606,7 +624,7 @@
                 self.progressInfo['progresVal'] += 1
                 if layer in self.progressInfo['downloading']:
                     self.progressInfo['downloading'].remove(layer)
-        
+
         # for updating statusbar text
         stText = ''
         first = True
@@ -620,44 +638,47 @@
         if stText:
             stText += '...'
 
-        if  self.progressInfo['range'] != len(self.progressInfo['rendered']):
+        if self.progressInfo['range'] != len(self.progressInfo['rendered']):
             if stText:
                 stText = _('Rendering & ') + stText
             else:
                 stText = _('Rendering...')
-        
+
         self.updateProgress.emit(range=self.progressInfo['range'],
                                  value=self.progressInfo['progresVal'],
                                  text=stText)
-        
-        if layer and self.progressInfo['progresVal'] == self.progressInfo['range']:
+
+        if layer and self.progressInfo[
+                'progresVal'] == self.progressInfo['range']:
             self.renderDone.emit()
 
+
 class Map(object):
-    def __init__(self, gisrc = None):
+
+    def __init__(self, gisrc=None):
         """Map composition (stack of map layers and overlays)
 
         :param gisrc: alternative gisrc (used eg. by georectifier)
         """
-        Debug.msg (1, "Map.__init__(): gisrc=%s" % gisrc)
+        Debug.msg(1, "Map.__init__(): gisrc=%s" % gisrc)
         # region/extent settigns
-        self.wind      = dict() # WIND settings (wind file)
-        self.region    = dict() # region settings (g.region)
-        self.width     = 640    # map width
-        self.height    = 480    # map height
+        self.wind = dict()  # WIND settings (wind file)
+        self.region = dict()  # region settings (g.region)
+        self.width = 640    # map width
+        self.height = 480    # map height
 
         # list of layers
-        self.layers    = list()  # stack of available GRASS layer
+        self.layers = list()  # stack of available GRASS layer
 
-        self.overlays  = list()  # stack of available overlays
-        self.ovlookup  = dict()  # lookup dictionary for overlay items and overlays
+        self.overlays = list()  # stack of available overlays
+        self.ovlookup = dict()  # lookup dictionary for overlay items and overlays
 
         # path to external gisrc
         self.gisrc = gisrc
-        
+
         # generated file for g.pnmcomp output for rendering the map
-        self.mapfile = grass.tempfile(create = False) + '.ppm'
-        
+        self.mapfile = grass.tempfile(create=False) + '.ppm'
+
         # setting some initial env. variables
         if not self.GetWindow():
             sys.stderr.write(_("Trying to recover from default region..."))
@@ -669,13 +690,13 @@
         self.layerChanged = Signal('Map.layerChanged')
         self.layerRemoved = Signal('Map:layerRemoved')
         self.layerAdded = Signal('Map:layerAdded')
-        
+
         self.renderMgr = RenderMapMgr(self)
 
     def GetRenderMgr(self):
         """Get render manager """
         return self.renderMgr
-        
+
     def GetProjInfo(self):
         """Get projection info"""
         return self.projinfo
@@ -712,22 +733,26 @@
         """Read WIND file and set up self.wind dictionary"""
         # FIXME: duplicated region WIND == g.region (at least some values)
         env = grass.gisenv()
-        filename = os.path.join (env['GISDBASE'],
-                                 env['LOCATION_NAME'],
-                                 env['MAPSET'],
-                                 "WIND")
+        filename = os.path.join(env['GISDBASE'],
+                                env['LOCATION_NAME'],
+                                env['MAPSET'],
+                                "WIND")
         try:
-            windfile = open (filename, "r")
+            windfile = open(filename, "r")
         except IOError as e:
-            sys.exit(_("Error: Unable to open '%(file)s'. Reason: %(ret)s. wxGUI exited.\n") % \
-                         { 'file' : filename, 'ret' : e})
+            sys.exit(
+                _("Error: Unable to open '%(file)s'. Reason: %(ret)s. wxGUI exited.\n") % {
+                    'file': filename,
+                    'ret': e})
 
         for line in windfile.readlines():
             line = line.strip()
             try:
                 key, value = line.split(":", 1)
             except ValueError as e:
-                sys.stderr.write(_("\nERROR: Unable to read WIND file: %s\n") % e)
+                sys.stderr.write(
+                    _("\nERROR: Unable to read WIND file: %s\n") %
+                    e)
                 return None
 
             self.wind[key.strip()] = value.strip()
@@ -743,16 +768,16 @@
         computational resolution. Set computational resolution through
         g.region.
         """
-        mapwidth    = abs(self.region["e"] - self.region["w"])
-        mapheight   = abs(self.region['n'] - self.region['s'])
+        mapwidth = abs(self.region["e"] - self.region["w"])
+        mapheight = abs(self.region['n'] - self.region['s'])
 
-        self.region["nsres"] =  mapheight / self.height
-        self.region["ewres"] =  mapwidth  / self.width
-        self.region['rows']  = round(mapheight / self.region["nsres"])
-        self.region['cols']  = round(mapwidth / self.region["ewres"])
+        self.region["nsres"] = mapheight / self.height
+        self.region["ewres"] = mapwidth / self.width
+        self.region['rows'] = round(mapheight / self.region["nsres"])
+        self.region['cols'] = round(mapwidth / self.region["ewres"])
         self.region['cells'] = self.region['rows'] * self.region['cols']
 
-        Debug.msg (3, "Map.AdjustRegion(): %s" % self.region)
+        Debug.msg(3, "Map.AdjustRegion(): %s" % self.region)
 
         return self.region
 
@@ -778,8 +803,8 @@
         w = float(self.region['w'])
 
         # Calculate rows, columns, and extents
-        new['rows'] = math.fabs(round((n-s)/nsres))
-        new['cols'] = math.fabs(round((e-w)/ewres))
+        new['rows'] = math.fabs(round((n - s) / nsres))
+        new['cols'] = math.fabs(round((e - w) / ewres))
 
         # Calculate new extents
         new['s'] = nsres * round(s / nsres)
@@ -798,9 +823,14 @@
         else:
             res = self.region["nsres"]
 
-        Debug.msg(3, "Map.AlignExtentFromDisplay(): width=%d, height=%d, res=%f, center=%f,%f" % \
-                      (self.width, self.height, res, self.region['center_easting'],
-                       self.region['center_northing']))
+        Debug.msg(
+            3,
+            "Map.AlignExtentFromDisplay(): width=%d, height=%d, res=%f, center=%f,%f" %
+            (self.width,
+             self.height,
+             res,
+             self.region['center_easting'],
+             self.region['center_northing']))
 
         ew = (self.width / 2) * res
         ns = (self.height / 2) * res
@@ -821,21 +851,24 @@
         :param size: map size given as tuple
         """
         try:
-            self.width  = int(size[0])
+            self.width = int(size[0])
             self.height = int(size[1])
             if self.width < 1 or self.height < 1:
-                sys.stderr.write(_("Invalid map size %d,%d\n") % (self.width, self.height))
+                sys.stderr.write(
+                    _("Invalid map size %d,%d\n") %
+                    (self.width, self.height))
                 raise ValueError
         except ValueError:
-            self.width  = 640
+            self.width = 640
             self.height = 480
 
-        Debug.msg(2, "Map.ChangeMapSize(): width=%d, height=%d" % \
-                      (self.width, self.height))
+        Debug.msg(2, "Map.ChangeMapSize(): width=%d, height=%d" %
+                  (self.width, self.height))
 
-    def GetRegion(self, rast=None, zoom=False, vect=None, rast3d=None, regionName=None,
-                  n=None, s=None, e=None, w=None, default=False,
-                  update=False, add3d=False):
+    def GetRegion(
+            self, rast=None, zoom=False, vect=None, rast3d=None,
+            regionName=None, n=None, s=None, e=None, w=None, default=False,
+            update=False, add3d=False):
         """Get region settings (g.region -upgc)
 
         Optionally extent, raster or vector map layer can be given.
@@ -896,8 +929,8 @@
             cmd['raster_3d'] = rast3d
 
         ret, reg, msg = RunCommand('g.region',
-                                   read = True,
-                                   getErrorMsg = True,
+                                   read=True,
+                                   getErrorMsg=True,
                                    env=env,
                                    **cmd)
 
@@ -912,9 +945,10 @@
                 message = _("Unable to zoom to 3d raster map <%s>.") % rast3d + \
                     "\n\n" + _("Details:") + " %s" % msg
             else:
-                message = _("Unable to get current geographic extent. "
-                            "Force quiting wxGUI. Please manually run g.region to "
-                            "fix the problem.")
+                message = _(
+                    "Unable to get current geographic extent. "
+                    "Force quiting wxGUI. Please manually run g.region to "
+                    "fix the problem.")
             GError(message)
             return self.region
 
@@ -925,7 +959,7 @@
             except ValueError:
                 region[key] = val
 
-        Debug.msg (3, "Map.GetRegion(): %s" % region)
+        Debug.msg(3, "Map.GetRegion(): %s" % region)
 
         if update:
             self.region = region
@@ -939,7 +973,7 @@
         """
         return self.region
 
-    def SetRegion(self, windres = False, windres3 = False):
+    def SetRegion(self, windres=False, windres3=False):
         """Render string for GRASS_REGION env. variable, so that the
         images will be rendered from desired zoom level.
 
@@ -952,7 +986,7 @@
         grass_region = ""
 
         if windres:
-            compRegion = self.GetRegion(add3d = windres3)
+            compRegion = self.GetRegion(add3d=windres3)
             region = copy.copy(self.region)
             for key in ('nsres', 'ewres', 'cells'):
                 region[key] = compRegion[key]
@@ -1025,17 +1059,17 @@
                     grass_region += "depths: %d; " % \
                         (region['depths'])
                 else:
-                    grass_region += key + ": "  + self.wind[key] + "; "
+                    grass_region += key + ": " + self.wind[key] + "; "
 
-            Debug.msg (3, "Map.SetRegion(): %s" % grass_region)
+            Debug.msg(3, "Map.SetRegion(): %s" % grass_region)
 
             return grass_region
 
         except:
             return None
 
-    def GetListOfLayers(self, ltype = None, mapset = None, name = None,
-                        active = None, hidden = None, except_ltype=False):
+    def GetListOfLayers(self, ltype=None, mapset=None, name=None,
+                        active=None, hidden=None, except_ltype=False):
         """Returns list of layers of selected properties or list of
         all layers.
 
@@ -1050,7 +1084,7 @@
         """
         selected = []
 
-        if type(ltype) == types.StringType:
+        if isinstance(ltype, types.StringType):
             one_type = True
         else:
             one_type = False
@@ -1063,39 +1097,39 @@
         # ["raster", "vector", "wms", ... ]
         for layer in llist:
             # specified type only
-            if ltype != None:
+            if ltype is not None:
                 if one_type:
                     if (not except_ltype and layer.type != ltype) or \
-                        (except_ltype and layer.type == ltype):
+                            (except_ltype and layer.type == ltype):
                         continue
                 elif not one_type:
                     if (not except_ltype and layer.type not in ltype) or \
                        (except_ltype and layer.type in ltype):
                         continue
-            
+
             # mapset
-            if (mapset != None and ltype != 'overlay') and \
+            if (mapset is not None and ltype != 'overlay') and \
                     layer.GetMapset() != mapset:
                 continue
 
             # name
-            if name != None and layer.name != name:
+            if name is not None and layer.name != name:
                 continue
 
             # hidden and active layers
-            if active != None and \
-                   hidden != None:
+            if active is not None and \
+                    hidden is not None:
                 if layer.active == active and \
-                       layer.hidden == hidden:
+                        layer.hidden == hidden:
                     selected.append(layer)
 
             # active layers
-            elif active != None:
+            elif active is not None:
                 if layer.active == active:
                     selected.append(layer)
 
             # hidden layers
-            elif hidden != None:
+            elif hidden is not None:
                 if layer.hidden == hidden:
                     selected.append(layer)
 
@@ -1103,11 +1137,13 @@
             else:
                 selected.append(layer)
 
-        Debug.msg (3, "Map.GetListOfLayers(ltype=%s): -> %d" % (ltype, len(selected)))
+        Debug.msg(
+            3, "Map.GetListOfLayers(ltype=%s): -> %d" %
+            (ltype, len(selected)))
 
         return selected
 
-    def Render(self, force = False, windres = False):
+    def Render(self, force=False, windres=False):
         """Creates final image composite
 
         This function can conditionaly use high-level tools, which
@@ -1118,26 +1154,28 @@
                         resolution
         """
         self.renderMgr.Render(force, windres)
-        
+
     def _addLayer(self, layer, pos=-1):
         if layer.type == 'overlay':
             llist = self.overlays
         else:
             llist = self.layers
-        
+
         # add maplayer to the list of layers
         if pos > -1:
             llist.insert(pos, layer)
         else:
             llist.append(layer)
-        
-        Debug.msg (3, "Map._addLayer(): layer=%s type=%s" % (layer.name, layer.type))
-        
+
+        Debug.msg(
+            3, "Map._addLayer(): layer=%s type=%s" %
+            (layer.name, layer.type))
+
         return layer
 
-    def AddLayer(self, ltype, command, name = None,
-                 active = True, hidden = False, opacity = 1.0, render = False,
-                 pos = -1):
+    def AddLayer(self, ltype, command, name=None,
+                 active=True, hidden=False, opacity=1.0, render=False,
+                 pos=-1):
         """Adds generic map layer to list of layers
 
         :param ltype: layer type ('raster', 'vector', etc.)
@@ -1157,24 +1195,27 @@
             opacity = 0
         elif opacity > 1:
             opacity = 1
-        layer = MapLayer(ltype = ltype, name = name, cmd = command, Map = self,
-                         active = active, hidden = hidden, opacity = opacity)
-        
+        layer = MapLayer(ltype=ltype, name=name, cmd=command, Map=self,
+                         active=active, hidden=hidden, opacity=opacity)
+
         self._addLayer(layer, pos)
-        
+
         renderMgr = layer.GetRenderMgr()
-        Debug.msg(1, "Map.AddLayer(): ltype={}, command={}".format(ltype, layer.GetCmd(string=True)))
+        Debug.msg(
+            1, "Map.AddLayer(): ltype={}, command={}".format(
+                ltype, layer.GetCmd(
+                    string=True)))
         if renderMgr:
             if layer.type == 'wms':
                 renderMgr.dataFetched.connect(self.renderMgr.ReportProgress)
             renderMgr.updateProgress.connect(self.renderMgr.ReportProgress)
         layer.forceRender = render
-        
+
         self.layerAdded.emit(layer=layer)
-        
+
         return layer
 
-    def DeleteAllLayers(self, overlay = False):
+    def DeleteAllLayers(self, overlay=False):
         """Delete all layers
 
         :param overlay: True to delete also overlayes
@@ -1183,7 +1224,7 @@
         if overlay:
             self.overlays = []
 
-    def DeleteLayer(self, layer, overlay = False):
+    def DeleteLayer(self, layer, overlay=False):
         """Removes layer from list of layers
 
         :param layer: layer instance in layer tree
@@ -1191,7 +1232,7 @@
 
         :return: removed layer on success or None
         """
-        Debug.msg (3, "Map.DeleteLayer(): name=%s" % layer.name)
+        Debug.msg(3, "Map.DeleteLayer(): name=%s" % layer.name)
 
         if overlay:
             list = self.overlays
@@ -1219,7 +1260,7 @@
         self.layers = layers
         Debug.msg(5, "Map.SetLayers(): layers=%s" % (layers))
 
-    def ChangeLayer(self, layer, render = False, **kargs):
+    def ChangeLayer(self, layer, render=False, **kargs):
         """Change map layer properties
 
         :param layer: map layer instance
@@ -1231,10 +1272,10 @@
         :param opacity: opacity level range from 0(transparent) - 1(not transparent)
         :param render: render an image if True
         """
-        Debug.msg (3, "Map.ChangeLayer(): layer=%s" % layer.name)
+        Debug.msg(3, "Map.ChangeLayer(): layer=%s" % layer.name)
 
         if 'ltype' in kargs:
-            layer.SetType(kargs['ltype']) # check type
+            layer.SetType(kargs['ltype'])  # check type
 
         if 'command' in kargs:
             layer.SetCmd(kargs['command'])
@@ -1250,12 +1291,12 @@
 
         if 'opacity' in kargs:
             layer.SetOpacity(kargs['opacity'])
-        
+
         self.forceRender = render
-        
+
         # not needed since there is self.forceRender
-        ### self.layerChanged(layer=layer)
-        
+        # self.layerChanged(layer=layer)
+
         return layer
 
     def ChangeOpacity(self, layer, opacity):
@@ -1265,12 +1306,14 @@
         :param opacity: opacity level <0;1>
         """
         # opacity must be <0;1>
-        if opacity < 0: opacity = 0
-        elif opacity > 1: opacity = 1
+        if opacity < 0:
+            opacity = 0
+        elif opacity > 1:
+            opacity = 1
 
         layer.opacity = opacity
-        Debug.msg (3, "Map.ChangeOpacity(): layer=%s, opacity=%f" % \
-                   (layer.name, layer.opacity))
+        Debug.msg(3, "Map.ChangeOpacity(): layer=%s, opacity=%f" %
+                  (layer.name, layer.opacity))
 
     def ChangeLayerActive(self, layer, active):
         """Enable or disable map layer
@@ -1282,20 +1325,20 @@
         if active:
             layer.forceRender = True
 
-        Debug.msg (3, "Map.ChangeLayerActive(): name='%s' -> active=%d" % \
-                   (layer.name, layer.active))
+        Debug.msg(3, "Map.ChangeLayerActive(): name='%s' -> active=%d" %
+                  (layer.name, layer.active))
 
-    def ChangeLayerName (self, layer, name):
+    def ChangeLayerName(self, layer, name):
         """Change name of the layer
 
         :param layer: layer instance in layer tree
         :param name:  layer name to set up
         """
-        Debug.msg (3, "Map.ChangeLayerName(): from=%s to=%s" % \
-                   (layer.name, name))
-        layer.name =  name
+        Debug.msg(3, "Map.ChangeLayerName(): from=%s to=%s" %
+                  (layer.name, name))
+        layer.name = name
 
-    def RemoveLayer(self, name = None, id = None):
+    def RemoveLayer(self, name=None, id=None):
         """Removes layer from layer list
 
         Layer is defined by name at mapset or id.
@@ -1319,12 +1362,12 @@
                     self.layers.remove(layer)
                     return retlayer
         # del by id
-        elif id != None:
+        elif id is not None:
             return self.layers.pop(id)
 
         return None
 
-    def GetLayerIndex(self, layer, overlay = False):
+    def GetLayerIndex(self, layer, overlay=False):
         """Get index of layer in layer list.
 
         :param layer: layer instace in layer tree
@@ -1344,7 +1387,7 @@
         return -1
 
     def AddOverlay(self, id, ltype, command,
-                   active = True, hidden = True, opacity = 1.0, render = False):
+                   active=True, hidden=True, opacity=1.0, render=False):
         """Adds overlay (grid, barscale, legend, etc.) to list of
         overlays
 
@@ -1358,19 +1401,22 @@
         :return: new layer on success
         :return: None on failure
         """
-        overlay = Overlay(id = id, name = ltype, cmd = command, Map = self,
-                          active = active, hidden = hidden, opacity = opacity)
-        
+        overlay = Overlay(id=id, name=ltype, cmd=command, Map=self,
+                          active=active, hidden=hidden, opacity=opacity)
+
         self._addLayer(overlay)
-        
+
         renderMgr = overlay.GetRenderMgr()
-        Debug.msg (1, "Map.AddOverlay(): cmd={}".format(overlay.GetCmd(string=True)))
+        Debug.msg(
+            1, "Map.AddOverlay(): cmd={}".format(
+                overlay.GetCmd(
+                    string=True)))
         if renderMgr:
             renderMgr.updateProgress.connect(self.renderMgr.ReportProgress)
         overlay.forceRender = render
-        
+
         return overlay
-    
+
     def ChangeOverlay(self, id, **kargs):
         """Change overlay properities
 
@@ -1385,12 +1431,12 @@
 
         :return: new layer on success
         """
-        overlay = self.GetOverlay(id, list = False)
-        if  overlay is None:
-            overlay = Overlay(id, ltype = None, cmd = None)
+        overlay = self.GetOverlay(id, list=False)
+        if overlay is None:
+            overlay = Overlay(id, ltype=None, cmd=None)
 
         if 'ltype' in kargs:
-            overlay.SetName(kargs['ltype']) # ltype -> overlay
+            overlay.SetName(kargs['ltype'])  # ltype -> overlay
 
         if 'command' in kargs:
             overlay.SetCmd(kargs['command'])
@@ -1403,10 +1449,10 @@
 
         if 'opacity' in kargs:
             overlay.SetOpacity(kargs['opacity'])
-        
+
         if 'render' in kargs:
             overlay.forceRender = kargs['render']
-            
+
         return overlay
 
     def GetOverlay(self, id, list=False):
@@ -1440,7 +1486,7 @@
 
         :return: removed overlay on success or None
         """
-        return self.DeleteLayer(overlay, overlay = True)
+        return self.DeleteLayer(overlay, overlay=True)
 
     def _clean(self, llist):
         for layer in llist:

Modified: grass/trunk/gui/wxpython/core/settings.py
===================================================================
--- grass/trunk/gui/wxpython/core/settings.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/settings.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -24,47 +24,52 @@
 import copy
 import types
 
-from core       import globalvar
-from core.gcmd  import GException, GError
+from core import globalvar
+from core.gcmd import GException, GError
 from core.utils import GetSettingsPath, PathJoin, rgb2str, _
 
+
 class Settings:
     """Generic class where to store settings"""
+
     def __init__(self):
         # settings file
         self.filePath = os.path.join(GetSettingsPath(), 'wx')
-        
+
         # key/value separator
         self.sep = ';'
-        
+
         # define default settings
         self._defaultSettings()  # -> self.defaultSettings
-        
+
         # read settings from the file
         self.userSettings = copy.deepcopy(self.defaultSettings)
         try:
             self.ReadSettingsFile()
         except GException as e:
             print >> sys.stderr, e.value
-        
+
         # define internal settings
-        self._internalSettings() # -> self.internalSettings
+        self._internalSettings()  # -> self.internalSettings
 
     def _generateLocale(self):
         """Generate locales
         """
         try:
-            self.locs = os.listdir(os.path.join(os.environ['GISBASE'], 'locale'))
-            self.locs.append('en') # GRASS doesn't ship EN po files
+            self.locs = os.listdir(
+                os.path.join(
+                    os.environ['GISBASE'],
+                    'locale'))
+            self.locs.append('en')  # GRASS doesn't ship EN po files
             self.locs.sort()
             # Add a default choice to not override system locale
             self.locs.insert(0, 'system')
         except:
             # No NLS
             self.locs = ['system']
-        
+
         return 'system'
-        
+
     def _defaultSettings(self):
         """Define default settings
         """
@@ -72,761 +77,761 @@
             projFile = PathJoin(os.environ["GRASS_PROJSHARE"], 'epsg')
         except KeyError:
             projFile = ''
-        
+
         id_loc = self._generateLocale()
-        
+
         self.defaultSettings = {
             #
             # general
             #
             'general': {
                 # use default window layout (layer manager, displays, ...)
-                'defWindowPos' : {
-                    'enabled' : True,
+                'defWindowPos': {
+                    'enabled': True,
                     'dim' : '1,1,%d,%d,%d,1,%d,%d' % \
-                        (globalvar.GM_WINDOW_SIZE[0],
-                         globalvar.GM_WINDOW_SIZE[1],
-                         globalvar.GM_WINDOW_SIZE[0] + 1,
-                         globalvar.MAP_WINDOW_SIZE[0],
-                         globalvar.MAP_WINDOW_SIZE[1])
-                    },
+                    (globalvar.GM_WINDOW_SIZE[0],
+                     globalvar.GM_WINDOW_SIZE[1],
+                     globalvar.GM_WINDOW_SIZE[0] + 1,
+                     globalvar.MAP_WINDOW_SIZE[0],
+                     globalvar.MAP_WINDOW_SIZE[1])
+                },
                 # workspace
-                'workspace' : {
-                    'posDisplay' : {
-                        'enabled' : False
-                        },
-                    'posManager' : {
-                        'enabled' : False
-                        },
+                'workspace': {
+                    'posDisplay': {
+                        'enabled': False
                     },
+                    'posManager': {
+                        'enabled': False
+                    },
                 },
-            'manager' : {
+            },
+            'manager': {
                 # show opacity level widget
-                'changeOpacityLevel' : {
-                    'enabled' : False
-                    }, 
+                'changeOpacityLevel': {
+                    'enabled': False
+                },
                 # ask when removing layer from layer tree
-                'askOnRemoveLayer' : {
-                    'enabled' : True
-                    },
+                'askOnRemoveLayer': {
+                    'enabled': True
+                },
                 # ask when quiting wxGUI or closing display
-                'askOnQuit' : {
-                    'enabled' : True
-                    },
+                'askOnQuit': {
+                    'enabled': True
+                },
                 # hide tabs
-                'hideTabs' : {
-                    'search' : False,
-                    'pyshell' : False,
-                    },
-                'copySelectedTextToClipboard' : {
-                    'enabled' : False
-                    },
+                'hideTabs': {
+                    'search': False,
+                    'pyshell': False,
                 },
+                'copySelectedTextToClipboard': {
+                    'enabled': False
+                },
+            },
             #
             # appearance
             #
             'appearance': {
-                'outputfont' : {
-                    'type' : 'Courier New',
+                'outputfont': {
+                    'type': 'Courier New',
                     'size': '10',
-                    },
+                },
                 # expand/collapse element list
-                'elementListExpand' : {
-                    'selection' : 0 
-                    },
-                'menustyle' : {
-                    'selection' : 1
-                    },
-                'gSelectPopupHeight' : {
-                    'value' : 200
-                    },
-                'iconTheme' : {
-                    'type' : 'grass'
-                    },
-                'commandNotebook' : {
-                    'selection' : 0 if sys.platform in ('win32', 'darwin') else 1
-                    },
+                'elementListExpand': {
+                    'selection': 0
                 },
+                'menustyle': {
+                    'selection': 1
+                },
+                'gSelectPopupHeight': {
+                    'value': 200
+                },
+                'iconTheme': {
+                    'type': 'grass'
+                },
+                'commandNotebook': {
+                    'selection': 0 if sys.platform in ('win32', 'darwin') else 1
+                },
+            },
             #
             # language
             #
             'language': {
                 'locale': {
-                    'lc_all' : id_loc
+                    'lc_all': id_loc
                 }
             },
             #
             # display
             #
             'display': {
-                'font' : {
-                    'type' : '',
+                'font': {
+                    'type': '',
                     'encoding': 'UTF-8',
-                    },
+                },
                 'driver': {
                     'type': 'cairo'
-                    },
-                'alignExtent' : {
-                    'enabled' : True
-                    },
-                'compResolution' : {
-                    'enabled' : False
-                    },
+                },
+                'alignExtent': {
+                    'enabled': True
+                },
+                'compResolution': {
+                    'enabled': False
+                },
                 'autoRendering': {
-                    'enabled' : True
-                    },
-                'autoZooming' : {
-                    'enabled' : False
-                    },
+                    'enabled': True
+                },
+                'autoZooming': {
+                    'enabled': False
+                },
                 'statusbarMode': {
-                    'selection' : 0
-                    },
+                    'selection': 0
+                },
                 'bgcolor': {
-                    'color' : (255, 255, 255, 255),
-                    },
-                'mouseWheelZoom' : {
-                    'selection' : 1,
-                    },
-                'scrollDirection' : {
-                    'selection' : 0,
-                    },
-                'nvizDepthBuffer' : {
-                    'value' : '16',
-                    },
+                    'color': (255, 255, 255, 255),
                 },
+                'mouseWheelZoom': {
+                    'selection': 1,
+                },
+                'scrollDirection': {
+                    'selection': 0,
+                },
+                'nvizDepthBuffer': {
+                    'value': '16',
+                },
+            },
             #
             # projection
             #
-            'projection' : {
-                'statusbar' : {
-                    'proj4'    : '',
-                    'epsg'     : '',
-                    'projFile' : projFile,
-                    },
-                'format' : {
-                    'll'  : 'DMS',
-                    'precision' : 2,
-                    },
+            'projection': {
+                'statusbar': {
+                    'proj4': '',
+                    'epsg': '',
+                    'projFile': projFile,
                 },
+                'format': {
+                    'll': 'DMS',
+                    'precision': 2,
+                },
+            },
             #
             # Attribute Table Manager
             #
-            'atm' : {
-                'highlight' : {
-                    'color' : (255, 255, 0, 255),
-                    'width' : 2,
-                    'auto'  : True,
-                    },
-                'leftDbClick' : {
-                    'selection' : 1 # draw selected
-                    },
-                'askOnDeleteRec' : {
-                    'enabled' : True
-                    },
-                'keycolumn' : {
-                    'value' : 'cat'
-                    },
-                'encoding' : {
-                    'value' : '',
-                    }
+            'atm': {
+                'highlight': {
+                    'color': (255, 255, 0, 255),
+                    'width': 2,
+                    'auto': True,
                 },
+                'leftDbClick': {
+                    'selection': 1  # draw selected
+                },
+                'askOnDeleteRec': {
+                    'enabled': True
+                },
+                'keycolumn': {
+                    'value': 'cat'
+                },
+                'encoding': {
+                    'value': '',
+                }
+            },
             #
             # Command
             #
             'cmd': {
-                'overwrite' : {
-                    'enabled' : False
-                    },
-                'closeDlg' : {
-                    'enabled' : False
-                    },
-                'verbosity' : {
-                    'selection' : 'grassenv'
-                    },
-                'addNewLayer' : {
-                    'enabled' : True,
-                    },
-                'interactiveInput' : {
-                    'enabled' : True,
-                    },
+                'overwrite': {
+                    'enabled': False
                 },
+                'closeDlg': {
+                    'enabled': False
+                },
+                'verbosity': {
+                    'selection': 'grassenv'
+                },
+                'addNewLayer': {
+                    'enabled': True,
+                },
+                'interactiveInput': {
+                    'enabled': True,
+                },
+            },
             #
             # d.rast
             #
             'rasterLayer': {
                 'opaque': {
-                    'enabled' : False
-                    },
+                    'enabled': False
+                },
                 'colorTable': {
-                    'enabled' : False,
-                    'selection' : 'rainbow'
-                    },
+                    'enabled': False,
+                    'selection': 'rainbow'
                 },
+            },
             #
             # d.vect
             #
             'vectorLayer': {
                 'featureColor': {
-                    'color' : (0, 0, 0),
-                    'transparent' : {
+                    'color': (0, 0, 0),
+                    'transparent': {
                         'enabled': False
-                        }
-                    },
+                    }
+                },
                 'areaFillColor': {
-                    'color' : (200, 200, 200),
-                    'transparent' : {
+                    'color': (200, 200, 200),
+                    'transparent': {
                         'enabled': False
-                        }
-                    },
+                    }
+                },
                 'line': {
-                    'width' : 0,
-                    },
+                    'width': 0,
+                },
                 'point': {
                     'symbol': 'basic/x',
-                    'size' : 5,
-                    },
+                    'size': 5,
+                },
                 'showType': {
-                    'point' : {
-                        'enabled' : True
-                        },
-                    'line' : {
-                        'enabled' : True
-                        },
-                    'centroid' : {
-                        'enabled' : False
-                        },
-                    'boundary' : {
-                        'enabled' : False
-                        },
-                    'area' : {
-                        'enabled' : True
-                        },
-                    'face' : {
-                        'enabled' : True
-                        },
+                    'point': {
+                        'enabled': True
                     },
+                    'line': {
+                        'enabled': True
+                    },
+                    'centroid': {
+                        'enabled': False
+                    },
+                    'boundary': {
+                        'enabled': False
+                    },
+                    'area': {
+                        'enabled': True
+                    },
+                    'face': {
+                        'enabled': True
+                    },
                 },
+            },
             #
             # vdigit
             #
-            'vdigit' : {
+            'vdigit': {
                 # symbology
-                'symbol' : {
-                    'newSegment' : {
-                        'enabled' : None,
-                        'color' : (255, 0, 0, 255)
-                        }, # red
-                    'newLine' : {
-                        'enabled' : None,
-                        'color' : (0, 86, 45, 255)
-                        }, # dark green
-                    'highlight' : {
-                        'enabled' : None,
-                        'color' : (255, 255, 0, 255)
-                        }, # yellow
-                    'highlightDupl' : {
-                        'enabled' : None,
-                        'color' : (255, 72, 0, 255)
-                        }, # red
-                    'point' : {
-                        'enabled' : True,
-                        'color' : (0, 0, 0, 255)
-                        }, # black
-                    'line' : {
-                        'enabled' : True,
-                        'color' : (0, 0, 0, 255)
-                        }, # black
-                    'boundaryNo' : {
-                        'enabled' : True,
-                        'color' : (126, 126, 126, 255)
-                        }, # grey
-                    'boundaryOne' : {
-                        'enabled' : True,
-                        'color' : (0, 255, 0, 255)
-                        }, # green
-                    'boundaryTwo' : {
-                        'enabled' : True,
-                        'color' : (255, 135, 0, 255)
-                        }, # orange
-                    'centroidIn' : {
-                        'enabled' : True,
-                        'color' : (0, 0, 255, 255)
-                        }, # blue
-                    'centroidOut' : {
-                        'enabled' : True,
-                        'color' : (165, 42, 42, 255)
-                        }, # brown
-                    'centroidDup' : {
-                        'enabled' : True,
-                        'color' : (156, 62, 206, 255)
-                        }, # violet
-                    'nodeOne' : {
-                        'enabled' : True,
-                        'color' : (255, 0, 0, 255)
-                        }, # red
-                    'nodeTwo' : {
-                        'enabled' : True,
-                        'color' : (0, 86, 45, 255)
-                        }, # dark green
-                    'vertex' : {
-                        'enabled' : False,
-                        'color' : (255, 20, 147, 255)
-                        }, # deep pink
-                    'area' : {
-                        'enabled' : True,
-                        'color' : (217, 255, 217, 255)
-                        }, # green
-                    'direction' : {
-                        'enabled' : False,
-                        'color' : (255, 0, 0, 255)
-                        }, # red
-                    },
+                'symbol': {
+                    'newSegment': {
+                        'enabled': None,
+                        'color': (255, 0, 0, 255)
+                    },  # red
+                    'newLine': {
+                        'enabled': None,
+                        'color': (0, 86, 45, 255)
+                    },  # dark green
+                    'highlight': {
+                        'enabled': None,
+                        'color': (255, 255, 0, 255)
+                    },  # yellow
+                    'highlightDupl': {
+                        'enabled': None,
+                        'color': (255, 72, 0, 255)
+                    },  # red
+                    'point': {
+                        'enabled': True,
+                        'color': (0, 0, 0, 255)
+                    },  # black
+                    'line': {
+                        'enabled': True,
+                        'color': (0, 0, 0, 255)
+                    },  # black
+                    'boundaryNo': {
+                        'enabled': True,
+                        'color': (126, 126, 126, 255)
+                    },  # grey
+                    'boundaryOne': {
+                        'enabled': True,
+                        'color': (0, 255, 0, 255)
+                    },  # green
+                    'boundaryTwo': {
+                        'enabled': True,
+                        'color': (255, 135, 0, 255)
+                    },  # orange
+                    'centroidIn': {
+                        'enabled': True,
+                        'color': (0, 0, 255, 255)
+                    },  # blue
+                    'centroidOut': {
+                        'enabled': True,
+                        'color': (165, 42, 42, 255)
+                    },  # brown
+                    'centroidDup': {
+                        'enabled': True,
+                        'color': (156, 62, 206, 255)
+                    },  # violet
+                    'nodeOne': {
+                        'enabled': True,
+                        'color': (255, 0, 0, 255)
+                    },  # red
+                    'nodeTwo': {
+                        'enabled': True,
+                        'color': (0, 86, 45, 255)
+                    },  # dark green
+                    'vertex': {
+                        'enabled': False,
+                        'color': (255, 20, 147, 255)
+                    },  # deep pink
+                    'area': {
+                        'enabled': True,
+                        'color': (217, 255, 217, 255)
+                    },  # green
+                    'direction': {
+                        'enabled': False,
+                        'color': (255, 0, 0, 255)
+                    },  # red
+                },
                 # display
-                'lineWidth' : {
-                    'value' : 2,
-                    'units' : 'screen pixels'
-                    },
+                'lineWidth': {
+                    'value': 2,
+                    'units': 'screen pixels'
+                },
                 # snapping
-                'snapping' : {
-                    'value' : 10,
-                    'units' : 'screen pixels'
-                    },
-                'snapToVertex' : {
-                    'enabled' : True
-                    },
+                'snapping': {
+                    'value': 10,
+                    'units': 'screen pixels'
+                },
+                'snapToVertex': {
+                    'enabled': True
+                },
                 # digitize new record
-                'addRecord' : {
-                    'enabled' : True
-                    },
-                'layer' :{
-                    'value' : 1
-                    },
-                'category' : {
-                    'value' : 1
-                    },
-                'categoryMode' : {
-                    'selection' : 0
-                    },
+                'addRecord': {
+                    'enabled': True
+                },
+                'layer': {
+                    'value': 1
+                },
+                'category': {
+                    'value': 1
+                },
+                'categoryMode': {
+                    'selection': 0
+                },
                 # delete existing feature(s)
-                'delRecord' : {
-                    'enabled' : True
-                    },
+                'delRecord': {
+                    'enabled': True
+                },
                 # query tool
-                'query' : {
-                    'selection' : 0,
-                    'box' : True
-                    },
-                'queryLength' : {
-                    'than-selection' : 0,
-                    'thresh' : 0
-                    },
-                'queryDangle' : {
-                    'than-selection' : 0,
-                    'thresh' : 0
-                    },
+                'query': {
+                    'selection': 0,
+                    'box': True
+                },
+                'queryLength': {
+                    'than-selection': 0,
+                    'thresh': 0
+                },
+                'queryDangle': {
+                    'than-selection': 0,
+                    'thresh': 0
+                },
                 # select feature (point, line, centroid, boundary)
                 'selectType': {
-                    'point' : {
-                        'enabled' : True
-                        },
-                    'line' : {
-                        'enabled' : True
-                        },
-                    'centroid' : {
-                        'enabled' : True
-                        },
-                    'boundary' : {
-                        'enabled' : True
-                        },
+                    'point': {
+                        'enabled': True
                     },
-                'selectThresh' : {
-                    'value' : 10,
-                    'units' : 'screen pixels'
+                    'line': {
+                        'enabled': True
                     },
-                'checkForDupl' : {
-                    'enabled' : False
+                    'centroid': {
+                        'enabled': True
                     },
-                'selectInside' : {
-                    'enabled' : False
+                    'boundary': {
+                        'enabled': True
                     },
+                },
+                'selectThresh': {
+                    'value': 10,
+                    'units': 'screen pixels'
+                },
+                'checkForDupl': {
+                    'enabled': False
+                },
+                'selectInside': {
+                    'enabled': False
+                },
                 # exit
-                'saveOnExit' : {
-                    'enabled' : False,
-                    },
+                'saveOnExit': {
+                    'enabled': False,
+                },
                 # break lines on intersection
-                'breakLines' : {
-                    'enabled' : True,
-                    },
+                'breakLines': {
+                    'enabled': True,
+                },
                 # close boundary (snap to the first node)
-                'closeBoundary' : {
-                    'enabled' : False,
-                    }
-                },
-             # 
-             # plots for profiles, histograms, and scatterplots
-             #
+                'closeBoundary': {
+                    'enabled': False,
+                }
+            },
+            #
+            # plots for profiles, histograms, and scatterplots
+            #
             'profile': {
-                'raster' : {
-                    'pcolor'        : (0, 0, 255, 255), # line color
-                    'pwidth'        : 1, # line width
-                    'pstyle'        : 'solid', # line pen style
-                    'datatype'      : 'cell', # raster type
-                    },
-                'font' : {
-                    'titleSize' : 12,
-                    'axisSize' : 11,
-                    'legendSize' : 10,
-                    },
-                'marker' : {
-                    'color' : (0, 0, 0, 255),
-                    'fill' : 'transparent',
-                    'size' : 2,
-                    'type' : 'triangle',
-                    'legend' : _('Segment break'),
-                    },
-                'grid' : {
-                    'color' : (200, 200, 200, 255),
-                    'enabled' : True,
-                    },
-                'x-axis' : {
-                    'type' : 'auto', # axis format
-                    'min' : 0, # axis min for custom axis range
-                    'max': 0, # axis max for custom axis range
-                    'log' : False,
-                    },
-                'y-axis' : {
-                    'type' : 'auto', # axis format
-                    'min' : 0, # axis min for custom axis range
-                    'max': 0, # axis max for custom axis range
-                    'log' : False,
-                    },
-                'legend' : {
-                    'enabled' : True
-                    },
+                'raster': {
+                    'pcolor': (0, 0, 255, 255),  # line color
+                    'pwidth': 1,  # line width
+                    'pstyle': 'solid',  # line pen style
+                    'datatype': 'cell',  # raster type
                 },
-             'histogram': {
-                'raster' : {
-                    'pcolor'        : (0, 0, 255, 255), # line color
-                    'pwidth'        : 1, # line width
-                    'pstyle'        : 'solid', # line pen style
-                    'datatype'      : 'cell', # raster type
-                    },
-                'font' : {
-                    'titleSize'     : 12,
-                    'axisSize'      : 11,
-                    'legendSize'    : 10,
-                    },
-                'grid' : {
-                    'color'         : (200, 200, 200, 255),
-                    'enabled'       : True,
-                    },
-                'x-axis' : {
-                    'type'          : 'auto', # axis format
-                    'min'           : 0, # axis min for custom axis range
-                    'max'           : 0, # axis max for custom axis range
-                    'log'           : False,
-                    },
-                'y-axis' : {
-                    'type'          : 'auto', # axis format
-                    'min'           : 0, # axis min for custom axis range
-                    'max'           : 0, # axis max for custom axis range
-                    'log'           : False,
-                    },
-                'legend' : {
-                    'enabled'       : True
-                    },
+                'font': {
+                    'titleSize': 12,
+                    'axisSize': 11,
+                    'legendSize': 10,
                 },
-             'scatter': {
-                'raster' : {
-                    'pcolor' : (0, 0, 255, 255),
-                    'pfill' : 'solid',
-                    'psize' : 1,
-                    'ptype' : 'dot',
+                'marker': {
+                    'color': (0, 0, 0, 255),
+                    'fill': 'transparent',
+                    'size': 2,
+                    'type': 'triangle',
+                    'legend': _('Segment break'),
+                },
+                'grid': {
+                    'color': (200, 200, 200, 255),
+                    'enabled': True,
+                },
+                'x-axis': {
+                    'type': 'auto',  # axis format
+                    'min': 0,  # axis min for custom axis range
+                    'max': 0,  # axis max for custom axis range
+                    'log': False,
+                },
+                'y-axis': {
+                    'type': 'auto',  # axis format
+                    'min': 0,  # axis min for custom axis range
+                    'max': 0,  # axis max for custom axis range
+                    'log': False,
+                },
+                'legend': {
+                    'enabled': True
+                },
+            },
+            'histogram': {
+                'raster': {
+                    'pcolor': (0, 0, 255, 255),  # line color
+                    'pwidth': 1,  # line width
+                    'pstyle': 'solid',  # line pen style
+                    'datatype': 'cell',  # raster type
+                },
+                'font': {
+                    'titleSize': 12,
+                    'axisSize': 11,
+                    'legendSize': 10,
+                },
+                'grid': {
+                    'color': (200, 200, 200, 255),
+                    'enabled': True,
+                },
+                'x-axis': {
+                    'type': 'auto',  # axis format
+                    'min': 0,  # axis min for custom axis range
+                    'max': 0,  # axis max for custom axis range
+                    'log': False,
+                },
+                'y-axis': {
+                    'type': 'auto',  # axis format
+                    'min': 0,  # axis min for custom axis range
+                    'max': 0,  # axis max for custom axis range
+                    'log': False,
+                },
+                'legend': {
+                    'enabled': True
+                },
+            },
+            'scatter': {
+                'raster': {
+                    'pcolor': (0, 0, 255, 255),
+                    'pfill': 'solid',
+                    'psize': 1,
+                    'ptype': 'dot',
                     # FIXME: this is only a quick fix
                     # using also names used in a base class for compatibility
                     # probably used only for initialization
                     # base should be rewritten to not require this
-                    'pwidth' : 1,  # required by wxplot/base, maybe useless here
-                    'pstyle' : 'dot', # line pen style
-                    'plegend' : _('Data point'),
-                    0 : {'datatype' : 'CELL'},
-                    1 : {'datatype' : 'CELL'},
+                    'pwidth': 1,  # required by wxplot/base, maybe useless here
+                    'pstyle': 'dot',  # line pen style
+                    'plegend': _('Data point'),
+                    0: {'datatype': 'CELL'},
+                    1: {'datatype': 'CELL'},
+                },
+                'font': {
+                    'titleSize': 12,
+                    'axisSize': 11,
+                    'legendSize': 10,
+                },
+                'grid': {
+                    'color': (200, 200, 200, 255),
+                    'enabled': True,
+                },
+                'x-axis': {
+                    'type': 'auto',  # axis format
+                    'min': 0,  # axis min for custom axis range
+                    'max': 0,  # axis max for custom axis range
+                    'log': False,
+                },
+                'y-axis': {
+                    'type': 'auto',  # axis format
+                    'min': 0,  # axis min for custom axis range
+                    'max': 0,  # axis max for custom axis range
+                    'log': False,
+                },
+                'legend': {
+                    'enabled': True
+                },
+            },
+            'gcpman': {
+                'rms': {
+                    'highestonly': True,
+                    'sdfactor': 1,
+                },
+                'symbol': {
+                    'color': (0, 0, 255, 255),
+                    'hcolor': (255, 0, 0, 255),
+                    'scolor': (0, 255, 0, 255),
+                    'ucolor': (255, 165, 0, 255),
+                    'unused': True,
+                    'size': 8,
+                    'width': 2,
+                },
+            },
+            'nviz': {
+                'view': {
+                    'persp': {
+                        'value': 20,
+                        'step': 2,
                     },
-                'font' : {
-                    'titleSize'     : 12,
-                    'axisSize'      : 11,
-                    'legendSize'    : 10,
+                    'position': {
+                        'x': 0.84,
+                        'y': 0.16,
                     },
-                'grid' : {
-                    'color'         : (200, 200, 200, 255),
-                    'enabled'       : True,
+                    'twist': {
+                        'value': 0,
                     },
-                'x-axis' : {
-                    'type'          : 'auto', # axis format
-                    'min'           : 0, # axis min for custom axis range
-                    'max'           : 0, # axis max for custom axis range
-                    'log'           : False,
+                    'z-exag': {
+                        'min': 0,
+                        'max': 10,
+                        'value': 1,
                     },
-                'y-axis' : {
-                    'type'          : 'auto', # axis format
-                    'min'           : 0, # axis min for custom axis range
-                    'max'           : 0, # axis max for custom axis range
-                    'log'           : False,
+                    'background': {
+                        'color': (255, 255, 255, 255),  # white
                     },
-                'legend' : {
-                    'enabled'       : True
-                    },
                 },
-            'gcpman' : {
-                'rms' : {
-                    'highestonly' : True,
-                    'sdfactor' : 1,
-                    },
-                'symbol' : {
-                    'color' : (0, 0, 255, 255),
-                    'hcolor' : (255, 0, 0, 255),
-                    'scolor' : (0, 255, 0, 255),
-                    'ucolor' : (255, 165, 0, 255),
-                    'unused' : True,
-                    'size' : 8,
-                    'width' : 2,
-                    },
+                'fly': {
+                    'exag': {
+                        'move': 5,
+                        'turn': 5,
+                    }
                 },
-            'nviz' : {
-                'view' : {
-                    'persp' : {
-                        'value' : 20,
-                        'step' : 2,
-                        },
-                    'position' : {
-                        'x' : 0.84,
-                        'y' : 0.16,
-                        },
-                    'twist' : {
-                        'value' : 0,
-                        },
-                    'z-exag' : {
-                        'min' : 0,
-                        'max' : 10,
-                        'value': 1,
-                        },
-                    'background' : {
-                        'color' : (255, 255, 255, 255), # white
-                        },
+                'animation': {
+                    'fps': 24,
+                    'prefix': _("animation")
+                },
+                'surface': {
+                    'shine': {
+                        'map': False,
+                        'value': 60.0,
                     },
-                'fly' : {
-                    'exag' : {
-                        'move' : 5,
-                        'turn' : 5,
-                        }
+                    'color': {
+                        'map': True,
+                        'value': (100, 100, 100, 255),  # constant: grey
                     },
-                'animation' : {
-                    'fps' : 24,
-                    'prefix' : _("animation")
+                    'draw': {
+                        'wire-color': (136, 136, 136, 255),
+                        'mode': 1,  # fine
+                        'style': 1,  # surface
+                        'shading': 1,  # gouraud
+                        'res-fine': 6,
+                        'res-coarse': 9,
                     },
-                'surface' : {
-                    'shine': {
-                        'map' : False,
-                        'value' : 60.0,
-                        },
-                    'color' : {
-                        'map' : True,
-                        'value' : (100, 100, 100, 255), # constant: grey
-                        },
-                    'draw' : {
-                        'wire-color' : (136, 136, 136, 255),
-                        'mode' : 1, # fine
-                        'style' : 1, # surface
-                        'shading' : 1, # gouraud
-                        'res-fine' : 6,
-                        'res-coarse' : 9,
-                        },
-                    'position' : {
-                        'x' : 0,
-                        'y' : 0,
-                        'z' : 0,
-                        },
+                    'position': {
+                        'x': 0,
+                        'y': 0,
+                        'z': 0,
                     },
-                'constant' : {
-                    'color' : (100, 100, 100, 255),
-                    'value' : 0.0,
-                    'transp' : 0,
+                },
+                'constant': {
+                    'color': (100, 100, 100, 255),
+                    'value': 0.0,
+                    'transp': 0,
                     'resolution': 6
                 },
-                'vector' : {
-                    'lines' : {
-                        'show' : False,
-                        'width' : 2,
-                        'color' : (0, 0, 0, 255),
-                        'flat' : False,
-                        'height' : 0,
+                'vector': {
+                    'lines': {
+                        'show': False,
+                        'width': 2,
+                        'color': (0, 0, 0, 255),
+                        'flat': False,
+                        'height': 0,
                         'rgbcolumn': None,
                         'sizecolumn': None,
-                        },
-                    'points' : {
-                        'show' : False,
-                        'size' : 100,
-                        'width' : 2,
-                        'marker' : 2,
-                        'color' : (0, 0, 0, 255),
-                        'height' : 0,
+                    },
+                    'points': {
+                        'show': False,
+                        'size': 100,
+                        'width': 2,
+                        'marker': 2,
+                        'color': (0, 0, 0, 255),
+                        'height': 0,
                         'rgbcolumn': None,
                         'sizecolumn': None,
-                        }
+                    }
+                },
+                'volume': {
+                    'color': {
+                        'map': True,
+                        'value': (100, 100, 100, 255),  # constant: grey
                     },
-                'volume' : {
-                    'color' : {
-                        'map' : True,
-                        'value' : (100, 100, 100, 255), # constant: grey
-                        },
-                    'draw' : {
-                        'mode'       : 0, # isosurfaces
-                        'shading'    : 1, # gouraud
-                        'resolution' : 3, # polygon resolution
-                        'box'        : False # draw wire box
-                        },
+                    'draw': {
+                        'mode': 0,  # isosurfaces
+                        'shading': 1,  # gouraud
+                        'resolution': 3,  # polygon resolution
+                        'box': False  # draw wire box
+                    },
                     'shine': {
-                        'map' : False,
-                        'value' : 60,
-                        },
+                        'map': False,
+                        'value': 60,
+                    },
                     'topo': {
-                        'map' : None,
-                        'value' : 0.0
-                        },
+                        'map': None,
+                        'value': 0.0
+                    },
                     'transp': {
-                        'map' : None,
+                        'map': None,
                         'value': 0
-                        },
+                    },
                     'mask': {
-                        'map' : None,
+                        'map': None,
                         'value': ''
-                        },
+                    },
                     'slice_position': {
-                        'x1' : 0,
-                        'x2' : 1,
-                        'y1' : 0,
-                        'y2' : 1,
-                        'z1' : 0,
-                        'z2' : 1,
-                        'axis' : 0,
-                        }
-                    },
-                'cplane' : {
+                        'x1': 0,
+                        'x2': 1,
+                        'y1': 0,
+                        'y2': 1,
+                        'z1': 0,
+                        'z2': 1,
+                        'axis': 0,
+                    }
+                },
+                'cplane': {
                     'shading': 4,
-                    'rotation':{
-                        'rot': 180, 
+                    'rotation': {
+                        'rot': 180,
                         'tilt': 0
-                        }, 
-                    'position':{
-                        'x' : 0,
-                        'y' : 0,
-                        'z' : 0
-                    }   
+                    },
+                    'position': {
+                        'x': 0,
+                        'y': 0,
+                        'z': 0
+                    }
                 },
-                'light' : {
-                    'position' : {
-                        'x' : 0.68,
-                        'y' : -0.68,
-                        'z' : 80,
-                        },
-                    'bright'  : 80,
-                    'color'   : (255, 255, 255, 255), # white
-                    'ambient' : 20,
+                'light': {
+                    'position': {
+                        'x': 0.68,
+                        'y': -0.68,
+                        'z': 80,
                     },
-                'fringe' : {
-                    'elev'   : 55,
-                    'color'  : (128, 128, 128, 255), # grey
-                    },
+                    'bright': 80,
+                    'color': (255, 255, 255, 255),  # white
+                    'ambient': 20,
+                },
+                'fringe': {
+                    'elev': 55,
+                    'color': (128, 128, 128, 255),  # grey
+                },
                 'arrow': {
                     'color': (0, 0, 0),
-                    },
+                },
                 'scalebar': {
                     'color': (0, 0, 0),
-                    }
+                }
+            },
+            'modeler': {
+                'disabled': {
+                    'color': (211, 211, 211, 255),  # light grey
                 },
-            'modeler' : {
-                'disabled': {
-                    'color': (211, 211, 211, 255), # light grey
+                'action': {
+                    'color': {
+                        'valid': (180, 234, 154, 255),  # light green
+                        'invalid': (255, 255, 255, 255),  # white
+                        'running': (255, 0, 0, 255),     # red
                     },
-                'action' : {
-                    'color' : {
-                        'valid'   :  (180, 234, 154, 255), # light green
-                        'invalid' :  (255, 255, 255, 255), # white
-                        'running' :  (255, 0, 0, 255),     # red
-                        },
-                    'size' : {
-                        'width'  : 125,
-                        'height' : 50,
-                        },
+                    'size': {
+                        'width': 125,
+                        'height': 50,
+                    },
                     'width': {
-                        'parameterized' : 2,
-                        'default'       : 1,
-                        },
+                        'parameterized': 2,
+                        'default': 1,
                     },
-                'data' : { 
+                },
+                'data': {
                     'color': {
-                        'raster'   : (215, 215, 248, 255), # light blue
-                        'raster3d' : (215, 248, 215, 255), # light green
-                        'vector'   : (248, 215, 215, 255), # light red
-                        'dbtable'  : (255, 253, 194, 255), # light yellow
-                        },
-                    'size' : {
-                        'width' : 175,
-                        'height' : 50,
-                        },
+                        'raster': (215, 215, 248, 255),  # light blue
+                        'raster3d': (215, 248, 215, 255),  # light green
+                        'vector': (248, 215, 215, 255),  # light red
+                        'dbtable': (255, 253, 194, 255),  # light yellow
                     },
-                'loop' : {
-                    'color' : {
-                        'valid'   :  (234, 226, 154, 255), # dark yellow
-                        },
-                    'size' : {
-                        'width' : 175,
-                        'height' : 40,
-                        },
+                    'size': {
+                        'width': 175,
+                        'height': 50,
                     },
-                'if-else' : {
-                    'size' : {
-                        'width' : 150,
-                        'height' : 40,
-                        },
+                },
+                'loop': {
+                    'color': {
+                        'valid': (234, 226, 154, 255),  # dark yellow
                     },
-                'comment' : {
-                    'color' : (255, 233, 208, 255), # light yellow
-                    'size' : {
-                        'width' : 200,
-                        'height' : 100,
-                        },
+                    'size': {
+                        'width': 175,
+                        'height': 40,
                     },
                 },
-            'mapswipe' : {
+                'if-else': {
+                    'size': {
+                        'width': 150,
+                        'height': 40,
+                    },
+                },
+                'comment': {
+                    'color': (255, 233, 208, 255),  # light yellow
+                    'size': {
+                        'width': 200,
+                        'height': 100,
+                    },
+                },
+            },
+            'mapswipe': {
                 'cursor': {
                     'color': (0, 0, 0, 255),
                     'size': 12,
                     'width': 1,
                     'type': {
                         'selection': 0,
-                        }
-                    },
+                    }
                 },
+            },
             'animation': {
                 'bgcolor': {
                     'color': (255, 255, 255, 255),
-                    },
+                },
                 'nprocs': {
                     'value': -1,
-                    },
+                },
                 'font': {
                     'bgcolor': (255, 255, 255, 255),
                     'fgcolor': (0, 0, 0, 255),
-                    },
+                },
                 'temporal': {
                     'format': '%Y-%m-%d %H:%M:%S',
                     'nodata': {
                         'enable': False
-                        },
                     },
                 },
-            }
+            },
+        }
 
         # quick fix, http://trac.osgeo.org/grass/ticket/1233
         # TODO
@@ -849,20 +854,22 @@
              _("Collapse all except current"),
              _("Collapse all"),
              _("Expand all"))
-             
-        self.internalSettings['language']['locale']['choices'] = tuple(self.locs)
-        self.internalSettings['atm']['leftDbClick']['choices'] = (_('Edit selected record'),
-                                                                  _('Display selected'))
-        
+
+        self.internalSettings['language'][
+            'locale']['choices'] = tuple(self.locs)
+        self.internalSettings['atm']['leftDbClick']['choices'] = (
+            _('Edit selected record'), _('Display selected'))
+
         self.internalSettings['cmd']['verbosity']['choices'] = ('grassenv',
                                                                 'verbose',
                                                                 'quiet')
-                                                                
-        self.internalSettings['appearance']['iconTheme']['choices'] = ('grass',)
+
+        self.internalSettings['appearance'][
+            'iconTheme']['choices'] = ('grass',)
         self.internalSettings['appearance']['menustyle']['choices'] = \
-                   (_("Classic (labels only)"),
-                    _("Combined (labels and module names)"),
-                    _("Expert (module names only)"))
+            (_("Classic (labels only)"),
+             _("Combined (labels and module names)"),
+             _("Expert (module names only)"))
         self.internalSettings['appearance']['gSelectPopupHeight']['min'] = 50
         # there is also maxHeight given to TreeCtrlComboPopup.GetAdjustedSize
         self.internalSettings['appearance']['gSelectPopupHeight']['max'] = 1000
@@ -872,13 +879,14 @@
              _("Fancy green"),
              _("List left"))
 
-        self.internalSettings['display']['driver']['choices'] = ['cairo', 'png']
-        self.internalSettings['display']['statusbarMode']['choices'] = None # set during MapFrame init
-        self.internalSettings['display']['mouseWheelZoom']['choices'] = (_('Zoom and recenter'),
-                                                                         _('Zoom to mouse cursor'),
-                                                                         _('Nothing'))
-        self.internalSettings['display']['scrollDirection']['choices'] = (_('Scroll forward to zoom in'),
-                                                                         _('Scroll back to zoom in'))
+        self.internalSettings['display'][
+            'driver']['choices'] = ['cairo', 'png']
+        self.internalSettings['display']['statusbarMode'][
+            'choices'] = None  # set during MapFrame init
+        self.internalSettings['display']['mouseWheelZoom']['choices'] = (
+            _('Zoom and recenter'), _('Zoom to mouse cursor'), _('Nothing'))
+        self.internalSettings['display']['scrollDirection']['choices'] = (
+            _('Scroll forward to zoom in'), _('Scroll back to zoom in'))
 
         self.internalSettings['nviz']['view'] = {}
         self.internalSettings['nviz']['view']['twist'] = {}
@@ -901,7 +909,7 @@
         self.internalSettings['nviz']['view']['dir']['y'] = -1
         self.internalSettings['nviz']['view']['dir']['z'] = -1
         self.internalSettings['nviz']['view']['dir']['use'] = False
-        
+
         for decor in ('arrow', 'scalebar'):
             self.internalSettings['nviz'][decor] = {}
             self.internalSettings['nviz'][decor]['position'] = {}
@@ -922,26 +930,25 @@
         self.internalSettings['vdigit']['bgmap']['value'] = ''
 
         self.internalSettings['mapswipe']['cursor']['type'] = {}
-        self.internalSettings['mapswipe']['cursor']['type']['choices'] = (_("cross"),
-                                                                          _("box"),
-                                                                          _("circle"))
+        self.internalSettings['mapswipe']['cursor']['type'][
+            'choices'] = (_("cross"), _("box"), _("circle"))
 
-    def ReadSettingsFile(self, settings = None):
+    def ReadSettingsFile(self, settings=None):
         """Reads settings file (mapset, location, gisdbase)"""
         if settings is None:
             settings = self.userSettings
-        
+
         self._readFile(self.filePath, settings)
-        
+
         # set environment variables
-        font = self.Get(group = 'display', key = 'font', subkey = 'type')
-        enc  = self.Get(group = 'display', key = 'font', subkey = 'encoding')
+        font = self.Get(group='display', key='font', subkey='type')
+        enc = self.Get(group='display', key='font', subkey='encoding')
         if font:
             os.environ["GRASS_FONT"] = font
         if enc:
             os.environ["GRASS_ENCODING"] = enc
-        
-    def _readFile(self, filename, settings = None):
+
+    def _readFile(self, filename, settings=None):
         """Read settings from file to dict
 
         :param filename: settings file path
@@ -949,16 +956,18 @@
         """
         if settings is None:
             settings = self.userSettings
-        
+
         if not os.path.exists(filename):
             return
-        
+
         try:
             fd = open(filename, "r")
         except IOError:
-            sys.stderr.write(_("Unable to read settings file <%s>\n") % filename)
+            sys.stderr.write(
+                _("Unable to read settings file <%s>\n") %
+                filename)
             return
-        
+
         try:
             line = ''
             for line in fd.readlines():
@@ -966,7 +975,7 @@
                 group, key = line.split(self.sep)[0:2]
                 kv = line.split(self.sep)[2:]
                 subkeyMaster = None
-                if len(kv) % 2 != 0: # multiple (e.g. nviz)
+                if len(kv) % 2 != 0:  # multiple (e.g. nviz)
                     subkeyMaster = kv[0]
                     del kv[0]
                 idx = 0
@@ -975,25 +984,25 @@
                         subkey = [subkeyMaster, kv[idx]]
                     else:
                         subkey = kv[idx]
-                    value = kv[idx+1]
-                    value = self._parseValue(value, read = True)
+                    value = kv[idx + 1]
+                    value = self._parseValue(value, read=True)
                     self.Append(settings, group, key, subkey, value)
                     idx += 2
         except ValueError as e:
-            print >> sys.stderr, _("Error: Reading settings from file <%(file)s> failed.\n"
-                                   "\t\tDetails: %(detail)s\n"
-                                   "\t\tLine: '%(line)s'\n") % { 'file' : filename,
-                                                               'detail' : e,
-                                                               'line' : line }
+            print >>sys.stderr, _(
+                "Error: Reading settings from file <%(file)s> failed.\n"
+                "\t\tDetails: %(detail)s\n"
+                "\t\tLine: '%(line)s'\n") % {
+                'file': filename, 'detail': e, 'line': line}
             fd.close()
-        
+
         fd.close()
-        
-    def SaveToFile(self, settings = None):
+
+    def SaveToFile(self, settings=None):
         """Save settings to the file"""
         if settings is None:
             settings = self.userSettings
-        
+
         dirPath = GetSettingsPath()
         if not os.path.exists(dirPath):
             try:
@@ -1001,7 +1010,7 @@
             except:
                 GError(_('Unable to create settings directory'))
                 return
-        
+
         try:
             file = open(self.filePath, "w")
             for group in settings.keys():
@@ -1010,50 +1019,63 @@
                     file.write('%s%s%s%s' % (group, self.sep, key, self.sep))
                     for idx in range(len(subkeys)):
                         value = settings[group][key][subkeys[idx]]
-                        if type(value) == types.DictType:
+                        if isinstance(value, types.DictType):
                             if idx > 0:
-                                file.write('%s%s%s%s%s' % (os.linesep, group, self.sep, key, self.sep))
+                                file.write(
+                                    '%s%s%s%s%s' %
+                                    (os.linesep, group, self.sep, key, self.sep))
                             file.write('%s%s' % (subkeys[idx], self.sep))
                             kvalues = settings[group][key][subkeys[idx]].keys()
                             srange = range(len(kvalues))
                             for sidx in srange:
-                                svalue = self._parseValue(settings[group][key][subkeys[idx]][kvalues[sidx]])
+                                svalue = self._parseValue(
+                                    settings[group][key][
+                                        subkeys[idx]][
+                                        kvalues[sidx]])
                                 file.write('%s%s%s' % (kvalues[sidx], self.sep,
                                                        svalue))
                                 if sidx < len(kvalues) - 1:
                                     file.write('%s' % self.sep)
                         else:
-                            if idx > 0 and \
-                                    type(settings[group][key][subkeys[idx - 1]]) == types.DictType:
-                                file.write('%s%s%s%s%s' % (os.linesep, group, self.sep, key, self.sep))
-                            value = self._parseValue(settings[group][key][subkeys[idx]])
-                            file.write('%s%s%s' % (subkeys[idx], self.sep, value))
-                            if idx < len(subkeys) - 1 and \
-                                    type(settings[group][key][subkeys[idx + 1]]) != types.DictType:
+                            if idx > 0 and isinstance(
+                                    settings[group][key]
+                                    [subkeys[idx - 1]],
+                                    types.DictType):
+                                file.write(
+                                    '%s%s%s%s%s' %
+                                    (os.linesep, group, self.sep, key, self.sep))
+                            value = self._parseValue(
+                                settings[group][key][subkeys[idx]])
+                            file.write(
+                                '%s%s%s' %
+                                (subkeys[idx], self.sep, value))
+                            if idx < len(subkeys) - 1 and not isinstance(
+                                    settings[group][key][subkeys[idx + 1]],
+                                    types.DictType):
                                 file.write('%s' % self.sep)
                     file.write(os.linesep)
         except IOError as e:
             raise GException(e)
-        except StandardError as e:
+        except Exception as e:
             raise GException(_('Writing settings to file <%(file)s> failed.'
-                               '\n\nDetails: %(detail)s') % { 'file' : self.filePath,
-                                                              'detail' : e })
+                               '\n\nDetails: %(detail)s') %
+                             {'file': self.filePath, 'detail': e})
         file.close()
         return self.filePath
-        
-    def _parseValue(self, value, read = False):
+
+    def _parseValue(self, value, read=False):
         """Parse value to be store in settings file"""
-        if read: # -> read settings (cast values)
+        if read:  # -> read settings (cast values)
             if value == 'True':
                 value = True
             elif value == 'False':
                 value = False
             elif value == 'None':
                 value = None
-            elif ':' in value: # -> color
+            elif ':' in value:  # -> color
                 try:
                     value = tuple(map(int, value.split(':')))
-                except ValueError: # -> string
+                except ValueError:  # -> string
                     pass
             else:
                 try:
@@ -1063,12 +1085,12 @@
                         value = float(value)
                     except ValueError:
                         pass
-        else: # -> write settings
-            if type(value) == type(()): # -> color
+        else:  # -> write settings
+            if isinstance(value, type(())):  # -> color
                 value = str(value[0]) + ':' +\
                     str(value[1]) + ':' + \
                     str(value[2])
-                
+
         return value
 
     def Get(self, group, key=None, subkey=None, settings_type='user'):
@@ -1098,15 +1120,15 @@
                 else:
                     return settings[group][key]
             else:
-                if type(subkey) == type(tuple()) or \
-                        type(subkey) == type(list()):
+                if isinstance(subkey, type(tuple())) or \
+                        isinstance(subkey, type(list())):
                     return settings[group][key][subkey[0]][subkey[1]]
                 else:
                     return settings[group][key][subkey]
 
         except KeyError:
-            print >> sys.stderr, "Settings: unable to get value '%s:%s:%s'\n" % \
-                (group, key, subkey)
+            print >> sys.stderr, "Settings: unable to get value '%s:%s:%s'\n" % (
+                group, key, subkey)
 
     def Set(self, group, value, key=None, subkey=None, settings_type='user'):
         """Set value of key/subkey
@@ -1134,19 +1156,20 @@
                 else:
                     settings[group][key] = value
             else:
-                if type(subkey) == type(tuple()) or \
-                        type(subkey) == type(list()):
+                if isinstance(subkey, type(tuple())) or \
+                        isinstance(subkey, type(list())):
                     settings[group][key][subkey[0]][subkey[1]] = value
                 else:
                     settings[group][key][subkey] = value
         except KeyError:
-            raise GException("%s '%s:%s:%s'" % (_("Unable to set "), group, key, subkey))
+            raise GException("%s '%s:%s:%s'" %
+                             (_("Unable to set "), group, key, subkey))
 
-    def Append(self, dict, group, key, subkey, value, overwrite = True):
+    def Append(self, dict, group, key, subkey, value, overwrite=True):
         """Set value of key/subkey
 
         Create group/key/subkey if not exists
-        
+
         :param dict: settings dictionary to use
         :param group: settings group
         :param key: key
@@ -1159,19 +1182,19 @@
         if group not in dict:
             dict[group] = {}
             hasValue = False
-        
+
         if key not in dict[group]:
             dict[group][key] = {}
             hasValue = False
-        
-        if type(subkey) == types.ListType:
+
+        if isinstance(subkey, types.ListType):
             # TODO: len(subkey) > 2
             if subkey[0] not in dict[group][key]:
                 dict[group][key][subkey[0]] = {}
                 hasValue = False
             if subkey[1] not in dict[group][key][subkey[0]]:
                 hasValue = False
-            
+
             try:
                 if overwrite or (not overwrite and not hasValue):
                     dict[group][key][subkey[0]][subkey[1]] = value
@@ -1181,19 +1204,19 @@
         else:
             if subkey not in dict[group][key]:
                 hasValue = False
-            
+
             try:
                 if overwrite or (not overwrite and not hasValue):
                     dict[group][key][subkey] = value
             except TypeError:
                 print >> sys.stderr, _("Unable to parse settings '%s'") % value + \
                     ' (' + group + ':' + key + ':' + subkey + ')'
-        
+
     def GetDefaultSettings(self):
         """Get default user settings"""
         return self.defaultSettings
 
-    def Reset(self, key = None):
+    def Reset(self, key=None):
         """Reset to default settings
 
         :param key: key in settings dict (None for all keys)
@@ -1202,28 +1225,57 @@
             self.userSettings = copy.deepcopy(self.defaultSettings)
         else:
             self.userSettings[key] = copy.deepcopy(self.defaultSettings[key])
-        
+
 UserSettings = Settings()
 
+
 def GetDisplayVectSettings():
     settings = list()
-    if not UserSettings.Get(group = 'vectorLayer', key = 'featureColor', subkey = ['transparent', 'enabled']):
-        featureColor = UserSettings.Get(group = 'vectorLayer', key = 'featureColor', subkey = 'color')
-        settings.append('color=%s' % rgb2str.get(featureColor, ':'.join(map(str,featureColor))))
+    if not UserSettings.Get(
+            group='vectorLayer', key='featureColor',
+            subkey=['transparent', 'enabled']):
+        featureColor = UserSettings.Get(
+            group='vectorLayer',
+            key='featureColor',
+            subkey='color')
+        settings.append('color=%s' % rgb2str.get(
+            featureColor, ':'.join(map(str, featureColor))))
     else:
         settings.append('color=none')
-    if not UserSettings.Get(group = 'vectorLayer', key = 'areaFillColor', subkey = ['transparent', 'enabled']):
-        fillColor = UserSettings.Get(group = 'vectorLayer', key = 'areaFillColor', subkey = 'color')
-        settings.append('fcolor=%s' % rgb2str.get(fillColor, ':'.join(map(str,fillColor))))
+    if not UserSettings.Get(
+            group='vectorLayer', key='areaFillColor',
+            subkey=['transparent', 'enabled']):
+        fillColor = UserSettings.Get(
+            group='vectorLayer',
+            key='areaFillColor',
+            subkey='color')
+        settings.append('fcolor=%s' %
+                        rgb2str.get(fillColor, ':'.join(map(str, fillColor))))
     else:
         settings.append('fcolor=none')
-    
-    settings.append('width=%s' % UserSettings.Get(group = 'vectorLayer', key = 'line', subkey = 'width'))
-    settings.append('icon=%s' % UserSettings.Get(group = 'vectorLayer', key = 'point', subkey = 'symbol'))
-    settings.append('size=%s' % UserSettings.Get(group = 'vectorLayer', key = 'point', subkey = 'size'))
+
+    settings.append(
+        'width=%s' %
+        UserSettings.Get(
+            group='vectorLayer',
+            key='line',
+            subkey='width'))
+    settings.append(
+        'icon=%s' %
+        UserSettings.Get(
+            group='vectorLayer',
+            key='point',
+            subkey='symbol'))
+    settings.append(
+        'size=%s' %
+        UserSettings.Get(
+            group='vectorLayer',
+            key='point',
+            subkey='size'))
     types = []
     for ftype in ['point', 'line', 'boundary', 'centroid', 'area', 'face']:
-        if UserSettings.Get(group = 'vectorLayer', key = 'showType', subkey = [ftype, 'enabled']):
+        if UserSettings.Get(group='vectorLayer',
+                            key='showType', subkey=[ftype, 'enabled']):
             types.append(ftype)
     settings.append('type=%s' % ','.join(types))
 

Modified: grass/trunk/gui/wxpython/core/toolboxes.py
===================================================================
--- grass/trunk/gui/wxpython/core/toolboxes.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/toolboxes.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -44,9 +44,9 @@
 
 
 # this could be placed to functions
-mainMenuFile    = os.path.join(WXGUIDIR, 'xml', 'main_menu.xml')
-toolboxesFile   = os.path.join(WXGUIDIR, 'xml', 'toolboxes.xml')
-wxguiItemsFile  = os.path.join(WXGUIDIR, 'xml', 'wxgui_items.xml')
+mainMenuFile = os.path.join(WXGUIDIR, 'xml', 'main_menu.xml')
+toolboxesFile = os.path.join(WXGUIDIR, 'xml', 'toolboxes.xml')
+wxguiItemsFile = os.path.join(WXGUIDIR, 'xml', 'wxgui_items.xml')
 moduleItemsFile = os.path.join(WXGUIDIR, 'xml', 'module_items.xml')
 
 
@@ -62,15 +62,20 @@
         # (these files are always check for existence here)
         return ""
 
+
 def _getUserToolboxesFile():
-    userToolboxesFile = os.path.join(GetSettingsPath(), 'toolboxes', 'toolboxes.xml')
+    userToolboxesFile = os.path.join(
+        GetSettingsPath(),
+        'toolboxes', 'toolboxes.xml')
     if not os.path.exists(userToolboxesFile):
         userToolboxesFile = None
     return userToolboxesFile
 
 
 def _getUserMainMenuFile():
-    userMainMenuFile = os.path.join(GetSettingsPath(), 'toolboxes', 'main_menu.xml')
+    userMainMenuFile = os.path.join(
+        GetSettingsPath(),
+        'toolboxes', 'main_menu.xml')
     if not os.path.exists(userMainMenuFile):
         userMainMenuFile = None
     return userMainMenuFile
@@ -144,7 +149,10 @@
     If something goes wrong during building or user doesn't modify menu,
     default file (from distribution) is returned.
     """
-    _debug(1, "toolboxes.getMenudataFile: {userRootFile}, {newFile}, {fallback}".format(**locals()))
+    _debug(
+        1,
+        "toolboxes.getMenudataFile: {userRootFile}, {newFile}, {fallback}".format(
+            **locals()))
 
     distributionRootFile = os.path.join(WXGUIDIR, 'xml', userRootFile)
     userRootFile = os.path.join(GetSettingsPath(), 'toolboxes', userRootFile)
@@ -164,23 +172,29 @@
             # remove menu file when there is no main_menu and toolboxes
             if not _getUserToolboxesFile() and not userRootFile:
                 os.remove(menudataFile)
-                _debug(2, "toolboxes.getMenudataFile: no user defined files, menudata deleted")
+                _debug(
+                    2, "toolboxes.getMenudataFile: no user defined files, menudata deleted")
                 return fallback
 
             if bool(_getUserToolboxesFile()) != bool(userRootFile):
-                # always generate new because we don't know if there has been any change
+                # always generate new because we don't know if there has been
+                # any change
                 generateNew = True
-                _debug(2, "toolboxes.getMenudataFile: only one of the user defined files")
+                _debug(
+                    2, "toolboxes.getMenudataFile: only one of the user defined files")
             else:
                 # if newer files -> generate new
                 menudataTime = os.path.getmtime(menudataFile)
                 if _getUserToolboxesFile():
-                    if os.path.getmtime(_getUserToolboxesFile()) > menudataTime:
-                        _debug(2, "toolboxes.getMenudataFile: user toolboxes is newer than menudata")
+                    if os.path.getmtime(
+                            _getUserToolboxesFile()) > menudataTime:
+                        _debug(
+                            2, "toolboxes.getMenudataFile: user toolboxes is newer than menudata")
                         generateNew = True
                 if userRootFile:
                     if os.path.getmtime(userRootFile) > menudataTime:
-                        _debug(2, "toolboxes.getMenudataFile: user root file is newer than menudata")
+                        _debug(
+                            2, "toolboxes.getMenudataFile: user root file is newer than menudata")
                         generateNew = True
         elif _getUserToolboxesFile() or userRootFile:
             _debug(2, "toolboxes.getMenudataFile: no menudata")
@@ -196,7 +210,9 @@
                 # Unfortunately, this is the case can be often: defined
                 # toolboxes but undefined module tree file.
                 _debug(2, "toolboxes.getMenudataFile: creating a tree")
-                tree = createTree(distributionRootFile=distributionRootFile, userRootFile=userRootFile)
+                tree = createTree(
+                    distributionRootFile=distributionRootFile,
+                    userRootFile=userRootFile)
             except ETREE_EXCEPTIONS:
                 _warning(_("Unable to parse user toolboxes XML files. "
                            "Default files will be loaded."))
@@ -209,7 +225,9 @@
                 fh.close()
                 return menudataFile
             except:
-                _debug(2, "toolboxes.getMenudataFile: writing menudata failed, returning fallback file")
+                _debug(
+                    2,
+                    "toolboxes.getMenudataFile: writing menudata failed, returning fallback file")
                 return fallback
         else:
             return menudataFile
@@ -236,10 +254,12 @@
         try:
             os.mkdir(path)
         except OSError as e:
-            # we cannot use GError or similar because the gui doesn't start at all
-            gcore.warning('%(reason)s\n%(detail)s' % 
-                    ({'reason':_('Unable to create toolboxes directory.'),
-                      'detail': str(e)}))
+            # we cannot use GError or similar because the gui doesn't start at
+            # all
+            gcore.warning(
+                '%(reason)s\n%(detail)s' % ({
+                    'reason': _('Unable to create toolboxes directory.'),
+                    'detail': str(e)}))
             return False
     return True
 
@@ -422,7 +442,9 @@
             idx = items.getchildren().index(subtoolbox)
 
             if has_xpath:
-                toolbox = toolboxes.find('.//toolbox[@name="%s"]' % subtoolbox.get('name'))
+                toolbox = toolboxes.find(
+                    './/toolbox[@name="%s"]' %
+                    subtoolbox.get('name'))
             else:
                 toolbox = None
                 potentialToolboxes = toolboxes.findall('.//toolbox')
@@ -455,7 +477,9 @@
     for n in node.findall('./items/user-toolboxes-list'):
         items = node.find('./items')
         idx = items.getchildren().index(n)
-        el = etree.Element('toolbox', attrib={'name': 'GeneratedUserToolboxesList'})
+        el = etree.Element(
+            'toolbox', attrib={
+                'name': 'GeneratedUserToolboxesList'})
         items.insert(idx, el)
         label = etree.SubElement(el, tag='label')
         label.text = _("Custom toolboxes")
@@ -485,14 +509,14 @@
         _warning(_("List of addons cannot be obtained"
                    " because g.extension failed."))
         return []
-    
+
     flist = []
     for line in output.splitlines():
         if not line.startswith('executables'):
             continue
         for fexe in line.split('=', 1)[1].split(','):
             flist.append(fexe)
-    
+
     return sorted(flist)
 
 
@@ -616,13 +640,15 @@
             n.text = _escapeXML(','.join(keywords))
             if loadMetadata and not desc:
                 hasErrors = True
-    
+
     if hasErrors:
         # not translatable until toolboxes compilation on Mac is fixed
         # translating causes importing globalvar, where sys.exit is called
-        sys.stderr.write("WARNING: Some addons failed when loading. "
-                         "Please consider to update your addons by running 'g.extension.all -f'.\n")
+        sys.stderr.write(
+            "WARNING: Some addons failed when loading. "
+            "Please consider to update your addons by running 'g.extension.all -f'.\n")
 
+
 def _escapeXML(text):
     """Helper function for correct escaping characters for XML.
 
@@ -786,10 +812,10 @@
     """Tests the module using test files included in the current
     directory and in files from distribution.
     """
-    toolboxesFile   = os.path.join(WXGUIDIR, 'xml', 'toolboxes.xml')
+    toolboxesFile = os.path.join(WXGUIDIR, 'xml', 'toolboxes.xml')
     userToolboxesFile = 'data/test_toolboxes_user_toolboxes.xml'
     menuFile = 'data/test_toolboxes_menu.xml'
-    wxguiItemsFile  = os.path.join(WXGUIDIR, 'xml', 'wxgui_items.xml')
+    wxguiItemsFile = os.path.join(WXGUIDIR, 'xml', 'wxgui_items.xml')
     moduleItemsFile = os.path.join(WXGUIDIR, 'xml', 'module_items.xml')
 
     toolboxes = etree.parse(toolboxesFile)

Modified: grass/trunk/gui/wxpython/core/treemodel.py
===================================================================
--- grass/trunk/gui/wxpython/core/treemodel.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/treemodel.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -19,11 +19,11 @@
 
 class TreeModel(object):
     """Class represents a tree structure with hidden root.
-    
+
     TreeModel is used together with TreeView class to display results in GUI.
     The functionality is not complete, only needed methods are implemented.
     If needed, the functionality can be extended.
-    
+
     >>> tree = TreeModel(DictNode)
     >>> root = tree.root
     >>> n1 = tree.AppendNode(parent=root, label='node1')
@@ -52,6 +52,7 @@
       node21
         * xxx : 1
     """
+
     def __init__(self, nodeClass):
         """Constructor creates root node.
 
@@ -66,11 +67,11 @@
 
     def AppendNode(self, parent, label, data=None):
         """Create node and append it to parent node.
-        
+
         :param parent: parent node of the new node
         :param label: node label
         :param data: optional node data
-        
+
         :return: new node
         """
         node = self.nodeClass(label=label, data=data)
@@ -84,7 +85,7 @@
         parent = parent if parent else self.root
         self._searchNodes(node=parent, foundNodes=nodes, **kwargs)
         return nodes
-        
+
     def _searchNodes(self, node, foundNodes, **kwargs):
         """Helper method for searching nodes."""
         if node.match(**kwargs):
@@ -101,27 +102,25 @@
         if len(index) == 0:
             return self.root
         return self._getNode(self.root, index)
-        
+
     def GetIndexOfNode(self, node):
         """Method used for communication between view (VirtualTree) and model."""
         index = []
         return self._getIndex(node, index)
-        
-        
+
     def _getIndex(self, node, index):
         if node.parent:
             index.insert(0, node.parent.children.index(node))
             return self._getIndex(node.parent, index)
         return index
-        
-        
+
     def GetChildrenByIndex(self, index):
         """Method used for communication between view (VirtualTree) and model."""
         if len(index) == 0:
             return self.root.children
         node = self._getNode(self.root, index)
         return node.children
-        
+
     def _getNode(self, node, index):
         if len(index) == 1:
             return node.children[index[0]]
@@ -152,6 +151,7 @@
 
 class DictNode(object):
     """Node which has data in a form of dictionary."""
+
     def __init__(self, label, data=None):
         """Create node.
 
@@ -160,7 +160,7 @@
         """
 
         self.label = label
-        if data == None:
+        if data is None:
             self.data = dict()
         else:
             self.data = data
@@ -175,9 +175,9 @@
         text.append(indent * ' ' + self.label)
         if self.data:
             for key, value in self.data.iteritems():
-                text.append("%(indent)s* %(key)s : %(value)s" % {'indent': (indent + 2) * ' ',
-                                                                 'key': key,
-                                                                 'value': value})
+                text.append(
+                    "%(indent)s* %(key)s : %(value)s" %
+                    {'indent': (indent + 2) * ' ', 'key': key, 'value': value})
 
         if self.children:
             for child in self.children:
@@ -196,6 +196,7 @@
 
 class ModuleNode(DictNode):
     """Node representing module."""
+
     def __init__(self, label, data=None):
         super(ModuleNode, self).__init__(label=label, data=data)
 
@@ -206,13 +207,15 @@
             return False
         if key in ('command', 'keywords', 'description'):
             try:
-                return len(self.data[key]) and (value in self.data[key] or value == '*')
+                return len(
+                    self.data[key]) and(
+                    value in self.data[key] or value == '*')
             except KeyError:
                 return False
-        
+
         return False
-            
-        
+
+
 def main():
     import doctest
     doctest.testmod()

Modified: grass/trunk/gui/wxpython/core/units.py
===================================================================
--- grass/trunk/gui/wxpython/core/units.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/units.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -29,42 +29,43 @@
 
 from core.utils import _
 
+
 class BaseUnits:
+
     def __init__(self):
         self._units = dict()
-        self._units['length'] = { 0 : { 'key' : 'mu', 'label' : _('map units') },
-                             1 : { 'key' : 'me', 'label' : _('meters') },
-                             2 : { 'key' : 'km', 'label' : _('kilometers') },
-                             3 : { 'key' : 'mi', 'label' : _('miles') },
-                             4 : { 'key' : 'ft', 'label' : _('feet') } }
-        
-        self._units['area']   = { 0 : { 'key' : 'mu', 'label' : _('sq map units') },
-                             1 : { 'key' : 'me', 'label' : _('sq meters') },
-                             2 : { 'key' : 'km', 'label' : _('sq kilometers') },
-                             3 : { 'key' : 'ar', 'label' : _('acres') },
-                             4 : { 'key' : 'ht', 'label' : _('hectares') } }
+        self._units['length'] = {0: {'key': 'mu', 'label': _('map units')},
+                                 1: {'key': 'me', 'label': _('meters')},
+                                 2: {'key': 'km', 'label': _('kilometers')},
+                                 3: {'key': 'mi', 'label': _('miles')},
+                                 4: {'key': 'ft', 'label': _('feet')}}
 
+        self._units['area'] = {0: {'key': 'mu', 'label': _('sq map units')},
+                               1: {'key': 'me', 'label': _('sq meters')},
+                               2: {'key': 'km', 'label': _('sq kilometers')},
+                               3: {'key': 'ar', 'label': _('acres')},
+                               4: {'key': 'ht', 'label': _('hectares')}}
+
     def GetUnitsList(self, type):
         """Get list of units (their labels)
-        
+
         :param type: units type ('length' or 'area')
-        
+
         :return: list of units labels
         """
         result = list()
         try:
-            keys = self._units[type].keys()
-            keys.sort()
+            keys = sorted(self._units[type].keys())
             for idx in keys:
                 result.append(self._units[type][idx]['label'])
         except KeyError:
             pass
-        
+
         return result
 
     def GetUnitsKey(self, type, index):
         """Get units key based on index
-        
+
         :param type: units type ('length' or 'area')
         :param index: units index
         """
@@ -72,7 +73,7 @@
 
     def GetUnitsIndex(self, type, key):
         """Get units index based on key
-        
+
         :param type: units type ('length' or 'area')
         :param key: units key, e.g. 'me' for meters
 
@@ -85,6 +86,7 @@
 
 Units = BaseUnits()
 
+
 def ConvertValue(value, type, units):
     """Convert value from map units to given units
 
@@ -96,7 +98,7 @@
     """
     # get map units
     # TODO
-    
+
     f = 1
     if type == 'length':
         if units == 'me':
@@ -107,7 +109,7 @@
             f = 6.21371192237334e-4
         elif units == 'ft':
             f = 3.28083989501312
-    else: # -> area
+    else:  # -> area
         if units == 'me':
             f = 1.0
         elif units == 'km':
@@ -125,80 +127,80 @@
 
 
 def formatDist(distance, mapunits):
-        """Formats length numbers and units in a nice way.
+    """Formats length numbers and units in a nice way.
 
-        Formats length numbers and units as a function of length.
+    Formats length numbers and units as a function of length.
 
-        >>> formatDist(20.56915, 'metres')
-        (20.57, 'm')
-        >>> formatDist(6983.4591, 'metres')
-        (6.983, 'km')
-        >>> formatDist(0.59, 'feet')
-        (0.59, 'ft')
-        >>> formatDist(8562, 'feet')
-        (1.622, 'miles')
-        >>> formatDist(0.48963, 'degrees')
-        (29.38, 'min')
-        >>> formatDist(20.2546, 'degrees')
-        (20.25, 'deg')
-        >>> formatDist(82.146, 'unknown')
-        (82.15, 'units')
+    >>> formatDist(20.56915, 'metres')
+    (20.57, 'm')
+    >>> formatDist(6983.4591, 'metres')
+    (6.983, 'km')
+    >>> formatDist(0.59, 'feet')
+    (0.59, 'ft')
+    >>> formatDist(8562, 'feet')
+    (1.622, 'miles')
+    >>> formatDist(0.48963, 'degrees')
+    (29.38, 'min')
+    >>> formatDist(20.2546, 'degrees')
+    (20.25, 'deg')
+    >>> formatDist(82.146, 'unknown')
+    (82.15, 'units')
 
-        Accepted map units are 'meters', 'metres', 'feet', 'degree'.
-        Returns 'units' instead of unrecognized units.
+    Accepted map units are 'meters', 'metres', 'feet', 'degree'.
+    Returns 'units' instead of unrecognized units.
 
-        :param distance: map units
-        :param mapunits: map units
+    :param distance: map units
+    :param mapunits: map units
 
-        From code by Hamish Bowman Grass Development Team 2006.
-        """
-        if mapunits == 'metres':
-            mapunits = 'meters'
-        outunits = mapunits
-        distance = float(distance)
-        divisor = 1.0
+    From code by Hamish Bowman Grass Development Team 2006.
+    """
+    if mapunits == 'metres':
+        mapunits = 'meters'
+    outunits = mapunits
+    distance = float(distance)
+    divisor = 1.0
 
-        # figure out which units to use
-        if mapunits == 'meters':
-            if distance > 2500.0:
-                outunits = 'km'
-                divisor = 1000.0
-            else:
-                outunits = 'm'
-        elif mapunits == 'feet':
-            # nano-bug: we match any "feet", but US Survey feet is really
-            #  5279.9894 per statute mile, or 10.6' per 1000 miles. As >1000
-            #  miles the tick markers are rounded to the nearest 10th of a
-            #  mile (528'), the difference in foot flavours is ignored.
-            if distance > 5280.0:
-                outunits = 'miles'
-                divisor = 5280.0
-            else:
-                outunits = 'ft'
-        elif 'degree' in mapunits:
-            # was: 'degree' in mapunits and not haveCtypes (for unknown reason)
-            if distance < 1:
-                outunits = 'min'
-                divisor = (1 / 60.0)
-            else:
-                outunits = 'deg'
+    # figure out which units to use
+    if mapunits == 'meters':
+        if distance > 2500.0:
+            outunits = 'km'
+            divisor = 1000.0
         else:
-            return (distance, 'units')
-
-        # format numbers in a nice way
-        if (distance / divisor) >= 2500.0:
-            outdistance = round(distance / divisor)
-        elif (distance / divisor) >= 1000.0:
-            outdistance = round(distance / divisor, 1)
-        elif (distance / divisor) > 0.0:
-            outdistance = round(distance / divisor,
-                                int(math.ceil(3 - math.log10(distance / divisor))))
+            outunits = 'm'
+    elif mapunits == 'feet':
+        # nano-bug: we match any "feet", but US Survey feet is really
+        #  5279.9894 per statute mile, or 10.6' per 1000 miles. As >1000
+        #  miles the tick markers are rounded to the nearest 10th of a
+        #  mile (528'), the difference in foot flavours is ignored.
+        if distance > 5280.0:
+            outunits = 'miles'
+            divisor = 5280.0
         else:
-            outdistance = float(distance / divisor)
+            outunits = 'ft'
+    elif 'degree' in mapunits:
+        # was: 'degree' in mapunits and not haveCtypes (for unknown reason)
+        if distance < 1:
+            outunits = 'min'
+            divisor = (1 / 60.0)
+        else:
+            outunits = 'deg'
+    else:
+        return (distance, 'units')
 
-        return (outdistance, outunits)
+    # format numbers in a nice way
+    if (distance / divisor) >= 2500.0:
+        outdistance = round(distance / divisor)
+    elif (distance / divisor) >= 1000.0:
+        outdistance = round(distance / divisor, 1)
+    elif (distance / divisor) > 0.0:
+        outdistance = round(distance / divisor,
+                            int(math.ceil(3 - math.log10(distance / divisor))))
+    else:
+        outdistance = float(distance / divisor)
 
+    return (outdistance, outunits)
 
+
 def doc_test():
     """Tests the module using doctest
 

Modified: grass/trunk/gui/wxpython/core/utils.py
===================================================================
--- grass/trunk/gui/wxpython/core/utils.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/utils.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -26,23 +26,29 @@
 from grass.exceptions import OpenError
 
 from core import globalvar
-from core.gcmd  import RunCommand
+from core.gcmd import RunCommand
 from core.debug import Debug
 
 try:
     # intended to be used also outside this module
     import gettext
-    _ = gettext.translation('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale')).ugettext
+    _ = gettext.translation(
+        'grasswxpy',
+        os.path.join(
+            os.getenv("GISBASE"),
+            'locale')).ugettext
 except IOError:
     # using no translation silently
     def null_gettext(string):
         return string
     _ = null_gettext
 
+
 def normalize_whitespace(text):
     """Remove redundant whitespace from a string"""
     return string.join(string.split(text), ' ')
 
+
 def split(s):
     """Platform spefic shlex.split"""
     try:
@@ -52,9 +58,10 @@
             return shlex.split(s)
     except ValueError as e:
         sys.stderr.write(_("Syntax error: %s") % e)
-    
+
     return []
 
+
 def GetTempfile(pref=None):
     """Creates GRASS temporary file using defined prefix.
 
@@ -66,8 +73,8 @@
     :return: Path to file name (string) or None
     """
     ret = RunCommand('g.tempfile',
-                     read = True,
-                     pid = os.getpid())
+                     read=True,
+                     pid=os.getpid())
 
     tempfile = ret.splitlines()[0].strip()
 
@@ -84,27 +91,28 @@
     except:
         return None
 
-def GetLayerNameFromCmd(dcmd, fullyQualified = False, param = None,
-                        layerType = None):
+
+def GetLayerNameFromCmd(dcmd, fullyQualified=False, param=None,
+                        layerType=None):
     """Get map name from GRASS command
-    
+
     Parameter dcmd can be modified when first parameter is not
     defined.
-    
+
     :param dcmd: GRASS command (given as list)
     :param fullyQualified: change map name to be fully qualified
     :param param: params directory
     :param str layerType: check also layer type ('raster', 'vector',
                           'raster_3d', ...)
-    
+
     :return: tuple (name, found)
     """
     mapname = ''
-    found   = True
-    
+    found = True
+
     if len(dcmd) < 1:
         return mapname, False
-    
+
     if 'd.grid' == dcmd[0]:
         mapname = 'grid'
     elif 'd.geodesic' in dcmd[0]:
@@ -120,7 +128,7 @@
                 p, v = dcmd[idx].split('=', 1)
             except ValueError:
                 continue
-            
+
             if p == param:
                 params = [(idx, p, v)]
                 break
@@ -157,7 +165,8 @@
             mapname = v
             mapset = ''
             if fullyQualified and '@' not in mapname:
-                if layerType in ('raster', 'vector', 'raster_3d', 'rgb', 'his'):
+                if layerType in ('raster', 'vector',
+                                 'raster_3d', 'rgb', 'his'):
                     try:
                         if layerType in ('raster', 'rgb', 'his'):
                             findType = 'cell'
@@ -165,15 +174,16 @@
                             findType = 'grid3'
                         else:
                             findType = layerType
-                        mapset = grass.find_file(mapname, element = findType)['mapset']
-                    except AttributeError: # not found
+                        mapset = grass.find_file(
+                            mapname, element=findType)['mapset']
+                    except AttributeError:  # not found
                         return '', False
                     if not mapset:
                         found = False
                 else:
-                    mapset = '' # grass.gisenv()['MAPSET']
+                    mapset = ''  # grass.gisenv()['MAPSET']
             mapsets[i] = mapset
-            
+
         # update dcmd
         for i, p, v in params:
             if p == 'layer':
@@ -181,7 +191,7 @@
             dcmd[i] = p + '=' + v
             if i in mapsets and mapsets[i]:
                 dcmd[i] += '@' + mapsets[i]
-        
+
         maps = list()
         ogr = False
         for i, p, v in params:
@@ -190,44 +200,46 @@
             if p == 'layer' and not ogr:
                 continue
             maps.append(dcmd[i].split('=', 1)[1])
-        
+
         mapname = '\n'.join(maps)
-    
+
     return mapname, found
 
+
 def GetValidLayerName(name):
     """Make layer name SQL compliant, based on G_str_to_sql()
-    
+
     .. todo::
         Better use directly Ctypes to reuse venerable libgis C fns...
     """
     retName = name.strip()
-    
+
     # check if name is fully qualified
     if '@' in retName:
         retName, mapset = retName.split('@')
     else:
         mapset = None
-    
+
     cIdx = 0
     retNameList = list(retName)
     for c in retNameList:
         if not (c >= 'A' and c <= 'Z') and \
-               not (c >= 'a' and c <= 'z') and \
-               not (c >= '0' and c <= '9'):
+                not (c >= 'a' and c <= 'z') and \
+                not (c >= '0' and c <= '9'):
             retNameList[cIdx] = '_'
         cIdx += 1
     retName = ''.join(retNameList)
-    
+
     if not (retName[0] >= 'A' and retName[0] <= 'Z') and \
-           not (retName[0] >= 'a' and retName[0] <= 'z'):
+            not (retName[0] >= 'a' and retName[0] <= 'z'):
         retName = 'x' + retName[1:]
 
     if mapset:
         retName = retName + '@' + mapset
-        
+
     return retName
 
+
 def ListOfCatsToRange(cats):
     """Convert list of category number to range(s)
 
@@ -263,38 +275,39 @@
         else:
             catstr += '%d,' % (cats[i])
             i += 1
-        
+
     return catstr.strip(',')
 
-def ListOfMapsets(get = 'ordered'):
+
+def ListOfMapsets(get='ordered'):
     """Get list of available/accessible mapsets
 
     :param str get: method ('all', 'accessible', 'ordered')
-    
+
     :return: list of mapsets
     :return: None on error
     """
     mapsets = []
-    
+
     if get == 'all' or get == 'ordered':
         ret = RunCommand('g.mapsets',
-                         read = True,
-                         quiet = True,
-                         flags = 'l',
-                         sep = 'newline')
-        
+                         read=True,
+                         quiet=True,
+                         flags='l',
+                         sep='newline')
+
         if ret:
             mapsets = ret.splitlines()
             ListSortLower(mapsets)
         else:
             return None
-        
+
     if get == 'accessible' or get == 'ordered':
         ret = RunCommand('g.mapsets',
-                         read = True,
-                         quiet = True,
-                         flags = 'p',
-                         sep = 'newline')
+                         read=True,
+                         quiet=True,
+                         flags='p',
+                         sep='newline')
         if ret:
             if get == 'accessible':
                 mapsets = ret.splitlines()
@@ -305,44 +318,52 @@
                 mapsets = mapsets_accessible + mapsets
         else:
             return None
-    
+
     return mapsets
 
+
 def ListSortLower(list):
     """Sort list items (not case-sensitive)"""
     list.sort(cmp=lambda x, y: cmp(x.lower(), y.lower()))
 
+
 def GetVectorNumberOfLayers(vector):
     """Get list of all vector layers"""
     layers = list()
     if not vector:
         return layers
-    
-    fullname = grass.find_file(name = vector, element = 'vector')['fullname']
+
+    fullname = grass.find_file(name=vector, element='vector')['fullname']
     if not fullname:
-        Debug.msg(5, "utils.GetVectorNumberOfLayers(): vector map '%s' not found" % vector)
+        Debug.msg(
+            5,
+            "utils.GetVectorNumberOfLayers(): vector map '%s' not found" %
+            vector)
         return layers
-    
+
     ret, out, msg = RunCommand('v.category',
-                               getErrorMsg = True,
-                               read = True,
-                               input = fullname,
-                               option = 'layers')
+                               getErrorMsg=True,
+                               read=True,
+                               input=fullname,
+                               option='layers')
     if ret != 0:
-        sys.stderr.write(_("Vector map <%(map)s>: %(msg)s\n") % { 'map' : fullname, 'msg' : msg })
+        sys.stderr.write(
+            _("Vector map <%(map)s>: %(msg)s\n") %
+            {'map': fullname, 'msg': msg})
         return layers
     else:
         Debug.msg(1, "GetVectorNumberOfLayers(): ret %s" % ret)
-    
+
     for layer in out.splitlines():
         layers.append(layer)
-    
-    Debug.msg(3, "utils.GetVectorNumberOfLayers(): vector=%s -> %s" % \
-                  (fullname, ','.join(layers)))
-    
+
+    Debug.msg(3, "utils.GetVectorNumberOfLayers(): vector=%s -> %s" %
+              (fullname, ','.join(layers)))
+
     return layers
 
-def Deg2DMS(lon, lat, string = True, hemisphere = True, precision = 3):
+
+def Deg2DMS(lon, lat, string=True, hemisphere=True, precision=3):
     """Convert deg value to dms string
 
     :param lon: longitude (x)
@@ -350,7 +371,7 @@
     :param string: True to return string otherwise tuple
     :param hemisphere: print hemisphere
     :param precision: seconds precision
-    
+
     :return: DMS string or tuple of values
     :return: empty string on error
     """
@@ -387,43 +408,45 @@
         flon = abs(flon)
         hlon = ''
         hlat = ''
-    
-    slat = __ll_parts(flat, precision = precision)
-    slon = __ll_parts(flon, precision = precision)
 
+    slat = __ll_parts(flat, precision=precision)
+    slon = __ll_parts(flon, precision=precision)
+
     if string:
         return slon + hlon + '; ' + slat + hlat
-    
+
     return (slon + hlon, slat + hlat)
 
+
 def DMS2Deg(lon, lat):
     """Convert dms value to deg
 
     :param lon: longitude (x)
     :param lat: latitude (y)
-    
+
     :return: tuple of converted values
     :return: ValueError on error
     """
-    x = __ll_parts(lon, reverse = True)
-    y = __ll_parts(lat, reverse = True)
-    
+    x = __ll_parts(lon, reverse=True)
+    y = __ll_parts(lat, reverse=True)
+
     return (x, y)
 
-def __ll_parts(value, reverse = False, precision = 3):
+
+def __ll_parts(value, reverse=False, precision=3):
     """Converts deg to d:m:s string
 
     :param value: value to be converted
     :param reverse: True to convert from d:m:s to deg
     :param precision: seconds precision (ignored if reverse is True)
-    
+
     :return: converted value (string/float)
     :return: ValueError on error (reverse == True)
     """
     if not reverse:
         if value == 0.0:
             return '%s%.*f' % ('00:00:0', precision, 0.0)
-    
+
         d = int(int(value))
         m = int((value - d) * 60)
         s = ((value - d) * 60 - m) * 60
@@ -439,9 +462,9 @@
             s = '0%.*f' % (precision, s)
         else:
             s = '%.*f' % (precision, s)
-        
+
         return str(d) + ':' + m + ':' + s
-    else: # -> reverse
+    else:  # -> reverse
         try:
             d, m, s = value.split(':')
             hs = s[-1]
@@ -461,37 +484,40 @@
                     s = '0.0'
                 except ValueError:
                     raise ValueError
-        
+
         if hs not in ('N', 'S', 'E', 'W'):
             raise ValueError
-        
+
         coef = 1.0
         if hs in ('S', 'W'):
             coef = -1.0
-        
+
         fm = int(m) / 60.0
         fs = float(s) / (60 * 60)
-        
+
         return coef * (float(d) + fm + fs)
-    
+
+
 def GetCmdString(cmd):
     """Get GRASS command as string.
-    
+
     :param cmd: GRASS command given as tuple
-    
+
     :return: command string
     """
     return ' '.join(gtask.cmdtuple_to_list(cmd))
 
+
 def PathJoin(*args):
     """Check path created by os.path.join"""
     path = os.path.join(*args)
     if platform.system() == 'Windows' and \
             '/' in path:
         return path[1].upper() + ':\\' + path[3:].replace('/', '\\')
-    
+
     return path
 
+
 def ReadEpsgCodes(path):
     """Read EPSG code from the file
 
@@ -513,7 +539,7 @@
             line = line.strip()
             if len(line) < 1:
                 continue
-                
+
             if line[0] == '#':
                 descr = line[1:].strip()
             elif line[0] == '<':
@@ -522,18 +548,19 @@
                     code = int(code.replace('<', '').replace('>', ''))
                 except ValueError as e:
                     raise OpenError('{}'.format(e))
-            
+
             if code is not None:
                 epsgCodeDict[code] = (descr, params)
                 code = None
-        
+
         f.close()
-    except StandardError as e:
+    except Exception as e:
         raise OpenError('{}'.format(e))
-    
+
     return epsgCodeDict
 
-def ReprojectCoordinates(coord, projOut, projIn = None, flags = ''):
+
+def ReprojectCoordinates(coord, projOut, projIn=None, flags=''):
     """Reproject coordinates
 
     :param coord: coordinates given as tuple
@@ -543,13 +570,13 @@
     :return: reprojected coordinates (returned as tuple)
     """
     coors = RunCommand('m.proj',
-                       flags = flags,
-                       input = '-',
-                       proj_in = projIn,
-                       proj_out = projOut,
-                       sep = ';',
-                       stdin = '%f;%f' % (coord[0], coord[1]),
-                       read = True)
+                       flags=flags,
+                       input='-',
+                       proj_in=projIn,
+                       proj_out=projOut,
+                       sep=';',
+                       stdin='%f;%f' % (coord[0], coord[1]),
+                       read=True)
     if coors:
         coors = coors.split(';')
         e = coors[0]
@@ -565,9 +592,10 @@
                 return (proj, (float(e), float(n)))
             except ValueError:
                 return (None, None)
-    
+
     return (None, None)
 
+
 def GetListOfLocations(dbase):
     """Get list of GRASS locations in given dbase
 
@@ -580,18 +608,21 @@
     try:
         for location in glob.glob(os.path.join(dbase, "*")):
             try:
-                if os.path.join(location, "PERMANENT") in glob.glob(os.path.join(location, "*")):
+                if os.path.join(
+                        location, "PERMANENT") in glob.glob(
+                        os.path.join(location, "*")):
                     listOfLocations.append(os.path.basename(location))
             except:
                 pass
     except UnicodeEncodeError as e:
         raise e
-    
+
     ListSortLower(listOfLocations)
-    
+
     return listOfLocations
 
-def GetListOfMapsets(dbase, location, selectable = False):
+
+def GetListOfMapsets(dbase, location, selectable=False):
     """Get list of mapsets in given GRASS location
 
     :param dbase: GRASS database path
@@ -601,80 +632,84 @@
     :return: list of mapsets - sorted (PERMANENT first)
     """
     listOfMapsets = list()
-    
+
     if selectable:
         ret = RunCommand('g.mapset',
-                         read = True,
-                         flags = 'l',
-                         location = location,
-                         dbase = dbase)
-        
+                         read=True,
+                         flags='l',
+                         location=location,
+                         dbase=dbase)
+
         if not ret:
             return listOfMapsets
-        
+
         for line in ret.rstrip().splitlines():
             listOfMapsets += line.split(' ')
     else:
         for mapset in glob.glob(os.path.join(dbase, location, "*")):
-            if os.path.isdir(mapset) and \
-                    os.path.isfile(os.path.join(dbase, location, mapset, "WIND")):
+            if os.path.isdir(mapset) and os.path.isfile(
+                    os.path.join(dbase, location, mapset, "WIND")):
                 listOfMapsets.append(os.path.basename(mapset))
-    
+
     ListSortLower(listOfMapsets)
     return listOfMapsets
 
+
 def GetColorTables():
     """Get list of color tables"""
     ret = RunCommand('r.colors',
-                     read = True,
-                     flags = 'l')
+                     read=True,
+                     flags='l')
     if not ret:
         return list()
-    
+
     return ret.splitlines()
 
+
 def _getGDALFormats():
     """Get dictionary of avaialble GDAL drivers"""
     try:
         ret = grass.read_command('r.in.gdal',
-                                 quiet = True,
-                                 flags = 'f')
+                                 quiet=True,
+                                 flags='f')
     except:
         ret = None
-    
-    return _parseFormats(ret), _parseFormats(ret, writableOnly = True)
 
+    return _parseFormats(ret), _parseFormats(ret, writableOnly=True)
+
+
 def _getOGRFormats():
     """Get dictionary of avaialble OGR drivers"""
     try:
         ret = grass.read_command('v.in.ogr',
-                                 quiet = True,
-                                 flags = 'f')
+                                 quiet=True,
+                                 flags='f')
     except:
         ret = None
 
-    return _parseFormats(ret), _parseFormats(ret, writableOnly = True)
+    return _parseFormats(ret), _parseFormats(ret, writableOnly=True)
 
-def _parseFormats(output, writableOnly = False):
+
+def _parseFormats(output, writableOnly=False):
     """Parse r.in.gdal/v.in.ogr -f output"""
-    formats = { 'file'     : list(),
-                'database' : list(),
-                'protocol' : list()
-                }
-    
+    formats = {'file': list(),
+               'database': list(),
+               'protocol': list()
+               }
+
     if not output:
         return formats
-    
+
     patt = None
     if writableOnly:
         patt = re.compile('\(rw\+?\)$', re.IGNORECASE)
-    
+
     for line in output.splitlines():
         key, name = map(lambda x: x.strip(), line.strip().rsplit(':', -1))
-        
+
         if writableOnly and not patt.search(key):
             continue
-        
+
         if name in ('Memory', 'Virtual Raster', 'In Memory Raster'):
             continue
         if name in ('PostgreSQL', 'SQLite',
@@ -695,103 +730,104 @@
             formats['protocol'].append(name)
         else:
             formats['file'].append(name)
-    
+
     for items in formats.itervalues():
         items.sort()
-    
+
     return formats
 
 formats = None
 
-def GetFormats(writableOnly = False):
+
+def GetFormats(writableOnly=False):
     """Get GDAL/OGR formats"""
     global formats
     if not formats:
         gdalAll, gdalWritable = _getGDALFormats()
-        ogrAll,  ogrWritable  = _getOGRFormats()
+        ogrAll, ogrWritable = _getOGRFormats()
         formats = {
-            'all' : {
-                'gdal' : gdalAll,
-                'ogr'  : ogrAll,
-                },
-            'writable' : {
-                'gdal' : gdalWritable,
-                'ogr'  : ogrWritable,
-                },
-            }
-    
+            'all': {
+                'gdal': gdalAll,
+                'ogr': ogrAll,
+            },
+            'writable': {
+                'gdal': gdalWritable,
+                'ogr': ogrWritable,
+            },
+        }
+
     if writableOnly:
         return formats['writable']
-    
+
     return formats['all']
 
 
 rasterFormatExtension = {
-            'GeoTIFF' : 'tif',
-            'Erdas Imagine Images (.img)' : 'img',
-            'Ground-based SAR Applications Testbed File Format (.gff)' : 'gff',
-            'Arc/Info Binary Grid' : 'adf',
-            'Portable Network Graphics' : 'png',
-            'JPEG JFIF' : 'jpg',
-            'Japanese DEM (.mem)' : 'mem',
-            'Graphics Interchange Format (.gif)' : 'gif',
-            'X11 PixMap Format' : 'xpm',
-            'MS Windows Device Independent Bitmap' : 'bmp',
-            'SPOT DIMAP' : 'dim',
-            'RadarSat 2 XML Product' : 'xml',
-            'EarthWatch .TIL' : 'til',
-            'ERMapper .ers Labelled' : 'ers',
-            'ERMapper Compressed Wavelets' : 'ecw',
-            'GRIdded Binary (.grb)' : 'grb',
-            'EUMETSAT Archive native (.nat)' : 'nat',
-            'Idrisi Raster A.1' : 'rst',
-            'Golden Software ASCII Grid (.grd)' : 'grd',
-            'Golden Software Binary Grid (.grd)' : 'grd',
-            'Golden Software 7 Binary Grid (.grd)' : 'grd',
-            'R Object Data Store' : 'r',
-            'USGS DOQ (Old Style)' : 'doq',
-            'USGS DOQ (New Style)' : 'doq',
-            'ENVI .hdr Labelled' : 'hdr',
-            'ESRI .hdr Labelled' : 'hdr',
-            'Generic Binary (.hdr Labelled)' : 'hdr',
-            'PCI .aux Labelled' : 'aux',
-            'EOSAT FAST Format' : 'fst',
-            'VTP .bt (Binary Terrain) 1.3 Format' : 'bt',
-            'FARSITE v.4 Landscape File (.lcp)' : 'lcp',
-            'Swedish Grid RIK (.rik)' : 'rik',
-            'USGS Optional ASCII DEM (and CDED)' : 'dem',
-            'Northwood Numeric Grid Format .grd/.tab' : '',
-            'Northwood Classified Grid Format .grc/.tab' : '',
-            'ARC Digitized Raster Graphics' : 'arc',
-            'Magellan topo (.blx)' : 'blx',
-            'SAGA GIS Binary Grid (.sdat)' : 'sdat'
-            }
+    'GeoTIFF': 'tif',
+    'Erdas Imagine Images (.img)': 'img',
+    'Ground-based SAR Applications Testbed File Format (.gff)': 'gff',
+    'Arc/Info Binary Grid': 'adf',
+    'Portable Network Graphics': 'png',
+    'JPEG JFIF': 'jpg',
+    'Japanese DEM (.mem)': 'mem',
+    'Graphics Interchange Format (.gif)': 'gif',
+    'X11 PixMap Format': 'xpm',
+    'MS Windows Device Independent Bitmap': 'bmp',
+    'SPOT DIMAP': 'dim',
+    'RadarSat 2 XML Product': 'xml',
+    'EarthWatch .TIL': 'til',
+    'ERMapper .ers Labelled': 'ers',
+    'ERMapper Compressed Wavelets': 'ecw',
+    'GRIdded Binary (.grb)': 'grb',
+    'EUMETSAT Archive native (.nat)': 'nat',
+    'Idrisi Raster A.1': 'rst',
+    'Golden Software ASCII Grid (.grd)': 'grd',
+    'Golden Software Binary Grid (.grd)': 'grd',
+    'Golden Software 7 Binary Grid (.grd)': 'grd',
+    'R Object Data Store': 'r',
+    'USGS DOQ (Old Style)': 'doq',
+    'USGS DOQ (New Style)': 'doq',
+    'ENVI .hdr Labelled': 'hdr',
+    'ESRI .hdr Labelled': 'hdr',
+    'Generic Binary (.hdr Labelled)': 'hdr',
+    'PCI .aux Labelled': 'aux',
+    'EOSAT FAST Format': 'fst',
+    'VTP .bt (Binary Terrain) 1.3 Format': 'bt',
+    'FARSITE v.4 Landscape File (.lcp)': 'lcp',
+    'Swedish Grid RIK (.rik)': 'rik',
+    'USGS Optional ASCII DEM (and CDED)': 'dem',
+    'Northwood Numeric Grid Format .grd/.tab': '',
+    'Northwood Classified Grid Format .grc/.tab': '',
+    'ARC Digitized Raster Graphics': 'arc',
+    'Magellan topo (.blx)': 'blx',
+    'SAGA GIS Binary Grid (.sdat)': 'sdat'
+}
 
 
 vectorFormatExtension = {
-            'ESRI Shapefile' : 'shp',
-            'UK .NTF'        : 'ntf',
-            'SDTS'           : 'ddf',
-            'DGN'            : 'dgn',
-            'VRT'            : 'vrt',
-            'REC'            : 'rec',
-            'BNA'            : 'bna',
-            'CSV'            : 'csv',
-            'GML'            : 'gml',
-            'GPX'            : 'gpx',
-            'KML'            : 'kml',
-            'GMT'            : 'gmt',
-            'PGeo'           : 'mdb',
-            'XPlane'         : 'dat',
-            'AVCBin'         : 'adf',
-            'AVCE00'         : 'e00',
-            'DXF'            : 'dxf',
-            'Geoconcept'     : 'gxt',
-            'GeoRSS'         : 'xml',
-            'GPSTrackMaker'  : 'gtm',
-            'VFK'            : 'vfk',
-            'SVG'            : 'svg',
-            }
+    'ESRI Shapefile': 'shp',
+    'UK .NTF': 'ntf',
+    'SDTS': 'ddf',
+            'DGN': 'dgn',
+            'VRT': 'vrt',
+            'REC': 'rec',
+            'BNA': 'bna',
+            'CSV': 'csv',
+            'GML': 'gml',
+            'GPX': 'gpx',
+            'KML': 'kml',
+            'GMT': 'gmt',
+            'PGeo': 'mdb',
+            'XPlane': 'dat',
+            'AVCBin': 'adf',
+            'AVCE00': 'e00',
+            'DXF': 'dxf',
+            'Geoconcept': 'gxt',
+            'GeoRSS': 'xml',
+            'GPSTrackMaker': 'gtm',
+            'VFK': 'vfk',
+            'SVG': 'svg',
+}
 
 
 def GetSettingsPath():
@@ -801,22 +837,25 @@
         verFd = open(os.path.join(globalvar.ETCDIR, "VERSIONNUMBER"))
         version = int(verFd.readlines()[0].split(' ')[0].split('.')[0])
     except (IOError, ValueError, TypeError, IndexError) as e:
-        sys.exit(_("ERROR: Unable to determine GRASS version. Details: %s") % e)
-    
+        sys.exit(
+            _("ERROR: Unable to determine GRASS version. Details: %s") %
+            e)
+
     verFd.close()
 
     # keep location of settings files rc and wx in sync with lib/init/grass.py
     if sys.platform == 'win32':
         return os.path.join(os.getenv('APPDATA'), 'GRASS%d' % version)
-    
+
     return os.path.join(os.getenv('HOME'), '.grass%d' % version)
 
-def StoreEnvVariable(key, value = None, envFile = None):
+
+def StoreEnvVariable(key, value=None, envFile=None):
     """Store environmental variable
 
     If value is not given (is None) then environmental variable is
     unset.
-    
+
     :param key: env key
     :param value: env value
     :param envFile: path to the environmental file (None for default location)
@@ -825,10 +864,14 @@
     if not envFile:
         gVersion = grass.version()['version'].split('.', 1)[0]
         if not windows:
-            envFile = os.path.join(os.getenv('HOME'), '.grass%s' % gVersion, 'bashrc')
+            envFile = os.path.join(
+                os.getenv('HOME'), '.grass%s' %
+                gVersion, 'bashrc')
         else:
-            envFile = os.path.join(os.getenv('APPDATA'), 'GRASS%s' % gVersion, 'env.bat')
-    
+            envFile = os.path.join(
+                os.getenv('APPDATA'), 'GRASS%s' %
+                gVersion, 'env.bat')
+
     # read env file
     environ = dict()
     lineSkipped = list()
@@ -841,8 +884,11 @@
         for line in fd.readlines():
             line = line.rstrip(os.linesep)
             try:
-                k, v = map(lambda x: x.strip(), line.split(' ', 1)[1].split('=', 1))
-            except StandardError as e:
+                k, v = map(
+                    lambda x: x.strip(), line.split(
+                        ' ', 1)[1].split(
+                        '=', 1))
+            except Exception as e:
                 sys.stderr.write(_("%s: line skipped - unable to parse '%s'\n"
                                    "Reason: %s\n") % (envFile, line, e))
                 lineSkipped.append(line)
@@ -850,16 +896,16 @@
             if k in environ:
                 sys.stderr.write(_("Duplicated key: %s\n") % k)
             environ[k] = v
-        
+
         fd.close()
-    
+
     # update environmental variables
     if value is None:
         if key in environ:
             del environ[key]
     else:
         environ[key] = value
-    
+
     # write update env file
     try:
         fd = open(envFile, 'w')
@@ -870,17 +916,18 @@
         expCmd = 'set'
     else:
         expCmd = 'export'
-    
+
     for key, value in environ.iteritems():
         fd.write('%s %s=%s\n' % (expCmd, key, value))
-    
+
     # write also skipped lines
     for line in lineSkipped:
         fd.write(line + os.linesep)
-    
+
     fd.close()
 
-def SetAddOnPath(addonPath = None, key = 'PATH'):
+
+def SetAddOnPath(addonPath=None, key='PATH'):
     """Set default AddOn path
 
     :param addonPath: path to addons (None for default)
@@ -897,10 +944,10 @@
             addonPath = os.path.join(os.path.join(os.getenv('APPDATA'),
                                                   'GRASS%s' % gVersion,
                                                   'addons'))
-    
-    StoreEnvVariable(key = 'GRASS_ADDON_' + key, value = addonPath)
+
+    StoreEnvVariable(key='GRASS_ADDON_' + key, value=addonPath)
     os.environ['GRASS_ADDON_' + key] = addonPath
-    
+
     # update path
     if addonPath not in os.environ['PATH']:
         os.environ['PATH'] = addonPath + os.pathsep + os.environ['PATH']
@@ -949,32 +996,32 @@
             label = _('Select Color')
     return (rgb, label)
 
-command2ltype = {'d.rast'         : 'raster',
-                 'd.rast3d'       : 'raster_3d',
-                 'd.rgb'          : 'rgb',
-                 'd.his'          : 'his',
-                 'd.shade'        : 'shaded',
-                 'd.legend'       : 'rastleg',
-                 'd.rast.arrow'   : 'rastarrow',
-                 'd.rast.num'     : 'rastnum',
-                 'd.rast.leg'     : 'maplegend',
-                 'd.vect'         : 'vector',
+command2ltype = {'d.rast': 'raster',
+                 'd.rast3d': 'raster_3d',
+                 'd.rgb': 'rgb',
+                 'd.his': 'his',
+                 'd.shade': 'shaded',
+                 'd.legend': 'rastleg',
+                 'd.rast.arrow': 'rastarrow',
+                 'd.rast.num': 'rastnum',
+                 'd.rast.leg': 'maplegend',
+                 'd.vect': 'vector',
                  'd.vect.thematic': 'thememap',
-                 'd.vect.chart'   : 'themechart',
-                 'd.grid'         : 'grid',
-                 'd.geodesic'     : 'geodesic',
-                 'd.rhumbline'    : 'rhumb',
-                 'd.labels'       : 'labels',
-                 'd.barscale'     : 'barscale',
-                 'd.redraw'       : 'redraw',
-                 'd.wms'          : 'wms',
-                 'd.histogram'    : 'histogram',
-                 'd.colortable'   : 'colortable',
-                 'd.graph'        : 'graph',
-                 'd.out.file'     : 'export',
-                 'd.to.rast'      : 'torast',
-                 'd.text'         : 'text',
-                 'd.northarrow'   : 'northarrow'
+                 'd.vect.chart': 'themechart',
+                 'd.grid': 'grid',
+                 'd.geodesic': 'geodesic',
+                 'd.rhumbline': 'rhumb',
+                 'd.labels': 'labels',
+                 'd.barscale': 'barscale',
+                 'd.redraw': 'redraw',
+                 'd.wms': 'wms',
+                 'd.histogram': 'histogram',
+                 'd.colortable': 'colortable',
+                 'd.graph': 'graph',
+                 'd.out.file': 'export',
+                 'd.to.rast': 'torast',
+                 'd.text': 'text',
+                 'd.northarrow': 'northarrow'
                  }
 ltype2command = {}
 for (cmd, ltype) in command2ltype.items():
@@ -982,24 +1029,24 @@
 
 
 def GetGEventAttribsForHandler(method, event):
-    """Get attributes from event, which can be used by handler method. 
+    """Get attributes from event, which can be used by handler method.
 
     Be aware of event class attributes.
 
     :param method: handler method (including self arg)
     :param event: event
 
-    :return: (valid kwargs for method, 
-             list of method's args without default value 
+    :return: (valid kwargs for method,
+             list of method's args without default value
              which were not found among event attributes)
     """
     args_spec = inspect.getargspec(method)
 
     args = args_spec[0]
 
-    defaults =[]
+    defaults = []
     if args_spec[3]:
-        defaults =  args_spec[3]
+        defaults = args_spec[3]
 
     # number of arguments without def value
     req_args = len(args) - 1 - len(defaults)
@@ -1016,9 +1063,9 @@
     return kwargs, missing_args
 
 
-def PilImageToWxImage(pilImage, copyAlpha = True):
+def PilImageToWxImage(pilImage, copyAlpha=True):
     """Convert PIL image to wx.Image
-    
+
     Based on http://wiki.wxpython.org/WorkingWithImages
     """
     import wx
@@ -1027,17 +1074,34 @@
         wxImage = wx.EmptyImage(*pilImage.size)
         pilImageCopyRGBA = pilImage.copy()
         pilImageCopyRGB = pilImageCopyRGBA.convert('RGB')    # RGBA --> RGB
-        fn = getattr(pilImageCopyRGB, "tobytes", getattr(pilImageCopyRGB, "tostring"))
+        fn = getattr(
+            pilImageCopyRGB,
+            "tobytes",
+            getattr(
+                pilImageCopyRGB,
+                "tostring"))
         pilImageRgbData = fn()
         wxImage.SetData(pilImageRgbData)
-        fn = getattr(pilImageCopyRGBA, "tobytes", getattr(pilImageCopyRGBA, "tostring"))
-        wxImage.SetAlphaData(fn()[3::4])  # Create layer and insert alpha values.
+        fn = getattr(
+            pilImageCopyRGBA,
+            "tobytes",
+            getattr(
+                pilImageCopyRGBA,
+                "tostring"))
+        # Create layer and insert alpha values.
+        wxImage.SetAlphaData(fn()[3::4])
 
     else:    # The resulting image will not have alpha.
         wxImage = wx.EmptyImage(*pilImage.size)
         pilImageCopy = pilImage.copy()
-        pilImageCopyRGB = pilImageCopy.convert('RGB')    # Discard any alpha from the PIL image.
-        fn = getattr(pilImageCopyRGB, "tobytes", getattr(pilImageCopyRGB, "tostring"))
+        # Discard any alpha from the PIL image.
+        pilImageCopyRGB = pilImageCopy.convert('RGB')
+        fn = getattr(
+            pilImageCopyRGB,
+            "tobytes",
+            getattr(
+                pilImageCopyRGB,
+                "tostring"))
         pilImageRgbData = fn()
         wxImage.SetData(pilImageRgbData)
 
@@ -1127,6 +1191,7 @@
     do_doctest_gettext_workaround()
     return doctest.testmod().failed
 
+
 def registerPid(pid):
     """Register process id as GUI_PID GRASS variable
 
@@ -1138,7 +1203,8 @@
         guiPid = env['GUI_PID'].split(',')
     guiPid.append(str(pid))
     grass.run_command('g.gisenv', set='GUI_PID={}'.format(','.join(guiPid)))
-    
+
+
 def unregisterPid(pid):
     """Unregister process id from GUI_PID GRASS variable
 
@@ -1147,12 +1213,15 @@
     env = grass.gisenv()
     if 'GUI_PID' not in env:
         return
-    
+
     guiPid = env['GUI_PID'].split(',')
     pid = str(os.getpid())
     if pid in guiPid:
         guiPid.remove(pid)
-        grass.run_command('g.gisenv', set='GUI_PID={}'.format(','.join(guiPid)))
-    
+        grass.run_command(
+            'g.gisenv',
+            set='GUI_PID={}'.format(
+                ','.join(guiPid)))
+
 if __name__ == '__main__':
     sys.exit(doc_test())

Modified: grass/trunk/gui/wxpython/core/workspace.py
===================================================================
--- grass/trunk/gui/wxpython/core/workspace.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/workspace.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -20,29 +20,30 @@
 
 import wx
 
-from core.utils     import normalize_whitespace, _
-from core.settings  import UserSettings
-from core.gcmd      import EncodeString, GetDefaultEncoding
-from nviz.main      import NvizSettings
+from core.utils import normalize_whitespace, _
+from core.settings import UserSettings
+from core.gcmd import EncodeString, GetDefaultEncoding
+from nviz.main import NvizSettings
 
 from grass.script import core as gcore
 
 
 class ProcessWorkspaceFile:
+
     def __init__(self, tree):
         """A ElementTree handler for the GXW XML file, as defined in
         grass-gxw.dtd.
         """
         self.tree = tree
         self.root = self.tree.getroot()
-        
+
         #
         # layer manager properties
         #
-        self.layerManager = { 'pos' : None,  # window position
-                              'size' : None, # window size
-                              'cwd' : None } # current working directory
-        
+        self.layerManager = {'pos': None,  # window position
+                             'size': None,  # window size
+                             'cwd': None}  # current working directory
+
         #
         # list of mapdisplays
         #
@@ -55,27 +56,27 @@
         # nviz state
         #
         self.nviz_state = {}
-        
-        self.displayIndex = -1 # first display has index '0'
-        
+
+        self.displayIndex = -1  # first display has index '0'
+
         self.__processFile()
 
         if NvizSettings:
             self.nvizDefault = NvizSettings()
         else:
             self.nvizDefault = None
-        
+
     def __filterValue(self, value):
         """Filter value
-        
+
         :param value:
         """
         value = value.replace('<', '<')
         value = value.replace('>', '>')
-        
+
         return value
 
-    def __getNodeText(self, node, tag, default = ''):
+    def __getNodeText(self, node, tag, default=''):
         """Get node text"""
         p = node.find(tag)
         if p is not None:
@@ -85,9 +86,9 @@
                 return ''
 
             return normalize_whitespace(p.text)
-        
+
         return default
-    
+
     def __processFile(self):
         """Process workspace file"""
         #
@@ -99,122 +100,126 @@
             if posAttr:
                 posVal = map(int, posAttr.split(','))
                 try:
-                    self.layerManager['pos']  = (posVal[0], posVal[1])
+                    self.layerManager['pos'] = (posVal[0], posVal[1])
                     self.layerManager['size'] = (posVal[2], posVal[3])
                 except:
                     pass
             # current working directory
             cwdPath = self.__getNodeText(node_lm, 'cwd')
             if cwdPath:
-               self.layerManager['cwd'] = cwdPath 
-        
+                self.layerManager['cwd'] = cwdPath
+
         #
         # displays
         #
         for display in self.root.findall('display'):
             self.displayIndex += 1
-            
+
             # window position and size
             posAttr = display.get('dim', '')
             if posAttr:
                 posVal = map(int, posAttr.split(','))
                 try:
-                    pos  = (posVal[0], posVal[1])
+                    pos = (posVal[0], posVal[1])
                     size = (posVal[2], posVal[3])
                 except:
-                    pos  = None
+                    pos = None
                     size = None
-                # this happens on Windows when mapwindow is minimized when saving workspace
+                # this happens on Windows when mapwindow is minimized when
+                # saving workspace
                 else:
                     if posVal[0] == -32000:
                         pos = None
                         size = None
             else:
-                pos  = None
+                pos = None
                 size = None
-            
+
             extentAttr = display.get('extent', '')
             if extentAttr:
                 # w, s, e, n
                 extent = map(float, extentAttr.split(','))
             else:
                 extent = None
-            
+
             # projection
             node_projection = display.find('projection')
             if node_projection is not None:
-                projection = { 'enabled' : True,
-                               'epsg' : node_projection.get('epsg', ''),
-                               'proj' : self.__getNodeText(node_projection, 'value') }
+                projection = {
+                    'enabled': True, 'epsg': node_projection.get(
+                        'epsg', ''), 'proj': self.__getNodeText(
+                        node_projection, 'value')}
             else:
-                projection = { 'enabled' : False }
-            
-            self.displays.append( {
-                    "name"           : display.get('name'),
-                    "render"         : bool(int(display.get('render', "0"))),
-                    "mode"           : int(display.get('mode', 0)),
-                    "showCompExtent" : bool(int(display.get('showCompExtent', "0"))),
-                    "pos"            : pos,
-                    "size"           : size,
-                    "extent"         : extent,
-                    "tbres"          : display.get('tbres', '0'),
-                    "alignExtent"    : bool(int(display.get('alignExtent', "0"))),
-                    "constrainRes"   : bool(int(display.get('constrainRes', "0"))),
-                    "projection"     : projection,
-                    "viewMode"       : display.get('viewMode', '2d')} )
-            
+                projection = {'enabled': False}
+
+            self.displays.append({
+                "name": display.get('name'),
+                "render": bool(int(display.get('render', "0"))),
+                "mode": int(display.get('mode', 0)),
+                "showCompExtent": bool(int(display.get('showCompExtent', "0"))),
+                "pos": pos,
+                "size": size,
+                "extent": extent,
+                "tbres": display.get('tbres', '0'),
+                "alignExtent": bool(int(display.get('alignExtent', "0"))),
+                "constrainRes": bool(int(display.get('constrainRes', "0"))),
+                "projection": projection,
+                "viewMode": display.get('viewMode', '2d')})
+
             # process all layers/groups in the display
             self.__processLayers(display)
             # process nviz_state
             self.__processNvizState(display)
 
-    def __processLayers(self, node, inGroup = -1):
+    def __processLayers(self, node, inGroup=-1):
         """Process layers/groups of selected display
-        
+
         :param node: display tree node
         :param inGroup: in group -> index of group item otherwise -1
         """
         for item in node.getchildren():
             if item.tag == 'group':
                 # -> group
-                self.layers.append( {
-                        "type"    : 'group',
-                        "name"    : item.get('name', ''),
-                        "checked" : bool(int(item.get('checked', "0"))),
-                        "opacity" : None,
-                        "cmd"     : None,
-                        "group"   : inGroup,
-                        "display" : self.displayIndex,
-                        "vdigit"  : None,
-                        "nviz"    : None})
-                
-                self.__processLayers(item, inGroup = len(self.layers) - 1) # process items in group
-                
+                self.layers.append({
+                    "type": 'group',
+                    "name": item.get('name', ''),
+                    "checked": bool(int(item.get('checked', "0"))),
+                    "opacity": None,
+                    "cmd": None,
+                    "group": inGroup,
+                    "display": self.displayIndex,
+                    "vdigit": None,
+                    "nviz": None})
+
+                self.__processLayers(
+                    item, inGroup=len(
+                        self.layers) - 1)  # process items in group
+
             elif item.tag == 'layer':
                 cmd, selected, vdigit, nviz = self.__processLayer(item)
                 lname = item.get('name', None)
                 if lname and '\\n' in lname:
                     lname = lname.replace('\\n', os.linesep)
-                
-                self.layers.append( {
-                        "type"     : item.get('type', None),
-                        "name"     : lname,
-                        "checked"  : bool(int(item.get('checked', "0"))),
-                        "opacity"  : float(item.get('opacity', '1.0')),
-                        "cmd"      : cmd,
-                        "group"    : inGroup,
-                        "display"  : self.displayIndex,
-                        "selected" : selected,
-                        "vdigit"   : vdigit,
-                        "nviz"     : nviz } )
-            
+
+                self.layers.append({
+                    "type": item.get('type', None),
+                    "name": lname,
+                    "checked": bool(int(item.get('checked', "0"))),
+                    "opacity": float(item.get('opacity', '1.0')),
+                    "cmd": cmd,
+                    "group": inGroup,
+                    "display": self.displayIndex,
+                    "selected": selected,
+                    "vdigit": vdigit,
+                    "nviz": nviz})
+
     def __processLayer(self, layer):
         """Process layer item
 
         :param layer: tree node
         """
         cmd = list()
-        
+
         #
         # layer attributes (task) - 2D settings
         #
@@ -245,7 +250,7 @@
             selected = True
         else:
             selected = False
-        
+
         #
         # Vector digitizer settings
         #
@@ -254,7 +259,7 @@
             vdigit = self.__processLayerVdigit(node_vdigit)
         else:
             vdigit = None
-        
+
         #
         # Nviz (3D settings)
         #
@@ -263,7 +268,7 @@
             nviz = self.__processLayerNviz(node_nviz)
         else:
             nviz = None
-        
+
         return (cmd, selected, vdigit, nviz)
 
     def __processLayerVdigit(self, node_vdigit):
@@ -278,12 +283,12 @@
                 vdigit['geomAttr'] = dict()
             type = node.get('type')
             vdigit['geomAttr'][type] = dict()
-            vdigit['geomAttr'][type]['column'] = node.get('column') # required
+            vdigit['geomAttr'][type]['column'] = node.get('column')  # required
             # default map units
             vdigit['geomAttr'][type]['units'] = node.get('units', 'mu')
-        
+
         return vdigit
-    
+
     def __processLayerNviz(self, node_nviz):
         """Process 3D layer settings
 
@@ -307,9 +312,11 @@
             for sec in ('lines', 'points'):
                 nviz['vector'][sec] = {}
             if node_nviz.find('vlines'):
-                self.__processLayerNvizVectorLines(nviz, node_nviz.find('vlines'))
+                self.__processLayerNvizVectorLines(
+                    nviz, node_nviz.find('vlines'))
             if node_nviz.find('vpoints'):
-                self.__processLayerNvizVectorPoints(nviz, node_nviz.find('vpoints'))
+                self.__processLayerNvizVectorPoints(
+                    nviz, node_nviz.find('vpoints'))
 
         return nviz
 
@@ -343,7 +350,8 @@
             tagName = str(node_draw.tag)
             nvizData['surface'][tagName]['all'] = False
             nvizData['surface'][tagName]['mode'] = {}
-            nvizData['surface'][tagName]['mode']['value'] = -1  # to be calculated
+            nvizData['surface'][tagName]['mode'][
+                'value'] = -1  # to be calculated
             nvizData['surface'][tagName]['mode']['desc'] = {}
             nvizData['surface'][tagName]['mode']['desc']['shading'] = \
                 str(node_draw.get('shading', ''))
@@ -424,7 +432,8 @@
                 for vol_type in ('isosurface', 'slice'):
                     nd = node_res.find(vol_type)
                     value = int(self.__getNodeText(nd, 'value'))
-                    nvizData['volume']['draw']['resolution'][vol_type] = {'value': value}
+                    nvizData['volume']['draw']['resolution'][
+                        vol_type] = {'value': value}
             node_shading = node_draw.find('shading')
             if node_shading is not None:
                 nvizData['volume']['draw']['shading'] = {}
@@ -432,7 +441,8 @@
                     nd = node_shading.find(vol_type)
                     value = int(self.__getNodeText(nd, 'value'))
                     desc = self.__getNodeText(nd, 'desc')
-                    nvizData['volume']['draw']['shading'][vol_type] = {'value': value, 'desc': desc}
+                    nvizData['volume']['draw']['shading'][
+                        vol_type] = {'value': value, 'desc': desc}
 
         nvizData['volume']['isosurface'] = []
         for isosurfaceNode in nodeVolume.findall('isosurface'):
@@ -453,13 +463,16 @@
                         isoDict[att]['value'] = float(value)
             inout = isosurfaceNode.find('inout')
             if inout is not None:
-                isoDict['inout'] = {'value': int(float(inout.find('value').text))}
+                isoDict['inout'] = {'value': int(
+                    float(inout.find('value').text))}
             nvizData['volume']['isosurface'].append(isoDict)
-            
+
         nvizData['volume']['slice'] = []
         for sliceNode in nodeVolume.findall('slice'):
             sliceDict = {}
-            sliceDict['transp'] = {'value': int(sliceNode.find('transp').find('value').text)}
+            sliceDict['transp'] = {
+                'value': int(
+                    sliceNode.find('transp').find('value').text)}
             sliceDict['position'] = {}
             for child in sliceNode.find('position'):
                 if child.tag == 'axis':
@@ -467,7 +480,7 @@
                 else:
                     sliceDict['position'][child.tag] = float(child.text)
             nvizData['volume']['slice'].append(sliceDict)
-  
+
         # position
         node_pos = nodeVolume.find('position')
         if node_pos is not None:
@@ -486,14 +499,21 @@
         :param nodeVector: nviz vector points node
         """
         marker = str(nodePoints.get('marker', ''))
-        markerId = list(UserSettings.Get(group='nviz', key='vector',
-                                         subkey=['points', 'marker'], settings_type='internal')).index(marker)
+        markerId = list(
+            UserSettings.Get(
+                group='nviz',
+                key='vector',
+                subkey=[
+                    'points',
+                    'marker'],
+                settings_type='internal')).index(marker)
         nvizData['vector']['points']['marker'] = {'value': markerId}
 
         node_mode = nodePoints.find('mode')
         if node_mode is not None:
             nvizData['vector']['points']['mode'] = {}
-            nvizData['vector']['points']['mode']['type'] = str(node_mode.get('type', 'surface'))
+            nvizData['vector']['points']['mode'][
+                'type'] = str(node_mode.get('type', 'surface'))
             nvizData['vector']['points']['mode']['surface'] = {}
             nvizData['vector']['points']['mode']['surface']['value'] = []
             nvizData['vector']['points']['mode']['surface']['show'] = []
@@ -502,8 +522,8 @@
             for node_map in node_mode.findall('map'):
                 nvizData['vector']['points']['mode']['surface']['value'].append(
                     self.__processLayerNvizNode(node_map, 'name', str))
-                nvizData['vector']['points']['mode']['surface']['show'].append(bool(
-                    self.__processLayerNvizNode(node_map, 'checked', int)))
+                nvizData['vector']['points']['mode']['surface']['show'].append(
+                    bool(self.__processLayerNvizNode(node_map, 'checked', int)))
 
         # color
         self.__processLayerNvizNode(nodePoints, 'color', str,
@@ -524,12 +544,15 @@
         # thematic
         node_thematic = nodePoints.find('thematic')
         thematic = nvizData['vector']['points']['thematic'] = {}
-        thematic['rgbcolumn'] = self.__processLayerNvizNode(node_thematic, 'rgbcolumn', str)
-        thematic['sizecolumn'] = self.__processLayerNvizNode(node_thematic, 'sizecolumn', str)
+        thematic['rgbcolumn'] = self.__processLayerNvizNode(
+            node_thematic, 'rgbcolumn', str)
+        thematic['sizecolumn'] = self.__processLayerNvizNode(
+            node_thematic, 'sizecolumn', str)
         for col in ('rgbcolumn', 'sizecolumn'):
             if thematic[col] == 'None':
                 thematic[col] = None
-        thematic['layer'] = self.__processLayerNvizNode(node_thematic, 'layer', int)
+        thematic['layer'] = self.__processLayerNvizNode(
+            node_thematic, 'layer', int)
         for use in ('usecolor', 'usesize', 'usewidth'):
             if node_thematic.get(use, ''):
                 thematic[use] = int(node_thematic.get(use, '0'))
@@ -543,7 +566,8 @@
         node_mode = nodeLines.find('mode')
         if node_mode is not None:
             nvizData['vector']['lines']['mode'] = {}
-            nvizData['vector']['lines']['mode']['type'] = str(node_mode.get('type', ''))
+            nvizData['vector']['lines']['mode'][
+                'type'] = str(node_mode.get('type', ''))
             nvizData['vector']['lines']['mode']['surface'] = {}
             nvizData['vector']['lines']['mode']['surface']['value'] = []
             nvizData['vector']['lines']['mode']['surface']['show'] = []
@@ -552,8 +576,8 @@
             for node_map in node_mode.findall('map'):
                 nvizData['vector']['lines']['mode']['surface']['value'].append(
                     self.__processLayerNvizNode(node_map, 'name', str))
-                nvizData['vector']['lines']['mode']['surface']['show'].append(bool(
-                    self.__processLayerNvizNode(node_map, 'checked', int)))
+                nvizData['vector']['lines']['mode']['surface']['show'].append(
+                    bool(self.__processLayerNvizNode(node_map, 'checked', int)))
 
         # color
         self.__processLayerNvizNode(nodeLines, 'color', str,
@@ -570,17 +594,20 @@
         # thematic
         node_thematic = nodeLines.find('thematic')
         thematic = nvizData['vector']['lines']['thematic'] = {}
-        thematic['rgbcolumn'] = self.__processLayerNvizNode(node_thematic, 'rgbcolumn', str)
-        thematic['sizecolumn'] = self.__processLayerNvizNode(node_thematic, 'sizecolumn', str)
+        thematic['rgbcolumn'] = self.__processLayerNvizNode(
+            node_thematic, 'rgbcolumn', str)
+        thematic['sizecolumn'] = self.__processLayerNvizNode(
+            node_thematic, 'sizecolumn', str)
         for col in ('rgbcolumn', 'sizecolumn'):
             if thematic[col] == 'None':
                 thematic[col] = None
-        thematic['layer'] = self.__processLayerNvizNode(node_thematic, 'layer', int)
+        thematic['layer'] = self.__processLayerNvizNode(
+            node_thematic, 'layer', int)
         for use in ('usecolor', 'usesize', 'usewidth'):
             if node_thematic.get(use, ''):
                 thematic[use] = int(node_thematic.get(use, '0'))
 
-    def __processLayerNvizNode(self, node, tag, cast, dc = None):
+    def __processLayerNvizNode(self, node, tag, cast, dc=None):
         """Process given tag nviz/vector"""
         node_tag = node.find(tag)
         if node_tag is not None:
@@ -599,7 +626,7 @@
                 dc[tag]['value'] = value
             else:
                 return value
-    
+
     def __processNvizState(self, node):
         """Process tag nviz_state"""
         node_state = node.find('nviz_state')
@@ -612,36 +639,52 @@
         node_view = node_state.find('view')
         view = {}
         iview = {}
-        
+
         node_position = node_view.find('v_position')
         view['position'] = {}
-        view['position']['x'] = self.__processLayerNvizNode(node_position, 'x', float)
-        view['position']['y'] = self.__processLayerNvizNode(node_position, 'y', float)
+        view['position']['x'] = self.__processLayerNvizNode(
+            node_position, 'x', float)
+        view['position']['y'] = self.__processLayerNvizNode(
+            node_position, 'y', float)
         node_persp = node_view.find('persp')
         view['persp'] = {}
         iview['persp'] = {}
-        view['persp']['value'] = self.__processLayerNvizNode(node_persp, 'value', int)
-        view['persp']['step'] = self.__processLayerNvizNode(node_persp, 'step', int)
-        iview['persp']['min'] = self.__processLayerNvizNode(node_persp, 'min', int)
-        iview['persp']['max'] = self.__processLayerNvizNode(node_persp, 'max', int)
+        view['persp']['value'] = self.__processLayerNvizNode(
+            node_persp, 'value', int)
+        view['persp']['step'] = self.__processLayerNvizNode(
+            node_persp, 'step', int)
+        iview['persp']['min'] = self.__processLayerNvizNode(
+            node_persp, 'min', int)
+        iview['persp']['max'] = self.__processLayerNvizNode(
+            node_persp, 'max', int)
         node_height = node_view.find('v_height')
         iview['height'] = {}
-        iview['height']['value'] = self.__processLayerNvizNode(node_height, 'value', int)
-        iview['height']['min'] = self.__processLayerNvizNode(node_height, 'min', int)
-        iview['height']['max'] = self.__processLayerNvizNode(node_height, 'max', int)
+        iview['height']['value'] = self.__processLayerNvizNode(
+            node_height, 'value', int)
+        iview['height']['min'] = self.__processLayerNvizNode(
+            node_height, 'min', int)
+        iview['height']['max'] = self.__processLayerNvizNode(
+            node_height, 'max', int)
         node_twist = node_view.find('twist')
         view['twist'] = {}
         iview['twist'] = {}
-        view['twist']['value'] = self.__processLayerNvizNode(node_twist, 'value', int)
-        iview['twist']['min'] = self.__processLayerNvizNode(node_twist, 'min', int)
-        iview['twist']['max'] = self.__processLayerNvizNode(node_twist, 'max', int)
+        view['twist']['value'] = self.__processLayerNvizNode(
+            node_twist, 'value', int)
+        iview['twist']['min'] = self.__processLayerNvizNode(
+            node_twist, 'min', int)
+        iview['twist']['max'] = self.__processLayerNvizNode(
+            node_twist, 'max', int)
         node_zexag = node_view.find('z-exag')
         view['z-exag'] = {}
         iview['z-exag'] = {}
-        view['z-exag']['value'] = self.__processLayerNvizNode(node_zexag, 'value', float)
-        view['z-exag']['min'] = self.__processLayerNvizNode(node_zexag, 'min', int)
-        view['z-exag']['max'] = self.__processLayerNvizNode(node_zexag, 'max', int)
-        iview['z-exag']['llRatio'] = self.__processLayerNvizNode(node_zexag, 'llRatio', float)
+        view[
+            'z-exag']['value'] = self.__processLayerNvizNode(node_zexag, 'value', float)
+        view[
+            'z-exag']['min'] = self.__processLayerNvizNode(node_zexag, 'min', int)
+        view[
+            'z-exag']['max'] = self.__processLayerNvizNode(node_zexag, 'max', int)
+        iview[
+            'z-exag']['llRatio'] = self.__processLayerNvizNode(node_zexag, 'llRatio', float)
         node_focus = node_view.find('focus')
         iview['focus'] = {}
         iview['focus']['x'] = self.__processLayerNvizNode(node_focus, 'x', int)
@@ -664,12 +707,13 @@
         if node_rot is not None:
             rotation = node_rot.text
             if rotation:
-                iview['rotation'] = [float(item) for item in rotation.split(',')]
+                iview['rotation'] = [float(item)
+                                     for item in rotation.split(',')]
 
         view['background'] = {}
         color = self.__processLayerNvizNode(node_view, 'background_color', str)
         view['background']['color'] = tuple(map(int, color.split(':')))
-        
+
         self.nviz_state['view'] = view
         self.nviz_state['iview'] = iview
         #
@@ -677,63 +721,78 @@
         #
         node_light = node_state.find('light')
         light = {}
-        
+
         node_position = node_light.find('l_position')
         light['position'] = {}
-        light['position']['x'] = self.__processLayerNvizNode(node_position, 'x', float)
-        light['position']['y'] = self.__processLayerNvizNode(node_position, 'y', float)
-        light['position']['z'] = self.__processLayerNvizNode(node_position, 'z', int)
-        
-        light['bright'] = self.__processLayerNvizNode(node_light, 'bright', int) 
-        light['ambient'] = self.__processLayerNvizNode(node_light, 'ambient', int)
+        light['position']['x'] = self.__processLayerNvizNode(
+            node_position, 'x', float)
+        light['position']['y'] = self.__processLayerNvizNode(
+            node_position, 'y', float)
+        light['position']['z'] = self.__processLayerNvizNode(
+            node_position, 'z', int)
+
+        light['bright'] = self.__processLayerNvizNode(
+            node_light, 'bright', int)
+        light['ambient'] = self.__processLayerNvizNode(
+            node_light, 'ambient', int)
         color = self.__processLayerNvizNode(node_light, 'color', str)
         light['color'] = tuple(map(int, color.split(':')))
-        
+
         self.nviz_state['light'] = light
-        
+
         node_constants = node_state.find('constant_planes')
         constants = []
         if node_constants:
             for node_plane in node_constants.findall('plane'):
                 plane = {}
-                plane['color'] = self.__processLayerNvizNode(node_plane, 'color', str)                
-                plane['resolution'] = self.__processLayerNvizNode(node_plane, 'fine_resolution', int)
-                plane['value'] = self.__processLayerNvizNode(node_plane, 'height', int)
+                plane['color'] = self.__processLayerNvizNode(
+                    node_plane, 'color', str)
+                plane['resolution'] = self.__processLayerNvizNode(
+                    node_plane, 'fine_resolution', int)
+                plane['value'] = self.__processLayerNvizNode(
+                    node_plane, 'height', int)
                 plane['object'] = {}
                 constants.append({'constant': plane})
-        self.nviz_state['constants'] = constants    
+        self.nviz_state['constants'] = constants
 
+
 class WriteWorkspaceFile(object):
     """Generic class for writing workspace file"""
+
     def __init__(self, lmgr, file):
-        self.file =  file
+        self.file = file
         self.lmgr = lmgr
         self.indent = 0
-        
+
         # write header
 
-        self.file.write('<?xml version="1.0" encoding="%s"?>\n' % GetDefaultEncoding(forceUTF8 = True))
+        self.file.write(
+            '<?xml version="1.0" encoding="%s"?>\n' %
+            GetDefaultEncoding(
+                forceUTF8=True))
         self.file.write('<!DOCTYPE gxw SYSTEM "grass-gxw.dtd">\n')
         self.file.write('%s<gxw>\n' % (' ' * self.indent))
-        
-        self.indent =+ 4
-        
+
+        self.indent = + 4
+
         # layer manager
         windowPos = self.lmgr.GetPosition()
         windowSize = self.lmgr.GetSize()
-        file.write('%s<layer_manager dim="%d,%d,%d,%d">\n' % (' ' * self.indent,
-                                                              windowPos[0],
-                                                              windowPos[1],
-                                                              windowSize[0],
-                                                              windowSize[1]
-                                                              ))
+        file.write(
+            '%s<layer_manager dim="%d,%d,%d,%d">\n' %
+            (' ' *
+             self.indent,
+             windowPos[0],
+             windowPos[1],
+             windowSize[0],
+             windowSize[1]))
         self.indent += 4
         cwdPath = self.lmgr.GetCwdPath()
         if cwdPath:
             file.write('%s<cwd>%s</cwd>\n' % (' ' * self.indent, cwdPath))
         self.indent -= 4
         file.write('%s</layer_manager>\n' % (' ' * self.indent))
-        
+
         # list of displays
         for page in range(0, self.lmgr.GetLayerNotebook().GetPageCount()):
             dispName = self.lmgr.GetLayerNotebook().GetPageText(page)
@@ -741,14 +800,14 @@
             region = mapTree.GetMap().GetCurrentRegion()
             compRegion = gcore.region(region3d=True)
             mapdisp = mapTree.GetMapDisplay()
-            
+
             displayPos = mapdisp.GetPosition()
             displaySize = mapdisp.GetSize()
             if mapdisp.toolbars['map'].combo.GetSelection() == 1:
                 viewmode = '3d'
             else:
                 viewmode = '2d'
-            
+
             file.write('%s<display '
                        'name="%s" render="%d" '
                        'mode="%d" showCompExtent="%d" '
@@ -778,84 +837,98 @@
                                               viewmode
                                               ))
             # projection statusbar info
-            if mapdisp.GetProperty('projection') and \
-                    UserSettings.Get(group='display', key='projection', subkey='proj4'):
+            if mapdisp.GetProperty('projection') and UserSettings.Get(
+                    group='display', key='projection', subkey='proj4'):
                 self.indent += 4
                 file.write('%s<projection' % (' ' * self.indent))
-                epsg = UserSettings.Get(group='display', key='projection', subkey='epsg')
+                epsg = UserSettings.Get(
+                    group='display', key='projection', subkey='epsg')
                 if epsg:
                     file.write(' epsg="%s"' % epsg)
                 file.write('>\n')
-                proj = UserSettings.Get(group='display', key='projection', subkey='proj4')
-                self.indent += 4 
+                proj = UserSettings.Get(
+                    group='display', key='projection', subkey='proj4')
+                self.indent += 4
                 file.write('%s<value>%s</value>\n' % (' ' * self.indent, proj))
                 self.indent -= 4
                 file.write('%s</projection>\n' % (' ' * self.indent))
                 self.indent -= 4
-            
+
             # list of layers
             item = mapTree.GetFirstChild(mapTree.root)[0]
             self.__writeLayer(mapTree, item)
-            
+
             if mapdisp.MapWindow3D is not None:
                 nvizDisp = mapdisp.MapWindow3D
-                self.__writeNvizState(view = nvizDisp.view, iview =  nvizDisp.iview, 
-                                      light = nvizDisp.light, constants = nvizDisp.constants)
-            
+                self.__writeNvizState(
+                    view=nvizDisp.view,
+                    iview=nvizDisp.iview,
+                    light=nvizDisp.light,
+                    constants=nvizDisp.constants)
+
             file.write('%s</display>\n' % (' ' * self.indent))
-        
-        self.indent =- 4
+
+        self.indent = - 4
         file.write('%s</gxw>\n' % (' ' * self.indent))
 
     def __filterValue(self, value):
         """Make value XML-valid"""
         value = value.replace('<', '<')
         value = value.replace('>', '>')
-        
+
         return value
-    
+
     def __writeLayer(self, mapTree, item):
         """Write bunch of layers to GRASS Workspace XML file"""
         self.indent += 4
         itemSelected = mapTree.GetSelections()
         while item and item.IsOk():
-            type = mapTree.GetLayerInfo(item, key = 'type')
+            type = mapTree.GetLayerInfo(item, key='type')
             if type != 'group':
-                maplayer = mapTree.GetLayerInfo(item, key = 'maplayer')
+                maplayer = mapTree.GetLayerInfo(item, key='maplayer')
             else:
                 maplayer = None
 
             checked = int(item.IsChecked())
             if type == 'command':
-                cmd = mapTree.GetLayerInfo(item, key = 'maplayer').GetCmd(string=True)
-                self.file.write('%s<layer type="%s" name="%s" checked="%d">\n' % \
-                               (' ' * self.indent, type, EncodeString(cmd), checked))
+                cmd = mapTree.GetLayerInfo(
+                    item, key='maplayer').GetCmd(
+                    string=True)
+                self.file.write(
+                    '%s<layer type="%s" name="%s" checked="%d">\n' %
+                    (' ' * self.indent, type, EncodeString(cmd), checked))
                 self.file.write('%s</layer>\n' % (' ' * self.indent))
             elif type == 'group':
                 name = mapTree.GetItemText(item)
-                self.file.write('%s<group name="%s" checked="%d">\n' % \
-                               (' ' * self.indent, EncodeString(name), checked))
+                self.file.write(
+                    '%s<group name="%s" checked="%d">\n' %
+                    (' ' * self.indent, EncodeString(name), checked))
                 self.indent += 4
                 subItem = mapTree.GetFirstChild(item)[0]
                 self.__writeLayer(mapTree, subItem)
                 self.indent -= 4
-                self.file.write('%s</group>\n' % (' ' * self.indent));
+                self.file.write('%s</group>\n' % (' ' * self.indent))
             else:
-                cmd = mapTree.GetLayerInfo(item, key = 'maplayer').GetCmd(string = False)
+                cmd = mapTree.GetLayerInfo(
+                    item, key='maplayer').GetCmd(
+                    string=False)
                 name = mapTree.GetItemText(item).replace(os.linesep, '\\n')
                 opacity = maplayer.GetOpacity()
                 # remove 'opacity' part
                 if opacity < 1:
                     name = name.split('(', -1)[0].strip()
-                self.file.write('%s<layer type="%s" name="%s" checked="%d" opacity="%f">\n' % \
-                                    (' ' * self.indent, type, EncodeString(name), checked, opacity));
-                
+                self.file.write(
+                    '%s<layer type="%s" name="%s" checked="%d" opacity="%f">\n' %
+                    (' ' * self.indent, type, EncodeString(name), checked, opacity))
+
                 self.indent += 4
                 # selected ?
                 if item in itemSelected:
                     self.file.write('%s<selected />\n' % (' ' * self.indent))
                 # layer properties
-                self.file.write('%s<task name="%s">\n' % (' ' * self.indent, cmd[0]))
+                self.file.write(
+                    '%s<task name="%s">\n' %
+                    (' ' * self.indent, cmd[0]))
                 self.indent += 4
                 for key, val in cmd[1].iteritems():
                     if key == 'flags':
@@ -865,18 +938,21 @@
                     elif val in (True, False):
                         self.file.write('%s<flag name="%s" />\n' %
                                         (' ' * self.indent, key))
-                    else: # parameter
+                    else:  # parameter
                         self.file.write('%s<parameter name="%s">\n' %
                                         (' ' * self.indent, key))
                         self.indent += 4
-                        self.file.write('%s<value>%s</value>\n' %
-                                        (' ' * self.indent, self.__filterValue(val)))
+                        self.file.write(
+                            '%s<value>%s</value>\n' %
+                            (' ' * self.indent, self.__filterValue(val)))
                         self.indent -= 4
-                        self.file.write('%s</parameter>\n' % (' ' * self.indent))
+                        self.file.write(
+                            '%s</parameter>\n' %
+                            (' ' * self.indent))
                 self.indent -= 4
                 self.file.write('%s</task>\n' % (' ' * self.indent))
                 # vector digitizer
-                vdigit = mapTree.GetLayerInfo(item, key = 'vdigit')
+                vdigit = mapTree.GetLayerInfo(item, key='vdigit')
                 if vdigit:
                     self.file.write('%s<vdigit>\n' % (' ' * self.indent))
                     if 'geomAttr' in vdigit:
@@ -885,12 +961,13 @@
                             units = ''
                             if val['units'] != 'mu':
                                 units = ' units="%s"' % val['units']
-                            self.file.write('%s<geometryAttribute type="%s" column="%s"%s />\n' % \
-                                                (' ' * self.indent, type, val['column'], units))
+                            self.file.write(
+                                '%s<geometryAttribute type="%s" column="%s"%s />\n' %
+                                (' ' * self.indent, type, val['column'], units))
                         self.indent -= 4
                     self.file.write('%s</vdigit>\n' % (' ' * self.indent))
                 # nviz
-                nviz = mapTree.GetLayerInfo(item, key = 'nviz')
+                nviz = mapTree.GetLayerInfo(item, key='nviz')
                 if nviz:
                     self.file.write('%s<nviz>\n' % (' ' * self.indent))
                     if maplayer.type == 'raster':
@@ -904,70 +981,80 @@
                 self.file.write('%s</layer>\n' % (' ' * self.indent))
             item = mapTree.GetNextSibling(item)
         self.indent -= 4
-        
+
     def __writeNvizSurface(self, data):
         """Save Nviz raster layer properties to workspace
 
         :param data: Nviz layer properties
         """
-        if 'object' not in data: # skip disabled
+        if 'object' not in data:  # skip disabled
             return
         self.indent += 4
         self.file.write('%s<surface>\n' % (' ' * self.indent))
         self.indent += 4
         for attrb in data.iterkeys():
-            if len(data[attrb]) < 1: # skip empty attributes
+            if len(data[attrb]) < 1:  # skip empty attributes
                 continue
             if attrb == 'object':
                 continue
-            
+
             for name in data[attrb].iterkeys():
                 # surface attribute
                 if attrb == 'attribute':
                     if data[attrb][name]['map'] is None:
                         continue
-                    self.file.write('%s<%s name="%s" map="%d">\n' % \
-                                   (' ' * self.indent, attrb, name, data[attrb][name]['map']))
+                    self.file.write(
+                        '%s<%s name="%s" map="%d">\n' %
+                        (' ' * self.indent, attrb, name, data[attrb][name]['map']))
                     self.indent += 4
-                    self.file.write('%s<value>%s</value>\n' % (' ' * self.indent, data[attrb][name]['value']))
+                    self.file.write(
+                        '%s<value>%s</value>\n' %
+                        (' ' * self.indent, data[attrb][name]['value']))
                     self.indent -= 4
                     # end tag
                     self.file.write('%s</%s>\n' % (' ' * self.indent, attrb))
 
             # draw mode
             if attrb == 'draw':
-                self.file.write('%s<%s' %(' ' * self.indent, attrb))
+                self.file.write('%s<%s' % (' ' * self.indent, attrb))
                 if 'mode' in data[attrb]:
                     for tag, value in data[attrb]['mode']['desc'].iteritems():
                         self.file.write(' %s="%s"' % (tag, value))
-                self.file.write('>\n') # <draw ...>
+                self.file.write('>\n')  # <draw ...>
 
                 if 'resolution' in data[attrb]:
                     self.indent += 4
                     for type in ('coarse', 'fine'):
-                        self.file.write('%s<resolution type="%s">\n' % (' ' * self.indent, type))
+                        self.file.write(
+                            '%s<resolution type="%s">\n' %
+                            (' ' * self.indent, type))
                         self.indent += 4
-                        self.file.write('%s<value>%d</value>\n' % (' ' * self.indent,
-                                                                   data[attrb]['resolution'][type]))
+                        self.file.write(
+                            '%s<value>%d</value>\n' %
+                            (' ' * self.indent, data[attrb]['resolution'][type]))
                         self.indent -= 4
-                        self.file.write('%s</resolution>\n' % (' ' * self.indent))
+                        self.file.write(
+                            '%s</resolution>\n' %
+                            (' ' * self.indent))
 
                 if 'wire-color' in data[attrb]:
                     self.file.write('%s<wire_color>\n' % (' ' * self.indent))
                     self.indent += 4
-                    self.file.write('%s<value>%s</value>\n' % (' ' * self.indent,
-                                                               data[attrb]['wire-color']['value']))
+                    self.file.write(
+                        '%s<value>%s</value>\n' %
+                        (' ' * self.indent, data[attrb]['wire-color']['value']))
                     self.indent -= 4
                     self.file.write('%s</wire_color>\n' % (' ' * self.indent))
                 self.indent -= 4
-            
+
             # position
             elif attrb == 'position':
-                self.file.write('%s<%s>\n' %(' ' * self.indent, attrb))
+                self.file.write('%s<%s>\n' % (' ' * self.indent, attrb))
                 for tag in ('x', 'y', 'z'):
                     self.indent += 4
-                    self.file.write('%s<%s>%d</%s>\n' % (' ' * self.indent, tag,
-                                                        data[attrb][tag], tag))
+                    self.file.write(
+                        '%s<%s>%d</%s>\n' %
+                        (' ' * self.indent, tag, data[attrb][tag], tag))
                     self.indent -= 4
 
             if attrb != 'attribute':
@@ -999,10 +1086,13 @@
                     # surface attribute
                     if data[attrb][name]['map'] is None:
                         continue
-                    self.file.write('%s<%s name="%s" map="%d">\n' %
-                                   (' ' * self.indent, attrb, name, data[attrb][name]['map']))
+                    self.file.write(
+                        '%s<%s name="%s" map="%d">\n' %
+                        (' ' * self.indent, attrb, name, data[attrb][name]['map']))
                     self.indent += 4
-                    self.file.write('%s<value>%s</value>\n' % (' ' * self.indent, data[attrb][name]['value']))
+                    self.file.write(
+                        '%s<value>%s</value>\n' %
+                        (' ' * self.indent, data[attrb][name]['value']))
                     self.indent -= 4
                     # end tag
                     self.file.write('%s</%s>\n' % (' ' * self.indent, attrb))
@@ -1017,30 +1107,42 @@
                         self.file.write('%s<%s>\n' % (' ' * self.indent, att))
                         for type in ('isosurface', 'slice'):
                             self.indent += 4
-                            self.file.write('%s<%s>\n' % (' ' * self.indent, type))
+                            self.file.write(
+                                '%s<%s>\n' %
+                                (' ' * self.indent, type))
                             self.indent += 4
-                            self.file.write('%s<value>%d</value>\n' % (' ' * self.indent,
-                                                                       data[attrb][att][type]['value']))
+                            self.file.write(
+                                '%s<value>%d</value>\n' %
+                                (' ' * self.indent, data[attrb][att][type]['value']))
                             if att == 'shading':
-                                self.file.write('%s<desc>%s</desc>\n' % (' ' * self.indent,
-                                                                         data[attrb][att][type]['desc']))
+                                self.file.write(
+                                    '%s<desc>%s</desc>\n' %
+                                    (' ' * self.indent, data[attrb][att][type]['desc']))
                             self.indent -= 4
-                            self.file.write('%s</%s>\n' % (' ' * self.indent, type))
+                            self.file.write(
+                                '%s</%s>\n' %
+                                (' ' * self.indent, type))
                             self.indent -= 4
                         self.file.write('%s</%s>\n' % (' ' * self.indent, att))
 
                 if 'box' in data[attrb]:
                     self.file.write('%s<box>\n' % (' ' * self.indent))
                     self.indent += 4
-                    self.file.write('%s<enabled>%d</enabled>\n' % (' ' * self.indent, data[attrb]['box']['enabled']))
+                    self.file.write(
+                        '%s<enabled>%d</enabled>\n' %
+                        (' ' * self.indent, data[attrb]['box']['enabled']))
                     self.indent -= 4
                     self.file.write('%s</box>\n' % (' ' * self.indent))
 
                 if 'mode' in data[attrb]:
                     self.file.write('%s<mode>\n' % (' ' * self.indent))
                     self.indent += 4
-                    self.file.write('%s<desc>%s</desc>\n' % (' ' * self.indent, data[attrb]['mode']['desc']))
-                    self.file.write('%s<value>%d</value>\n' % (' ' * self.indent, data[attrb]['mode']['value']))
+                    self.file.write(
+                        '%s<desc>%s</desc>\n' %
+                        (' ' * self.indent, data[attrb]['mode']['desc']))
+                    self.file.write(
+                        '%s<value>%d</value>\n' %
+                        (' ' * self.indent, data[attrb]['mode']['value']))
                     self.indent -= 4
                     self.file.write('%s</mode>\n' % (' ' * self.indent))
                 self.indent -= 4
@@ -1050,8 +1152,15 @@
                 self.file.write('%s<%s>\n' % (' ' * self.indent, attrb))
                 for tag in ('x', 'y', 'z'):
                     self.indent += 4
-                    self.file.write('%s<%s>%d</%s>\n' % (' ' * self.indent, tag,
-                                                         data[attrb].get(tag, 0), tag))
+                    self.file.write(
+                        '%s<%s>%d</%s>\n' %
+                        (' ' *
+                         self.indent,
+                         tag,
+                         data[attrb].get(
+                             tag,
+                             0),
+                            tag))
                     self.indent -= 4
             if attrb == 'isosurface':
                 for isosurface in data[attrb]:
@@ -1072,11 +1181,15 @@
                                 except TypeError:  # None
                                     val = ''
                             self.indent += 4
-                            self.file.write(('%s<%s>' % (' ' * self.indent, att)) + val)
+                            self.file.write(
+                                ('%s<%s>' %
+                                 (' ' * self.indent, att)) + val)
                             self.file.write('</%s>\n' % att)
                             self.indent -= 4
                         # end tag
-                        self.file.write('%s</%s>\n' % (' ' * self.indent, name))
+                        self.file.write(
+                            '%s</%s>\n' %
+                            (' ' * self.indent, name))
                         self.indent -= 4
                     self.file.write('%s</%s>\n' % (' ' * self.indent, attrb))
 
@@ -1091,11 +1204,15 @@
                                 continue
                             val = slice_[name][att]
                             self.indent += 4
-                            self.file.write(('%s<%s>' % (' ' * self.indent, att)) + str(val))
+                            self.file.write(
+                                ('%s<%s>' %
+                                 (' ' * self.indent, att)) + str(val))
                             self.file.write('</%s>\n' % att)
                             self.indent -= 4
                         # end tag
-                        self.file.write('%s</%s>\n' % (' ' * self.indent, name))
+                        self.file.write(
+                            '%s</%s>\n' %
+                            (' ' * self.indent, name))
                         self.indent -= 4
                     self.file.write('%s</%s>\n' % (' ' * self.indent, attrb))
             if attrb not in ('attribute', 'isosurface', 'slice'):
@@ -1113,17 +1230,18 @@
         """
         self.indent += 4
         for attrb in data.iterkeys():
-            if len(data[attrb]) < 1: # skip empty attributes
+            if len(data[attrb]) < 1:  # skip empty attributes
                 continue
 
-            if 'object' not in data[attrb]: # skip disabled
+            if 'object' not in data[attrb]:  # skip disabled
                 continue
             if attrb == 'lines':
                 self.file.write('%s<v%s>\n' % (' ' * self.indent, attrb))
             elif attrb == 'points':
                 markerId = data[attrb]['marker']['value']
-                marker = UserSettings.Get(group = 'nviz', key = 'vector',
-                                          subkey = ['points', 'marker'], settings_type='internal')[markerId]
+                marker = UserSettings.Get(
+                    group='nviz', key='vector', subkey=[
+                        'points', 'marker'], settings_type='internal')[markerId]
                 self.file.write('%s<v%s marker="%s">\n' % (' ' * self.indent,
                                                            attrb,
                                                            marker))
@@ -1132,16 +1250,22 @@
                 if name in ('object', 'marker'):
                     continue
                 if name == 'mode':
-                    self.file.write('%s<%s type="%s">\n' % (' ' * self.indent, name,
-                                                          data[attrb][name]['type']))
+                    self.file.write(
+                        '%s<%s type="%s">\n' %
+                        (' ' * self.indent, name, data[attrb][name]['type']))
                     if data[attrb][name]['type'] == 'surface':
                         self.indent += 4
-                        for idx, surface in enumerate(data[attrb][name]['surface']['value']):
+                        for idx, surface in enumerate(
+                                data[attrb][name]['surface']['value']):
                             checked = data[attrb][name]['surface']['show'][idx]
                             self.file.write('%s<map>\n' % (' ' * self.indent))
                             self.indent += 4
-                            self.file.write('%s<name>%s</name>\n' % (' ' * self.indent, surface))
-                            self.file.write('%s<checked>%s</checked>\n' % (' ' * self.indent, int(checked)))
+                            self.file.write(
+                                '%s<name>%s</name>\n' %
+                                (' ' * self.indent, surface))
+                            self.file.write(
+                                '%s<checked>%s</checked>\n' %
+                                (' ' * self.indent, int(checked)))
                             self.indent -= 4
                             self.file.write('%s</map>\n' % (' ' * self.indent))
                         self.indent -= 4
@@ -1150,7 +1274,9 @@
                     self.file.write('%s<%s ' % (' ' * self.indent, name))
                     for key in data[attrb][name].iterkeys():
                         if key.startswith('use'):
-                            self.file.write('%s="%s" ' % (key, int(data[attrb][name][key])))
+                            self.file.write(
+                                '%s="%s" ' %
+                                (key, int(data[attrb][name][key])))
                     self.file.write('>\n')
                     self.indent += 4
                     for key, value in data[attrb][name].iteritems():
@@ -1158,13 +1284,17 @@
                             continue
                         if value is None:
                             value = ''
-                        self.file.write('%s<%s>%s</%s>\n' % (' ' * self.indent, key, value, key))
+                        self.file.write(
+                            '%s<%s>%s</%s>\n' %
+                            (' ' * self.indent, key, value, key))
                     self.indent -= 4
                     self.file.write('%s</%s>\n' % (' ' * self.indent, name))
                 else:
                     self.file.write('%s<%s>\n' % (' ' * self.indent, name))
                     self.indent += 4
-                    self.file.write('%s<value>%s</value>\n' % (' ' * self.indent, data[attrb][name]['value']))
+                    self.file.write(
+                        '%s<value>%s</value>\n' %
+                        (' ' * self.indent, data[attrb][name]['value']))
                     self.indent -= 4
                     self.file.write('%s</%s>\n' % (' ' * self.indent, name))
             self.indent -= 4
@@ -1190,59 +1320,91 @@
         # position
         self.file.write('%s<v_position>\n' % (' ' * self.indent))
         self.indent += 4
-        self.file.write('%s<x>%.2f</x>\n' % (' ' * self.indent, view['position']['x']))
-        self.file.write('%s<y>%.2f</y>\n' % (' ' * self.indent, view['position']['y']))
+        self.file.write(
+            '%s<x>%.2f</x>\n' %
+            (' ' * self.indent, view['position']['x']))
+        self.file.write(
+            '%s<y>%.2f</y>\n' %
+            (' ' * self.indent, view['position']['y']))
         self.indent -= 4
         self.file.write('%s</v_position>\n' % (' ' * self.indent))
         # perspective
         self.file.write('%s<persp>\n' % (' ' * self.indent))
         self.indent += 4
-        self.file.write('%s<value>%d</value>\n' % (' ' * self.indent, view['persp']['value']))
-        self.file.write('%s<step>%d</step>\n' % (' ' * self.indent, view['persp']['step']))
-        self.file.write('%s<min>%d</min>\n' % (' ' * self.indent, iview['persp']['min']))
-        self.file.write('%s<max>%d</max>\n' % (' ' * self.indent, iview['persp']['max']))
+        self.file.write('%s<value>%d</value>\n' %
+                        (' ' * self.indent, view['persp']['value']))
+        self.file.write('%s<step>%d</step>\n' %
+                        (' ' * self.indent, view['persp']['step']))
+        self.file.write('%s<min>%d</min>\n' %
+                        (' ' * self.indent, iview['persp']['min']))
+        self.file.write('%s<max>%d</max>\n' %
+                        (' ' * self.indent, iview['persp']['max']))
         self.indent -= 4
         self.file.write('%s</persp>\n' % (' ' * self.indent))
         # height
         self.file.write('%s<v_height>\n' % (' ' * self.indent))
         self.indent += 4
-        self.file.write('%s<value>%d</value>\n' % (' ' * self.indent, iview['height']['value']))
-        self.file.write('%s<min>%d</min>\n' % (' ' * self.indent, iview['height']['min']))
-        self.file.write('%s<max>%d</max>\n' % (' ' * self.indent, iview['height']['max']))
+        self.file.write('%s<value>%d</value>\n' %
+                        (' ' * self.indent, iview['height']['value']))
+        self.file.write('%s<min>%d</min>\n' %
+                        (' ' * self.indent, iview['height']['min']))
+        self.file.write('%s<max>%d</max>\n' %
+                        (' ' * self.indent, iview['height']['max']))
         self.indent -= 4
         self.file.write('%s</v_height>\n' % (' ' * self.indent))
         # twist
         self.file.write('%s<twist>\n' % (' ' * self.indent))
         self.indent += 4
-        self.file.write('%s<value>%d</value>\n' % (' ' * self.indent, view['twist']['value']))
-        self.file.write('%s<min>%d</min>\n' % (' ' * self.indent, iview['twist']['min']))
-        self.file.write('%s<max>%d</max>\n' % (' ' * self.indent, iview['twist']['max']))
+        self.file.write('%s<value>%d</value>\n' %
+                        (' ' * self.indent, view['twist']['value']))
+        self.file.write('%s<min>%d</min>\n' %
+                        (' ' * self.indent, iview['twist']['min']))
+        self.file.write('%s<max>%d</max>\n' %
+                        (' ' * self.indent, iview['twist']['max']))
         self.indent -= 4
         self.file.write('%s</twist>\n' % (' ' * self.indent))
         # z-exag
         self.file.write('%s<z-exag>\n' % (' ' * self.indent))
         self.indent += 4
-        self.file.write('%s<value>%.2f</value>\n' % (' ' * self.indent, view['z-exag']['value']))
-        self.file.write('%s<min>%d</min>\n' % (' ' * self.indent, view['z-exag']['min']))
-        self.file.write('%s<max>%d</max>\n' % (' ' * self.indent, view['z-exag']['max']))
-        self.file.write('%s<llRatio>%.2f</llRatio>\n' % (' ' * self.indent, iview['z-exag']['llRatio']))
+        self.file.write('%s<value>%.2f</value>\n' %
+                        (' ' * self.indent, view['z-exag']['value']))
+        self.file.write('%s<min>%d</min>\n' %
+                        (' ' * self.indent, view['z-exag']['min']))
+        self.file.write('%s<max>%d</max>\n' %
+                        (' ' * self.indent, view['z-exag']['max']))
+        self.file.write('%s<llRatio>%.2f</llRatio>\n' %
+                        (' ' * self.indent, iview['z-exag']['llRatio']))
         self.indent -= 4
         self.file.write('%s</z-exag>\n' % (' ' * self.indent))
         # focus (look here)
         self.file.write('%s<focus>\n' % (' ' * self.indent))
         self.indent += 4
-        self.file.write('%s<x>%d</x>\n' % (' ' * self.indent, iview['focus']['x']))
-        self.file.write('%s<y>%d</y>\n' % (' ' * self.indent, iview['focus']['y']))
-        self.file.write('%s<z>%d</z>\n' % (' ' * self.indent, iview['focus']['z']))
+        self.file.write(
+            '%s<x>%d</x>\n' %
+            (' ' * self.indent, iview['focus']['x']))
+        self.file.write(
+            '%s<y>%d</y>\n' %
+            (' ' * self.indent, iview['focus']['y']))
+        self.file.write(
+            '%s<z>%d</z>\n' %
+            (' ' * self.indent, iview['focus']['z']))
         self.indent -= 4
         self.file.write('%s</focus>\n' % (' ' * self.indent))
         # rotation
-        rotation = ','.join([str(i) for i in iview['rotation']]) if iview.get('rotation', '') else ''
-        self.file.write('%s<rotation>%s</rotation>\n' % (' ' * self.indent, rotation))
+        rotation = ','.join(
+            [str(i) for i in iview['rotation']]) if iview.get(
+            'rotation', '') else ''
+        self.file.write(
+            '%s<rotation>%s</rotation>\n' %
+            (' ' * self.indent, rotation))
 
         # background
-        self.__writeTagWithValue('background_color', view['background']['color'][:3], format = 'd:%d:%d')
-        
+        self.__writeTagWithValue(
+            'background_color',
+            view['background']['color'][
+                :3],
+            format='d:%d:%d')
+
         self.indent -= 4
         self.file.write('%s</view>\n' % (' ' * self.indent))
         #
@@ -1253,9 +1415,15 @@
         # position
         self.file.write('%s<l_position>\n' % (' ' * self.indent))
         self.indent += 4
-        self.file.write('%s<x>%.2f</x>\n' % (' ' * self.indent, light['position']['x']))
-        self.file.write('%s<y>%.2f</y>\n' % (' ' * self.indent, light['position']['y']))
-        self.file.write('%s<z>%d</z>\n' % (' ' * self.indent, light['position']['z']))
+        self.file.write(
+            '%s<x>%.2f</x>\n' %
+            (' ' * self.indent, light['position']['x']))
+        self.file.write(
+            '%s<y>%.2f</y>\n' %
+            (' ' * self.indent, light['position']['y']))
+        self.file.write(
+            '%s<z>%d</z>\n' %
+            (' ' * self.indent, light['position']['z']))
         self.indent -= 4
         self.file.write('%s</l_position>\n' % (' ' * self.indent))
         # bright
@@ -1263,8 +1431,8 @@
         # ambient
         self.__writeTagWithValue('ambient', light['ambient'])
         # color
-        self.__writeTagWithValue('color', light['color'][:3], format = 'd:%d:%d')
-        
+        self.__writeTagWithValue('color', light['color'][:3], format='d:%d:%d')
+
         self.indent -= 4
         self.file.write('%s</light>\n' % (' ' * self.indent))
         #
@@ -1276,21 +1444,25 @@
             for idx, plane in enumerate(constants):
                 self.file.write('%s<plane>\n' % (' ' * self.indent))
                 self.indent += 4
-                self.__writeTagWithValue('height', constants[idx]['constant']['value'])
-                self.__writeTagWithValue('fine_resolution', constants[idx]['constant']['resolution'])
-                self.__writeTagWithValue('color', constants[idx]['constant']['color'], format = 's')
+                self.__writeTagWithValue(
+                    'height', constants[idx]['constant']['value'])
+                self.__writeTagWithValue(
+                    'fine_resolution',
+                    constants[idx]['constant']['resolution'])
+                self.__writeTagWithValue(
+                    'color', constants[idx]['constant']['color'], format='s')
                 self.indent -= 4
                 self.file.write('%s</plane>\n' % (' ' * self.indent))
             self.indent -= 4
             self.file.write('%s</constant_planes>\n' % (' ' * self.indent))
         self.indent -= 4
-        
+
         self.file.write('%s</nviz_state>\n' % (' ' * self.indent))
         self.indent -= 4
-    
-    def __writeTagWithValue(self, tag, data, format = 'd'):
+
+    def __writeTagWithValue(self, tag, data, format='d'):
         """Helper function for writing pair tag
-        
+
         :param tag: written tag
         :param data: written data
         :param format: conversion type
@@ -1301,8 +1473,10 @@
         self.file.write(('<value>%' + format + '</value>\n') % data)
         self.indent -= 4
         self.file.write('%s</%s>\n' % (' ' * self.indent, tag))
-        
+
+
 class ProcessGrcFile(object):
+
     def __init__(self, filename):
         """Process GRC file"""
         self.filename = filename
@@ -1329,26 +1503,34 @@
         try:
             file = open(self.filename, "r")
         except IOError:
-            wx.MessageBox(parent=parent,
-                          message=_("Unable to open file <%s> for reading.") % self.filename,
-                          caption=_("Error"), style=wx.OK | wx.ICON_ERROR)
+            wx.MessageBox(
+                parent=parent,
+                message=_("Unable to open file <%s> for reading.") %
+                self.filename,
+                caption=_("Error"),
+                style=wx.OK | wx.ICON_ERROR)
             return []
 
         line_id = 1
         for line in file.readlines():
             self.process_line(line.rstrip('\n'), line_id)
-            line_id +=1
+            line_id += 1
 
         file.close()
 
         if self.num_error > 0:
-            wx.MessageBox(parent=parent,
-                          message=_("Some lines were skipped when reading settings "
-                                    "from file <%(file)s>.\nSee 'Command output' window for details.\n\n"
-                                    "Number of skipped lines: %(line)d") % \
-                                        { 'file' : self.filename, 'line' : self.num_error },
-                          caption=_("Warning"), style=wx.OK | wx.ICON_EXCLAMATION)
-            parent._gconsole.WriteLog('Map layers loaded from GRC file <%s>' % self.filename)
+            wx.MessageBox(
+                parent=parent,
+                message=_(
+                    "Some lines were skipped when reading settings "
+                    "from file <%(file)s>.\nSee 'Command output' window for details.\n\n"
+                    "Number of skipped lines: %(line)d") %
+                {'file': self.filename, 'line': self.num_error},
+                caption=_("Warning"),
+                style=wx.OK | wx.ICON_EXCLAMATION)
+            parent._gconsole.WriteLog(
+                'Map layers loaded from GRC file <%s>' %
+                self.filename)
             parent._gconsole.WriteLog('Skipped lines:\n%s' % self.error)
 
         return self.layers
@@ -1359,21 +1541,21 @@
         if element == 'Group':
             self.groupName = self._get_value(line)
             self.layers.append({
-                    "type"    : 'group',
-                    "name"    : self.groupName,
-                    "checked" : None,
-                    "opacity" : None,
-                    "cmd"     : None,
-                    "group"   : self.inGroup,
-                    "display" : 0 })
+                "type": 'group',
+                "name": self.groupName,
+                "checked": None,
+                "opacity": None,
+                "cmd": None,
+                "group": self.inGroup,
+                "display": 0})
             self.inGroup = True
 
         elif element == '_check':
-            if int(self._get_value(line)) ==  1:
+            if int(self._get_value(line)) == 1:
                 self.layers[-1]['checked'] = True
             else:
                 self.layers[-1]['checked'] = False
-            
+
         elif element == 'End':
             if self.inRaster:
                 self.inRaster = False
@@ -1383,7 +1565,7 @@
                 self.inGroup = False
             elif self.inGridline:
                 self.inGridline = False
-        
+
         elif element == 'opacity':
             self.layers[-1]['opacity'] = float(self._get_value(line))
 
@@ -1391,26 +1573,26 @@
         elif element == 'Raster':
             self.inRaster = True
             self.layers.append({
-                    "type"    : 'raster',
-                    "name"    : self._get_value(line),
-                    "checked" : None,
-                    "opacity" : None,
-                    "cmd"     : ['d.rast'],
-                    "group"   : self.inGroup,
-                    "display" : 0})
+                "type": 'raster',
+                "name": self._get_value(line),
+                "checked": None,
+                "opacity": None,
+                "cmd": ['d.rast'],
+                "group": self.inGroup,
+                "display": 0})
 
         elif element == 'map' and self.inRaster:
             self.layers[-1]['cmd'].append('map=%s' % self._get_value(line))
-            
+
         elif element == 'overlay' and self.inRaster:
             if int(self._get_value(line)) == 1:
                 self.layers[-1]['cmd'].append('-o')
-            
+
         elif element == 'rastquery' and self.inRaster:
             value = self._get_value(line)
             if value != '':
                 self.layers[-1]['cmd'].append('catlist=%s' % value)
-            
+
         elif element == 'bkcolor' and self.inRaster:
             value = self._get_value(line)
             if value != '':
@@ -1420,17 +1602,17 @@
         elif element == 'Vector':
             self.inVector = True
             self.layers.append({
-                    "type"    : 'vector',
-                    "name"    : self._get_value(line),
-                    "checked" : None,
-                    "opacity" : None,
-                    "cmd"     : ['d.vect'],
-                    "group"   : self.inGroup,
-                    "display" : 0})
+                "type": 'vector',
+                "name": self._get_value(line),
+                "checked": None,
+                "opacity": None,
+                "cmd": ['d.vect'],
+                "group": self.inGroup,
+                "display": 0})
 
         elif element == 'vector' and self.inVector:
             self.layers[-1]['cmd'].append('map=%s' % self._get_value(line))
-                
+
         elif element in ('display_shape',
                          'display_cat',
                          'display_topo',
@@ -1442,11 +1624,12 @@
                          'type_centroid',
                          'type_area',
                          'type_face') and self.inVector:
-            
+
             if int(self._get_value(line)) == 1:
                 name = element.split('_')[0]
                 type = element.split('_')[1]
-                paramId = self._get_cmd_param_index(self.layers[-1]['cmd'], name)
+                paramId = self._get_cmd_param_index(
+                    self.layers[-1]['cmd'], name)
                 if paramId == -1:
                     self.layers[-1]['cmd'].append('%s=%s' % (name, type))
                 else:
@@ -1457,8 +1640,8 @@
                          'lcolor') and self.inVector:
             value = self._get_value(line)
             if value != '':
-                self.layers[-1]['cmd'].append('%s=%s' % (element,
-                                                         self._color_name_to_rgb(value)))
+                self.layers[-1]['cmd'].append('%s=%s' %
+                                              (element, self._color_name_to_rgb(value)))
 
         elif element == 'rdmcolor' and self.inVector:
             if int(self._get_value(line)) == 1:
@@ -1481,7 +1664,7 @@
             if value != '':
                 self.layers[-1]['cmd'].append('%s=%s' % (element,
                                                          value))
-        
+
         elif element == 'lwidth':
             value = self._get_value(line)
             if value != '':
@@ -1491,7 +1674,7 @@
             value = self._get_value(line)
             if value != '':
                 self.layers[-1]['cmd'].append('llayer=%s' % value)
-                                        
+
         elif element == 'attribute':
             value = self._get_value(line)
             if value != '':
@@ -1506,28 +1689,31 @@
         elif element == 'gridline':
             self.inGridline = True
             self.layers.append({
-                    "type"    : 'grid',
-                    "name"    : self._get_value(line),
-                    "checked" : None,
-                    "opacity" : None,
-                    "cmd"     : ['d.grid'],
-                    "group"   : self.inGroup,
-                    "display" : 0})
+                "type": 'grid',
+                "name": self._get_value(line),
+                "checked": None,
+                "opacity": None,
+                "cmd": ['d.grid'],
+                "group": self.inGroup,
+                "display": 0})
 
         elif element == 'gridcolor':
             value = self._get_value(line)
             if value != '':
-                self.layers[-1]['cmd'].append('color=%s' % self._color_name_to_rgb(value))
+                self.layers[-1]['cmd'].append('color=%s' %
+                                              self._color_name_to_rgb(value))
 
         elif element == 'gridborder':
             value = self._get_value(line)
             if value != '':
-                self.layers[-1]['cmd'].append('bordercolor=%s' % self._color_name_to_rgb(value))
+                self.layers[-1]['cmd'].append('bordercolor=%s' %
+                                              self._color_name_to_rgb(value))
 
         elif element == 'textcolor':
             value = self._get_value(line)
             if value != '':
-                self.layers[-1]['cmd'].append('textcolor=%s' % self._color_name_to_rgb(value))
+                self.layers[-1]['cmd'].append('textcolor=%s' %
+                                              self._color_name_to_rgb(value))
 
         elif element in ('gridsize',
                          'gridorigin'):
@@ -1539,17 +1725,17 @@
             value = self._get_value(line)
             if value != '':
                 self.layers[-1]['cmd'].append('%s=%s' % (element, value))
-        
+
         elif element == 'griddraw':
             value = self._get_value(line)
             if value == '0':
                 self.layers[-1]['cmd'].append('-n')
-                
+
         elif element == 'gridgeo':
             value = self._get_value(line)
             if value == '1':
                 self.layers[-1]['cmd'].append('-g')
-        
+
         elif element == 'borderdraw':
             value = self._get_value(line)
             if value == '0':
@@ -1559,7 +1745,7 @@
             value = self._get_value(line)
             if value == '0':
                 self.layers[-1]['cmd'].append('-t')
-        
+
         else:
             self.error += _(' row %d:') % line_id + line + os.linesep
             self.num_error += 1

Modified: grass/trunk/gui/wxpython/core/ws.py
===================================================================
--- grass/trunk/gui/wxpython/core/ws.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/ws.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -27,15 +27,15 @@
 from grass.script import core as grass
 from grass.exceptions import CalledModuleError
 
-from core          import utils
-from core.debug    import Debug
-from core.gthread import  gThread
+from core import utils
+from core.debug import Debug
+from core.gthread import gThread
 from core.utils import _
 
 try:
     haveGdal = True
     from osgeo import gdal
-    from osgeo import gdalconst 
+    from osgeo import gdalconst
 except ImportError:
     haveGdal = False
 
@@ -45,13 +45,14 @@
 class RenderWMSMgr(wx.EvtHandler):
     """Fetch and prepare WMS data for rendering.
     """
+
     def __init__(self, layer, env):
         if not haveGdal:
-            sys.stderr.write(_("Unable to load GDAL Python bindings.\n"\
+            sys.stderr.write(_("Unable to load GDAL Python bindings.\n"
                                "WMS layers can not be displayed without the bindings.\n"))
 
         self.layer = layer
-        
+
         wx.EvtHandler.__init__(self)
 
         # thread for d.wms commands
@@ -65,7 +66,7 @@
 
         self.tempMap = grass.tempfile()
         self.dstSize = {}
- 
+
         self.dataFetched = Signal('RenderWMSMgr.dataFetched')
         self.updateProgress = Signal('RenderWMSMgr.updateProgress')
 
@@ -82,7 +83,7 @@
         if not haveGdal:
             return
 
-        Debug.msg(1, "RenderWMSMgr.Render(%s): force=%d img=%s" % \
+        Debug.msg(1, "RenderWMSMgr.Render(%s): force=%d img=%s" %
                   (self.layer, self.layer.forceRender, self.layer.mapfile))
 
         env = copy.copy(env)
@@ -93,7 +94,7 @@
         self._fitAspect(region, self.dstSize)
 
         self.updateMap = True
-        fetchData = True # changed to True when calling Render()
+        fetchData = True  # changed to True when calling Render()
         zoomChanged = False
 
         if self.renderedRegion is None or \
@@ -108,7 +109,7 @@
 
             for c in ['e-w resol', 'n-s resol']:
                 if self.renderedRegion and \
-                    region[c] != self.renderedRegion[c]:
+                        region[c] != self.renderedRegion[c]:
                     zoomChanged = True
                     break
 
@@ -120,7 +121,7 @@
             try_remove(self.tempMap)
 
             self.currentPid = self.thread.GetId()
-            ### self.thread.Terminate()
+            # self.thread.Terminate()
             self.downloading = True
 
             self.fetching_cmd = cmd
@@ -129,15 +130,15 @@
             env["GRASS_REGION"] = self._createRegionStr(region)
 
             cmd_render = copy.deepcopy(cmd)
-            cmd_render[1]['quiet'] = True # be quiet
-        
+            cmd_render[1]['quiet'] = True  # be quiet
+
             self._startTime = time.time()
             self.thread.Run(callable=self._render, cmd=cmd_render, env=env,
                             ondone=self.OnRenderDone)
             self.layer.forceRender = False
-            
+
         self.updateProgress.emit(layer=self.layer)
-        
+
     def _render(self, cmd, env):
         try:
             return grass.run_command(cmd[0], env=env, **cmd[1])
@@ -157,23 +158,30 @@
             self.fetched_data_cmd = None
             return
 
-        self.mapMerger = GDALRasterMerger(targetFile = self.layer.mapfile,
-                                          region = self.renderedRegion,
-                                          bandsNum = 3, gdalDriver = 'PNM', fillValue = 0)
-        self.mapMerger.AddRasterBands(self.tempMap, {1 : 1, 2 : 2, 3 : 3})
+        self.mapMerger = GDALRasterMerger(
+            targetFile=self.layer.mapfile,
+            region=self.renderedRegion,
+            bandsNum=3,
+            gdalDriver='PNM',
+            fillValue=0)
+        self.mapMerger.AddRasterBands(self.tempMap, {1: 1, 2: 2, 3: 3})
         del self.mapMerger
 
-        self.maskMerger = GDALRasterMerger(targetFile = self.layer.maskfile, region = self.renderedRegion,
-                                           bandsNum = 1, gdalDriver = 'PNM', fillValue = 0)
+        self.maskMerger = GDALRasterMerger(
+            targetFile=self.layer.maskfile,
+            region=self.renderedRegion,
+            bandsNum=1,
+            gdalDriver='PNM',
+            fillValue=0)
         #{4 : 1} alpha channel (4) to first and only channel (1) in mask
-        self.maskMerger.AddRasterBands(self.tempMap, {4 : 1}) 
+        self.maskMerger.AddRasterBands(self.tempMap, {4: 1})
         del self.maskMerger
 
         self.fetched_data_cmd = self.fetching_cmd
 
-        Debug.msg(1, "RenderWMSMgr.OnRenderDone(%s): ret=%d time=%f" % \
-                      (self.layer, event.ret, time.time() - self._startTime))
-        
+        Debug.msg(1, "RenderWMSMgr.OnRenderDone(%s): ret=%d time=%f" %
+                  (self.layer, event.ret, time.time() - self._startTime))
+
         self.dataFetched.emit(layer=self.layer)
 
     def _getRegionDict(self, env):
@@ -209,7 +217,7 @@
         return regionStr
 
     def IsDownloading(self):
-        """Is it downloading any data from WMS server? 
+        """Is it downloading any data from WMS server?
         """
         return self.downloading
 
@@ -219,7 +227,7 @@
         if region['n-s resol'] > region['e-w resol']:
             delta = region['n-s resol'] * size['cols'] / 2
 
-            center = (region['east'] - region['west'])/2
+            center = (region['east'] - region['west']) / 2
 
             region['east'] = center + delta + region['west']
             region['west'] = center - delta + region['west']
@@ -228,7 +236,7 @@
         else:
             delta = region['e-w resol'] * size['rows'] / 2
 
-            center = (region['north'] - region['south'])/2 
+            center = (region['north'] - region['south']) / 2
 
             region['north'] = center + delta + region['south']
             region['south'] = center - delta + region['south']
@@ -238,18 +246,21 @@
         """Abort rendering process"""
         Debug.msg(1, "RenderWMSMgr({}).Abort()".format(self.layer))
         self.thread.Terminate()
-        
+
         # force rendering layer next time
         self.layer.forceRender = True
         self.updateMap = False
         self.thread.Terminate(False)
 
+
 class GDALRasterMerger:
     """Merge rasters.
 
         Based on gdal_merge.py utility.
     """
-    def __init__(self, targetFile, region, bandsNum, gdalDriver, fillValue = None):
+
+    def __init__(self, targetFile, region, bandsNum,
+                 gdalDriver, fillValue=None):
         """Create raster for merging.
         """
         self.gdalDrvType = gdalDriver
@@ -257,12 +268,19 @@
         nsRes = (region['south'] - region['north']) / region['rows']
         ewRes = (region['east'] - region['west']) / region['cols']
 
-        self.tGeotransform = [region['west'], ewRes, 0, region['north'], 0, nsRes]
+        self.tGeotransform = [
+            region['west'],
+            ewRes, 0, region['north'],
+            0, nsRes]
 
-        self.tUlx, self.tUly, self.tLrx, self.tLry = self._getCorners(self.tGeotransform, region)
+        self.tUlx, self.tUly, self.tLrx, self.tLry = self._getCorners(
+            self.tGeotransform, region)
 
         driver = gdal.GetDriverByName(self.gdalDrvType)
-        self.tDataset = driver.Create(targetFile, region['cols'], region['rows'], bandsNum,  gdal.GDT_Byte)
+        self.tDataset = driver.Create(
+            targetFile, region['cols'],
+            region['rows'],
+            bandsNum, gdal.GDT_Byte)
 
         if fillValue is not None:
             # fill raster bands with a constant value
@@ -272,29 +290,29 @@
     def AddRasterBands(self, sourceFile, sTBands):
         """Add raster bands from sourceFile into the merging raster.
         """
-        sDataset = gdal.Open(sourceFile, gdal.GA_ReadOnly) 
+        sDataset = gdal.Open(sourceFile, gdal.GA_ReadOnly)
         if sDataset is None:
             return
 
         sGeotransform = sDataset.GetGeoTransform()
 
         sSize = {
-                    'rows' :  sDataset.RasterYSize,
-                    'cols' :  sDataset.RasterXSize
-                 }
+            'rows': sDataset.RasterYSize,
+            'cols': sDataset.RasterXSize
+        }
 
         sUlx, sUly, sLrx, sLry = self._getCorners(sGeotransform, sSize)
 
         # figure out intersection region
-        tIntsctUlx = max(self.tUlx,sUlx)
-        tIntsctLrx = min(self.tLrx,sLrx)
+        tIntsctUlx = max(self.tUlx, sUlx)
+        tIntsctLrx = min(self.tLrx, sLrx)
         if self.tGeotransform[5] < 0:
-            tIntsctUly = min(self.tUly,sUly)
-            tIntsctLry = max(self.tLry,sLry)
+            tIntsctUly = min(self.tUly, sUly)
+            tIntsctLry = max(self.tLry, sLry)
         else:
-            tIntsctUly = max(self.tUly,sUly)
-            tIntsctLry = min(self.tLry,sLry)
-        
+            tIntsctUly = max(self.tUly, sUly)
+            tIntsctLry = min(self.tLry, sLry)
+
         # do they even intersect?
         if tIntsctUlx >= tIntsctLrx:
             return
@@ -303,12 +321,21 @@
         if self.tGeotransform[5] > 0 and tIntsctUly >= tIntsctLry:
             return
 
-
         # compute target window in pixel coordinates.
-        tXoff = int((tIntsctUlx - self.tGeotransform[0]) / self.tGeotransform[1] + 0.1)
-        tYoff = int((tIntsctUly - self.tGeotransform[3]) / self.tGeotransform[5] + 0.1)
-        tXsize = int((tIntsctLrx - self.tGeotransform[0])/self.tGeotransform[1] + 0.5) - tXoff
-        tYsize = int((tIntsctLry - self.tGeotransform[3])/self.tGeotransform[5] + 0.5) - tYoff
+        tXoff = int(
+            (tIntsctUlx -
+             self.tGeotransform[0]) /
+            self.tGeotransform[1] +
+            0.1)
+        tYoff = int(
+            (tIntsctUly -
+             self.tGeotransform[3]) /
+            self.tGeotransform[5] +
+            0.1)
+        tXsize = int(
+            (tIntsctLrx - self.tGeotransform[0]) / self.tGeotransform[1] + 0.5) - tXoff
+        tYsize = int(
+            (tIntsctLry - self.tGeotransform[3]) / self.tGeotransform[5] + 0.5) - tYoff
 
         if tXsize < 1 or tYsize < 1:
             return
@@ -316,17 +343,19 @@
         # Compute source window in pixel coordinates.
         sXoff = int((tIntsctUlx - sGeotransform[0]) / sGeotransform[1])
         sYoff = int((tIntsctUly - sGeotransform[3]) / sGeotransform[5])
-        sXsize = int((tIntsctLrx - sGeotransform[0]) / sGeotransform[1] + 0.5) - sXoff
-        sYsize = int((tIntsctLry - sGeotransform[3]) / sGeotransform[5] + 0.5) - sYoff
+        sXsize = int(
+            (tIntsctLrx - sGeotransform[0]) / sGeotransform[1] + 0.5) - sXoff
+        sYsize = int(
+            (tIntsctLry - sGeotransform[3]) / sGeotransform[5] + 0.5) - sYoff
 
         if sXsize < 1 or sYsize < 1:
             return
 
         for sBandNnum, tBandNum in sTBands.iteritems():
-            bandData = sDataset.GetRasterBand(sBandNnum).ReadRaster(sXoff, sYoff, sXsize,
-                                                                    sYsize, tXsize, tYsize, gdal.GDT_Byte)
-            self.tDataset.GetRasterBand(tBandNum).WriteRaster(tXoff, tYoff, tXsize, tYsize, bandData, 
-                                                              tXsize, tYsize, gdal.GDT_Byte)
+            bandData = sDataset.GetRasterBand(sBandNnum).ReadRaster(
+                sXoff, sYoff, sXsize, sYsize, tXsize, tYsize, gdal.GDT_Byte)
+            self.tDataset.GetRasterBand(tBandNum).WriteRaster(
+                tXoff, tYoff, tXsize, tYsize, bandData, tXsize, tYsize, gdal.GDT_Byte)
 
     def _getCorners(self, geoTrans, size):
 
@@ -335,13 +364,13 @@
         lrx = geoTrans[0] + size['cols'] * geoTrans[1]
         lry = geoTrans[3] + size['rows'] * geoTrans[5]
 
-        return ulx, uly, lrx, lry 
+        return ulx, uly, lrx, lry
 
     def SetGeorefAndProj(self):
         """Set georeference and projection to target file
         """
-        projection = grass.read_command('g.proj', 
-                                        flags = 'wf')
+        projection = grass.read_command('g.proj',
+                                        flags='wf')
         self.tDataset.SetProjection(projection)
 
         self.tDataset.SetGeoTransform(self.tGeotransform)

Modified: grass/trunk/gui/wxpython/datacatalog/catalog.py
===================================================================
--- grass/trunk/gui/wxpython/datacatalog/catalog.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/datacatalog/catalog.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -25,21 +25,23 @@
 
 from grass.pydispatch.signal import Signal
 
+
 class DataCatalog(wx.Panel):
     """Data catalog panel"""
-    def __init__(self, parent, giface=None, id = wx.ID_ANY, title=_("Data catalog"),
-                 name='catalog', **kwargs):
+
+    def __init__(self, parent, giface=None, id=wx.ID_ANY,
+                 title=_("Data catalog"), name='catalog', **kwargs):
         """Panel constructor  """
         self.showNotification = Signal('DataCatalog.showNotification')
         self.parent = parent
         self.baseTitle = title
-        wx.Panel.__init__(self, parent = parent, id = id, **kwargs)
+        wx.Panel.__init__(self, parent=parent, id=id, **kwargs)
         self.SetName("DataCatalog")
-        
+
         Debug.msg(1, "DataCatalog.__init__()")
 
         # toolbar
-        self.toolbar = DataCatalogToolbar(parent = self)
+        self.toolbar = DataCatalogToolbar(parent=self)
 
         # tree with layers
         self.tree = DataCatalogTree(self, giface=giface)
@@ -54,15 +56,15 @@
         """Do layout"""
         sizer = wx.BoxSizer(wx.VERTICAL)
 
-        sizer.Add(item = self.toolbar, proportion = 0,
-                  flag = wx.EXPAND)          
+        sizer.Add(item=self.toolbar, proportion=0,
+                  flag=wx.EXPAND)
 
-        sizer.Add(item = self.tree.GetControl(), proportion = 1,
-                  flag = wx.EXPAND)          
-        
+        sizer.Add(item=self.tree.GetControl(), proportion=1,
+                  flag=wx.EXPAND)
+
         self.SetAutoLayout(True)
         self.SetSizer(sizer)
-        
+
         self.Layout()
 
     def LoadItems(self):

Modified: grass/trunk/gui/wxpython/datacatalog/frame.py
===================================================================
--- grass/trunk/gui/wxpython/datacatalog/frame.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/datacatalog/frame.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -29,11 +29,17 @@
 
 class DataCatalogFrame(wx.Frame):
     """Frame for testing purposes only."""
+
     def __init__(self, parent, giface=None):
         wx.Frame.__init__(self, parent=parent,
                           title=_('GRASS GIS Data Catalog'))
         self.SetName("DataCatalog")
-        self.SetIcon(wx.Icon(os.path.join(ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    ICONDIR,
+                    'grass.ico'),
+                wx.BITMAP_TYPE_ICO))
 
         self._giface = giface
         self.panel = wx.Panel(self)

Modified: grass/trunk/gui/wxpython/datacatalog/g.gui.datacatalog.py
===================================================================
--- grass/trunk/gui/wxpython/datacatalog/g.gui.datacatalog.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/datacatalog/g.gui.datacatalog.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -27,16 +27,17 @@
 
 import grass.script as gscript
 
+
 def main():
     options, flags = gscript.parser()
 
     # import wx only after running parser
     # to avoid issues when only interface is needed
     import wx
-    
+
     from grass.script.setup import set_gui_path
     set_gui_path()
-    
+
     from core.giface import StandaloneGrassInterface
     from datacatalog.frame import DataCatalogFrame
 

Modified: grass/trunk/gui/wxpython/datacatalog/toolbars.py
===================================================================
--- grass/trunk/gui/wxpython/datacatalog/toolbars.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/datacatalog/toolbars.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -20,16 +20,25 @@
 from core.utils import _
 
 icons = {
-    'reloadTree': MetaIcon(img='redraw', label=_("Reload GRASS locations")),
-    'reloadMapset': MetaIcon(img='reload', label=_("Reload current GRASS mapset only")),
-    'unlocked': MetaIcon(img='unlocked', label=_("Click to restrict editing to current mapset only")),
-    'locked': MetaIcon(img='locked', label=_("Click to allow editing other mapsets")),
-    }
+    'reloadTree': MetaIcon(
+        img='redraw',
+        label=_("Reload GRASS locations")),
+    'reloadMapset': MetaIcon(
+        img='reload',
+        label=_("Reload current GRASS mapset only")),
+    'unlocked': MetaIcon(
+        img='unlocked',
+        label=_("Click to restrict editing to current mapset only")),
+    'locked': MetaIcon(
+        img='locked',
+        label=_("Click to allow editing other mapsets")),
+}
 
 
 class DataCatalogToolbar(BaseToolbar):
     """Main data catalog toolbar
     """
+
     def __init__(self, parent):
         """Main toolbar constructor
         """

Modified: grass/trunk/gui/wxpython/datacatalog/tree.py
===================================================================
--- grass/trunk/gui/wxpython/datacatalog/tree.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/datacatalog/tree.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -61,29 +61,46 @@
     elements = ['raster', 'raster_3d', 'vector']
     try:
         if not mapsets:
-            mapsets = gscript.read_command('g.mapsets', flags='l', separator='comma', quiet=True, env=env).strip()
+            mapsets = gscript.read_command(
+                'g.mapsets',
+                flags='l',
+                separator='comma',
+                quiet=True,
+                env=env).strip()
     except CalledModuleError:
-        queue.put((maps_dict, _("Failed to read mapsets from location <{l}>.").format(l=location)))
+        queue.put(
+            (maps_dict,
+             _("Failed to read mapsets from location <{l}>.").format(
+                 l=location)))
         gscript.try_remove(tmp_gisrc_file)
         return
     else:
         listOfMapsets = mapsets.split(',')
-        Debug.msg(4, "Location <{}>: {} mapsets found".format(location, len(listOfMapsets)))
+        Debug.msg(
+            4, "Location <{}>: {} mapsets found".format(
+                location, len(listOfMapsets)))
         for each in listOfMapsets:
             maps_dict[each] = {}
             for elem in elements:
                 maps_dict[each][elem] = []
     try:
-        maplist = gscript.read_command('g.list', flags='mt', type=elements,
-                                       mapset=','.join(listOfMapsets), quiet=True, env=env).strip()
+        maplist = gscript.read_command(
+            'g.list', flags='mt', type=elements,
+            mapset=','.join(listOfMapsets),
+            quiet=True, env=env).strip()
     except CalledModuleError:
-        queue.put((maps_dict, _("Failed to read maps from location <{l}>.").format(l=location)))
+        queue.put(
+            (maps_dict,
+             _("Failed to read maps from location <{l}>.").format(
+                 l=location)))
         gscript.try_remove(tmp_gisrc_file)
         return
     else:
         # fill dictionary
         listOfMaps = maplist.splitlines()
-        Debug.msg(4, "Location <{}>: {} maps found".format(location, len(listOfMaps)))
+        Debug.msg(
+            4, "Location <{}>: {} maps found".format(
+                location, len(listOfMaps)))
         for each in listOfMaps:
             ltype, wholename = each.split('/')
             name, mapset = wholename.split('@')
@@ -109,9 +126,15 @@
         element = 'grid3'
     # g.findfile returns non-zero when file was not found
     # se we ignore return code and just focus on stdout
-    process = gscript.start_command('g.findfile', flags='n',
-                                    element=element, file=name, mapset=mapset,
-                                    stdout=gscript.PIPE, stderr=gscript.PIPE, env=env)
+    process = gscript.start_command(
+        'g.findfile',
+        flags='n',
+        element=element,
+        file=name,
+        mapset=mapset,
+        stdout=gscript.PIPE,
+        stderr=gscript.PIPE,
+        env=env)
     output, errors = process.communicate()
     info = gscript.parse_key_val(output, sep='=')
     # file is the key questioned in grass.script.core find_file()
@@ -123,6 +146,7 @@
 
 
 class NameEntryDialog(TextEntryDialog):
+
     def __init__(self, element, mapset, env, **kwargs):
         TextEntryDialog.__init__(self, **kwargs)
         self._element = element
@@ -136,10 +160,16 @@
         if not new:
             return
         if map_exists(new, self._element, self._env, self._mapset):
-            dlg = wx.MessageDialog(self, message=_("Map of type {elem} <{name}> already exists in mapset <{mapset}>. "
-                                                   "Do you want to overwrite it?").format(elem=self._element,
-                                   name=new, mapset=self._mapset),
-                                   caption=_("Overwrite?"), style=wx.YES_NO)
+            dlg = wx.MessageDialog(
+                self,
+                message=_(
+                    "Map of type {elem} <{name}> already exists in mapset <{mapset}>. "
+                    "Do you want to overwrite it?").format(
+                    elem=self._element,
+                    name=new,
+                    mapset=self._mapset),
+                caption=_("Overwrite?"),
+                style=wx.YES_NO)
             if dlg.ShowModal() == wx.ID_YES:
                 dlg.Destroy()
                 self._env['GRASS_OVERWRITE'] = '1'
@@ -153,6 +183,7 @@
 
 class DataCatalogNode(DictNode):
     """Node representing item in datacatalog."""
+
     def __init__(self, label, data=None):
         super(DataCatalogNode, self).__init__(label=label, data=data)
 
@@ -172,11 +203,20 @@
 
 
 class LocationMapTree(TreeView):
-    def __init__(self, parent, model=None, style=wx.TR_HIDE_ROOT | wx.TR_EDIT_LABELS | wx.TR_LINES_AT_ROOT |
-                 wx.TR_HAS_BUTTONS | wx.TR_FULL_ROW_HIGHLIGHT | wx.TR_SINGLE):
+
+    def __init__(
+            self, parent, model=None, style=wx.TR_HIDE_ROOT | wx.TR_EDIT_LABELS
+            | wx.TR_LINES_AT_ROOT | wx.TR_HAS_BUTTONS | wx.TR_FULL_ROW_HIGHLIGHT |
+            wx.TR_SINGLE):
         """Location Map Tree constructor."""
         self._model = TreeModel(DataCatalogNode)
-        super(LocationMapTree, self).__init__(parent=parent, model=self._model, id=wx.ID_ANY, style=style)
+        super(
+            LocationMapTree,
+            self).__init__(
+            parent=parent,
+            model=self._model,
+            id=wx.ID_ANY,
+            style=style)
         self.showNotification = Signal('Tree.showNotification')
         self.parent = parent
         self.contextMenu.connect(self.OnRightClick)
@@ -200,23 +240,26 @@
         try:
             nprocs = cpu_count()
         except NotImplementedError:
-                nprocs = 4
+            nprocs = 4
 
         results = dict()
         errors = []
         location_nodes = []
         nlocations = len(locations)
-        grassdata_node = self._model.AppendNode(parent=self._model.root,
-                                                label=_('GRASS locations in {}').format(genv['GISDBASE']),
-                                                data=dict(type='grassdata'))
+        grassdata_node = self._model.AppendNode(
+            parent=self._model.root, label=_('GRASS locations in {}').format(
+                genv['GISDBASE']), data=dict(
+                type='grassdata'))
         for location in locations:
             results[location] = dict()
-            varloc = self._model.AppendNode(parent=grassdata_node, label=location,
-                                            data=dict(type='location', name=location))
+            varloc = self._model.AppendNode(
+                parent=grassdata_node, label=location, data=dict(
+                    type='location', name=location))
             location_nodes.append(varloc)
             loc_count += 1
 
-            Debug.msg(3, "Scanning location <{}> ({}/{})".format(location, loc_count, nlocations))
+            Debug.msg(
+                3, "Scanning location <{}> ({}/{})".format(location, loc_count, nlocations))
 
             q = Queue()
             p = Process(target=getLocationTree,
@@ -238,8 +281,10 @@
                         errors.append(error)
 
                     for key in sorted(maps.keys()):
-                        mapset_node = self._model.AppendNode(parent=location_nodes[i], label=key,
-                                                             data=dict(type='mapset', name=key))
+                        mapset_node = self._model.AppendNode(
+                            parent=location_nodes[i],
+                            label=key, data=dict(
+                                type='mapset', name=key))
                         self._populateMapsetItem(mapset_node, maps[key])
 
                 proc_count = 0
@@ -284,8 +329,13 @@
                 node = get_first_child(mapsetItem)
 
         q = Queue()
-        p = Process(target=getLocationTree,
-                    args=(genv['GISDBASE'], locationItem.data['name'], q, mapsetItem.data['name']))
+        p = Process(
+            target=getLocationTree,
+            args=(
+                genv['GISDBASE'],
+                locationItem.data['name'],
+                q,
+                mapsetItem.data['name']))
         p.start()
         maps, error = q.get()
         if error:
@@ -298,8 +348,9 @@
     def _populateMapsetItem(self, mapset_node, data):
         for elem in data:
             if data[elem]:
-                element_node = self._model.AppendNode(parent=mapset_node, label=elem,
-                                                      data=dict(type='element', name=elem))
+                element_node = self._model.AppendNode(
+                    parent=mapset_node, label=elem,
+                    data=dict(type='element', name=elem))
                 for layer in data[elem]:
                     self._model.AppendNode(parent=element_node, label=layer,
                                            data=dict(type=elem, name=layer))
@@ -392,7 +443,9 @@
         if not locationItem:
             return None, None
 
-        mapsetItem = self._model.SearchNodes(parent=locationItem[0], name=mapset, type='mapset')
+        mapsetItem = self._model.SearchNodes(
+            parent=locationItem[0],
+            name=mapset, type='mapset')
         if not mapsetItem:
             return locationItem[0], None
 
@@ -407,6 +460,7 @@
 
 
 class DataCatalogTree(LocationMapTree):
+
     def __init__(self, parent, giface=None):
         """Data Catalog Tree constructor."""
         super(DataCatalogTree, self).__init__(parent)
@@ -459,17 +513,27 @@
         self.copy_type = self.selected_type
         self.copy_mapset = self.selected_mapset
         self.copy_location = self.selected_location
-        label = _("Map <{layer}> marked for copying. "
-                  "You can paste it to the current mapset "
-                  "<{mapset}>.".format(layer=self.copy_layer.label, mapset=gisenv()['MAPSET']))
+        label = _(
+            "Map <{layer}> marked for copying. "
+            "You can paste it to the current mapset "
+            "<{mapset}>.".format(
+                layer=self.copy_layer.label,
+                mapset=gisenv()['MAPSET']))
         self.showNotification.emit(message=label)
 
     def OnRenameMap(self, event):
         """Rename layer with dialog"""
         old_name = self.selected_layer.label
-        gisrc, env = getEnvironment(gisenv()['GISDBASE'], self.selected_location.label, mapset=self.selected_mapset.label)
-        new_name = self._getNewMapName(_('New name'), _('Rename map'),
-                                       old_name, env=env, mapset=self.selected_mapset.label, element=self.selected_type.label)
+        gisrc, env = getEnvironment(
+            gisenv()['GISDBASE'],
+            self.selected_location.label, mapset=self.selected_mapset.label)
+        new_name = self._getNewMapName(
+            _('New name'),
+            _('Rename map'),
+            old_name,
+            env=env,
+            mapset=self.selected_mapset.label,
+            element=self.selected_type.label)
         if new_name:
             self.Rename(old_name, new_name)
 
@@ -493,7 +557,9 @@
     def Rename(self, old, new):
         """Rename layer"""
         string = old + ',' + new
-        gisrc, env = getEnvironment(gisenv()['GISDBASE'], self.selected_location.label, self.selected_mapset.label)
+        gisrc, env = getEnvironment(
+            gisenv()['GISDBASE'],
+            self.selected_location.label, self.selected_mapset.label)
         label = _("Renaming map <{name}>...").format(name=string)
         self.showNotification.emit(message=label)
         if self.selected_type.label == 'vector':
@@ -501,12 +567,14 @@
         elif self.selected_type.label == 'raster':
             renamed, cmd = self._runCommand('g.rename', raster=string, env=env)
         else:
-            renamed, cmd = self._runCommand('g.rename', raster3d=string, env=env)
+            renamed, cmd = self._runCommand(
+                'g.rename', raster3d=string, env=env)
         if renamed == 0:
             self.selected_layer.label = new
             self.selected_layer.data['name'] = new
             self.RefreshNode(self.selected_layer)
-            self.showNotification.emit(message=_("{cmd} -- completed").format(cmd=cmd))
+            self.showNotification.emit(
+                message=_("{cmd} -- completed").format(cmd=cmd))
             Debug.msg(1, "LAYER RENAMED TO: " + new)
         gscript.try_remove(gisrc)
 
@@ -517,29 +585,47 @@
             GMessage(_("No map selected for copying."), parent=self)
             return
         if self.selected_location == self.copy_location:
-            gisrc, env = getEnvironment(gisenv()['GISDBASE'], self.selected_location.label, mapset=self.selected_mapset.label)
-            new_name = self._getNewMapName(_('New name'), _('Copy map'),
-                                           self.copy_layer.label, env=env, mapset=self.selected_mapset.label, element=self.copy_type.label)
+            gisrc, env = getEnvironment(
+                gisenv()['GISDBASE'], self.selected_location.label, mapset=self.selected_mapset.label)
+            new_name = self._getNewMapName(
+                _('New name'),
+                _('Copy map'),
+                self.copy_layer.label,
+                env=env,
+                mapset=self.selected_mapset.label,
+                element=self.copy_type.label)
             if not new_name:
                 return
-            if map_exists(new_name, element=self.copy_type.label, env=env, mapset=self.selected_mapset.label):
-                GMessage(_("Failed to copy map: new map has the same name"), parent=self)
+            if map_exists(
+                    new_name, element=self.copy_type.label, env=env,
+                    mapset=self.selected_mapset.label):
+                GMessage(
+                    _("Failed to copy map: new map has the same name"),
+                    parent=self)
                 return
 
             if not self.selected_type:
-                found = self._model.SearchNodes(parent=self.selected_mapset, type='element', name=self.copy_type.label)
+                found = self._model.SearchNodes(
+                    parent=self.selected_mapset, type='element',
+                    name=self.copy_type.label)
                 self.selected_type = found[0] if found else None
 
             overwrite = False
             if self.selected_type:
-                found = self._model.SearchNodes(parent=self.selected_type, type=self.copy_type.label, name=new_name)
+                found = self._model.SearchNodes(
+                    parent=self.selected_type,
+                    type=self.copy_type.label,
+                    name=new_name)
                 if found and found[0]:
-                    dlg = wx.MessageDialog(parent=self,
-                                           message=_("Map <{map}> already exists "
-                                                     "in the current mapset. "
-                                                     "Do you want to overwrite it?").format(map=new_name),
-                                           caption=_("Overwrite?"),
-                                           style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+                    dlg = wx.MessageDialog(
+                        parent=self,
+                        message=_(
+                            "Map <{map}> already exists "
+                            "in the current mapset. "
+                            "Do you want to overwrite it?").format(
+                            map=new_name),
+                        caption=_("Overwrite?"),
+                        style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
                     ret = dlg.ShowModal()
                     dlg.Destroy()
                     if ret == wx.ID_YES:
@@ -551,34 +637,44 @@
             label = _("Copying <{name}>...").format(name=string)
             self.showNotification.emit(message=label)
             if self.copy_type.label == 'vector':
-                pasted, cmd = self._runCommand('g.copy', vector=string, overwrite=overwrite, env=env)
+                pasted, cmd = self._runCommand(
+                    'g.copy', vector=string, overwrite=overwrite, env=env)
                 node = 'vector'
             elif self.copy_type.label == 'raster':
-                pasted, cmd = self._runCommand('g.copy', raster=string, overwrite=overwrite, env=env)
+                pasted, cmd = self._runCommand(
+                    'g.copy', raster=string, overwrite=overwrite, env=env)
                 node = 'raster'
             else:
-                pasted, cmd = self._runCommand('g.copy', raster_3d=string, overwrite=overwrite, env=env)
+                pasted, cmd = self._runCommand(
+                    'g.copy', raster_3d=string, overwrite=overwrite, env=env)
                 node = 'raster_3d'
             if pasted == 0:
-                self.InsertLayer(name=new_name, mapset_node=self.selected_mapset, element_name=node)
+                self.InsertLayer(
+                    name=new_name,
+                    mapset_node=self.selected_mapset,
+                    element_name=node)
                 Debug.msg(1, "COPIED TO: " + new_name)
-                self.showNotification.emit(message=_("g.copy completed").format(cmd=cmd))
+                self.showNotification.emit(
+                    message=_("g.copy completed").format(cmd=cmd))
             gscript.try_remove(gisrc)
         else:
-            GError(_("Failed to copy map: action is allowed only within the same location."),
-                   parent=self)
+            GError(
+                _("Failed to copy map: action is allowed only within the same location."),
+                parent=self)
 
         # expand selected mapset
         self.ExpandNode(self.selected_mapset, recursive=True)
 
     def InsertLayer(self, name, mapset_node, element_name):
         """Insert layer into model and refresh tree"""
-        found_element = self._model.SearchNodes(parent=mapset_node, type='element', name=element_name)
+        found_element = self._model.SearchNodes(
+            parent=mapset_node, type='element', name=element_name)
         found_element = found_element[0] if found_element else None
         if not found_element:
             # add type node if not exists
-            found_element = self._model.AppendNode(parent=mapset_node, label=element_name,
-                                                   data=dict(type='element', name=element_name))
+            found_element = self._model.AppendNode(
+                parent=mapset_node, label=element_name,
+                data=dict(type='element', name=element_name))
         found = self._model.SearchNodes(parent=found_element, name=name)
         if len(found) == 0:
             self._model.AppendNode(parent=found_element, label=name,
@@ -589,34 +685,41 @@
     def OnDeleteMap(self, event):
         """Delete layer or mapset"""
         name = self.selected_layer.label
-        gisrc, env = getEnvironment(gisenv()['GISDBASE'], self.selected_location.label, self.selected_mapset.label)
-        if self._confirmDialog(question=_("Do you really want to delete map <{m}> of type <{etype}> from mapset "
-                               "<{mapset}> in location <{loc}>?").format(m=name, mapset=self.selected_mapset.label,
-                                                                         etype=self.selected_type.label,
-                                                                         loc=self.selected_location.label),
-                               title=_('Delete map')) == wx.ID_YES:
+        gisrc, env = getEnvironment(
+            gisenv()['GISDBASE'],
+            self.selected_location.label, self.selected_mapset.label)
+        if self._confirmDialog(
+                question=_(
+                    "Do you really want to delete map <{m}> of type <{etype}> from mapset "
+                    "<{mapset}> in location <{loc}>?").format(
+                    m=name, mapset=self.selected_mapset.label,
+                    etype=self.selected_type.label,
+                    loc=self.selected_location.label),
+                title=_('Delete map')) == wx.ID_YES:
             label = _("Deleting {name}...").format(name=name)
             self.showNotification.emit(message=label)
             if self.selected_type.label == 'vector':
-                removed, cmd = self._runCommand('g.remove', flags='f', type='vector',
-                                                name=name, env=env)
+                removed, cmd = self._runCommand(
+                    'g.remove', flags='f', type='vector', name=name, env=env)
             elif self.selected_type.label == 'raster':
-                removed, cmd = self._runCommand('g.remove', flags='f', type='raster',
-                                                name=name, env=env)
+                removed, cmd = self._runCommand(
+                    'g.remove', flags='f', type='raster', name=name, env=env)
             else:
-                removed, cmd = self._runCommand('g.remove', flags='f', type='raster_3d',
-                                                name=name, env=env)
+                removed, cmd = self._runCommand(
+                    'g.remove', flags='f', type='raster_3d', name=name, env=env)
             if removed == 0:
                 self._model.RemoveNode(self.selected_layer)
                 self.RefreshNode(self.selected_type, recursive=True)
                 Debug.msg(1, "LAYER " + name + " DELETED")
-                self.showNotification.emit(message=_("g.remove completed").format(cmd=cmd))
+                self.showNotification.emit(
+                    message=_("g.remove completed").format(cmd=cmd))
         gscript.try_remove(gisrc)
 
     def OnDisplayLayer(self, event):
         """Display layer in current graphics view"""
         layerName = []
-        if self.selected_location.label == gisenv()['LOCATION_NAME'] and self.selected_mapset:
+        if self.selected_location.label == gisenv(
+        )['LOCATION_NAME'] and self.selected_mapset:
             string = self.selected_layer.label + '@' + self.selected_mapset.label
             layerName.append(string)
             label = _("Displaying {name}...").format(name=string)
@@ -629,18 +732,21 @@
                 self._giface.lmgr.AddMaps(layerName, 'raster', True)
             else:
                 self._giface.lmgr.AddMaps(layerName, 'raster_3d', True)
-                label = "d.rast --q map=" + string + _(" -- completed. Go to Layers tab for further operations.")  # generate this message (command) automatically?
+                # generate this message (command) automatically?
+                label = "d.rast --q map=" + string + _(
+                    " -- completed. Go to Layers tab for further operations.")
             self.showNotification.emit(message=label)
             Debug.msg(1, "LAYER " + self.selected_layer.label + " DISPLAYED")
         else:
-            GError(_("Failed to display layer: not in current mapset or invalid layer"),
-                   parent=self)
+            GError(
+                _("Failed to display layer: not in current mapset or invalid layer"),
+                parent=self)
 
     def OnBeginDrag(self, node, event):
         """Just copy necessary data"""
         self.DefineItems(node)
-        if self.selected_layer and \
-           not (self._restricted and gisenv()['LOCATION_NAME'] != self.selected_location.label):
+        if self.selected_layer and not (self._restricted and gisenv()[
+                                        'LOCATION_NAME'] != self.selected_location.label):
             event.Allow()
             self.OnCopyMap(event)
             Debug.msg(1, "DRAG")
@@ -656,8 +762,11 @@
             return
         if node:
             self.DefineItems(node)
-            if self._restricted and gisenv()['MAPSET'] != self.selected_mapset.label:
-                GMessage(_("Maps can be copied only to current mapset"), parent=self)
+            if self._restricted and gisenv(
+            )['MAPSET'] != self.selected_mapset.label:
+                GMessage(
+                    _("Maps can be copied only to current mapset"),
+                    parent=self)
                 event.Veto()
                 return
             if self.selected_location == self.copy_location and self.selected_mapset:
@@ -708,7 +817,9 @@
         item = wx.MenuItem(menu, wx.NewId(), _("&Paste"))
         menu.AppendItem(item)
         self.Bind(wx.EVT_MENU, self.OnPasteMap, item)
-        if not(currentLocation and self.copy_layer and self.selected_location == self.copy_location):
+        if not(
+                currentLocation and self.copy_layer and self.selected_location ==
+                self.copy_location):
             item.Enable(False)
 
         item = wx.MenuItem(menu, wx.NewId(), _("&Delete"))

Modified: grass/trunk/gui/wxpython/dbmgr/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/dbmgr/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/dbmgr/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -5,4 +5,4 @@
     'manager',
     'base',
     'dialogs',
-    ]
+]

Modified: grass/trunk/gui/wxpython/dbmgr/base.py
===================================================================
--- grass/trunk/gui/wxpython/dbmgr/base.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/dbmgr/base.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -40,24 +40,26 @@
 from core import globalvar
 import wx
 import wx.lib.mixins.listctrl as listmix
-import wx.lib.flatnotebook    as FN
+import wx.lib.flatnotebook as FN
 import wx.lib.scrolledpanel as scrolled
 
 import grass.script as grass
 
 from dbmgr.sqlbuilder import SQLBuilderSelect, SQLBuilderUpdate
-from core.gcmd        import RunCommand, GException, GError, GMessage, GWarning
-from core.utils       import ListOfCatsToRange, _
+from core.gcmd import RunCommand, GException, GError, GMessage, GWarning
+from core.utils import ListOfCatsToRange, _
 from gui_core.dialogs import CreateNewVector
-from dbmgr.vinfo      import VectorDBInfo, GetUnicodeValue, CreateDbInfoDesc
-from core.debug       import Debug
-from dbmgr.dialogs    import ModifyTableRecord, AddColumnDialog
-from core.settings    import UserSettings
+from dbmgr.vinfo import VectorDBInfo, GetUnicodeValue, CreateDbInfoDesc
+from core.debug import Debug
+from dbmgr.dialogs import ModifyTableRecord, AddColumnDialog
+from core.settings import UserSettings
 
+
 class Log:
     """The log output SQL is redirected to the status bar of the
     containing frame.
     """
+
     def __init__(self, parent):
         self.parent = parent
 
@@ -66,66 +68,70 @@
         if self.parent:
             self.parent.SetStatusText(text_string.strip())
 
+
 class VirtualAttributeList(wx.ListCtrl,
                            listmix.ListCtrlAutoWidthMixin,
                            listmix.ColumnSorterMixin):
     """Support virtual list class for Attribute Table Manager (browse page)
     """
+
     def __init__(self, parent, log, dbMgrData, layer, pages):
         # initialize variables
-        self.parent  = parent
-        self.log     = log
+        self.parent = parent
+        self.log = log
         self.dbMgrData = dbMgrData
         self.mapDBInfo = self.dbMgrData['mapDBInfo']
-        self.layer   = layer
+        self.layer = layer
         self.pages = pages
 
         self.fieldCalc = None
-        self.fieldStats = None      
-        self.columns = {} # <- LoadData()
-        
+        self.fieldStats = None
+        self.columns = {}  # <- LoadData()
+
         self.sqlFilter = {}
 
-        wx.ListCtrl.__init__(self, parent = parent, id = wx.ID_ANY,
-                             style = wx.LC_REPORT | wx.LC_HRULES |
-                             wx.LC_VRULES | wx.LC_VIRTUAL | wx.LC_SORT_ASCENDING)
-        
+        wx.ListCtrl.__init__(self, parent=parent, id=wx.ID_ANY,
+                             style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_VRULES |
+                             wx.LC_VIRTUAL | wx.LC_SORT_ASCENDING)
+
         try:
             keyColumn = self.LoadData(layer)
         except GException as e:
-            GError(parent = self,
-                   message = e.value)
+            GError(parent=self,
+                   message=e.value)
             return
-        
+
         # add some attributes (colourful background for each item rows)
         self.attr1 = wx.ListItemAttr()
-        self.attr1.SetBackgroundColour(wx.Colour(238,238,238))
+        self.attr1.SetBackgroundColour(wx.Colour(238, 238, 238))
         self.attr2 = wx.ListItemAttr()
         self.attr2.SetBackgroundColour("white")
         self.il = wx.ImageList(16, 16)
-        self.sm_up = self.il.Add(wx.ArtProvider_GetBitmap(wx.ART_GO_UP,   wx.ART_TOOLBAR,
-                                                          (16,16)))
-        self.sm_dn = self.il.Add(wx.ArtProvider_GetBitmap(wx.ART_GO_DOWN, wx.ART_TOOLBAR,
-                                                          (16,16)))
+        self.sm_up = self.il.Add(
+            wx.ArtProvider_GetBitmap(
+                wx.ART_GO_UP, wx.ART_TOOLBAR, (16, 16)))
+        self.sm_dn = self.il.Add(
+            wx.ArtProvider_GetBitmap(
+                wx.ART_GO_DOWN, wx.ART_TOOLBAR, (16, 16)))
         self.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
-        
+
         # setup mixins
         listmix.ListCtrlAutoWidthMixin.__init__(self)
         listmix.ColumnSorterMixin.__init__(self, len(self.columns))
 
         # sort item by category (id)
         if keyColumn > -1:
-            self.SortListItems(col = keyColumn, ascending = True) 
+            self.SortListItems(col=keyColumn, ascending=True)
         elif keyColumn:
-            self.SortListItems(col = 0, ascending = True) 
-        
+            self.SortListItems(col=0, ascending=True)
+
         # events
-        self.Bind(wx.EVT_LIST_ITEM_SELECTED,   self.OnItemSelected)
+        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
         self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnItemDeselected)
-        self.Bind(wx.EVT_LIST_COL_CLICK,       self.OnColumnSort)     
-        self.Bind(wx.EVT_LIST_COL_RIGHT_CLICK, self.OnColumnMenu)     
-        
-    def Update(self, mapDBInfo = None):
+        self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColumnSort)
+        self.Bind(wx.EVT_LIST_COL_RIGHT_CLICK, self.OnColumnMenu)
+
+    def Update(self, mapDBInfo=None):
         """Update list according new mapDBInfo description"""
         if mapDBInfo:
             self.mapDBInfo = mapDBInfo
@@ -133,46 +139,46 @@
         else:
             self.LoadData(self.layer, **self.sqlFilter)
 
-    def LoadData(self, layer, columns = None, where = None, sql = None):
+    def LoadData(self, layer, columns=None, where=None, sql=None):
         """Load data into list
 
         :param layer: layer number
         :param columns: list of columns for output (-> v.db.select)
         :param where: where statement (-> v.db.select)
         :param sql: full sql statement (-> db.select)
-        
-        :return: id of key column 
+
+        :return: id of key column
         :return: -1 if key column is not displayed
         """
         self.log.write(_("Loading data..."))
-        
-        tableName    = self.mapDBInfo.layers[layer]['table']
-        keyColumn    = self.mapDBInfo.layers[layer]['key']
+
+        tableName = self.mapDBInfo.layers[layer]['table']
+        keyColumn = self.mapDBInfo.layers[layer]['key']
         try:
             self.columns = self.mapDBInfo.tables[tableName]
         except KeyError:
             raise GException(_("Attribute table <%s> not found. "
-                                    "For creating the table switch to "
-                                    "'Manage layers' tab.") % tableName)
-        
+                               "For creating the table switch to "
+                               "'Manage layers' tab.") % tableName)
+
         if not columns:
             columns = self.mapDBInfo.GetColumns(tableName)
         else:
             all = self.mapDBInfo.GetColumns(tableName)
             for col in columns:
                 if col not in all:
-                    GError(parent = self,
-                           message = _("Column <%(column)s> not found in "
-                                       "in the table <%(table)s>.") % \
-                               { 'column' : col, 'table' : tableName })
+                    GError(parent=self,
+                           message=_("Column <%(column)s> not found in "
+                                     "in the table <%(table)s>.") %
+                           {'column': col, 'table': tableName})
                     return
-        
+
         try:
             # for maps connected via v.external
             keyId = columns.index(keyColumn)
         except:
             keyId = -1
-        
+
         # read data
         # FIXME: Max. number of rows, while the GUI is still usable
 
@@ -184,46 +190,46 @@
         # highly unlikely to exist naturally.
         fs = '{_sep_}'
 
-        outFile = tempfile.NamedTemporaryFile(mode = 'w+b')
+        outFile = tempfile.NamedTemporaryFile(mode='w+b')
 
-        cmdParams = dict(quiet = True,
-                         parent = self,
-                         flags = 'c',
-                         separator = fs)
+        cmdParams = dict(quiet=True,
+                         parent=self,
+                         flags='c',
+                         separator=fs)
 
         if sql:
-            cmdParams.update(dict(sql = sql,
-                                  output = outFile.name,
-                                  overwrite = True))
+            cmdParams.update(dict(sql=sql,
+                                  output=outFile.name,
+                                  overwrite=True))
             ret = RunCommand('db.select',
                              **cmdParams)
-            self.sqlFilter = {"sql" : sql}
+            self.sqlFilter = {"sql": sql}
         else:
-            cmdParams.update(dict(map = self.mapDBInfo.map,
-                                  layer = layer,
-                                  where = where,
-                                  stdout = outFile))
-            
-            self.sqlFilter = {"where" : where}
+            cmdParams.update(dict(map=self.mapDBInfo.map,
+                                  layer=layer,
+                                  where=where,
+                                  stdout=outFile))
 
+            self.sqlFilter = {"where": where}
+
             if columns:
-                cmdParams.update(dict(columns = ','.join(columns)))
+                cmdParams.update(dict(columns=','.join(columns)))
 
             ret = RunCommand('v.db.select',
                              **cmdParams)
-        
+
         # These two should probably be passed to init more cleanly
         # setting the numbers of items = number of elements in the dictionary
-        self.itemDataMap  = {}
+        self.itemDataMap = {}
         self.itemIndexMap = []
-        self.itemCatsMap  = {}
-        
+        self.itemCatsMap = {}
+
         self.DeleteAllItems()
-        
+
         # self.ClearAll()
         for i in range(self.GetColumnCount()):
             self.DeleteColumn(0)
-        
+
         i = 0
         info = wx.ListItem()
         info.m_mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT
@@ -233,18 +239,19 @@
             info.m_text = column
             self.InsertColumnInfo(i, info)
             i += 1
-            
+
             if i >= 256:
                 self.log.write(_("Can display only 256 columns."))
-        
+
         i = 0
         outFile.seek(0)
-        
+
         while True:
             # os.linesep doesn't work here (MSYS)
             # not sure what the replace is for?
             # but we need strip to get rid of the ending newline
-            # which on windows leaves \r in a last empty attribute table cell and causes error
+            # which on windows leaves \r in a last empty attribute table cell
+            # and causes error
             record = outFile.readline().strip().replace('\n', '')
 
             if not record:
@@ -252,64 +259,67 @@
 
             record = record.split(fs)
             if len(columns) != len(record):
-                GError(parent = self,
-                       message = _("Inconsistent number of columns "
-                                   "in the table <%(table)s>.") % \
-                               {'table' : tableName })
-                self.columns = {} # because of IsEmpty method
+                GError(parent=self,
+                       message=_("Inconsistent number of columns "
+                                 "in the table <%(table)s>.") %
+                       {'table': tableName})
+                self.columns = {}  # because of IsEmpty method
                 return
 
             self.AddDataRow(i, record, columns, keyId)
-            
+
             i += 1
             if i >= 100000:
                 self.log.write(_("Viewing limit: 100000 records."))
                 break
-        
+
         self.SetItemCount(i)
-        
+
         if where:
             item = -1
             while True:
                 item = self.GetNextItem(item)
                 if item == -1:
                     break
-                self.SetItemState(item, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)
-        
+                self.SetItemState(
+                    item,
+                    wx.LIST_STATE_SELECTED,
+                    wx.LIST_STATE_SELECTED)
+
         i = 0
         for col in columns:
-            width = self.columns[col]['length'] * 6 # FIXME
+            width = self.columns[col]['length'] * 6  # FIXME
             if width < 60:
                 width = 60
             if width > 300:
                 width = 300
-            self.SetColumnWidth(col = i, width = width)
+            self.SetColumnWidth(col=i, width=width)
             i += 1
-        
+
         self.SendSizeEvent()
-        
-        self.log.write(_("Number of loaded records: %d") % \
-                           self.GetItemCount())
-        
+
+        self.log.write(_("Number of loaded records: %d") %
+                       self.GetItemCount())
+
         return keyId
-    
+
     def AddDataRow(self, i, record, columns, keyId):
         """Add row to the data list"""
         self.itemDataMap[i] = []
         keyColumn = self.mapDBInfo.layers[self.layer]['key']
         j = 0
         cat = None
-        
+
         if keyColumn == 'OGC_FID':
-            self.itemDataMap[i].append(i+1)
+            self.itemDataMap[i].append(i + 1)
             j += 1
             cat = i + 1
-        
+
         for value in record:
             if self.columns[columns[j]]['ctype'] != types.StringType:
                 try:
-                    ### casting disabled (2009/03)
-                    ### self.itemDataMap[i].append(self.columns[columns[j]]['ctype'](value))
+                    # casting disabled (2009/03)
+                    # self.itemDataMap[i].append(self.columns[columns[j]]['ctype'](value))
                     self.itemDataMap[i].append(value)
                 except ValueError:
                     self.itemDataMap[i].append(_('Unknown value'))
@@ -320,32 +330,36 @@
                 except UnicodeDecodeError:
                     self.itemDataMap[i].append(_("Unable to decode value. "
                                                  "Set encoding in GUI preferences ('Attributes')."))
-                
+
             if not cat and keyId > -1 and keyId == j:
                 try:
-                    cat = self.columns[columns[j]]['ctype'] (value)
+                    cat = self.columns[columns[j]]['ctype'](value)
                 except ValueError as e:
                     cat = -1
-                    GError(parent = self,
-                           message = _("Error loading attribute data. "
-                                       "Record number: %(rec)d. Unable to convert value '%(val)s' in "
-                                       "key column (%(key)s) to integer.\n\n"
-                                       "Details: %(detail)s") % \
-                               { 'rec' : i + 1, 'val' : value,
-                                 'key' : keyColumn, 'detail' : e})
+                    GError(
+                        parent=self,
+                        message=_(
+                            "Error loading attribute data. "
+                            "Record number: %(rec)d. Unable to convert value '%(val)s' in "
+                            "key column (%(key)s) to integer.\n\n"
+                            "Details: %(detail)s") % {
+                            'rec': i + 1,
+                            'val': value,
+                            'key': keyColumn,
+                            'detail': e})
             j += 1
-        
+
         self.itemIndexMap.append(i)
-        if keyId > -1: # load cats only when LoadData() is called first time
+        if keyId > -1:  # load cats only when LoadData() is called first time
             self.itemCatsMap[i] = cat
-        
+
     def OnItemSelected(self, event):
         """Item selected. Add item to selected cats..."""
         #         cat = int(self.GetItemText(event.m_itemIndex))
         #         if cat not in self.selectedCats:
         #             self.selectedCats.append(cat)
         #             self.selectedCats.sort()
-        
+
         event.Skip()
 
     def OnItemDeselected(self, event):
@@ -372,7 +386,7 @@
         cats = []
         for item in range(self.GetItemCount()):
             cats.append(self.GetItemText(item))
-        
+
         return cats
 
     def GetColumnText(self, index, col):
@@ -392,7 +406,7 @@
 
     def OnGetItemAttr(self, item):
         """Get item attributes"""
-        if ( item % 2) == 0:
+        if (item % 2) == 0:
             return self.attr2
         else:
             return self.attr1
@@ -400,70 +414,100 @@
     def OnColumnMenu(self, event):
         """Column heading right mouse button -> pop-up menu"""
         self._col = event.GetColumn()
-        
+
         popupMenu = wx.Menu()
 
-        if not hasattr (self, "popupID"):
-            self.popupId = { 'sortAsc' : wx.NewId(),
-                             'sortDesc' : wx.NewId(),
-                             'calculate' : wx.NewId(),
-                             'area' : wx.NewId(),
-                             'length' : wx.NewId(),
-                             'compact' : wx.NewId(),
-                             'fractal' : wx.NewId(),
-                             'perimeter' : wx.NewId(),
-                             'ncats' : wx.NewId(),
-                             'slope' : wx.NewId(),
-                             'lsin' : wx.NewId(),
-                             'lazimuth' : wx.NewId(),
-                             'calculator' : wx.NewId(),
-                             'stats' : wx.NewId() }
-        
-        popupMenu.Append(self.popupId['sortAsc'], text = _("Sort ascending"))
-        popupMenu.Append(self.popupId['sortDesc'], text = _("Sort descending"))
+        if not hasattr(self, "popupID"):
+            self.popupId = {'sortAsc': wx.NewId(),
+                            'sortDesc': wx.NewId(),
+                            'calculate': wx.NewId(),
+                            'area': wx.NewId(),
+                            'length': wx.NewId(),
+                            'compact': wx.NewId(),
+                            'fractal': wx.NewId(),
+                            'perimeter': wx.NewId(),
+                            'ncats': wx.NewId(),
+                            'slope': wx.NewId(),
+                            'lsin': wx.NewId(),
+                            'lazimuth': wx.NewId(),
+                            'calculator': wx.NewId(),
+                            'stats': wx.NewId()}
+
+        popupMenu.Append(self.popupId['sortAsc'], text=_("Sort ascending"))
+        popupMenu.Append(self.popupId['sortDesc'], text=_("Sort descending"))
         popupMenu.AppendSeparator()
         subMenu = wx.Menu()
-        popupMenu.AppendMenu(self.popupId['calculate'], _("Calculate (only numeric columns)"),
-                             subMenu)
-        popupMenu.Append(self.popupId['calculator'], text = _("Field calculator"))
+        popupMenu.AppendMenu(self.popupId['calculate'], _(
+            "Calculate (only numeric columns)"), subMenu)
+        popupMenu.Append(
+            self.popupId['calculator'],
+            text=_("Field calculator"))
         popupMenu.AppendSeparator()
-        popupMenu.Append(self.popupId['stats'], text = _("Statistics"))
-        
+        popupMenu.Append(self.popupId['stats'], text=_("Statistics"))
+
         if not self.pages['manageTable']:
             popupMenu.AppendSeparator()
             self.popupId['addCol'] = wx.NewId()
-            popupMenu.Append(self.popupId['addCol'], text = _("Add column"))
+            popupMenu.Append(self.popupId['addCol'], text=_("Add column"))
             if not self.dbMgrData['editable']:
                 popupMenu.Enable(self.popupId['addCol'], False)
 
         if not self.dbMgrData['editable']:
             popupMenu.Enable(self.popupId['calculator'], False)
-          
-        if not self.dbMgrData['editable'] or \
-                self.columns[self.GetColumn(self._col).GetText()]['ctype'] not in (types.IntType, types.FloatType):
+
+        if not self.dbMgrData['editable'] or self.columns[
+                self.GetColumn(self._col).GetText()]['ctype'] not in (
+                types.IntType, types.FloatType):
             popupMenu.Enable(self.popupId['calculate'], False)
-        
-        subMenu.Append(self.popupId['area'],  text = _("Area size"))
-        subMenu.Append(self.popupId['length'],  text = _("Line length"))
-        subMenu.Append(self.popupId['compact'],  text = _("Compactness of an area"))
-        subMenu.Append(self.popupId['fractal'],  text = _("Fractal dimension of boundary defining a polygon"))
-        subMenu.Append(self.popupId['perimeter'],  text = _("Perimeter length of an area"))
-        subMenu.Append(self.popupId['ncats'],  text = _("Number of features for each category"))
-        subMenu.Append(self.popupId['slope'], text = _("Slope steepness of 3D line"))
-        subMenu.Append(self.popupId['lsin'], text = _("Line sinuousity"))
-        subMenu.Append(self.popupId['lazimuth'], text = _("Line azimuth"))
-        
-        self.Bind (wx.EVT_MENU, self.OnColumnSortAsc,  id = self.popupId['sortAsc'])
-        self.Bind (wx.EVT_MENU, self.OnColumnSortDesc, id = self.popupId['sortDesc'])
-        self.Bind(wx.EVT_MENU, self.OnFieldCalculator, id = self.popupId['calculator'])
-        self.Bind(wx.EVT_MENU, self.OnFieldStatistics, id = self.popupId['stats'])
+
+        subMenu.Append(self.popupId['area'], text=_("Area size"))
+        subMenu.Append(self.popupId['length'], text=_("Line length"))
+        subMenu.Append(
+            self.popupId['compact'],
+            text=_("Compactness of an area"))
+        subMenu.Append(self.popupId['fractal'], text=_(
+            "Fractal dimension of boundary defining a polygon"))
+        subMenu.Append(
+            self.popupId['perimeter'],
+            text=_("Perimeter length of an area"))
+        subMenu.Append(self.popupId['ncats'], text=_(
+            "Number of features for each category"))
+        subMenu.Append(
+            self.popupId['slope'],
+            text=_("Slope steepness of 3D line"))
+        subMenu.Append(self.popupId['lsin'], text=_("Line sinuousity"))
+        subMenu.Append(self.popupId['lazimuth'], text=_("Line azimuth"))
+
+        self.Bind(
+            wx.EVT_MENU,
+            self.OnColumnSortAsc,
+            id=self.popupId['sortAsc'])
+        self.Bind(
+            wx.EVT_MENU,
+            self.OnColumnSortDesc,
+            id=self.popupId['sortDesc'])
+        self.Bind(
+            wx.EVT_MENU,
+            self.OnFieldCalculator,
+            id=self.popupId['calculator'])
+        self.Bind(
+            wx.EVT_MENU,
+            self.OnFieldStatistics,
+            id=self.popupId['stats'])
         if not self.pages['manageTable']:
-            self.Bind(wx.EVT_MENU, self.OnAddColumn, id = self.popupId['addCol'])
+            self.Bind(wx.EVT_MENU, self.OnAddColumn, id=self.popupId['addCol'])
 
-        for id in (self.popupId['area'], self.popupId['length'], self.popupId['compact'],
-                   self.popupId['fractal'], self.popupId['perimeter'], self.popupId['ncats'],
-                   self.popupId['slope'], self.popupId['lsin'], self.popupId['lazimuth']):
-            self.Bind(wx.EVT_MENU, self.OnColumnCompute, id = id)
+        for id in (
+                self.popupId['area'],
+                self.popupId['length'],
+                self.popupId['compact'],
+                self.popupId['fractal'],
+                self.popupId['perimeter'],
+                self.popupId['ncats'],
+                self.popupId['slope'],
+                self.popupId['lsin'],
+                self.popupId['lazimuth']):
+            self.Bind(wx.EVT_MENU, self.OnColumnCompute, id=id)
 
         self.PopupMenu(popupMenu)
         popupMenu.Destroy()
@@ -471,25 +515,25 @@
     def OnColumnSort(self, event):
         """Column heading left mouse button -> sorting"""
         self._col = event.GetColumn()
-        
+
         self.ColumnSort()
-        
+
         event.Skip()
 
     def OnColumnSortAsc(self, event):
         """Sort values of selected column (ascending)"""
-        self.SortListItems(col = self._col, ascending = True)
+        self.SortListItems(col=self._col, ascending=True)
         event.Skip()
 
     def OnColumnSortDesc(self, event):
         """Sort values of selected column (descending)"""
-        self.SortListItems(col = self._col, ascending = False)
+        self.SortListItems(col=self._col, ascending=False)
         event.Skip()
-        
+
     def OnColumnCompute(self, event):
         """Compute values of selected column"""
         id = event.GetId()
-        
+
         option = None
         if id == self.popupId['area']:
             option = 'area'
@@ -509,19 +553,19 @@
             option = 'sinuous'
         elif id == self.popupId['lazimuth']:
             option = 'azimuth'
-        
+
         if not option:
             return
-        
+
         RunCommand('v.to.db',
-                   parent = self.parent,
-                   map = self.mapDBInfo.map,
-                   layer = self.layer, 
-                   option = option,
-                   columns = self.GetColumn(self._col).GetText())
-        
+                   parent=self.parent,
+                   map=self.mapDBInfo.map,
+                   layer=self.layer,
+                   option=option,
+                   columns=self.GetColumn(self._col).GetText())
+
         self.LoadData(self.layer)
-        
+
     def ColumnSort(self):
         """Sort values of selected column (self._col)"""
         # remove duplicated arrow symbol from column header
@@ -532,14 +576,17 @@
         for column in range(self.GetColumnCount()):
             info.m_text = self.GetColumn(column).GetText()
             self.SetColumn(column, info)
-        
+
     def OnFieldCalculator(self, event):
         """Calls SQLBuilderUpdate instance"""
         if not self.fieldCalc:
-            self.fieldCalc = SQLBuilderUpdate(parent = self, id = wx.ID_ANY,
-                                              vectmap = self.dbMgrData['vectName'],
-                                              layer = self.layer,
-                                              column = self.GetColumn(self._col).GetText())
+            self.fieldCalc = SQLBuilderUpdate(
+                parent=self,
+                id=wx.ID_ANY,
+                vectmap=self.dbMgrData['vectName'],
+                layer=self.layer,
+                column=self.GetColumn(
+                    self._col).GetText())
             self.fieldCalc.Show()
         else:
             self.fieldCalc.Raise()
@@ -547,31 +594,34 @@
     def OnFieldStatistics(self, event):
         """Calls FieldStatistics instance"""
         if not self.fieldStats:
-            self.fieldStats = FieldStatistics(parent = self, id = wx.ID_ANY)
+            self.fieldStats = FieldStatistics(parent=self, id=wx.ID_ANY)
             self.fieldStats.Show()
         else:
             self.fieldStats.Raise()
 
         selLayer = self.dbMgrData['mapDBInfo'].layers[self.layer]
-        self.fieldStats.Update(driver = selLayer['driver'],
-                               database = selLayer['database'],
-                               table = selLayer['table'],
-                               column = self.GetColumn(self._col).GetText())
+        self.fieldStats.Update(driver=selLayer['driver'],
+                               database=selLayer['database'],
+                               table=selLayer['table'],
+                               column=self.GetColumn(self._col).GetText())
 
     def OnAddColumn(self, event):
         """Add column into table"""
         table = self.dbMgrData['mapDBInfo'].layers[self.layer]['table']
-        dlg = AddColumnDialog(parent = self, title = _('Add column to table <%s>') % table)
+        dlg = AddColumnDialog(
+            parent=self,
+            title=_('Add column to table <%s>') %
+            table)
         if not dlg:
             return
         if dlg.ShowModal() == wx.ID_OK:
             data = dlg.GetData()
-            self.pages['browse'].AddColumn(name = data['name'],
-                                           ctype = data['ctype'],
-                                           length = data['length'])
+            self.pages['browse'].AddColumn(name=data['name'],
+                                           ctype=data['ctype'],
+                                           length=data['length'])
         dlg.Destroy()
 
-    def SortItems(self, sorter = cmp):
+    def SortItems(self, sorter=cmp):
         """Sort items"""
         items = list(self.itemDataMap.keys())
         items.sort(self.Sorter)
@@ -579,27 +629,31 @@
 
         # redraw the list
         self.Refresh()
-        
+
     def Sorter(self, key1, key2):
         colName = self.GetColumn(self._col).GetText()
         ascending = self._colSortFlag[self._col]
         try:
-            item1 = self.columns[colName]["ctype"](self.itemDataMap[key1][self._col])
-            item2 = self.columns[colName]["ctype"](self.itemDataMap[key2][self._col])
+            item1 = self.columns[colName]["ctype"](
+                self.itemDataMap[key1][self._col])
+            item2 = self.columns[colName]["ctype"](
+                self.itemDataMap[key2][self._col])
         except ValueError:
             item1 = self.itemDataMap[key1][self._col]
             item2 = self.itemDataMap[key2][self._col]
 
-        if type(item1) == types.StringType or type(item2) == types.StringTypes:
+        if isinstance(
+                item1, types.StringType) or isinstance(
+                item2, types.StringTypes):
             cmpVal = locale.strcoll(str(item1), str(item2))
         else:
             cmpVal = cmp(item1, item2)
 
+        # If the items are equal then pick something else to make the sort
+        # value unique
+        if cmpVal == 0:
+            cmpVal = cmp(*self.GetSecondarySortValues(self._col, key1, key2))
 
-        # If the items are equal then pick something else to make the sort value unique
-        if cmpVal == 0:
-            cmpVal = apply(cmp, self.GetSecondarySortValues(self._col, key1, key2))
-        
         if ascending:
             return cmpVal
         else:
@@ -613,22 +667,24 @@
         """Check if list if empty"""
         if self.columns:
             return False
-        
+
         return True
 
+
 class DbMgrBase:
-    def __init__(self, id = wx.ID_ANY, mapdisplay = None,
-                 vectorName = None, item = None, giface = None,
-                 statusbar = None, 
+
+    def __init__(self, id=wx.ID_ANY, mapdisplay=None,
+                 vectorName=None, item=None, giface=None,
+                 statusbar=None,
                  **kwargs):
-        """Base class, which enables usage of separate pages of Attribute Table Manager 
+        """Base class, which enables usage of separate pages of Attribute Table Manager
 
         :param id: window id
         :param mapdisplay: MapFrame instance
         :param vectorName: name of vector map
         :param item: item from Layer Tree
         :param log: log window
-        :param statusbar: widget with statusbar 
+        :param statusbar: widget with statusbar
         :param kwagrs: other wx.Frame's arguments
         """
 
@@ -639,7 +695,7 @@
 
         self.mapdisplay = mapdisplay
 
-        if  self.mapdisplay:
+        if self.mapdisplay:
             self.map = mapdisplay.Map
         else:
             self.map = None
@@ -647,35 +703,39 @@
         if not self.mapdisplay:
             pass
         elif self.mapdisplay.tree and \
-            self.dbMgrData['treeItem'] and not self.dbMgrData['vectName']:
+                self.dbMgrData['treeItem'] and not self.dbMgrData['vectName']:
             maptree = self.mapdisplay.tree
-            name = maptree.GetLayerInfo(self.dbMgrData['treeItem'], key = 'maplayer').GetName()
+            name = maptree.GetLayerInfo(
+                self.dbMgrData['treeItem'],
+                key='maplayer').GetName()
             self.dbMgrData['vectName'] = name
-        
+
         # vector attributes can be changed only if vector map is in
         # the current mapset
         mapInfo = None
         if self.dbMgrData['vectName']:
-            mapInfo = grass.find_file(name = self.dbMgrData['vectName'], element = 'vector')
+            mapInfo = grass.find_file(
+                name=self.dbMgrData['vectName'],
+                element='vector')
         if not mapInfo or mapInfo['mapset'] != grass.gisenv()['MAPSET']:
             self.dbMgrData['editable'] = False
         else:
             self.dbMgrData['editable'] = True
-        
+
         self.giface = giface
 
         # status bar log class
-        self.log = Log(statusbar) # -> statusbar
+        self.log = Log(statusbar)  # -> statusbar
 
         # -> layers / tables description
         self.dbMgrData['mapDBInfo'] = VectorDBInfo(self.dbMgrData['vectName'])
 
-        # store information, which pages were initialized 
+        # store information, which pages were initialized
         self.pages = {
-                        'browse' : None,
-                        'manageTable' : None,
-                        'manageLayer' : None
-                     }
+            'browse': None,
+            'manageTable': None,
+            'manageLayer': None
+        }
 
     def ChangeVectorMap(self, vectorName):
         """Change of vector map
@@ -683,7 +743,7 @@
         Does not import layers of new vector map into pages.
         For the import use methods addLayer in DbMgrBrowsePage and DbMgrTablesPage
         """
-        if self.pages['browse']: 
+        if self.pages['browse']:
             self.pages['browse'].DeleteAllPages()
         if self.pages['manageTable']:
             self.pages['manageTable'].DeleteAllPages()
@@ -695,7 +755,9 @@
 
         # vector attributes can be changed only if vector map is in
         # the current mapset
-        mapInfo = grass.find_file(name = self.dbMgrData['vectName'], element = 'vector')
+        mapInfo = grass.find_file(
+            name=self.dbMgrData['vectName'],
+            element='vector')
         if not mapInfo or mapInfo['mapset'] != grass.gisenv()['MAPSET']:
             self.dbMgrData['editable'] = False
         else:
@@ -703,9 +765,9 @@
 
         # 'manage layers page
         if self.pages['manageLayer']:
-            self.pages['manageLayer'].UpdatePage()       
+            self.pages['manageLayer'].UpdatePage()
 
-    def CreateDbMgrPage(self, parent, pageName, onlyLayer = -1):
+    def CreateDbMgrPage(self, parent, pageName, onlyLayer=-1):
         """Creates chosen page
 
         :param pageName: can be 'browse' or 'manageTable' or
@@ -714,20 +776,21 @@
         :return: created instance of page, if the page has been already
                  created returns the previously created instance
         :return: None  if wrong identifier was passed
-        """       
+        """
         if pageName == 'browse':
             if not self.pages['browse']:
-                self.pages[pageName] = DbMgrBrowsePage(parent = parent, parentDbMgrBase = self,
-                                                     onlyLayer = onlyLayer)
+                self.pages[pageName] = DbMgrBrowsePage(
+                    parent=parent, parentDbMgrBase=self, onlyLayer=onlyLayer)
             return self.pages[pageName]
         if pageName == 'manageTable':
             if not self.pages['manageTable']:
-                self.pages[pageName] = DbMgrTablesPage(parent = parent, parentDbMgrBase = self,
-                                                          onlyLayer = onlyLayer)
+                self.pages[pageName] = DbMgrTablesPage(
+                    parent=parent, parentDbMgrBase=self, onlyLayer=onlyLayer)
             return self.pages[pageName]
         if pageName == 'manageLayer':
             if not self.pages['manageLayer']:
-                self.pages[pageName] = DbMgrLayersPage(parent = parent, parentDbMgrBase = self)
+                self.pages[pageName] = DbMgrLayersPage(
+                    parent=parent, parentDbMgrBase=self)
             return self.pages[pageName]
         return None
 
@@ -740,13 +803,13 @@
             # if self.browsePage.GetPageText(page).replace('Layer ', '').strip() == str(layer):
             # self.browsePage.DeletePage(page)
             # break
-            if self.pages['browse']: 
+            if self.pages['browse']:
                 self.pages['browse'].DeletePage(layer)
-            if self.pages['manageTable']:                
+            if self.pages['manageTable']:
                 self.pages['manageTable'].DeletePage(layer)
 
         # fetch fresh db info
-        self.dbMgrData['mapDBInfo'] = VectorDBInfo(self.dbMgrData['vectName'])    
+        self.dbMgrData['mapDBInfo'] = VectorDBInfo(self.dbMgrData['vectName'])
 
         #
         # add new page
@@ -762,7 +825,7 @@
         # manage layers page
         if self.pages['manageLayer']:
             self.pages['manageLayer'].UpdatePage()
-    
+
     def GetVectorName(self):
         """Get vector name"""
         return self.dbMgrData['vectName']
@@ -771,7 +834,9 @@
         """Get layers of vector map which have table"""
         return self.dbMgrData['mapDBInfo'].layers.keys()
 
+
 class DbMgrNotebookBase(FN.FlatNotebook):
+
     def __init__(self, parent, parentDbMgrBase):
         """Base class for notebook with attribute tables in tabs
 
@@ -788,18 +853,18 @@
         self.map = self.parentDbMgrBase.map
         self.mapdisplay = self.parentDbMgrBase.mapdisplay
 
-        #TODO no need to have it in class scope make it local? 
-        self.listOfCommands      = [] 
+        # TODO no need to have it in class scope make it local?
+        self.listOfCommands = []
         self.listOfSQLStatements = []
 
-        #initializet pages
+        # initializet pages
         self.pages = self.parentDbMgrBase.pages
 
         # shared data among pages
         self.dbMgrData = self.parentDbMgrBase.dbMgrData
 
         # set up virtual lists (each layer)
-        ### {layer: list, widgets...}
+        # {layer: list, widgets...}
         self.layerPage = {}
 
         # currently selected layer
@@ -809,11 +874,11 @@
         self.layers = []
 
         if globalvar.hasAgw:
-            dbmStyle = { 'agwStyle' : globalvar.FNPageStyle }
+            dbmStyle = {'agwStyle': globalvar.FNPageStyle}
         else:
-            dbmStyle = { 'style' : globalvar.FNPageStyle }
+            dbmStyle = {'style': globalvar.FNPageStyle}
 
-        FN.FlatNotebook.__init__(self,parent = self.parent, id = wx.ID_ANY,
+        FN.FlatNotebook.__init__(self, parent=self.parent, id=wx.ID_ANY,
                                  **dbmStyle)
 
         self.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnLayerPageChanged)
@@ -821,25 +886,27 @@
     def OnLayerPageChanged(self, event):
         """Layer tab changed"""
 
-        # because of SQL Query notebook  
+        # because of SQL Query notebook
         if event.GetEventObject() != self:
             return
 
-        pageNum = self.GetSelection()    
+        pageNum = self.GetSelection()
         self.selLayer = self.layers[pageNum]
         try:
             idCol = self.layerPage[self.selLayer]['whereColumn']
         except KeyError:
             idCol = None
-        
+
         try:
             # update statusbar
-            self.log.write(_("Number of loaded records: %d") % \
-                               self.FindWindowById(self.layerPage[self.selLayer]['data']).\
-                               GetItemCount())
+            self.log.write(
+                _("Number of loaded records: %d") %
+                self.FindWindowById(
+                    self.layerPage[
+                        self.selLayer]['data']). GetItemCount())
         except:
             pass
-        
+
         if idCol:
             winCol = self.FindWindowById(idCol)
             table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]["table"]
@@ -853,15 +920,16 @@
         """
         # perform GRASS commands (e.g. v.db.addcolumn)
         wx.BeginBusyCursor()
-        
+
         if len(listOfCommands) > 0:
             for cmd in listOfCommands:
-                RunCommand(prog = cmd[0],
-                           quiet = True,
-                           parent = self,
+                RunCommand(prog=cmd[0],
+                           quiet=True,
+                           parent=self,
                            **cmd[1])
-            
-            self.dbMgrData['mapDBInfo'] = VectorDBInfo(self.dbMgrData['vectName'])
+
+            self.dbMgrData['mapDBInfo'] = VectorDBInfo(
+                self.dbMgrData['vectName'])
             if self.pages['manageTable']:
                 self.pages['manageTable'].UpdatePage(self.selLayer)
 
@@ -869,13 +937,15 @@
                 self.pages['browse'].UpdatePage(self.selLayer)
             # reset list of commands
             listOfCommands = []
-        
-        # perform SQL non-select statements (e.g. 'delete from table where cat=1')
+
+        # perform SQL non-select statements (e.g. 'delete from table where
+        # cat=1')
         if len(listOfSQLStatements) > 0:
             fd, sqlFilePath = tempfile.mkstemp(text=True)
             sqlFile = open(sqlFilePath, 'w')
             for sql in listOfSQLStatements:
-                enc = UserSettings.Get(group = 'atm', key = 'encoding', subkey = 'value')
+                enc = UserSettings.Get(
+                    group='atm', key='encoding', subkey='value')
                 if not enc and 'GRASS_DB_ENCODING' in os.environ:
                     enc = os.environ['GRASS_DB_ENCODING']
                 if enc:
@@ -885,25 +955,27 @@
                 sqlFile.write(os.linesep)
             sqlFile.close()
 
-            driver   = self.dbMgrData['mapDBInfo'].layers[self.selLayer]["driver"]
-            database = self.dbMgrData['mapDBInfo'].layers[self.selLayer]["database"]
-            
+            driver = self.dbMgrData['mapDBInfo'].layers[
+                self.selLayer]["driver"]
+            database = self.dbMgrData['mapDBInfo'].layers[
+                self.selLayer]["database"]
+
             Debug.msg(3, 'AttributeManger.ApplyCommands(): %s' %
                       ';'.join(["%s" % s for s in listOfSQLStatements]))
-            
+
             RunCommand('db.execute',
-                       parent = self,
-                       input = sqlFilePath,
-                       driver = driver,
-                       database = database)
-            
+                       parent=self,
+                       input=sqlFilePath,
+                       driver=driver,
+                       database=database)
+
             os.close(fd)
             os.remove(sqlFilePath)
             # reset list of statements
             self.listOfSQLStatements = []
-            
-        wx.EndBusyCursor()        
 
+        wx.EndBusyCursor()
+
     def DeletePage(self, layer):
         """Removes layer page"""
         if layer not in self.layers:
@@ -931,56 +1003,60 @@
     def AddColumn(self, name, ctype, length):
         """Add new column to the table"""
         table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table']
-        
+
         if not name:
-            GError(parent = self,
-                   message = _("Unable to add column to the table. "
-                               "No column name defined."))
+            GError(parent=self,
+                   message=_("Unable to add column to the table. "
+                             "No column name defined."))
             return False
-         
+
         # cast type if needed
         if ctype == 'double':
             ctype = 'double precision'
         if ctype != 'varchar':
-            length = '' # FIXME
-        
+            length = ''  # FIXME
+
         # check for duplicate items
         if name in self.dbMgrData['mapDBInfo'].GetColumns(table):
-            GError(parent = self,
-                   message = _("Column <%(column)s> already exists in table <%(table)s>.") % \
-                       {'column' : name, 'table' : self.dbMgrData['mapDBInfo'].layers[self.selLayer]["table"]}
-                   )
+            GError(
+                parent=self,
+                message=_("Column <%(column)s> already exists in table <%(table)s>.") % {
+                    'column': name,
+                    'table': self.dbMgrData['mapDBInfo'].layers[
+                        self.selLayer]["table"]})
             return False
 
         # add v.db.addcolumn command to the list
         if ctype == 'varchar':
             ctype += ' (%d)' % length
         self.listOfCommands.append(('v.db.addcolumn',
-                                    { 'map'     : self.dbMgrData['vectName'],
-                                      'layer'   : self.selLayer,
-                                      'columns' : '%s %s' % (name, ctype) }
+                                    {'map': self.dbMgrData['vectName'],
+                                     'layer': self.selLayer,
+                                     'columns': '%s %s' % (name, ctype)}
                                     ))
         # apply changes
         self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)
-                
+
         return True
 
     def GetAddedLayers(self):
         """Get list of added layers"""
         return self.layers[:]
 
+
 class DbMgrBrowsePage(DbMgrNotebookBase):
-    def __init__(self, parent, parentDbMgrBase, onlyLayer = -1):
+
+    def __init__(self, parent, parentDbMgrBase, onlyLayer=-1):
         """Browse page class
 
         :param parent: GUI parent
         :param parentDbMgrBase: instance of DbMgrBase class
         :param onlyLayer: create only tab of given layer, if -1 creates
-                          tabs of all layers 
+                          tabs of all layers
         """
 
-        DbMgrNotebookBase.__init__(self, parent = parent, 
-                                       parentDbMgrBase = parentDbMgrBase)
+        DbMgrNotebookBase.__init__(self, parent=parent,
+                                   parentDbMgrBase=parentDbMgrBase)
 
         #   for Sql Query notebook adaptation on current width
         self.sqlBestSize = None
@@ -991,10 +1067,13 @@
             self.AddLayer(layer)
 
         if self.layers:
-            self.SetSelection(0) 
+            self.SetSelection(0)
             self.selLayer = self.layers[0]
-            self.log.write(_("Number of loaded records: %d") % \
-                           self.FindWindowById(self.layerPage[self.selLayer]['data']).GetItemCount())
+            self.log.write(
+                _("Number of loaded records: %d") %
+                self.FindWindowById(
+                    self.layerPage[
+                        self.selLayer]['data']).GetItemCount())
 
         # query map layer (if parent (GMFrame) is given)
         self.qlayer = None
@@ -1002,30 +1081,31 @@
         # sqlbuilder
         self.builder = None
 
-    def AddLayer(self, layer, pos = -1):
+    def AddLayer(self, layer, pos=-1):
         """Adds tab which represents table and enables browse it
 
         :param layer: vector map layer conntected to table
         :param pos: position of tab, if -1 it is added to end
 
-        :return: True if layer was added 
+        :return: True if layer was added
         :return: False if layer was not added - layer has been already
-                 added or has empty table or does not exist 
+                 added or has empty table or does not exist
         """
         if layer in self.layers or \
-            layer not in self.parentDbMgrBase.GetVectorLayers():
-            return False    
+                layer not in self.parentDbMgrBase.GetVectorLayers():
+            return False
 
-        panel = wx.Panel(parent = self, id = wx.ID_ANY)
-            
-        #IMPORTANT NOTE: wx.StaticBox MUST be defined BEFORE any of the 
+        panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
+        # IMPORTANT NOTE: wx.StaticBox MUST be defined BEFORE any of the
         #   controls that are placed IN the wx.StaticBox, or it will freeze
         #   on the Mac
-            
-        listBox = wx.StaticBox(parent = panel, id = wx.ID_ANY,
-                               label = " %s " % _("Attribute data - right-click to edit/manage records"))
+
+        listBox = wx.StaticBox(
+            parent=panel, id=wx.ID_ANY, label=" %s " %
+            _("Attribute data - right-click to edit/manage records"))
         listSizer = wx.StaticBoxSizer(listBox, wx.VERTICAL)
-            
+
         win = VirtualAttributeList(panel, self.log,
                                    self.dbMgrData, layer, self.pages)
         if win.IsEmpty():
@@ -1033,165 +1113,195 @@
             return False
 
         self.layers.append(layer)
-            
+
         win.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnDataItemActivated)
 
         self.layerPage[layer] = {'browsePage': panel.GetId()}
-            
+
         label = _("Table")
         if not self.dbMgrData['editable']:
             label += _(" (readonly)")
 
         if pos == -1:
-            pos = self.GetPageCount() 
-        self.InsertPage(pos, page = panel,
-                        text = " %d / %s %s" % \
-                       (layer, label, self.dbMgrData['mapDBInfo'].layers[layer]['table']))
-            
+            pos = self.GetPageCount()
+        self.InsertPage(
+            pos, page=panel, text=" %d / %s %s" %
+            (layer, label, self.dbMgrData['mapDBInfo'].layers[layer]['table']))
+
         pageSizer = wx.BoxSizer(wx.VERTICAL)
 
-        sqlQueryPanel = wx.Panel(parent = panel, id = wx.ID_ANY)
+        sqlQueryPanel = wx.Panel(parent=panel, id=wx.ID_ANY)
 
-        # attribute data            
-        sqlBox = wx.StaticBox(parent = sqlQueryPanel, id = wx.ID_ANY,
-                              label = " %s " % _("SQL Query"))
+        # attribute data
+        sqlBox = wx.StaticBox(parent=sqlQueryPanel, id=wx.ID_ANY,
+                              label=" %s " % _("SQL Query"))
 
         sqlSizer = wx.StaticBoxSizer(sqlBox, wx.VERTICAL)
 
-        win.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnDataRightUp) #wxMSW
-        win.Bind(wx.EVT_RIGHT_UP,            self.OnDataRightUp) #wxGTK
-        if UserSettings.Get(group = 'atm', key = 'leftDbClick', subkey = 'selection') == 0:
+        win.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnDataRightUp)  # wxMSW
+        win.Bind(wx.EVT_RIGHT_UP, self.OnDataRightUp)  # wxGTK
+        if UserSettings.Get(group='atm', key='leftDbClick',
+                            subkey='selection') == 0:
             win.Bind(wx.EVT_LEFT_DCLICK, self.OnDataItemEdit)
             win.Bind(wx.EVT_COMMAND_LEFT_DCLICK, self.OnDataItemEdit)
         else:
             win.Bind(wx.EVT_LEFT_DCLICK, self.OnDataDrawSelected)
             win.Bind(wx.EVT_COMMAND_LEFT_DCLICK, self.OnDataDrawSelected)
-            
-        listSizer.Add(item = win, proportion = 1,
-                      flag = wx.EXPAND | wx.ALL,
-                      border = 3)
 
+        listSizer.Add(item=win, proportion=1,
+                      flag=wx.EXPAND | wx.ALL,
+                      border=3)
+
         # sql statement box
         FNPageStyle = FN.FNB_NO_NAV_BUTTONS | \
-                       FN.FNB_NO_X_BUTTON
+            FN.FNB_NO_X_BUTTON
         if globalvar.hasAgw:
-            dbmStyle = { 'agwStyle' : FNPageStyle }
+            dbmStyle = {'agwStyle': FNPageStyle}
         else:
-            dbmStyle = { 'style' : FNPageStyle }
-        sqlNtb = FN.FlatNotebook(parent = sqlQueryPanel, id = wx.ID_ANY,
+            dbmStyle = {'style': FNPageStyle}
+        sqlNtb = FN.FlatNotebook(parent=sqlQueryPanel, id=wx.ID_ANY,
                                  **dbmStyle)
         # Simple tab
-        simpleSqlPanel = wx.Panel(parent = sqlNtb, id = wx.ID_ANY)
-        sqlNtb.AddPage(page = simpleSqlPanel,
-                       text = _('Simple'))
+        simpleSqlPanel = wx.Panel(parent=sqlNtb, id=wx.ID_ANY)
+        sqlNtb.AddPage(page=simpleSqlPanel,
+                       text=_('Simple'))
 
-        btnApply = wx.Button(parent = simpleSqlPanel, id = wx.ID_APPLY, name = 'btnApply')
-        btnApply.SetToolTipString(_("Apply SELECT statement and reload data records"))
+        btnApply = wx.Button(
+            parent=simpleSqlPanel,
+            id=wx.ID_APPLY,
+            name='btnApply')
+        btnApply.SetToolTipString(
+            _("Apply SELECT statement and reload data records"))
         btnApply.Bind(wx.EVT_BUTTON, self.OnApplySqlStatement)
 
-        whereSimpleSqlPanel = wx.Panel(parent = simpleSqlPanel, id = wx.ID_ANY, name = 'wherePanel')   
-        sqlWhereColumn = wx.ComboBox(parent = whereSimpleSqlPanel, id = wx.ID_ANY,
-                                     size = (150,-1),
-                                     style = wx.CB_SIMPLE | wx.CB_READONLY,
-                                     choices = self.dbMgrData['mapDBInfo'].GetColumns(self.dbMgrData['mapDBInfo'].layers[layer]['table']))
+        whereSimpleSqlPanel = wx.Panel(
+            parent=simpleSqlPanel,
+            id=wx.ID_ANY,
+            name='wherePanel')
+        sqlWhereColumn = wx.ComboBox(
+            parent=whereSimpleSqlPanel, id=wx.ID_ANY, size=(150, -1),
+            style=wx.CB_SIMPLE | wx.CB_READONLY,
+            choices=self.dbMgrData['mapDBInfo'].GetColumns(
+                self.dbMgrData['mapDBInfo'].layers[layer]['table']))
         sqlWhereColumn.SetSelection(0)
-        sqlWhereCond = wx.Choice(parent = whereSimpleSqlPanel, id = wx.ID_ANY,
-                                 size = (55,-1),
-                                 choices = ['=', '!=', '<', '<=', '>', '>='])
+        sqlWhereCond = wx.Choice(parent=whereSimpleSqlPanel, id=wx.ID_ANY,
+                                 size=(55, -1),
+                                 choices=['=', '!=', '<', '<=', '>', '>='])
         sqlWhereCond.SetSelection(0)
-        sqlWhereValue = wx.TextCtrl(parent = whereSimpleSqlPanel, id = wx.ID_ANY, value = "",
-                                    style = wx.TE_PROCESS_ENTER)
-        sqlWhereValue.SetToolTipString(_("Example: %s") % "MULTILANE = 'no' AND OBJECTID < 10")
+        sqlWhereValue = wx.TextCtrl(
+            parent=whereSimpleSqlPanel,
+            id=wx.ID_ANY,
+            value="",
+            style=wx.TE_PROCESS_ENTER)
+        sqlWhereValue.SetToolTipString(
+            _("Example: %s") %
+            "MULTILANE = 'no' AND OBJECTID < 10")
 
-        sqlLabel = wx.StaticText(parent = simpleSqlPanel, id = wx.ID_ANY,
-                                label = "SELECT * FROM %s WHERE " % \
-                                      self.dbMgrData['mapDBInfo'].layers[layer]['table'])
+        sqlLabel = wx.StaticText(
+            parent=simpleSqlPanel,
+            id=wx.ID_ANY,
+            label="SELECT * FROM %s WHERE " %
+            self.dbMgrData['mapDBInfo'].layers[layer]['table'])
         # Advanced tab
-        advancedSqlPanel = wx.Panel(parent = sqlNtb, id = wx.ID_ANY)   
-        sqlNtb.AddPage(page = advancedSqlPanel,
-                       text = _('Builder'))
+        advancedSqlPanel = wx.Panel(parent=sqlNtb, id=wx.ID_ANY)
+        sqlNtb.AddPage(page=advancedSqlPanel,
+                       text=_('Builder'))
 
-        btnSqlBuilder = wx.Button(parent = advancedSqlPanel, id = wx.ID_ANY, label = _("SQL Builder"))
+        btnSqlBuilder = wx.Button(
+            parent=advancedSqlPanel,
+            id=wx.ID_ANY,
+            label=_("SQL Builder"))
         btnSqlBuilder.Bind(wx.EVT_BUTTON, self.OnBuilder)
 
-        sqlStatement = wx.TextCtrl(parent = advancedSqlPanel, id = wx.ID_ANY,
-                                   value = "SELECT * FROM %s" % \
-                                       self.dbMgrData['mapDBInfo'].layers[layer]['table'],
-                                   style = wx.TE_PROCESS_ENTER)
-        sqlStatement.SetToolTipString(_("Example: %s") % "SELECT * FROM roadsmajor WHERE MULTILANE = 'no' AND OBJECTID < 10")
+        sqlStatement = wx.TextCtrl(
+            parent=advancedSqlPanel,
+            id=wx.ID_ANY,
+            value="SELECT * FROM %s" %
+            self.dbMgrData['mapDBInfo'].layers[layer]['table'],
+            style=wx.TE_PROCESS_ENTER)
+        sqlStatement.SetToolTipString(
+            _("Example: %s") %
+            "SELECT * FROM roadsmajor WHERE MULTILANE = 'no' AND OBJECTID < 10")
         sqlWhereValue.Bind(wx.EVT_TEXT_ENTER, self.OnApplySqlStatement)
         sqlStatement.Bind(wx.EVT_TEXT_ENTER, self.OnApplySqlStatement)
 
         # Simple tab layout
-        simpleSqlSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
+        simpleSqlSizer = wx.GridBagSizer(hgap=5, vgap=5)
 
-        sqlSimpleWhereSizer= wx.BoxSizer(wx.HORIZONTAL)
+        sqlSimpleWhereSizer = wx.BoxSizer(wx.HORIZONTAL)
 
-        sqlSimpleWhereSizer.Add(item = sqlWhereColumn,
-                                flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL| wx.LEFT,
-                                border = 3)
-        sqlSimpleWhereSizer.Add(item = sqlWhereCond,
-                                flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
-                                border = 3)
-        sqlSimpleWhereSizer.Add(item = sqlWhereValue, proportion = 1,
-                                flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
-                                border = 3)
+        sqlSimpleWhereSizer.Add(
+            item=sqlWhereColumn,
+            flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
+            border=3)
+        sqlSimpleWhereSizer.Add(
+            item=sqlWhereCond,
+            flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
+            border=3)
+        sqlSimpleWhereSizer.Add(
+            item=sqlWhereValue,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
+            border=3)
         whereSimpleSqlPanel.SetSizer(sqlSimpleWhereSizer)
-        simpleSqlSizer.Add(item = sqlLabel, border = 5, pos = (0, 0),
-                           flag = wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.LEFT)
-        simpleSqlSizer.Add(item = whereSimpleSqlPanel, border = 5, pos = (0, 1),
-                           flag = wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.EXPAND)     
-        simpleSqlSizer.Add(item = btnApply, border = 5, pos = (0, 2),
-                           flag = wx.ALIGN_CENTER_VERTICAL | wx.TOP)
+        simpleSqlSizer.Add(item=sqlLabel, border=5, pos=(0, 0),
+                           flag=wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.LEFT)
+        simpleSqlSizer.Add(item=whereSimpleSqlPanel, border=5, pos=(0, 1),
+                           flag=wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.EXPAND)
+        simpleSqlSizer.Add(item=btnApply, border=5, pos=(0, 2),
+                           flag=wx.ALIGN_CENTER_VERTICAL | wx.TOP)
         simpleSqlSizer.AddGrowableCol(1)
 
         simpleSqlPanel.SetSizer(simpleSqlSizer)
 
         # Advanced tab layout
-        advancedSqlSizer = wx.FlexGridSizer (cols = 2, hgap = 5, vgap = 5)
+        advancedSqlSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
         advancedSqlSizer.AddGrowableCol(0)
 
-        advancedSqlSizer.Add(item = sqlStatement,
-                             flag = wx.EXPAND | wx.ALL, border = 5)
-        advancedSqlSizer.Add(item = btnSqlBuilder,
-                             flag = wx.ALIGN_RIGHT | wx.TOP | wx.RIGHT | wx.BOTTOM, border = 5)
+        advancedSqlSizer.Add(item=sqlStatement,
+                             flag=wx.EXPAND | wx.ALL, border=5)
+        advancedSqlSizer.Add(
+            item=btnSqlBuilder,
+            flag=wx.ALIGN_RIGHT | wx.TOP | wx.RIGHT | wx.BOTTOM,
+            border=5)
 
-        sqlSizer.Add(item = sqlNtb,
-                     flag = wx.ALL | wx.EXPAND,
-                     border = 3)
+        sqlSizer.Add(item=sqlNtb,
+                     flag=wx.ALL | wx.EXPAND,
+                     border=3)
 
         advancedSqlPanel.SetSizer(advancedSqlSizer)
 
-        pageSizer.Add(item = listSizer,
-                      proportion = 1,
-                      flag = wx.ALL | wx.EXPAND,
-                      border = 5)
+        pageSizer.Add(item=listSizer,
+                      proportion=1,
+                      flag=wx.ALL | wx.EXPAND,
+                      border=5)
 
         sqlQueryPanel.SetSizer(sqlSizer)
-        
-        pageSizer.Add(item = sqlQueryPanel,
-                      proportion = 0,
-                      flag = wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.EXPAND,
-                      border = 5)
 
+        pageSizer.Add(item=sqlQueryPanel,
+                      proportion=0,
+                      flag=wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.EXPAND,
+                      border=5)
+
         panel.SetSizer(pageSizer)
-         
+
         sqlNtb.Bind(wx.EVT_SIZE, self.OnSqlQuerySizeWrap(layer))
 
-        self.layerPage[layer]['data']      = win.GetId()
-        self.layerPage[layer]['sqlNtb']    = sqlNtb.GetId()
+        self.layerPage[layer]['data'] = win.GetId()
+        self.layerPage[layer]['sqlNtb'] = sqlNtb.GetId()
         self.layerPage[layer]['whereColumn'] = sqlWhereColumn.GetId()
         self.layerPage[layer]['whereOperator'] = sqlWhereCond.GetId()
-        self.layerPage[layer]['where']     = sqlWhereValue.GetId()
-        self.layerPage[layer]['builder']   = btnSqlBuilder.GetId()
+        self.layerPage[layer]['where'] = sqlWhereValue.GetId()
+        self.layerPage[layer]['builder'] = btnSqlBuilder.GetId()
         self.layerPage[layer]['statement'] = sqlStatement.GetId()
-        self.layerPage[layer]['sqlIsReduced'] = False  # for SQL Query adaptation on width     
+        # for SQL Query adaptation on width
+        self.layerPage[layer]['sqlIsReduced'] = False
 
         return True
 
     def OnSqlQuerySizeWrap(self, layer):
         """Helper function"""
-        return lambda event : self.OnSqlQuerySize(event, layer)  
+        return lambda event: self.OnSqlQuerySize(event, layer)
 
     def OnSqlQuerySize(self, event, layer):
         """Adapts SQL Query Simple tab on current width"""
@@ -1200,8 +1310,8 @@
         if not self.sqlBestSize:
             self.sqlBestSize = sqlNtb.GetBestSize()
 
-        size = sqlNtb.GetSize()    
-        sqlReduce = self.sqlBestSize[0] > size[0] 
+        size = sqlNtb.GetSize()
+        sqlReduce = self.sqlBestSize[0] > size[0]
         if (sqlReduce and self.layerPage[layer]['sqlIsReduced']) or \
            (not sqlReduce and not self.layerPage[layer]['sqlIsReduced']):
             event.Skip()
@@ -1247,24 +1357,40 @@
             self.popupDataID10 = wx.NewId()
             self.popupDataID11 = wx.NewId()
 
-            self.Bind(wx.EVT_MENU, self.OnDataItemEdit,       id = self.popupDataID1)
-            self.Bind(wx.EVT_MENU, self.OnDataItemAdd,        id = self.popupDataID2)
-            self.Bind(wx.EVT_MENU, self.OnDataItemDelete,     id = self.popupDataID3)
-            self.Bind(wx.EVT_MENU, self.OnDataItemDeleteAll,  id = self.popupDataID4)
-            self.Bind(wx.EVT_MENU, self.OnDataSelectAll,      id = self.popupDataID5)
-            self.Bind(wx.EVT_MENU, self.OnDataSelectNone,     id = self.popupDataID6)
-            self.Bind(wx.EVT_MENU, self.OnDataDrawSelected,   id = self.popupDataID7)
-            self.Bind(wx.EVT_MENU, self.OnDataDrawSelectedZoom, id = self.popupDataID8)
-            self.Bind(wx.EVT_MENU, self.OnExtractSelected,    id = self.popupDataID9)
-            self.Bind(wx.EVT_MENU, self.OnDeleteSelected,     id = self.popupDataID11)
-            self.Bind(wx.EVT_MENU, self.OnDataReload,         id = self.popupDataID10)
+            self.Bind(wx.EVT_MENU, self.OnDataItemEdit, id=self.popupDataID1)
+            self.Bind(wx.EVT_MENU, self.OnDataItemAdd, id=self.popupDataID2)
+            self.Bind(wx.EVT_MENU, self.OnDataItemDelete, id=self.popupDataID3)
+            self.Bind(
+                wx.EVT_MENU,
+                self.OnDataItemDeleteAll,
+                id=self.popupDataID4)
+            self.Bind(wx.EVT_MENU, self.OnDataSelectAll, id=self.popupDataID5)
+            self.Bind(wx.EVT_MENU, self.OnDataSelectNone, id=self.popupDataID6)
+            self.Bind(
+                wx.EVT_MENU,
+                self.OnDataDrawSelected,
+                id=self.popupDataID7)
+            self.Bind(
+                wx.EVT_MENU,
+                self.OnDataDrawSelectedZoom,
+                id=self.popupDataID8)
+            self.Bind(
+                wx.EVT_MENU,
+                self.OnExtractSelected,
+                id=self.popupDataID9)
+            self.Bind(
+                wx.EVT_MENU,
+                self.OnDeleteSelected,
+                id=self.popupDataID11)
+            self.Bind(wx.EVT_MENU, self.OnDataReload, id=self.popupDataID10)
 
         tlist = self.FindWindowById(self.layerPage[self.selLayer]['data'])
         # generate popup-menu
         menu = wx.Menu()
         menu.Append(self.popupDataID1, _("Edit selected record"))
         selected = tlist.GetFirstSelected()
-        if not self.dbMgrData['editable'] or selected == -1 or tlist.GetNextSelected(selected) != -1:
+        if not self.dbMgrData[
+                'editable'] or selected == -1 or tlist.GetNextSelected(selected) != -1:
             menu.Enable(self.popupDataID1, False)
         menu.Append(self.popupDataID2, _("Insert new record"))
         menu.Append(self.popupDataID3, _("Delete selected record(s)"))
@@ -1278,7 +1404,9 @@
         menu.Append(self.popupDataID6, _("Deselect all"))
         menu.AppendSeparator()
         menu.Append(self.popupDataID7, _("Highlight selected features"))
-        menu.Append(self.popupDataID8, _("Highlight selected features and zoom"))
+        menu.Append(
+            self.popupDataID8,
+            _("Highlight selected features and zoom"))
         if not self.map or len(tlist.GetSelectedItems()) == 0:
             menu.Enable(self.popupDataID7, False)
             menu.Enable(self.popupDataID8, False)
@@ -1297,66 +1425,68 @@
         menu.Destroy()
 
         # update statusbar
-        self.log.write(_("Number of loaded records: %d") % \
-                           tlist.GetItemCount())
+        self.log.write(_("Number of loaded records: %d") %
+                       tlist.GetItemCount())
 
     def OnDataItemEdit(self, event):
         """Edit selected record of the attribute table"""
-        tlist      = self.FindWindowById(self.layerPage[self.selLayer]['data'])
-        item      = tlist.GetFirstSelected()
+        tlist = self.FindWindowById(self.layerPage[self.selLayer]['data'])
+        item = tlist.GetFirstSelected()
         if item == -1:
             return
-        table     = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table']
+        table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table']
         keyColumn = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['key']
-        cat       = tlist.itemCatsMap[tlist.itemIndexMap[item]]
+        cat = tlist.itemCatsMap[tlist.itemIndexMap[item]]
 
         # (column name, value)
         data = []
 
         # collect names of all visible columns
         columnName = []
-        for i in range(tlist.GetColumnCount()): 
+        for i in range(tlist.GetColumnCount()):
             columnName.append(tlist.GetColumn(i).GetText())
 
-
         # key column must be always presented
         if keyColumn not in columnName:
-            columnName.insert(0, keyColumn) # insert key column on first position
+            # insert key column on first position
+            columnName.insert(0, keyColumn)
             data.append((keyColumn, str(cat)))
             keyId = 0
             missingKey = True
         else:
             missingKey = False
-            
+
         # add other visible columns
         for i in range(len(columnName)):
-            ctype = self.dbMgrData['mapDBInfo'].tables[table][columnName[i]]['ctype']
-            ctypeStr = self.dbMgrData['mapDBInfo'].tables[table][columnName[i]]['type']
-            if columnName[i] == keyColumn: # key 
-                if missingKey is False: 
+            ctype = self.dbMgrData['mapDBInfo'].tables[
+                table][columnName[i]]['ctype']
+            ctypeStr = self.dbMgrData['mapDBInfo'].tables[
+                table][columnName[i]]['type']
+            if columnName[i] == keyColumn:  # key
+                if missingKey is False:
                     data.append((columnName[i], ctype, ctypeStr, str(cat)))
                     keyId = i
             else:
                 if missingKey is True:
-                    value = tlist.GetItem(item, i-1).GetText()
+                    value = tlist.GetItem(item, i - 1).GetText()
                 else:
                     value = tlist.GetItem(item, i).GetText()
                 data.append((columnName[i], ctype, ctypeStr, value))
 
-        dlg = ModifyTableRecord(parent = self, 
-                                title = _("Update existing record"),
-                                data = data, keyEditable = (keyId, False))
+        dlg = ModifyTableRecord(parent=self,
+                                title=_("Update existing record"),
+                                data=data, keyEditable=(keyId, False))
 
         if dlg.ShowModal() == wx.ID_OK:
-            values = dlg.GetValues() # string
+            values = dlg.GetValues()  # string
             updateList = list()
             try:
-                for i in range(len(values)): 
-                    if i == keyId: # skip key column
+                for i in range(len(values)):
+                    if i == keyId:  # skip key column
                         continue
                     if tlist.GetItem(item, i).GetText() == values[i]:
-                        continue # no change
-                    
+                        continue  # no change
+
                     column = tlist.columns[columnName[i]]
                     if len(values[i]) > 0:
                         try:
@@ -1364,89 +1494,99 @@
                                 idx = i - 1
                             else:
                                 idx = i
-                            
+
                             if column['ctype'] != types.StringType:
-                                tlist.itemDataMap[item][idx] = column['ctype'] (values[i])
-                            else: # -> string
+                                tlist.itemDataMap[item][
+                                    idx] = column['ctype'](values[i])
+                            else:  # -> string
                                 tlist.itemDataMap[item][idx] = values[i]
                         except ValueError:
-                            raise ValueError(_("Value '%(value)s' needs to be entered as %(type)s.") % \
-                                                 {'value' : str(values[i]),
-                                                  'type' : column['type']})
-                        
+                            raise ValueError(_("Value '%(value)s' needs to be entered as %(type)s.") %
+                                             {'value': str(values[i]),
+                                              'type': column['type']})
+
                         if column['ctype'] == types.StringType:
-                            if "'" in values[i]: # replace "'" -> "''"
+                            if "'" in values[i]:  # replace "'" -> "''"
                                 values[i] = values[i].replace("'", "''")
-                            updateList.append("%s='%s'" % (columnName[i], values[i]))
+                            updateList.append(
+                                "%s='%s'" %
+                                (columnName[i], values[i]))
                         else:
-                            updateList.append("%s=%s" % (columnName[i], values[i]))
-                    else: # -> NULL
+                            updateList.append(
+                                "%s=%s" %
+                                (columnName[i], values[i]))
+                    else:  # -> NULL
                         updateList.append("%s=NULL" % (columnName[i]))
             except ValueError as err:
-                GError(parent = self,
-                       message = _("Unable to update existing record.\n%s") % err,
-                       showTraceback = False)
+                GError(
+                    parent=self,
+                    message=_("Unable to update existing record.\n%s") %
+                    err,
+                    showTraceback=False)
                 self.OnDataItemEdit(event)
                 return
-            
+
             if updateList:
-                self.listOfSQLStatements.append('UPDATE %s SET %s WHERE %s=%d' % \
-                                                    (table, ','.join(updateList),
-                                                     keyColumn, cat))
-                self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)
-            
+                self.listOfSQLStatements.append(
+                    'UPDATE %s SET %s WHERE %s=%d' %
+                    (table, ','.join(updateList), keyColumn, cat))
+                self.ApplyCommands(
+                    self.listOfCommands,
+                    self.listOfSQLStatements)
+
             tlist.Update()
-        
+
     def OnDataItemAdd(self, event):
         """Add new record to the attribute table"""
-        tlist      = self.FindWindowById(self.layerPage[self.selLayer]['data'])
-        table     = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table']
+        tlist = self.FindWindowById(self.layerPage[self.selLayer]['data'])
+        table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table']
         keyColumn = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['key']
-        
+
         # (column name, value)
         data = []
 
         # collect names of all visible columns
         columnName = []
-        for i in range(tlist.GetColumnCount()): 
+        for i in range(tlist.GetColumnCount()):
             columnName.append(tlist.GetColumn(i).GetText())
 
         # maximal category number
         if len(tlist.itemCatsMap.values()) > 0:
             maxCat = max(tlist.itemCatsMap.values())
         else:
-            maxCat = 0 # starting category '1'
-        
+            maxCat = 0  # starting category '1'
+
         # key column must be always presented
         if keyColumn not in columnName:
-            columnName.insert(0, keyColumn) # insert key column on first position
+            # insert key column on first position
+            columnName.insert(0, keyColumn)
             data.append((keyColumn, str(maxCat + 1)))
             missingKey = True
         else:
             missingKey = False
-            
+
         # add other visible columns
         colIdx = 0
         keyId = -1
         for col in columnName:
             ctype = self.dbMgrData['mapDBInfo'].tables[table][col]['ctype']
             ctypeStr = self.dbMgrData['mapDBInfo'].tables[table][col]['type']
-            if col == keyColumn: # key 
-                if missingKey is False: 
+            if col == keyColumn:  # key
+                if missingKey is False:
                     data.append((col, ctype, ctypeStr, str(maxCat + 1)))
                     keyId = colIdx
             else:
                 data.append((col, ctype, ctypeStr, ''))
-            
+
             colIdx += 1
-                
-        dlg = ModifyTableRecord(parent = self,
-                                title = _("Insert new record"),
-                                data = data, keyEditable = (keyId, True))
 
+        dlg = ModifyTableRecord(parent=self,
+                                title=_("Insert new record"),
+                                data=data, keyEditable=(keyId, True))
+
         if dlg.ShowModal() == wx.ID_OK:
-            try: # get category number
-                cat = int(dlg.GetValues(columns = [keyColumn])[0])
+            try:  # get category number
+                cat = int(dlg.GetValues(columns=[keyColumn])[0])
             except:
                 cat = -1
 
@@ -1455,21 +1595,21 @@
                     raise ValueError(_("Record with category number %d "
                                        "already exists in the table.") % cat)
 
-                values = dlg.GetValues() # values (need to be casted)
+                values = dlg.GetValues()  # values (need to be casted)
                 columnsString = ''
-                valuesString   = ''
-                
+                valuesString = ''
+
                 for i in range(len(values)):
-                    if len(values[i]) == 0: # NULL
+                    if len(values[i]) == 0:  # NULL
                         if columnName[i] == keyColumn:
                             raise ValueError(_("Category number (column %s)"
                                                " is missing.") % keyColumn)
                         else:
                             continue
-                    
+
                     try:
                         if tlist.columns[columnName[i]]['ctype'] == int:
-                            # values[i] is stored as text. 
+                            # values[i] is stored as text.
                             values[i] = int(float(values[i]))
                         elif tlist.columns[columnName[i]]['ctype'] == float:
                             values[i] = float(values[i])
@@ -1478,74 +1618,76 @@
                                          {'value': values[i],
                                           'type': tlist.columns[columnName[i]]['type']})
                     columnsString += '%s,' % columnName[i]
-                    
+
                     if tlist.columns[columnName[i]]['ctype'] == str:
                         valuesString += "'%s'," % values[i]
                     else:
                         valuesString += "%s," % values[i]
-                
+
             except ValueError as err:
-                GError(parent = self,
-                       message = _("Unable to insert new record.\n%s") % err,
-                       showTraceback = False)
+                GError(parent=self,
+                       message=_("Unable to insert new record.\n%s") % err,
+                       showTraceback=False)
                 self.OnDataItemAdd(event)
                 return
-            
-            # remove category if need 
+
+            # remove category if need
             if missingKey is True:
                 del values[0]
-                
+
             # add new item to the tlist
             if len(tlist.itemIndexMap) > 0:
                 index = max(tlist.itemIndexMap) + 1
             else:
                 index = 0
-            
+
             tlist.itemIndexMap.append(index)
             tlist.itemDataMap[index] = values
             tlist.itemCatsMap[index] = cat
             tlist.SetItemCount(tlist.GetItemCount() + 1)
 
-            self.listOfSQLStatements.append('INSERT INTO %s (%s) VALUES(%s)' % \
-                                                (table,
-                                                 columnsString.rstrip(','),
-                                                 valuesString.rstrip(',')))
-            
+            self.listOfSQLStatements.append('INSERT INTO %s (%s) VALUES(%s)' %
+                                            (table,
+                                             columnsString.rstrip(','),
+                                             valuesString.rstrip(',')))
+
             self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)
 
-        
     def OnDataItemDelete(self, event):
         """Delete selected item(s) from the tlist (layer/category pair)"""
         dlist = self.FindWindowById(self.layerPage[self.selLayer]['data'])
         item = dlist.GetFirstSelected()
-        
-        table    = self.dbMgrData['mapDBInfo'].layers[self.selLayer]["table"]
-        key      = self.dbMgrData['mapDBInfo'].layers[self.selLayer]["key"]
-        
+
+        table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]["table"]
+        key = self.dbMgrData['mapDBInfo'].layers[self.selLayer]["key"]
+
         indices = []
         # collect SQL statements
         while item != -1:
             index = dlist.itemIndexMap[item]
             indices.append(index)
-            
+
             cat = dlist.itemCatsMap[index]
-            
-            self.listOfSQLStatements.append('DELETE FROM %s WHERE %s=%d' % \
-                                                (table, key, cat))
-            
+
+            self.listOfSQLStatements.append('DELETE FROM %s WHERE %s=%d' %
+                                            (table, key, cat))
+
             item = dlist.GetNextSelected(item)
-        
-        if UserSettings.Get(group = 'atm', key = 'askOnDeleteRec', subkey = 'enabled'):
-            deleteDialog = wx.MessageBox(parent = self,
-                                         message = _("Selected data records (%d) will be permanently deleted "
-                                                   "from table. Do you want to delete them?") % \
-                                             (len(self.listOfSQLStatements)),
-                                         caption = _("Delete records"),
-                                         style = wx.YES_NO | wx.CENTRE)
+
+        if UserSettings.Get(
+                group='atm', key='askOnDeleteRec', subkey='enabled'):
+            deleteDialog = wx.MessageBox(
+                parent=self,
+                message=_(
+                    "Selected data records (%d) will be permanently deleted "
+                    "from table. Do you want to delete them?") %
+                (len(self.listOfSQLStatements)),
+                caption=_("Delete records"),
+                style=wx.YES_NO | wx.CENTRE)
             if deleteDialog != wx.YES:
                 self.listOfSQLStatements = []
                 return False
-        
+
         # restore maps
         i = 0
         indexTemp = copy.copy(dlist.itemIndexMap)
@@ -1554,7 +1696,7 @@
         dlist.itemDataMap = {}
         catsTemp = copy.deepcopy(dlist.itemCatsMap)
         dlist.itemCatsMap = {}
-        
+
         i = 0
         for index in indexTemp:
             if index in indices:
@@ -1562,37 +1704,41 @@
             dlist.itemIndexMap.append(i)
             dlist.itemDataMap[i] = dataTemp[index]
             dlist.itemCatsMap[i] = catsTemp[index]
-            
+
             i += 1
-            
+
         dlist.SetItemCount(len(dlist.itemIndexMap))
-        
+
         # deselect items
         item = dlist.GetFirstSelected()
         while item != -1:
-            dlist.SetItemState(item, 0, wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED)
+            dlist.SetItemState(
+                item, 0, wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED)
             item = dlist.GetNextSelected(item)
-        
+
         # submit SQL statements
         self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)
-        
+
         return True
 
     def OnDataItemDeleteAll(self, event):
         """Delete all items from the list"""
         dlist = self.FindWindowById(self.layerPage[self.selLayer]['data'])
-        if UserSettings.Get(group = 'atm', key = 'askOnDeleteRec', subkey = 'enabled'):
-            deleteDialog = wx.MessageBox(parent = self,
-                                         message = _("All data records (%d) will be permanently deleted "
-                                                   "from table. Do you want to delete them?") % \
-                                             (len(dlist.itemIndexMap)),
-                                         caption = _("Delete records"),
-                                         style = wx.YES_NO | wx.CENTRE)
+        if UserSettings.Get(
+                group='atm', key='askOnDeleteRec', subkey='enabled'):
+            deleteDialog = wx.MessageBox(
+                parent=self,
+                message=_(
+                    "All data records (%d) will be permanently deleted "
+                    "from table. Do you want to delete them?") %
+                (len(dlist.itemIndexMap)),
+                caption=_("Delete records"),
+                style=wx.YES_NO | wx.CENTRE)
             if deleteDialog != wx.YES:
                 return
 
         dlist.DeleteAllItems()
-        dlist.itemDataMap  = {}
+        dlist.itemDataMap = {}
         dlist.itemIndexMap = []
         dlist.SetItemCount(0)
 
@@ -1600,45 +1746,48 @@
         self.listOfSQLStatements.append('DELETE FROM %s' % table)
 
         self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)
-        
+
         event.Skip()
 
     def _drawSelected(self, zoom, selectedOnly=True):
         """Highlight selected features"""
         if not self.map or not self.mapdisplay:
             return
-        
+
         tlist = self.FindWindowById(self.layerPage[self.selLayer]['data'])
         if selectedOnly:
             fn = tlist.GetSelectedItems
         else:
             fn = tlist.GetItems
-        
+
         cats = map(int, fn())
-        
+
         digitToolbar = None
         if 'vdigit' in self.mapdisplay.toolbars:
             digitToolbar = self.mapdisplay.toolbars['vdigit']
-        if digitToolbar and digitToolbar.GetLayer() and \
-                digitToolbar.GetLayer().GetName() == self.dbMgrData['vectName']:
+        if digitToolbar and digitToolbar.GetLayer() and digitToolbar.GetLayer(
+        ).GetName() == self.dbMgrData['vectName']:
             display = self.mapdisplay.GetMapWindow().GetDisplay()
-            display.SetSelected(cats, layer = self.selLayer)
+            display.SetSelected(cats, layer=self.selLayer)
             if zoom:
                 n, s, w, e = display.GetRegionSelected()
-                self.mapdisplay.Map.GetRegion(n = n, s = s, w = w, e = e,
-                                              update = True)
+                self.mapdisplay.Map.GetRegion(n=n, s=s, w=w, e=e,
+                                              update=True)
         else:
             # add map layer with higlighted vector features
-            self.AddQueryMapLayer(selectedOnly) # -> self.qlayer
+            self.AddQueryMapLayer(selectedOnly)  # -> self.qlayer
 
             # set opacity based on queried layer
             if self.parent and self.mapdisplay.tree and \
                     self.dbMgrData['treeItem']:
-                maptree = self.mapdisplay.tree # TODO: giface
-                opacity = maptree.GetLayerInfo(self.dbMgrData['treeItem'], key = 'maplayer').GetOpacity()
+                maptree = self.mapdisplay.tree  # TODO: giface
+                opacity = maptree.GetLayerInfo(
+                    self.dbMgrData['treeItem'],
+                    key='maplayer').GetOpacity()
                 self.qlayer.SetOpacity(opacity)
             if zoom:
-                keyColumn = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['key']
+                keyColumn = self.dbMgrData[
+                    'mapDBInfo'].layers[self.selLayer]['key']
                 where = ''
                 for range in ListOfCatsToRange(cats).split(','):
                     if '-' in range:
@@ -1649,16 +1798,16 @@
                     else:
                         where += '%s = %d or ' % (keyColumn, int(range))
                 where = where.rstrip('or ')
-                
+
                 select = RunCommand('v.db.select',
-                                    parent = self,
-                                    read = True,
-                                    quiet = True,
-                                    flags = 'r',
-                                    map = self.dbMgrData['mapDBInfo'].map,
-                                    layer = int(self.selLayer),
-                                    where = where)
-                
+                                    parent=self,
+                                    read=True,
+                                    quiet=True,
+                                    flags='r',
+                                    map=self.dbMgrData['mapDBInfo'].map,
+                                    layer=int(self.selLayer),
+                                    where=where)
+
                 region = {}
                 for line in select.splitlines():
                     key, value = line.split('=')
@@ -1666,25 +1815,27 @@
 
                 nsdist = ewdist = 0
                 renderer = self.mapdisplay.GetMap()
-                nsdist = 10 * ((renderer.GetCurrentRegion()['n'] - renderer.GetCurrentRegion()['s']) /
-                        renderer.height)
-                ewdist = 10 * ((renderer.GetCurrentRegion()['e'] - renderer.GetCurrentRegion()['w']) /
-                        renderer.width)
+                nsdist = 10 * ((renderer.GetCurrentRegion()
+                                ['n'] - renderer.GetCurrentRegion()['s']) / renderer.height)
+                ewdist = 10 * ((renderer.GetCurrentRegion()
+                                ['e'] - renderer.GetCurrentRegion()['w']) / renderer.width)
                 north = region['n'] + nsdist
                 south = region['s'] - nsdist
                 west = region['w'] - ewdist
                 east = region['e'] + ewdist
-                renderer.GetRegion(n = north, s = south, w = west, e = east, update = True)
-                self.mapdisplay.GetMapWindow().ZoomHistory(n = north, s = south, w = west, e = east)
-        
+                renderer.GetRegion(
+                    n=north, s=south, w=west, e=east, update=True)
+                self.mapdisplay.GetMapWindow().ZoomHistory(n=north, s=south, w=west, e=east)
+
         if zoom:
             self.mapdisplay.Map.AdjustRegion()           # adjust resolution
-            self.mapdisplay.Map.AlignExtentFromDisplay() # adjust extent
-            self.mapdisplay.MapWindow.UpdateMap(render = True,  renderVector = True)
+            self.mapdisplay.Map.AlignExtentFromDisplay()  # adjust extent
+            self.mapdisplay.MapWindow.UpdateMap(render=True, renderVector=True)
         else:
-            self.mapdisplay.MapWindow.UpdateMap(render = False, renderVector = True)
-        
-    def AddQueryMapLayer(self, selectedOnly = True):
+            self.mapdisplay.MapWindow.UpdateMap(
+                render=False, renderVector=True)
+
+    def AddQueryMapLayer(self, selectedOnly=True):
         """Redraw a map
 
         :return: True if map has been redrawn, False if no map is given
@@ -1695,15 +1846,19 @@
         else:
             fn = tlist.GetItems
 
-        cats = { self.selLayer : fn() }
-        
+        cats = {self.selLayer: fn()}
+
         if self.mapdisplay.Map.GetLayerIndex(self.qlayer) < 0:
             self.qlayer = None
-            
+
         if self.qlayer:
-            self.qlayer.SetCmd(self.mapdisplay.AddTmpVectorMapLayer(self.dbMgrData['vectName'], cats, addLayer = False))
+            self.qlayer.SetCmd(
+                self.mapdisplay.AddTmpVectorMapLayer(
+                    self.dbMgrData['vectName'],
+                    cats, addLayer=False))
         else:
-            self.qlayer = self.mapdisplay.AddTmpVectorMapLayer(self.dbMgrData['vectName'], cats)
+            self.qlayer = self.mapdisplay.AddTmpVectorMapLayer(
+                self.dbMgrData['vectName'], cats)
 
         return self.qlayer
 
@@ -1721,7 +1876,10 @@
             item = tlist.GetNextItem(item)
             if item == -1:
                 break
-            tlist.SetItemState(item, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)
+            tlist.SetItemState(
+                item,
+                wx.LIST_STATE_SELECTED,
+                wx.LIST_STATE_SELECTED)
 
         event.Skip()
 
@@ -1734,21 +1892,21 @@
             item = tlist.GetNextItem(item, wx.LIST_STATE_SELECTED)
             if item == -1:
                 break
-            tlist.SetItemState(item, 0, wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED)
+            tlist.SetItemState(
+                item, 0, wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED)
         tlist.Focus(0)
-        
+
         event.Skip()
 
-
     def OnDataDrawSelected(self, event):
         """Reload table description"""
-        self._drawSelected(zoom = False)
+        self._drawSelected(zoom=False)
         event.Skip()
 
     def OnDataDrawSelectedZoom(self, event):
-        self._drawSelected(zoom = True)
+        self._drawSelected(zoom=True)
         event.Skip()
- 
+
     def OnExtractSelected(self, event):
         """Extract vector objects selected in attribute browse window
         to new vector map
@@ -1757,32 +1915,33 @@
         # cats = tlist.selectedCats[:]
         cats = tlist.GetSelectedItems()
         if len(cats) == 0:
-            GMessage(parent = self,
-                     message = _('Nothing to extract.'))
+            GMessage(parent=self,
+                     message=_('Nothing to extract.'))
             return
         else:
             # dialog to get file name
-            dlg = CreateNewVector(parent=self, title=_('Extract selected features'),
-                                  giface=self.giface,
-                                  cmd=(('v.extract',
-                                        {'input': self.dbMgrData['vectName'],
-                                         'cats': ListOfCatsToRange(cats)},
-                                        'output')),
-                                  disableTable=True)
+            dlg = CreateNewVector(
+                parent=self, title=_('Extract selected features'),
+                giface=self.giface,
+                cmd=(('v.extract',
+                      {'input': self.dbMgrData['vectName'],
+                       'cats': ListOfCatsToRange(cats)},
+                      'output')),
+                disableTable=True)
             if not dlg:
                 return
-            
-            name = dlg.GetName(full = True)
 
+            name = dlg.GetName(full=True)
+
             if not self.mapdisplay and self.mapdisplay.tree:
-                pass 
+                pass
             elif name and dlg.IsChecked('add'):
                 # add layer to map layer tree
-                self.mapdisplay.tree.AddLayer(ltype = 'vector',
-                                              lname = name,
-                                              lcmd = ['d.vect', 'map=%s' % name])
+                self.mapdisplay.tree.AddLayer(ltype='vector',
+                                              lname=name,
+                                              lcmd=['d.vect', 'map=%s' % name])
             dlg.Destroy()
-            
+
     def OnDeleteSelected(self, event):
         """Delete vector objects selected in attribute browse window
         (attribures and geometry)
@@ -1790,9 +1949,9 @@
         tlist = self.FindWindowById(self.layerPage[self.selLayer]['data'])
         cats = tlist.GetSelectedItems()
         if len(cats) == 0:
-            GMessage(parent = self,
-                     message = _('Nothing to delete.'))
-        
+            GMessage(parent=self,
+                     message=_('Nothing to delete.'))
+
             return
 
         display = None
@@ -1800,44 +1959,49 @@
             pass
         elif 'vdigit' in self.mapdisplay.toolbars:
             digitToolbar = self.mapdisplay.toolbars['vdigit']
-            if digitToolbar and digitToolbar.GetLayer() and \
-                    digitToolbar.GetLayer().GetName() == self.dbMgrData['vectName']:
+            if digitToolbar and digitToolbar.GetLayer() and digitToolbar.GetLayer(
+            ).GetName() == self.dbMgrData['vectName']:
                 display = self.mapdisplay.GetMapWindow().GetDisplay()
-                display.SetSelected(map(int, cats), layer = self.selLayer)
-                self.mapdisplay.MapWindow.UpdateMap(render = True, renderVector = True)
-        
+                display.SetSelected(map(int, cats), layer=self.selLayer)
+                self.mapdisplay.MapWindow.UpdateMap(
+                    render=True, renderVector=True)
+
         if self.OnDataItemDelete(None) and self.mapdisplay:
             if display:
                 self.mapdisplay.GetMapWindow().digit.DeleteSelectedLines()
             else:
                 RunCommand('v.edit',
-                           parent = self,
-                           quiet = True,
-                           map = self.dbMgrData['vectName'],
-                           tool = 'delete',
-                           cats = ListOfCatsToRange(cats))
-            
-            self.mapdisplay.MapWindow.UpdateMap(render = True, renderVector = True)
-     
+                           parent=self,
+                           quiet=True,
+                           map=self.dbMgrData['vectName'],
+                           tool='delete',
+                           cats=ListOfCatsToRange(cats))
+
+            self.mapdisplay.MapWindow.UpdateMap(render=True, renderVector=True)
+
     def OnApplySqlStatement(self, event):
         """Apply simple/advanced sql statement"""
-        keyColumn = -1 # index of key column
+        keyColumn = -1  # index of key column
         listWin = self.FindWindowById(self.layerPage[self.selLayer]['data'])
         sql = None
         win = self.FindWindowById(self.layerPage[self.selLayer]['sqlNtb'])
         if not win:
             return
-        
+
         showSelected = False
         wx.BeginBusyCursor()
         if win.GetSelection() == 0:
             # simple sql statement
-            whereCol = self.FindWindowById(self.layerPage[self.selLayer]['whereColumn']).GetStringSelection()
-            whereOpe = self.FindWindowById(self.layerPage[self.selLayer]['whereOperator']).GetStringSelection()
-            whereWin = self.FindWindowById(self.layerPage[self.selLayer]['where'])
+            whereCol = self.FindWindowById(self.layerPage[self.selLayer][
+                                           'whereColumn']).GetStringSelection()
+            whereOpe = self.FindWindowById(self.layerPage[self.selLayer][
+                                           'whereOperator']).GetStringSelection()
+            whereWin = self.FindWindowById(
+                self.layerPage[self.selLayer]['where'])
             whereVal = whereWin.GetValue().strip()
-            table    = self.dbMgrData['mapDBInfo'].layers[self.selLayer]["table"]
-            if self.dbMgrData['mapDBInfo'].tables[table][whereCol]['ctype'] == str:
+            table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]["table"]
+            if self.dbMgrData['mapDBInfo'].tables[
+                    table][whereCol]['ctype'] == str:
                 # string attribute, check for quotes
                 whereVal = whereVal.replace('"', "'")
                 if whereVal:
@@ -1846,20 +2010,27 @@
                     if not whereVal.endswith("'"):
                         whereVal += "'"
                     whereWin.SetValue(whereVal)
-            
+
             try:
                 if len(whereVal) > 0:
                     showSelected = True
-                    keyColumn = listWin.LoadData(self.selLayer, where = whereCol + whereOpe + whereVal)
+                    keyColumn = listWin.LoadData(
+                        self.selLayer, where=whereCol + whereOpe + whereVal)
                 else:
                     keyColumn = listWin.LoadData(self.selLayer)
             except GException as e:
-                GError(parent = self,
-                       message = _("Loading attribute data failed.\n\n%s") % e.value)
-                self.FindWindowById(self.layerPage[self.selLayer]['where']).SetValue('')
+                GError(
+                    parent=self,
+                    message=_("Loading attribute data failed.\n\n%s") %
+                    e.value)
+                self.FindWindowById(
+                    self.layerPage[
+                        self.selLayer]['where']).SetValue('')
         else:
             # advanced sql statement
-            win = self.FindWindowById(self.layerPage[self.selLayer]['statement'])
+            win = self.FindWindowById(
+                self.layerPage[
+                    self.selLayer]['statement'])
             try:
                 cols, where = self.ValidateSelectStatement(win.GetValue())
                 if cols is None and where is None:
@@ -1867,64 +2038,79 @@
                 if where:
                     showSelected = True
             except TypeError:
-                GError(parent = self,
-                       message = _("Loading attribute data failed.\n"
-                                   "Invalid SQL select statement.\n\n%s") % win.GetValue())
-                win.SetValue("SELECT * FROM %s" % self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table'])
+                GError(
+                    parent=self, message=_(
+                        "Loading attribute data failed.\n"
+                        "Invalid SQL select statement.\n\n%s") %
+                    win.GetValue())
+                win.SetValue(
+                    "SELECT * FROM %s" %
+                    self.dbMgrData['mapDBInfo'].layers[
+                        self.selLayer]['table'])
                 cols = None
                 where = None
-            
+
             if cols or where or sql:
                 try:
-                    keyColumn = listWin.LoadData(self.selLayer, columns = cols,
-                                                 where = where, sql = sql)
+                    keyColumn = listWin.LoadData(self.selLayer, columns=cols,
+                                                 where=where, sql=sql)
                 except GException as e:
-                    GError(parent = self,
-                           message = _("Loading attribute data failed.\n\n%s") % e.value)
-                    win.SetValue("SELECT * FROM %s" % self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table'])
-        
+                    GError(
+                        parent=self,
+                        message=_("Loading attribute data failed.\n\n%s") %
+                        e.value)
+                    win.SetValue(
+                        "SELECT * FROM %s" %
+                        self.dbMgrData['mapDBInfo'].layers[
+                            self.selLayer]['table'])
+
         # sort by key column
         if sql and 'order by' in sql.lower():
-            pass # don't order by key column
+            pass  # don't order by key column
         else:
             if keyColumn > -1:
-                listWin.SortListItems(col = keyColumn, ascending = True)
+                listWin.SortListItems(col=keyColumn, ascending=True)
             else:
-                listWin.SortListItems(col = 0, ascending = True) 
-        
+                listWin.SortListItems(col=0, ascending=True)
+
         wx.EndBusyCursor()
-        
+
         # update statusbar
-        self.log.write(_("Number of loaded records: %d") % \
-                           self.FindWindowById(self.layerPage[self.selLayer]['data']).GetItemCount())
+        self.log.write(
+            _("Number of loaded records: %d") %
+            self.FindWindowById(
+                self.layerPage[
+                    self.selLayer]['data']).GetItemCount())
 
         # update map display if needed
         if self.mapdisplay and \
-                UserSettings.Get(group = 'atm', key = 'highlight', subkey = 'auto'):
+                UserSettings.Get(group='atm', key='highlight', subkey='auto'):
             # TODO: replace by signals
             if showSelected:
-                self._drawSelected(zoom=False, selectedOnly=False) 
+                self._drawSelected(zoom=False, selectedOnly=False)
             else:
                 self.mapdisplay.RemoveQueryLayer()
-                self.mapdisplay.MapWindow.UpdateMap(render=False) # TODO: replace by signals
+                self.mapdisplay.MapWindow.UpdateMap(
+                    render=False)  # TODO: replace by signals
 
-    def OnBuilder(self,event):
+    def OnBuilder(self, event):
         """SQL Builder button pressed -> show the SQLBuilder dialog"""
         if not self.builder:
-            self.builder = SQLBuilderSelect(parent = self, id = wx.ID_ANY, 
-                                            vectmap = self.dbMgrData['vectName'],
-                                            layer = self.selLayer,
-                                            evtHandler = self.OnBuilderEvt)
+            self.builder = SQLBuilderSelect(parent=self, id=wx.ID_ANY,
+                                            vectmap=self.dbMgrData['vectName'],
+                                            layer=self.selLayer,
+                                            evtHandler=self.OnBuilderEvt)
             self.builder.Show()
         else:
             self.builder.Raise()
-        
+
     def OnBuilderEvt(self, event):
         if event == 'apply':
             sqlstr = self.builder.GetSQLStatement()
-            self.FindWindowById(self.layerPage[self.selLayer]['statement']).SetValue(sqlstr)
+            self.FindWindowById(self.layerPage[self.selLayer][
+                                'statement']).SetValue(sqlstr)
             # apply query
-            #self.listOfSQLStatements.append(sqlstr) #TODO probably it was bug 
+            # self.listOfSQLStatements.append(sqlstr) #TODO probably it was bug
             self.OnApplySqlStatement(None)
             # close builder on apply
             if self.builder.CloseOnApply():
@@ -1940,7 +2126,7 @@
         """
         if statement[0:7].lower() != 'select ':
             return None
-        
+
         cols = ''
         index = 7
         for c in statement[index:]:
@@ -1952,26 +2138,28 @@
             cols = None
         else:
             cols = cols.split(',')
-        
-        tablelen = len(self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table'])
-        
-        if statement[index+1:index+6].lower() != 'from ' or \
-                statement[index+6:index+6+tablelen] != '%s' % \
+
+        tablelen = len(
+            self.dbMgrData['mapDBInfo'].layers[
+                self.selLayer]['table'])
+
+        if statement[index + 1:index + 6].lower() != 'from ' or \
+                statement[index + 6:index + 6 + tablelen] != '%s' % \
                 (self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table']):
             return None
-        
-        if len(statement[index+7+tablelen:]) > 0:
+
+        if len(statement[index + 7 + tablelen:]) > 0:
             index = statement.lower().find('where ')
             if index > -1:
-                where = statement[index+6:]
+                where = statement[index + 6:]
             else:
                 where = None
         else:
             where = None
-        
+
         return (cols, where)
 
-    def LoadData(self, layer, columns = None, where = None, sql = None):
+    def LoadData(self, layer, columns=None, where=None, sql=None):
         """Load data into list
 
         :param int layer: layer number
@@ -1979,7 +2167,7 @@
         :param str where: where statement
         :param str sql: full sql statement
 
-        :return: id of key column 
+        :return: id of key column
         :return: -1 if key column is not displayed
         """
         listWin = self.FindWindowById(self.layerPage[layer]['data'])
@@ -1998,27 +2186,33 @@
             return
         win = self.FindWindowById(self.layerPage[self.selLayer]['sqlNtb'])
         if win.GetSelection() == 0:
-            self.FindWindowById(self.layerPage[layer]['whereColumn']).SetSelection(0)
-            self.FindWindowById(self.layerPage[layer]['whereOperator']).SetSelection(0)
+            self.FindWindowById(
+                self.layerPage[layer]['whereColumn']).SetSelection(0)
+            self.FindWindowById(
+                self.layerPage[layer]['whereOperator']).SetSelection(0)
             self.FindWindowById(self.layerPage[layer]['where']).SetValue('')
         else:
-            sqlWin = self.FindWindowById(self.layerPage[self.selLayer]['statement'])
-            sqlWin.SetValue("SELECT * FROM %s" % self.dbMgrData['mapDBInfo'].layers[layer]['table'])
-            
+            sqlWin = self.FindWindowById(
+                self.layerPage[self.selLayer]['statement'])
+            sqlWin.SetValue("SELECT * FROM %s" %
+                            self.dbMgrData['mapDBInfo'].layers[layer]['table'])
+
         self.UpdatePage(layer)
-        
-class DbMgrTablesPage(DbMgrNotebookBase):   
-    def __init__(self, parent, parentDbMgrBase, onlyLayer = -1):
+
+
+class DbMgrTablesPage(DbMgrNotebookBase):
+
+    def __init__(self, parent, parentDbMgrBase, onlyLayer=-1):
         """Page for managing tables
 
         :param parent: GUI parent
         :param parentDbMgrBase: instance of DbMgrBase class
         :param onlyLayer: create only tab of given layer, if -1
-                          creates tabs of all layers 
+                          creates tabs of all layers
         """
 
-        DbMgrNotebookBase.__init__(self, parent = parent,
-                                 parentDbMgrBase = parentDbMgrBase)
+        DbMgrNotebookBase.__init__(self, parent=parent,
+                                   parentDbMgrBase=parentDbMgrBase)
 
         for layer in self.dbMgrData['mapDBInfo'].layers.keys():
             if onlyLayer > 0 and layer != onlyLayer:
@@ -2026,26 +2220,26 @@
             self.AddLayer(layer)
 
         if self.layers:
-            self.SetSelection(0) # select first layer
+            self.SetSelection(0)  # select first layer
             self.selLayer = self.layers[0]
 
-    def AddLayer(self, layer, pos = -1):
-        """Adds tab which represents table 
+    def AddLayer(self, layer, pos=-1):
+        """Adds tab which represents table
 
         :param layer: vector map layer connected to table
         :param pos: position of tab, if -1 it is added to end
 
-        :return: True if layer was added 
-        :return: False if layer was not added - layer has been already added or does not exist 
+        :return: True if layer was added
+        :return: False if layer was not added - layer has been already added or does not exist
         """
         if layer in self.layers or \
-            layer not in self.parentDbMgrBase.GetVectorLayers():
+                layer not in self.parentDbMgrBase.GetVectorLayers():
             return False
 
-        self.layers.append(layer) 
+        self.layers.append(layer)
 
         self.layerPage[layer] = {}
-        panel = wx.Panel(parent = self, id = wx.ID_ANY)
+        panel = wx.Panel(parent=self, id=wx.ID_ANY)
         self.layerPage[layer]['tablePage'] = panel.GetId()
         label = _("Table")
         if not self.dbMgrData['editable']:
@@ -2053,162 +2247,198 @@
 
         if pos == -1:
             pos = self.GetPageCount()
-        self.InsertPage(pos, page = panel,
-                        text = " %d / %s %s" % (layer, label,
-                        self.dbMgrData['mapDBInfo'].layers[layer]['table']))
-            
+        self.InsertPage(
+            pos, page=panel, text=" %d / %s %s" %
+            (layer, label, self.dbMgrData['mapDBInfo'].layers[layer]['table']))
+
         pageSizer = wx.BoxSizer(wx.VERTICAL)
-            
+
         #
         # dbInfo
         #
-        dbBox = wx.StaticBox(parent = panel, id = wx.ID_ANY,
-                                      label = " %s " % _("Database connection"))
+        dbBox = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                             label=" %s " % _("Database connection"))
         dbSizer = wx.StaticBoxSizer(dbBox, wx.VERTICAL)
-        dbSizer.Add(item = CreateDbInfoDesc(panel, self.dbMgrData['mapDBInfo'], layer),
-                    proportion = 1,
-                    flag = wx.EXPAND | wx.ALL,
-                    border = 3)
-            
+        dbSizer.Add(
+            item=CreateDbInfoDesc(
+                panel,
+                self.dbMgrData['mapDBInfo'],
+                layer),
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=3)
+
         #
         # table description
         #
         table = self.dbMgrData['mapDBInfo'].layers[layer]['table']
-        tableBox = wx.StaticBox(parent = panel, id = wx.ID_ANY,
-                                label = " %s " % _("Table <%s> - right-click to delete column(s)") % table)
-        
+        tableBox = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Table <%s> - right-click to delete column(s)") %
+            table)
+
         tableSizer = wx.StaticBoxSizer(tableBox, wx.VERTICAL)
-            
+
         tlist = self._createTableDesc(panel, table)
-        tlist.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnTableRightUp) #wxMSW
-        tlist.Bind(wx.EVT_RIGHT_UP,            self.OnTableRightUp) #wxGTK
+        tlist.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnTableRightUp)  # wxMSW
+        tlist.Bind(wx.EVT_RIGHT_UP, self.OnTableRightUp)  # wxGTK
         self.layerPage[layer]['tableData'] = tlist.GetId()
-           
+
         # manage columns (add)
-        addBox = wx.StaticBox(parent = panel, id = wx.ID_ANY,
-                              label = " %s " % _("Add column"))
+        addBox = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                              label=" %s " % _("Add column"))
         addSizer = wx.StaticBoxSizer(addBox, wx.HORIZONTAL)
-           
-        column = wx.TextCtrl(parent = panel, id = wx.ID_ANY, value = '',
-                             size = (150, -1), style = wx.TE_PROCESS_ENTER)
-        column.Bind(wx.EVT_TEXT,       self.OnTableAddColumnName)
+
+        column = wx.TextCtrl(parent=panel, id=wx.ID_ANY, value='',
+                             size=(150, -1), style=wx.TE_PROCESS_ENTER)
+        column.Bind(wx.EVT_TEXT, self.OnTableAddColumnName)
         column.Bind(wx.EVT_TEXT_ENTER, self.OnTableItemAdd)
         self.layerPage[layer]['addColName'] = column.GetId()
-        addSizer.Add(item =  wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Column")),
-                     flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
-                     border = 5)
-        addSizer.Add(item = column, proportion = 1,
-                     flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
-                     border = 5)
-           
-        ctype = wx.Choice (parent = panel, id = wx.ID_ANY,
-                           choices = ["integer",
-                                      "double",
-                                      "varchar",
-                                      "date"]) # FIXME
+        addSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_("Column")),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+            border=5)
+        addSizer.Add(item=column, proportion=1,
+                     flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+                     border=5)
+
+        ctype = wx.Choice(parent=panel, id=wx.ID_ANY,
+                          choices=["integer",
+                                   "double",
+                                   "varchar",
+                                   "date"])  # FIXME
         ctype.SetSelection(0)
         ctype.Bind(wx.EVT_CHOICE, self.OnTableChangeType)
         self.layerPage[layer]['addColType'] = ctype.GetId()
-        addSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Type")), 
-                     flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
-                     border = 5)
-        addSizer.Add(item = ctype,
-                     flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
-                     border = 5)
-            
-        length = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                             initial = 250,
-                             min = 1, max = 1e6)
+        addSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_("Type")),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+            border=5)
+        addSizer.Add(item=ctype,
+                     flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+                     border=5)
+
+        length = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                             initial=250,
+                             min=1, max=1e6)
         length.Enable(False)
         self.layerPage[layer]['addColLength'] = length.GetId()
-        addSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Length")),
-                     flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
-                     border = 5)
-        addSizer.Add(item = length,
-                     flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
-                     border = 5)
-            
-        btnAddCol = wx.Button(parent = panel, id = wx.ID_ANY, label = _("Add"))
+        addSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_("Length")),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+            border=5)
+        addSizer.Add(item=length,
+                     flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+                     border=5)
+
+        btnAddCol = wx.Button(parent=panel, id=wx.ID_ANY, label=_("Add"))
         btnAddCol.Bind(wx.EVT_BUTTON, self.OnTableItemAdd)
         btnAddCol.Enable(False)
         self.layerPage[layer]['addColButton'] = btnAddCol.GetId()
-        addSizer.Add(item = btnAddCol, flag = wx.ALL | wx.ALIGN_RIGHT | wx.EXPAND,
-                     border = 3)
-            
+        addSizer.Add(item=btnAddCol, flag=wx.ALL | wx.ALIGN_RIGHT | wx.EXPAND,
+                     border=3)
+
         # manage columns (rename)
-        renameBox = wx.StaticBox(parent = panel, id = wx.ID_ANY,
-                                 label = " %s " % _("Rename column"))
+        renameBox = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                                 label=" %s " % _("Rename column"))
         renameSizer = wx.StaticBoxSizer(renameBox, wx.HORIZONTAL)
-            
-        columnFrom = wx.ComboBox(parent = panel, id = wx.ID_ANY, size = (150, -1),
-                                 style = wx.CB_SIMPLE | wx.CB_READONLY,
-                                 choices = self.dbMgrData['mapDBInfo'].GetColumns(table))
+
+        columnFrom = wx.ComboBox(
+            parent=panel, id=wx.ID_ANY, size=(150, -1),
+            style=wx.CB_SIMPLE | wx.CB_READONLY,
+            choices=self.dbMgrData['mapDBInfo'].GetColumns(table))
         columnFrom.SetSelection(0)
         self.layerPage[layer]['renameCol'] = columnFrom.GetId()
-        renameSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Column")),
-                        flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
-                        border = 5)
-        renameSizer.Add(item = columnFrom, proportion = 1,
-                        flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
-                        border = 5)
-            
-        columnTo = wx.TextCtrl(parent = panel, id = wx.ID_ANY, value = '',
-                               size = (150, -1), style = wx.TE_PROCESS_ENTER)
-        columnTo.Bind(wx.EVT_TEXT,       self.OnTableRenameColumnName)
+        renameSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_("Column")),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+            border=5)
+        renameSizer.Add(item=columnFrom, proportion=1,
+                        flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+                        border=5)
+
+        columnTo = wx.TextCtrl(parent=panel, id=wx.ID_ANY, value='',
+                               size=(150, -1), style=wx.TE_PROCESS_ENTER)
+        columnTo.Bind(wx.EVT_TEXT, self.OnTableRenameColumnName)
         columnTo.Bind(wx.EVT_TEXT_ENTER, self.OnTableItemChange)
         self.layerPage[layer]['renameColTo'] = columnTo.GetId()
-        renameSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("To")),
-                        flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
-                        border = 5)
-        renameSizer.Add(item = columnTo, proportion = 1,
-                        flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
-                        border = 5)
-            
-        btnRenameCol = wx.Button(parent = panel, id = wx.ID_ANY, label = _("&Rename"))
+        renameSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_("To")),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+            border=5)
+        renameSizer.Add(item=columnTo, proportion=1,
+                        flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+                        border=5)
+
+        btnRenameCol = wx.Button(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("&Rename"))
         btnRenameCol.Bind(wx.EVT_BUTTON, self.OnTableItemChange)
         btnRenameCol.Enable(False)
         self.layerPage[layer]['renameColButton'] = btnRenameCol.GetId()
-        renameSizer.Add(item = btnRenameCol, flag = wx.ALL | wx.ALIGN_RIGHT | wx.EXPAND,
-                        border = 3)
-            
-        tableSizer.Add(item = tlist,
-                       flag = wx.ALL | wx.EXPAND,
-                       proportion = 1,
-                       border = 3)
-            
+        renameSizer.Add(
+            item=btnRenameCol,
+            flag=wx.ALL | wx.ALIGN_RIGHT | wx.EXPAND,
+            border=3)
+
+        tableSizer.Add(item=tlist,
+                       flag=wx.ALL | wx.EXPAND,
+                       proportion=1,
+                       border=3)
+
         pageSizer.Add(item=dbSizer,
-                      flag = wx.ALL | wx.EXPAND,
-                      proportion = 0,
-                      border = 3)
-           
-        pageSizer.Add(item = tableSizer,
-                      flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
-                      proportion = 1,
-                      border = 3)
-            
-        pageSizer.Add(item = addSizer,
-                      flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
-                      proportion = 0,
-                      border = 3)
-        pageSizer.Add(item = renameSizer,
-                      flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
-                      proportion = 0,
-                      border = 3)
-            
+                      flag=wx.ALL | wx.EXPAND,
+                      proportion=0,
+                      border=3)
+
+        pageSizer.Add(item=tableSizer,
+                      flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
+                      proportion=1,
+                      border=3)
+
+        pageSizer.Add(item=addSizer,
+                      flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
+                      proportion=0,
+                      border=3)
+        pageSizer.Add(item=renameSizer,
+                      flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
+                      proportion=0,
+                      border=3)
+
         panel.SetSizer(pageSizer)
-           
+
         if not self.dbMgrData['editable']:
-            for widget in [columnTo, columnFrom, length, ctype, 
-                           column,   btnAddCol,  btnRenameCol]:
+            for widget in [columnTo, columnFrom, length, ctype,
+                           column, btnAddCol, btnRenameCol]:
                 widget.Enable(False)
 
         return True
 
     def _createTableDesc(self, parent, table):
         """Create list with table description"""
-        tlist = TableListCtrl(parent = parent, id = wx.ID_ANY,
-                             table = self.dbMgrData['mapDBInfo'].tables[table],
-                             columns = self.dbMgrData['mapDBInfo'].GetColumns(table))
+        tlist = TableListCtrl(
+            parent=parent,
+            id=wx.ID_ANY,
+            table=self.dbMgrData['mapDBInfo'].tables[table],
+            columns=self.dbMgrData['mapDBInfo'].GetColumns(table))
         tlist.Populate()
         # sorter
         # itemDataMap = list.Populate()
@@ -2219,7 +2449,9 @@
     def OnTableChangeType(self, event):
         """Data type for new column changed. Enable or disable
         data length widget"""
-        win = self.FindWindowById(self.layerPage[self.selLayer]['addColLength'])
+        win = self.FindWindowById(
+            self.layerPage[
+                self.selLayer]['addColLength'])
         if event.GetString() == "varchar":
             win.Enable(True)
         else:
@@ -2227,9 +2459,13 @@
 
     def OnTableRenameColumnName(self, event):
         """Editing column name to be added to the table"""
-        btn  = self.FindWindowById(self.layerPage[self.selLayer]['renameColButton'])
-        col  = self.FindWindowById(self.layerPage[self.selLayer]['renameCol'])
-        colTo = self.FindWindowById(self.layerPage[self.selLayer]['renameColTo'])
+        btn = self.FindWindowById(
+            self.layerPage[
+                self.selLayer]['renameColButton'])
+        col = self.FindWindowById(self.layerPage[self.selLayer]['renameCol'])
+        colTo = self.FindWindowById(
+            self.layerPage[
+                self.selLayer]['renameColTo'])
         if len(col.GetValue()) > 0 and len(colTo.GetValue()) > 0:
             btn.Enable(True)
         else:
@@ -2239,7 +2475,9 @@
 
     def OnTableAddColumnName(self, event):
         """Editing column name to be added to the table"""
-        btn = self.FindWindowById(self.layerPage[self.selLayer]['addColButton'])
+        btn = self.FindWindowById(
+            self.layerPage[
+                self.selLayer]['addColButton'])
         if len(event.GetString()) > 0:
             btn.Enable(True)
         else:
@@ -2249,50 +2487,61 @@
 
     def OnTableItemChange(self, event):
         """Rename column in the table"""
-        tlist   = self.FindWindowById(self.layerPage[self.selLayer]['tableData'])
-        name   = self.FindWindowById(self.layerPage[self.selLayer]['renameCol']).GetValue()
-        nameTo = self.FindWindowById(self.layerPage[self.selLayer]['renameColTo']).GetValue()
+        tlist = self.FindWindowById(self.layerPage[self.selLayer]['tableData'])
+        name = self.FindWindowById(
+            self.layerPage[
+                self.selLayer]['renameCol']).GetValue()
+        nameTo = self.FindWindowById(self.layerPage[self.selLayer][
+                                     'renameColTo']).GetValue()
 
         table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]["table"]
 
         if not name or not nameTo:
-            GError(parent = self,
-                   message = _("Unable to rename column. "
-                               "No column name defined."))
+            GError(parent=self,
+                   message=_("Unable to rename column. "
+                             "No column name defined."))
             return
         else:
-            item = tlist.FindItem(start = -1, str = name)
+            item = tlist.FindItem(start=-1, str=name)
             if item > -1:
-                if tlist.FindItem(start = -1, str = nameTo) > -1:
-                    GError(parent = self,
-                           message = _("Unable to rename column <%(column)s> to "
-                                       "<%(columnTo)s>. Column already exists "
-                                       "in the table <%(table)s>.") % \
-                               {'column' : name, 'columnTo' : nameTo,
-                                'table' : table})
+                if tlist.FindItem(start=-1, str=nameTo) > -1:
+                    GError(parent=self,
+                           message=_("Unable to rename column <%(column)s> to "
+                                     "<%(columnTo)s>. Column already exists "
+                                     "in the table <%(table)s>.") %
+                           {'column': name, 'columnTo': nameTo,
+                            'table': table})
                     return
                 else:
                     tlist.SetItemText(item, nameTo)
 
                     self.listOfCommands.append(('v.db.renamecolumn',
-                                                { 'map'    : self.dbMgrData['vectName'],
-                                                  'layer'  : self.selLayer,
-                                                  'column' : '%s,%s' % (name, nameTo) }
+                                                {'map': self.dbMgrData['vectName'],
+                                                 'layer': self.selLayer,
+                                                 'column': '%s,%s' % (name, nameTo)}
                                                 ))
             else:
-                GError(parent = self,
-                       message = _("Unable to rename column. "
-                                   "Column <%(column)s> doesn't exist in the table <%(table)s>.") % 
-                       {'column' : name, 'table' : table})
+                GError(
+                    parent=self,
+                    message=_(
+                        "Unable to rename column. "
+                        "Column <%(column)s> doesn't exist in the table <%(table)s>.") % {
+                        'column': name,
+                        'table': table})
                 return
-            
+
         # apply changes
         self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)
 
         # update widgets
-        self.FindWindowById(self.layerPage[self.selLayer]['renameCol']).SetItems(self.dbMgrData['mapDBInfo'].GetColumns(table))
-        self.FindWindowById(self.layerPage[self.selLayer]['renameCol']).SetSelection(0)
-        self.FindWindowById(self.layerPage[self.selLayer]['renameColTo']).SetValue('')
+        self.FindWindowById(
+            self.layerPage[
+                self.selLayer]['renameCol']).SetItems(
+            self.dbMgrData['mapDBInfo'].GetColumns(table))
+        self.FindWindowById(self.layerPage[self.selLayer][
+                            'renameCol']).SetSelection(0)
+        self.FindWindowById(self.layerPage[self.selLayer][
+                            'renameColTo']).SetValue('')
 
         event.Skip()
 
@@ -2302,20 +2551,27 @@
             self.popupTableID1 = wx.NewId()
             self.popupTableID2 = wx.NewId()
             self.popupTableID3 = wx.NewId()
-            self.Bind(wx.EVT_MENU, self.OnTableItemDelete,    id = self.popupTableID1)
-            self.Bind(wx.EVT_MENU, self.OnTableItemDeleteAll, id = self.popupTableID2)
-            self.Bind(wx.EVT_MENU, self.OnTableReload,        id = self.popupTableID3)
+            self.Bind(
+                wx.EVT_MENU,
+                self.OnTableItemDelete,
+                id=self.popupTableID1)
+            self.Bind(
+                wx.EVT_MENU,
+                self.OnTableItemDeleteAll,
+                id=self.popupTableID2)
+            self.Bind(wx.EVT_MENU, self.OnTableReload, id=self.popupTableID3)
 
         # generate popup-menu
         menu = wx.Menu()
         menu.Append(self.popupTableID1, _("Drop selected column"))
-        if self.FindWindowById(self.layerPage[self.selLayer]['tableData']).GetFirstSelected() == -1:
+        if self.FindWindowById(self.layerPage[self.selLayer][
+                               'tableData']).GetFirstSelected() == -1:
             menu.Enable(self.popupTableID1, False)
         menu.Append(self.popupTableID2, _("Drop all columns"))
         menu.AppendSeparator()
         menu.Append(self.popupTableID3, _("Reload"))
-        
-        if not self.dbMgrData['editable']: 
+
+        if not self.dbMgrData['editable']:
             menu.Enable(self.popupTableID1, False)
             menu.Enable(self.popupTableID2, False)
 
@@ -2325,10 +2581,11 @@
     def OnTableItemDelete(self, event):
         """Delete selected item(s) from the list"""
         tlist = self.FindWindowById(self.layerPage[self.selLayer]['tableData'])
-        
+
         item = tlist.GetFirstSelected()
         countSelected = tlist.GetSelectedItemCount()
-        if UserSettings.Get(group = 'atm', key = 'askOnDeleteRec', subkey = 'enabled'):
+        if UserSettings.Get(
+                group='atm', key='askOnDeleteRec', subkey='enabled'):
             # if the user select more columns to delete, all the columns name
             # will appear the the warning dialog
             if tlist.GetSelectedItemCount() > 1:
@@ -2339,102 +2596,127 @@
                         deleteColumns += ", '%s'" % tlist.GetItemText(item)
             else:
                 deleteColumns = "column '%s'" % tlist.GetItemText(item)
-            deleteDialog = wx.MessageBox(parent = self,
-                                         message = _("Selected %s will PERMANENTLY removed "
-                                                   "from table. Do you want to drop the column?") % \
-                                             (deleteColumns),
-                                         caption = _("Drop column(s)"),
-                                         style = wx.YES_NO | wx.CENTRE)
+            deleteDialog = wx.MessageBox(
+                parent=self,
+                message=_(
+                    "Selected %s will PERMANENTLY removed "
+                    "from table. Do you want to drop the column?") %
+                (deleteColumns),
+                caption=_("Drop column(s)"),
+                style=wx.YES_NO | wx.CENTRE)
             if deleteDialog != wx.YES:
                 return False
         item = tlist.GetFirstSelected()
         while item != -1:
             self.listOfCommands.append(('v.db.dropcolumn',
-                                        { 'map' : self.dbMgrData['vectName'],
-                                          'layer' : self.selLayer,
-                                          'column' : tlist.GetItemText(item) }
+                                        {'map': self.dbMgrData['vectName'],
+                                         'layer': self.selLayer,
+                                         'column': tlist.GetItemText(item)}
                                         ))
             tlist.DeleteItem(item)
             item = tlist.GetFirstSelected()
-        
+
         # apply changes
         self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)
-        
+
         # update widgets
         table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table']
-        self.FindWindowById(self.layerPage[self.selLayer]['renameCol']).SetItems(self.dbMgrData['mapDBInfo'].GetColumns(table))
-        self.FindWindowById(self.layerPage[self.selLayer]['renameCol']).SetSelection(0)
-        
+        self.FindWindowById(
+            self.layerPage[
+                self.selLayer]['renameCol']).SetItems(
+            self.dbMgrData['mapDBInfo'].GetColumns(table))
+        self.FindWindowById(self.layerPage[self.selLayer][
+                            'renameCol']).SetSelection(0)
+
         event.Skip()
 
     def OnTableItemDeleteAll(self, event):
         """Delete all items from the list"""
-        table     = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table']
-        cols      = self.dbMgrData['mapDBInfo'].GetColumns(table)
+        table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table']
+        cols = self.dbMgrData['mapDBInfo'].GetColumns(table)
         keyColumn = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['key']
         if keyColumn in cols:
             cols.remove(keyColumn)
-        
-        if UserSettings.Get(group = 'atm', key = 'askOnDeleteRec', subkey = 'enabled'):
-            deleteDialog = wx.MessageBox(parent = self,
-                                         message = _("Selected columns\n%s\nwill PERMANENTLY removed "
-                                                   "from table. Do you want to drop the columns?") % \
-                                             ('\n'.join(cols)),
-                                         caption = _("Drop column(s)"),
-                                         style = wx.YES_NO | wx.CENTRE)
+
+        if UserSettings.Get(
+                group='atm', key='askOnDeleteRec', subkey='enabled'):
+            deleteDialog = wx.MessageBox(
+                parent=self,
+                message=_(
+                    "Selected columns\n%s\nwill PERMANENTLY removed "
+                    "from table. Do you want to drop the columns?") %
+                ('\n'.join(cols)),
+                caption=_("Drop column(s)"),
+                style=wx.YES_NO | wx.CENTRE)
             if deleteDialog != wx.YES:
                 return False
-        
+
         for col in cols:
             self.listOfCommands.append(('v.db.dropcolumn',
-                                        { 'map' : self.dbMgrData['vectName'],
-                                          'layer' : self.selLayer,
-                                          'column' : col }
+                                        {'map': self.dbMgrData['vectName'],
+                                         'layer': self.selLayer,
+                                         'column': col}
                                         ))
-        self.FindWindowById(self.layerPage[self.selLayer]['tableData']).DeleteAllItems()
+        self.FindWindowById(self.layerPage[self.selLayer][
+                            'tableData']).DeleteAllItems()
 
         # apply changes
         self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)
 
         # update widgets
         table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table']
-        self.FindWindowById(self.layerPage[self.selLayer]['renameCol']).SetItems(self.dbMgrData['mapDBInfo'].GetColumns(table))
-        self.FindWindowById(self.layerPage[self.selLayer]['renameCol']).SetSelection(0)
+        self.FindWindowById(
+            self.layerPage[
+                self.selLayer]['renameCol']).SetItems(
+            self.dbMgrData['mapDBInfo'].GetColumns(table))
+        self.FindWindowById(self.layerPage[self.selLayer][
+                            'renameCol']).SetSelection(0)
 
         event.Skip()
 
-    def OnTableReload(self, event = None):
+    def OnTableReload(self, event=None):
         """Reload table description"""
-        self.FindWindowById(self.layerPage[self.selLayer]['tableData']).Populate(update = True)
+        self.FindWindowById(
+            self.layerPage[
+                self.selLayer]['tableData']).Populate(
+            update=True)
         self.listOfCommands = []
 
     def OnTableItemAdd(self, event):
         """Add new column to the table"""
-        name = self.FindWindowById(self.layerPage[self.selLayer]['addColName']).GetValue()
-                
-        ctype = self.FindWindowById(self.layerPage[self.selLayer]['addColType']). \
-            GetStringSelection()
-        
-        length = int(self.FindWindowById(self.layerPage[self.selLayer]['addColLength']). \
-                     GetValue())
-        
+        name = self.FindWindowById(
+            self.layerPage[
+                self.selLayer]['addColName']).GetValue()
+
+        ctype = self.FindWindowById(self.layerPage[self.selLayer][
+                                    'addColType']). GetStringSelection()
+
+        length = int(
+            self.FindWindowById(
+                self.layerPage[
+                    self.selLayer]['addColLength']). GetValue())
+
         # add item to the list of table columns
         tlist = self.FindWindowById(self.layerPage[self.selLayer]['tableData'])
 
-
-        index = tlist.InsertStringItem(sys.maxint, str(name))
+        index = tlist.InsertStringItem(sys.maxsize, str(name))
         tlist.SetStringItem(index, 0, str(name))
         tlist.SetStringItem(index, 1, str(ctype))
         tlist.SetStringItem(index, 2, str(length))
-        
+
         self.AddColumn(name, ctype, length)
 
         # update widgets
         table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table']
-        self.FindWindowById(self.layerPage[self.selLayer]['addColName']).SetValue('')
-        self.FindWindowById(self.layerPage[self.selLayer]['renameCol']).SetItems(self.dbMgrData['mapDBInfo'].GetColumns(table))
-        self.FindWindowById(self.layerPage[self.selLayer]['renameCol']).SetSelection(0)
-        
+        self.FindWindowById(self.layerPage[self.selLayer][
+                            'addColName']).SetValue('')
+        self.FindWindowById(
+            self.layerPage[
+                self.selLayer]['renameCol']).SetItems(
+            self.dbMgrData['mapDBInfo'].GetColumns(table))
+        self.FindWindowById(self.layerPage[self.selLayer][
+                            'renameCol']).SetSelection(0)
+
         event.Skip()
 
     def UpdatePage(self, layer):
@@ -2444,86 +2726,90 @@
 
             # update table description
             tlist = self.FindWindowById(self.layerPage[layer]['tableData'])
-            tlist.Update(table = self.dbMgrData['mapDBInfo'].tables[table],
-                         columns = self.dbMgrData['mapDBInfo'].GetColumns(table))
+            tlist.Update(table=self.dbMgrData['mapDBInfo'].tables[table],
+                         columns=self.dbMgrData['mapDBInfo'].GetColumns(table))
             self.OnTableReload(None)
 
+
 class DbMgrLayersPage(wx.Panel):
+
     def __init__(self, parent, parentDbMgrBase):
         """Create layer manage page"""
         self.parentDbMgrBase = parentDbMgrBase
         self.dbMgrData = self.parentDbMgrBase.dbMgrData
 
-        wx.Panel.__init__(self, parent = parent)
-        splitterWin = wx.SplitterWindow(parent = self, id = wx.ID_ANY)
+        wx.Panel.__init__(self, parent=parent)
+        splitterWin = wx.SplitterWindow(parent=self, id=wx.ID_ANY)
         splitterWin.SetMinimumPaneSize(100)
-                
+
         #
         # list of layers
         #
-        panelList = wx.Panel(parent = splitterWin, id = wx.ID_ANY)
+        panelList = wx.Panel(parent=splitterWin, id=wx.ID_ANY)
 
-        panelListSizer  = wx.BoxSizer(wx.VERTICAL)
-        layerBox = wx.StaticBox(parent = panelList, id = wx.ID_ANY,
-                                label = " %s " % _("List of layers"))
+        panelListSizer = wx.BoxSizer(wx.VERTICAL)
+        layerBox = wx.StaticBox(parent=panelList, id=wx.ID_ANY,
+                                label=" %s " % _("List of layers"))
         layerSizer = wx.StaticBoxSizer(layerBox, wx.VERTICAL)
 
         self.layerList = self._createLayerDesc(panelList)
-        self.layerList.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnLayerRightUp) #wxMSW
-        self.layerList.Bind(wx.EVT_RIGHT_UP,            self.OnLayerRightUp) #wxGTK
-        
-        layerSizer.Add(item = self.layerList,
-                       flag = wx.ALL | wx.EXPAND,
-                       proportion = 1,
-                       border = 3)
+        self.layerList.Bind(
+            wx.EVT_COMMAND_RIGHT_CLICK,
+            self.OnLayerRightUp)  # wxMSW
+        self.layerList.Bind(wx.EVT_RIGHT_UP, self.OnLayerRightUp)  # wxGTK
 
-        panelListSizer.Add(item = layerSizer,
-                           flag = wx.ALL | wx.EXPAND,
-                           proportion = 1,
-                           border = 3)
+        layerSizer.Add(item=self.layerList,
+                       flag=wx.ALL | wx.EXPAND,
+                       proportion=1,
+                       border=3)
 
+        panelListSizer.Add(item=layerSizer,
+                           flag=wx.ALL | wx.EXPAND,
+                           proportion=1,
+                           border=3)
+
         panelList.SetSizer(panelListSizer)
 
         #
         # manage part
         #
-        panelManage = wx.Panel(parent = splitterWin, id = wx.ID_ANY)
-         
+        panelManage = wx.Panel(parent=splitterWin, id=wx.ID_ANY)
+
         manageSizer = wx.BoxSizer(wx.VERTICAL)
 
-        self.manageLayerBook = LayerBook(parent = panelManage, id = wx.ID_ANY,
-                                         parentDialog = self)
+        self.manageLayerBook = LayerBook(parent=panelManage, id=wx.ID_ANY,
+                                         parentDialog=self)
         if not self.dbMgrData['editable']:
             self.manageLayerBook.Enable(False)
 
-        manageSizer.Add(item = self.manageLayerBook,
-                        proportion = 1,
-                        flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
-                        border = 5)
+        manageSizer.Add(item=self.manageLayerBook,
+                        proportion=1,
+                        flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
+                        border=5)
 
-        panelSizer  = wx.BoxSizer(wx.VERTICAL)
-        panelSizer.Add(item = splitterWin,
-                      proportion = 1, 
-                      flag = wx.EXPAND) 
+        panelSizer = wx.BoxSizer(wx.VERTICAL)
+        panelSizer.Add(item=splitterWin,
+                       proportion=1,
+                       flag=wx.EXPAND)
 
         panelManage.SetSizer(manageSizer)
-        splitterWin.SplitHorizontally(panelList, panelManage, 100) 
+        splitterWin.SplitHorizontally(panelList, panelManage, 100)
         splitterWin.Fit()
         self.SetSizer(panelSizer)
 
     def _createLayerDesc(self, parent):
         """Create list of linked layers"""
-        tlist = LayerListCtrl(parent = parent, id = wx.ID_ANY,
-                             layers = self.dbMgrData['mapDBInfo'].layers)
-        
+        tlist = LayerListCtrl(parent=parent, id=wx.ID_ANY,
+                              layers=self.dbMgrData['mapDBInfo'].layers)
+
         tlist.Populate()
         # sorter
         # itemDataMap = list.Populate()
         # listmix.ColumnSorterMixin.__init__(self, 2)
 
         return tlist
-   
-    def UpdatePage(self):           
+
+    def UpdatePage(self):
         #
         # 'manage layers' page
         #
@@ -2532,45 +2818,50 @@
         #self.dbMgrData['mapDBInfo'] = VectorDBInfo(self.dbMgrData['vectName'])
 
         self.layerList.Update(self.dbMgrData['mapDBInfo'].layers)
-        self.layerList.Populate(update = True)
+        self.layerList.Populate(update=True)
         # update selected widgets
         listOfLayers = map(str, self.dbMgrData['mapDBInfo'].layers.keys())
-        ### delete layer page
+        # delete layer page
         self.manageLayerBook.deleteLayer.SetItems(listOfLayers)
         if len(listOfLayers) > 0:
-            self.manageLayerBook.deleteLayer.SetStringSelection(listOfLayers[0])
-            tableName = self.dbMgrData['mapDBInfo'].layers[int(listOfLayers[0])]['table']
+            self.manageLayerBook.deleteLayer.SetStringSelection(
+                listOfLayers
+                [0])
+            tableName = self.dbMgrData['mapDBInfo'].layers[int(listOfLayers[0])][
+                'table']
             maxLayer = max(self.dbMgrData['mapDBInfo'].layers.keys())
         else:
             tableName = ''
             maxLayer = 0
-        self.manageLayerBook.deleteTable.SetLabel( \
-            _('Drop also linked attribute table (%s)') % \
-                tableName)
-        ### add layer page
-        self.manageLayerBook.addLayerWidgets['layer'][1].SetValue(\
-            maxLayer+1)
-        ### modify layer
-        self.manageLayerBook.modifyLayerWidgets['layer'][1].SetItems(listOfLayers)
-        self.manageLayerBook.OnChangeLayer(event = None)
+        self.manageLayerBook.deleteTable.SetLabel(
+            _('Drop also linked attribute table (%s)') %
+            tableName)
+        # add layer page
+        self.manageLayerBook.addLayerWidgets['layer'][1].SetValue(
+            maxLayer + 1)
+        # modify layer
+        self.manageLayerBook.modifyLayerWidgets[
+            'layer'][1].SetItems(listOfLayers)
+        self.manageLayerBook.OnChangeLayer(event=None)
 
     def OnLayerRightUp(self, event):
         """Layer description area, context menu"""
         pass
 
+
 class TableListCtrl(wx.ListCtrl,
                     listmix.ListCtrlAutoWidthMixin):
     #                    listmix.TextEditMixin):
     """Table description list"""
 
-    def __init__(self, parent, id, table, columns, pos = wx.DefaultPosition,
-                 size = wx.DefaultSize):
+    def __init__(self, parent, id, table, columns, pos=wx.DefaultPosition,
+                 size=wx.DefaultSize):
 
-        self.parent  = parent
-        self.table   = table
+        self.parent = parent
+        self.table = table
         self.columns = columns
         wx.ListCtrl.__init__(self, parent, id, pos, size,
-                             style = wx.LC_REPORT | wx.LC_HRULES | wx.LC_VRULES |
+                             style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_VRULES |
                              wx.BORDER_NONE)
 
         listmix.ListCtrlAutoWidthMixin.__init__(self)
@@ -2578,27 +2869,27 @@
 
     def Update(self, table, columns):
         """Update column description"""
-        self.table   = table
+        self.table = table
         self.columns = columns
 
-    def Populate(self, update = False):
+    def Populate(self, update=False):
         """Populate the list"""
-        itemData = {} # requested by sorter
+        itemData = {}  # requested by sorter
 
         if not update:
             headings = [_("Column name"), _("Data type"), _("Data length")]
             i = 0
             for h in headings:
-                self.InsertColumn(col = i, heading = h)
+                self.InsertColumn(col=i, heading=h)
                 i += 1
-            self.SetColumnWidth(col = 0, width = 350)
-            self.SetColumnWidth(col = 1, width = 175)
+            self.SetColumnWidth(col=0, width=350)
+            self.SetColumnWidth(col=1, width=175)
         else:
             self.DeleteAllItems()
 
         i = 0
         for column in self.columns:
-            index = self.InsertStringItem(sys.maxint, str(column))
+            index = self.InsertStringItem(sys.maxsize, str(column))
             self.SetStringItem(index, 0, str(column))
             self.SetStringItem(index, 1, str(self.table[column]['type']))
             self.SetStringItem(index, 2, str(self.table[column]['length']))
@@ -2609,9 +2900,10 @@
             i = i + 1
 
         self.SendSizeEvent()
-        
+
         return itemData
 
+
 class LayerListCtrl(wx.ListCtrl,
                     listmix.ListCtrlAutoWidthMixin):
                     # listmix.ColumnSorterMixin):
@@ -2619,13 +2911,13 @@
     """Layer description list"""
 
     def __init__(self, parent, id, layers,
-                 pos = wx.DefaultPosition,
-                 size = wx.DefaultSize):
+                 pos=wx.DefaultPosition,
+                 size=wx.DefaultSize):
 
         self.parent = parent
         self.layers = layers
         wx.ListCtrl.__init__(self, parent, id, pos, size,
-                             style = wx.LC_REPORT | wx.LC_HRULES | wx.LC_VRULES |
+                             style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_VRULES |
                              wx.BORDER_NONE)
 
         listmix.ListCtrlAutoWidthMixin.__init__(self)
@@ -2635,27 +2927,32 @@
         """Update description"""
         self.layers = layers
 
-    def Populate(self, update = False):
+    def Populate(self, update=False):
         """Populate the list"""
-        itemData = {} # requested by sorter
+        itemData = {}  # requested by sorter
 
         if not update:
-            headings = [_("Layer"),  _("Driver"), _("Database"), _("Table"), _("Key")]
+            headings = [
+                _("Layer"),
+                _("Driver"),
+                _("Database"),
+                _("Table"),
+                _("Key")]
             i = 0
             for h in headings:
-                self.InsertColumn(col = i, heading = h)
+                self.InsertColumn(col=i, heading=h)
                 i += 1
         else:
             self.DeleteAllItems()
 
         i = 0
         for layer in self.layers.keys():
-            index = self.InsertStringItem(sys.maxint, str(layer))
+            index = self.InsertStringItem(sys.maxsize, str(layer))
             self.SetStringItem(index, 0, str(layer))
             database = str(self.layers[layer]['database'])
-            driver   = str(self.layers[layer]['driver'])
-            table    = str(self.layers[layer]['table'])
-            key      = str(self.layers[layer]['key'])
+            driver = str(self.layers[layer]['driver'])
+            table = str(self.layers[layer]['table'])
+            key = str(self.layers[layer]['key'])
             self.SetStringItem(index, 1, driver)
             self.SetStringItem(index, 2, database)
             self.SetStringItem(index, 3, table)
@@ -2669,63 +2966,66 @@
             i += 1
 
         for i in range(self.GetColumnCount()):
-            self.SetColumnWidth(col = i, width = wx.LIST_AUTOSIZE)
-            if self.GetColumnWidth(col = i) < 60:
-                self.SetColumnWidth(col = i, width = 60)
+            self.SetColumnWidth(col=i, width=wx.LIST_AUTOSIZE)
+            if self.GetColumnWidth(col=i) < 60:
+                self.SetColumnWidth(col=i, width=60)
 
         self.SendSizeEvent()
-        
+
         return itemData
 
+
 class LayerBook(wx.Notebook):
     """Manage layers (add, delete, modify)"""
+
     def __init__(self, parent, id,
                  parentDialog,
-                 style = wx.BK_DEFAULT):
-        wx.Notebook.__init__(self, parent, id, style = style)
+                 style=wx.BK_DEFAULT):
+        wx.Notebook.__init__(self, parent, id, style=style)
 
-        self.parent       = parent
+        self.parent = parent
         self.parentDialog = parentDialog
-        self.mapDBInfo    = self.parentDialog.dbMgrData['mapDBInfo']
+        self.mapDBInfo = self.parentDialog.dbMgrData['mapDBInfo']
 
         #
         # drivers
         #
         drivers = RunCommand('db.drivers',
-                             quiet = True,
-                             read = True,
-                             flags = 'p')
-        
+                             quiet=True,
+                             read=True,
+                             flags='p')
+
         self.listOfDrivers = []
         for drv in drivers.splitlines():
             self.listOfDrivers.append(drv.strip())
-        
+
         #
         # get default values
         #
         self.defaultConnect = {}
         connect = RunCommand('db.connect',
-                             flags = 'p',
-                             read = True,
-                             quiet = True)
-        
+                             flags='p',
+                             read=True,
+                             quiet=True)
+
         for line in connect.splitlines():
             item, value = line.split(':', 1)
             self.defaultConnect[item.strip()] = value.strip()
-        
-        ### really needed?
+
+        # really needed?
         # if len(self.defaultConnect['driver']) == 0 or \
         #        len(self.defaultConnect['database']) == 0:
         #     GWarning(parent = self.parent,
         #              message = _("Unknown default DB connection. "
         #                          "Please define DB connection using db.connect module."))
-        
+
         self.defaultTables = self._getTables(self.defaultConnect['driver'],
                                              self.defaultConnect['database'])
         try:
-            self.defaultColumns = self._getColumns(self.defaultConnect['driver'],
-                                                    self.defaultConnect['database'],
-                                                    self.defaultTables[0])
+            self.defaultColumns = self._getColumns(
+                self.defaultConnect['driver'],
+                self.defaultConnect['database'],
+                self.defaultTables[0])
         except IndexError:
             self.defaultColumns = []
 
@@ -2735,112 +3035,118 @@
 
     def _createAddPage(self):
         """Add new layer"""
-        self.addPanel = wx.Panel(parent = self, id = wx.ID_ANY)
-        self.AddPage(page = self.addPanel, text = _("Add layer"))
-        
+        self.addPanel = wx.Panel(parent=self, id=wx.ID_ANY)
+        self.AddPage(page=self.addPanel, text=_("Add layer"))
+
         try:
             maxLayer = max(self.mapDBInfo.layers.keys())
         except ValueError:
             maxLayer = 0
 
         # layer description
-        
-        layerBox = wx.StaticBox (parent = self.addPanel, id = wx.ID_ANY,
-                                 label = " %s " % (_("Layer description")))
+
+        layerBox = wx.StaticBox(parent=self.addPanel, id=wx.ID_ANY,
+                                label=" %s " % (_("Layer description")))
         layerSizer = wx.StaticBoxSizer(layerBox, wx.VERTICAL)
-        
+
         #
         # list of layer widgets (label, value)
         #
         self.addLayerWidgets = {'layer':
-                                    (wx.StaticText(parent = self.addPanel, id = wx.ID_ANY,
-                                                   label = '%s:' % _("Layer")),
-                                     wx.SpinCtrl(parent = self.addPanel, id = wx.ID_ANY, size = (65, -1),
-                                                 initial = maxLayer+1,
-                                                 min = 1, max = 1e6)),
+                                (wx.StaticText(parent=self.addPanel, id=wx.ID_ANY,
+                                               label='%s:' % _("Layer")),
+                                 wx.SpinCtrl(parent=self.addPanel, id=wx.ID_ANY, size=(65, -1),
+                                             initial=maxLayer + 1,
+                                             min=1, max=1e6)),
                                 'driver':
-                                    (wx.StaticText(parent = self.addPanel, id = wx.ID_ANY,
-                                                   label = '%s:' % _("Driver")),
-                                     wx.Choice(parent = self.addPanel, id = wx.ID_ANY, size = (200, -1),
-                                               choices = self.listOfDrivers)),
+                                    (wx.StaticText(parent=self.addPanel, id=wx.ID_ANY,
+                                                   label='%s:' % _("Driver")),
+                                     wx.Choice(parent=self.addPanel, id=wx.ID_ANY, size=(200, -1),
+                                               choices=self.listOfDrivers)),
                                 'database':
-                                    (wx.StaticText(parent = self.addPanel, id = wx.ID_ANY,
-                                                   label = '%s:' % _("Database")),
-                                     wx.TextCtrl(parent = self.addPanel, id = wx.ID_ANY,
-                                                 value = '',
-                                                 style = wx.TE_PROCESS_ENTER)),
+                                    (wx.StaticText(parent=self.addPanel, id=wx.ID_ANY,
+                                                   label='%s:' % _("Database")),
+                                     wx.TextCtrl(parent=self.addPanel, id=wx.ID_ANY,
+                                                 value='',
+                                                 style=wx.TE_PROCESS_ENTER)),
                                 'table':
-                                    (wx.StaticText(parent = self.addPanel, id = wx.ID_ANY,
-                                                   label = '%s:' % _("Table")),
-                                     wx.Choice(parent = self.addPanel, id = wx.ID_ANY, size = (200, -1),
-                                               choices = self.defaultTables)),
+                                    (wx.StaticText(parent=self.addPanel, id=wx.ID_ANY,
+                                                   label='%s:' % _("Table")),
+                                     wx.Choice(parent=self.addPanel, id=wx.ID_ANY, size=(200, -1),
+                                               choices=self.defaultTables)),
                                 'key':
-                                    (wx.StaticText(parent = self.addPanel, id = wx.ID_ANY,
-                                                   label = '%s:' % _("Key column")),
-                                     wx.Choice(parent = self.addPanel, id = wx.ID_ANY, size = (200, -1),
-                                               choices = self.defaultColumns)),
+                                    (wx.StaticText(parent=self.addPanel, id=wx.ID_ANY,
+                                                   label='%s:' % _("Key column")),
+                                     wx.Choice(parent=self.addPanel, id=wx.ID_ANY, size=(200, -1),
+                                               choices=self.defaultColumns)),
                                 'addCat':
-                                    (wx.CheckBox(parent = self.addPanel, id = wx.ID_ANY,
-                                                 label = _("Insert record for each category into table")),
+                                    (wx.CheckBox(parent=self.addPanel, id=wx.ID_ANY,
+                                                 label=_("Insert record for each category into table")),
                                      None),
                                 }
-        
+
         # set default values for widgets
-        self.addLayerWidgets['driver'][1].SetStringSelection(self.defaultConnect['driver'])
-        self.addLayerWidgets['database'][1].SetValue(self.defaultConnect['database'])
+        self.addLayerWidgets['driver'][1].SetStringSelection(
+            self.defaultConnect['driver'])
+        self.addLayerWidgets['database'][1].SetValue(
+            self.defaultConnect['database'])
         self.addLayerWidgets['table'][1].SetSelection(0)
         self.addLayerWidgets['key'][1].SetSelection(0)
         self.addLayerWidgets['addCat'][0].SetValue(True)
         # events
-        self.addLayerWidgets['driver'][1].Bind(wx.EVT_CHOICE, self.OnDriverChanged)
-        self.addLayerWidgets['database'][1].Bind(wx.EVT_TEXT_ENTER, self.OnDatabaseChanged)
-        self.addLayerWidgets['table'][1].Bind(wx.EVT_CHOICE, self.OnTableChanged)
-        
+        self.addLayerWidgets['driver'][1].Bind(
+            wx.EVT_CHOICE, self.OnDriverChanged)
+        self.addLayerWidgets['database'][1].Bind(
+            wx.EVT_TEXT_ENTER, self.OnDatabaseChanged)
+        self.addLayerWidgets['table'][1].Bind(
+            wx.EVT_CHOICE, self.OnTableChanged)
+
         # tooltips
-        self.addLayerWidgets['addCat'][0].SetToolTipString(_("You need to add categories "
-                                                             "by v.category module."))
+        self.addLayerWidgets['addCat'][0].SetToolTipString(
+            _("You need to add categories " "by v.category module."))
 
         # table description
-        tableBox = wx.StaticBox (parent = self.addPanel, id = wx.ID_ANY,
-                                 label = " %s " % (_("Table description")))
+        tableBox = wx.StaticBox(parent=self.addPanel, id=wx.ID_ANY,
+                                label=" %s " % (_("Table description")))
         tableSizer = wx.StaticBoxSizer(tableBox, wx.VERTICAL)
 
         #
         # list of table widgets
         #
-        keyCol = UserSettings.Get(group = 'atm', key = 'keycolumn', subkey = 'value')
-        self.tableWidgets = {'table': (wx.StaticText(parent = self.addPanel, id = wx.ID_ANY,
-                                                     label = '%s:' % _("Table name")),
-                                       wx.TextCtrl(parent = self.addPanel, id = wx.ID_ANY,
-                                                   value = '',
-                                                   style = wx.TE_PROCESS_ENTER)),
-                             'key': (wx.StaticText(parent = self.addPanel, id = wx.ID_ANY,
-                                                   label = '%s:' % _("Key column")),
-                                     wx.TextCtrl(parent = self.addPanel, id = wx.ID_ANY,
-                                                 value = keyCol,
-                                                 style = wx.TE_PROCESS_ENTER))}
+        keyCol = UserSettings.Get(group='atm', key='keycolumn', subkey='value')
+        self.tableWidgets = {'table': (wx.StaticText(parent=self.addPanel, id=wx.ID_ANY,
+                                                     label='%s:' % _("Table name")),
+                                       wx.TextCtrl(parent=self.addPanel, id=wx.ID_ANY,
+                                                   value='',
+                                                   style=wx.TE_PROCESS_ENTER)),
+                             'key': (wx.StaticText(parent=self.addPanel, id=wx.ID_ANY,
+                                                   label='%s:' % _("Key column")),
+                                     wx.TextCtrl(parent=self.addPanel, id=wx.ID_ANY,
+                                                 value=keyCol,
+                                                 style=wx.TE_PROCESS_ENTER))}
         # events
-        self.tableWidgets['table'][1].Bind(wx.EVT_TEXT_ENTER, self.OnCreateTable)
+        self.tableWidgets['table'][1].Bind(
+            wx.EVT_TEXT_ENTER, self.OnCreateTable)
         self.tableWidgets['key'][1].Bind(wx.EVT_TEXT_ENTER, self.OnCreateTable)
-        
-        btnTable   = wx.Button(self.addPanel, wx.ID_ANY, _("&Create table"),
-                             size = (125,-1))
+
+        btnTable = wx.Button(self.addPanel, wx.ID_ANY, _("&Create table"),
+                             size=(125, -1))
         btnTable.Bind(wx.EVT_BUTTON, self.OnCreateTable)
-        
-        btnLayer   = wx.Button(self.addPanel, wx.ID_ANY, _("&Add layer"),
-                             size = (125,-1))
+
+        btnLayer = wx.Button(self.addPanel, wx.ID_ANY, _("&Add layer"),
+                             size=(125, -1))
         btnLayer.Bind(wx.EVT_BUTTON, self.OnAddLayer)
-        
+
         btnDefault = wx.Button(self.addPanel, wx.ID_ANY, _("&Set default"),
-                               size = (125,-1))
+                               size=(125, -1))
         btnDefault.Bind(wx.EVT_BUTTON, self.OnSetDefault)
-        
+
         # do layout
-        
+
         pageSizer = wx.BoxSizer(wx.HORIZONTAL)
-                
+
         # data area
-        dataSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
+        dataSizer = wx.GridBagSizer(hgap=5, vgap=5)
         row = 0
         for key in ('layer', 'driver', 'database', 'table', 'key', 'addCat'):
             label, value = self.addLayerWidgets[key]
@@ -2848,10 +3154,10 @@
                 span = (1, 2)
             else:
                 span = (1, 1)
-            dataSizer.Add(item = label,
-                          flag = wx.ALIGN_CENTER_VERTICAL, pos = (row, 0),
-                          span = span)
-            
+            dataSizer.Add(item=label,
+                          flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0),
+                          span=span)
+
             if not value:
                 row += 1
                 continue
@@ -2860,69 +3166,69 @@
                 style = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT
             else:
                 style = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND
-            
-            dataSizer.Add(item = value,
-                          flag = style, pos = (row, 1))
-            
+
+            dataSizer.Add(item=value,
+                          flag=style, pos=(row, 1))
+
             row += 1
-        
+
         dataSizer.AddGrowableCol(1)
-        layerSizer.Add(item = dataSizer,
-                       proportion = 1,
-                       flag = wx.ALL | wx.EXPAND,
-                       border = 5)
-        
+        layerSizer.Add(item=dataSizer,
+                       proportion=1,
+                       flag=wx.ALL | wx.EXPAND,
+                       border=5)
+
         btnSizer = wx.BoxSizer(wx.HORIZONTAL)
-        btnSizer.Add(item = btnDefault,
-                     proportion = 0,
-                     flag = wx.ALL | wx.ALIGN_LEFT,
-                     border = 5)
-        
-        btnSizer.Add(item = (5, 5),
-                     proportion = 1,
-                     flag = wx.ALL | wx.EXPAND,
-                     border = 5)
-        
-        btnSizer.Add(item = btnLayer,
-                     proportion = 0,
-                     flag = wx.ALL | wx.ALIGN_RIGHT,
-                     border = 5)
-        
-        layerSizer.Add(item = btnSizer,
-                       proportion = 0,
-                       flag = wx.ALL | wx.EXPAND,
-                       border = 0)
-                
+        btnSizer.Add(item=btnDefault,
+                     proportion=0,
+                     flag=wx.ALL | wx.ALIGN_LEFT,
+                     border=5)
+
+        btnSizer.Add(item=(5, 5),
+                     proportion=1,
+                     flag=wx.ALL | wx.EXPAND,
+                     border=5)
+
+        btnSizer.Add(item=btnLayer,
+                     proportion=0,
+                     flag=wx.ALL | wx.ALIGN_RIGHT,
+                     border=5)
+
+        layerSizer.Add(item=btnSizer,
+                       proportion=0,
+                       flag=wx.ALL | wx.EXPAND,
+                       border=0)
+
         # data area
-        dataSizer = wx.FlexGridSizer(cols = 2, hgap = 5, vgap = 5)
+        dataSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
         dataSizer.AddGrowableCol(1)
         for key in ['table', 'key']:
             label, value = self.tableWidgets[key]
-            dataSizer.Add(item = label,
-                          flag = wx.ALIGN_CENTER_VERTICAL)
-            dataSizer.Add(item = value,
-                          flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
+            dataSizer.Add(item=label,
+                          flag=wx.ALIGN_CENTER_VERTICAL)
+            dataSizer.Add(item=value,
+                          flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
 
-        tableSizer.Add(item = dataSizer,
-                       proportion = 1,
-                       flag = wx.ALL | wx.EXPAND,
-                       border = 5)
+        tableSizer.Add(item=dataSizer,
+                       proportion=1,
+                       flag=wx.ALL | wx.EXPAND,
+                       border=5)
 
-        tableSizer.Add(item = btnTable,
-                       proportion = 0,
-                       flag = wx.ALL | wx.ALIGN_BOTTOM | wx.ALIGN_RIGHT,
-                       border = 5)
+        tableSizer.Add(item=btnTable,
+                       proportion=0,
+                       flag=wx.ALL | wx.ALIGN_BOTTOM | wx.ALIGN_RIGHT,
+                       border=5)
 
-        pageSizer.Add(item = layerSizer,
-                      proportion = 3,
-                      flag = wx.ALL | wx.EXPAND,
-                      border = 3)
-        
-        pageSizer.Add(item = tableSizer,
-                      proportion = 2,
-                      flag = wx.TOP | wx.BOTTOM | wx.RIGHT | wx.EXPAND,
-                      border = 3)
+        pageSizer.Add(item=layerSizer,
+                      proportion=3,
+                      flag=wx.ALL | wx.EXPAND,
+                      border=3)
 
+        pageSizer.Add(item=tableSizer,
+                      proportion=2,
+                      flag=wx.TOP | wx.BOTTOM | wx.RIGHT | wx.EXPAND,
+                      border=3)
+
         # SetVirtualSizeHints is deprecated and is
         # exactly the same as FitInside() in wxWidgets 2.9 and later
         getattr(layerSizer, 'FitInside',
@@ -2931,36 +3237,41 @@
         self.addPanel.SetAutoLayout(True)
         self.addPanel.SetSizer(pageSizer)
         pageSizer.Fit(self.addPanel)
-        
+
     def _createDeletePage(self):
         """Delete layer"""
-        self.deletePanel = wx.Panel(parent = self, id = wx.ID_ANY)
-        self.AddPage(page = self.deletePanel, text = _("Remove layer"))
+        self.deletePanel = wx.Panel(parent=self, id=wx.ID_ANY)
+        self.AddPage(page=self.deletePanel, text=_("Remove layer"))
 
-        label = wx.StaticText(parent = self.deletePanel, id = wx.ID_ANY,
-                              label = '%s:' % _("Layer to remove"))
+        label = wx.StaticText(parent=self.deletePanel, id=wx.ID_ANY,
+                              label='%s:' % _("Layer to remove"))
 
-        self.deleteLayer = wx.ComboBox(parent = self.deletePanel, id = wx.ID_ANY, size = (100, -1),
-                                       style = wx.CB_SIMPLE | wx.CB_READONLY,
-                                       choices = map(str, self.mapDBInfo.layers.keys()))
-        self.deleteLayer.SetSelection(0)           
+        self.deleteLayer = wx.ComboBox(
+            parent=self.deletePanel, id=wx.ID_ANY, size=(100, -1),
+            style=wx.CB_SIMPLE | wx.CB_READONLY,
+            choices=map(str, self.mapDBInfo.layers.keys()))
+        self.deleteLayer.SetSelection(0)
         self.deleteLayer.Bind(wx.EVT_COMBOBOX, self.OnChangeLayer)
 
         try:
-            tableName = self.mapDBInfo.layers[int(self.deleteLayer.GetStringSelection())]['table']
+            tableName = self.mapDBInfo.layers[
+                int(self.deleteLayer.GetStringSelection())]['table']
         except ValueError:
             tableName = ''
-            
-        self.deleteTable = wx.CheckBox(parent = self.deletePanel, id = wx.ID_ANY,
-                                       label = _('Drop also linked attribute table (%s)') % \
-                                       tableName)
 
+        self.deleteTable = wx.CheckBox(
+            parent=self.deletePanel,
+            id=wx.ID_ANY,
+            label=_('Drop also linked attribute table (%s)') %
+            tableName)
+
         if tableName == '':
             self.deleteLayer.Enable(False)
             self.deleteTable.Enable(False)
-            
-        btnDelete   = wx.Button(self.deletePanel, wx.ID_DELETE, _("&Remove layer"),
-                                size = (125,-1))
+
+        btnDelete = wx.Button(
+            self.deletePanel, wx.ID_DELETE, _("&Remove layer"),
+            size=(125, -1))
         btnDelete.Bind(wx.EVT_BUTTON, self.OnDeleteLayer)
 
         #
@@ -2970,89 +3281,90 @@
 
         dataSizer = wx.BoxSizer(wx.VERTICAL)
 
-        flexSizer = wx.FlexGridSizer(cols = 2, hgap = 5, vgap = 5)
+        flexSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
 
-        flexSizer.Add(item = label,
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        flexSizer.Add(item = self.deleteLayer,
-                      flag = wx.ALIGN_CENTER_VERTICAL)
+        flexSizer.Add(item=label,
+                      flag=wx.ALIGN_CENTER_VERTICAL)
+        flexSizer.Add(item=self.deleteLayer,
+                      flag=wx.ALIGN_CENTER_VERTICAL)
 
-        dataSizer.Add(item = flexSizer,
-                      proportion = 0,
-                      flag = wx.ALL | wx.EXPAND,
-                      border = 1)
+        dataSizer.Add(item=flexSizer,
+                      proportion=0,
+                      flag=wx.ALL | wx.EXPAND,
+                      border=1)
 
-        dataSizer.Add(item = self.deleteTable,
-                      proportion = 0,
-                      flag = wx.ALL | wx.EXPAND,
-                      border = 1)
+        dataSizer.Add(item=self.deleteTable,
+                      proportion=0,
+                      flag=wx.ALL | wx.EXPAND,
+                      border=1)
 
-        pageSizer.Add(item = dataSizer,
-                      proportion = 1,
-                      flag = wx.ALL | wx.EXPAND,
-                      border = 5)
+        pageSizer.Add(item=dataSizer,
+                      proportion=1,
+                      flag=wx.ALL | wx.EXPAND,
+                      border=5)
 
-        pageSizer.Add(item = btnDelete,
-                      proportion = 0,
-                      flag = wx.ALL | wx.ALIGN_RIGHT,
-                      border = 5)
+        pageSizer.Add(item=btnDelete,
+                      proportion=0,
+                      flag=wx.ALL | wx.ALIGN_RIGHT,
+                      border=5)
 
         self.deletePanel.SetSizer(pageSizer)
 
     def _createModifyPage(self):
         """Modify layer"""
-        self.modifyPanel = wx.Panel(parent = self, id = wx.ID_ANY)
-        self.AddPage(page = self.modifyPanel, text = _("Modify layer"))
+        self.modifyPanel = wx.Panel(parent=self, id=wx.ID_ANY)
+        self.AddPage(page=self.modifyPanel, text=_("Modify layer"))
 
         #
         # list of layer widgets (label, value)
         #
         self.modifyLayerWidgets = {'layer':
-                                       (wx.StaticText(parent = self.modifyPanel, id = wx.ID_ANY,
-                                                      label = '%s:' % _("Layer")),
-                                        wx.ComboBox(parent = self.modifyPanel, id = wx.ID_ANY,
-                                                    size = (100, -1),
-                                                    style = wx.CB_SIMPLE | wx.CB_READONLY,
-                                                    choices = map(str, 
-                                                                self.mapDBInfo.layers.keys()))),
+                                   (wx.StaticText(parent=self.modifyPanel, id=wx.ID_ANY,
+                                                  label='%s:' % _("Layer")),
+                                    wx.ComboBox(parent=self.modifyPanel, id=wx.ID_ANY,
+                                                size=(100, -1),
+                                                style=wx.CB_SIMPLE | wx.CB_READONLY,
+                                                choices=map(str,
+                                                            self.mapDBInfo.layers.keys()))),
                                    'driver':
-                                       (wx.StaticText(parent = self.modifyPanel, id = wx.ID_ANY,
-                                                      label = '%s:' % _("Driver")),
-                                        wx.Choice(parent = self.modifyPanel, id = wx.ID_ANY,
-                                                  size = (200, -1),
-                                                  choices = self.listOfDrivers)),
+                                       (wx.StaticText(parent=self.modifyPanel, id=wx.ID_ANY,
+                                                      label='%s:' % _("Driver")),
+                                        wx.Choice(parent=self.modifyPanel, id=wx.ID_ANY,
+                                                  size=(200, -1),
+                                                  choices=self.listOfDrivers)),
                                    'database':
-                                       (wx.StaticText(parent = self.modifyPanel, id = wx.ID_ANY,
-                                                      label = '%s:' % _("Database")),
-                                        wx.TextCtrl(parent = self.modifyPanel, id = wx.ID_ANY,
-                                                    value = '', size = (350, -1),
-                                                    style = wx.TE_PROCESS_ENTER)),
+                                       (wx.StaticText(parent=self.modifyPanel, id=wx.ID_ANY,
+                                                      label='%s:' % _("Database")),
+                                        wx.TextCtrl(parent=self.modifyPanel, id=wx.ID_ANY,
+                                                    value='', size=(350, -1),
+                                                    style=wx.TE_PROCESS_ENTER)),
                                    'table':
-                                       (wx.StaticText(parent = self.modifyPanel, id = wx.ID_ANY,
-                                                      label = '%s:' % _("Table")),
-                                        wx.Choice(parent = self.modifyPanel, id = wx.ID_ANY,
-                                                  size = (200, -1),
-                                                  choices = self.defaultTables)),
+                                       (wx.StaticText(parent=self.modifyPanel, id=wx.ID_ANY,
+                                                      label='%s:' % _("Table")),
+                                        wx.Choice(parent=self.modifyPanel, id=wx.ID_ANY,
+                                                  size=(200, -1),
+                                                  choices=self.defaultTables)),
                                    'key':
-                                       (wx.StaticText(parent = self.modifyPanel, id = wx.ID_ANY,
-                                                      label = '%s:' % _("Key column")),
-                                        wx.Choice(parent = self.modifyPanel, id = wx.ID_ANY,
-                                                  size = (200, -1),
-                                                  choices = self.defaultColumns))}
-        
+                                       (wx.StaticText(parent=self.modifyPanel, id=wx.ID_ANY,
+                                                      label='%s:' % _("Key column")),
+                                        wx.Choice(parent=self.modifyPanel, id=wx.ID_ANY,
+                                                  size=(200, -1),
+                                                  choices=self.defaultColumns))}
+
         # set default values for widgets
         self.modifyLayerWidgets['layer'][1].SetSelection(0)
         try:
-            layer = int(self.modifyLayerWidgets['layer'][1].GetStringSelection())
+            layer = int(self.modifyLayerWidgets[
+                        'layer'][1].GetStringSelection())
         except ValueError:
             layer = None
             for label in self.modifyLayerWidgets.keys():
                 self.modifyLayerWidgets[label][1].Enable(False)
 
         if layer:
-            driver   = self.mapDBInfo.layers[layer]['driver']
+            driver = self.mapDBInfo.layers[layer]['driver']
             database = self.mapDBInfo.layers[layer]['database']
-            table    = self.mapDBInfo.layers[layer]['table']
+            table = self.mapDBInfo.layers[layer]['table']
 
             listOfColumns = self._getColumns(driver, database, table)
             self.modifyLayerWidgets['driver'][1].SetStringSelection(driver)
@@ -3061,21 +3373,24 @@
                 self.modifyLayerWidgets['table'][1].SetStringSelection(table)
             else:
                 if self.defaultConnect['schema'] != '':
-                    table = self.defaultConnect['schema'] + table # try with default schema
+                    # try with default schema
+                    table = self.defaultConnect['schema'] + table
                 else:
-                    table = 'public.' + table # try with 'public' schema
+                    table = 'public.' + table  # try with 'public' schema
                 self.modifyLayerWidgets['table'][1].SetStringSelection(table)
             self.modifyLayerWidgets['key'][1].SetItems(listOfColumns)
             self.modifyLayerWidgets['key'][1].SetSelection(0)
 
         # events
-        self.modifyLayerWidgets['layer'][1].Bind(wx.EVT_COMBOBOX, self.OnChangeLayer)
+        self.modifyLayerWidgets['layer'][1].Bind(
+            wx.EVT_COMBOBOX, self.OnChangeLayer)
         # self.modifyLayerWidgets['driver'][1].Bind(wx.EVT_CHOICE, self.OnDriverChanged)
         # self.modifyLayerWidgets['database'][1].Bind(wx.EVT_TEXT_ENTER, self.OnDatabaseChanged)
         # self.modifyLayerWidgets['table'][1].Bind(wx.EVT_CHOICE, self.OnTableChanged)
 
-        btnModify = wx.Button(self.modifyPanel, wx.ID_DELETE, _("&Modify layer"),
-                              size = (125,-1))
+        btnModify = wx.Button(
+            self.modifyPanel, wx.ID_DELETE, _("&Modify layer"),
+            size=(125, -1))
         btnModify.Bind(wx.EVT_BUTTON, self.OnModifyLayer)
 
         #
@@ -3084,28 +3399,28 @@
         pageSizer = wx.BoxSizer(wx.VERTICAL)
 
         # data area
-        dataSizer = wx.FlexGridSizer(cols = 2, hgap = 5, vgap = 5)
+        dataSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
         dataSizer.AddGrowableCol(1)
         for key in ('layer', 'driver', 'database', 'table', 'key'):
             label, value = self.modifyLayerWidgets[key]
-            dataSizer.Add(item = label,
-                          flag = wx.ALIGN_CENTER_VERTICAL)
+            dataSizer.Add(item=label,
+                          flag=wx.ALIGN_CENTER_VERTICAL)
             if key == 'layer':
-                dataSizer.Add(item = value,
-                              flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
+                dataSizer.Add(item=value,
+                              flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
             else:
-                dataSizer.Add(item = value,
-                              flag = wx.ALIGN_CENTER_VERTICAL)
+                dataSizer.Add(item=value,
+                              flag=wx.ALIGN_CENTER_VERTICAL)
 
-        pageSizer.Add(item = dataSizer,
-                      proportion = 1,
-                      flag = wx.ALL | wx.EXPAND,
-                      border = 5)
+        pageSizer.Add(item=dataSizer,
+                      proportion=1,
+                      flag=wx.ALL | wx.EXPAND,
+                      border=5)
 
-        pageSizer.Add(item = btnModify,
-                      proportion = 0,
-                      flag = wx.ALL | wx.ALIGN_RIGHT,
-                      border = 5)
+        pageSizer.Add(item=btnModify,
+                      proportion=0,
+                      flag=wx.ALL | wx.ALIGN_RIGHT,
+                      border=5)
 
         self.modifyPanel.SetSizer(pageSizer)
 
@@ -3114,22 +3429,23 @@
         tables = []
 
         ret = RunCommand('db.tables',
-                         parent = self,
-                         read = True,
-                         flags = 'p',
-                         driver = driver,
-                         database = database)
-        
+                         parent=self,
+                         read=True,
+                         flags='p',
+                         driver=driver,
+                         database=database)
+
         if ret is None:
-            GError(parent = self,
-                   message = _("Unable to get list of tables.\n"
-                               "Please use db.connect to set database parameters."))
-            
+            GError(
+                parent=self, message=_(
+                    "Unable to get list of tables.\n"
+                    "Please use db.connect to set database parameters."))
+
             return tables
-        
+
         for table in ret.splitlines():
             tables.append(table)
-        
+
         return tables
 
     def _getColumns(self, driver, database, table):
@@ -3137,19 +3453,19 @@
         columns = []
 
         ret = RunCommand('db.columns',
-                         parent = self,
-                         quiet = True,
-                         read = True,
-                         driver = driver,
-                         database = database,
-                         table = table)
-        
-        if ret == None:
+                         parent=self,
+                         quiet=True,
+                         read=True,
+                         driver=driver,
+                         database=database,
+                         table=table)
+
+        if ret is None:
             return columns
-        
+
         for column in ret.splitlines():
             columns.append(column)
-        
+
         return columns
 
     def OnDriverChanged(self, event):
@@ -3158,8 +3474,8 @@
         database = self.addLayerWidgets['database'][1].GetValue()
 
         winTable = self.addLayerWidgets['table'][1]
-        winKey   = self.addLayerWidgets['key'][1]
-        tables   = self._getTables(driver, database)
+        winKey = self.addLayerWidgets['key'][1]
+        tables = self._getTables(driver, database)
 
         winTable.SetItems(tables)
         winTable.SetSelection(0)
@@ -3175,11 +3491,11 @@
 
     def OnTableChanged(self, event):
         """Table name changed, update list of columns"""
-        driver   = self.addLayerWidgets['driver'][1].GetStringSelection()
+        driver = self.addLayerWidgets['driver'][1].GetStringSelection()
         database = self.addLayerWidgets['database'][1].GetValue()
-        table    = event.GetString()
+        table = event.GetString()
 
-        win  = self.addLayerWidgets['key'][1]
+        win = self.addLayerWidgets['key'][1]
         cols = self._getColumns(driver, database, table)
         win.SetItems(cols)
         win.SetSelection(0)
@@ -3188,23 +3504,23 @@
 
     def OnSetDefault(self, event):
         """Set default values"""
-        driver   = self.addLayerWidgets['driver'][1]
+        driver = self.addLayerWidgets['driver'][1]
         database = self.addLayerWidgets['database'][1]
-        table    = self.addLayerWidgets['table'][1]
-        key      = self.addLayerWidgets['key'][1]
+        table = self.addLayerWidgets['table'][1]
+        key = self.addLayerWidgets['key'][1]
 
         driver.SetStringSelection(self.defaultConnect['driver'])
         database.SetValue(self.defaultConnect['database'])
         tables = self._getTables(self.defaultConnect['driver'],
-                                  self.defaultConnect['database'])
+                                 self.defaultConnect['database'])
         table.SetItems(tables)
         table.SetSelection(0)
         if len(tables) == 0:
             key.SetItems([])
         else:
             cols = self._getColumns(self.defaultConnect['driver'],
-                                     self.defaultConnect['database'],
-                                     tables[0])
+                                    self.defaultConnect['database'],
+                                    tables[0])
             key.SetItems(cols)
             key.SetSelection(0)
 
@@ -3212,34 +3528,36 @@
 
     def OnCreateTable(self, event):
         """Create new table (name and key column given)"""
-        driver   = self.addLayerWidgets['driver'][1].GetStringSelection()
+        driver = self.addLayerWidgets['driver'][1].GetStringSelection()
         database = self.addLayerWidgets['database'][1].GetValue()
-        table    = self.tableWidgets['table'][1].GetValue()
-        key      = self.tableWidgets['key'][1].GetValue()
-        
+        table = self.tableWidgets['table'][1].GetValue()
+        key = self.tableWidgets['key'][1].GetValue()
+
         if not table or not key:
-            GError(parent = self,
-                   message = _("Unable to create new table. "
-                               "Table name or key column name is missing."))
+            GError(parent=self,
+                   message=_("Unable to create new table. "
+                             "Table name or key column name is missing."))
             return
 
         if table in self.addLayerWidgets['table'][1].GetItems():
-            GError(parent = self,
-                   message = _("Unable to create new table. "
-                               "Table <%s> already exists in the database.") % table)
+            GError(
+                parent=self, message=_(
+                    "Unable to create new table. "
+                    "Table <%s> already exists in the database.") %
+                table)
             return
-        
+
         # create table
         sql = 'CREATE TABLE %s (%s INTEGER)' % (table, key)
 
         RunCommand('db.execute',
-                   quiet = True,
-                   parent = self,
-                   stdin = sql,
-                   input = '-',
-                   driver = driver,
-                   database = database)
-        
+                   quiet=True,
+                   parent=self,
+                   stdin=sql,
+                   input='-',
+                   driver=driver,
+                   database=database)
+
         # update list of tables
         tableList = self.addLayerWidgets['table'][1]
         tableList.SetItems(self._getTables(driver, database))
@@ -3249,54 +3567,56 @@
         keyList = self.addLayerWidgets['key'][1]
         keyList.SetItems(self._getColumns(driver, database, table))
         keyList.SetStringSelection(key)
-        
+
         event.Skip()
 
     def OnAddLayer(self, event):
         """Add new layer to vector map"""
-        layer    = int(self.addLayerWidgets['layer'][1].GetValue())
+        layer = int(self.addLayerWidgets['layer'][1].GetValue())
         layerWin = self.addLayerWidgets['layer'][1]
-        driver   = self.addLayerWidgets['driver'][1].GetStringSelection()
+        driver = self.addLayerWidgets['driver'][1].GetStringSelection()
         database = self.addLayerWidgets['database'][1].GetValue()
-        table    = self.addLayerWidgets['table'][1].GetStringSelection()
-        key      = self.addLayerWidgets['key'][1].GetStringSelection()
-        
+        table = self.addLayerWidgets['table'][1].GetStringSelection()
+        key = self.addLayerWidgets['key'][1].GetStringSelection()
+
         if layer in self.mapDBInfo.layers.keys():
-            GError(parent = self,
-                   message = _("Unable to add new layer to vector map <%(vector)s>. "
-                               "Layer %(layer)d already exists.") % \
-                       {'vector' : self.mapDBInfo.map, 'layer' : layer})
+            GError(
+                parent=self,
+                message=_(
+                    "Unable to add new layer to vector map <%(vector)s>. "
+                    "Layer %(layer)d already exists.") %
+                {'vector': self.mapDBInfo.map, 'layer': layer})
             return
 
         # add new layer
         ret = RunCommand('v.db.connect',
-                         parent = self,
-                         quiet = True,
-                         map = self.mapDBInfo.map,
-                         driver = driver,
-                         database = database,
-                         table = table,
-                         key = key,
-                         layer = layer)
-        
+                         parent=self,
+                         quiet=True,
+                         map=self.mapDBInfo.map,
+                         driver=driver,
+                         database=database,
+                         table=table,
+                         key=key,
+                         layer=layer)
+
         # insert records into table if required
         if self.addLayerWidgets['addCat'][0].IsChecked():
             RunCommand('v.to.db',
-                       parent = self,
-                       quiet = True,
-                       map = self.mapDBInfo.map,
-                       layer = layer,
-                       qlayer = layer,
-                       option = 'cat',
-                       columns = key)
+                       parent=self,
+                       quiet=True,
+                       map=self.mapDBInfo.map,
+                       layer=layer,
+                       qlayer=layer,
+                       option='cat',
+                       columns=key)
 
         if ret == 0:
             # update dialog (only for new layer)
-            self.parentDialog.parentDbMgrBase.UpdateDialog(layer = layer) 
+            self.parentDialog.parentDbMgrBase.UpdateDialog(layer=layer)
             # update db info
             self.mapDBInfo = self.parentDialog.dbMgrData['mapDBInfo']
             # increase layer number
-            layerWin.SetValue(layer+1)
+            layerWin.SetValue(layer + 1)
 
         if len(self.mapDBInfo.layers.keys()) == 1:
             # first layer add --- enable previously disabled widgets
@@ -3304,7 +3624,7 @@
             self.deleteTable.Enable()
             for label in self.modifyLayerWidgets.keys():
                 self.modifyLayerWidgets[label][1].Enable()
-            
+
     def OnDeleteLayer(self, event):
         """Delete layer"""
         try:
@@ -3313,17 +3633,17 @@
             return
 
         RunCommand('v.db.connect',
-                   parent = self,
-                   flags = 'd',
-                   map = self.mapDBInfo.map,
-                   layer = layer)
+                   parent=self,
+                   flags='d',
+                   map=self.mapDBInfo.map,
+                   layer=layer)
 
         # drop also table linked to layer which is deleted
         if self.deleteTable.IsChecked():
-            driver   = self.addLayerWidgets['driver'][1].GetStringSelection()
+            driver = self.addLayerWidgets['driver'][1].GetStringSelection()
             database = self.addLayerWidgets['database'][1].GetValue()
-            table    = self.mapDBInfo.layers[layer]['table']
-            sql      = 'DROP TABLE %s' % (table)
+            table = self.mapDBInfo.layers[layer]['table']
+            sql = 'DROP TABLE %s' % (table)
 
             RunCommand('db.execute',
                        input='-',
@@ -3332,14 +3652,14 @@
                        quiet=True,
                        driver=driver,
                        database=database)
-            
+
             # update list of tables
             tableList = self.addLayerWidgets['table'][1]
             tableList.SetItems(self._getTables(driver, database))
             tableList.SetStringSelection(table)
-        
+
         # update dialog
-        self.parentDialog.parentDbMgrBase.UpdateDialog(layer = layer) 
+        self.parentDialog.parentDbMgrBase.UpdateDialog(layer=layer)
         # update db info
         self.mapDBInfo = self.parentDialog.dbMgrData['mapDBInfo']
 
@@ -3349,7 +3669,7 @@
             self.deleteTable.Enable(False)
             for label in self.modifyLayerWidgets.keys():
                 self.modifyLayerWidgets[label][1].Enable(False)
-            
+
         event.Skip()
 
     def OnChangeLayer(self, event):
@@ -3363,9 +3683,9 @@
                 return
 
         if self.GetCurrentPage() == self.modifyPanel:
-            driver   = self.mapDBInfo.layers[layer]['driver']
+            driver = self.mapDBInfo.layers[layer]['driver']
             database = self.mapDBInfo.layers[layer]['database']
-            table    = self.mapDBInfo.layers[layer]['table']
+            table = self.mapDBInfo.layers[layer]['table']
             listOfColumns = self._getColumns(driver, database, table)
             self.modifyLayerWidgets['driver'][1].SetStringSelection(driver)
             self.modifyLayerWidgets['database'][1].SetValue(database)
@@ -3373,8 +3693,9 @@
             self.modifyLayerWidgets['key'][1].SetItems(listOfColumns)
             self.modifyLayerWidgets['key'][1].SetSelection(0)
         else:
-            self.deleteTable.SetLabel(_('Drop also linked attribute table (%s)') % \
-                                          self.mapDBInfo.layers[layer]['table'])
+            self.deleteTable.SetLabel(
+                _('Drop also linked attribute table (%s)') %
+                self.mapDBInfo.layers[layer]['table'])
         if event:
             event.Skip()
 
@@ -3397,57 +3718,69 @@
         if modify:
             # delete layer
             RunCommand('v.db.connect',
-                       parent = self,
-                       quiet = True,
-                       flags = 'd',
-                       map = self.mapDBInfo.map,
-                       layer = layer)
+                       parent=self,
+                       quiet=True,
+                       flags='d',
+                       map=self.mapDBInfo.map,
+                       layer=layer)
 
             # add modified layer
-            RunCommand('v.db.connect',
-                       quiet = True,
-                       map = self.mapDBInfo.map,
-                       driver = self.modifyLayerWidgets['driver'][1].GetStringSelection(),
-                       database = self.modifyLayerWidgets['database'][1].GetValue(),
-                       table = self.modifyLayerWidgets['table'][1].GetStringSelection(),
-                       key = self.modifyLayerWidgets['key'][1].GetStringSelection(),
-                       layer = int(layer))
-            
+            RunCommand(
+                'v.db.connect',
+                quiet=True,
+                map=self.mapDBInfo.map,
+                driver=self.modifyLayerWidgets['driver'][1].GetStringSelection(),
+                database=self.modifyLayerWidgets['database'][1].GetValue(),
+                table=self.modifyLayerWidgets['table'][1].GetStringSelection(),
+                key=self.modifyLayerWidgets['key'][1].GetStringSelection(),
+                layer=int(layer))
+
             # update dialog (only for new layer)
-            self.parentDialog.parentDbMgrBase.UpdateDialog(layer = layer) 
+            self.parentDialog.parentDbMgrBase.UpdateDialog(layer=layer)
             # update db info
             self.mapDBInfo = self.parentDialog.dbMgrData['mapDBInfo']
 
         event.Skip()
 
+
 class FieldStatistics(wx.Frame):
+
     def __init__(self, parent, id=wx.ID_ANY,
-                 style = wx.DEFAULT_FRAME_STYLE, **kwargs):
+                 style=wx.DEFAULT_FRAME_STYLE, **kwargs):
         """Dialog to display and save statistics of field stats
         """
         self.parent = parent
-        wx.Frame.__init__(self, parent, id, style = style, **kwargs)
-        
+        wx.Frame.__init__(self, parent, id, style=style, **kwargs)
+
         self.SetTitle(_("Field statistics"))
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass_sql.ico'), wx.BITMAP_TYPE_ICO))
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass_sql.ico'),
+                wx.BITMAP_TYPE_ICO))
 
-        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
-        
-        self.sp = scrolled.ScrolledPanel(parent=self.panel, id=wx.ID_ANY, size=(250, 150),
-                                         style = wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER, name="Statistics" )
-        self.text = wx.TextCtrl(parent=self.sp, id=wx.ID_ANY, style=wx.TE_MULTILINE|wx.TE_READONLY)
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
+        self.sp = scrolled.ScrolledPanel(parent=self.panel, id=wx.ID_ANY, size=(
+            250, 150), style=wx.TAB_TRAVERSAL | wx.SUNKEN_BORDER, name="Statistics")
+        self.text = wx.TextCtrl(
+            parent=self.sp,
+            id=wx.ID_ANY,
+            style=wx.TE_MULTILINE | wx.TE_READONLY)
         self.text.SetBackgroundColour("white")
-                
+
         # buttons
-        self.btnClipboard = wx.Button(parent=self.panel, id = wx.ID_COPY)
-        self.btnClipboard.SetToolTipString(_("Copy statistics the clipboard (Ctrl+C)"))
+        self.btnClipboard = wx.Button(parent=self.panel, id=wx.ID_COPY)
+        self.btnClipboard.SetToolTipString(
+            _("Copy statistics the clipboard (Ctrl+C)"))
         self.btnCancel = wx.Button(parent=self.panel, id=wx.ID_CLOSE)
         self.btnCancel.SetDefault()
 
         # bindings
         self.btnCancel.Bind(wx.EVT_BUTTON, self.OnClose)
         self.btnClipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
-        
+
         self._layout()
 
     def _layout(self):
@@ -3455,27 +3788,31 @@
         txtSizer = wx.BoxSizer(wx.VERTICAL)
         btnSizer = wx.BoxSizer(wx.HORIZONTAL)
 
-        txtSizer.Add(item = self.text, proportion = 1, 
-                     flag = wx.EXPAND|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
-        
+        txtSizer.Add(item=self.text, proportion=1, flag=wx.EXPAND |
+                     wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
+
         self.sp.SetSizer(txtSizer)
         self.sp.SetAutoLayout(True)
-        self.sp.SetupScrolling() 
+        self.sp.SetupScrolling()
 
-        sizer.Add(item = self.sp, proportion = 1, flag = wx.GROW |
-                  wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 3)
+        sizer.Add(item=self.sp, proportion=1, flag=wx.GROW |
+                  wx.LEFT | wx.RIGHT | wx.BOTTOM, border=3)
 
-        line = wx.StaticLine(parent = self.panel, id = wx.ID_ANY,
-                             size = (20, -1), style = wx.LI_HORIZONTAL)
-        sizer.Add(item = line, proportion = 0,
-                  flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, border = 3)
+        line = wx.StaticLine(parent=self.panel, id=wx.ID_ANY,
+                             size=(20, -1), style=wx.LI_HORIZONTAL)
+        sizer.Add(item=line, proportion=0, flag=wx.GROW |
+                  wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, border=3)
 
         # buttons
-        btnSizer.Add(item = self.btnClipboard, proportion = 0,
-                     flag = wx.ALIGN_LEFT | wx.ALL, border = 5)
-        btnSizer.Add(item = self.btnCancel, proportion = 0,
-                     flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)        
-        sizer.Add(item = btnSizer, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
+        btnSizer.Add(item=self.btnClipboard, proportion=0,
+                     flag=wx.ALIGN_LEFT | wx.ALL, border=5)
+        btnSizer.Add(item=self.btnCancel, proportion=0,
+                     flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
+        sizer.Add(
+            item=btnSizer,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT | wx.ALL,
+            border=5)
 
         self.panel.SetSizer(sizer)
         sizer.Fit(self.panel)
@@ -3486,7 +3823,7 @@
         stats = self.text.GetValue()
         rdata = wx.TextDataObject()
         rdata.SetText(stats)
-        
+
         if wx.TheClipboard.Open():
             wx.TheClipboard.SetData(rdata)
             wx.TheClipboard.Close()
@@ -3498,7 +3835,7 @@
 
     def Update(self, driver, database, table, column):
         """!Update statistics for given column
-        
+
         :param: column column name
         """
         if driver == 'dbf':
@@ -3506,57 +3843,64 @@
                    message=_("Statistics is not support for DBF tables."))
             self.Close()
             return
-        
+
         fd, sqlFilePath = tempfile.mkstemp(text=True)
         sqlFile = open(sqlFilePath, 'w')
         stats = ['count', 'min', 'max', 'avg', 'sum', 'null']
         for fn in stats:
             if fn == 'null':
-                sqlFile.write('select count(*) from %s where %s is null;%s' % (table, column, os.linesep))
+                sqlFile.write(
+                    'select count(*) from %s where %s is null;%s' %
+                    (table, column, os.linesep))
             else:
-                sqlFile.write('select %s(%s) from %s;%s' % (fn, column, table, os.linesep))
+                sqlFile.write(
+                    'select %s(%s) from %s;%s' %
+                    (fn, column, table, os.linesep))
         sqlFile.close()
-        
+
         dataStr = RunCommand('db.select',
-                             parent = self.parent,
-                             read = True,
+                             parent=self.parent,
+                             read=True,
                              flags='c',
-                             input = sqlFilePath,
-                             driver = driver,
-                             database = database)
+                             input=sqlFilePath,
+                             driver=driver,
+                             database=database)
         if not dataStr:
-            GError(parent = self.parent,
-                   message = _("Unable to calculte statistics."))
+            GError(parent=self.parent,
+                   message=_("Unable to calculte statistics."))
             self.Close()
             return
-        
+
         dataLines = dataStr.splitlines()
         if len(dataLines) != len(stats):
-            GError(parent = self.parent,
-                   message = _("Unable to calculte statistics. "
-                               "Invalid number of lines %d (should be %d).") % (len(dataLines), len(stats)))
+            GError(
+                parent=self.parent, message=_(
+                    "Unable to calculte statistics. "
+                    "Invalid number of lines %d (should be %d).") %
+                (len(dataLines), len(stats)))
             self.Close()
             return
-        
+
         # calculate stddev
         avg = float(dataLines[stats.index('avg')])
         count = float(dataLines[stats.index('count')])
-        sql = "select (%(column)s - %(avg)f)*(%(column)s - %(avg)f) from %(table)s" % { 'column' : column, 'avg' : avg, 'table' : table }
+        sql = "select (%(column)s - %(avg)f)*(%(column)s - %(avg)f) from %(table)s" % {
+            'column': column, 'avg': avg, 'table': table}
         dataVar = RunCommand('db.select',
-                             parent = self.parent,
-                             read = True,
+                             parent=self.parent,
+                             read=True,
                              flags='c',
-                             sql = sql,
-                             driver = driver,
-                             database = database)
+                             sql=sql,
+                             driver=driver,
+                             database=database)
         if not dataVar:
-            GWarning(parent = self.parent,
-                     message = _("Unable to calculte standard deviation."))
+            GWarning(parent=self.parent,
+                     message=_("Unable to calculte standard deviation."))
         varSum = 0
         for var in dataVar.splitlines():
             varSum += float(var)
-        stddev = math.sqrt(varSum/count)
-        
+        stddev = math.sqrt(varSum / count)
+
         self.SetTitle(_("Field statistics <%s>") % column)
         self.text.Clear()
         for idx in range(len(stats)):

Modified: grass/trunk/gui/wxpython/dbmgr/dialogs.py
===================================================================
--- grass/trunk/gui/wxpython/dbmgr/dialogs.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/dbmgr/dialogs.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -25,24 +25,26 @@
 import wx
 import wx.lib.scrolledpanel as scrolled
 
-from core.gcmd        import RunCommand, GError
-from core.debug       import Debug
-from core.settings    import UserSettings
-from dbmgr.vinfo      import VectorDBInfo, GetUnicodeValue
+from core.gcmd import RunCommand, GError
+from core.debug import Debug
+from core.settings import UserSettings
+from dbmgr.vinfo import VectorDBInfo, GetUnicodeValue
 from gui_core.widgets import IntegerValidator, FloatValidator
 
+
 class DisplayAttributesDialog(wx.Dialog):
+
     def __init__(self, parent, map,
-                 query = None, cats = None, line = None,
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
-                 pos = wx.DefaultPosition,
-                 action = "add", ignoreError = False):
+                 query=None, cats=None, line=None,
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
+                 pos=wx.DefaultPosition,
+                 action="add", ignoreError=False):
         """Standard dialog used to add/update/display attributes linked
         to the vector map.
-        
+
         Attribute data can be selected based on layer and category number
         or coordinates.
-        
+
         :param parent:
         :param map: vector map
         :param query: query coordinates and distance (used for v.edit)
@@ -53,63 +55,67 @@
         :param action: (add, update, display)
         :param ignoreError: True to ignore errors
         """
-        self.parent = parent # mapdisplay.BufferedWindow
-        self.map    = map
+        self.parent = parent  # mapdisplay.BufferedWindow
+        self.map = map
         self.action = action
 
         # ids/cats of selected features
         # fid : {layer : cats}
         self.cats = {}
-        self.fid = -1 # feature id
-        
+        self.fid = -1  # feature id
+
         # get layer/table/column information
         self.mapDBInfo = VectorDBInfo(self.map)
-        
-        layers = self.mapDBInfo.layers.keys() # get available layers
 
+        layers = self.mapDBInfo.layers.keys()  # get available layers
+
         # check if db connection / layer exists
         if len(layers) <= 0:
             if not ignoreError:
-                dlg = wx.MessageDialog(parent = self.parent,
-                                       message = _("No attribute table found.\n\n"
-                                                   "Do you want to create a new attribute table "
-                                                   "and defined a link to vector map <%s>?") % self.map,
-                                       caption = _("Create table?"),
-                                       style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
+                dlg = wx.MessageDialog(
+                    parent=self.parent,
+                    message=_(
+                        "No attribute table found.\n\n"
+                        "Do you want to create a new attribute table "
+                        "and defined a link to vector map <%s>?") %
+                    self.map,
+                    caption=_("Create table?"),
+                    style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
                 if dlg.ShowModal() == wx.ID_YES:
                     lmgr = self.parent.lmgr
-                    lmgr.OnShowAttributeTable(event = None, selection = 'layers')
-                
+                    lmgr.OnShowAttributeTable(event=None, selection='layers')
+
                 dlg.Destroy()
-            
+
             self.mapDBInfo = None
-        
-        wx.Dialog.__init__(self, parent = self.parent, id = wx.ID_ANY,
-                           title = "", style = style, pos = pos)
 
+        wx.Dialog.__init__(self, parent=self.parent, id=wx.ID_ANY,
+                           title="", style=style, pos=pos)
+
         # dialog body
         mainSizer = wx.BoxSizer(wx.VERTICAL)
 
         # notebook
-        self.notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
+        self.notebook = wx.Notebook(
+            parent=self, id=wx.ID_ANY, style=wx.BK_DEFAULT)
 
-        self.closeDialog = wx.CheckBox(parent = self, id = wx.ID_ANY,
-                                       label = _("Close dialog on submit"))
+        self.closeDialog = wx.CheckBox(parent=self, id=wx.ID_ANY,
+                                       label=_("Close dialog on submit"))
         self.closeDialog.SetValue(True)
         if self.action == 'display':
             self.closeDialog.Enable(False)
-        
+
         # feature id (text/choice for duplicates)
-        self.fidMulti = wx.Choice(parent = self, id = wx.ID_ANY,
-                                  size = (150, -1))
+        self.fidMulti = wx.Choice(parent=self, id=wx.ID_ANY,
+                                  size=(150, -1))
         self.fidMulti.Bind(wx.EVT_CHOICE, self.OnFeature)
-        self.fidText = wx.StaticText(parent = self, id = wx.ID_ANY)
+        self.fidText = wx.StaticText(parent=self, id=wx.ID_ANY)
 
-        self.noFoundMsg = wx.StaticText(parent = self, id = wx.ID_ANY,
-                                        label = _("No attributes found"))
-        
-        self.UpdateDialog(query = query, cats = cats)
+        self.noFoundMsg = wx.StaticText(parent=self, id=wx.ID_ANY,
+                                        label=_("No attributes found"))
 
+        self.UpdateDialog(query=query, cats=cats)
+
         # set title
         if self.action == "update":
             self.SetTitle(_("Update attributes"))
@@ -120,11 +126,11 @@
 
         # buttons
         btnCancel = wx.Button(self, wx.ID_CANCEL)
-        btnReset  = wx.Button(self, wx.ID_UNDO, _("&Reload"))
+        btnReset = wx.Button(self, wx.ID_UNDO, _("&Reload"))
         btnSubmit = wx.Button(self, wx.ID_OK, _("&Submit"))
         if self.action == 'display':
             btnSubmit.Enable(False)
-        
+
         btnSizer = wx.StdDialogButtonSizer()
         btnSizer.AddButton(btnCancel)
         btnSizer.AddButton(btnReset)
@@ -133,25 +139,28 @@
         btnSizer.AddButton(btnSubmit)
         btnSizer.Realize()
 
-        mainSizer.Add(item = self.noFoundMsg, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL, border = 5)
-        mainSizer.Add(item = self.notebook, proportion = 1,
-                      flag = wx.EXPAND | wx.ALL, border = 5)
+        mainSizer.Add(item=self.noFoundMsg, proportion=0,
+                      flag=wx.EXPAND | wx.ALL, border=5)
+        mainSizer.Add(item=self.notebook, proportion=1,
+                      flag=wx.EXPAND | wx.ALL, border=5)
         fidSizer = wx.BoxSizer(wx.HORIZONTAL)
-        fidSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
-                                        label = _("Feature id:")),
-                     proportion = 0, border = 5,
-                     flag = wx.ALIGN_CENTER_VERTICAL)
-        fidSizer.Add(item = self.fidMulti, proportion = 0,
-                     flag = wx.EXPAND | wx.ALL,  border = 5)
-        fidSizer.Add(item = self.fidText, proportion = 0,
-                     flag = wx.EXPAND | wx.ALL,  border = 5)
-        mainSizer.Add(item = fidSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
-        mainSizer.Add(item = self.closeDialog, proportion = 0, flag = wx.EXPAND | wx.LEFT | wx.RIGHT,
-                      border = 5)
-        mainSizer.Add(item = btnSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
+        fidSizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY,
+                                        label=_("Feature id:")),
+                     proportion=0, border=5,
+                     flag=wx.ALIGN_CENTER_VERTICAL)
+        fidSizer.Add(item=self.fidMulti, proportion=0,
+                     flag=wx.EXPAND | wx.ALL, border=5)
+        fidSizer.Add(item=self.fidText, proportion=0,
+                     flag=wx.EXPAND | wx.ALL, border=5)
+        mainSizer.Add(item=fidSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5)
+        mainSizer.Add(
+            item=self.closeDialog,
+            proportion=0,
+            flag=wx.EXPAND | wx.LEFT | wx.RIGHT,
+            border=5)
+        mainSizer.Add(item=btnSizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
 
         # bindigs
         btnReset.Bind(wx.EVT_BUTTON, self.OnReset)
@@ -169,11 +178,11 @@
             self.SetMinSize((w, 200))
         else:
             self.SetMinSize((w, h))
-        
+
         if self.notebook.GetPageCount() == 0:
             Debug.msg(2, "DisplayAttributesDialog(): Nothing found!")
             ### self.mapDBInfo = None
-        
+
     def OnSQLStatement(self, event):
         """Update SQL statement"""
         pass
@@ -185,36 +194,36 @@
         :return: False attributes not found
         """
         return bool(self.mapDBInfo and self.notebook.GetPageCount() > 0)
-    
-    def GetSQLString(self, updateValues = False):
+
+    def GetSQLString(self, updateValues=False):
         """Create SQL statement string based on self.sqlStatement
 
         Show error message when invalid values are entered.
-        
+
         If updateValues is True, update dataFrame according to values
         in textfields.
         """
         sqlCommands = []
         # find updated values for each layer/category
-        for layer in self.mapDBInfo.layers.keys(): # for each layer
+        for layer in self.mapDBInfo.layers.keys():  # for each layer
             table = self.mapDBInfo.GetTable(layer)
             key = self.mapDBInfo.GetKeyColumn(layer)
             columns = self.mapDBInfo.GetTableDesc(table)
-            for idx in range(len(columns[key]['values'])): # for each category
+            for idx in range(len(columns[key]['values'])):  # for each category
                 updatedColumns = []
                 updatedValues = []
                 for name in columns.keys():
                     if name == key:
                         cat = columns[name]['values'][idx]
                         continue
-                    ctype  = columns[name]['ctype']
+                    ctype = columns[name]['ctype']
                     value = columns[name]['values'][idx]
-                    id    = columns[name]['ids'][idx]
+                    id = columns[name]['ids'][idx]
                     try:
                         newvalue = self.FindWindowById(id).GetValue()
                     except:
                         newvalue = self.FindWindowById(id).GetLabel()
-                  
+
                     if newvalue:
                         try:
                             if ctype == int:
@@ -222,18 +231,19 @@
                             elif ctype == float:
                                 newvalue = float(newvalue)
                         except ValueError:
-                            GError(parent = self,
-                                   message = _("Column <%(col)s>: Value '%(value)s' needs to be entered as %(type)s.") % \
-                                       {'col' : name,
-                                        'value' : str(newvalue),
-                                        'type' : columns[name]['type'].lower()},
-                                   showTraceback = False)
+                            GError(
+                                parent=self,
+                                message=_("Column <%(col)s>: Value '%(value)s' needs to be entered as %(type)s.") % {
+                                    'col': name,
+                                    'value': str(newvalue),
+                                    'type': columns[name]['type'].lower()},
+                                showTraceback=False)
                             sqlCommands.append(None)
                             continue
                     else:
                         if self.action == 'add':
                             continue
-                    
+
                     if newvalue != value:
                         updatedColumns.append(name)
                         if not newvalue:
@@ -260,13 +270,13 @@
                     else:
                         sqlString += name + "=" + updatedValues[idx] + ","
 
-                sqlString = sqlString[:-1] # remove last comma
+                sqlString = sqlString[:-1]  # remove last comma
 
                 if self.action == "add":
                     sqlString += ") VALUES (%s," % cat
                     for value in updatedValues:
                         sqlString += value + ","
-                    sqlString = sqlString[:-1] # remove last comma
+                    sqlString = sqlString[:-1]  # remove last comma
                     sqlString += ")"
                 else:
                     sqlString += " WHERE %s=%s" % (key, cat)
@@ -274,11 +284,13 @@
             # for each category
         # for each layer END
 
-        Debug.msg(3, "DisplayAttributesDialog.GetSQLString(): %s" % sqlCommands)
+        Debug.msg(
+            3, "DisplayAttributesDialog.GetSQLString(): %s" %
+            sqlCommands)
 
         return sqlCommands
 
-    def OnReset(self, event = None):
+    def OnReset(self, event=None):
         """Reset form"""
         for layer in self.mapDBInfo.layers.keys():
             table = self.mapDBInfo.layers[layer]["table"]
@@ -286,7 +298,7 @@
             columns = self.mapDBInfo.tables[table]
             for idx in range(len(columns[key]['values'])):
                 for name in columns.keys():
-                    type  = columns[name]['type']
+                    type = columns[name]['type']
                     value = columns[name]['values'][idx]
                     if value is None:
                         value = ''
@@ -294,7 +306,7 @@
                         id = columns[name]['ids'][idx]
                     except IndexError:
                         id = wx.NOT_FOUND
-                    
+
                     if name != key and id != wx.NOT_FOUND:
                         self.FindWindowById(id).SetValue(str(value))
 
@@ -306,10 +318,10 @@
         if hasattr(self, "digit"):
             self.parent.digit.GetDisplay().SetSelected([])
             if frame.IsAutoRendered():
-                self.parent.UpdateMap(render = False)
+                self.parent.UpdateMap(render=False)
         elif frame.IsAutoRendered():
             frame.RemoveQueryLayer()
-            self.parent.UpdateMap(render = True)
+            self.parent.UpdateMap(render=True)
         if self.IsModal():
             self.EndModal(wx.ID_OK)
         else:
@@ -319,11 +331,11 @@
         """Submit records"""
         layer = 1
         close = True
-        enc = UserSettings.Get(group = 'atm', key = 'encoding', subkey = 'value')
+        enc = UserSettings.Get(group='atm', key='encoding', subkey='value')
         if not enc and 'GRASS_DB_ENCODING' in os.environ:
             enc = os.environ['GRASS_DB_ENCODING']
-        
-        for sql in self.GetSQLString(updateValues = True):
+
+        for sql in self.GetSQLString(updateValues=True):
             if not sql:
                 close = False
                 continue
@@ -331,26 +343,26 @@
                 sql = sql.encode(enc)
             else:
                 sql = sql.encode('utf-8')
-            
+
             driver, database = self.mapDBInfo.GetDbSettings(layer)
             Debug.msg(1, "SQL: %s" % sql)
             RunCommand('db.execute',
-                       parent = self,
-                       quiet = True,
-                       input = '-',
-                       stdin = sql,
-                       driver = driver,
-                       database = database)
-            
+                       parent=self,
+                       quiet=True,
+                       input='-',
+                       stdin=sql,
+                       driver=driver,
+                       database=database)
+
             layer += 1
-        
+
         if close and self.closeDialog.IsChecked():
             self.OnClose(event)
 
     def OnFeature(self, event):
         self.fid = int(event.GetString())
-        self.UpdateDialog(cats = self.cats, fid = self.fid)
-        
+        self.UpdateDialog(cats=self.cats, fid=self.fid)
+
     def GetCats(self):
         """Get id of selected vector object or 'None' if nothing selected
 
@@ -358,23 +370,23 @@
         """
         if self.fid < 0:
             return None
-        
+
         return self.cats[self.fid]
 
     def GetFid(self):
         """Get selected feature id"""
         return self.fid
-    
-    def UpdateDialog(self, map = None, query = None, cats = None, fid = -1,
-                     action = None):
+
+    def UpdateDialog(self, map=None, query=None, cats=None, fid=-1,
+                     action=None):
         """Update dialog
-        
+
         :param map: name of vector map
         :param query:
         :param cats:
         :param fid: feature id
         :param action: add, update, display or None
-        
+
         :return: True if updated
         :return: False
         """
@@ -386,21 +398,21 @@
                 enabled = True
             self.closeDialog.Enable(enabled)
             self.FindWindowById(wx.ID_OK).Enable(enabled)
-        
+
         if map:
             self.map = map
             # get layer/table/column information
             self.mapDBInfo = VectorDBInfo(self.map)
-        
+
         if not self.mapDBInfo:
             return False
-        
+
         self.mapDBInfo.Reset()
-        
-        layers = self.mapDBInfo.layers.keys() # get available layers
-        
+
+        layers = self.mapDBInfo.layers.keys()  # get available layers
+
         # id of selected line
-        if query: # select by position
+        if query:  # select by position
             data = self.mapDBInfo.SelectByPoint(query[0],
                                                 query[1])
             self.cats = {}
@@ -411,7 +423,7 @@
                     if data['Id'][idx] is not None:
                         tfid = int(data['Id'][idx])
                     else:
-                        tfid = 0 # Area / Volume
+                        tfid = 0  # Area / Volume
                     if not tfid in self.cats:
                         self.cats[tfid] = {}
                     if not layer in self.cats[tfid]:
@@ -421,14 +433,14 @@
                     idx += 1
         else:
             self.cats = cats
-        
+
         if fid > 0:
             self.fid = fid
         elif len(self.cats.keys()) > 0:
             self.fid = self.cats.keys()[0]
         else:
             self.fid = -1
-        
+
         if len(self.cats.keys()) == 1:
             self.fidMulti.Show(False)
             self.fidText.Show(True)
@@ -444,24 +456,23 @@
                 choices.append(str(tfid))
             self.fidMulti.SetItems(choices)
             self.fidMulti.SetStringSelection(str(self.fid))
-        
+
         # reset notebook
         self.notebook.DeleteAllPages()
-        
-        for layer in layers: # for each layer
-            if not query: # select by layer/cat
+
+        for layer in layers:  # for each layer
+            if not query:  # select by layer/cat
                 if self.fid > 0 and layer in self.cats[self.fid]:
                     for cat in self.cats[self.fid][layer]:
-                        nselected = self.mapDBInfo.SelectFromTable(layer,
-                                                                   where = "%s=%d" % \
-                                                                   (self.mapDBInfo.layers[layer]['key'],
-                                                                    cat))
+                        nselected = self.mapDBInfo.SelectFromTable(
+                            layer, where="%s=%d" %
+                            (self.mapDBInfo.layers[layer]['key'], cat))
                 else:
                     nselected = 0
-            
+
             # if nselected <= 0 and self.action != "add":
             #    continue # nothing selected ...
-            
+
             if self.action == "add":
                 if nselected <= 0:
                     if layer in self.cats[self.fid]:
@@ -471,47 +482,51 @@
                         for name in columns.keys():
                             if name == key:
                                 for cat in self.cats[self.fid][layer]:
-                                    self.mapDBInfo.tables[table][name]['values'].append(cat)
+                                    self.mapDBInfo.tables[table][
+                                        name]['values'].append(cat)
                             else:
-                                self.mapDBInfo.tables[table][name]['values'].append(None)
-                else: # change status 'add' -> 'update'
+                                self.mapDBInfo.tables[table][
+                                    name]['values'].append(None)
+                else:  # change status 'add' -> 'update'
                     self.action = "update"
-            
-            table   = self.mapDBInfo.layers[layer]["table"]
-            key   = self.mapDBInfo.layers[layer]["key"]
+
+            table = self.mapDBInfo.layers[layer]["table"]
+            key = self.mapDBInfo.layers[layer]["key"]
             columns = self.mapDBInfo.tables[table]
-            
+
             for idx in range(len(columns[key]['values'])):
                 for name in columns.keys():
                     if name == key:
                         cat = int(columns[name]['values'][idx])
                         break
 
-                # use scrolled panel instead (and fix initial max height of the window to 480px)
-                panel = scrolled.ScrolledPanel(parent = self.notebook, id = wx.ID_ANY,
-                                               size = (-1, 150))
-                panel.SetupScrolling(scroll_x = False)
-                
-                self.notebook.AddPage(page = panel, text = " %s %d / %s %d" % (_("Layer"), layer,
-                                                                           _("Category"), cat))
-                
+                # use scrolled panel instead (and fix initial max height of the
+                # window to 480px)
+                panel = scrolled.ScrolledPanel(
+                    parent=self.notebook, id=wx.ID_ANY, size=(-1, 150))
+                panel.SetupScrolling(scroll_x=False)
+
+                self.notebook.AddPage(
+                    page=panel, text=" %s %d / %s %d" %
+                    (_("Layer"), layer, _("Category"), cat))
+
                 # notebook body
                 border = wx.BoxSizer(wx.VERTICAL)
-                
-                flexSizer = wx.FlexGridSizer (cols = 3, hgap = 3, vgap = 3)
+
+                flexSizer = wx.FlexGridSizer(cols=3, hgap=3, vgap=3)
                 flexSizer.AddGrowableCol(2)
                 # columns (sorted by index)
                 names = [''] * len(columns.keys())
                 for name in columns.keys():
                     names[columns[name]['index']] = name
-                
+
                 for name in names:
-                    if name == key: # skip key column (category)
+                    if name == key:  # skip key column (category)
                         continue
-                    
-                    vtype  = columns[name]['type'].lower()
-                    ctype  = columns[name]['ctype']
-                    
+
+                    vtype = columns[name]['type'].lower()
+                    ctype = columns[name]['ctype']
+
                     if columns[name]['values'][idx] is not None:
                         if columns[name]['ctype'] != types.StringType:
                             value = str(columns[name]['values'][idx])
@@ -519,43 +534,51 @@
                             value = columns[name]['values'][idx]
                     else:
                         value = ''
-                    
-                    colName = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                            label = name)
-                    colType = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                            label = "[%s]:" % vtype)
-                    colValue = wx.TextCtrl(parent = panel, id = wx.ID_ANY, value = value)
+
+                    colName = wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                            label=name)
+                    colType = wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                            label="[%s]:" % vtype)
+                    colValue = wx.TextCtrl(
+                        parent=panel, id=wx.ID_ANY, value=value)
                     colValue.SetName(name)
                     if ctype == int:
                         colValue.SetValidator(IntegerValidator())
                     elif ctype == float:
                         colValue.SetValidator(FloatValidator())
-                    
+
                     self.Bind(wx.EVT_TEXT, self.OnSQLStatement, colValue)
                     if self.action == 'display':
                         colValue.SetWindowStyle(wx.TE_READONLY)
-                    
-                    flexSizer.Add(colName, proportion = 0,
-                                  flag = wx.ALIGN_CENTER_VERTICAL)
-                    flexSizer.Add(colType, proportion = 0,
-                                  flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
-                    flexSizer.Add(colValue, proportion = 1,
-                                  flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
+
+                    flexSizer.Add(colName, proportion=0,
+                                  flag=wx.ALIGN_CENTER_VERTICAL)
+                    flexSizer.Add(
+                        colType,
+                        proportion=0,
+                        flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
+                    flexSizer.Add(colValue, proportion=1,
+                                  flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
                     # add widget reference to self.columns
-                    columns[name]['ids'].append(colValue.GetId()) # name, type, values, id
+                    columns[name]['ids'].append(
+                        colValue.GetId())  # name, type, values, id
                 # for each attribute (including category) END
-                border.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
+                border.Add(
+                    item=flexSizer,
+                    proportion=1,
+                    flag=wx.ALL | wx.EXPAND,
+                    border=5)
                 panel.SetSizer(border)
             # for each category END
         # for each layer END
-        
+
         if self.notebook.GetPageCount() == 0:
             self.noFoundMsg.Show(True)
         else:
             self.noFoundMsg.Show(False)
-        
+
         self.Layout()
-        
+
         return True
 
     def SetColumnValue(self, layer, column, value):
@@ -566,46 +589,48 @@
         """
         table = self.mapDBInfo.GetTable(layer)
         columns = self.mapDBInfo.GetTableDesc(table)
-        
+
         for key, col in columns.iteritems():
             if key == column:
-                col['values'] = [col['ctype'](value),]
+                col['values'] = [col['ctype'](value), ]
                 break
-        
+
+
 class ModifyTableRecord(wx.Dialog):
-    def __init__(self, parent, title, data, keyEditable = (-1, True),
-                 id = wx.ID_ANY, style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
+
+    def __init__(self, parent, title, data, keyEditable=(-1, True),
+                 id=wx.ID_ANY, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
         """Dialog for inserting/updating table record
-        
+
         :param data: a list: [(column, value)]
         :param keyEditable: (id, editable?) indicates if textarea for
                             key column is editable(True) or not
         """
         # parent -> VDigitWindow
-        wx.Dialog.__init__(self, parent, id, title, style = style)
-        
+        wx.Dialog.__init__(self, parent, id, title, style=style)
+
         self.CenterOnParent()
-        
+
         self.keyId = keyEditable[0]
-        
-        box = wx.StaticBox(parent = self, id = wx.ID_ANY)
+
+        box = wx.StaticBox(parent=self, id=wx.ID_ANY)
         box.Hide()
-        self.dataPanel = scrolled.ScrolledPanel(parent = self, id = wx.ID_ANY,
-                                                style = wx.TAB_TRAVERSAL)
-        self.dataPanel.SetupScrolling(scroll_x = False)
-        
+        self.dataPanel = scrolled.ScrolledPanel(parent=self, id=wx.ID_ANY,
+                                                style=wx.TAB_TRAVERSAL)
+        self.dataPanel.SetupScrolling(scroll_x=False)
+
         # buttons
         self.btnCancel = wx.Button(self, wx.ID_CANCEL)
         self.btnSubmit = wx.Button(self, wx.ID_OK, _("&Submit"))
         self.btnSubmit.SetDefault()
-        
+
         # data area
         self.widgets = []
         cId = 0
         self.usebox = False
         self.cat = None
         winFocus = False
-        
+
         for column, ctype, ctypeStr, value in data:
             if self.keyId == cId:
                 self.cat = int(value)
@@ -617,11 +642,12 @@
                     cId += 1
                     continue
                 else:
-                    valueWin = wx.SpinCtrl(parent = self.dataPanel, id = wx.ID_ANY,
-                                           value = value, min = -1e9, max = 1e9, size = (250, -1))
+                    valueWin = wx.SpinCtrl(
+                        parent=self.dataPanel, id=wx.ID_ANY, value=value,
+                        min=-1e9, max=1e9, size=(250, -1))
             else:
-                valueWin = wx.TextCtrl(parent = self.dataPanel, id = wx.ID_ANY,
-                                       value = value, size = (250, -1))
+                valueWin = wx.TextCtrl(parent=self.dataPanel, id=wx.ID_ANY,
+                                       value=value, size=(250, -1))
                 if ctype == int:
                     valueWin.SetValidator(IntegerValidator())
                 elif ctype == float:
@@ -629,116 +655,119 @@
                 if not winFocus:
                     wx.CallAfter(valueWin.SetFocus)
                     winFocus = True
-            
-            label = wx.StaticText(parent = self.dataPanel, id = wx.ID_ANY,
-                                  label = column)
-            ctype = wx.StaticText(parent = self.dataPanel, id = wx.ID_ANY,
-                                  label = "[%s]:" % ctypeStr.lower())
-            self.widgets.append((label.GetId(), ctype.GetId(), valueWin.GetId()))
-            
+
+            label = wx.StaticText(parent=self.dataPanel, id=wx.ID_ANY,
+                                  label=column)
+            ctype = wx.StaticText(parent=self.dataPanel, id=wx.ID_ANY,
+                                  label="[%s]:" % ctypeStr.lower())
+            self.widgets.append(
+                (label.GetId(), ctype.GetId(), valueWin.GetId()))
+
             cId += 1
-        
+
         self._layout()
-        
+
     def _layout(self):
         """Do layout"""
         sizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         # data area
-        dataSizer = wx.FlexGridSizer(cols = 3, hgap = 3, vgap = 3)
+        dataSizer = wx.FlexGridSizer(cols=3, hgap=3, vgap=3)
         dataSizer.AddGrowableCol(2)
-        
+
         for labelId, ctypeId, valueId in self.widgets:
             label = self.FindWindowById(labelId)
             ctype = self.FindWindowById(ctypeId)
             value = self.FindWindowById(valueId)
-            
-            dataSizer.Add(label, proportion = 0,
-                          flag = wx.ALIGN_CENTER_VERTICAL)
-            dataSizer.Add(ctype, proportion = 0,
-                          flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
-            dataSizer.Add(value, proportion = 0,
-                          flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
-        
+
+            dataSizer.Add(label, proportion=0,
+                          flag=wx.ALIGN_CENTER_VERTICAL)
+            dataSizer.Add(ctype, proportion=0,
+                          flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
+            dataSizer.Add(value, proportion=0,
+                          flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
+
         self.dataPanel.SetAutoLayout(True)
         self.dataPanel.SetSizer(dataSizer)
         dataSizer.Fit(self.dataPanel)
-        
+
         if self.usebox:
-            self.boxSizer.Add(item = self.dataPanel, proportion = 1,
-                              flag = wx.EXPAND | wx.ALL, border = 5)
-            
+            self.boxSizer.Add(item=self.dataPanel, proportion=1,
+                              flag=wx.EXPAND | wx.ALL, border=5)
+
         # buttons
         btnSizer = wx.StdDialogButtonSizer()
         btnSizer.AddButton(self.btnCancel)
         btnSizer.AddButton(self.btnSubmit)
         btnSizer.Realize()
-        
+
         if not self.usebox:
-            sizer.Add(item = self.dataPanel, proportion = 1,
-                      flag = wx.EXPAND | wx.ALL, border = 5)
+            sizer.Add(item=self.dataPanel, proportion=1,
+                      flag=wx.EXPAND | wx.ALL, border=5)
         else:
-            sizer.Add(item = self.boxSizer, proportion = 1,
-                      flag = wx.EXPAND | wx.ALL, border = 5)
-        
-        sizer.Add(item = btnSizer, proportion = 0,
-                  flag = wx.EXPAND | wx.ALL, border = 5)
-        
+            sizer.Add(item=self.boxSizer, proportion=1,
+                      flag=wx.EXPAND | wx.ALL, border=5)
+
+        sizer.Add(item=btnSizer, proportion=0,
+                  flag=wx.EXPAND | wx.ALL, border=5)
+
         framewidth = self.GetBestSize()[0] + 25
         self.SetMinSize((framewidth, 250))
 
         self.SetAutoLayout(True)
         self.SetSizer(sizer)
         sizer.Fit(self)
-        
+
         self.Layout()
-        
-    def GetValues(self, columns = None):
+
+    def GetValues(self, columns=None):
         """Return list of values (casted to string).
-        
+
         If columns is given (list), return only values of given columns.
         """
         valueList = list()
         for labelId, ctypeId, valueId in self.widgets:
             column = self.FindWindowById(labelId).GetLabel()
             if columns is None or column in columns:
-                value = GetUnicodeValue(self.FindWindowById(valueId).GetValue())
+                value = GetUnicodeValue(
+                    self.FindWindowById(valueId).GetValue())
                 valueList.append(value)
-        
+
         # add key value
         if self.usebox:
             valueList.insert(self.keyId, GetUnicodeValue(str(self.cat)))
-        
+
         return valueList
 
+
 class AddColumnDialog(wx.Dialog):
-    def __init__(self, parent, title, id = wx.ID_ANY,
-                 style = wx.DEFAULT_DIALOG_STYLE  | wx.RESIZE_BORDER):
+
+    def __init__(self, parent, title, id=wx.ID_ANY,
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
         """Dialog for adding column into table
         """
-        wx.Dialog.__init__(self, parent, id, title, style = style)
-        
+        wx.Dialog.__init__(self, parent, id, title, style=style)
+
         self.CenterOnParent()
 
-        self.data = {} 
-        self.data['addColName'] = wx.TextCtrl(parent = self, id = wx.ID_ANY, value = '',
-                                              size = (150, -1), style = wx.TE_PROCESS_ENTER)
+        self.data = {}
+        self.data['addColName'] = wx.TextCtrl(
+            parent=self, id=wx.ID_ANY, value='', size=(
+                150, -1), style=wx.TE_PROCESS_ENTER)
 
-           
-        self.data['addColType'] = wx.Choice (parent = self, id = wx.ID_ANY,
-                                             choices = ["integer",
-                                                        "double",
-                                                        "varchar",
-                                                        "date"]) # FIXME
+        self.data['addColType'] = wx.Choice(parent=self, id=wx.ID_ANY,
+                                            choices=["integer",
+                                                     "double",
+                                                     "varchar",
+                                                     "date"])  # FIXME
         self.data['addColType'].SetSelection(0)
         self.data['addColType'].Bind(wx.EVT_CHOICE, self.OnTableChangeType)
-            
-        self.data['addColLength'] = wx.SpinCtrl(parent = self, id = wx.ID_ANY, size = (65, -1),
-                                                initial = 250,
-                                                min = 1, max = 1e6)
+
+        self.data['addColLength'] = wx.SpinCtrl(
+            parent=self, id=wx.ID_ANY, size=(
+                65, -1), initial=250, min=1, max=1e6)
         self.data['addColLength'].Enable(False)
 
-
         # buttons
         self.btnCancel = wx.Button(self, wx.ID_CANCEL)
         self.btnOk = wx.Button(self, wx.ID_OK)
@@ -751,37 +780,49 @@
         sizer = wx.BoxSizer(wx.VERTICAL)
         addSizer = wx.BoxSizer(wx.HORIZONTAL)
 
-        addSizer.Add(item =  wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Column")),
-                     flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
-                     border = 5)
-        addSizer.Add(item = self.data['addColName'], proportion = 1,
-                     flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
-                     border = 5)
+        addSizer.Add(
+            item=wx.StaticText(
+                parent=self,
+                id=wx.ID_ANY,
+                label=_("Column")),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+            border=5)
+        addSizer.Add(item=self.data['addColName'], proportion=1,
+                     flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+                     border=5)
 
-        addSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Type")), 
-                     flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
-                     border = 5)
-        addSizer.Add(item = self.data['addColType'],
-                     flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
-                     border = 5)
+        addSizer.Add(
+            item=wx.StaticText(
+                parent=self,
+                id=wx.ID_ANY,
+                label=_("Type")),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+            border=5)
+        addSizer.Add(item=self.data['addColType'],
+                     flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+                     border=5)
 
-        addSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Length")),
-                     flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
-                     border = 5)
-        addSizer.Add(item = self.data['addColLength'],
-                     flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
-                     border = 5)
+        addSizer.Add(
+            item=wx.StaticText(
+                parent=self,
+                id=wx.ID_ANY,
+                label=_("Length")),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+            border=5)
+        addSizer.Add(item=self.data['addColLength'],
+                     flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+                     border=5)
 
-        sizer.Add(item = addSizer, proportion = 0,
-                  flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
+        sizer.Add(item=addSizer, proportion=0,
+                  flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
 
         btnSizer = wx.StdDialogButtonSizer()
         btnSizer.AddButton(self.btnCancel)
         btnSizer.AddButton(self.btnOk)
         btnSizer.Realize()
 
-        sizer.Add(item = btnSizer, proportion = 0,
-                  flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
+        sizer.Add(item=btnSizer, proportion=0,
+                  flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
 
         self.SetSizer(sizer)
 
@@ -795,11 +836,11 @@
         values['length'] = int(self.data['addColLength'].GetValue())
 
         return values
-  
+
     def OnTableChangeType(self, event):
         """Data type for new column changed. Enable or disable
         data length widget"""
         if event.GetString() == "varchar":
             self.data['addColLength'].Enable(True)
         else:
-            self.data['addColLength'].Enable(False)     
+            self.data['addColLength'].Enable(False)

Modified: grass/trunk/gui/wxpython/dbmgr/g.gui.dbmgr.py
===================================================================
--- grass/trunk/gui/wxpython/dbmgr/g.gui.dbmgr.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/dbmgr/g.gui.dbmgr.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -38,7 +38,7 @@
 
     from grass.script.setup import set_gui_path
     set_gui_path()
-    
+
     from core.utils import _
     from dbmgr.manager import AttributeManager
 
@@ -48,11 +48,13 @@
         gscript.fatal(_("Vector map <%s> not found") % options['map'])
 
     app = wx.App()
-    gscript.message(_("Loading attribute data for vector map <%s>...") % mapName)
-    f = AttributeManager(parent=None, id=wx.ID_ANY,
-                         title="%s - <%s>" % (_("GRASS GIS Attribute Table Manager"),
-                                              mapName),
-                         size=(900, 600), vectorName=mapName)
+    gscript.message(
+        _("Loading attribute data for vector map <%s>...") %
+        mapName)
+    f = AttributeManager(
+        parent=None, id=wx.ID_ANY, title="%s - <%s>" %
+        (_("GRASS GIS Attribute Table Manager"), mapName), size=(
+            900, 600), vectorName=mapName)
     f.Show()
 
     app.MainLoop()

Modified: grass/trunk/gui/wxpython/dbmgr/manager.py
===================================================================
--- grass/trunk/gui/wxpython/dbmgr/manager.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/dbmgr/manager.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -26,21 +26,23 @@
 import os
 
 import wx
-import wx.lib.flatnotebook    as FN
+import wx.lib.flatnotebook as FN
 
 import grass.script as grass
 
-from core             import globalvar
-from core.gcmd        import GMessage
-from core.debug       import Debug
+from core import globalvar
+from core.gcmd import GMessage
+from core.debug import Debug
 from core.utils import _
-from dbmgr.base       import DbMgrBase
+from dbmgr.base import DbMgrBase
 from gui_core.widgets import GNotebook
-                
+
+
 class AttributeManager(wx.Frame, DbMgrBase):
-    def __init__(self, parent, id = wx.ID_ANY,
-                 title = None, vectorName = None, item = None, log = None,
-                 selection = None, **kwargs):
+
+    def __init__(self, parent, id=wx.ID_ANY,
+                 title=None, vectorName=None, item=None, log=None,
+                 selection=None, **kwargs):
         """GRASS Attribute Table Manager window
 
         :param parent: parent window
@@ -57,12 +59,12 @@
             mapdisplay = self.parent.GetMapDisplay()
         except:
             mapdisplay = None
-        
-        DbMgrBase.__init__(self, id = id, mapdisplay = mapdisplay,
-                           vectorName = vectorName, item = item, 
-                           log = log, statusbar = self, 
+
+        DbMgrBase.__init__(self, id=id, mapdisplay=mapdisplay,
+                           vectorName=vectorName, item=item,
+                           log=log, statusbar=self,
                            **kwargs)
-        
+
         wx.Frame.__init__(self, parent, id, *kwargs)
 
         # title
@@ -72,72 +74,86 @@
                 title += _("READONLY - ")
             title += "<%s>" % (self.dbMgrData['vectName'])
 
+        self.SetTitle(title)
 
-        self.SetTitle(title)
-        
         # icon
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass_sql.ico'), wx.BITMAP_TYPE_ICO))
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass_sql.ico'),
+                wx.BITMAP_TYPE_ICO))
 
-        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
-             
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
         if len(self.dbMgrData['mapDBInfo'].layers.keys()) == 0:
-            GMessage(parent = self.parent,
-                     message = _("Database connection for vector map <%s> "
-                                 "is not defined in DB file. "
-                                 "You can define new connection in "
-                                 "'Manage layers' tab.") % self.dbMgrData['vectName'])
-        
+            GMessage(
+                parent=self.parent, message=_(
+                    "Database connection for vector map <%s> "
+                    "is not defined in DB file. "
+                    "You can define new connection in "
+                    "'Manage layers' tab.") %
+                self.dbMgrData['vectName'])
+
         busy = wx.BusyInfo(message=_("Please wait, loading attribute data..."),
                            parent=self.parent)
         wx.SafeYield()
-        self.CreateStatusBar(number = 1)
+        self.CreateStatusBar(number=1)
 
-        self.notebook = GNotebook(self.panel, style = globalvar.FNPageDStyle)
-                
-        self.CreateDbMgrPage(parent = self, pageName = 'browse')
+        self.notebook = GNotebook(self.panel, style=globalvar.FNPageDStyle)
 
-        self.notebook.AddPage(page = self.pages['browse'], text = _("Browse data"),
-                              name = 'browse')
+        self.CreateDbMgrPage(parent=self, pageName='browse')
+
+        self.notebook.AddPage(page=self.pages['browse'], text=_("Browse data"),
+                              name='browse')
         self.pages['browse'].SetTabAreaColour(globalvar.FNPageColor)
 
-        self.CreateDbMgrPage(parent = self, pageName = 'manageTable')
+        self.CreateDbMgrPage(parent=self, pageName='manageTable')
 
-        self.notebook.AddPage(page = self.pages['manageTable'], text = _("Manage tables"),
-                              name = 'table')
+        self.notebook.AddPage(
+            page=self.pages['manageTable'],
+            text=_("Manage tables"),
+            name='table')
         self.pages['manageTable'].SetTabAreaColour(globalvar.FNPageColor)
 
-        self.CreateDbMgrPage(parent = self, pageName = 'manageLayer')
-        self.notebook.AddPage(page = self.pages['manageLayer'], text = _("Manage layers"),
-                              name = 'layers')
+        self.CreateDbMgrPage(parent=self, pageName='manageLayer')
+        self.notebook.AddPage(
+            page=self.pages['manageLayer'],
+            text=_("Manage layers"),
+            name='layers')
         del busy
 
         if selection:
             wx.CallAfter(self.notebook.SetSelectionByName, selection)
         else:
-            wx.CallAfter(self.notebook.SetSelection, 0) # select browse tab
-        
+            wx.CallAfter(self.notebook.SetSelection, 0)  # select browse tab
+
         # buttons
-        self.btnClose   = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
+        self.btnClose = wx.Button(parent=self.panel, id=wx.ID_CLOSE)
         self.btnClose.SetToolTipString(_("Close Attribute Table Manager"))
-        self.btnReload = wx.Button(parent = self.panel, id = wx.ID_REFRESH)
-        self.btnReload.SetToolTipString(_("Reload currently selected attribute data"))
-        self.btnReset = wx.Button(parent = self.panel, id = wx.ID_CLEAR)
-        self.btnReset.SetToolTipString(_("Reload all attribute data (drop current selection)"))
-        
+        self.btnReload = wx.Button(parent=self.panel, id=wx.ID_REFRESH)
+        self.btnReload.SetToolTipString(
+            _("Reload currently selected attribute data"))
+        self.btnReset = wx.Button(parent=self.panel, id=wx.ID_CLEAR)
+        self.btnReset.SetToolTipString(
+            _("Reload all attribute data (drop current selection)"))
+
         # events
-        self.btnClose.Bind(wx.EVT_BUTTON,   self.OnCloseWindow)
-        self.btnReload.Bind(wx.EVT_BUTTON,  self.OnReloadData)
-        self.btnReset.Bind(wx.EVT_BUTTON,   self.OnReloadDataAll)
-        self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
+        self.btnClose.Bind(wx.EVT_BUTTON, self.OnCloseWindow)
+        self.btnReload.Bind(wx.EVT_BUTTON, self.OnReloadData)
+        self.btnReset.Bind(wx.EVT_BUTTON, self.OnReloadDataAll)
+        self.notebook.Bind(
+            FN.EVT_FLATNOTEBOOK_PAGE_CHANGED,
+            self.OnPageChanged)
         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
 
         # do layout
         self._layout()
 
         # self.SetMinSize(self.GetBestSize())
-        self.SetSize((700, 550)) # FIXME hard-coded size
+        self.SetSize((700, 550))  # FIXME hard-coded size
         self.SetMinSize(self.GetSize())
-    
+
     def _layout(self):
         """Do layout"""
         # frame body
@@ -145,36 +161,36 @@
 
         # buttons
         btnSizer = wx.BoxSizer(wx.HORIZONTAL)
-        btnSizer.Add(item = self.btnReset, proportion = 1,
-                     flag = wx.ALL | wx.ALIGN_RIGHT, border = 5)
-        btnSizer.Add(item = self.btnReload, proportion = 1,
-                     flag = wx.ALL | wx.ALIGN_RIGHT, border = 5)
-        btnSizer.Add(item = self.btnClose, proportion = 1,
-                     flag = wx.ALL | wx.ALIGN_RIGHT, border = 5)
+        btnSizer.Add(item=self.btnReset, proportion=1,
+                     flag=wx.ALL | wx.ALIGN_RIGHT, border=5)
+        btnSizer.Add(item=self.btnReload, proportion=1,
+                     flag=wx.ALL | wx.ALIGN_RIGHT, border=5)
+        btnSizer.Add(item=self.btnClose, proportion=1,
+                     flag=wx.ALL | wx.ALIGN_RIGHT, border=5)
 
-        mainSizer.Add(item = self.notebook, proportion = 1, flag = wx.EXPAND)
-        mainSizer.Add(item = btnSizer, flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
+        mainSizer.Add(item=self.notebook, proportion=1, flag=wx.EXPAND)
+        mainSizer.Add(item=btnSizer, flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
 
         self.panel.SetAutoLayout(True)
         self.panel.SetSizer(mainSizer)
         mainSizer.Fit(self.panel)
         self.Layout()
-  
+
     def OnCloseWindow(self, event):
         """Cancel button pressed"""
         if self.parent and self.parent.GetName() == 'LayerManager':
             # deregister ATM
             self.parent.dialogs['atm'].remove(self)
-                    
+
         if not isinstance(event, wx.CloseEvent):
             self.Destroy()
-        
+
         event.Skip()
 
     def OnReloadData(self, event):
         """Reload data"""
         if self.pages['browse']:
-            self.pages['browse'].OnDataReload(event) # TODO replace by signal
+            self.pages['browse'].OnDataReload(event)  # TODO replace by signal
 
     def OnReloadDataAll(self, event):
         """Reload all data"""
@@ -191,11 +207,13 @@
                 id = None
         except KeyError:
             id = None
-        
+
         if event.GetSelection() == self.notebook.GetPageIndexByName('browse') and id:
             win = self.FindWindowById(id)
             if win:
-                self.log.write(_("Number of loaded records: %d") % win.GetItemCount())
+                self.log.write(
+                    _("Number of loaded records: %d") %
+                    win.GetItemCount())
             else:
                 self.log.write("")
             self.btnReload.Enable()
@@ -204,14 +222,14 @@
             self.log.write("")
             self.btnReload.Enable(False)
             self.btnReset.Enable(False)
-        
-        event.Skip()   
 
+        event.Skip()
+
     def OnTextEnter(self, event):
         pass
 
     def UpdateDialog(self, layer):
         """Updates dialog layout for given layer"""
-        DbMgrBase.UpdateDialog(self, layer = layer)
+        DbMgrBase.UpdateDialog(self, layer=layer)
         # set current page selection
-        self.notebook.SetSelectionByName('layers') 
+        self.notebook.SetSelectionByName('layers')

Modified: grass/trunk/gui/wxpython/dbmgr/sqlbuilder.py
===================================================================
--- grass/trunk/gui/wxpython/dbmgr/sqlbuilder.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/dbmgr/sqlbuilder.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -33,256 +33,317 @@
 
 from grass.pydispatch.signal import Signal
 
-from core.gcmd   import RunCommand, GError, GMessage
+from core.gcmd import RunCommand, GError, GMessage
 from dbmgr.vinfo import CreateDbInfoDesc, VectorDBInfo, GetUnicodeValue
 
 import grass.script as grass
 
+
 class SQLBuilder(wx.Frame):
     """SQLBuider class
     Base class for classes, which builds SQL statements.
     """
-    def __init__(self, parent, title, vectmap, modeChoices, id = wx.ID_ANY,
-                 layer = 1):
+
+    def __init__(self, parent, title, vectmap, modeChoices, id=wx.ID_ANY,
+                 layer=1):
         wx.Frame.__init__(self, parent, id, title)
-        
+
         self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass_sql.ico'),
                              wx.BITMAP_TYPE_ICO))
-        
-        self.parent     = parent
-        
+
+        self.parent = parent
+
         # variables
-        self.vectmap = vectmap # fullname
+        self.vectmap = vectmap  # fullname
         if not "@" in self.vectmap:
-            self.vectmap = grass.find_file(self.vectmap, element = 'vector')['fullname']
+            self.vectmap = grass.find_file(
+                self.vectmap, element='vector')['fullname']
             if not self.vectmap:
                 grass.fatal(_("Vector map <%s> not found") % vectmap)
         self.mapname, self.mapset = self.vectmap.split("@", 1)
-        
+
         # db info
         self.layer = layer
         self.dbInfo = VectorDBInfo(self.vectmap)
         self.tablename = self.dbInfo.GetTable(self.layer)
         self.driver, self.database = self.dbInfo.GetDbSettings(self.layer)
-        
+
         self.colvalues = []     # array with unique values in selected column
-        
-        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
 
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
         # statusbar
         self.statusbar = self.CreateStatusBar(number=1)
-        
+
         self._doLayout(modeChoices)
 
         self.panel.SetAutoLayout(True)
         self.panel.SetSizer(self.pagesizer)
         self.pagesizer.Fit(self.panel)
-        
+
         self.SetMinSize((400, 600))
         self.SetClientSize(self.panel.GetSize())
         self.CenterOnParent()
-                
+
     def _doLayout(self, modeChoices):
         """Do dialog layout"""
-        
+
         self.pagesizer = wx.BoxSizer(wx.VERTICAL)
 
-        
         # dbInfo
-        databasebox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
-                                   label = " %s " % _("Database connection"))
+        databasebox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
+                                   label=" %s " % _("Database connection"))
         databaseboxsizer = wx.StaticBoxSizer(databasebox, wx.VERTICAL)
-        databaseboxsizer.Add(item = CreateDbInfoDesc(self.panel, self.dbInfo, layer = self.layer),
-                             proportion=1,
-                             flag=wx.EXPAND | wx.ALL,
-                             border=3)
+        databaseboxsizer.Add(
+            item=CreateDbInfoDesc(
+                self.panel,
+                self.dbInfo,
+                layer=self.layer),
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=3)
 
         #
         # text areas
         #
         # sql box
-        sqlbox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
-                              label = " %s " % _("Query"))
+        sqlbox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
+                              label=" %s " % _("Query"))
         sqlboxsizer = wx.StaticBoxSizer(sqlbox, wx.VERTICAL)
 
-        self.text_sql = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
-                                    value = '', size = (-1, 50),
+        self.text_sql = wx.TextCtrl(parent=self.panel, id=wx.ID_ANY,
+                                    value='', size=(-1, 50),
                                     style=wx.TE_MULTILINE)
-        
+
         self.text_sql.SetInsertionPointEnd()
         wx.CallAfter(self.text_sql.SetFocus)
 
-        sqlboxsizer.Add(item = self.text_sql, flag = wx.EXPAND)
-        
+        sqlboxsizer.Add(item=self.text_sql, flag=wx.EXPAND)
+
         #
         # buttons
         #
-        self.btn_clear  = wx.Button(parent = self.panel, id = wx.ID_CLEAR)
+        self.btn_clear = wx.Button(parent=self.panel, id=wx.ID_CLEAR)
         self.btn_clear.SetToolTipString(_("Set SQL statement to default"))
-        self.btn_apply  = wx.Button(parent = self.panel, id = wx.ID_APPLY)
-        self.btn_apply.SetToolTipString(_("Apply SQL statement in Attribute Table Manager"))
-        self.btn_close  = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
+        self.btn_apply = wx.Button(parent=self.panel, id=wx.ID_APPLY)
+        self.btn_apply.SetToolTipString(
+            _("Apply SQL statement in Attribute Table Manager"))
+        self.btn_close = wx.Button(parent=self.panel, id=wx.ID_CLOSE)
         self.btn_close.SetToolTipString(_("Close the dialog"))
-        
-        self.btn_logic = { 'is' : ['=', ],
-                           'isnot' : ['!=', ],
-                           'like'  : ['LIKE', ],
-                           'gt'    : ['>', ],
-                           'ge'    : ['>=', ],
-                           'lt'    : ['<', ],
-                           'le'    : ['<=', ],
-                           'or'    : ['OR', ],
-                           'not'   : ['NOT', ],
-                           'and'   : ['AND', ],
-                           'brac'  : ['()', ],
-                           'prc'   : ['%', ] }
-    
-        self.btn_logicpanel = wx.Panel(parent = self.panel, id = wx.ID_ANY)    
+
+        self.btn_logic = {'is': ['=', ],
+                          'isnot': ['!=', ],
+                          'like': ['LIKE', ],
+                          'gt': ['>', ],
+                          'ge': ['>=', ],
+                          'lt': ['<', ],
+                          'le': ['<=', ],
+                          'or': ['OR', ],
+                          'not': ['NOT', ],
+                          'and': ['AND', ],
+                          'brac': ['()', ],
+                          'prc': ['%', ]}
+
+        self.btn_logicpanel = wx.Panel(parent=self.panel, id=wx.ID_ANY)
         for key, value in self.btn_logic.iteritems():
-            btn = wx.Button(parent = self.btn_logicpanel, id = wx.ID_ANY,
-                            label = value[0])
+            btn = wx.Button(parent=self.btn_logicpanel, id=wx.ID_ANY,
+                            label=value[0])
             self.btn_logic[key].append(btn.GetId())
-            
-        self.buttonsizer = wx.FlexGridSizer(cols = 4, hgap = 5, vgap = 5)
-        self.buttonsizer.Add(item = self.btn_clear)
-        self.buttonsizer.Add(item = self.btn_apply)
-        self.buttonsizer.Add(item = self.btn_close)
-        
+
+        self.buttonsizer = wx.FlexGridSizer(cols=4, hgap=5, vgap=5)
+        self.buttonsizer.Add(item=self.btn_clear)
+        self.buttonsizer.Add(item=self.btn_apply)
+        self.buttonsizer.Add(item=self.btn_close)
+
         btn_logicsizer = wx.GridBagSizer(5, 5)
-        btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['is'][1]), pos = (0,0))
-        btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['isnot'][1]), pos = (1,0))
-        btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['like'][1]), pos = (2, 0))
+        btn_logicsizer.Add(
+            item=self.FindWindowById(
+                self.btn_logic['is'][1]), pos=(
+                0, 0))
+        btn_logicsizer.Add(
+            item=self.FindWindowById(
+                self.btn_logic['isnot'][1]), pos=(
+                1, 0))
+        btn_logicsizer.Add(
+            item=self.FindWindowById(
+                self.btn_logic['like'][1]), pos=(
+                2, 0))
 
-        btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['gt'][1]), pos = (0, 1))
-        btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['ge'][1]), pos = (1, 1))
-        btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['or'][1]), pos = (2, 1))
+        btn_logicsizer.Add(
+            item=self.FindWindowById(
+                self.btn_logic['gt'][1]), pos=(
+                0, 1))
+        btn_logicsizer.Add(
+            item=self.FindWindowById(
+                self.btn_logic['ge'][1]), pos=(
+                1, 1))
+        btn_logicsizer.Add(
+            item=self.FindWindowById(
+                self.btn_logic['or'][1]), pos=(
+                2, 1))
 
-        btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['lt'][1]), pos = (0, 2))
-        btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['le'][1]), pos = (1, 2))
-        btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['not'][1]), pos = (2, 2))
+        btn_logicsizer.Add(
+            item=self.FindWindowById(
+                self.btn_logic['lt'][1]), pos=(
+                0, 2))
+        btn_logicsizer.Add(
+            item=self.FindWindowById(
+                self.btn_logic['le'][1]), pos=(
+                1, 2))
+        btn_logicsizer.Add(
+            item=self.FindWindowById(
+                self.btn_logic['not'][1]), pos=(
+                2, 2))
 
-        btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['brac'][1]), pos = (0, 3))
-        btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['prc'][1]), pos = (1, 3))
-        btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['and'][1]), pos = (2, 3))
-    
+        btn_logicsizer.Add(
+            item=self.FindWindowById(
+                self.btn_logic['brac'][1]), pos=(
+                0, 3))
+        btn_logicsizer.Add(
+            item=self.FindWindowById(
+                self.btn_logic['prc'][1]), pos=(
+                1, 3))
+        btn_logicsizer.Add(
+            item=self.FindWindowById(
+                self.btn_logic['and'][1]), pos=(
+                2, 3))
+
         self.btn_logicpanel.SetSizer(btn_logicsizer)
 
         #
         # list boxes (columns, values)
         #
         self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
-        
-        columnsbox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
-                                  label = " %s " % _("Columns"))
+
+        columnsbox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
+                                  label=" %s " % _("Columns"))
         columnsizer = wx.StaticBoxSizer(columnsbox, wx.VERTICAL)
-        self.list_columns = wx.ListBox(parent = self.panel, id = wx.ID_ANY,
-                                       choices = self.dbInfo.GetColumns(self.tablename),
-                                       style = wx.LB_MULTIPLE)
-        columnsizer.Add(item = self.list_columns, proportion = 1,
-                        flag = wx.EXPAND)
+        self.list_columns = wx.ListBox(
+            parent=self.panel,
+            id=wx.ID_ANY,
+            choices=self.dbInfo.GetColumns(
+                self.tablename),
+            style=wx.LB_MULTIPLE)
+        columnsizer.Add(item=self.list_columns, proportion=1,
+                        flag=wx.EXPAND)
 
         modesizer = wx.BoxSizer(wx.VERTICAL)
-        
-        self.mode = wx.RadioBox(parent = self.panel, id = wx.ID_ANY,
-                                label = " %s " % _("Interactive insertion"),
-                                choices = modeChoices, 
-                                style = wx.RA_SPECIFY_COLS,
-                                majorDimension = 1)
 
-        self.mode.SetSelection(1) # default 'values'
-        modesizer.Add(item = self.mode, proportion = 1,
-                      flag = wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND, border = 5)
+        self.mode = wx.RadioBox(parent=self.panel, id=wx.ID_ANY,
+                                label=" %s " % _("Interactive insertion"),
+                                choices=modeChoices,
+                                style=wx.RA_SPECIFY_COLS,
+                                majorDimension=1)
 
+        self.mode.SetSelection(1)  # default 'values'
+        modesizer.Add(item=self.mode, proportion=1,
+                      flag=wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND, border=5)
+
         # self.list_columns.SetMinSize((-1,130))
         # self.list_values.SetMinSize((-1,100))
 
-        self.valuespanel = wx.Panel(parent = self.panel, id = wx.ID_ANY)
-        valuesbox = wx.StaticBox(parent = self.valuespanel, id = wx.ID_ANY,
-                                 label = " %s " % _("Values"))
+        self.valuespanel = wx.Panel(parent=self.panel, id=wx.ID_ANY)
+        valuesbox = wx.StaticBox(parent=self.valuespanel, id=wx.ID_ANY,
+                                 label=" %s " % _("Values"))
         valuesizer = wx.StaticBoxSizer(valuesbox, wx.VERTICAL)
-        self.list_values = wx.ListBox(parent = self.valuespanel, id = wx.ID_ANY,
-                                      choices = self.colvalues,
-                                      style = wx.LB_MULTIPLE)
-        valuesizer.Add(item = self.list_values, proportion = 1,
-                       flag = wx.EXPAND)
+        self.list_values = wx.ListBox(parent=self.valuespanel, id=wx.ID_ANY,
+                                      choices=self.colvalues,
+                                      style=wx.LB_MULTIPLE)
+        valuesizer.Add(item=self.list_values, proportion=1,
+                       flag=wx.EXPAND)
         self.valuespanel.SetSizer(valuesizer)
 
-        self.btn_unique = wx.Button(parent = self.valuespanel, id = wx.ID_ANY,
-                                    label = _("Get all values"))
+        self.btn_unique = wx.Button(parent=self.valuespanel, id=wx.ID_ANY,
+                                    label=_("Get all values"))
         self.btn_unique.Enable(False)
-        self.btn_uniquesample = wx.Button(parent = self.valuespanel, id = wx.ID_ANY,
-                                          label = _("Get sample"))
-        self.btn_uniquesample.SetToolTipString(_("Get first 256 unique values as sample"))
+        self.btn_uniquesample = wx.Button(
+            parent=self.valuespanel,
+            id=wx.ID_ANY,
+            label=_("Get sample"))
+        self.btn_uniquesample.SetToolTipString(
+            _("Get first 256 unique values as sample"))
         self.btn_uniquesample.Enable(False)
 
         buttonsizer3 = wx.BoxSizer(wx.HORIZONTAL)
-        buttonsizer3.Add(item = self.btn_uniquesample, proportion = 0,
-                         flag = wx.ALIGN_CENTER_HORIZONTAL | wx.RIGHT, border = 5)
-        buttonsizer3.Add(item = self.btn_unique, proportion = 0,
-                         flag = wx.ALIGN_CENTER_HORIZONTAL)
+        buttonsizer3.Add(item=self.btn_uniquesample, proportion=0,
+                         flag=wx.ALIGN_CENTER_HORIZONTAL | wx.RIGHT, border=5)
+        buttonsizer3.Add(item=self.btn_unique, proportion=0,
+                         flag=wx.ALIGN_CENTER_HORIZONTAL)
 
-        valuesizer.Add(item = buttonsizer3, proportion = 0,
-                       flag = wx.TOP, border = 5)
+        valuesizer.Add(item=buttonsizer3, proportion=0,
+                       flag=wx.TOP, border=5)
 
         # go to
         gotosizer = wx.BoxSizer(wx.HORIZONTAL)
-        self.goto = wx.TextCtrl(parent = self.valuespanel, id = wx.ID_ANY, style = wx.TE_PROCESS_ENTER)
-        gotosizer.Add(item = wx.StaticText(parent = self.valuespanel, id = wx.ID_ANY,
-                                              label = _("Go to:")), proportion = 0,
-                      flag = wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, border = 5)
-        gotosizer.Add(item = self.goto, proportion = 1,
-                      flag = wx.EXPAND)
-        valuesizer.Add(item = gotosizer, proportion = 0,
-                       flag = wx.ALL | wx.EXPAND, border = 5)
-        
-        self.hsizer.Add(item = columnsizer, proportion = 1,
-                        flag = wx.EXPAND)
-        self.hsizer.Add(item = self.valuespanel, proportion = 1,
-                        flag = wx.EXPAND)
+        self.goto = wx.TextCtrl(
+            parent=self.valuespanel,
+            id=wx.ID_ANY,
+            style=wx.TE_PROCESS_ENTER)
+        gotosizer.Add(item=wx.StaticText(parent=self.valuespanel, id=wx.ID_ANY,
+                                         label=_("Go to:")), proportion=0,
+                      flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, border=5)
+        gotosizer.Add(item=self.goto, proportion=1,
+                      flag=wx.EXPAND)
+        valuesizer.Add(item=gotosizer, proportion=0,
+                       flag=wx.ALL | wx.EXPAND, border=5)
 
-        self.close_onapply = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
-                                         label = _("Close dialog on apply"))
+        self.hsizer.Add(item=columnsizer, proportion=1,
+                        flag=wx.EXPAND)
+        self.hsizer.Add(item=self.valuespanel, proportion=1,
+                        flag=wx.EXPAND)
+
+        self.close_onapply = wx.CheckBox(parent=self.panel, id=wx.ID_ANY,
+                                         label=_("Close dialog on apply"))
         self.close_onapply.SetValue(True)
- 
-        self.pagesizer.Add(item = databaseboxsizer,
-                           flag = wx.ALL | wx.EXPAND, border = 5)
-        self.pagesizer.Add(item = modesizer, proportion = 0,
-                           flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
-        self.pagesizer.Add(item = self.hsizer, proportion = 1,
-                           flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
+
+        self.pagesizer.Add(item=databaseboxsizer,
+                           flag=wx.ALL | wx.EXPAND, border=5)
+        self.pagesizer.Add(
+            item=modesizer,
+            proportion=0,
+            flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
+            border=5)
+        self.pagesizer.Add(
+            item=self.hsizer,
+            proportion=1,
+            flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
+            border=5)
         # self.pagesizer.Add(self.btn_uniqe,0,wx.ALIGN_LEFT|wx.TOP,border=5)
         # self.pagesizer.Add(self.btn_uniqesample,0,wx.ALIGN_LEFT|wx.TOP,border=5)
-        self.pagesizer.Add(item = self.btn_logicpanel, proportion = 0,
-                           flag = wx.ALIGN_CENTER_HORIZONTAL)
-        self.pagesizer.Add(item = sqlboxsizer, proportion = 0,
-                           flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
-        self.pagesizer.Add(item = self.buttonsizer, proportion = 0,
-                           flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
-        self.pagesizer.Add(item = self.close_onapply, proportion = 0,
-                           flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
-        
+        self.pagesizer.Add(item=self.btn_logicpanel, proportion=0,
+                           flag=wx.ALIGN_CENTER_HORIZONTAL)
+        self.pagesizer.Add(item=sqlboxsizer, proportion=0,
+                           flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5)
+        self.pagesizer.Add(item=self.buttonsizer, proportion=0,
+                           flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
+        self.pagesizer.Add(
+            item=self.close_onapply,
+            proportion=0,
+            flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
+            border=5)
+
         #
         # bindings
         #
         self.mode.Bind(wx.EVT_RADIOBOX, self.OnMode)
-        #self.text_sql.Bind(wx.EVT_ACTIVATE, self.OnTextSqlActivate)TODO
+        # self.text_sql.Bind(wx.EVT_ACTIVATE, self.OnTextSqlActivate)TODO
 
-        self.btn_unique.Bind(wx.EVT_BUTTON,       self.OnUniqueValues)
+        self.btn_unique.Bind(wx.EVT_BUTTON, self.OnUniqueValues)
         self.btn_uniquesample.Bind(wx.EVT_BUTTON, self.OnSampleValues)
-        
+
         for key, value in self.btn_logic.iteritems():
             self.FindWindowById(value[1]).Bind(wx.EVT_BUTTON, self.OnAddMark)
-                     
-        self.btn_close.Bind(wx.EVT_BUTTON,       self.OnClose)
-        self.btn_clear.Bind(wx.EVT_BUTTON,       self.OnClear)
-        self.btn_apply.Bind(wx.EVT_BUTTON,       self.OnApply)
 
-        self.list_columns.Bind(wx.EVT_LISTBOX,   self.OnAddColumn)
-        self.list_values.Bind(wx.EVT_LISTBOX,    self.OnAddValue)
-        self.goto.Bind(wx.EVT_TEXT,              self.OnGoTo)
-        self.goto.Bind(wx.EVT_TEXT_ENTER,        self.OnAddValue)
+        self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
+        self.btn_clear.Bind(wx.EVT_BUTTON, self.OnClear)
+        self.btn_apply.Bind(wx.EVT_BUTTON, self.OnApply)
 
-    def OnUniqueValues(self, event, justsample = False):
+        self.list_columns.Bind(wx.EVT_LISTBOX, self.OnAddColumn)
+        self.list_values.Bind(wx.EVT_LISTBOX, self.OnAddValue)
+        self.goto.Bind(wx.EVT_TEXT, self.OnGoTo)
+        self.goto.Bind(wx.EVT_TEXT_ENTER, self.OnAddValue)
+
+    def OnUniqueValues(self, event, justsample=False):
         """Get unique values"""
         vals = []
         try:
@@ -291,29 +352,34 @@
         except:
             self.list_values.Clear()
             return
-        
+
         self.list_values.Clear()
-        
-        data = grass.db_select(sql = "SELECT %s FROM %s" % (column, self.tablename),
-                               database = self.database,
-                               driver = self.driver, sep = '{_sep_}')
+
+        data = grass.db_select(
+            sql="SELECT %s FROM %s" %
+            (column,
+             self.tablename),
+            database=self.database,
+            driver=self.driver,
+            sep='{_sep_}')
         if not data:
             return
-        
-        desc = self.dbInfo.GetTableDesc(self.dbInfo.GetTable(self.layer))[column]
-        
+
+        desc = self.dbInfo.GetTableDesc(
+            self.dbInfo.GetTable(self.layer))[column]
+
         i = 0
         for item in sorted(set(map(lambda x: desc['ctype'](x[0]), data))):
             if justsample and i > 255:
                 break
-            
+
             if desc['type'] != 'character':
                 item = str(item)
             else:
                 item = GetUnicodeValue(item)
             self.list_values.Append(item)
             i += 1
-        
+
     def OnSampleValues(self, event):
         """Get sample values"""
         self.OnUniqueValues(None, True)
@@ -323,12 +389,12 @@
         idx = self.list_columns.GetSelections()
         for i in idx:
             column = self.list_columns.GetString(i)
-            self._add(element = 'column', value = column)
-        
+            self._add(element='column', value=column)
+
         if not self.btn_uniquesample.IsEnabled():
             self.btn_uniquesample.Enable(True)
             self.btn_unique.Enable(True)
-        
+
     def OnAddValue(self, event):
         """Add value"""
         selection = self.list_values.GetSelections()
@@ -340,19 +406,21 @@
         value = self.list_values.GetString(idx)
         idx = self.list_columns.GetSelections()[0]
         column = self.list_columns.GetString(idx)
-        
-        ctype = self.dbInfo.GetTableDesc(self.dbInfo.GetTable(self.layer))[column]['type']
-        
+
+        ctype = self.dbInfo.GetTableDesc(
+            self.dbInfo.GetTable(
+                self.layer))[column]['type']
+
         if ctype == 'character':
             value = "'%s'" % value
-        
-        self._add(element = 'value', value = value)
 
+        self._add(element='value', value=value)
+
     def OnGoTo(self, event):
         # clear all previous selections
         for item in self.list_values.GetSelections():
             self.list_values.Deselect(item)
-        
+
         gotoText = event.GetString()
         lenLimit = len(gotoText)
         found = idx = 0
@@ -364,7 +432,7 @@
 
         if found > 0:
             self.list_values.SetSelection(found)
-            
+
     def OnAddMark(self, event):
         """Add mark"""
         mark = None
@@ -372,58 +440,61 @@
            self.btn_logicpanel.IsShown():
             btns = self.btn_logic
         elif self.btn_arithmeticpanel and \
-             self.btn_arithmeticpanel.IsShown():
+                self.btn_arithmeticpanel.IsShown():
             btns = self.btn_arithmetic
-             
+
         for key, value in btns.iteritems():
             if event.GetId() == value[1]:
                 mark = value[0]
                 break
-        
-        self._add(element = 'mark', value = mark)
 
+        self._add(element='mark', value=mark)
+
     def GetSQLStatement(self):
         """Return SQL statement"""
-        return self.text_sql.GetValue().strip().replace("\n"," ")
-        
+        return self.text_sql.GetValue().strip().replace("\n", " ")
+
     def OnClose(self, event):
         self.Destroy()
         event.Skip()
- 
+
+
 class SQLBuilderSelect(SQLBuilder):
     """Class for building SELECT SQL statement"""
-    def __init__(self, parent, vectmap, id = wx.ID_ANY,
-                 layer = 1, evtHandler = None):
 
+    def __init__(self, parent, vectmap, id=wx.ID_ANY,
+                 layer=1, evtHandler=None):
+
         self.evtHandler = evtHandler
 
         # set dialog title
         title = _("GRASS SQL Builder (%(type)s) - <%(map)s>") % \
-                 { 'type' : "SELECT", 'map' : vectmap }
+            {'type': "SELECT", 'map': vectmap}
 
-        modeChoices = [_("Column to show (SELECT clause)"), 
+        modeChoices = [_("Column to show (SELECT clause)"),
                        _("Constraint for query (WHERE clause)")]
 
-        SQLBuilder.__init__(self, parent, title, vectmap, id = wx.ID_ANY,
-                            modeChoices = modeChoices, layer = layer)
+        SQLBuilder.__init__(self, parent, title, vectmap, id=wx.ID_ANY,
+                            modeChoices=modeChoices, layer=layer)
 
-
     def _doLayout(self, modeChoices):
         """Do dialog layout"""
 
         SQLBuilder._doLayout(self, modeChoices)
 
         self.text_sql.SetValue("SELECT * FROM %s" % self.tablename)
-        self.text_sql.SetToolTipString(_("Example: %s") % "SELECT * FROM roadsmajor WHERE MULTILANE = 'no' OR OBJECTID < 10")
+        self.text_sql.SetToolTipString(
+            _("Example: %s") %
+            "SELECT * FROM roadsmajor WHERE MULTILANE = 'no' OR OBJECTID < 10")
 
-        self.btn_verify = wx.Button(parent = self.panel, id = wx.ID_ANY,
-                                    label = _("Verify"))
+        self.btn_verify = wx.Button(parent=self.panel, id=wx.ID_ANY,
+                                    label=_("Verify"))
         self.btn_verify.SetToolTipString(_("Verify SQL statement"))
 
-        self.buttonsizer.Insert(item = self.btn_verify, before = 1)
-        
+        self.buttonsizer.Insert(item=self.btn_verify, before=1)
+
         self.text_sql.Bind(wx.EVT_TEXT, self.OnText)
-        self.btn_verify.Bind(wx.EVT_BUTTON,      self.OnVerify)
+        self.btn_verify.Bind(wx.EVT_BUTTON, self.OnVerify)
 
         self.text_sql.SetInsertionPoint(self.text_sql.GetLastPosition())
         self.statusbar.SetStatusText(_("SQL statement not verified"), 0)
@@ -431,11 +502,11 @@
     def OnApply(self, event):
         """Apply button pressed"""
         if self.evtHandler:
-            self.evtHandler(event = 'apply')
-        
+            self.evtHandler(event='apply')
+
         if self.close_onapply.IsChecked():
             self.Destroy()
-            
+
         event.Skip()
 
     def OnClear(self, event):
@@ -448,8 +519,8 @@
             self.valuespanel.Hide()
             self.btn_logicpanel.Hide()
         elif self.mode.GetSelection() == 1:
-             self.valuespanel.Show()
-             self.btn_logicpanel.Show()
+            self.valuespanel.Show()
+            self.btn_logicpanel.Show()
         self.pagesizer.Layout()
 
     def OnText(self, event):
@@ -458,21 +529,21 @@
             self.btn_verify.Enable(True)
         else:
             self.btn_verify.Enable(False)
-            
+
     def OnVerify(self, event):
         """Verify button pressed"""
         ret, msg = RunCommand('db.select',
-                              getErrorMsg = True,
-                              table = self.tablename,
-                              sql = self.text_sql.GetValue(),
-                              flags = 't',
-                              driver = self.driver,
-                              database = self.database)
-        
+                              getErrorMsg=True,
+                              table=self.tablename,
+                              sql=self.text_sql.GetValue(),
+                              flags='t',
+                              driver=self.driver,
+                              database=self.database)
+
         if ret != 0 and msg:
             self.statusbar.SetStatusText(_("SQL statement is not valid"), 0)
-            GError(parent = self,
-                   message = _("SQL statement is not valid.\n\n%s") % msg)
+            GError(parent=self,
+                   message=_("SQL statement is not valid.\n\n%s") % msg)
         else:
             self.statusbar.SetStatusText(_("SQL statement is valid"), 0)
 
@@ -485,7 +556,7 @@
         curspos = self.text_sql.GetInsertionPoint()
         newsqlstr = ''
         if element == 'column':
-            if self.mode.GetSelection() == 0: # -> column
+            if self.mode.GetSelection() == 0:  # -> column
                 idx1 = len('select')
                 idx2 = sqlstr.lower().find('from')
                 colstr = sqlstr[idx1:idx2].strip()
@@ -494,28 +565,28 @@
                 else:
                     cols = colstr.split(',')
                 if value in cols:
-                        cols.remove(value)
+                    cols.remove(value)
                 else:
                     cols.append(value)
-                
+
                 if len(cols) < 1:
-                    cols = ['*',]  
+                    cols = ['*', ]
                 newsqlstr = 'SELECT ' + ','.join(cols) + ' '
                 curspos = len(newsqlstr)
                 newsqlstr += sqlstr[idx2:]
-            else: # -> where
+            else:  # -> where
                 newsqlstr = ''
                 if sqlstr.lower().find('where') < 0:
-                    newsqlstr += ' WHERE'       
+                    newsqlstr += ' WHERE'
                 newsqlstr += ' ' + value
                 curspos = self.text_sql.GetLastPosition() + len(newsqlstr)
                 newsqlstr = sqlstr + newsqlstr
 
-        elif element in  ['value', 'mark']:
+        elif element in ['value', 'mark']:
             addstr = ' ' + value + ' '
             newsqlstr = sqlstr[:curspos] + addstr + sqlstr[curspos:]
             curspos += len(addstr)
-        
+
         if newsqlstr:
             self.text_sql.SetValue(newsqlstr)
 
@@ -529,30 +600,32 @@
     def OnClose(self, event):
         """Close button pressed"""
         if self.evtHandler:
-            self.evtHandler(event = 'close')
-    
+            self.evtHandler(event='close')
+
         SQLBuilder.OnClose(self, event)
 
+
 class SQLBuilderUpdate(SQLBuilder):
     """Class for building UPDATE SQL statement"""
-    def __init__(self, parent, vectmap, id = wx.ID_ANY,
-                 layer = 1, column = None):
 
-        self.column = column 
+    def __init__(self, parent, vectmap, id=wx.ID_ANY,
+                 layer=1, column=None):
+
+        self.column = column
         # set dialog title
         title = _("GRASS SQL Builder (%(type)s) - <%(map)s>") % \
-                 { 'type' : "UPDATE", 'map' : vectmap }
+            {'type': "UPDATE", 'map': vectmap}
 
-        modeChoices = [_("Column to set (SET clause)"), 
-                       _("Constraint for query (WHERE clause)"), 
+        modeChoices = [_("Column to set (SET clause)"),
+                       _("Constraint for query (WHERE clause)"),
                        _("Calculate column value to set")]
 
-        SQLBuilder.__init__(self, parent, title, vectmap, id = wx.ID_ANY,
-                            modeChoices = modeChoices, layer = layer)
+        SQLBuilder.__init__(self, parent, title, vectmap, id=wx.ID_ANY,
+                            modeChoices=modeChoices, layer=layer)
 
         # signals
         self.sqlApplied = Signal("SQLBuilder.sqlApplied")
-        if parent: # TODO: replace by giface
+        if parent:  # TODO: replace by giface
             self.sqlApplied.connect(parent.Update)
 
     def _doLayout(self, modeChoices):
@@ -562,61 +635,78 @@
 
         self.initText = "UPDATE %s SET" % self.tablename
         if self.column:
-            self.initText += " %s = " % self.column 
+            self.initText += " %s = " % self.column
 
         self.text_sql.SetValue(self.initText)
 
-        self.btn_arithmetic = { 'eq'        : ['=', ],
-                                'brac'      : ['()',],
-                                'plus'      : ['+', ],
-                                'minus'     : ['-', ],
-                                'divide'    : ['/', ],
-                                'multiply'  : ['*', ]} 
+        self.btn_arithmetic = {'eq': ['=', ],
+                               'brac': ['()', ],
+                               'plus': ['+', ],
+                               'minus': ['-', ],
+                               'divide': ['/', ],
+                               'multiply': ['*', ]}
 
-        self.btn_arithmeticpanel = wx.Panel(parent = self.panel, id = wx.ID_ANY)
+        self.btn_arithmeticpanel = wx.Panel(parent=self.panel, id=wx.ID_ANY)
 
         for key, value in self.btn_arithmetic.iteritems():
-            btn = wx.Button(parent = self.btn_arithmeticpanel, id = wx.ID_ANY,
-                            label = value[0])
+            btn = wx.Button(parent=self.btn_arithmeticpanel, id=wx.ID_ANY,
+                            label=value[0])
             self.btn_arithmetic[key].append(btn.GetId())
 
-        btn_arithmeticsizer = wx.GridBagSizer(hgap = 5, vgap = 5)
+        btn_arithmeticsizer = wx.GridBagSizer(hgap=5, vgap=5)
 
-        btn_arithmeticsizer.Add(item = self.FindWindowById(self.btn_arithmetic['eq'][1]), pos = (0, 0))
-        btn_arithmeticsizer.Add(item = self.FindWindowById(self.btn_arithmetic['brac'][1]), pos = (1, 0))
+        btn_arithmeticsizer.Add(
+            item=self.FindWindowById(
+                self.btn_arithmetic['eq'][1]), pos=(
+                0, 0))
+        btn_arithmeticsizer.Add(
+            item=self.FindWindowById(
+                self.btn_arithmetic['brac'][1]), pos=(
+                1, 0))
 
-        btn_arithmeticsizer.Add(item = self.FindWindowById(self.btn_arithmetic['plus'][1]), pos = (0, 1))
-        btn_arithmeticsizer.Add(item = self.FindWindowById(self.btn_arithmetic['minus'][1]), pos = (1, 1))
+        btn_arithmeticsizer.Add(
+            item=self.FindWindowById(
+                self.btn_arithmetic['plus'][1]), pos=(
+                0, 1))
+        btn_arithmeticsizer.Add(
+            item=self.FindWindowById(
+                self.btn_arithmetic['minus'][1]), pos=(
+                1, 1))
 
-        btn_arithmeticsizer.Add(item = self.FindWindowById(self.btn_arithmetic['divide'][1]), pos = (0, 2))
-        btn_arithmeticsizer.Add(item = self.FindWindowById(self.btn_arithmetic['multiply'][1]), pos = (1, 2))
+        btn_arithmeticsizer.Add(
+            item=self.FindWindowById(
+                self.btn_arithmetic['divide'][1]), pos=(
+                0, 2))
+        btn_arithmeticsizer.Add(
+            item=self.FindWindowById(
+                self.btn_arithmetic['multiply'][1]), pos=(
+                1, 2))
 
         self.btn_arithmeticpanel.SetSizer(btn_arithmeticsizer)
 
-        self.pagesizer.Insert(item = self.btn_arithmeticpanel, before = 3,
-                              proportion = 0, flag = wx.ALIGN_CENTER_HORIZONTAL)       
+        self.pagesizer.Insert(item=self.btn_arithmeticpanel, before=3,
+                              proportion=0, flag=wx.ALIGN_CENTER_HORIZONTAL)
 
-
-        self.funcpanel = wx.Panel(parent = self.panel, id = wx.ID_ANY)
+        self.funcpanel = wx.Panel(parent=self.panel, id=wx.ID_ANY)
         self._initSqlFunctions()
-        funcsbox = wx.StaticBox(parent = self.funcpanel, id = wx.ID_ANY,
-                                label = " %s " % _("Functions"))
+        funcsbox = wx.StaticBox(parent=self.funcpanel, id=wx.ID_ANY,
+                                label=" %s " % _("Functions"))
         funcsizer = wx.StaticBoxSizer(funcsbox, wx.VERTICAL)
-        self.list_func = wx.ListBox(parent = self.funcpanel, id = wx.ID_ANY,
-                                    choices = self.sqlFuncs['sqlite'].keys(),
-                                    style = wx.LB_SORT)
+        self.list_func = wx.ListBox(parent=self.funcpanel, id=wx.ID_ANY,
+                                    choices=self.sqlFuncs['sqlite'].keys(),
+                                    style=wx.LB_SORT)
 
-        funcsizer.Add(item = self.list_func, proportion = 1,
-                      flag = wx.EXPAND)
+        funcsizer.Add(item=self.list_func, proportion=1,
+                      flag=wx.EXPAND)
 
         self.funcpanel.SetSizer(funcsizer)
 
-        self.hsizer.Insert(item =  self.funcpanel, before = 2,
-                          proportion = 1, flag = wx.EXPAND) 
+        self.hsizer.Insert(item=self.funcpanel, before=2,
+                           proportion=1, flag=wx.EXPAND)
 
-        self.list_func.Bind(wx.EVT_LISTBOX,    self.OnAddFunc)
+        self.list_func.Bind(wx.EVT_LISTBOX, self.OnAddFunc)
         for key, value in self.btn_arithmetic.iteritems():
-            self.FindWindowById(value[1]).Bind(wx.EVT_BUTTON, self.OnAddMark)  
+            self.FindWindowById(value[1]).Bind(wx.EVT_BUTTON, self.OnAddMark)
         self.mode.SetSelection(0)
         self.OnMode(None)
         self.text_sql.SetInsertionPoint(self.text_sql.GetLastPosition())
@@ -625,18 +715,18 @@
         """Apply button pressed"""
 
         ret, msg = RunCommand('db.execute',
-                             getErrorMsg = True,
-                             parent = self,
-                             stdin = self.text_sql.GetValue(),
-                             input = '-',
-                             driver = self.driver,
-                             database = self.database)
+                              getErrorMsg=True,
+                              parent=self,
+                              stdin=self.text_sql.GetValue(),
+                              input='-',
+                              driver=self.driver,
+                              database=self.database)
 
         if ret != 0 and msg:
             self.statusbar.SetStatusText(_("SQL statement was not applied"), 0)
         else:
             self.statusbar.SetStatusText(_("SQL statement applied"), 0)
-        
+
         self.sqlApplied.emit()
 
     def OnClear(self, event):
@@ -651,31 +741,31 @@
             self.btn_arithmeticpanel.Hide()
             self.funcpanel.Hide()
         elif self.mode.GetSelection() == 1:
-             self.valuespanel.Show()
-             self.btn_logicpanel.Show()
-             self.btn_arithmeticpanel.Hide()
-             self.funcpanel.Hide()       
+            self.valuespanel.Show()
+            self.btn_logicpanel.Show()
+            self.btn_arithmeticpanel.Hide()
+            self.funcpanel.Hide()
         elif self.mode.GetSelection() == 2:
-             self.valuespanel.Hide()
-             self.btn_logicpanel.Hide()
-             self.btn_arithmeticpanel.Show()
-             self.funcpanel.Show()
+            self.valuespanel.Hide()
+            self.btn_logicpanel.Hide()
+            self.btn_arithmeticpanel.Show()
+            self.funcpanel.Show()
         self.pagesizer.Layout()
 
-
     def OnAddFunc(self, event):
         """Add function to the query"""
 
         if self.driver == 'dbf':
-            GMessage(parent = self,
-                     message = _("Dbf driver does not support usage of SQL functions."))
+            GMessage(
+                parent=self,
+                message=_(
+                    "Dbf driver does not support usage of SQL functions."))
             return
 
         idx = self.list_func.GetSelections()
         for i in idx:
-            func =  self.sqlFuncs['sqlite'][self.list_func.GetString(i)][0]
-            self._add(element = 'func', value = func)
-        
+            func = self.sqlFuncs['sqlite'][self.list_func.GetString(i)][0]
+            self._add(element='func', value=func)
 
     def _add(self, element, value):
         """Add element to the query
@@ -687,41 +777,41 @@
         newsqlstr = ''
 
         if element in  ['value', 'mark', 'func'] or \
-          (element == 'column' and self.mode.GetSelection() == 2):
+                (element == 'column' and self.mode.GetSelection() == 2):
             addstr = ' ' + value + ' '
             newsqlstr = sqlstr[:curspos] + addstr + sqlstr[curspos:]
             curspos += len(addstr)
         elif element == 'column':
-            if self.mode.GetSelection() == 0: # -> column
+            if self.mode.GetSelection() == 0:  # -> column
                 idx1 = sqlstr.lower().find('set') + len('set')
                 idx2 = sqlstr.lower().find('where')
 
-                if idx2 >= 0: 
+                if idx2 >= 0:
                     colstr = sqlstr[idx1:idx2].strip()
                 else:
                     colstr = sqlstr[idx1:].strip()
- 
-                cols =  [col.split('=')[0].strip() for col in colstr.split(',')]
+
+                cols = [col.split('=')[0].strip() for col in colstr.split(',')]
                 if unicode(value) in cols:
                     self.text_sql.SetInsertionPoint(curspos)
-                    wx.CallAfter(self.text_sql.SetFocus)           
+                    wx.CallAfter(self.text_sql.SetFocus)
                     return
                 if colstr:
                     colstr += ','
                 colstr = ' ' + colstr
                 colstr += ' ' + value + '= '
                 newsqlstr = sqlstr[:idx1] + colstr
-                if idx2 >= 0: 
+                if idx2 >= 0:
                     newsqlstr += sqlstr[idx2:]
                 curspos = idx1 + len(colstr)
 
-            elif  self.mode.GetSelection() == 1: # -> where
+            elif self.mode.GetSelection() == 1:  # -> where
                 newsqlstr = ''
                 if sqlstr.lower().find('where') < 0:
                     newsqlstr += ' WHERE'
                 newsqlstr += ' ' + value
                 curspos = self.text_sql.GetLastPosition() + len(newsqlstr)
-                newsqlstr = sqlstr + newsqlstr              
+                newsqlstr = sqlstr + newsqlstr
 
         if newsqlstr:
             self.text_sql.SetValue(newsqlstr)
@@ -734,22 +824,22 @@
         self.sqlFuncs = {}
         # TODO add functions for other drivers
         self.sqlFuncs['sqlite'] = {
-                                 'ABS'   : ['ABS()'],
-                                 'LENGTH'   : ['LENGTH()'],
-                                 'LOWER'   : ['LOWER()'],
-                                 'LTRIM'   : ['LTRIM(,)'],
-                                 'MAX'   : ['MAX()'],
-                                 'MIN'   : ['MIN()'],
-                                 'RTRIM'   : ['RTRIM(,)'],
-                                 'SUBSTR' : ['SUBSTR (,[,])'],                         
-                                 'TRIM' : ['TRIM (,)']                            
-                                }
+            'ABS': ['ABS()'],
+            'LENGTH': ['LENGTH()'],
+            'LOWER': ['LOWER()'],
+            'LTRIM': ['LTRIM(,)'],
+            'MAX': ['MAX()'],
+            'MIN': ['MIN()'],
+            'RTRIM': ['RTRIM(,)'],
+            'SUBSTR': ['SUBSTR (,[,])'],
+            'TRIM': ['TRIM (,)']
+        }
 
 if __name__ == "__main__":
     if len(sys.argv) not in [3, 4]:
         print >>sys.stderr, __doc__
         sys.exit()
-    
+
     if len(sys.argv) == 3:
         layer = 1
     else:
@@ -764,7 +854,7 @@
         sys.exit()
 
     app = wx.App(0)
-    sqlb = sqlBuilder(parent = None, vectmap = sys.argv[2], layer = layer)
+    sqlb = sqlBuilder(parent=None, vectmap=sys.argv[2], layer=layer)
     sqlb.Show()
-      
+
     app.MainLoop()

Modified: grass/trunk/gui/wxpython/dbmgr/vinfo.py
===================================================================
--- grass/trunk/gui/wxpython/dbmgr/vinfo.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/dbmgr/vinfo.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -20,11 +20,12 @@
 import wx
 
 from gui_core.gselect import VectorDBInfo as VectorDBInfoBase
-from core.gcmd        import RunCommand, GError
-from core.settings    import UserSettings
+from core.gcmd import RunCommand, GError
+from core.settings import UserSettings
 from core.utils import _
 import grass.script as grass
 
+
 def GetUnicodeValue(value):
     """Get unicode value
 
@@ -32,57 +33,69 @@
 
     :return: unicode value
     """
-    if type(value) == types.UnicodeType:
+    if isinstance(value, types.UnicodeType):
         return value
-    
-    enc = UserSettings.Get(group = 'atm', key = 'encoding', subkey = 'value')
+
+    enc = UserSettings.Get(group='atm', key='encoding', subkey='value')
     if not enc and 'GRASS_DB_ENCODING' in os.environ:
         enc = os.environ['GRASS_DB_ENCODING']
     else:
-        enc = 'utf-8' # assuming UTF-8
-    
-    return unicode(str(value), enc, errors = 'replace')
+        enc = 'utf-8'  # assuming UTF-8
 
+    return unicode(str(value), enc, errors='replace')
+
+
 def CreateDbInfoDesc(panel, mapDBInfo, layer):
     """Create database connection information content"""
-    infoFlexSizer = wx.FlexGridSizer (cols = 2, hgap = 1, vgap = 1)
+    infoFlexSizer = wx.FlexGridSizer(cols=2, hgap=1, vgap=1)
     infoFlexSizer.AddGrowableCol(1)
-    
-    infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = "Driver:"))
-    infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = mapDBInfo.layers[layer]['driver']))
-    infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = "Database:"))
-    infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = mapDBInfo.layers[layer]['database']))
-    infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = "Table:"))
-    infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = mapDBInfo.layers[layer]['table']))
-    infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = "Key:"))
-    infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = mapDBInfo.layers[layer]['key']))
-    
+
+    infoFlexSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label="Driver:"))
+    infoFlexSizer.Add(
+        item=wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=mapDBInfo.layers[layer]['driver']))
+    infoFlexSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label="Database:"))
+    infoFlexSizer.Add(
+        item=wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=mapDBInfo.layers[layer]['database']))
+    infoFlexSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label="Table:"))
+    infoFlexSizer.Add(
+        item=wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=mapDBInfo.layers[layer]['table']))
+    infoFlexSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label="Key:"))
+    infoFlexSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=mapDBInfo.layers[layer]['key']))
+
     return infoFlexSizer
-        
+
+
 class VectorDBInfo(VectorDBInfoBase):
     """Class providing information about attribute tables
     linked to the vector map"""
+
     def __init__(self, map):
         VectorDBInfoBase.__init__(self, map)
-        
+
     def GetColumns(self, table):
         """Return list of columns names (based on their index)"""
         try:
             names = [''] * len(self.tables[table].keys())
         except KeyError:
             return []
-        
+
         for name, desc in self.tables[table].iteritems():
             names[desc['index']] = name
-        
+
         return names
 
     def SelectByPoint(self, queryCoords, qdist):
@@ -93,17 +106,21 @@
         nselected = 0
 
         try:
-            data = grass.vector_what(map=self.map,
-                                     coord=(float(queryCoords[0]), float(queryCoords[1])),
-                                     distance=float(qdist))
+            data = grass.vector_what(
+                map=self.map, coord=(
+                    float(
+                        queryCoords[0]), float(
+                        queryCoords[1])), distance=float(qdist))
         except grass.ScriptError:
-            GError(parent=None,
-                   message=_("Failed to query vector map <{map}>. "
-                             "Check database settings and topology.").format(map=self.map))
+            GError(
+                parent=None, message=_(
+                    "Failed to query vector map <{map}>. "
+                    "Check database settings and topology.").format(
+                    map=self.map))
 
         if len(data) < 1 or all(('Table' not in record) for record in data):
             return None
-        
+
         # process attributes
         ret = dict()
         for key in ['Category', 'Layer', 'Table', 'Id']:
@@ -119,11 +136,11 @@
                     value = None
                 else:
                     if self.tables[table][key]['ctype'] != types.StringType:
-                        value = self.tables[table][key]['ctype'] (value)
+                        value = self.tables[table][key]['ctype'](value)
                     else:
                         value = GetUnicodeValue(value)
                 self.tables[table][key]['values'].append(value)
-            
+
             for key, value in record.iteritems():
                 if key == 'Attributes':
                     continue
@@ -133,8 +150,8 @@
                 ret['Id'].append(None)
 
         return ret
-    
-    def SelectFromTable(self, layer, cols = '*', where = None):
+
+    def SelectFromTable(self, layer, cols='*', where=None):
         """Select records from the table
 
         Return number of selected records, -1 on error
@@ -144,29 +161,29 @@
 
         nselected = 0
 
-        table = self.layers[layer]["table"] # get table desc
+        table = self.layers[layer]["table"]  # get table desc
         # select values (only one record)
         if where is None or where is '':
             sql = "SELECT %s FROM %s" % (cols, table)
         else:
             sql = "SELECT %s FROM %s WHERE %s" % (cols, table, where)
-        
+
         ret = RunCommand('db.select',
-                         read = True,
-                         quiet = True,
-                         flags = 'v',
-                         sql= sql,
-                         database = self.layers[layer]["database"],
-                         driver = self.layers[layer]["driver"])
-        
+                         read=True,
+                         quiet=True,
+                         flags='v',
+                         sql=sql,
+                         database=self.layers[layer]["database"],
+                         driver=self.layers[layer]["driver"])
+
         # self.tables[table][key][1] = str(cat)
         if ret:
             for line in ret.splitlines():
                 name, value = line.split('|')
                 # casting ...
                 if value:
-                    if self.tables[table][name]['ctype'] != type(''):
-                        value = self.tables[table][name]['ctype'] (value)
+                    if not isinstance('', self.tables[table][name]['ctype']):
+                        value = self.tables[table][name]['ctype'](value)
                     else:
                         value = GetUnicodeValue(value)
                 else:

Modified: grass/trunk/gui/wxpython/docs/wxgui_sphinx/conf.py
===================================================================
--- grass/trunk/gui/wxpython/docs/wxgui_sphinx/conf.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/docs/wxgui_sphinx/conf.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -12,7 +12,8 @@
 # All configuration values have a default; values that are commented out
 # serve to show the default.
 
-import sys, os
+import sys
+import os
 from datetime import date
 import string
 from shutil import copy
@@ -22,12 +23,19 @@
 # documentation root, use os.path.abspath to make it absolute, like shown here.
 if not os.getenv('GISBASE'):
     sys.exit("GISBASE not defined")
-sys.path.insert(0, os.path.abspath(os.path.join(os.environ['GISBASE'], 'etc', 'python', 'grass')))
+sys.path.insert(
+    0,
+    os.path.abspath(
+        os.path.join(
+            os.environ['GISBASE'],
+            'etc',
+            'python',
+            'grass')))
 
 from grass.script import core
 
-footer_tmpl = string.Template(\
-r"""
+footer_tmpl = string.Template(
+    r"""
 {% block footer %}<hr class="header">
 <p><a href="../index.html">Help Index</a> | <a href="../topics.html">Topics Index</a> | <a href="../keywords.html">Keywords Index</a> | <a href="../full_index.html">Full Index</a></p>
 <p>© 2003-${year} <a href="http://grass.osgeo.org">GRASS Development Team</a>, GRASS GIS ${grass_version} Reference Manual</p>
@@ -39,10 +47,13 @@
 
 copy("_templates/layout.html.template", "_templates/layout.html")
 with open("_templates/layout.html", "a+b") as f:
-    f.write(footer_tmpl.substitute(grass_version=grass_version, year=today.year))
+    f.write(
+        footer_tmpl.substitute(
+            grass_version=grass_version,
+            year=today.year))
     f.close()
 
-# -- General configuration -----------------------------------------------------
+# -- General configuration -----------------------------------------------
 
 # If your documentation needs a minimal Sphinx version, state it here.
 #needs_sphinx = '1.0'
@@ -174,7 +185,7 @@
 #html_use_smartypants = True
 
 # Custom sidebar templates, maps document names to template names.
-html_sidebars = {"**":["localtoc.html",'relations.html','searchbox.html']}
+html_sidebars = {"**": ["localtoc.html", 'relations.html', 'searchbox.html']}
 
 # Additional templates that should be rendered to pages, maps page names to
 # template names.
@@ -213,22 +224,22 @@
 # -- Options for LaTeX output ---------------------------------------------
 
 latex_elements = {
-# The paper size ('letterpaper' or 'a4paper').
-'papersize': 'a4paper',
+    # The paper size ('letterpaper' or 'a4paper').
+    'papersize': 'a4paper',
 
-# The font size ('10pt', '11pt' or '12pt').
-'pointsize': '10pt',
+    # The font size ('10pt', '11pt' or '12pt').
+    'pointsize': '10pt',
 
-# Additional stuff for the LaTeX preamble.
-#'preamble': '',
+    # Additional stuff for the LaTeX preamble.
+    #'preamble': '',
 }
 
 # Grouping the document tree into LaTeX files. List of tuples
 # (source start file, target name, title,
 #  author, documentclass [howto, manual, or own class]).
 latex_documents = [
-  ('index', 'wxGUI.tex', u'wxGUI Documentation',
-   u'GRASS Development Team', 'manual'),
+    ('index', 'wxGUI.tex', u'wxGUI Documentation',
+     u'GRASS Development Team', 'manual'),
 ]
 
 # The name of an image file (relative to this directory) to place at the top of
@@ -271,9 +282,9 @@
 # (source start file, target name, title, author,
 #  dir menu entry, description, category)
 texinfo_documents = [
-  ('index', 'wxGUI', u'wxGUI Documentation',
-   u'GRASS Development Team', 'wxGUI', 'One line description of project.',
-   'Miscellaneous'),
+    ('index', 'wxGUI', u'wxGUI Documentation',
+     u'GRASS Development Team', 'wxGUI', 'One line description of project.',
+     'Miscellaneous'),
 ]
 
 # Documents to append as an appendix to all manuals.

Modified: grass/trunk/gui/wxpython/gcp/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/gcp/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gcp/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -2,4 +2,4 @@
     'manager',
     'mapdisplay',
     'toolbars',
-    ]
+]

Modified: grass/trunk/gui/wxpython/gcp/g.gui.gcp.py
===================================================================
--- grass/trunk/gui/wxpython/gcp/g.gui.gcp.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gcp/g.gui.gcp.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -47,10 +47,10 @@
     options, flags = gscript.parser()
 
     import wx
-    
+
     from grass.script.setup import set_gui_path
     set_gui_path()
-    
+
     from core.settings import UserSettings
     from core.globalvar import CheckWxVersion
     from core.giface import StandaloneGrassInterface

Modified: grass/trunk/gui/wxpython/gcp/manager.py
===================================================================
--- grass/trunk/gui/wxpython/gcp/manager.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gcp/manager.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -35,22 +35,22 @@
 import wx
 from wx.lib.mixins.listctrl import CheckListCtrlMixin, ColumnSorterMixin, ListCtrlAutoWidthMixin
 import wx.lib.colourselect as csel
-import wx.wizard           as wiz
+import wx.wizard as wiz
 
 import grass.script as grass
 
-from core              import globalvar
-from core              import utils
-from core.render       import Map
+from core import globalvar
+from core import utils
+from core.render import Map
 from core.utils import _
-from gui_core.gselect  import Select, LocationSelect, MapsetSelect
-from gui_core.dialogs  import GroupDialog
-from core.gcmd         import RunCommand, GMessage, GError, GWarning, EncodeString
-from core.settings     import UserSettings
-from gcp.mapdisplay    import MapFrame
+from gui_core.gselect import Select, LocationSelect, MapsetSelect
+from gui_core.dialogs import GroupDialog
+from core.gcmd import RunCommand, GMessage, GError, GWarning, EncodeString
+from core.settings import UserSettings
+from gcp.mapdisplay import MapFrame
 from core.giface import Notification
 
-from location_wizard.wizard   import TitledPage as TitledPage
+from location_wizard.wizard import TitledPage as TitledPage
 
 #
 # global variables
@@ -60,10 +60,11 @@
 global maptype
 
 src_map = ''
-tgt_map = { 'raster' : '',
-            'vector' : '' }
+tgt_map = {'raster': '',
+           'vector': ''}
 maptype = 'raster'
 
+
 def getSmallUpArrowImage():
     stream = open(os.path.join(globalvar.IMGDIR, 'small_up_arrow.png'), 'rb')
     try:
@@ -72,6 +73,7 @@
         stream.close()
     return img
 
+
 def getSmallDnArrowImage():
     stream = open(os.path.join(globalvar.IMGDIR, 'small_down_arrow.png'), 'rb')
     try:
@@ -81,20 +83,21 @@
     stream.close()
     return img
 
+
 class GCPWizard(object):
     """
     Start wizard here and finish wizard here
     """
 
     def __init__(self, parent, giface):
-        self.parent = parent # GMFrame
+        self.parent = parent  # GMFrame
         self._giface = giface
 
         #
         # get environmental variables
         #
         self.grassdatabase = grass.gisenv()['GISDBASE']
-        
+
         #
         # read original environment settings
         #
@@ -110,13 +113,13 @@
                 self.gisrc_dict[key.strip()] = value.strip()
         finally:
             f.close()
-            
+
         self.currentlocation = self.gisrc_dict['LOCATION_NAME']
         self.currentmapset = self.gisrc_dict['MAPSET']
         # location for xy map to georectify
         self.newlocation = ''
         # mapset for xy map to georectify
-        self.newmapset = '' 
+        self.newmapset = ''
 
         global maptype
         global src_map
@@ -133,7 +136,10 @@
         #
         # define wizard pages
         #
-        self.wizard = wiz.Wizard(parent=parent, id=wx.ID_ANY, title=_("Setup for georectification"))
+        self.wizard = wiz.Wizard(
+            parent=parent,
+            id=wx.ID_ANY,
+            title=_("Setup for georectification"))
         self.startpage = LocationPage(self.wizard, self)
         self.grouppage = GroupPage(self.wizard, self)
         self.mappage = DispMapPage(self.wizard, self)
@@ -165,12 +171,12 @@
         if self.wizard.RunWizard(self.startpage):
             success = self.OnWizFinished()
             if success == False:
-                GMessage(parent = self.parent,
-                         message = _("Georectifying setup canceled."))
+                GMessage(parent=self.parent,
+                         message=_("Georectifying setup canceled."))
                 self.Cleanup()
         else:
-            GMessage(parent = self.parent,
-                     message = _("Georectifying setup canceled."))
+            GMessage(parent=self.parent,
+                     message=_("Georectifying setup canceled."))
             self.Cleanup()
 
         #
@@ -179,25 +185,31 @@
         if success != False:
             # instance of render.Map to be associated with display
             self.SwitchEnv('source')
-            self.SrcMap = Map(gisrc=self.source_gisrc) 
+            self.SrcMap = Map(gisrc=self.source_gisrc)
             self.SwitchEnv('target')
             self.TgtMap = Map(gisrc=self.target_gisrc)
             self.Map = self.SrcMap
-            
+
             #
             # add layer to source map
             #
             if maptype == 'raster':
                 rendertype = 'raster'
                 cmdlist = ['d.rast', 'map=%s' % src_map]
-            else: # -> vector layer
+            else:  # -> vector layer
                 rendertype = 'vector'
                 cmdlist = ['d.vect', 'map=%s' % src_map]
-            
+
             self.SwitchEnv('source')
             name, found = utils.GetLayerNameFromCmd(cmdlist)
-            self.SrcMap.AddLayer(ltype=rendertype, command=cmdlist, active=True,
-                                 name=name, hidden=False, opacity=1.0, render=False)
+            self.SrcMap.AddLayer(
+                ltype=rendertype,
+                command=cmdlist,
+                active=True,
+                name=name,
+                hidden=False,
+                opacity=1.0,
+                render=False)
 
             self.SwitchEnv('target')
             if tgt_map['raster']:
@@ -206,26 +218,38 @@
                 #
                 rendertype = 'raster'
                 cmdlist = ['d.rast', 'map=%s' % tgt_map['raster']]
-                
+
                 name, found = utils.GetLayerNameFromCmd(cmdlist)
-                self.TgtMap.AddLayer(ltype=rendertype, command=cmdlist, active=True,
-                                     name=name, hidden=False, opacity=1.0, render=False)
-            
+                self.TgtMap.AddLayer(
+                    ltype=rendertype,
+                    command=cmdlist,
+                    active=True,
+                    name=name,
+                    hidden=False,
+                    opacity=1.0,
+                    render=False)
+
             if tgt_map['vector']:
                 #
                 # add raster layer to target map
                 #
                 rendertype = 'vector'
                 cmdlist = ['d.vect', 'map=%s' % tgt_map['vector']]
-                
+
                 name, found = utils.GetLayerNameFromCmd(cmdlist)
-                self.TgtMap.AddLayer(ltype=rendertype, command=cmdlist, active=True,
-                                     name=name, hidden=False, opacity=1.0, render=False)
-            
+                self.TgtMap.AddLayer(
+                    ltype=rendertype,
+                    command=cmdlist,
+                    active=True,
+                    name=name,
+                    hidden=False,
+                    opacity=1.0,
+                    render=False)
+
             #
             # start GCP Manager
             #
-            self.gcpmgr = GCP(self.parent, giface = self._giface, 
+            self.gcpmgr = GCP(self.parent, giface=self._giface,
                               grwiz=self, size=globalvar.MAP_WINDOW_SIZE,
                               toolbars=["gcpdisp"],
                               Map=self.SrcMap, lmgr=self.parent)
@@ -238,7 +262,7 @@
             self.gcpmgr._mgr.Update()
         else:
             self.Cleanup()
-                            
+
     def SetSrcEnv(self, location, mapset):
         """Create environment to use for location and mapset
         that are the source of the file(s) to georectify
@@ -249,21 +273,22 @@
         :return: False on error
         :return: True on success
         """
-        
+
         self.newlocation = location
         self.newmapset = mapset
-        
-        # check to see if we are georectifying map in current working location/mapset
+
+        # check to see if we are georectifying map in current working
+        # location/mapset
         if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
             return False
-        
+
         self.gisrc_dict['LOCATION_NAME'] = location
         self.gisrc_dict['MAPSET'] = mapset
-        
+
         self.source_gisrc = EncodeString(utils.GetTempfile())
 
         try:
-            f = open(self.source_gisrc, mode='w')        
+            f = open(self.source_gisrc, mode='w')
             for line in self.gisrc_dict.items():
                 f.write(line[0] + ": " + line[1] + "\n")
         finally:
@@ -276,7 +301,8 @@
         Switches between original working location/mapset and
         location/mapset that is source of file(s) to georectify
         """
-        # check to see if we are georectifying map in current working location/mapset
+        # check to see if we are georectifying map in current working
+        # location/mapset
         if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
             return False
 
@@ -286,16 +312,16 @@
             os.environ['GISRC'] = str(self.source_gisrc)
 
         return True
-    
+
     def OnWizFinished(self):
         # self.Cleanup()
 
         return True
-        
+
     def OnGLMFocus(self, event):
         """Layer Manager focus"""
         # self.SwitchEnv('target')
-        
+
         event.Skip()
 
     def Cleanup(self):
@@ -306,50 +332,71 @@
         self.SwitchEnv('target')
         self.wizard.Destroy()
 
+
 class LocationPage(TitledPage):
     """
     Set map type (raster or vector) to georectify and
     select location/mapset of map(s) to georectify.
     """
+
     def __init__(self, wizard, parent):
-        TitledPage.__init__(self, wizard, _("Select map type and location/mapset"))
+        TitledPage.__init__(self, wizard, _(
+            "Select map type and location/mapset"))
 
         self.parent = parent
         self.grassdatabase = self.parent.grassdatabase
-        
+
         self.xylocation = ''
         self.xymapset = ''
-        
+
         #
         # layout
         #
         # map type
-        self.rb_maptype = wx.RadioBox(parent=self, id=wx.ID_ANY,
-                                      label=' %s ' % _("Map type to georectify"),
-                                      choices=[_('raster'), _('vector')],
-                                      majorDimension=wx.RA_SPECIFY_COLS)
+        self.rb_maptype = wx.RadioBox(
+            parent=self, id=wx.ID_ANY, label=' %s ' %
+            _("Map type to georectify"), choices=[
+                _('raster'), _('vector')], majorDimension=wx.RA_SPECIFY_COLS)
         self.sizer.Add(item=self.rb_maptype,
                        flag=wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, border=5,
                        pos=(1, 1), span=(1, 2))
 
         # location
-        self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select source location:')),
-                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
-                       pos=(2, 1))
-        self.cb_location = LocationSelect(parent = self, gisdbase = self.grassdatabase)
-        self.sizer.Add(item=self.cb_location,
-                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
-                       pos=(2, 2))
+        self.sizer.Add(
+            item=wx.StaticText(
+                parent=self,
+                id=wx.ID_ANY,
+                label=_('Select source location:')),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5,
+            pos=(
+                2,
+                1))
+        self.cb_location = LocationSelect(
+            parent=self, gisdbase=self.grassdatabase)
+        self.sizer.Add(
+            item=self.cb_location,
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5,
+            pos=(
+                2,
+                2))
 
         # mapset
-        self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select source mapset:')),
-                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
-                       pos=(3, 1))
-        self.cb_mapset = MapsetSelect(parent = self, gisdbase = self.grassdatabase,
-                                              setItems = False)
-        self.sizer.Add(item=self.cb_mapset,
-                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
-                       pos=(3,2))
+        self.sizer.Add(
+            item=wx.StaticText(
+                parent=self,
+                id=wx.ID_ANY,
+                label=_('Select source mapset:')),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5,
+            pos=(
+                3,
+                1))
+        self.cb_mapset = MapsetSelect(parent=self, gisdbase=self.grassdatabase,
+                                      setItems=False)
+        self.sizer.Add(item=self.cb_mapset, flag=wx.ALIGN_LEFT |
+                       wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5, pos=(3, 2))
         self.sizer.AddGrowableCol(2)
 
         #
@@ -362,7 +409,7 @@
         self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
         # self.Bind(wx.EVT_CLOSE, self.parent.Cleanup)
 
-    def OnMaptype(self,event):
+    def OnMaptype(self, event):
         """Change map type"""
         global maptype
 
@@ -370,17 +417,17 @@
             maptype = 'raster'
         else:
             maptype = 'vector'
-        
+
     def OnLocation(self, event):
         """Sets source location for map(s) to georectify"""
         self.xylocation = event.GetString()
-        
-        #create a list of valid mapsets
+
+        # create a list of valid mapsets
         tmplist = os.listdir(os.path.join(self.grassdatabase, self.xylocation))
         self.mapsetList = []
         for item in tmplist:
             if os.path.isdir(os.path.join(self.grassdatabase, self.xylocation, item)) and \
-                os.path.exists(os.path.join(self.grassdatabase, self.xylocation, item, 'WIND')):
+                    os.path.exists(os.path.join(self.grassdatabase, self.xylocation, item, 'WIND')):
                 if item != 'PERMANENT':
                     self.mapsetList.append(item)
 
@@ -389,7 +436,7 @@
         self.mapsetList.insert(0, 'PERMANENT')
         self.cb_mapset.SetItems(self.mapsetList)
         self.cb_mapset.SetStringSelection(self.xymapset)
-        
+
         if not wx.FindWindowById(wx.ID_FORWARD).IsEnabled():
             wx.FindWindowById(wx.ID_FORWARD).Enable(True)
 
@@ -398,43 +445,46 @@
         if self.xylocation == '':
             GMessage(_('You must select a valid location '
                        'before selecting a mapset'),
-                     parent = self)
+                     parent=self)
             return
 
         self.xymapset = event.GetString()
-        
+
         if not wx.FindWindowById(wx.ID_FORWARD).IsEnabled():
             wx.FindWindowById(wx.ID_FORWARD).Enable(True)
 
     def OnPageChanging(self, event=None):
         if event.GetDirection() and \
-               (self.xylocation == '' or self.xymapset == ''):
+                (self.xylocation == '' or self.xymapset == ''):
             GMessage(_('You must select a valid location '
-                            'and mapset in order to continue'),
-                          parent = self)
+                       'and mapset in order to continue'),
+                     parent=self)
             event.Veto()
             return
-        
+
         self.parent.SetSrcEnv(self.xylocation, self.xymapset)
-        
+
     def OnEnterPage(self, event=None):
         if self.xylocation == '' or self.xymapset == '':
             wx.FindWindowById(wx.ID_FORWARD).Enable(False)
         else:
             wx.FindWindowById(wx.ID_FORWARD).Enable(True)
 
+
 class GroupPage(TitledPage):
     """
     Set group to georectify. Create group if desired.
     """
+
     def __init__(self, wizard, parent):
-        TitledPage.__init__(self, wizard, _("Select image/map group to georectify"))
+        TitledPage.__init__(self, wizard, _(
+            "Select image/map group to georectify"))
 
         self.parent = parent
-        
+
         self.grassdatabase = self.parent.grassdatabase
         self.groupList = []
-        
+
         self.xylocation = ''
         self.xymapset = ''
         self.xygroup = ''
@@ -446,42 +496,73 @@
         # layout
         #
         # group
-        self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select group:')),
-                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
-                       pos=(1, 1))
+        self.sizer.Add(
+            item=wx.StaticText(
+                parent=self,
+                id=wx.ID_ANY,
+                label=_('Select group:')),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5,
+            pos=(
+                1,
+                1))
         self.cb_group = wx.ComboBox(parent=self, id=wx.ID_ANY,
                                     choices=self.groupList, size=(350, -1),
                                     style=wx.CB_DROPDOWN | wx.CB_READONLY)
-        self.sizer.Add(item=self.cb_group,
-                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
-                       pos=(1, 2))
-        
-        # create group               
-        self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Create group if none exists')),
-                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
-                       pos=(2, 1))
+        self.sizer.Add(item=self.cb_group, flag=wx.ALIGN_LEFT |
+                       wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5, pos=(1, 2))
+
+        # create group
+        self.sizer.Add(
+            item=wx.StaticText(
+                parent=self,
+                id=wx.ID_ANY,
+                label=_('Create group if none exists')),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5,
+            pos=(
+                2,
+                1))
         btnSizer = wx.BoxSizer(wx.HORIZONTAL)
-        self.btn_mkgroup = wx.Button(parent=self, id=wx.ID_ANY, label=_("Create/edit group..."))
-        self.btn_vgroup = wx.Button(parent=self, id=wx.ID_ANY, label=_("Add vector map to group..."))
+        self.btn_mkgroup = wx.Button(
+            parent=self,
+            id=wx.ID_ANY,
+            label=_("Create/edit group..."))
+        self.btn_vgroup = wx.Button(
+            parent=self,
+            id=wx.ID_ANY,
+            label=_("Add vector map to group..."))
         btnSizer.Add(item=self.btn_mkgroup,
                      flag=wx.RIGHT, border=5)
 
         btnSizer.Add(item=self.btn_vgroup,
                      flag=wx.LEFT, border=5)
-        
-        self.sizer.Add(item=btnSizer,
-                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
-                       pos=(2, 2))
-        
+
+        self.sizer.Add(
+            item=btnSizer,
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5,
+            pos=(
+                2,
+                2))
+
         # extension
-        self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Extension for output maps:')),
-                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
-                       pos=(3, 1))
-        self.ext_txt = wx.TextCtrl(parent=self, id=wx.ID_ANY, value="", size=(350,-1))
+        self.sizer.Add(
+            item=wx.StaticText(
+                parent=self,
+                id=wx.ID_ANY,
+                label=_('Extension for output maps:')),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5,
+            pos=(
+                3,
+                1))
+        self.ext_txt = wx.TextCtrl(
+            parent=self, id=wx.ID_ANY, value="", size=(
+                350, -1))
         self.ext_txt.SetValue(self.extension)
-        self.sizer.Add(item=self.ext_txt,
-                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
-                       pos=(3, 2))
+        self.sizer.Add(item=self.ext_txt, flag=wx.ALIGN_LEFT |
+                       wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5, pos=(3, 2))
 
         self.sizer.AddGrowableCol(2)
         #
@@ -496,12 +577,12 @@
         # hide vector group button by default
         self.btn_vgroup.Hide()
 
-    def OnGroup(self, event):        
+    def OnGroup(self, event):
         self.xygroup = event.GetString()
-        
+
     def OnMkGroup(self, event):
         """Create new group in source location/mapset"""
-        dlg = GroupDialog(parent = self, defaultGroup = self.xygroup)
+        dlg = GroupDialog(parent=self, defaultGroup=self.xygroup)
         dlg.DisableSubgroupEdit()
         dlg.ShowModal()
         gr, s = dlg.GetSelectedGroup()
@@ -510,25 +591,25 @@
         else:
             gr = ''
         dlg.Destroy()
-        
+
         self.OnEnterPage()
         self.Update()
-        
+
     def OnVGroup(self, event):
         """Add vector maps to group"""
-        dlg = VectGroup(parent = self,
-                        id = wx.ID_ANY,
-                        grassdb = self.grassdatabase,
-                        location = self.xylocation,
-                        mapset = self.xymapset,
-                        group = self.xygroup)
+        dlg = VectGroup(parent=self,
+                        id=wx.ID_ANY,
+                        grassdb=self.grassdatabase,
+                        location=self.xylocation,
+                        mapset=self.xymapset,
+                        group=self.xygroup)
 
         if dlg.ShowModal() != wx.ID_OK:
             return
 
         dlg.MakeVGroup()
         self.OnEnterPage()
-        
+
     def OnExtension(self, event):
         self.extension = self.ext_txt.GetValue()
 
@@ -536,20 +617,20 @@
         if event.GetDirection() and self.xygroup == '':
             GMessage(_('You must select a valid image/map '
                        'group in order to continue'),
-                     parent = self)
+                     parent=self)
             event.Veto()
             return
 
         if event.GetDirection() and self.extension == '':
             GMessage(_('You must enter an map name '
                        'extension in order to continue'),
-                     parent = self)
+                     parent=self)
             event.Veto()
             return
 
     def OnEnterPage(self, event=None):
         global maptype
-        
+
         self.groupList = []
 
         self.xylocation = self.parent.gisrc_dict['LOCATION_NAME']
@@ -571,7 +652,7 @@
                                               'group',
                                               item)):
                     self.groupList.append(item)
-        
+
         if maptype == 'raster':
             self.btn_vgroup.Hide()
             self.Bind(wx.EVT_BUTTON, self.OnMkGroup, self.btn_mkgroup)
@@ -580,34 +661,37 @@
             self.btn_vgroup.Show()
             self.Bind(wx.EVT_BUTTON, self.OnMkGroup, self.btn_mkgroup)
             self.Bind(wx.EVT_BUTTON, self.OnVGroup, self.btn_vgroup)
-        
+
         utils.ListSortLower(self.groupList)
         self.cb_group.SetItems(self.groupList)
-        
+
         if len(self.groupList) > 0:
             if self.xygroup and self.xygroup in self.groupList:
                 self.cb_group.SetStringSelection(self.xygroup)
             else:
                 self.cb_group.SetSelection(0)
                 self.xygroup = self.groupList[0]
-        
+
         if self.xygroup == '' or \
                 self.extension == '':
             wx.FindWindowById(wx.ID_FORWARD).Enable(False)
         else:
             wx.FindWindowById(wx.ID_FORWARD).Enable(True)
-        
+
         # switch to source
         self.parent.SwitchEnv('source')
-    
+
+
 class DispMapPage(TitledPage):
     """
     Select ungeoreferenced map to display for interactively
     setting ground control points (GCPs).
     """
+
     def __init__(self, wizard, parent):
-        TitledPage.__init__(self, wizard,
-                            _("Select maps to display for ground control point (GCP) creation"))
+        TitledPage.__init__(
+            self, wizard,
+            _("Select maps to display for ground control point (GCP) creation"))
 
         self.parent = parent
         global maptype
@@ -615,39 +699,78 @@
         #
         # layout
         #
-        self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select source map to display:')),
-                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
-                       pos=(1, 1))
-        
-        self.srcselection = Select(self, id=wx.ID_ANY,
-                                   size=globalvar.DIALOG_GSELECT_SIZE, type=maptype, updateOnPopup = False)
-        
-        self.sizer.Add(item=self.srcselection,
-                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
-                       pos=(1, 2))
+        self.sizer.Add(
+            item=wx.StaticText(
+                parent=self,
+                id=wx.ID_ANY,
+                label=_('Select source map to display:')),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5,
+            pos=(
+                1,
+                1))
 
-        self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select target raster map to display:')),
-                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
-                       pos=(2, 1))
+        self.srcselection = Select(
+            self,
+            id=wx.ID_ANY,
+            size=globalvar.DIALOG_GSELECT_SIZE,
+            type=maptype,
+            updateOnPopup=False)
 
-        self.tgtrastselection = Select(self, id=wx.ID_ANY,
-                                   size=globalvar.DIALOG_GSELECT_SIZE, type='raster', updateOnPopup = False)
+        self.sizer.Add(
+            item=self.srcselection,
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5,
+            pos=(
+                1,
+                2))
 
-        self.sizer.Add(item=self.tgtrastselection,
-                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
-                       pos=(2, 2))
+        self.sizer.Add(
+            item=wx.StaticText(
+                parent=self,
+                id=wx.ID_ANY,
+                label=_('Select target raster map to display:')),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5,
+            pos=(
+                2,
+                1))
 
-        self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select target vector map to display:')),
-                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
-                       pos=(3, 1))
+        self.tgtrastselection = Select(
+            self, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
+            type='raster', updateOnPopup=False)
 
-        self.tgtvectselection = Select(self, id=wx.ID_ANY,
-                                   size=globalvar.DIALOG_GSELECT_SIZE, type='vector', updateOnPopup = False)
-        
-        self.sizer.Add(item=self.tgtvectselection,
-                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
-                       pos=(3, 2))
+        self.sizer.Add(
+            item=self.tgtrastselection,
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5,
+            pos=(
+                2,
+                2))
 
+        self.sizer.Add(
+            item=wx.StaticText(
+                parent=self,
+                id=wx.ID_ANY,
+                label=_('Select target vector map to display:')),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5,
+            pos=(
+                3,
+                1))
+
+        self.tgtvectselection = Select(
+            self, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
+            type='vector', updateOnPopup=False)
+
+        self.sizer.Add(
+            item=self.tgtvectselection,
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5,
+            pos=(
+                3,
+                2))
+
         #
         # bindings
         #
@@ -671,12 +794,13 @@
             wx.FindWindowById(wx.ID_FORWARD).Enable(True)
 
         try:
-        # set computational region to match selected map and zoom display to region
+            # set computational region to match selected map and zoom display
+            # to region
             if maptype == 'raster':
                 p = RunCommand('g.region', 'raster=src_map')
             elif maptype == 'vector':
                 p = RunCommand('g.region', 'vector=src_map')
-            
+
             if p.returncode == 0:
                 print 'returncode = ', str(p.returncode)
                 self.parent.Map.region = self.parent.Map.GetRegion()
@@ -689,7 +813,7 @@
 
         tgt_map['raster'] = self.tgtrastselection.GetValue()
 
-    def OnTgtVectSelection(self,event):
+    def OnTgtVectSelection(self, event):
         """Source map to display selected"""
         global tgt_map
 
@@ -702,12 +826,12 @@
         if event.GetDirection() and (src_map == ''):
             GMessage(_('You must select a source map '
                        'in order to continue'),
-                     parent = self)
+                     parent=self)
             event.Veto()
             return
 
         self.parent.SwitchEnv('target')
-        
+
     def OnEnterPage(self, event=None):
         global maptype
         global src_map
@@ -717,18 +841,19 @@
 
         if maptype == 'raster':
             ret = RunCommand('i.group',
-                             parent = self,
-                             read = True,
-                             group = self.parent.grouppage.xygroup,
-                             flags = 'g')            
+                             parent=self,
+                             read=True,
+                             group=self.parent.grouppage.xygroup,
+                             flags='g')
 
             if ret:
                 self.parent.src_maps = ret.splitlines()
             else:
-                GError(parent = self,
-                       message = _('No maps in selected group <%s>.\n'
-                                   'Please edit group or select another group.') %
-                       self.parent.grouppage.xygroup)
+                GError(
+                    parent=self, message=_(
+                        'No maps in selected group <%s>.\n'
+                        'Please edit group or select another group.') %
+                    self.parent.grouppage.xygroup)
                 return
 
         elif maptype == 'vector':
@@ -738,11 +863,11 @@
             # make list of vectors to georectify from VREF
 
             vgrpfile = os.path.join(grassdatabase,
-                                     xylocation,
-                                     xymapset,
-                                     'group',
-                                     self.parent.grouppage.xygroup,
-                                     'VREF')
+                                    xylocation,
+                                    xymapset,
+                                    'group',
+                                    self.parent.grouppage.xygroup,
+                                    'VREF')
 
             f = open(vgrpfile)
             try:
@@ -753,16 +878,17 @@
                     self.parent.src_maps.append(vect)
             finally:
                 f.close()
-                
+
             if len(self.parent.src_maps) < 1:
-                GError(parent = self,
-                       message = _('No maps in selected group <%s>.\n'
-                                   'Please edit group or select another group.') %
-                       self.parent.grouppage.xygroup)
+                GError(
+                    parent=self, message=_(
+                        'No maps in selected group <%s>.\n'
+                        'Please edit group or select another group.') %
+                    self.parent.grouppage.xygroup)
                 return
 
         # filter out all maps not in group
-        self.srcselection.tcp.GetElementList(elements = self.parent.src_maps)
+        self.srcselection.tcp.GetElementList(elements=self.parent.src_maps)
         src_map = self.parent.src_maps[0]
         self.srcselection.SetValue(src_map)
 
@@ -778,26 +904,35 @@
         else:
             wx.FindWindowById(wx.ID_FORWARD).Enable(True)
 
+
 class GCP(MapFrame, ColumnSorterMixin):
     """
     Manages ground control points for georectifying. Calculates RMS statistics.
     Calls i.rectify or v.rectify to georectify map.
     """
-    def __init__(self, parent, giface, grwiz = None, id = wx.ID_ANY,
-                 title = _("Manage Ground Control Points"),
-                 size = (700, 300), toolbars = ["gcpdisp"], Map = None, lmgr = None):
 
-        self.grwiz = grwiz # GR Wizard
+    def __init__(self, parent, giface, grwiz=None, id=wx.ID_ANY,
+                 title=_("Manage Ground Control Points"),
+                 size=(700, 300), toolbars=["gcpdisp"], Map=None, lmgr=None):
+
+        self.grwiz = grwiz  # GR Wizard
         self._giface = giface
 
         if tgt_map['raster'] == '' and tgt_map['vector'] == '':
             self.show_target = False
         else:
             self.show_target = True
-        
+
         #wx.Frame.__init__(self, parent, id, title, size = size, name = "GCPFrame")
-        MapFrame.__init__(self, parent = parent, giface = self._giface, title = title, size = size,
-                            Map=Map, toolbars=toolbars, name='GCPMapWindow')
+        MapFrame.__init__(
+            self,
+            parent=parent,
+            giface=self._giface,
+            title=title,
+            size=size,
+            Map=Map,
+            toolbars=toolbars,
+            name='GCPMapWindow')
 
         # init variables
         self.parent = parent
@@ -805,8 +940,10 @@
         #
         # register data structures for drawing GCP's
         #
-        self.pointsToDrawTgt = self.TgtMapWindow.RegisterGraphicsToDraw(graphicsType = "point", setStatusFunc = self.SetGCPSatus)
-        self.pointsToDrawSrc = self.SrcMapWindow.RegisterGraphicsToDraw(graphicsType = "point", setStatusFunc = self.SetGCPSatus)
+        self.pointsToDrawTgt = self.TgtMapWindow.RegisterGraphicsToDraw(
+            graphicsType="point", setStatusFunc=self.SetGCPSatus)
+        self.pointsToDrawSrc = self.SrcMapWindow.RegisterGraphicsToDraw(
+            graphicsType="point", setStatusFunc=self.SetGCPSatus)
 
         # connect to the map windows signals
         # used to add or edit GCP
@@ -837,44 +974,44 @@
         self.VectGRList = []
 
         self.file = {
-            'points' : os.path.join(self.grassdatabase,
-                                    self.xylocation,
-                                    self.xymapset,
-                                    'group',
-                                    self.xygroup,
-                                    'POINTS'),
-            'points_bak' : os.path.join(self.grassdatabase,
-                                    self.xylocation,
-                                    self.xymapset,
-                                    'group',
-                                    self.xygroup,
-                                    'POINTS_BAK'),
-            'rgrp' : os.path.join(self.grassdatabase,
-                                  self.xylocation,
-                                  self.xymapset,
-                                  'group',
-                                  self.xygroup,
-                                  'REF'),
-            'vgrp' : os.path.join(self.grassdatabase,
-                                  self.xylocation,
-                                  self.xymapset,
-                                  'group',
-                                  self.xygroup,
-                                  'VREF'),
-            'target' : os.path.join(self.grassdatabase,
-                                    self.xylocation,
-                                    self.xymapset,
-                                    'group',
-                                    self.xygroup,
-                                    'TARGET'),
-            }
+            'points': os.path.join(self.grassdatabase,
+                                   self.xylocation,
+                                   self.xymapset,
+                                   'group',
+                                   self.xygroup,
+                                   'POINTS'),
+            'points_bak': os.path.join(self.grassdatabase,
+                                       self.xylocation,
+                                       self.xymapset,
+                                       'group',
+                                       self.xygroup,
+                                       'POINTS_BAK'),
+            'rgrp': os.path.join(self.grassdatabase,
+                                 self.xylocation,
+                                 self.xymapset,
+                                 'group',
+                                 self.xygroup,
+                                 'REF'),
+            'vgrp': os.path.join(self.grassdatabase,
+                                 self.xylocation,
+                                 self.xymapset,
+                                 'group',
+                                 self.xygroup,
+                                 'VREF'),
+            'target': os.path.join(self.grassdatabase,
+                                   self.xylocation,
+                                   self.xymapset,
+                                   'group',
+                                   self.xygroup,
+                                   'TARGET'),
+        }
 
         # make a backup of the current points file
         if os.path.exists(self.file['points']):
             shutil.copy(self.file['points'], self.file['points_bak'])
 
         # polynomial order transformation for georectification
-        self.gr_order = 1 
+        self.gr_order = 1
         # interpolation method for georectification
         self.gr_method = 'nearest'
         # region clipping for georectified map
@@ -887,17 +1024,17 @@
         self.bkw_rmserror = 0.0
         # list map coords and ID of map display they came from
         self.mapcoordlist = []
-        self.mapcoordlist.append([ 0,        # GCP number
-                                   0.0,      # source east
-                                   0.0,      # source north
-                                   0.0,      # target east
-                                   0.0,      # target north
-                                   0.0,      # forward error
-                                   0.0 ] )   # backward error
+        self.mapcoordlist.append([0,        # GCP number
+                                  0.0,      # source east
+                                  0.0,      # source north
+                                  0.0,      # target east
+                                  0.0,      # target north
+                                  0.0,      # forward error
+                                  0.0])   # backward error
 
         # init vars to highlight high RMS errors
         self.highest_only = True
-        self.show_unused =  True
+        self.show_unused = True
         self.highest_key = -1
         self.rmsthresh = 0
         self.rmsmean = 0
@@ -911,8 +1048,8 @@
         # CheckListCtrlMixin must set an ImageList first
         self.il = self.list.GetImageList(wx.IMAGE_LIST_SMALL)
 
-        SmallUpArrow = wx.BitmapFromImage(getSmallUpArrowImage())            
-        SmallDnArrow = wx.BitmapFromImage(getSmallDnArrowImage())            
+        SmallUpArrow = wx.BitmapFromImage(getSmallUpArrowImage())
+        SmallDnArrow = wx.BitmapFromImage(getSmallDnArrowImage())
         self.sm_dn = self.il.Add(SmallDnArrow)
         self.sm_up = self.il.Add(SmallUpArrow)
 
@@ -925,7 +1062,7 @@
         self.mapwin.SetNamedCursor('cross')
 
         self.mapwin = self.TgtMapWindow
-        
+
         # set mouse characteristics
         self.mapwin.mouse['box'] = 'point'
         self.mapwin.mouse["use"] == "pointer"
@@ -949,10 +1086,10 @@
         # bindings
         #
         self.Bind(wx.EVT_ACTIVATE, self.OnFocus)
-        self.Bind(wx.EVT_SIZE,     self.OnSize)
-        self.Bind(wx.EVT_IDLE,     self.OnIdle)
-        self.Bind(wx.EVT_CLOSE,    self.OnQuit)
-        
+        self.Bind(wx.EVT_SIZE, self.OnSize)
+        self.Bind(wx.EVT_IDLE, self.OnIdle)
+        self.Bind(wx.EVT_CLOSE, self.OnQuit)
+
         self.SetSettings()
 
     def __del__(self):
@@ -960,7 +1097,7 @@
         # leaving the method here but was used only to delete gcpmanagement
         # from layer manager which is now not needed
         pass
-        
+
     def CreateGCPList(self):
         """Create GCP List Control"""
 
@@ -969,7 +1106,7 @@
     # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
     def GetListCtrl(self):
         return self.list
-        
+
     def GetMapCoordList(self):
         return self.mapcoordlist
 
@@ -979,13 +1116,13 @@
 
     def GetFwdError(self):
         return self.fwd_rmserror
-        
+
     def GetBkwError(self):
         return self.bkw_rmserror
-                
+
     def InitMapDisplay(self):
         self.list.LoadData()
-        
+
         # initialize column sorter
         self.itemDataMap = self.mapcoordlist
         ncols = self.list.GetColumnCount()
@@ -997,19 +1134,20 @@
         """
         Sets rectification target to current location and mapset
         """
-        # check to see if we are georectifying map in current working location/mapset
+        # check to see if we are georectifying map in current working
+        # location/mapset
         if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
             RunCommand('i.target',
-                       parent = self,
-                       flags = 'c',
-                       group = tgroup)
+                       parent=self,
+                       flags='c',
+                       group=tgroup)
         else:
             self.grwiz.SwitchEnv('source')
             RunCommand('i.target',
-                       parent = self,
-                       group = tgroup,
-                       location = tlocation,
-                       mapset = tmapset)
+                       parent=self,
+                       group=tgroup,
+                       location=tlocation,
+                       mapset=tmapset)
             self.grwiz.SwitchEnv('target')
 
     def AddGCP(self, event):
@@ -1017,16 +1155,17 @@
         Appends an item to GCP list
         """
         keyval = self.list.AddGCPItem() + 1
-        # source east, source north, target east, target north, forward error, backward error
-        self.mapcoordlist.append([ keyval,             # GCP number
-                                   0.0,                # source east
-                                   0.0,                # source north
-                                   0.0,                # target east
-                                   0.0,                # target north
-                                   0.0,                # forward error
-                                   0.0 ] )             # backward error
+        # source east, source north, target east, target north, forward error,
+        # backward error
+        self.mapcoordlist.append([keyval,             # GCP number
+                                  0.0,                # source east
+                                  0.0,                # source north
+                                  0.0,                # target east
+                                  0.0,                # target north
+                                  0.0,                # forward error
+                                  0.0])             # backward error
 
-        if self.statusbarManager.GetMode() == 8: # go to
+        if self.statusbarManager.GetMode() == 8:  # go to
             self.StatusbarUpdate()
 
     def DeleteGCP(self, event):
@@ -1036,8 +1175,10 @@
         minNumOfItems = self.OnGROrder(None)
 
         if self.list.GetItemCount() <= minNumOfItems:
-            GMessage(parent = self,
-                     message=_("At least %d GCPs required. Operation canceled.") % minNumOfItems)
+            GMessage(
+                parent=self,
+                message=_("At least %d GCPs required. Operation canceled.") %
+                minNumOfItems)
             return
 
         key = self.list.DeleteGCPItem()
@@ -1053,24 +1194,27 @@
         # update selected
         if self.list.GetItemCount() > 0:
             if self.list.selected < self.list.GetItemCount():
-                self.list.selectedkey = self.list.GetItemData(self.list.selected)
+                self.list.selectedkey = self.list.GetItemData(
+                    self.list.selected)
             else:
                 self.list.selected = self.list.GetItemCount() - 1
-                self.list.selectedkey = self.list.GetItemData(self.list.selected)
-                
+                self.list.selectedkey = self.list.GetItemData(
+                    self.list.selected)
+
             self.list.SetItemState(self.list.selected,
-                              wx.LIST_STATE_SELECTED,
-                              wx.LIST_STATE_SELECTED)
+                                   wx.LIST_STATE_SELECTED,
+                                   wx.LIST_STATE_SELECTED)
         else:
             self.list.selected = wx.NOT_FOUND
             self.list.selectedkey = -1
 
         self.UpdateColours()
 
-        if self.statusbarManager.GetMode() == 8: # go to
+        if self.statusbarManager.GetMode() == 8:  # go to
             self.StatusbarUpdate()
             if self.list.selectedkey > 0:
-                self.statusbarManager.SetProperty('gotoGCP', self.list.selectedkey)
+                self.statusbarManager.SetProperty(
+                    'gotoGCP', self.list.selectedkey)
 
     def ClearGCP(self, event):
         """
@@ -1085,56 +1229,63 @@
         self.list.SetStringItem(index, 6, '')
         self.list.CheckItem(index, False)
 
-        # GCP number, source E, source N, target E, target N, fwd error, bkwd error
+        # GCP number, source E, source N, target E, target N, fwd error, bkwd
+        # error
         self.mapcoordlist[key] = [key, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
 
     def SetSettings(self):
         """Sets settings for drawing of GCP's.
         """
-        self.highest_only = UserSettings.Get(group='gcpman', key='rms', subkey='highestonly')
-        self.show_unused =  UserSettings.Get(group='gcpman', key='symbol', subkey='unused')
-        
-        colours = { "color"  : "default", 
-                    "hcolor" : "highest", 
-                    "scolor" : "selected",
-                    "ucolor" : "unused" }
-        wpx = UserSettings.Get(group = 'gcpman', key = 'symbol', subkey = 'width')
-        
+        self.highest_only = UserSettings.Get(
+            group='gcpman', key='rms', subkey='highestonly')
+        self.show_unused = UserSettings.Get(
+            group='gcpman', key='symbol', subkey='unused')
+
+        colours = {"color": "default",
+                   "hcolor": "highest",
+                   "scolor": "selected",
+                   "ucolor": "unused"}
+        wpx = UserSettings.Get(group='gcpman', key='symbol', subkey='width')
+
         for k, v in colours.iteritems():
-            col = UserSettings.Get(group='gcpman', key='symbol', subkey= k)
-            self.pointsToDrawSrc.GetPen(v).SetColour(wx.Colour(col[0], col[1], col[2], 255)) # TODO GetPen neni to spatne? 
-            self.pointsToDrawTgt.GetPen(v).SetColour(wx.Colour(col[0], col[1], col[2], 255))
-            
+            col = UserSettings.Get(group='gcpman', key='symbol', subkey=k)
+            self.pointsToDrawSrc.GetPen(v).SetColour(wx.Colour(
+                col[0], col[1], col[2], 255))  # TODO GetPen neni to spatne?
+            self.pointsToDrawTgt.GetPen(v).SetColour(
+                wx.Colour(col[0], col[1], col[2], 255))
+
             self.pointsToDrawSrc.GetPen(v).SetWidth(wpx)
             self.pointsToDrawTgt.GetPen(v).SetWidth(wpx)
-        
-        spx = UserSettings.Get(group = 'gcpman', key = 'symbol', subkey = 'size')
+
+        spx = UserSettings.Get(group='gcpman', key='symbol', subkey='size')
         self.pointsToDrawSrc.SetPropertyVal("size", int(spx))
         self.pointsToDrawTgt.SetPropertyVal("size", int(spx))
-        
+
         font = self.GetFont()
         font.SetPointSize(int(spx) + 2)
-        
+
         textProp = {}
         textProp['active'] = True
         textProp['font'] = font
         self.pointsToDrawSrc.SetPropertyVal("text", textProp)
         self.pointsToDrawTgt.SetPropertyVal("text", copy(textProp))
-        
+
     def SetGCPSatus(self, item, itemIndex):
         """Before GCP is drawn, decides it's colour and whether it
         will be drawed.
         """
         key = self.list.GetItemData(itemIndex)
-        itemIndex += 1 # incremented because of itemDataMap (has one more item) - will be changed
-        
+        # incremented because of itemDataMap (has one more item) - will be
+        # changed
+        itemIndex += 1
+
         if not self.list.IsChecked(key - 1):
-                wxPen = "unused"
-                if not self.show_unused:
-                    item.SetPropertyVal('hide', True)
-                else:
-                    item.SetPropertyVal('hide', False)
-        
+            wxPen = "unused"
+            if not self.show_unused:
+                item.SetPropertyVal('hide', True)
+            else:
+                item.SetPropertyVal('hide', False)
+
         else:
             item.SetPropertyVal('hide', False)
             if self.highest_only == True:
@@ -1147,10 +1298,10 @@
                     wxPen = "highest"
                 else:
                     wxPen = "default"
-        
+
         if itemIndex == self.list.selectedkey:
             wxPen = "selected"
-        
+
         item.SetPropertyVal('label', str(itemIndex))
         item.SetPropertyVal('penName', wxPen)
 
@@ -1172,44 +1323,44 @@
                 currloc = _("source")
             else:
                 currloc = _("target")
-            ret = wx.MessageBox(parent = self,
-                                caption = _("Set GCP coordinates"),
-                                message = _('Set %(coor)s coordinates for GCP No. %(key)s? \n\n'
-                                            'East: %(coor0)s \n'
-                                            'North: %(coor1)s') % \
-                                    { 'coor' : currloc,
-                                      'key' : str(key),
-                                      'coor0' : str(coord0),
-                                      'coor1' : str(coord1) },
-                                style = wx.ICON_QUESTION | wx.YES_NO | wx.CENTRE)
-            
+            ret = wx.MessageBox(
+                parent=self, caption=_("Set GCP coordinates"),
+                message=_(
+                    'Set %(coor)s coordinates for GCP No. %(key)s? \n\n'
+                    'East: %(coor0)s \n'
+                    'North: %(coor1)s') %
+                {'coor': currloc, 'key': str(key),
+                 'coor0': str(coord0),
+                 'coor1': str(coord1)},
+                style=wx.ICON_QUESTION | wx.YES_NO | wx.CENTRE)
+
             # for wingrass
             if os.name == 'nt':
                 self.MapWindow.SetFocus()
             if ret == wx.NO:
                 return
-        
+
         if coordtype == 'source':
             self.list.SetStringItem(index, 1, str(coord0))
             self.list.SetStringItem(index, 2, str(coord1))
             self.mapcoordlist[key][1] = coord[0]
             self.mapcoordlist[key][2] = coord[1]
             self.pointsToDrawSrc.GetItem(key - 1).SetCoords([coord0, coord1])
-            
+
         elif coordtype == 'target':
             self.list.SetStringItem(index, 3, str(coord0))
             self.list.SetStringItem(index, 4, str(coord1))
             self.mapcoordlist[key][3] = coord[0]
             self.mapcoordlist[key][4] = coord[1]
             self.pointsToDrawTgt.GetItem(key - 1).SetCoords([coord0, coord1])
-        
+
         self.list.SetStringItem(index, 5, '0')
         self.list.SetStringItem(index, 6, '0')
         self.mapcoordlist[key][5] = 0.0
         self.mapcoordlist[key][6] = 0.0
-        
+
         # self.list.ResizeColumns()
-        
+
     def SaveGCPs(self, event):
         """Make a POINTS file or save GCP coordinates to existing
         POINTS file
@@ -1224,7 +1375,8 @@
             f.write("# target mapset: " + self.currentmapset + '\n')
             f.write("#\tsource\t\ttarget\t\tstatus\n")
             f.write("#\teast\tnorth\teast\tnorth\t(1=ok, 0=ignore)\n")
-            f.write("#-----------------------     -----------------------     ---------------\n")
+            f.write(
+                "#-----------------------     -----------------------     ---------------\n")
 
             for index in range(self.list.GetItemCount()):
                 if self.list.IsChecked(index) == True:
@@ -1236,12 +1388,26 @@
                 coord1 = self.list.GetItem(index, 2).GetText()
                 coord2 = self.list.GetItem(index, 3).GetText()
                 coord3 = self.list.GetItem(index, 4).GetText()
-                f.write(coord0 + ' ' + coord1 + '     ' + coord2 + ' ' + coord3 + '     ' + check + '\n')
+                f.write(
+                    coord0 +
+                    ' ' +
+                    coord1 +
+                    '     ' +
+                    coord2 +
+                    ' ' +
+                    coord3 +
+                    '     ' +
+                    check +
+                    '\n')
 
         except IOError as err:
-            GError(parent = self,
-                   message="%s <%s>. %s%s" % (_("Writing POINTS file failed"),
-                                              self.file['points'], os.linesep, err))
+            GError(
+                parent=self,
+                message="%s <%s>. %s%s" %
+                (_("Writing POINTS file failed"),
+                 self.file['points'],
+                    os.linesep,
+                    err))
             return
 
         f.close()
@@ -1249,41 +1415,43 @@
         # if event != None save also to backup file
         if event:
             shutil.copy(self.file['points'], self.file['points_bak'])
-            self._giface.WriteLog(_('POINTS file saved for group <%s>') % self.xygroup)
+            self._giface.WriteLog(
+                _('POINTS file saved for group <%s>') %
+                self.xygroup)
             #self.SetStatusText(_('POINTS file saved'))
 
     def ReadGCPs(self):
         """
         Reads GCPs and georectified coordinates from POINTS file
         """
-        
+
         self.GCPcount = 0
 
         sourceMapWin = self.SrcMapWindow
         targetMapWin = self.TgtMapWindow
-        
+
         if not sourceMapWin:
-            GError(parent = self,
-                   message = "%s. %s%s" % (_("source mapwin not defined"),
-                                           os.linesep, err))
-        
+            GError(parent=self,
+                   message="%s. %s%s" % (_("source mapwin not defined"),
+                                         os.linesep, err))
+
         if not targetMapWin:
-            GError(parent = self,
+            GError(parent=self,
                    message="%s. %s%s" % (_("target mapwin not defined"),
                                          os.linesep, err))
-        
+
         try:
             f = open(self.file['points'], 'r')
             GCPcnt = 0
-            
+
             for line in f.readlines():
-                if line[0] == '#' or line =='':
+                if line[0] == '#' or line == '':
                     continue
                 line = line.replace('\n', '').strip()
                 coords = map(float, line.split())
                 if coords[4] == 1:
                     check = True
-                    self.GCPcount +=1
+                    self.GCPcount += 1
                 else:
                     check = False
 
@@ -1296,9 +1464,13 @@
                 GCPcnt += 1
 
         except IOError as err:
-            GError(parent = self,
-                   message = "%s <%s>. %s%s" % (_("Reading POINTS file failed"),
-                                                self.file['points'], os.linesep, err))
+            GError(
+                parent=self,
+                message="%s <%s>. %s%s" %
+                (_("Reading POINTS file failed"),
+                 self.file['points'],
+                    os.linesep,
+                    err))
             return
 
         f.close()
@@ -1320,13 +1492,13 @@
 
         # delete all items in mapcoordlist
         self.mapcoordlist = []
-        self.mapcoordlist.append([ 0,        # GCP number
-                                   0.0,      # source east
-                                   0.0,      # source north
-                                   0.0,      # target east
-                                   0.0,      # target north
-                                   0.0,      # forward error
-                                   0.0 ] )   # backward error
+        self.mapcoordlist.append([0,        # GCP number
+                                  0.0,      # source east
+                                  0.0,      # source north
+                                  0.0,      # target east
+                                  0.0,      # target north
+                                  0.0,      # forward error
+                                  0.0])   # backward error
 
         self.list.LoadData()
         self.itemDataMap = self.mapcoordlist
@@ -1341,7 +1513,7 @@
         if self.show_target:
             targetMapWin = self.TgtMapWindow
             targetMapWin.UpdateMap(render=False, renderVector=False)
-    
+
     def OnFocus(self, event):
         # TODO: it is here just to remove old or obsolate beavior of base class gcp/MapFrame?
         # self.grwiz.SwitchEnv('source')
@@ -1361,29 +1533,31 @@
         """
         RMS button handler
         """
-        self.RMSError(self.xygroup,self.gr_order)
+        self.RMSError(self.xygroup, self.gr_order)
 
         sourceMapWin = self.SrcMapWindow
         sourceMapWin.UpdateMap(render=False, renderVector=False)
         if self.show_target:
             targetMapWin = self.TgtMapWindow
             targetMapWin.UpdateMap(render=False, renderVector=False)
-        
+
     def CheckGCPcount(self, msg=False):
         """
         Checks to make sure that the minimum number of GCPs have been defined and
         are active for the selected transformation order
         """
         if (self.GCPcount < 3 and self.gr_order == 1) or \
-            (self.GCPcount < 6 and self.gr_order == 2) or \
-            (self.GCPcount < 10 and self.gr_order == 3):
+                (self.GCPcount < 6 and self.gr_order == 2) or \
+                (self.GCPcount < 10 and self.gr_order == 3):
             if msg:
-                GWarning(parent = self,
-                         message=_('Insufficient points defined and active (checked) '
-                                   'for selected rectification method (order: %d).\n'
-                                   '3+ points needed for 1st order,\n'
-                                   '6+ points for 2nd order, and\n'
-                                   '10+ points for 3rd order.') % self.gr_order)
+                GWarning(
+                    parent=self, message=_(
+                        'Insufficient points defined and active (checked) '
+                        'for selected rectification method (order: %d).\n'
+                        '3+ points needed for 1st order,\n'
+                        '6+ points for 2nd order, and\n'
+                        '10+ points for 3rd order.') %
+                    self.gr_order)
                 return False
         else:
             return True
@@ -1394,7 +1568,7 @@
         """
         global maptype
         self.SaveGCPs(None)
-        
+
         if self.CheckGCPcount(msg=True) == False:
             return
 
@@ -1411,26 +1585,26 @@
             wx.Yield()
 
             ret, msg = RunCommand('i.rectify',
-                                  parent = self,
-                                  getErrorMsg = True,
-                                  quiet = True,
-                                  group = self.xygroup,
-                                  extension = self.extension,
-                                  order = self.gr_order,
+                                  parent=self,
+                                  getErrorMsg=True,
+                                  quiet=True,
+                                  group=self.xygroup,
+                                  extension=self.extension,
+                                  order=self.gr_order,
                                   method=self.gr_method,
-                                  flags = flags)
+                                  flags=flags)
 
             busy.Destroy()
 
             # provide feedback on failure
             if ret != 0:
                 print >> sys.stderr, msg
-                
+
         elif maptype == 'vector':
             # loop through all vectors in VREF
 
             self.grwiz.SwitchEnv('source')
-            
+
             # make list of vectors to georectify from VREF
             f = open(self.file['vgrp'])
             vectlist = []
@@ -1442,33 +1616,34 @@
                     vectlist.append(vect)
             finally:
                 f.close()
-                               
+
             # georectify each vector in VREF using v.rectify
             for vect in vectlist:
                 self.outname = str(vect.split('@')[0]) + self.extension
-                self._giface.WriteLog(text = _('Transforming <%s>...') % vect,
+                self._giface.WriteLog(text=_('Transforming <%s>...') % vect,
                                       notification=Notification.MAKE_VISIBLE)
                 ret = msg = ''
-                
-                busy = wx.BusyInfo(message=_("Rectifying vector map <%s>, please wait...") % vect,
-                                   parent=self)
+
+                busy = wx.BusyInfo(
+                    message=_("Rectifying vector map <%s>, please wait...") %
+                    vect, parent=self)
                 wx.Yield()
 
                 ret, msg = RunCommand('v.rectify',
-                                      parent = self,
-                                      getErrorMsg = True,
-                                      quiet = True,
-                                      input = vect,
-                                      output = self.outname,
-                                      group = self.xygroup,
-                                      order = self.gr_order)
+                                      parent=self,
+                                      getErrorMsg=True,
+                                      quiet=True,
+                                      input=vect,
+                                      output=self.outname,
+                                      group=self.xygroup,
+                                      order=self.gr_order)
 
                 busy.Destroy()
 
                 # provide feedback on failure
                 if ret != 0:
                     print >> sys.stderr, msg
-                                                   
+
         self.grwiz.SwitchEnv('target')
 
     def OnGeorectDone(self, **kargs):
@@ -1476,17 +1651,17 @@
         global maptype
         if maptype == 'raster':
             return
-        
+
         returncode = kargs['returncode']
-        
+
         if returncode == 0:
             self.VectGRList.append(self.outname)
             print '*****vector list = ' + str(self.VectGRList)
         else:
-            self._giface.WriteError(_('Georectification of vector map <%s> failed') %
-                                      self.outname)
+            self._giface.WriteError(
+                _('Georectification of vector map <%s> failed') %
+                self.outname)
 
-         
     def OnSettings(self, event):
         """GCP Manager settings"""
         dlg = GrSettingsDialog(parent=self, giface=self._giface,
@@ -1494,11 +1669,11 @@
 
         if dlg.ShowModal() == wx.ID_OK:
             pass
-        
+
         dlg.Destroy()
 
     def UpdateColours(self, srcrender=False, srcrenderVector=False,
-                            tgtrender=False, tgtrenderVector=False):
+                      tgtrender=False, tgtrenderVector=False):
         """update colours"""
         highest_fwd_err = 0.0
         self.highest_key = 0
@@ -1522,7 +1697,7 @@
                         self.list.SetItemTextColour(index, wx.BLACK)
             else:
                 self.list.SetItemTextColour(index, wx.BLACK)
-        
+
         if self.highest_only and highest_fwd_err > 0.0:
             self.list.SetItemTextColour(highest_idx, wx.RED)
 
@@ -1530,14 +1705,16 @@
         sourceMapWin.UpdateMap(render=srcrender, renderVector=srcrenderVector)
         if self.show_target:
             targetMapWin = self.TgtMapWindow
-            targetMapWin.UpdateMap(render=tgtrender, renderVector=tgtrenderVector)
+            targetMapWin.UpdateMap(
+                render=tgtrender,
+                renderVector=tgtrenderVector)
 
     def OnQuit(self, event):
         """Quit georectifier"""
-        ret = wx.MessageBox(parent=self,
-                      caption=_("Quit GCP Manager"),
-                      message=_('Save ground control points?'),
-                      style=wx.ICON_QUESTION | wx.YES_NO | wx.CANCEL | wx.CENTRE)
+        ret = wx.MessageBox(
+            parent=self, caption=_("Quit GCP Manager"),
+            message=_('Save ground control points?'),
+            style=wx.ICON_QUESTION | wx.YES_NO | wx.CANCEL | wx.CENTRE)
 
         if ret != wx.CANCEL:
             if ret == wx.YES:
@@ -1557,7 +1734,7 @@
 
             self.Destroy()
 
-        #event.Skip()
+        # event.Skip()
 
     def OnGROrder(self, event):
         """
@@ -1568,7 +1745,7 @@
 
         numOfItems = self.list.GetItemCount()
         minNumOfItems = numOfItems
-        
+
         if self.gr_order == 1:
             minNumOfItems = 3
             # self.SetStatusText(_('Insufficient points, 3+ points needed for 1st order'))
@@ -1586,7 +1763,7 @@
             self.AddGCP(None)
 
         return minNumOfItems
-    
+
     def RMSError(self, xygroup, order):
         """
         Uses m.transform to calculate forward and backward error for each used GCP
@@ -1595,32 +1772,36 @@
         """
         # save GCPs to points file to make sure that all checked GCPs are used
         self.SaveGCPs(None)
-        #self.SetStatusText('')
-        
+        # self.SetStatusText('')
+
         if self.CheckGCPcount(msg=True) == False:
             return
-        
+
         # get list of forward and reverse rms error values for each point
         self.grwiz.SwitchEnv('source')
-        
+
         ret = RunCommand('m.transform',
-                         parent = self,
-                         read = True,
-                         group = xygroup,
-                         order = order)
-        
+                         parent=self,
+                         read=True,
+                         group=xygroup,
+                         order=order)
+
         self.grwiz.SwitchEnv('target')
 
         if ret:
             errlist = ret.splitlines()
         else:
-            GError(parent = self,
+            GError(parent=self,
                    message=_('Could not calculate RMS Error.\n'
                              'Possible error with m.transform.'))
             return
-        
+
         # insert error values into GCP list for checked items
-        sdfactor = float(UserSettings.Get(group='gcpman', key='rms', subkey='sdfactor'))
+        sdfactor = float(
+            UserSettings.Get(
+                group='gcpman',
+                key='rms',
+                subkey='sdfactor'))
         GCPcount = 0
         sumsq_fwd_err = 0.0
         sumsq_bkw_err = 0.0
@@ -1628,7 +1809,7 @@
         highest_fwd_err = 0.0
         self.highest_key = 0
         highest_idx = 0
-        
+
         for index in range(self.list.GetItemCount()):
             key = self.list.GetItemData(index)
             if self.list.IsChecked(index):
@@ -1643,7 +1824,7 @@
                         highest_fwd_err = float(fwd_err)
                         self.highest_key = key
                         highest_idx = index
-                        
+
                 sumsq_fwd_err += float(fwd_err)**2
                 sumsq_bkw_err += float(bkw_err)**2
                 sum_fwd_err += float(fwd_err)
@@ -1673,26 +1854,26 @@
                     key = self.list.GetItemData(index)
                     if (self.mapcoordlist[key][5] > self.rmsthresh):
                         self.list.SetItemTextColour(index, wx.RED)
-            
+
         # calculate global RMS error (geometric mean)
-        self.fwd_rmserror = round((sumsq_fwd_err/GCPcount)**0.5,4)
-        self.bkw_rmserror = round((sumsq_bkw_err/GCPcount)**0.5,4)
+        self.fwd_rmserror = round((sumsq_fwd_err / GCPcount)**0.5, 4)
+        self.bkw_rmserror = round((sumsq_bkw_err / GCPcount)**0.5, 4)
         self.list.ResizeColumns()
 
-    def GetNewExtent(self, region, map = None):
+    def GetNewExtent(self, region, map=None):
 
         coord_file = utils.GetTempfile()
-        newreg = { 'n' : 0.0, 's' : 0.0, 'e' : 0.0, 'w' : 0.0,}
+        newreg = {'n': 0.0, 's': 0.0, 'e': 0.0, 'w': 0.0, }
 
         try:
             f = open(coord_file, mode='w')
-            # NW corner        
+            # NW corner
             f.write(str(region['e']) + " " + str(region['n']) + "\n")
-            # NE corner        
+            # NE corner
             f.write(str(region['e']) + " " + str(region['s']) + "\n")
-            # SW corner        
+            # SW corner
             f.write(str(region['w']) + " " + str(region['n']) + "\n")
-            # SE corner        
+            # SE corner
             f.write(str(region['w']) + " " + str(region['s']) + "\n")
         finally:
             f.close()
@@ -1706,39 +1887,39 @@
         if self.CheckGCPcount(msg=True) == False:
             self.gr_order = order
             return
-        
+
         self.gr_order = order
 
         # get list of forward and reverse rms error values for each point
         self.grwiz.SwitchEnv('source')
-        
+
         if map == 'source':
             ret = RunCommand('m.transform',
-                             parent = self,
-                             read = True,
-                             group = self.xygroup,
-                             order = 1,
-                             format = 'dst',
-                             coords = coord_file)
+                             parent=self,
+                             read=True,
+                             group=self.xygroup,
+                             order=1,
+                             format='dst',
+                             coords=coord_file)
 
         elif map == 'target':
             ret = RunCommand('m.transform',
-                             parent = self,
-                             read = True,
-                             group = self.xygroup,
-                             order = 1,
-                             flags = 'r',
-                             format = 'src',
-                             coords = coord_file)
+                             parent=self,
+                             read=True,
+                             group=self.xygroup,
+                             order=1,
+                             flags='r',
+                             format='src',
+                             coords=coord_file)
 
         os.unlink(coord_file)
-        
+
         self.grwiz.SwitchEnv('target')
 
         if ret:
             errlist = ret.splitlines()
         else:
-            GError(parent = self,
+            GError(parent=self,
                    message=_('Could not calculate new extends.\n'
                              'Possible error with m.transform.'))
             return
@@ -1788,7 +1969,8 @@
     def UpdateActive(self, win):
 
         # optionally disable tool zoomback tool
-        self.GetMapToolbar().Enable('zoomback', enable = (len(self.MapWindow.zoomhistory) > 1))
+        self.GetMapToolbar().Enable('zoomback',
+                                    enable=(len(self.MapWindow.zoomhistory) > 1))
 
         if self.activemap.GetSelection() != (win == self.TgtMapWindow):
             self.activemap.SetSelection(win == self.TgtMapWindow)
@@ -1805,7 +1987,7 @@
         self.Map.region['w'] = newreg['w']
 
         self.MapWindow.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
-                 self.Map.region['e'], self.Map.region['w'])
+                                   self.Map.region['e'], self.Map.region['w'])
 
         # LL locations
         if self.Map.projinfo['proj'] == 'll':
@@ -1813,19 +1995,20 @@
                 newreg['n'] = 90.0
             if newreg['s'] < -90.0:
                 newreg['s'] = -90.0
-        
+
         ce = newreg['w'] + (newreg['e'] - newreg['w']) / 2
         cn = newreg['s'] + (newreg['n'] - newreg['s']) / 2
-        
+
         # calculate new center point and display resolution
         self.Map.region['center_easting'] = ce
         self.Map.region['center_northing'] = cn
         self.Map.region["ewres"] = (newreg['e'] - newreg['w']) / self.Map.width
-        self.Map.region["nsres"] = (newreg['n'] - newreg['s']) / self.Map.height
+        self.Map.region["nsres"] = (
+            newreg['n'] - newreg['s']) / self.Map.height
         self.Map.AlignExtentFromDisplay()
 
         self.MapWindow.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
-                 self.Map.region['e'], self.Map.region['w'])
+                                   self.Map.region['e'], self.Map.region['w'])
 
         if self.MapWindow.redrawAll is False:
             self.MapWindow.redrawAll = True
@@ -1868,11 +2051,13 @@
         zoommenu = wx.Menu()
         # Add items to the menu
 
-        zoomsource = wx.MenuItem(zoommenu, wx.ID_ANY, _('Adjust source display to target display'))
+        zoomsource = wx.MenuItem(zoommenu, wx.ID_ANY, _(
+            'Adjust source display to target display'))
         zoommenu.AppendItem(zoomsource)
         self.Bind(wx.EVT_MENU, self.OnZoomToTarget, zoomsource)
 
-        zoomtarget = wx.MenuItem(zoommenu, wx.ID_ANY, _('Adjust target display to source display'))
+        zoomtarget = wx.MenuItem(zoommenu, wx.ID_ANY, _(
+            'Adjust target display to source display'))
         zoommenu.AppendItem(zoomtarget)
         self.Bind(wx.EVT_MENU, self.OnZoomToSource, zoomtarget)
 
@@ -1880,7 +2065,7 @@
         # will be called before PopupMenu returns.
         self.PopupMenu(zoommenu)
         zoommenu.Destroy()
-        
+
     def OnSize(self, event):
         """Adjust Map Windows after GCP Map Display has been resized
         """
@@ -1909,10 +2094,11 @@
                 event.RequestMore()
         pass
 
+
 class GCPList(wx.ListCtrl,
               CheckListCtrlMixin,
               ListCtrlAutoWidthMixin):
-              
+
     def __init__(self, parent, gcp, id=wx.ID_ANY,
                  pos=wx.DefaultPosition, size=wx.DefaultSize,
                  style=wx.LC_REPORT | wx.SUNKEN_BORDER | wx.LC_HRULES |
@@ -1920,7 +2106,7 @@
 
         wx.ListCtrl.__init__(self, parent, id, pos, size, style)
 
-        self.gcp = gcp # GCP class
+        self.gcp = gcp  # GCP class
         self.render = True
 
         # Mixin settings
@@ -1929,7 +2115,7 @@
         # TextEditMixin.__init__(self)
 
         # tracks whether list items are checked or not
-        self.CheckList = [] 
+        self.CheckList = []
 
         self._Create()
 
@@ -1946,29 +2132,30 @@
             # normal, simple columns
             idx_col = 0
             for col in (_('use'),
-                _('source E'),
-                _('source N'),
-                _('target E'),
-                _('target N'),
-                _('Forward error'),
-                _('Backward error')):
+                        _('source E'),
+                        _('source N'),
+                        _('target E'),
+                        _('target N'),
+                        _('Forward error'),
+                        _('Backward error')):
                 self.InsertColumn(idx_col, col)
                 idx_col += 1
         else:
             # the hard way: we want images on the column header
             info = wx.ListItem()
-            info.SetMask(wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT)
+            info.SetMask(
+                wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT)
             info.SetImage(-1)
             info.m_format = wx.LIST_FORMAT_LEFT
 
             idx_col = 0
             for lbl in (_('use'),
-                _('source E'),
-                _('source N'),
-                _('target E'),
-                _('target N'),
-                _('Forward error'),
-                _('Backward error')):
+                        _('source E'),
+                        _('source N'),
+                        _('target E'),
+                        _('target N'),
+                        _('Forward error'),
+                        _('Backward error')):
                 info.SetText(lbl)
                 self.InsertColumnInfo(idx_col, info)
                 idx_col += 1
@@ -2007,7 +2194,7 @@
             if self.gcp.show_target:
                 targetMapWin = self.gcp.TgtMapWindow
                 targetMapWin.UpdateMap(render=False, renderVector=False)
-    
+
     def AddGCPItem(self):
         """
         Appends an item to GCP list
@@ -2030,10 +2217,12 @@
                           wx.LIST_STATE_SELECTED)
 
         self.ResizeColumns()
-        
-        self.gcp.pointsToDrawSrc.AddItem(coords = [0,0], label = str(self.selectedkey))
-        self.gcp.pointsToDrawTgt.AddItem(coords = [0,0], label = str(self.selectedkey))
-        
+
+        self.gcp.pointsToDrawSrc.AddItem(
+            coords=[0, 0], label=str(self.selectedkey))
+        self.gcp.pointsToDrawTgt.AddItem(
+            coords=[0, 0], label=str(self.selectedkey))
+
         self.EnsureVisible(self.selected)
 
         return self.selected
@@ -2046,16 +2235,16 @@
 
         key = self.GetItemData(self.selected)
         self.DeleteItem(self.selected)
-        
+
         if self.selected != wx.NOT_FOUND:
             item = self.gcp.pointsToDrawSrc.GetItem(key - 1)
             self.gcp.pointsToDrawSrc.DeleteItem(item)
-            
+
             item = self.gcp.pointsToDrawTgt.GetItem(key - 1)
             self.gcp.pointsToDrawTgt.DeleteItem(item)
-        
+
         return key
-        
+
     def ResizeColumns(self):
         """Resize columns"""
         minWidth = [90, 120]
@@ -2064,7 +2253,7 @@
             # first column is checkbox, don't set to minWidth
             if i > 0 and self.GetColumnWidth(i) < minWidth[i > 4]:
                 self.SetColumnWidth(i, minWidth[i > 4])
-        
+
         self.SendSizeEvent()
 
     def GetSelected(self):
@@ -2099,11 +2288,11 @@
         dlg = EditGCP(parent=self, id=wx.ID_ANY, data=coords, gcpno=key)
 
         if dlg.ShowModal() == wx.ID_OK:
-            values = dlg.GetValues() # string
-            
+            values = dlg.GetValues()  # string
+
             if len(values) == 0:
-                GError(parent = self,
-                       message=_("Invalid coordinate value. Operation canceled."))
+                GError(parent=self, message=_(
+                    "Invalid coordinate value. Operation canceled."))
             else:
                 for i in range(len(values)):
                     if values[i] != coords[i]:
@@ -2122,39 +2311,41 @@
                                                   float(values[3]),
                                                   0.0,
                                                   0.0]
-                    
-                    self.gcp.pointsToDrawSrc.GetItem(key - 1).SetCoords([float(values[0]), 
-                                                                         float(values[1])])
-                    self.gcp.pointsToDrawTgt.GetItem(key - 1).SetCoords([float(values[2]), 
-                                                                         float(values[3])])
+
+                    self.gcp.pointsToDrawSrc.GetItem(
+                        key - 1).SetCoords([float(values[0]), float(values[1])])
+                    self.gcp.pointsToDrawTgt.GetItem(
+                        key - 1).SetCoords([float(values[2]), float(values[3])])
                     self.gcp.UpdateColours()
-                    
+
     def OnColClick(self, event):
         """ListCtrl forgets selected item..."""
         self.selected = self.FindItemData(-1, self.selectedkey)
         self.SetItemState(self.selected,
                           wx.LIST_STATE_SELECTED,
                           wx.LIST_STATE_SELECTED)
-        
+
         event.Skip()
 
+
 class VectGroup(wx.Dialog):
     """Dialog to create a vector group (VREF file) for georectifying
 
     .. todo::
         Replace by g.group
     """
+
     def __init__(self, parent, id, grassdb, location, mapset, group,
                  style=wx.DEFAULT_DIALOG_STYLE):
-        
+
         wx.Dialog.__init__(self, parent, id, style=style,
-                           title = _("Create vector map group"))
-        
+                           title=_("Create vector map group"))
+
         self.grassdatabase = grassdb
         self.xylocation = location
         self.xymapset = mapset
         self.xygroup = group
-        
+
         #
         # get list of valid vector directories
         #
@@ -2164,15 +2355,15 @@
                                            'vector'))
         for dir in vectlist:
             if not os.path.isfile(os.path.join(self.grassdatabase,
-                                           self.xylocation,
-                                           self.xymapset,
-                                           'vector',
-                                           dir,
-                                           'coor')):
+                                               self.xylocation,
+                                               self.xymapset,
+                                               'vector',
+                                               dir,
+                                               'coor')):
                 vectlist.remove(dir)
-        
+
         utils.ListSortLower(vectlist)
-        
+
         # path to vref file
         self.vgrpfile = os.path.join(self.grassdatabase,
                                      self.xylocation,
@@ -2180,23 +2371,22 @@
                                      'group',
                                      self.xygroup,
                                      'VREF')
-        
+
         #
         # buttons
         #
-        self.btnCancel = wx.Button(parent = self,
-                                   id = wx.ID_CANCEL)
-        self.btnOK = wx.Button(parent = self,
-                                   id = wx.ID_OK)
+        self.btnCancel = wx.Button(parent=self,
+                                   id=wx.ID_CANCEL)
+        self.btnOK = wx.Button(parent=self,
+                               id=wx.ID_OK)
         self.btnOK.SetDefault()
 
-
         #
         # list of vector maps
         #
-        self.listMap = wx.CheckListBox(parent = self, id = wx.ID_ANY,
-                                      choices = vectlist)
-        
+        self.listMap = wx.CheckListBox(parent=self, id=wx.ID_ANY,
+                                       choices=vectlist)
+
         if os.path.isfile(self.vgrpfile):
             f = open(self.vgrpfile)
             try:
@@ -2209,64 +2399,71 @@
                 self.listMap.SetCheckedStrings(checked)
             finally:
                 f.close()
-                
-        line = wx.StaticLine(parent = self,
-                             id = wx.ID_ANY, size = (20, -1),
-                             style = wx.LI_HORIZONTAL)
 
+        line = wx.StaticLine(parent=self,
+                             id=wx.ID_ANY, size=(20, -1),
+                             style=wx.LI_HORIZONTAL)
+
         #
         # layout
         #
         sizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         box = wx.BoxSizer(wx.HORIZONTAL)
-        box.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
-                                     label = _('Select vector map(s) to add to group:')),
-                flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
-                border = 5)
+        box.Add(
+            item=wx.StaticText(
+                parent=self,
+                id=wx.ID_ANY,
+                label=_('Select vector map(s) to add to group:')),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
+            border=5)
 
-        box.Add(item = self.listMap,
-                flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
-                border = 5)
+        box.Add(item=self.listMap,
+                flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
+                border=5)
 
-        
-        sizer.Add(box, flag = wx.ALIGN_RIGHT | wx.ALL,
-                  border = 3)
-        
-        sizer.Add(item = line, proportion = 0,
-                  flag = wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
-                  border = 5)
-        
+        sizer.Add(box, flag=wx.ALIGN_RIGHT | wx.ALL,
+                  border=3)
+
+        sizer.Add(item=line, proportion=0,
+                  flag=wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+                  border=5)
+
         # buttons
         btnSizer = wx.StdDialogButtonSizer()
         btnSizer.AddButton(self.btnCancel)
         btnSizer.AddButton(self.btnOK)
         btnSizer.Realize()
 
-        sizer.Add(item = btnSizer, proportion = 0,
-                  flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER,
-                  border = 5)
-        
+        sizer.Add(item=btnSizer, proportion=0,
+                  flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER,
+                  border=5)
+
         self.SetSizer(sizer)
         sizer.Fit(self)
         self.Layout()
-        
+
     def MakeVGroup(self):
         """Create VREF file"""
         vgrouplist = []
         for item in range(self.listMap.GetCount()):
             if not self.listMap.IsChecked(item):
                 continue
-            vgrouplist.append(self.listMap.GetString(item) + '@' + self.xymapset)
-        
+            vgrouplist.append(
+                self.listMap.GetString(item) +
+                '@' +
+                self.xymapset)
+
         f = open(self.vgrpfile, mode='w')
         try:
             for vect in vgrouplist:
                 f.write(vect + '\n')
         finally:
             f.close()
-        
+
+
 class EditGCP(wx.Dialog):
+
     def __init__(self, parent, data, gcpno, id=wx.ID_ANY,
                  title=_("Edit GCP"),
                  style=wx.DEFAULT_DIALOG_STYLE):
@@ -2278,13 +2475,14 @@
 
         sizer = wx.BoxSizer(wx.VERTICAL)
 
-        box = wx.StaticBox (parent=panel, id=wx.ID_ANY,
-                            label=" %s %s " % (_("Ground Control Point No."), str(gcpno)))
+        box = wx.StaticBox(
+            parent=panel, id=wx.ID_ANY, label=" %s %s " %
+            (_("Ground Control Point No."), str(gcpno)))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
 
         # source coordinates
         gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
-       
+
         self.xcoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
         self.ycoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
         self.ecoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
@@ -2294,7 +2492,7 @@
         tmp_coord = data[1]
         data[1] = data[2]
         data[2] = tmp_coord
-        
+
         row = 0
         col = 0
         idx = 0
@@ -2322,7 +2520,7 @@
                 col = 0
 
         boxSizer.Add(item=gridSizer, proportion=1,
-                  flag=wx.EXPAND | wx.ALL, border=5)
+                     flag=wx.EXPAND | wx.ALL, border=5)
 
         sizer.Add(item=boxSizer, proportion=1,
                   flag=wx.EXPAND | wx.ALL, border=5)
@@ -2364,9 +2562,12 @@
 
         return valuelist
 
+
 class GrSettingsDialog(wx.Dialog):
-    def __init__(self, parent, id, giface, title, pos=wx.DefaultPosition, size=wx.DefaultSize,
-                 style=wx.DEFAULT_DIALOG_STYLE):
+
+    def __init__(
+            self, parent, id, giface, title, pos=wx.DefaultPosition,
+            size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE):
         wx.Dialog.__init__(self, parent, id, title, pos, size, style)
         """
         Dialog to set profile text options: font, title
@@ -2377,16 +2578,16 @@
         #
         self.parent = parent
         self.new_src_map = src_map
-        self.new_tgt_map = { 'raster' : tgt_map['raster'],
-                             'vector' : tgt_map['vector'] }
+        self.new_tgt_map = {'raster': tgt_map['raster'],
+                            'vector': tgt_map['vector']}
         self.sdfactor = 0
 
         self.symbol = {}
-        
+
         self.methods = ["nearest",
                         "linear",
                         "linear_f",
-                        "cubic", 
+                        "cubic",
                         "cubic_f",
                         "lanczos",
                         "lanczos_f"]
@@ -2406,7 +2607,8 @@
         btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
         btnApply.SetToolTipString(_("Apply changes for the current session"))
         btnSave.Bind(wx.EVT_BUTTON, self.OnSave)
-        btnSave.SetToolTipString(_("Apply and save changes to user settings file (default for next sessions)"))
+        btnSave.SetToolTipString(
+            _("Apply and save changes to user settings file (default for next sessions)"))
         btnClose.Bind(wx.EVT_BUTTON, self.OnClose)
         btnClose.SetToolTipString(_("Close dialog"))
 
@@ -2415,17 +2617,21 @@
         btnSizer.Add(btnApply, flag=wx.LEFT | wx.RIGHT, border=5)
         btnSizer.Add(btnSave, flag=wx.LEFT | wx.RIGHT, border=5)
         btnSizer.Add(btnClose, flag=wx.LEFT | wx.RIGHT, border=5)
-        
+
         # sizers
         mainSizer = wx.BoxSizer(wx.VERTICAL)
-        mainSizer.Add(item=notebook, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
+        mainSizer.Add(
+            item=notebook,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
         mainSizer.Add(item=btnSizer, proportion=0,
-                       flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
+                      flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
         #              flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
 
         self.SetSizer(mainSizer)
         mainSizer.Fit(self)
-        
+
     def __CreateSymbologyPage(self, notebook):
         """Create notebook page with symbology settings"""
 
@@ -2437,24 +2643,41 @@
         rmsgridSizer = wx.GridBagSizer(vgap=5, hgap=5)
 
         # highlight only highest forward RMS error
-        self.highlighthighest = wx.CheckBox(parent=panel, id=wx.ID_ANY,
-                                label=_("Highlight highest RMS error only"))
+        self.highlighthighest = wx.CheckBox(
+            parent=panel, id=wx.ID_ANY,
+            label=_("Highlight highest RMS error only"))
         hh = UserSettings.Get(group='gcpman', key='rms', subkey='highestonly')
         self.highlighthighest.SetValue(hh)
-        rmsgridSizer.Add(item=self.highlighthighest, flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 0))
+        rmsgridSizer.Add(
+            item=self.highlighthighest,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                0,
+                0))
 
         # RMS forward error threshold
-        rmslabel = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Highlight RMS error > M + SD * factor:"))
-        rmslabel.SetToolTip(wx.ToolTip(_("Highlight GCPs with an RMS error larger than \n"
-                              "mean + standard deviation * given factor. \n"
-                              "Recommended values for this factor are between 1 and 2.")))
-        rmsgridSizer.Add(item=rmslabel, flag=wx.ALIGN_CENTER_VERTICAL, pos=(1, 0))
-        sdfactor = UserSettings.Get(group='gcpman', key='rms', subkey='sdfactor')
+        rmslabel = wx.StaticText(
+            parent=panel, id=wx.ID_ANY,
+            label=_("Highlight RMS error > M + SD * factor:"))
+        rmslabel.SetToolTip(
+            wx.ToolTip(
+                _(
+                    "Highlight GCPs with an RMS error larger than \n"
+                    "mean + standard deviation * given factor. \n"
+                    "Recommended values for this factor are between 1 and 2.")))
+        rmsgridSizer.Add(
+            item=rmslabel,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                1,
+                0))
+        sdfactor = UserSettings.Get(
+            group='gcpman', key='rms', subkey='sdfactor')
         self.rmsWin = wx.TextCtrl(parent=panel, id=wx.ID_ANY,
-                       size=(70,-1), style=wx.TE_NOHIDESEL)
+                                  size=(70, -1), style=wx.TE_NOHIDESEL)
         self.rmsWin.SetValue("%s" % str(sdfactor))
         if (self.parent.highest_only == True):
-           self.rmsWin.Disable()
+            self.rmsWin.Disable()
 
         self.symbol['sdfactor'] = self.rmsWin.GetId()
         rmsgridSizer.Add(item=self.rmsWin, flag=wx.ALIGN_RIGHT, pos=(1, 1))
@@ -2487,14 +2710,17 @@
         # symbol color for high forward RMS error
         #
         row += 1
-        label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Color for high RMS error:"))
+        label = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Color for high RMS error:"))
         gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
         hcol = UserSettings.Get(group='gcpman', key='symbol', subkey='hcolor')
         hcolWin = csel.ColourSelect(parent=panel, id=wx.ID_ANY,
-                                   colour=wx.Colour(hcol[0],
-                                                    hcol[1],
-                                                    hcol[2],
-                                                    255))
+                                    colour=wx.Colour(hcol[0],
+                                                     hcol[1],
+                                                     hcol[2],
+                                                     255))
         self.symbol['hcolor'] = hcolWin.GetId()
         gridSizer.Add(item=hcolWin,
                       flag=wx.ALIGN_RIGHT,
@@ -2504,14 +2730,17 @@
         # symbol color for selected GCP
         #
         row += 1
-        label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Color for selected GCP:"))
+        label = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Color for selected GCP:"))
         gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
         scol = UserSettings.Get(group='gcpman', key='symbol', subkey='scolor')
         scolWin = csel.ColourSelect(parent=panel, id=wx.ID_ANY,
-                                   colour=wx.Colour(scol[0],
-                                                    scol[1],
-                                                    scol[2],
-                                                    255))
+                                    colour=wx.Colour(scol[0],
+                                                     scol[1],
+                                                     scol[2],
+                                                     255))
         self.symbol['scolor'] = scolWin.GetId()
         gridSizer.Add(item=scolWin,
                       flag=wx.ALIGN_RIGHT,
@@ -2521,14 +2750,17 @@
         # symbol color for unused GCP
         #
         row += 1
-        label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Color for unused GCPs:"))
+        label = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Color for unused GCPs:"))
         gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
         ucol = UserSettings.Get(group='gcpman', key='symbol', subkey='ucolor')
         ucolWin = csel.ColourSelect(parent=panel, id=wx.ID_ANY,
-                                   colour=wx.Colour(ucol[0],
-                                                    ucol[1],
-                                                    ucol[2],
-                                                    255))
+                                    colour=wx.Colour(ucol[0],
+                                                     ucol[1],
+                                                     ucol[2],
+                                                     255))
         self.symbol['ucolor'] = ucolWin.GetId()
         gridSizer.Add(item=ucolWin,
                       flag=wx.ALIGN_RIGHT,
@@ -2537,33 +2769,52 @@
         # show unused GCPs
         row += 1
         self.showunused = wx.CheckBox(parent=panel, id=wx.ID_ANY,
-                                label=_("Show unused GCPs"))
+                                      label=_("Show unused GCPs"))
         shuu = UserSettings.Get(group='gcpman', key='symbol', subkey='unused')
         self.showunused.SetValue(shuu)
-        gridSizer.Add(item=self.showunused, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
+        gridSizer.Add(
+            item=self.showunused,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                row,
+                0))
 
         #
         # symbol size
         #
         row += 1
-        label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Symbol size:"))
+        label = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Symbol size:"))
         gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
-        symsize = int(UserSettings.Get(group='gcpman', key='symbol', subkey='size'))
+        symsize = int(
+            UserSettings.Get(
+                group='gcpman',
+                key='symbol',
+                subkey='size'))
         sizeWin = wx.SpinCtrl(parent=panel, id=wx.ID_ANY,
-                             min=1, max=20)
+                              min=1, max=20)
         sizeWin.SetValue(symsize)
         self.symbol['size'] = sizeWin.GetId()
         gridSizer.Add(item=sizeWin,
                       flag=wx.ALIGN_RIGHT,
                       pos=(row, 1))
-        
+
         #
         # symbol width
         #
         row += 1
-        label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Line width:"))
+        label = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Line width:"))
         gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
-        width = int(UserSettings.Get(group='gcpman', key='symbol', subkey='width'))
+        width = int(
+            UserSettings.Get(
+                group='gcpman',
+                key='symbol',
+                subkey='width'))
         widWin = wx.SpinCtrl(parent=panel, id=wx.ID_ANY,
                              min=1, max=10)
         widWin.SetValue(width)
@@ -2572,7 +2823,7 @@
                       flag=wx.ALIGN_RIGHT,
                       pos=(row, 1))
         gridSizer.AddGrowableCol(1)
-        
+
         boxSizer.Add(item=gridSizer, flag=wx.EXPAND)
         sizer.Add(item=boxSizer, flag=wx.EXPAND | wx.ALL, border=5)
 
@@ -2580,39 +2831,72 @@
         # maps to display
         #
         # source map to display
-        self.srcselection = Select(panel, id=wx.ID_ANY,
-                                   size=globalvar.DIALOG_GSELECT_SIZE, type='maptype', updateOnPopup = False)
+        self.srcselection = Select(
+            panel,
+            id=wx.ID_ANY,
+            size=globalvar.DIALOG_GSELECT_SIZE,
+            type='maptype',
+            updateOnPopup=False)
         self.parent.grwiz.SwitchEnv('source')
         self.srcselection.SetElementList(maptype)
         # filter out all maps not in group
-        self.srcselection.tcp.GetElementList(elements = self.parent.src_maps)
+        self.srcselection.tcp.GetElementList(elements=self.parent.src_maps)
 
         # target map(s) to display
         self.parent.grwiz.SwitchEnv('target')
-        self.tgtrastselection = Select(panel, id=wx.ID_ANY,
-                                   size=globalvar.DIALOG_GSELECT_SIZE, type='raster', updateOnPopup = False)
+        self.tgtrastselection = Select(
+            panel, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
+            type='raster', updateOnPopup=False)
         self.tgtrastselection.SetElementList('cell')
         self.tgtrastselection.GetElementList()
 
-        self.tgtvectselection = Select(panel, id=wx.ID_ANY,
-                                   size=globalvar.DIALOG_GSELECT_SIZE, type='vector', updateOnPopup = False)
+        self.tgtvectselection = Select(
+            panel, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
+            type='vector', updateOnPopup=False)
         self.tgtvectselection.SetElementList('vector')
         self.tgtvectselection.GetElementList()
 
-        sizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_('Select source map to display:')),
-                       proportion=0, flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
-        sizer.Add(item=self.srcselection, proportion=0, 
-                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
+        sizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_('Select source map to display:')),
+            proportion=0,
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5)
+        sizer.Add(
+            item=self.srcselection,
+            proportion=0,
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5)
         self.srcselection.SetValue(src_map)
-        sizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_('Select target raster map to display:')),
-                       proportion=0, flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
-        sizer.Add(item=self.tgtrastselection, proportion=0, 
-                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
+        sizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_('Select target raster map to display:')),
+            proportion=0,
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5)
+        sizer.Add(
+            item=self.tgtrastselection,
+            proportion=0,
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5)
         self.tgtrastselection.SetValue(tgt_map['raster'])
-        sizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_('Select target vector map to display:')),
-                       proportion=0, flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
-        sizer.Add(item=self.tgtvectselection, proportion=0, 
-                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
+        sizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_('Select target vector map to display:')),
+            proportion=0,
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5)
+        sizer.Add(
+            item=self.tgtvectselection,
+            proportion=0,
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5)
         self.tgtvectselection.SetValue(tgt_map['vector'])
 
         # bindings
@@ -2623,7 +2907,7 @@
         self.tgtvectselection.Bind(wx.EVT_TEXT, self.OnTgtVectSelection)
 
         panel.SetSizer(sizer)
-        
+
         return panel
 
     def __CreateRectificationPage(self, notebook):
@@ -2635,40 +2919,65 @@
         sizer = wx.BoxSizer(wx.VERTICAL)
 
         # transformation order
-        self.rb_grorder = wx.RadioBox(parent=panel, id=wx.ID_ANY,
-                                       label=" %s " % _("Select rectification order"),
-                                       choices=[_('1st order'), _('2nd order'), _('3rd order')],
-                                       majorDimension=wx.RA_SPECIFY_COLS)
+        self.rb_grorder = wx.RadioBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Select rectification order"),
+            choices=[
+                _('1st order'),
+                _('2nd order'),
+                _('3rd order')],
+            majorDimension=wx.RA_SPECIFY_COLS)
         sizer.Add(item=self.rb_grorder, proportion=0,
-                       flag=wx.EXPAND | wx.ALL, border=5)
+                  flag=wx.EXPAND | wx.ALL, border=5)
         self.rb_grorder.SetSelection(self.parent.gr_order - 1)
 
         # interpolation method
         gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
-        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_('Select interpolation method:')),
-                       pos=(0,0), flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_('Select interpolation method:')),
+            pos=(
+                0,
+                0),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5)
         self.grmethod = wx.Choice(parent=panel, id=wx.ID_ANY,
-                                  choices = self.methods)
-        gridSizer.Add(item=self.grmethod, pos=(0,1),
-                       flag=wx.ALIGN_RIGHT, border=5)
+                                  choices=self.methods)
+        gridSizer.Add(item=self.grmethod, pos=(0, 1),
+                      flag=wx.ALIGN_RIGHT, border=5)
         self.grmethod.SetStringSelection(self.parent.gr_method)
         gridSizer.AddGrowableCol(1)
         sizer.Add(item=gridSizer, flag=wx.EXPAND | wx.ALL, border=5)
 
         # clip to region
-        self.check = wx.CheckBox(parent=panel, id=wx.ID_ANY,
-                                label=_("clip to computational region in target location"))
+        self.check = wx.CheckBox(parent=panel, id=wx.ID_ANY, label=_(
+            "clip to computational region in target location"))
         sizer.Add(item=self.check, proportion=0,
-                       flag=wx.EXPAND | wx.ALL, border=5)
+                  flag=wx.EXPAND | wx.ALL, border=5)
         self.check.SetValue(self.parent.clip_to_region)
 
         # extension
-        sizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_('Extension for output maps:')),
-                       proportion=0, flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
-        self.ext_txt = wx.TextCtrl(parent=panel, id=wx.ID_ANY, value="", size=(350,-1))
+        sizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_('Extension for output maps:')),
+            proportion=0,
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5)
+        self.ext_txt = wx.TextCtrl(
+            parent=panel, id=wx.ID_ANY, value="", size=(
+                350, -1))
         self.ext_txt.SetValue(self.parent.extension)
-        sizer.Add(item=self.ext_txt,
-                       proportion=0, flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
+        sizer.Add(
+            item=self.ext_txt,
+            proportion=0,
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5)
 
         # bindings
         self.ext_txt.Bind(wx.EVT_TEXT, self.OnExtension)
@@ -2677,7 +2986,7 @@
         self.Bind(wx.EVT_CHECKBOX, self.OnClipRegion, self.check)
 
         panel.SetSizer(sizer)
-        
+
         return panel
 
     def OnHighlight(self, event):
@@ -2689,36 +2998,36 @@
             self.parent.highest_only = False
             self.rmsWin.Enable()
 
-    def OnSDFactor(self,event):
+    def OnSDFactor(self, event):
         """New factor for RMS threshold = M + SD * factor"""
         try:
             self.sdfactor = float(self.rmsWin.GetValue())
         except ValueError:
             return
         if self.sdfactor <= 0:
-            GError(parent = self,
+            GError(parent=self,
                    message=_('RMS threshold factor must be > 0'))
         elif self.sdfactor < 1:
-            GError(parent = self,
+            GError(parent=self,
                    message=_('RMS threshold factor is < 1\n'
                              'Too many points might be highlighted'))
-        
-    def OnSrcSelection(self,event):
+
+    def OnSrcSelection(self, event):
         """Source map to display selected"""
         global src_map
 
         tmp_map = self.srcselection.GetValue()
-        
+
         if not tmp_map == '' and not tmp_map == src_map:
             self.new_src_map = tmp_map
 
-    def OnTgtRastSelection(self,event):
+    def OnTgtRastSelection(self, event):
         """Target map to display selected"""
         global tgt_map
 
         self.new_tgt_map['raster'] = self.tgtrastselection.GetValue()
 
-    def OnTgtVectSelection(self,event):
+    def OnTgtVectSelection(self, event):
         """Target map to display selected"""
         global tgt_map
 
@@ -2729,7 +3038,7 @@
 
     def OnClipRegion(self, event):
         self.parent.clip_to_region = event.IsChecked()
-        
+
     def OnExtension(self, event):
         self.parent.extension = self.ext_txt.GetValue()
 
@@ -2740,32 +3049,60 @@
 
         layers = None
 
-        UserSettings.Set(group = 'gcpman', key = 'rms', subkey = 'highestonly',
-                         value = self.highlighthighest.GetValue())
-        
+        UserSettings.Set(group='gcpman', key='rms', subkey='highestonly',
+                         value=self.highlighthighest.GetValue())
+
         if self.sdfactor > 0:
             UserSettings.Set(group='gcpman', key='rms', subkey='sdfactor',
                              value=self.sdfactor)
-            
+
             self.parent.sdfactor = self.sdfactor
             if self.parent.rmsthresh > 0:
                 self.parent.rmsthresh = self.parent.rmsmean + self.parent.sdfactor * self.parent.rmssd
-        
-        UserSettings.Set(group='gcpman', key='symbol', subkey='color',
-                         value=tuple(wx.FindWindowById(self.symbol['color']).GetColour()))
-        UserSettings.Set(group='gcpman', key='symbol', subkey='hcolor',
-                         value=tuple(wx.FindWindowById(self.symbol['hcolor']).GetColour()))
-        UserSettings.Set(group='gcpman', key='symbol', subkey='scolor',
-                         value=tuple(wx.FindWindowById(self.symbol['scolor']).GetColour()))
-        UserSettings.Set(group='gcpman', key='symbol', subkey='ucolor',
-                         value=tuple(wx.FindWindowById(self.symbol['ucolor']).GetColour()))
+
+        UserSettings.Set(
+            group='gcpman',
+            key='symbol',
+            subkey='color',
+            value=tuple(
+                wx.FindWindowById(
+                    self.symbol['color']).GetColour()))
+        UserSettings.Set(
+            group='gcpman',
+            key='symbol',
+            subkey='hcolor',
+            value=tuple(
+                wx.FindWindowById(
+                    self.symbol['hcolor']).GetColour()))
+        UserSettings.Set(
+            group='gcpman',
+            key='symbol',
+            subkey='scolor',
+            value=tuple(
+                wx.FindWindowById(
+                    self.symbol['scolor']).GetColour()))
+        UserSettings.Set(
+            group='gcpman',
+            key='symbol',
+            subkey='ucolor',
+            value=tuple(
+                wx.FindWindowById(
+                    self.symbol['ucolor']).GetColour()))
         UserSettings.Set(group='gcpman', key='symbol', subkey='unused',
                          value=self.showunused.GetValue())
-        UserSettings.Set(group='gcpman', key='symbol', subkey='size',
-                         value=wx.FindWindowById(self.symbol['size']).GetValue())
-        UserSettings.Set(group='gcpman', key='symbol', subkey='width',
-                         value=wx.FindWindowById(self.symbol['width']).GetValue())
-        
+        UserSettings.Set(
+            group='gcpman',
+            key='symbol',
+            subkey='size',
+            value=wx.FindWindowById(
+                self.symbol['size']).GetValue())
+        UserSettings.Set(
+            group='gcpman',
+            key='symbol',
+            subkey='width',
+            value=wx.FindWindowById(
+                self.symbol['width']).GetValue())
+
         srcrender = False
         srcrenderVector = False
         tgtrender = False
@@ -2775,7 +3112,7 @@
             # remove old layer
             layers = self.parent.grwiz.SrcMap.GetListOfLayers()
             self.parent.grwiz.SrcMap.DeleteLayer(layers[0])
-            
+
             src_map = self.new_src_map
             if maptype == 'raster':
                 cmdlist = ['d.rast', 'map=%s' % src_map]
@@ -2785,8 +3122,9 @@
                 srcrenderVector = True
             self.parent.grwiz.SwitchEnv('source')
             name, found = utils.GetLayerNameFromCmd(cmdlist)
-            self.parent.grwiz.SrcMap.AddLayer(ltype=maptype, command=cmdlist, active=True,
-                              name=name, hidden=False, opacity=1.0, render=False)
+            self.parent.grwiz.SrcMap.AddLayer(
+                ltype=maptype, command=cmdlist, active=True, name=name,
+                hidden=False, opacity=1.0, render=False)
 
             self.parent.grwiz.SwitchEnv('target')
 
@@ -2798,7 +3136,7 @@
                 self.parent.grwiz.TgtMap.DeleteLayer(layers[0])
                 del layers[0]
                 layers = self.parent.grwiz.TgtMap.GetListOfLayers()
-            #self.parent.grwiz.TgtMap.DeleteAllLayers()
+            # self.parent.grwiz.TgtMap.DeleteAllLayers()
             reload_target = True
             tgt_map['raster'] = self.new_tgt_map['raster']
             tgt_map['vector'] = self.new_tgt_map['vector']
@@ -2806,16 +3144,18 @@
             if tgt_map['raster'] != '':
                 cmdlist = ['d.rast', 'map=%s' % tgt_map['raster']]
                 name, found = utils.GetLayerNameFromCmd(cmdlist)
-                self.parent.grwiz.TgtMap.AddLayer(ltype='raster', command=cmdlist, active=True,
-                                  name=name, hidden=False, opacity=1.0, render=False)
+                self.parent.grwiz.TgtMap.AddLayer(
+                    ltype='raster', command=cmdlist, active=True, name=name,
+                    hidden=False, opacity=1.0, render=False)
 
                 tgtrender = True
 
             if tgt_map['vector'] != '':
                 cmdlist = ['d.vect', 'map=%s' % tgt_map['vector']]
                 name, found = utils.GetLayerNameFromCmd(cmdlist)
-                self.parent.grwiz.TgtMap.AddLayer(ltype='vector', command=cmdlist, active=True,
-                                  name=name, hidden=False, opacity=1.0, render=False)
+                self.parent.grwiz.TgtMap.AddLayer(
+                    ltype='vector', command=cmdlist, active=True, name=name,
+                    hidden=False, opacity=1.0, render=False)
 
                 tgtrenderVector = True
 
@@ -2826,7 +3166,7 @@
                 self.parent._mgr.Update()
                 self.parent.activemap.SetSelection(0)
                 self.parent.activemap.Enable(False)
-                self.parent.GetMapToolbar().Enable('zoommenu', enable = False)
+                self.parent.GetMapToolbar().Enable('zoommenu', enable=False)
         else:
             if self.parent.show_target == False:
                 self.parent.show_target = True
@@ -2834,12 +3174,17 @@
                 self.parent._mgr.Update()
                 self.parent.activemap.SetSelection(0)
                 self.parent.activemap.Enable(True)
-                self.parent.GetMapToolbar().Enable('zoommenu', enable = True)
-                self.parent.TgtMapWindow.ZoomToMap(layers = self.parent.TgtMap.GetListOfLayers())
-        
-        self.parent.UpdateColours(srcrender, srcrenderVector, tgtrender, tgtrenderVector)
-        self.parent.SetSettings()        
+                self.parent.GetMapToolbar().Enable('zoommenu', enable=True)
+                self.parent.TgtMapWindow.ZoomToMap(
+                    layers=self.parent.TgtMap.GetListOfLayers())
 
+        self.parent.UpdateColours(
+            srcrender,
+            srcrenderVector,
+            tgtrender,
+            tgtrenderVector)
+        self.parent.SetSettings()
+
     def OnSave(self, event):
         """Button 'Save' pressed"""
         self.UpdateSettings()
@@ -2847,13 +3192,15 @@
         UserSettings.ReadSettingsFile(settings=fileSettings)
         fileSettings['gcpman'] = UserSettings.Get(group='gcpman')
         file = UserSettings.SaveToFile(fileSettings)
-        self.parent._giface.WriteLog(_('GCP Manager settings saved to file \'%s\'.') % file)
-        #self.Close()
+        self.parent._giface.WriteLog(
+            _('GCP Manager settings saved to file \'%s\'.') %
+            file)
+        # self.Close()
 
     def OnApply(self, event):
         """Button 'Apply' pressed"""
         self.UpdateSettings()
-        #self.Close()
+        # self.Close()
 
     def OnClose(self, event):
         """Button 'Cancel' pressed"""

Modified: grass/trunk/gui/wxpython/gcp/mapdisplay.py
===================================================================
--- grass/trunk/gui/wxpython/gcp/mapdisplay.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gcp/mapdisplay.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -23,14 +23,14 @@
 import wx
 import wx.aui
 
-from mapdisp.toolbars  import MapToolbar
-from gcp.toolbars      import GCPDisplayToolbar, GCPManToolbar
-from mapdisp.gprint    import PrintOptions
-from core.gcmd         import GMessage
+from mapdisp.toolbars import MapToolbar
+from gcp.toolbars import GCPDisplayToolbar, GCPManToolbar
+from mapdisp.gprint import PrintOptions
+from core.gcmd import GMessage
 from core.utils import _
-from gui_core.dialogs  import GetImageHandlers, ImageSizeDialog
-from gui_core.mapdisp  import SingleMapFrame
-from core.settings     import UserSettings
+from gui_core.dialogs import GetImageHandlers, ImageSizeDialog
+from gui_core.mapdisp import SingleMapFrame
+from core.settings import UserSettings
 from mapwin.buffered import BufferedMapWindow
 from mapwin.base import MapWindowProperties
 
@@ -40,10 +40,12 @@
 # for standalone app
 cmdfilename = None
 
+
 class MapFrame(SingleMapFrame):
     """Main frame for map display window. Drawing takes place in
     child double buffered drawing window.
     """
+
     def __init__(self, parent, giface,
                  title=_("GRASS GIS Manage Ground Control Points"),
                  toolbars=["gcpdisp"], Map=None, auimgr=None,
@@ -58,10 +60,17 @@
         :param auimgs: AUI manager
         :param kwargs: wx.Frame attribures
         """
-        
-        SingleMapFrame.__init__(self, parent = parent, giface = giface, title = title,
-                              Map = Map, auimgr = auimgr, name = name, **kwargs)
 
+        SingleMapFrame.__init__(
+            self,
+            parent=parent,
+            giface=giface,
+            title=title,
+            Map=Map,
+            auimgr=auimgr,
+            name=name,
+            **kwargs)
+
         self._giface = giface
         # properties are shared in other objects, so defining here
         self.mapWindowProperties = MapWindowProperties()
@@ -76,15 +85,15 @@
 
         self.activemap = self.toolbars['gcpdisp'].togglemap
         self.activemap.SetSelection(0)
-        
-        self.SrcMap        = self.grwiz.SrcMap       # instance of render.Map
-        self.TgtMap        = self.grwiz.TgtMap       # instance of render.Map
+
+        self.SrcMap = self.grwiz.SrcMap       # instance of render.Map
+        self.TgtMap = self.grwiz.TgtMap       # instance of render.Map
         self._mgr.SetDockSizeConstraint(0.5, 0.5)
 
         #
         # Add statusbar
         #
-        
+
         # items for choice
         self.statusbarItems = [sb.SbCoordinates,
                                sb.SbRegionExtent,
@@ -96,32 +105,35 @@
                                sb.SbProjection,
                                sbgcp.SbGoToGCP,
                                sbgcp.SbRMSError]
-                            
-        
+
         # create statusbar and its manager
-        statusbar = self.CreateStatusBar(number = 4, style = 0)
+        statusbar = self.CreateStatusBar(number=4, style=0)
         statusbar.SetStatusWidths([-5, -2, -1, -1])
-        self.statusbarManager = sb.SbManager(mapframe = self, statusbar = statusbar)
-        
+        self.statusbarManager = sb.SbManager(
+            mapframe=self, statusbar=statusbar)
+
         # fill statusbar manager
-        self.statusbarManager.AddStatusbarItemsByClass(self.statusbarItems, mapframe = self, statusbar = statusbar)
-        self.statusbarManager.AddStatusbarItem(sb.SbMask(self, statusbar = statusbar, position = 2))
-        self.statusbarManager.AddStatusbarItem(sb.SbRender(self, statusbar = statusbar, position = 3))
-        
-        self.statusbarManager.SetMode(8) # goto GCP
+        self.statusbarManager.AddStatusbarItemsByClass(
+            self.statusbarItems, mapframe=self, statusbar=statusbar)
+        self.statusbarManager.AddStatusbarItem(
+            sb.SbMask(self, statusbar=statusbar, position=2))
+        self.statusbarManager.AddStatusbarItem(
+            sb.SbRender(self, statusbar=statusbar, position=3))
 
+        self.statusbarManager.SetMode(8)  # goto GCP
+
         #
         # Init map display (buffered DC & set default cursor)
         #
         self.grwiz.SwitchEnv('source')
-        self.SrcMapWindow = BufferedMapWindow(parent=self, giface=self._giface, id=wx.ID_ANY,
-                                              properties=self.mapWindowProperties,
-                                              Map=self.SrcMap)
+        self.SrcMapWindow = BufferedMapWindow(
+            parent=self, giface=self._giface, id=wx.ID_ANY,
+            properties=self.mapWindowProperties, Map=self.SrcMap)
 
         self.grwiz.SwitchEnv('target')
-        self.TgtMapWindow = BufferedMapWindow(parent=self, giface=self._giface, id=wx.ID_ANY,
-                                              properties=self.mapWindowProperties,
-                                              Map=self.TgtMap)
+        self.TgtMapWindow = BufferedMapWindow(
+            parent=self, giface=self._giface, id=wx.ID_ANY,
+            properties=self.mapWindowProperties, Map=self.TgtMap)
         self.MapWindow = self.SrcMapWindow
         self.Map = self.SrcMap
         self._setUpMapWindow(self.SrcMapWindow)
@@ -139,9 +151,9 @@
         #
         # initialize region values
         #
-        self._initMap(Map = self.SrcMap) 
-        self._initMap(Map = self.TgtMap) 
-        
+        self._initMap(Map=self.SrcMap)
+        self._initMap(Map=self.TgtMap)
+
         self.GetMapToolbar().SelectDefault()
 
         #
@@ -149,29 +161,30 @@
         #
         self.activemap.Bind(wx.EVT_CHOICE, self.OnUpdateActive)
         self.Bind(wx.EVT_SIZE, self.OnSize)
-        
+
         #
         # Update fancy gui style
         #
-        # AuiManager wants a CentrePane, workaround to get two equally sized windows
+        # AuiManager wants a CentrePane, workaround to get two equally sized
+        # windows
         self.list = self.CreateGCPList()
 
         #self.SrcMapWindow.SetSize((300, 300))
         #self.TgtMapWindow.SetSize((300, 300))
         self.list.SetSize((100, 150))
         self._mgr.AddPane(self.list, wx.aui.AuiPaneInfo().
-                  Name("gcplist").Caption(_("GCP List")).LeftDockable(False).
-                  RightDockable(False).PinButton().FloatingSize((600,200)).
-                  CloseButton(False).DestroyOnClose(True).
-                  Top().Layer(1).MinSize((200,100)))
+                          Name("gcplist").Caption(_("GCP List")).LeftDockable(False).
+                          RightDockable(False).PinButton().FloatingSize((600, 200)).
+                          CloseButton(False).DestroyOnClose(True).
+                          Top().Layer(1).MinSize((200, 100)))
         self._mgr.AddPane(self.SrcMapWindow, wx.aui.AuiPaneInfo().
-                  Name("source").Caption(_("Source Display")).Dockable(False).
-                  CloseButton(False).DestroyOnClose(True).Floatable(False).
-                  Centre())
+                          Name("source").Caption(_("Source Display")).Dockable(False).
+                          CloseButton(False).DestroyOnClose(True).Floatable(False).
+                          Centre())
         self._mgr.AddPane(self.TgtMapWindow, wx.aui.AuiPaneInfo().
-                  Name("target").Caption(_("Target Display")).Dockable(False).
-                  CloseButton(False).DestroyOnClose(True).Floatable(False).
-                  Right().Layer(0))
+                          Name("target").Caption(_("Target Display")).Dockable(False).
+                          CloseButton(False).DestroyOnClose(True).Floatable(False).
+                          Right().Layer(0))
 
         srcwidth, srcheight = self.SrcMapWindow.GetSize()
         tgtwidth, tgtheight = self.TgtMapWindow.GetSize()
@@ -192,7 +205,7 @@
         # Init print module and classes
         #
         self.printopt = PrintOptions(self, self.MapWindow)
-        
+
         #
         # Initialization of digitization tool
         #
@@ -201,7 +214,7 @@
         # set active map
         self.MapWindow = self.SrcMapWindow
         self.Map = self.SrcMap
-        
+
         # do not init zoom history here, that happens when zooming to map(s)
 
         #
@@ -213,7 +226,7 @@
         self.dialogs['barscale'] = None
         self.dialogs['legend'] = None
 
-        self.decorationDialog = None # decoration/overlays
+        self.decorationDialog = None  # decoration/overlays
 
         # doing nice things in statusbar when other things are ready
         self.statusbarManager.Update()
@@ -231,7 +244,7 @@
 
     def AddToolbar(self, name):
         """Add defined toolbar to the window
-        
+
         Currently known toolbars are:
          - 'map'     - basic map toolbar
          - 'vdigit'  - vector digitizer
@@ -254,7 +267,8 @@
 
         # GCP display
         elif name == "gcpdisp":
-            self.toolbars['gcpdisp'] = GCPDisplayToolbar(self, self._toolSwitcher)
+            self.toolbars['gcpdisp'] = GCPDisplayToolbar(
+                self, self._toolSwitcher)
 
             self._mgr.AddPane(self.toolbars['gcpdisp'],
                               wx.aui.AuiPaneInfo().
@@ -265,7 +279,7 @@
                               CloseButton(False).Layer(2))
 
             if self.show_target == False:
-                self.toolbars['gcpdisp'].Enable('zoommenu', enable = False)
+                self.toolbars['gcpdisp'].Enable('zoommenu', enable=False)
 
             self.toolbars['gcpman'] = GCPManToolbar(self)
 
@@ -276,7 +290,7 @@
                               LeftDockable(False).RightDockable(False).
                               BottomDockable(False).TopDockable(True).
                               CloseButton(False).Layer(2))
-            
+
         self._mgr.Update()
 
     def OnUpdateProgress(self, event):
@@ -284,9 +298,9 @@
         Update progress bar info
         """
         self.GetProgressBar().UpdateProgress(event.layer, event.map)
-        
+
         event.Skip()
-        
+
     def OnFocus(self, event):
         """
         Change choicebook page to match display.
@@ -304,8 +318,8 @@
     def OnDraw(self, event):
         """Re-display current map composition
         """
-        self.MapWindow.UpdateMap(render = False)
-        
+        self.MapWindow.UpdateMap(render=False)
+
     def OnRender(self, event):
         """Re-render map composition (each map layer)
         """
@@ -318,13 +332,13 @@
         self.SrcMapWindow.UpdateMap(render=True)
         if self.show_target:
             self.TgtMapWindow.UpdateMap(render=True)
-        
+
         # update statusbar
         self.StatusbarUpdate()
 
     def OnPointer(self, event):
         """Pointer button clicked
-        """      
+        """
         self.SrcMapWindow.SetModePointer()
         self.TgtMapWindow.SetModePointer()
         # change the default cursor
@@ -364,8 +378,8 @@
         """
         img = self.MapWindow.img
         if not img:
-            GMessage(parent = self,
-                     message = _("Nothing to render (empty map). Operation canceled."))
+            GMessage(parent=self, message=_(
+                "Nothing to render (empty map). Operation canceled."))
             return
         filetype, ltype = GetImageHandlers(img)
 
@@ -377,29 +391,29 @@
             return
         width, height = dlg.GetValues()
         dlg.Destroy()
-        
+
         # get filename
-        dlg = wx.FileDialog(parent = self,
-                            message = _("Choose a file name to save the image "
-                                        "(no need to add extension)"),
-                            wildcard = filetype,
+        dlg = wx.FileDialog(parent=self,
+                            message=_("Choose a file name to save the image "
+                                      "(no need to add extension)"),
+                            wildcard=filetype,
                             style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
-        
+
         if dlg.ShowModal() == wx.ID_OK:
             path = dlg.GetPath()
             if not path:
                 dlg.Destroy()
                 return
-            
+
             base, ext = os.path.splitext(path)
             fileType = ltype[dlg.GetFilterIndex()]['type']
-            extType  = ltype[dlg.GetFilterIndex()]['ext']
+            extType = ltype[dlg.GetFilterIndex()]['ext']
             if ext != extType:
                 path = base + '.' + extType
-            
+
             self.MapWindow.SaveToFile(path, fileType,
                                       width, height)
-            
+
         dlg.Destroy()
 
     def PrintMenu(self, event):
@@ -430,25 +444,25 @@
         """
         Set display extents to match selected raster map (ignore NULLs)
         """
-        self.MapWindow.ZoomToMap(ignoreNulls = True)
-        
+        self.MapWindow.ZoomToMap(ignoreNulls=True)
+
     def OnZoomToSaved(self, event):
         """Set display geometry to match extents in
         saved region file
         """
         self.MapWindow.SetRegion(zoomOnly=True)
-        
+
     def OnDisplayToWind(self, event):
         """Set computational region (WIND file) to match display
         extents
         """
         self.MapWindow.DisplayToWind()
- 
+
     def SaveDisplayRegion(self, event):
         """Save display extents to named region file.
         """
         self.MapWindow.SaveDisplayRegion()
-        
+
     def OnZoomMenu(self, event):
         """Popup Zoom menu
         """
@@ -456,11 +470,13 @@
         zoommenu = wx.Menu()
         # Add items to the menu
 
-        zoomwind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to computational region (set with g.region)'))
+        zoomwind = wx.MenuItem(zoommenu, wx.ID_ANY, _(
+            'Zoom to computational region (set with g.region)'))
         zoommenu.AppendItem(zoomwind)
         self.Bind(wx.EVT_MENU, self.OnZoomToWind, zoomwind)
 
-        zoomdefault = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to default region'))
+        zoomdefault = wx.MenuItem(
+            zoommenu, wx.ID_ANY, _('Zoom to default region'))
         zoommenu.AppendItem(zoomdefault)
         self.Bind(wx.EVT_MENU, self.OnZoomToDefault, zoomdefault)
 
@@ -468,11 +484,13 @@
         zoommenu.AppendItem(zoomsaved)
         self.Bind(wx.EVT_MENU, self.OnZoomToSaved, zoomsaved)
 
-        savewind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Set computational region from display'))
+        savewind = wx.MenuItem(zoommenu, wx.ID_ANY, _(
+            'Set computational region from display'))
         zoommenu.AppendItem(savewind)
         self.Bind(wx.EVT_MENU, self.OnDisplayToWind, savewind)
 
-        savezoom = wx.MenuItem(zoommenu, wx.ID_ANY, _('Save display geometry to named region'))
+        savezoom = wx.MenuItem(zoommenu, wx.ID_ANY, _(
+            'Save display geometry to named region'))
         zoommenu.AppendItem(savezoom)
         self.Bind(wx.EVT_MENU, self.SaveDisplayRegion, savezoom)
 
@@ -480,13 +498,12 @@
         # will be called before PopupMenu returns.
         self.PopupMenu(zoommenu)
         zoommenu.Destroy()
-        
-        
+
     def IsStandalone(self):
         """Check if Map display is standalone"""
         # we do not know and we do not care, so always False
         return True
-    
+
     def GetLayerManager(self):
         """Get reference to Layer Manager
 
@@ -496,13 +513,13 @@
 
     def GetSrcWindow(self):
         return self.SrcMapWindow
-        
+
     def GetTgtWindow(self):
         return self.TgtMapWindow
-    
+
     def GetShowTarget(self):
         return self.show_target
-        
+
     def GetMapToolbar(self):
         """Returns toolbar with zooming tools"""
         return self.toolbars['gcpdisp']

Modified: grass/trunk/gui/wxpython/gcp/statusbar.py
===================================================================
--- grass/trunk/gui/wxpython/gcp/statusbar.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gcp/statusbar.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -30,6 +30,7 @@
     Requires MapFrame.GetSrcWindow, MapFrame.GetTgtWindow,
     MapFrame.GetListCtrl, MapFrame.GetMapCoordList.
     """
+
     def __init__(self, mapframe, statusbar, position=0):
         SbItem.__init__(self, mapframe, statusbar, position)
         self.name = 'gotoGCP'
@@ -112,6 +113,7 @@
 
     Requires MapFrame.GetFwdError, MapFrame.GetBkwError.
     """
+
     def __init__(self, mapframe, statusbar, position=0):
         SbTextItem.__init__(self, mapframe, statusbar, position)
         self.name = 'RMSError'

Modified: grass/trunk/gui/wxpython/gcp/toolbars.py
===================================================================
--- grass/trunk/gui/wxpython/gcp/toolbars.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gcp/toolbars.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -20,7 +20,7 @@
 
 import wx
 
-from core              import globalvar
+from core import globalvar
 from core.utils import _
 from gui_core.toolbars import BaseToolbar, BaseIcons
 from icons.icon import MetaIcon
@@ -31,32 +31,33 @@
 
     :param parent: reference to GCP widget
     """
+
     def __init__(self, parent):
         BaseToolbar.__init__(self, parent)
-        
+
         self.InitToolbar(self._toolbarData())
-        
+
         # realize the toolbar
         self.Realize()
 
     def _toolbarData(self):
         icons = {
-            'gcpAdd'     : MetaIcon(img = 'gcp-add',
-                                    label = _('Add new GCP to the list')),
-            'gcpDelete'  : MetaIcon(img = 'gcp-delete',
-                                    label = _('Delete selected GCP')),
-            'gcpClear'   : MetaIcon(img = 'gcp-remove',
-                                    label = _('Clear selected GCP')),
-            'gcpRms'     : MetaIcon(img = 'gcp-rms',
-                                    label = _('Recalculate RMS error')),
-            'georectify' : MetaIcon(img = 'georectify',
-                                    label = _('Georectify')),
-            'gcpSave'    : MetaIcon(img = 'gcp-save',
-                                    label = _('Save GCPs to POINTS file')),
-            'gcpReload'  : MetaIcon(img = 'reload',
-                                    label = _('Reload GCPs from POINTS file')),
-            }
-        
+            'gcpAdd': MetaIcon(img='gcp-add',
+                               label=_('Add new GCP to the list')),
+            'gcpDelete': MetaIcon(img='gcp-delete',
+                                  label=_('Delete selected GCP')),
+            'gcpClear': MetaIcon(img='gcp-remove',
+                                 label=_('Clear selected GCP')),
+            'gcpRms': MetaIcon(img='gcp-rms',
+                               label=_('Recalculate RMS error')),
+            'georectify': MetaIcon(img='georectify',
+                                   label=_('Georectify')),
+            'gcpSave': MetaIcon(img='gcp-save',
+                                label=_('Save GCPs to POINTS file')),
+            'gcpReload': MetaIcon(img='reload',
+                                  label=_('Reload GCPs from POINTS file')),
+        }
+
         return self._getToolbarData((('gcpAdd', icons["gcpAdd"],
                                       self.parent.AddGCP),
                                      ('gcpDelete', icons["gcpDelete"],
@@ -74,48 +75,57 @@
                                      ('gcpReload', icons["gcpReload"],
                                       self.parent.ReloadGCPs))
                                     )
-    
+
+
 class GCPDisplayToolbar(BaseToolbar):
     """GCP Display toolbar
     """
+
     def __init__(self, parent, toolSwitcher):
         """GCP Display toolbar constructor
         """
         BaseToolbar.__init__(self, parent, toolSwitcher)
-        
+
         self.InitToolbar(self._toolbarData())
         self._default = self.gcpset
-        
+
         # add tool to toggle active map window
         self.togglemapid = wx.NewId()
-        self.togglemap = wx.Choice(parent = self, id = self.togglemapid,
-                                   choices = [_('source'), _('target')])
+        self.togglemap = wx.Choice(parent=self, id=self.togglemapid,
+                                   choices=[_('source'), _('target')])
 
         self.InsertControl(10, self.togglemap)
 
-        self.SetToolShortHelp(self.togglemapid, '%s %s %s' % (_('Set map canvas for '),
-                                                              BaseIcons["zoomBack"].GetLabel(),
-                                                              _(' / Zoom to map')))
+        self.SetToolShortHelp(
+            self.togglemapid, '%s %s %s' %
+            (_('Set map canvas for '),
+             BaseIcons["zoomBack"].GetLabel(),
+             _(' / Zoom to map')))
 
         for tool in (self.gcpset, self.pan, self.zoomin, self.zoomout):
-            self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=tool)
+            self.toolSwitcher.AddToolToGroup(
+                group='mouseUse', toolbar=self, tool=tool)
 
         # realize the toolbar
         self.Realize()
 
         self.EnableTool(self.zoomback, False)
-        
+
     def _toolbarData(self):
         """Toolbar data"""
         icons = {
-            'gcpSet'    : MetaIcon(img = 'gcp-create',
-                                   label = _('Update GCP coordinates'),
-                                   desc = _('Update GCP coordinates)')),
-            'quit'      : BaseIcons['quit'].SetLabel(_('Quit georectification tool')),
-            'settings'  : BaseIcons['settings'].SetLabel( _('Georectifier settings')),
-            'help'      : BaseIcons['help'].SetLabel(_('Georectifier manual')),
-            }
-        
+            'gcpSet': MetaIcon(
+                img='gcp-create',
+                label=_('Update GCP coordinates'),
+                desc=_('Update GCP coordinates)')),
+            'quit': BaseIcons['quit'].SetLabel(
+                _('Quit georectification tool')),
+            'settings': BaseIcons['settings'].SetLabel(
+                _('Georectifier settings')),
+            'help': BaseIcons['help'].SetLabel(
+                _('Georectifier manual')),
+        }
+
         return self._getToolbarData((("displaymap", BaseIcons["display"],
                                       self.parent.OnDraw),
                                      ("rendermap", BaseIcons["render"],

Modified: grass/trunk/gui/wxpython/gis_set.py
===================================================================
--- grass/trunk/gui/wxpython/gis_set.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gis_set.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -50,13 +50,15 @@
     exit_user_requested = 5
 
     """GRASS start-up screen"""
-    def __init__(self, parent = None, id = wx.ID_ANY, style = wx.DEFAULT_FRAME_STYLE):
 
+    def __init__(self, parent=None, id=wx.ID_ANY,
+                 style=wx.DEFAULT_FRAME_STYLE):
+
         #
         # GRASS variables
         #
-        self.gisbase  = os.getenv("GISBASE")
-        self.grassrc  = self._readGisRC()
+        self.gisbase = os.getenv("GISBASE")
+        self.grassrc = self._readGisRC()
         self.gisdbase = self.GetRCValue("GISDBASE")
 
         #
@@ -65,11 +67,11 @@
         self.listOfLocations = []
         self.listOfMapsets = []
         self.listOfMapsetsSelectable = []
-        
-        wx.Frame.__init__(self, parent = parent, id = id, style = style)
-        
-        self.locale = wx.Locale(language = wx.LANGUAGE_DEFAULT)
 
+        wx.Frame.__init__(self, parent=parent, id=id, style=style)
+
+        self.locale = wx.Locale(language=wx.LANGUAGE_DEFAULT)
+
         # scroll panel was used here but not properly and is probably not need
         # as long as it is not high too much
         self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
@@ -82,17 +84,23 @@
         # image
         try:
             if os.getenv('ISISROOT'):
-                name = os.path.join(globalvar.GUIDIR, "images", "startup_banner_isis.png")
+                name = os.path.join(
+                    globalvar.GUIDIR,
+                    "images",
+                    "startup_banner_isis.png")
             else:
-                name = os.path.join(globalvar.GUIDIR, "images", "startup_banner.png")
+                name = os.path.join(
+                    globalvar.GUIDIR, "images", "startup_banner.png")
             self.hbitmap = wx.StaticBitmap(self.panel, wx.ID_ANY,
-                                           wx.Bitmap(name = name,
-                                                     type = wx.BITMAP_TYPE_PNG))
+                                           wx.Bitmap(name=name,
+                                                     type=wx.BITMAP_TYPE_PNG))
         except:
-            self.hbitmap = wx.StaticBitmap(self.panel, wx.ID_ANY, wx.BitmapFromImage(wx.EmptyImage(530,150)))
+            self.hbitmap = wx.StaticBitmap(
+                self.panel, wx.ID_ANY, wx.BitmapFromImage(
+                    wx.EmptyImage(530, 150)))
 
         # labels
-        ### crashes when LOCATION doesn't exist
+        # crashes when LOCATION doesn't exist
         # get version & revision
         versionFile = open(os.path.join(globalvar.ETCDIR, "VERSIONNUMBER"))
         versionLine = versionFile.readline().rstrip('\n')
@@ -106,14 +114,17 @@
         except ValueError:
             grassVersion = versionLine
             grassRevisionStr = ''
-        
-        self.gisdbase_box = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
-                                         label=" %s " % _("1. Select GRASS GIS database directory"))
-        self.location_box = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
-                                         label=" %s " % _("2. Select GRASS Location"))
-        self.mapset_box = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
-                                         label=" %s " % _("3. Select GRASS Mapset"))
 
+        self.gisdbase_box = wx.StaticBox(
+            parent=self.panel, id=wx.ID_ANY, label=" %s " %
+            _("1. Select GRASS GIS database directory"))
+        self.location_box = wx.StaticBox(
+            parent=self.panel, id=wx.ID_ANY, label=" %s " %
+            _("2. Select GRASS Location"))
+        self.mapset_box = wx.StaticBox(
+            parent=self.panel, id=wx.ID_ANY, label=" %s " %
+            _("3. Select GRASS Mapset"))
+
         self.lmessage = wx.StaticText(parent=self.panel)
         # It is not clear if all wx versions supports color, so try-except.
         # The color itself may not be correct for all platforms/system settings
@@ -123,7 +134,7 @@
             self.lmessage.SetForegroundColour(wx.Colour(255, 0, 0))
         except AttributeError:
             pass
-        
+
         self.gisdbase_panel = wx.Panel(parent=self.panel)
         self.location_panel = wx.Panel(parent=self.panel)
         self.mapset_panel = wx.Panel(parent=self.panel)
@@ -156,57 +167,62 @@
             pass
 
         # buttons
-        self.bstart = wx.Button(parent = self.panel, id = wx.ID_ANY,
-                                label = _("Start &GRASS session"))
+        self.bstart = wx.Button(parent=self.panel, id=wx.ID_ANY,
+                                label=_("Start &GRASS session"))
         self.bstart.SetDefault()
-        self.bexit = wx.Button(parent = self.panel, id = wx.ID_EXIT)
+        self.bexit = wx.Button(parent=self.panel, id=wx.ID_EXIT)
         self.bstart.SetMinSize((180, self.bexit.GetSize()[1]))
-        self.bhelp = wx.Button(parent = self.panel, id = wx.ID_HELP)
-        self.bbrowse = wx.Button(parent = self.gisdbase_panel, id = wx.ID_ANY,
-                                 label = _("&Browse"))
-        self.bmapset = wx.Button(parent = self.mapset_panel, id = wx.ID_ANY,
-        # GTC New mapset
-                                 label = _("&New"))
+        self.bhelp = wx.Button(parent=self.panel, id=wx.ID_HELP)
+        self.bbrowse = wx.Button(parent=self.gisdbase_panel, id=wx.ID_ANY,
+                                 label=_("&Browse"))
+        self.bmapset = wx.Button(parent=self.mapset_panel, id=wx.ID_ANY,
+                                 # GTC New mapset
+                                 label=_("&New"))
         self.bmapset.SetToolTipString(
             _("Create a new Mapset in selected Location"))
-        self.bwizard = wx.Button(parent = self.location_panel, id = wx.ID_ANY,
-        # GTC New location
-                                 label = _("N&ew"))
-        self.bwizard.SetToolTipString(_("Create a new location using location wizard."
-                                        " After location is created successfully,"
-                                        " GRASS session is started."))
+        self.bwizard = wx.Button(parent=self.location_panel, id=wx.ID_ANY,
+                                 # GTC New location
+                                 label=_("N&ew"))
+        self.bwizard.SetToolTipString(
+            _(
+                "Create a new location using location wizard."
+                " After location is created successfully,"
+                " GRASS session is started."))
         self.rename_location_button = wx.Button(parent=self.location_panel, id=wx.ID_ANY,
-        # GTC Rename location
+                                                # GTC Rename location
                                                 label=_("Ren&ame"))
-        self.rename_location_button.SetToolTipString(_("Rename selected location"))
+        self.rename_location_button.SetToolTipString(
+            _("Rename selected location"))
         self.delete_location_button = wx.Button(parent=self.location_panel, id=wx.ID_ANY,
-        # GTC Delete location
+                                                # GTC Delete location
                                                 label=_("De&lete"))
-        self.delete_location_button.SetToolTipString(_("Delete selected location"))
+        self.delete_location_button.SetToolTipString(
+            _("Delete selected location"))
         self.rename_mapset_button = wx.Button(parent=self.mapset_panel, id=wx.ID_ANY,
-        # GTC Rename mapset
-                                                label=_("&Rename"))
+                                              # GTC Rename mapset
+                                              label=_("&Rename"))
         self.rename_mapset_button.SetToolTipString(_("Rename selected mapset"))
         self.delete_mapset_button = wx.Button(parent=self.mapset_panel, id=wx.ID_ANY,
-        # GTC Delete mapset
+                                              # GTC Delete mapset
                                               label=_("&Delete"))
         self.delete_mapset_button.SetToolTipString(_("Delete selected mapset"))
 
         # textinputs
-        self.tgisdbase = wx.TextCtrl(parent = self.gisdbase_panel, id = wx.ID_ANY, value = "", size = (300, -1),
-                                     style = wx.TE_PROCESS_ENTER)
+        self.tgisdbase = wx.TextCtrl(
+            parent=self.gisdbase_panel, id=wx.ID_ANY, value="", size=(
+                300, -1), style=wx.TE_PROCESS_ENTER)
 
         # Locations
-        self.lblocations = GListBox(parent = self.location_panel,
+        self.lblocations = GListBox(parent=self.location_panel,
                                     id=wx.ID_ANY, size=(180, 200),
-                                    choices = self.listOfLocations)
+                                    choices=self.listOfLocations)
         self.lblocations.SetColumnWidth(0, 180)
 
         # TODO: sort; but keep PERMANENT on top of list
         # Mapsets
-        self.lbmapsets = GListBox(parent = self.mapset_panel,
+        self.lbmapsets = GListBox(parent=self.mapset_panel,
                                   id=wx.ID_ANY, size=(180, 200),
-                                  choices = self.listOfMapsets)
+                                  choices=self.listOfMapsets)
         self.lbmapsets.SetColumnWidth(0, 180)
 
         # layout & properties, first do layout so everything is created
@@ -214,24 +230,24 @@
         self._set_properties(grassVersion, grassRevisionStr)
 
         # events
-        self.bbrowse.Bind(wx.EVT_BUTTON,      self.OnBrowse)
-        self.bstart.Bind(wx.EVT_BUTTON,       self.OnStart)
-        self.bexit.Bind(wx.EVT_BUTTON,        self.OnExit)
-        self.bhelp.Bind(wx.EVT_BUTTON,        self.OnHelp)
-        self.bmapset.Bind(wx.EVT_BUTTON,      self.OnCreateMapset)
-        self.bwizard.Bind(wx.EVT_BUTTON,      self.OnWizard)
-        
+        self.bbrowse.Bind(wx.EVT_BUTTON, self.OnBrowse)
+        self.bstart.Bind(wx.EVT_BUTTON, self.OnStart)
+        self.bexit.Bind(wx.EVT_BUTTON, self.OnExit)
+        self.bhelp.Bind(wx.EVT_BUTTON, self.OnHelp)
+        self.bmapset.Bind(wx.EVT_BUTTON, self.OnCreateMapset)
+        self.bwizard.Bind(wx.EVT_BUTTON, self.OnWizard)
+
         self.rename_location_button.Bind(wx.EVT_BUTTON, self.RenameLocation)
         self.delete_location_button.Bind(wx.EVT_BUTTON, self.DeleteLocation)
         self.rename_mapset_button.Bind(wx.EVT_BUTTON, self.RenameMapset)
         self.delete_mapset_button.Bind(wx.EVT_BUTTON, self.DeleteMapset)
-        
+
         self.lblocations.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectLocation)
-        self.lbmapsets.Bind(wx.EVT_LIST_ITEM_SELECTED,   self.OnSelectMapset)
+        self.lbmapsets.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectMapset)
         self.lbmapsets.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnStart)
         self.tgisdbase.Bind(wx.EVT_TEXT_ENTER, self.OnSetDatabase)
-        self.Bind(wx.EVT_CLOSE,               self.OnCloseWindow)
-        
+        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
+
     def _set_properties(self, version, revision):
         """Set frame properties"""
         self.SetTitle(_("GRASS GIS %s startup%s") % (version, revision))
@@ -258,66 +274,69 @@
         try:
             self.tgisdbase.SetValue(self.gisdbase)
         except UnicodeDecodeError:
-            wx.MessageBox(parent = self, caption = _("Error"),
-                          message = _("Unable to set GRASS database. "
-                                      "Check your locale settings."),
-                          style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
-        
+            wx.MessageBox(parent=self, caption=_("Error"),
+                          message=_("Unable to set GRASS database. "
+                                    "Check your locale settings."),
+                          style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
+
         self.OnSetDatabase(None)
         location = self.GetRCValue("LOCATION_NAME")
         if location == "<UNKNOWN>":
             return
         if not os.path.isdir(os.path.join(self.gisdbase, location)):
             location = None
-        
+
         # list of locations
         self.UpdateLocations(self.gisdbase)
         try:
             self.lblocations.SetSelection(self.listOfLocations.index(location),
-                                          force = True)
-            self.lblocations.EnsureVisible(self.listOfLocations.index(location))
+                                          force=True)
+            self.lblocations.EnsureVisible(
+                self.listOfLocations.index(location))
         except ValueError:
-            sys.stderr.write(_("ERROR: Location <%s> not found\n") % self.GetRCValue("LOCATION_NAME"))
+            sys.stderr.write(
+                _("ERROR: Location <%s> not found\n") %
+                self.GetRCValue("LOCATION_NAME"))
             if len(self.listOfLocations) > 0:
-                self.lblocations.SetSelection(0, force = True)
+                self.lblocations.SetSelection(0, force=True)
                 self.lblocations.EnsureVisible(0)
                 location = self.listOfLocations[0]
             else:
                 return
-        
+
         # list of mapsets
         self.UpdateMapsets(os.path.join(self.gisdbase, location))
         mapset = self.GetRCValue("MAPSET")
         if mapset:
             try:
                 self.lbmapsets.SetSelection(self.listOfMapsets.index(mapset),
-                                            force = True)
+                                            force=True)
                 self.lbmapsets.EnsureVisible(self.listOfMapsets.index(mapset))
             except ValueError:
                 sys.stderr.write(_("ERROR: Mapset <%s> not found\n") % mapset)
-                self.lbmapsets.SetSelection(0, force = True)
+                self.lbmapsets.SetSelection(0, force=True)
                 self.lbmapsets.EnsureVisible(0)
-        
+
     def _do_layout(self):
         sizer = wx.BoxSizer(wx.VERTICAL)
         self.sizer = sizer  # for the layout call after changing message
-        dbase_sizer     = wx.BoxSizer(wx.HORIZONTAL)
-        
-        location_mapset_sizer  = wx.BoxSizer(wx.HORIZONTAL)
+        dbase_sizer = wx.BoxSizer(wx.HORIZONTAL)
 
-        gisdbase_panel_sizer  = wx.BoxSizer(wx.VERTICAL)
-        gisdbase_boxsizer = wx.StaticBoxSizer(self.gisdbase_box, wx.VERTICAL)        
+        location_mapset_sizer = wx.BoxSizer(wx.HORIZONTAL)
 
-        btns_sizer      = wx.BoxSizer(wx.HORIZONTAL)
-        
+        gisdbase_panel_sizer = wx.BoxSizer(wx.VERTICAL)
+        gisdbase_boxsizer = wx.StaticBoxSizer(self.gisdbase_box, wx.VERTICAL)
+
+        btns_sizer = wx.BoxSizer(wx.HORIZONTAL)
+
         self.gisdbase_panel.SetSizer(gisdbase_panel_sizer)
 
         # gis data directory
-        
+
         gisdbase_boxsizer.Add(item=self.gisdbase_panel, proportion=1,
                               flag=wx.EXPAND | wx.ALL,
                               border=1)
-        
+
         gisdbase_panel_sizer.Add(item=dbase_sizer, proportion=1,
                                  flag=wx.EXPAND | wx.ALL,
                                  border=1)
@@ -325,12 +344,12 @@
                                  flag=wx.EXPAND | wx.ALL,
                                  border=1)
 
-        dbase_sizer.Add(item = self.tgisdbase, proportion = 1,
-                        flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL,
-                        border = 1)
-        dbase_sizer.Add(item = self.bbrowse, proportion = 0,
-                        flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL,
-                        border = 1)
+        dbase_sizer.Add(item=self.tgisdbase, proportion=1,
+                        flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+                        border=1)
+        dbase_sizer.Add(item=self.bbrowse, proportion=0,
+                        flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+                        border=1)
 
         gisdbase_panel_sizer.Fit(self.gisdbase_panel)
 
@@ -352,9 +371,11 @@
                            flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
                            border=1)
             for button in buttons:
-                buttons_sizer.Add(item=button, proportion=0,
-                                  flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                                  border=3)
+                buttons_sizer.Add(
+                    item=button,
+                    proportion=0,
+                    flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                    border=3)
             box_sizer.Add(item=panel, proportion=1,
                           flag=wx.EXPAND | wx.ALL,
                           border=1)
@@ -383,40 +404,40 @@
 
         # location and mapset sizer
         location_mapset_sizer.Add(item=location_boxsizer, proportion=1,
-                           flag = wx.LEFT | wx.RIGHT | wx.EXPAND,
-                           border = 3) 
+                                  flag=wx.LEFT | wx.RIGHT | wx.EXPAND,
+                                  border=3)
         location_mapset_sizer.Add(item=mapset_boxsizer, proportion=1,
-                           flag = wx.RIGHT | wx.EXPAND,
-                           border = 3)
+                                  flag=wx.RIGHT | wx.EXPAND,
+                                  border=3)
 
         # buttons
-        btns_sizer.Add(item = self.bstart, proportion = 0,
-                       flag = wx.ALIGN_CENTER_HORIZONTAL |
+        btns_sizer.Add(item=self.bstart, proportion=0,
+                       flag=wx.ALIGN_CENTER_HORIZONTAL |
                        wx.ALIGN_CENTER_VERTICAL |
                        wx.ALL,
-                       border = 5)
-        btns_sizer.Add(item = self.bexit, proportion = 0,
-                       flag = wx.ALIGN_CENTER_HORIZONTAL |
+                       border=5)
+        btns_sizer.Add(item=self.bexit, proportion=0,
+                       flag=wx.ALIGN_CENTER_HORIZONTAL |
                        wx.ALIGN_CENTER_VERTICAL |
                        wx.ALL,
-                       border = 5)
-        btns_sizer.Add(item = self.bhelp, proportion = 0,
-                       flag = wx.ALIGN_CENTER_HORIZONTAL |
+                       border=5)
+        btns_sizer.Add(item=self.bhelp, proportion=0,
+                       flag=wx.ALIGN_CENTER_HORIZONTAL |
                        wx.ALIGN_CENTER_VERTICAL |
                        wx.ALL,
-                       border = 5)
-        
+                       border=5)
+
         # main sizer
-        sizer.Add(item = self.hbitmap,
-                  proportion = 0,
-                  flag = wx.ALIGN_CENTER_VERTICAL |
+        sizer.Add(item=self.hbitmap,
+                  proportion=0,
+                  flag=wx.ALIGN_CENTER_VERTICAL |
                   wx.ALIGN_CENTER_HORIZONTAL |
                   wx.ALL,
-                  border = 3) # image
+                  border=3)  # image
         sizer.Add(item=gisdbase_boxsizer, proportion=0,
-                  flag = wx.ALIGN_CENTER_HORIZONTAL |
+                  flag=wx.ALIGN_CENTER_HORIZONTAL |
                   wx.RIGHT | wx.LEFT | wx.TOP | wx.EXPAND,
-                  border = 3) # GISDBASE setting
+                  border=3)  # GISDBASE setting
 
         # warning/error message
         sizer.Add(item=self.lmessage,
@@ -424,13 +445,13 @@
                   flag=wx.ALIGN_CENTER_VERTICAL |
                   wx.ALIGN_LEFT | wx.ALL | wx.EXPAND, border=5)
         sizer.Add(item=location_mapset_sizer, proportion=1,
-                  flag = wx.RIGHT | wx.LEFT | wx.EXPAND,
-                  border = 1)
-        sizer.Add(item = btns_sizer, proportion = 0,
-                  flag = wx.ALIGN_CENTER_VERTICAL |
+                  flag=wx.RIGHT | wx.LEFT | wx.EXPAND,
+                  border=1)
+        sizer.Add(item=btns_sizer, proportion=0,
+                  flag=wx.ALIGN_CENTER_VERTICAL |
                   wx.ALIGN_CENTER_HORIZONTAL |
                   wx.RIGHT | wx.LEFT,
-                  border = 3)
+                  border=3)
 
         self.panel.SetAutoLayout(True)
         self.panel.SetSizer(sizer)
@@ -442,9 +463,9 @@
         """Read variables from $HOME/.grass7/rc file
         """
         grassrc = {}
-        
+
         gisrc = os.getenv("GISRC")
-        
+
         if gisrc and os.path.isfile(gisrc):
             try:
                 rc = open(gisrc, "r")
@@ -452,12 +473,12 @@
                     try:
                         key, val = line.split(":", 1)
                     except ValueError as e:
-                        sys.stderr.write(_('Invalid line in GISRC file (%s):%s\n' % \
-                                               (e, line)))
+                        sys.stderr.write(
+                            _('Invalid line in GISRC file (%s):%s\n' % (e, line)))
                     grassrc[key.strip()] = DecodeString(val.strip())
             finally:
                 rc.close()
-        
+
         return grassrc
 
     def _showWarning(self, text):
@@ -498,45 +519,48 @@
     def GetRCValue(self, value):
         """Return GRASS variable (read from GISRC)
         """
-        if self.grassrc.has_key(value):
+        if value in self.grassrc:
             return self.grassrc[value]
         else:
             return None
-        
+
     def OnWizard(self, event):
         """Location wizard started"""
         from location_wizard.wizard import LocationWizard
-        gWizard = LocationWizard(parent = self,
-                                 grassdatabase = self.tgisdbase.GetValue())
-        if gWizard.location !=  None:
+        gWizard = LocationWizard(parent=self,
+                                 grassdatabase=self.tgisdbase.GetValue())
+        if gWizard.location is not None:
             self.tgisdbase.SetValue(gWizard.grassdatabase)
             self.OnSetDatabase(None)
             self.UpdateMapsets(os.path.join(self.gisdbase, gWizard.location))
-            self.lblocations.SetSelection(self.listOfLocations.index(gWizard.location))
+            self.lblocations.SetSelection(
+                self.listOfLocations.index(
+                    gWizard.location))
             self.lbmapsets.SetSelection(0)
             self.SetLocation(self.gisdbase, gWizard.location, 'PERMANENT')
             if gWizard.georeffile:
-                message = _("Do you want to import <%(name)s> to the newly created location?") % \
-                    {'name': gWizard.georeffile}
-                dlg = wx.MessageDialog(parent = self,
-                                       message = message,
-                                       caption = _("Import data?"),
-                                       style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+                message = _("Do you want to import <%(name)s> to the newly created location?") % {
+                    'name': gWizard.georeffile}
+                dlg = wx.MessageDialog(parent=self, message=message, caption=_(
+                    "Import data?"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
                 dlg.CenterOnScreen()
                 if dlg.ShowModal() == wx.ID_YES:
                     self.ImportFile(gWizard.georeffile)
                 else:
-                    self.SetDefaultRegion(location = gWizard.location)
+                    self.SetDefaultRegion(location=gWizard.location)
                 dlg.Destroy()
             else:
-                self.SetDefaultRegion(location = gWizard.location)
+                self.SetDefaultRegion(location=gWizard.location)
 
-            dlg = TextEntryDialog(parent=self,
-                                  message=_("Do you want to create new mapset?"),
-                                  caption=_("Create new mapset"),
-                                  defaultValue=self._getDefaultMapsetName(),
-                                  validator=GenericValidator(grass.legal_name, self._nameValidationFailed),
-                                  style=wx.OK | wx.CANCEL | wx.HELP)
+            dlg = TextEntryDialog(
+                parent=self,
+                message=_("Do you want to create new mapset?"),
+                caption=_("Create new mapset"),
+                defaultValue=self._getDefaultMapsetName(),
+                validator=GenericValidator(
+                    grass.legal_name,
+                    self._nameValidationFailed),
+                style=wx.OK | wx.CANCEL | wx.HELP)
             help = dlg.FindWindowById(wx.ID_HELP)
             help.Bind(wx.EVT_BUTTON, self.OnHelp)
             if dlg.ShowModal() == wx.ID_OK:
@@ -548,15 +572,14 @@
         caption = _("Location <%s> created") % location
         message = _("Do you want to set the default "
                     "region extents and resolution now?")
-        dlg = wx.MessageDialog(parent = self,
-                               message = "%(caption)s.\n\n%(extent)s" % ({'caption': caption,
-                                                                          'extent': message}),
-                               caption = caption,
-                               style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
+        dlg = wx.MessageDialog(
+            parent=self, message="%(caption)s.\n\n%(extent)s" %
+            ({'caption': caption, 'extent': message}),
+            caption=caption, style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
         dlg.CenterOnScreen()
         if dlg.ShowModal() == wx.ID_YES:
             dlg.Destroy()
-            defineRegion = RegionDef(self, location = location)
+            defineRegion = RegionDef(self, location=location)
             defineRegion.CenterOnScreen()
             defineRegion.ShowModal()
             defineRegion.Destroy()
@@ -570,71 +593,87 @@
         """
         RunCommand('db.connect', flags='c')
         mapName = os.path.splitext(os.path.basename(filePath))[0]
-        vectors = RunCommand('v.in.ogr', input = filePath, flags = 'l',
-                             read = True)
-        
+        vectors = RunCommand('v.in.ogr', input=filePath, flags='l',
+                             read=True)
+
         wx.BeginBusyCursor()
         wx.Yield()
         if mapName in vectors:
             # vector detected
-            returncode, error = RunCommand('v.in.ogr', input=filePath, output=mapName, flags='e',
-                                           getErrorMsg=True)
+            returncode, error = RunCommand(
+                'v.in.ogr', input=filePath, output=mapName, flags='e',
+                getErrorMsg=True)
         else:
-            returncode, error = RunCommand('r.in.gdal', input=filePath, output=mapName, flags='e',
-                                           getErrorMsg=True)
+            returncode, error = RunCommand(
+                'r.in.gdal', input=filePath, output=mapName, flags='e',
+                getErrorMsg=True)
         wx.EndBusyCursor()
 
         if returncode != 0:
-            GError(parent = self,
-                   message = _("Import of <%(name)s> failed.\n"
-                               "Reason: %(msg)s") % ({'name': filePath, 'msg': error}))
+            GError(
+                parent=self,
+                message=_(
+                    "Import of <%(name)s> failed.\n"
+                    "Reason: %(msg)s") % ({
+                        'name': filePath,
+                        'msg': error}))
         else:
-            GMessage(message=_("Data file <%(name)s> imported successfully. "
-                               "The location's default region was set from this imported map.") %
-                               {'name': filePath},
-                     parent=self)
+            GMessage(
+                message=_(
+                    "Data file <%(name)s> imported successfully. "
+                    "The location's default region was set from this imported map.") % {
+                    'name': filePath},
+                parent=self)
 
     # the event can be refactored out by using lambda in bind
     def RenameMapset(self, event):
         """Rename selected mapset
         """
         location = self.listOfLocations[self.lblocations.GetSelection()]
-        mapset   = self.listOfMapsets[self.lbmapsets.GetSelection()]
-        if mapset ==  'PERMANENT':
-            GMessage(parent = self,
-                     message = _('Mapset <PERMANENT> is required for valid GRASS location.\n\n'
-                                 'This mapset cannot be renamed.'))
+        mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
+        if mapset == 'PERMANENT':
+            GMessage(
+                parent=self, message=_(
+                    'Mapset <PERMANENT> is required for valid GRASS location.\n\n'
+                    'This mapset cannot be renamed.'))
             return
-        
-        dlg = TextEntryDialog(parent = self,
-                              message = _('Current name: %s\n\nEnter new name:') % mapset,
-                              caption = _('Rename selected mapset'),
-                              validator = GenericValidator(grass.legal_name, self._nameValidationFailed))
-        
-        if dlg.ShowModal() ==  wx.ID_OK:
+
+        dlg = TextEntryDialog(
+            parent=self,
+            message=_('Current name: %s\n\nEnter new name:') %
+            mapset,
+            caption=_('Rename selected mapset'),
+            validator=GenericValidator(
+                grass.legal_name,
+                self._nameValidationFailed))
+
+        if dlg.ShowModal() == wx.ID_OK:
             newmapset = dlg.GetValue()
-            if newmapset ==  mapset:
+            if newmapset == mapset:
                 dlg.Destroy()
                 return
-            
+
             if newmapset in self.listOfMapsets:
-                wx.MessageBox(parent = self,
-                              caption = _('Message'),
-                              message = _('Unable to rename mapset.\n\n'
-                                        'Mapset <%s> already exists in location.') % newmapset,
-                              style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
+                wx.MessageBox(
+                    parent=self, caption=_('Message'), message=_(
+                        'Unable to rename mapset.\n\n'
+                        'Mapset <%s> already exists in location.') %
+                    newmapset, style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
             else:
                 try:
                     os.rename(os.path.join(self.gisdbase, location, mapset),
                               os.path.join(self.gisdbase, location, newmapset))
                     self.OnSelectLocation(None)
-                    self.lbmapsets.SetSelection(self.listOfMapsets.index(newmapset))
-                except StandardError as e:
-                    wx.MessageBox(parent = self,
-                                  caption = _('Error'),
-                                  message = _('Unable to rename mapset.\n\n%s') % e,
-                                  style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
-            
+                    self.lbmapsets.SetSelection(
+                        self.listOfMapsets.index(newmapset))
+                except Exception as e:
+                    wx.MessageBox(
+                        parent=self,
+                        caption=_('Error'),
+                        message=_('Unable to rename mapset.\n\n%s') %
+                        e,
+                        style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
+
         dlg.Destroy()
 
     def RenameLocation(self, event):
@@ -642,64 +681,75 @@
         """
         location = self.listOfLocations[self.lblocations.GetSelection()]
 
-        dlg = TextEntryDialog(parent = self,
-                              message = _('Current name: %s\n\nEnter new name:') % location,
-                              caption = _('Rename selected location'),
-                              validator = GenericValidator(grass.legal_name, self._nameValidationFailed))
+        dlg = TextEntryDialog(
+            parent=self,
+            message=_('Current name: %s\n\nEnter new name:') %
+            location,
+            caption=_('Rename selected location'),
+            validator=GenericValidator(
+                grass.legal_name,
+                self._nameValidationFailed))
 
-        if dlg.ShowModal() ==  wx.ID_OK:
+        if dlg.ShowModal() == wx.ID_OK:
             newlocation = dlg.GetValue()
-            if newlocation ==  location:
+            if newlocation == location:
                 dlg.Destroy()
                 return
 
             if newlocation in self.listOfLocations:
-                wx.MessageBox(parent = self,
-                              caption = _('Message'),
-                              message = _('Unable to rename location.\n\n'
-                                        'Location <%s> already exists in GRASS database.') % newlocation,
-                              style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
+                wx.MessageBox(
+                    parent=self, caption=_('Message'), message=_(
+                        'Unable to rename location.\n\n'
+                        'Location <%s> already exists in GRASS database.') %
+                    newlocation, style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
             else:
                 try:
                     os.rename(os.path.join(self.gisdbase, location),
                               os.path.join(self.gisdbase, newlocation))
                     self.UpdateLocations(self.gisdbase)
-                    self.lblocations.SetSelection(self.listOfLocations.index(newlocation))
+                    self.lblocations.SetSelection(
+                        self.listOfLocations.index(newlocation))
                     self.UpdateMapsets(newlocation)
-                except StandardError as e:
-                    wx.MessageBox(parent = self,
-                                  caption = _('Error'),
-                                  message = _('Unable to rename location.\n\n%s') % e,
-                                  style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
-        
+                except Exception as e:
+                    wx.MessageBox(
+                        parent=self,
+                        caption=_('Error'),
+                        message=_('Unable to rename location.\n\n%s') %
+                        e,
+                        style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
+
         dlg.Destroy()
 
     def DeleteMapset(self, event):
         """Delete selected mapset
         """
         location = self.listOfLocations[self.lblocations.GetSelection()]
-        mapset   = self.listOfMapsets[self.lbmapsets.GetSelection()]
-        if mapset ==  'PERMANENT':
-            GMessage(parent = self,
-                     message = _('Mapset <PERMANENT> is required for valid GRASS location.\n\n'
-                                 'This mapset cannot be deleted.'))
+        mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
+        if mapset == 'PERMANENT':
+            GMessage(
+                parent=self, message=_(
+                    'Mapset <PERMANENT> is required for valid GRASS location.\n\n'
+                    'This mapset cannot be deleted.'))
             return
-        
-        dlg = wx.MessageDialog(parent = self, message = _("Do you want to continue with deleting mapset <%(mapset)s> "
-                                                      "from location <%(location)s>?\n\n"
-                                                      "ALL MAPS included in this mapset will be "
-                                                      "PERMANENTLY DELETED!") % {'mapset' : mapset,
-                                                                                 'location' : location},
-                               caption = _("Delete selected mapset"),
-                               style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
 
-        if dlg.ShowModal() ==  wx.ID_YES:
+        dlg = wx.MessageDialog(
+            parent=self,
+            message=_(
+                "Do you want to continue with deleting mapset <%(mapset)s> "
+                "from location <%(location)s>?\n\n"
+                "ALL MAPS included in this mapset will be "
+                "PERMANENTLY DELETED!") %
+            {'mapset': mapset, 'location': location},
+            caption=_("Delete selected mapset"),
+            style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
+
+        if dlg.ShowModal() == wx.ID_YES:
             try:
                 shutil.rmtree(os.path.join(self.gisdbase, location, mapset))
                 self.OnSelectLocation(None)
                 self.lbmapsets.SetSelection(0)
             except:
-                wx.MessageBox(message = _('Unable to delete mapset'))
+                wx.MessageBox(message=_('Unable to delete mapset'))
 
         dlg.Destroy()
 
@@ -710,14 +760,18 @@
 
         location = self.listOfLocations[self.lblocations.GetSelection()]
 
-        dlg = wx.MessageDialog(parent = self, message = _("Do you want to continue with deleting "
-                                                      "location <%s>?\n\n"
-                                                      "ALL MAPS included in this location will be "
-                                                      "PERMANENTLY DELETED!") % (location),
-                               caption = _("Delete selected location"),
-                               style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
+        dlg = wx.MessageDialog(
+            parent=self,
+            message=_(
+                "Do you want to continue with deleting "
+                "location <%s>?\n\n"
+                "ALL MAPS included in this location will be "
+                "PERMANENTLY DELETED!") %
+            (location),
+            caption=_("Delete selected location"),
+            style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
 
-        if dlg.ShowModal() ==  wx.ID_YES:
+        if dlg.ShowModal() == wx.ID_YES:
             try:
                 shutil.rmtree(os.path.join(self.gisdbase, location))
                 self.UpdateLocations(self.gisdbase)
@@ -725,7 +779,7 @@
                 self.OnSelectLocation(None)
                 self.lbmapsets.SetSelection(0)
             except:
-                wx.MessageBox(message = _('Unable to delete location'))
+                wx.MessageBox(message=_('Unable to delete location'))
 
         dlg.Destroy()
 
@@ -734,10 +788,10 @@
         try:
             self.listOfLocations = GetListOfLocations(dbase)
         except UnicodeEncodeError:
-            GError(parent = self,
-                   message = _("Unable to set GRASS database. "
-                               "Check your locale settings."))
-                
+            GError(parent=self,
+                   message=_("Unable to set GRASS database. "
+                             "Check your locale settings."))
+
         self.lblocations.Clear()
         self.lblocations.InsertItems(self.listOfLocations, 0)
 
@@ -755,35 +809,35 @@
 
     def UpdateMapsets(self, location):
         """Update list of mapsets"""
-        self.FormerMapsetSelection = wx.NOT_FOUND # for non-selectable item
-        
+        self.FormerMapsetSelection = wx.NOT_FOUND  # for non-selectable item
+
         self.listOfMapsetsSelectable = list()
         self.listOfMapsets = GetListOfMapsets(self.gisdbase, location)
-        
+
         self.lbmapsets.Clear()
-        
+
         # disable mapset with denied permission
         locationName = os.path.basename(location)
-        
+
         ret = RunCommand('g.mapset',
-                         read = True,
-                         flags = 'l',
-                         location = locationName,
-                         gisdbase = self.gisdbase)
-            
+                         read=True,
+                         flags='l',
+                         location=locationName,
+                         gisdbase=self.gisdbase)
+
         if ret:
             for line in ret.splitlines():
                 self.listOfMapsetsSelectable += line.split(' ')
         else:
             RunCommand("g.gisenv",
-                       set = "GISDBASE=%s" % self.gisdbase)
+                       set="GISDBASE=%s" % self.gisdbase)
             RunCommand("g.gisenv",
-                       set = "LOCATION_NAME=%s" % locationName)
+                       set="LOCATION_NAME=%s" % locationName)
             RunCommand("g.gisenv",
-                       set = "MAPSET=PERMANENT")
+                       set="MAPSET=PERMANENT")
             # first run only
             self.listOfMapsetsSelectable = copy.copy(self.listOfMapsets)
-        
+
         disabled = []
         idx = 0
         for mapset in self.listOfMapsets:
@@ -792,40 +846,44 @@
                                                 locationName,
                                                 mapset, ".gislock")):
                 disabled.append(idx)
-            idx +=  1
-        
-        self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled = disabled)
-        
+            idx += 1
+
+        self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled=disabled)
+
         return self.listOfMapsets
 
     def OnSelectLocation(self, event):
         """Location selected"""
         if event:
             self.lblocations.SetSelection(event.GetIndex())
-            
-        if self.lblocations.GetSelection() !=  wx.NOT_FOUND:
-            self.UpdateMapsets(os.path.join(self.gisdbase,
-                                            self.listOfLocations[self.lblocations.GetSelection()]))
+
+        if self.lblocations.GetSelection() != wx.NOT_FOUND:
+            self.UpdateMapsets(
+                os.path.join(
+                    self.gisdbase,
+                    self.listOfLocations[
+                        self.lblocations.GetSelection()]))
         else:
             self.listOfMapsets = []
-        
+
         disabled = []
         idx = 0
         try:
-            locationName = self.listOfLocations[self.lblocations.GetSelection()]
+            locationName = self.listOfLocations[
+                self.lblocations.GetSelection()]
         except IndexError:
             locationName = ''
-        
+
         for mapset in self.listOfMapsets:
             if mapset not in self.listOfMapsetsSelectable or \
                     os.path.isfile(os.path.join(self.gisdbase,
                                                 locationName,
                                                 mapset, ".gislock")):
                 disabled.append(idx)
-            idx +=  1
+            idx += 1
 
         self.lbmapsets.Clear()
-        self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled = disabled)
+        self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled=disabled)
 
         if len(self.listOfMapsets) > 0:
             self.lbmapsets.SetSelection(0)
@@ -848,7 +906,7 @@
             self.delete_location_button.Enable(False)
             self.rename_mapset_button.Enable(False)
             self.delete_mapset_button.Enable(False)
-        
+
     def OnSelectMapset(self, event):
         """Mapset selected"""
         self.lbmapsets.SetSelection(event.GetIndex())
@@ -866,10 +924,10 @@
         if not os.path.exists(gisdbase):
             self._showError(_("Path '%s' doesn't exist.") % gisdbase)
             return
-        
+
         self.gisdbase = self.tgisdbase.GetValue()
         self.UpdateLocations(self.gisdbase)
-        
+
         self.OnSelectLocation(None)
 
     def OnBrowse(self, event):
@@ -878,109 +936,126 @@
             defaultPath = os.getenv('HOME')
         else:
             defaultPath = ""
-        
-        dlg = wx.DirDialog(parent = self, message = _("Choose GIS Data Directory"),
-                           defaultPath = defaultPath, style = wx.DD_DEFAULT_STYLE)
-        
-        if dlg.ShowModal() ==  wx.ID_OK:
+
+        dlg = wx.DirDialog(parent=self, message=_("Choose GIS Data Directory"),
+                           defaultPath=defaultPath, style=wx.DD_DEFAULT_STYLE)
+
+        if dlg.ShowModal() == wx.ID_OK:
             self.gisdbase = dlg.GetPath()
             self.tgisdbase.SetValue(self.gisdbase)
             self.OnSetDatabase(event)
-        
+
         dlg.Destroy()
 
     def OnCreateMapset(self, event):
         """Create new mapset"""
-        dlg = TextEntryDialog(parent = self,
-                              message = _('Enter name for new mapset:'),
-                              caption = _('Create new mapset'),
-                              defaultValue = self._getDefaultMapsetName(),
-                              validator = GenericValidator(grass.legal_name, self._nameValidationFailed))
+        dlg = TextEntryDialog(
+            parent=self,
+            message=_('Enter name for new mapset:'),
+            caption=_('Create new mapset'),
+            defaultValue=self._getDefaultMapsetName(),
+            validator=GenericValidator(
+                grass.legal_name,
+                self._nameValidationFailed))
         if dlg.ShowModal() == wx.ID_OK:
             mapset = dlg.GetValue()
-            return self.CreateNewMapset(mapset = mapset)
+            return self.CreateNewMapset(mapset=mapset)
         else:
             return False
 
     def CreateNewMapset(self, mapset):
         if mapset in self.listOfMapsets:
-            GMessage(parent = self,
-                     message = _("Mapset <%s> already exists.") % mapset)
+            GMessage(parent=self,
+                     message=_("Mapset <%s> already exists.") % mapset)
             return False
 
         if mapset.lower() == 'ogr':
-            dlg1 = wx.MessageDialog(parent = self,
-                                    message = _("Mapset <%s> is reserved for direct "
-                                                "read access to OGR layers. Please consider to use "
-                                                "another name for your mapset.\n\n"
-                                                "Are you really sure that you want to create this mapset?") % mapset,
-                                    caption = _("Reserved mapset name"),
-                                    style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
+            dlg1 = wx.MessageDialog(
+                parent=self,
+                message=_(
+                    "Mapset <%s> is reserved for direct "
+                    "read access to OGR layers. Please consider to use "
+                    "another name for your mapset.\n\n"
+                    "Are you really sure that you want to create this mapset?") %
+                mapset,
+                caption=_("Reserved mapset name"),
+                style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
             ret = dlg1.ShowModal()
             dlg1.Destroy()
             if ret == wx.ID_NO:
                 dlg1.Destroy()
                 return False
-        
+
         try:
             self.gisdbase = self.tgisdbase.GetValue()
             location = self.listOfLocations[self.lblocations.GetSelection()]
             os.mkdir(os.path.join(self.gisdbase, location, mapset))
-            # copy WIND file and its permissions from PERMANENT and set permissions to u+rw,go+r
-            shutil.copy(os.path.join(self.gisdbase, location, 'PERMANENT', 'WIND'),
-                        os.path.join(self.gisdbase, location, mapset))
+            # copy WIND file and its permissions from PERMANENT and set
+            # permissions to u+rw,go+r
+            shutil.copy(
+                os.path.join(
+                    self.gisdbase,
+                    location,
+                    'PERMANENT',
+                    'WIND'),
+                os.path.join(
+                    self.gisdbase,
+                    location,
+                    mapset))
             # os.chmod(os.path.join(database,location,mapset,'WIND'), 0644)
             self.OnSelectLocation(None)
             self.lbmapsets.SetSelection(self.listOfMapsets.index(mapset))
             self.bstart.SetFocus()
 
             return True
-        except StandardError as e:
-            GError(parent = self,
-                   message = _("Unable to create new mapset: %s") % e,
-                   showTraceback = False)
+        except Exception as e:
+            GError(parent=self,
+                   message=_("Unable to create new mapset: %s") % e,
+                   showTraceback=False)
             return False
 
     def OnStart(self, event):
         """'Start GRASS' button clicked"""
-        dbase    = self.tgisdbase.GetValue()
+        dbase = self.tgisdbase.GetValue()
         location = self.listOfLocations[self.lblocations.GetSelection()]
-        mapset   = self.listOfMapsets[self.lbmapsets.GetSelection()]
-        
+        mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
+
         lockfile = os.path.join(dbase, location, mapset, '.gislock')
         if os.path.isfile(lockfile):
-            dlg = wx.MessageDialog(parent = self,
-                                   message = _("GRASS is already running in selected mapset <%(mapset)s>\n"
-                                               "(file %(lock)s found).\n\n"
-                                               "Concurrent use not allowed.\n\n"
-                                               "Do you want to try to remove .gislock (note that you "
-                                               "need permission for this operation) and continue?") % 
-                                   { 'mapset' : mapset, 'lock' : lockfile },
-                                   caption = _("Lock file found"),
-                                   style = wx.YES_NO | wx.NO_DEFAULT |
-                                   wx.ICON_QUESTION | wx.CENTRE)
-            
+            dlg = wx.MessageDialog(
+                parent=self,
+                message=_(
+                    "GRASS is already running in selected mapset <%(mapset)s>\n"
+                    "(file %(lock)s found).\n\n"
+                    "Concurrent use not allowed.\n\n"
+                    "Do you want to try to remove .gislock (note that you "
+                    "need permission for this operation) and continue?") %
+                {'mapset': mapset, 'lock': lockfile},
+                caption=_("Lock file found"),
+                style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
+
             ret = dlg.ShowModal()
             dlg.Destroy()
             if ret == wx.ID_YES:
-                dlg1 = wx.MessageDialog(parent = self,
-                                        message = _("ARE YOU REALLY SURE?\n\n"
-                                                    "If you really are running another GRASS session doing this "
-                                                    "could corrupt your data. Have another look in the processor "
-                                                    "manager just to be sure..."),
-                                        caption = _("Lock file found"),
-                                        style = wx.YES_NO | wx.NO_DEFAULT |
-                                        wx.ICON_QUESTION | wx.CENTRE)
-                
+                dlg1 = wx.MessageDialog(
+                    parent=self,
+                    message=_(
+                        "ARE YOU REALLY SURE?\n\n"
+                        "If you really are running another GRASS session doing this "
+                        "could corrupt your data. Have another look in the processor "
+                        "manager just to be sure..."),
+                    caption=_("Lock file found"),
+                    style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
+
                 ret = dlg1.ShowModal()
                 dlg1.Destroy()
-                
+
                 if ret == wx.ID_YES:
                     try:
                         os.remove(lockfile)
                     except IOError as e:
                         GError(_("Unable to remove '%(lock)s'.\n\n"
-                                 "Details: %(reason)s") % { 'lock' : lockfile, 'reason' : e})
+                                 "Details: %(reason)s") % {'lock': lockfile, 'reason': e})
                 else:
                     return
             else:
@@ -990,18 +1065,19 @@
 
     def SetLocation(self, dbase, location, mapset):
         RunCommand("g.gisenv",
-                   set = "GISDBASE=%s" % dbase)
+                   set="GISDBASE=%s" % dbase)
         RunCommand("g.gisenv",
-                   set = "LOCATION_NAME=%s" % location)
+                   set="LOCATION_NAME=%s" % location)
         RunCommand("g.gisenv",
-                   set = "MAPSET=%s" % mapset)
+                   set="MAPSET=%s" % mapset)
 
     def _getDefaultMapsetName(self):
         """Returns default name for mapset."""
         try:
             defaultName = getpass.getuser()
-            defaultName.encode('ascii') # raise error if not ascii (not valid mapset name)
-        except: # whatever might go wrong
+            # raise error if not ascii (not valid mapset name)
+            defaultName.encode('ascii')
+        except:  # whatever might go wrong
             defaultName = 'user'
 
         return defaultName
@@ -1019,7 +1095,7 @@
         """'Help' button clicked"""
 
         # help text in lib/init/helptext.html
-        RunCommand('g.manual', entry = 'helptext')
+        RunCommand('g.manual', entry='helptext')
 
     def OnCloseWindow(self, event):
         """Close window event"""
@@ -1027,61 +1103,69 @@
         sys.exit(self.exit_user_requested)
 
     def _nameValidationFailed(self, ctrl):
-        message = _("Name <%(name)s> is not a valid name for location or mapset. "
-                    "Please use only ASCII characters excluding %(chars)s "
-                    "and space.") % {'name': ctrl.GetValue(), 'chars': '/"\'@,=*~'}
+        message = _(
+            "Name <%(name)s> is not a valid name for location or mapset. "
+            "Please use only ASCII characters excluding %(chars)s "
+            "and space.") % {
+            'name': ctrl.GetValue(),
+            'chars': '/"\'@,=*~'}
         GError(parent=self, message=message, caption=_("Invalid name"))
 
 
 class GListBox(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
     """Use wx.ListCtrl instead of wx.ListBox, different style for
     non-selectable items (e.g. mapsets with denied permission)"""
+
     def __init__(self, parent, id, size,
-                 choices, disabled = []):
-        wx.ListCtrl.__init__(self, parent, id, size = size,
-                             style = wx.LC_REPORT | wx.LC_NO_HEADER | wx.LC_SINGLE_SEL |
-                             wx.BORDER_SUNKEN)
-        
+                 choices, disabled=[]):
+        wx.ListCtrl.__init__(
+            self, parent, id, size=size, style=wx.LC_REPORT | wx.LC_NO_HEADER |
+            wx.LC_SINGLE_SEL | wx.BORDER_SUNKEN)
+
         listmix.ListCtrlAutoWidthMixin.__init__(self)
-        
+
         self.InsertColumn(0, '')
-        
+
         self.selected = wx.NOT_FOUND
-        
+
         self._LoadData(choices, disabled)
-        
-    def _LoadData(self, choices, disabled = []):
+
+    def _LoadData(self, choices, disabled=[]):
         """Load data into list
-        
+
         :param choices: list of item
         :param disabled: list of indices of non-selectable items
         """
         idx = 0
         for item in choices:
-            index = self.InsertStringItem(sys.maxint, item)
+            index = self.InsertStringItem(sys.maxsize, item)
             self.SetStringItem(index, 0, item)
-            
+
             if idx in disabled:
                 self.SetItemTextColour(idx, wx.Colour(150, 150, 150))
-            idx +=  1
-        
+            idx += 1
+
     def Clear(self):
         self.DeleteAllItems()
-        
-    def InsertItems(self, choices, pos, disabled = []):
+
+    def InsertItems(self, choices, pos, disabled=[]):
         self._LoadData(choices, disabled)
-        
-    def SetSelection(self, item, force = False):
+
+    def SetSelection(self, item, force=False):
         if item !=  wx.NOT_FOUND and \
-                (platform.system() !=  'Windows' or force):
-            ### Windows -> FIXME
-            self.SetItemState(item, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)
-        
+                (platform.system() != 'Windows' or force):
+            # Windows -> FIXME
+            self.SetItemState(
+                item,
+                wx.LIST_STATE_SELECTED,
+                wx.LIST_STATE_SELECTED)
+
         self.selected = item
-        
+
     def GetSelection(self):
         return self.selected
-        
+
+
 class StartUp(wx.App):
     """Start-up application"""
 
@@ -1092,25 +1176,26 @@
         StartUp.CenterOnScreen()
         self.SetTopWindow(StartUp)
         StartUp.Show()
-        
-        if StartUp.GetRCValue("LOCATION_NAME") ==  "<UNKNOWN>":
+
+        if StartUp.GetRCValue("LOCATION_NAME") == "<UNKNOWN>":
             # TODO: This is not ideal, either it should be checked elsewhere
             # where other checks are performed or it should use some public
             # API. There is no reason for not exposing it.
             # TODO: another question is what should be warning, hint or message
-            StartUp._showWarning(_('GRASS needs a directory (GRASS database) '
-                                   'in which to store its data. '
-                                   'Create one now if you have not already done so. '
-                                   'A popular choice is "grassdata", located in '
-                                   'your home directory. '
-                                   'Press Browse button to select the directory.'))
+            StartUp._showWarning(
+                _(
+                    'GRASS needs a directory (GRASS database) '
+                    'in which to store its data. '
+                    'Create one now if you have not already done so. '
+                    'A popular choice is "grassdata", located in '
+                    'your home directory. '
+                    'Press Browse button to select the directory.'))
 
         return 1
 
-if __name__ ==  "__main__":
+if __name__ == "__main__":
     if os.getenv("GISBASE") is None:
         sys.exit("Failed to start GUI, GRASS GIS is not running.")
-        
-    
+
     GRASSStartUp = StartUp(0)
     GRASSStartUp.MainLoop()

Modified: grass/trunk/gui/wxpython/gis_set_error.py
===================================================================
--- grass/trunk/gui/wxpython/gis_set_error.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gis_set_error.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -1,4 +1,4 @@
-""" 
+"""
 @package gis_set_error
 
 GRASS start-up screen error message.
@@ -17,21 +17,22 @@
 from core import globalvar
 import wx
 
+
 def main():
     app = wx.App()
-    
+
     if len(sys.argv) == 1:
         msg = "Unknown reason"
     else:
         msg = ''
         for m in sys.argv[1:]:
             msg += m
-    
-    wx.MessageBox(caption = "Error",
-                  message = msg,
-                  style = wx.OK | wx.ICON_ERROR)
-    
+
+    wx.MessageBox(caption="Error",
+                  message=msg,
+                  style=wx.OK | wx.ICON_ERROR)
+
     app.MainLoop()
-    
+
 if __name__ == "__main__":
     main()

Modified: grass/trunk/gui/wxpython/gmodeler/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/gmodeler/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gmodeler/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -7,4 +7,4 @@
     'dialogs',
     'toolbars',
     'frame',
-    ]
+]

Modified: grass/trunk/gui/wxpython/gmodeler/dialogs.py
===================================================================
--- grass/trunk/gui/wxpython/gmodeler/dialogs.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gmodeler/dialogs.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -29,51 +29,59 @@
 import wx
 import wx.lib.mixins.listctrl as listmix
 
-from core                 import globalvar
-from core                 import utils
+from core import globalvar
+from core import utils
 from core.utils import _
-from gui_core.widgets     import SearchModuleWidget, SimpleValidator
-from core.gcmd            import GError, EncodeString
-from gui_core.dialogs     import SimpleDialog, MapLayersDialogForModeler
-from gui_core.prompt      import GPromptSTC
-from gui_core.gselect     import Select, ElementSelect
-from gmodeler.model       import *
-from lmgr.menudata        import LayerManagerMenuData
+from gui_core.widgets import SearchModuleWidget, SimpleValidator
+from core.gcmd import GError, EncodeString
+from gui_core.dialogs import SimpleDialog, MapLayersDialogForModeler
+from gui_core.prompt import GPromptSTC
+from gui_core.gselect import Select, ElementSelect
+from gmodeler.model import *
+from lmgr.menudata import LayerManagerMenuData
 
 from grass.script import task as gtask
 
+
 class ModelDataDialog(SimpleDialog):
     """Data item properties dialog"""
-    def __init__(self, parent, shape, title = _("Data properties")):
+
+    def __init__(self, parent, shape, title=_("Data properties")):
         self.parent = parent
         self.shape = shape
-        
+
         label, etype = self._getLabel()
         self.etype = etype
         SimpleDialog.__init__(self, parent, title)
-                
-        self.element = Select(parent = self.panel,
-                              type = self.shape.GetPrompt(),
-                              validator = SimpleValidator(callback = self.ValidatorCallback))
+
+        self.element = Select(
+            parent=self.panel,
+            type=self.shape.GetPrompt(),
+            validator=SimpleValidator(
+                callback=self.ValidatorCallback))
         if shape.GetValue():
             self.element.SetValue(shape.GetValue())
-        
-        self.Bind(wx.EVT_BUTTON, self.OnOK,     self.btnOK)
+
+        self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOK)
         self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
         if self.etype:
-            self.typeSelect = ElementSelect(parent = self.panel,
-                                            elements = ['raster', 'raster_3d', 'vector'],
-                                            size = globalvar.DIALOG_GSELECT_SIZE)
+            self.typeSelect = ElementSelect(
+                parent=self.panel,
+                elements=[
+                    'raster',
+                    'raster_3d',
+                    'vector'],
+                size=globalvar.DIALOG_GSELECT_SIZE)
             self.typeSelect.Bind(wx.EVT_CHOICE, self.OnType)
             self.typeSelect.SetSelection(0)
             self.element.SetType('raster')
-            
+
         if shape.GetValue():
             self.btnOK.Enable()
-        
+
         self._layout()
         self.SetMinSize(self.GetSize())
-        
+
     def _getLabel(self):
         etype = False
         prompt = self.shape.GetPrompt()
@@ -86,21 +94,26 @@
             label = _('Name of element:')
 
         return label, etype
-    
+
     def _layout(self):
         """Do layout"""
         if self.etype:
-            self.dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                                    label = _("Type of element:")),
-                               proportion = 0, flag = wx.ALL, border = 1)
-            self.dataSizer.Add(item = self.typeSelect,
-                               proportion = 0, flag = wx.ALL, border = 1)
-        self.dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                                label = _("Name of element:")),
-                           proportion = 0, flag = wx.ALL, border = 1)
+            self.dataSizer.Add(
+                item=wx.StaticText(
+                    parent=self.panel,
+                    id=wx.ID_ANY,
+                    label=_("Type of element:")),
+                proportion=0,
+                flag=wx.ALL,
+                border=1)
+            self.dataSizer.Add(item=self.typeSelect,
+                               proportion=0, flag=wx.ALL, border=1)
+        self.dataSizer.Add(item=wx.StaticText(parent=self.panel, id=wx.ID_ANY,
+                                              label=_("Name of element:")),
+                           proportion=0, flag=wx.ALL, border=1)
         self.dataSizer.Add(self.element, proportion=0,
-                      flag=wx.EXPAND | wx.ALL, border=1)
-        
+                           flag=wx.EXPAND | wx.ALL, border=1)
+
         self.panel.SetSizer(self.sizer)
         self.sizer.Fit(self)
 
@@ -126,16 +139,16 @@
                 self.shape.SetPrompt('vector')
             elif elem == 'raster_3d':
                 self.shape.SetPrompt('raster_3d')
-        
+
         self.parent.canvas.Refresh()
         self.parent.SetStatusText('', 0)
         self.shape.SetPropDialog(None)
-        
+
         if self.IsModal():
-            event.Skip() 
+            event.Skip()
         else:
             self.Destroy()
-    
+
     def OnCancel(self, event):
         """Cancel pressed"""
         self.shape.SetPropDialog(None)
@@ -144,93 +157,110 @@
         else:
             self.Destroy()
 
+
 class ModelSearchDialog(wx.Dialog):
-    def __init__(self, parent, title = _("Add GRASS command to the model"),
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
+
+    def __init__(self, parent, title=_("Add GRASS command to the model"),
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
         """Graphical modeler module search window
-        
+
         :param parent: parent window
         :param id: window id
         :param title: window title
         :param kwargs: wx.Dialogs' arguments
         """
         self.parent = parent
-        
-        wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY, title = title, **kwargs)
+
+        wx.Dialog.__init__(
+            self,
+            parent=parent,
+            id=wx.ID_ANY,
+            title=title,
+            **kwargs)
         self.SetName("ModelerDialog")
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
-        
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass.ico'),
+                wx.BITMAP_TYPE_ICO))
+
         self._command = None
-        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
-        
-        self.cmdBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
+        self.cmdBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
                                    label=" %s " % _("Command"))
-        self.labelBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
-                                   label=" %s " % _("Label and comment"))
-        
+        self.labelBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
+                                     label=" %s " % _("Label and comment"))
+
         # menu data for search widget and prompt
         menuModel = LayerManagerMenuData()
-        
-        self.cmd_prompt = GPromptSTC(parent = self, menuModel = menuModel.GetModel())
+
+        self.cmd_prompt = GPromptSTC(
+            parent=self, menuModel=menuModel.GetModel())
         self.cmd_prompt.promptRunCmd.connect(self.OnCommand)
-        self.cmd_prompt.commandSelected.connect(lambda command: self.label.SetValue(command))
-        self.search = SearchModuleWidget(parent = self.panel,
-                                         model = menuModel.GetModel(),
-                                         showTip = True)
-        self.search.moduleSelected.connect(lambda name:
-                                           self.cmd_prompt.SetTextAndFocus(name + ' '))
+        self.cmd_prompt.commandSelected.connect(
+            lambda command: self.label.SetValue(command))
+        self.search = SearchModuleWidget(parent=self.panel,
+                                         model=menuModel.GetModel(),
+                                         showTip=True)
+        self.search.moduleSelected.connect(
+            lambda name: self.cmd_prompt.SetTextAndFocus(name + ' '))
         wx.CallAfter(self.cmd_prompt.SetFocus)
-        
-        self.label = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY)
-        self.comment = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY, style =  wx.TE_MULTILINE)
-        
+
+        self.label = wx.TextCtrl(parent=self.panel, id=wx.ID_ANY)
+        self.comment = wx.TextCtrl(
+            parent=self.panel,
+            id=wx.ID_ANY,
+            style=wx.TE_MULTILINE)
+
         self.btnCancel = wx.Button(self.panel, wx.ID_CANCEL)
-        self.btnOk     = wx.Button(self.panel, wx.ID_OK)
+        self.btnOk = wx.Button(self.panel, wx.ID_OK)
         self.btnOk.SetDefault()
 
         self.Bind(wx.EVT_BUTTON, self.OnOk, self.btnOk)
         self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
-        
+
         self._layout()
-        
+
         self.SetSize((500, -1))
 
     def _layout(self):
         cmdSizer = wx.StaticBoxSizer(self.cmdBox, wx.VERTICAL)
-        cmdSizer.Add(item = self.cmd_prompt, proportion = 1,
-                     flag = wx.EXPAND)
+        cmdSizer.Add(item=self.cmd_prompt, proportion=1,
+                     flag=wx.EXPAND)
         labelSizer = wx.StaticBoxSizer(self.labelBox, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
-        gridSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                           label = _("Label:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL, pos = (0, 0))
-        gridSizer.Add(item = self.label, pos = (0, 1), flag =  wx.EXPAND)
-        gridSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                           label = _("Comment:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL, pos = (1, 0))
-        gridSizer.Add(item = self.comment, pos = (1, 1), flag =  wx.EXPAND)
+        gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
+        gridSizer.Add(item=wx.StaticText(parent=self.panel, id=wx.ID_ANY,
+                                         label=_("Label:")),
+                      flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 0))
+        gridSizer.Add(item=self.label, pos=(0, 1), flag=wx.EXPAND)
+        gridSizer.Add(item=wx.StaticText(parent=self.panel, id=wx.ID_ANY,
+                                         label=_("Comment:")),
+                      flag=wx.ALIGN_CENTER_VERTICAL, pos=(1, 0))
+        gridSizer.Add(item=self.comment, pos=(1, 1), flag=wx.EXPAND)
         gridSizer.AddGrowableRow(1)
         gridSizer.AddGrowableCol(1)
-        labelSizer.Add(item = gridSizer, proportion = 1, flag = wx.EXPAND)
-        
+        labelSizer.Add(item=gridSizer, proportion=1, flag=wx.EXPAND)
+
         btnSizer = wx.StdDialogButtonSizer()
         btnSizer.AddButton(self.btnCancel)
         btnSizer.AddButton(self.btnOk)
         btnSizer.Realize()
-        
+
         mainSizer = wx.BoxSizer(wx.VERTICAL)
-        mainSizer.Add(item = self.search, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL, border = 3)
-        mainSizer.Add(item = cmdSizer, proportion = 1,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border = 3)
-        mainSizer.Add(item = labelSizer, proportion = 1,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border = 3)
-        mainSizer.Add(item = btnSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
-        
+        mainSizer.Add(item=self.search, proportion=0,
+                      flag=wx.EXPAND | wx.ALL, border=3)
+        mainSizer.Add(item=cmdSizer, proportion=1,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border=3)
+        mainSizer.Add(item=labelSizer, proportion=1,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border=3)
+        mainSizer.Add(item=btnSizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
+
         self.panel.SetSizer(mainSizer)
         mainSizer.Fit(self)
-        
+
         self.Layout()
 
     def GetPanel(self):
@@ -255,18 +285,20 @@
     def GetLabel(self):
         """Get label and comment"""
         return self.label.GetValue(), self.comment.GetValue()
-    
+
     def ValidateCmd(self, cmd):
         if len(cmd) < 1:
-            GError(parent = self,
-                   message = _("Command not defined.\n\n"
-                               "Unable to add new action to the model."))
+            GError(parent=self,
+                   message=_("Command not defined.\n\n"
+                             "Unable to add new action to the model."))
             return False
-        
+
         if cmd[0] not in globalvar.grassCmd:
-            GError(parent = self,
-                   message = _("'%s' is not a GRASS module.\n\n"
-                               "Unable to add new action to the model.") % cmd[0])
+            GError(
+                parent=self, message=_(
+                    "'%s' is not a GRASS module.\n\n"
+                    "Unable to add new action to the model.") %
+                cmd[0])
             return False
         return True
 
@@ -286,7 +318,7 @@
     def OnCancel(self, event):
         """Cancel pressed, close window"""
         self.Hide()
-        
+
     def Reset(self):
         """Reset dialog"""
         self.search.Reset()
@@ -295,128 +327,136 @@
         self.cmd_prompt.OnCmdErase(None)
         self.cmd_prompt.SetFocus()
 
+
 class ModelRelationDialog(wx.Dialog):
     """Relation properties dialog"""
-    def __init__(self, parent, shape, id = wx.ID_ANY, title = _("Relation properties"),
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
+
+    def __init__(self, parent, shape, id=wx.ID_ANY,
+                 title=_("Relation properties"),
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
         self.parent = parent
         self.shape = shape
-        
+
         options = self._getOptions()
         if not options:
             self.valid = False
             return
-        
+
         self.valid = True
-        wx.Dialog.__init__(self, parent, id, title, style = style, **kwargs)
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
-        
-        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
-        
-        self.fromBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
-                                    label = " %s " % _("From"))
-        self.toBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
-                                  label = " %s " % _("To"))
-        
-        self.option = wx.ComboBox(parent = self.panel, id = wx.ID_ANY,
-                                  style = wx.CB_READONLY,
-                                  choices = options)
+        wx.Dialog.__init__(self, parent, id, title, style=style, **kwargs)
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass.ico'),
+                wx.BITMAP_TYPE_ICO))
+
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
+        self.fromBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
+                                    label=" %s " % _("From"))
+        self.toBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
+                                  label=" %s " % _("To"))
+
+        self.option = wx.ComboBox(parent=self.panel, id=wx.ID_ANY,
+                                  style=wx.CB_READONLY,
+                                  choices=options)
         self.option.Bind(wx.EVT_COMBOBOX, self.OnOption)
-        
+
         self.btnCancel = wx.Button(self.panel, wx.ID_CANCEL)
-        self.btnOk     = wx.Button(self.panel, wx.ID_OK)
+        self.btnOk = wx.Button(self.panel, wx.ID_OK)
         self.btnOk.Enable(False)
-        
+
         self._layout()
 
     def _layout(self):
         mainSizer = wx.BoxSizer(wx.VERTICAL)
 
         fromSizer = wx.StaticBoxSizer(self.fromBox, wx.VERTICAL)
-        self._layoutShape(shape = self.shape.GetFrom(), sizer = fromSizer)
+        self._layoutShape(shape=self.shape.GetFrom(), sizer=fromSizer)
         toSizer = wx.StaticBoxSizer(self.toBox, wx.VERTICAL)
-        self._layoutShape(shape = self.shape.GetTo(), sizer = toSizer)
+        self._layoutShape(shape=self.shape.GetTo(), sizer=toSizer)
 
         btnSizer = wx.StdDialogButtonSizer()
         btnSizer.AddButton(self.btnCancel)
         btnSizer.AddButton(self.btnOk)
         btnSizer.Realize()
-        
-        mainSizer.Add(item = fromSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL, border = 5)
-        mainSizer.Add(item = toSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
-        mainSizer.Add(item = btnSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
-        
+
+        mainSizer.Add(item=fromSizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALL, border=5)
+        mainSizer.Add(item=toSizer, proportion=0, flag=wx.EXPAND |
+                      wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
+        mainSizer.Add(item=btnSizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
+
         self.panel.SetSizer(mainSizer)
         mainSizer.Fit(self.panel)
-        
+
         self.Layout()
         self.SetSize(self.GetBestSize())
-        
+
     def _layoutShape(self, shape, sizer):
         if isinstance(shape, ModelData):
-            sizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                           label = _("Data: %s") % shape.GetLog()),
-                      proportion = 1, flag = wx.EXPAND | wx.ALL,
-                      border = 5)
+            sizer.Add(item=wx.StaticText(parent=self.panel, id=wx.ID_ANY,
+                                         label=_("Data: %s") % shape.GetLog()),
+                      proportion=1, flag=wx.EXPAND | wx.ALL,
+                      border=5)
         elif isinstance(shape, ModelAction):
-            gridSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
-            gridSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                               label = _("Command:")),
-                          pos = (0, 0))
-            gridSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                               label = shape.GetLabel()),
-                          pos = (0, 1))
-            gridSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                               label = _("Option:")),
-                          flag = wx.ALIGN_CENTER_VERTICAL,
-                          pos = (1, 0))
-            gridSizer.Add(item = self.option,
-                          pos = (1, 1))
-            sizer.Add(item = gridSizer,
-                      proportion = 1, flag = wx.EXPAND | wx.ALL,
-                      border = 5)
-            
+            gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
+            gridSizer.Add(item=wx.StaticText(parent=self.panel, id=wx.ID_ANY,
+                                             label=_("Command:")),
+                          pos=(0, 0))
+            gridSizer.Add(item=wx.StaticText(parent=self.panel, id=wx.ID_ANY,
+                                             label=shape.GetLabel()),
+                          pos=(0, 1))
+            gridSizer.Add(item=wx.StaticText(parent=self.panel, id=wx.ID_ANY,
+                                             label=_("Option:")),
+                          flag=wx.ALIGN_CENTER_VERTICAL,
+                          pos=(1, 0))
+            gridSizer.Add(item=self.option,
+                          pos=(1, 1))
+            sizer.Add(item=gridSizer,
+                      proportion=1, flag=wx.EXPAND | wx.ALL,
+                      border=5)
+
     def _getOptions(self):
         """Get relevant options"""
         items = []
         fromShape = self.shape.GetFrom()
         if not isinstance(fromShape, ModelData):
-            GError(parent = self.parent,
-                   message = _("Relation doesn't start with data item.\n"
-                               "Unable to add relation."))
+            GError(parent=self.parent,
+                   message=_("Relation doesn't start with data item.\n"
+                             "Unable to add relation."))
             return items
-        
+
         toShape = self.shape.GetTo()
         if not isinstance(toShape, ModelAction):
-            GError(parent = self.parent,
-                   message = _("Relation doesn't point to GRASS command.\n"
-                               "Unable to add relation."))
+            GError(parent=self.parent,
+                   message=_("Relation doesn't point to GRASS command.\n"
+                             "Unable to add relation."))
             return items
-        
+
         prompt = fromShape.GetPrompt()
         task = toShape.GetTask()
         for p in task.get_options()['params']:
             if p.get('prompt', '') == prompt and \
                     'name' in p:
                 items.append(p['name'])
-        
+
         if not items:
-            GError(parent = self.parent,
-                   message = _("No relevant option found.\n"
-                               "Unable to add relation."))
+            GError(parent=self.parent,
+                   message=_("No relevant option found.\n"
+                             "Unable to add relation."))
         return items
-    
+
     def GetOption(self):
         """Get selected option"""
         return self.option.GetStringSelection()
-    
+
     def IsValid(self):
         """Check if relation is valid"""
         return self.valid
-    
+
     def OnOption(self, event):
         """Set option"""
         if event.GetString():
@@ -424,207 +464,227 @@
         else:
             self.btnOk.Enable(False)
 
+
 class ModelItemDialog(wx.Dialog):
     """Abstract item properties dialog"""
-    def __init__(self, parent, shape, title, id = wx.ID_ANY,
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
+
+    def __init__(self, parent, shape, title, id=wx.ID_ANY,
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
         self.parent = parent
         self.shape = shape
-        
-        wx.Dialog.__init__(self, parent, id, title = title, style = style, **kwargs)
-        
-        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
-        
-        self.condBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
+
+        wx.Dialog.__init__(
+            self,
+            parent,
+            id,
+            title=title,
+            style=style,
+            **kwargs)
+
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
+        self.condBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
                                     label=" %s " % _("Condition"))
-        self.condText = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
-                                    value = shape.GetLabel())
-        
-        self.itemList = ItemCheckListCtrl(parent = self.panel,
-                                          columns = [_("Label"),
-                                                     _("Command")],
-                                          shape = shape,
-                                          frame = parent)
-        
+        self.condText = wx.TextCtrl(parent=self.panel, id=wx.ID_ANY,
+                                    value=shape.GetLabel())
+
+        self.itemList = ItemCheckListCtrl(parent=self.panel,
+                                          columns=[_("Label"),
+                                                   _("Command")],
+                                          shape=shape,
+                                          frame=parent)
+
         self.itemList.Populate(self.parent.GetModel().GetItems())
-        
-        self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
-        self.btnOk     = wx.Button(parent = self.panel, id = wx.ID_OK)
+
+        self.btnCancel = wx.Button(parent=self.panel, id=wx.ID_CANCEL)
+        self.btnOk = wx.Button(parent=self.panel, id=wx.ID_OK)
         self.btnOk.SetDefault()
-        
+
     def _layout(self):
         """Do layout (virtual method)"""
         pass
-    
+
     def GetCondition(self):
         """Get loop condition"""
         return self.condText.GetValue()
 
+
 class ModelLoopDialog(ModelItemDialog):
     """Loop properties dialog"""
-    def __init__(self, parent, shape, id = wx.ID_ANY, title = _("Loop properties"),
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
+
+    def __init__(self, parent, shape, id=wx.ID_ANY, title=_("Loop properties"),
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
         ModelItemDialog.__init__(self, parent, shape, title,
-                                 style = style, **kwargs)
-        
-        self.listBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
+                                 style=style, **kwargs)
+
+        self.listBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
                                     label=" %s " % _("List of items in loop"))
-        
-        self.btnSeries = wx.Button(parent = self.panel, id = wx.ID_ANY,
-                                   label = _("Series"))
-        self.btnSeries.SetToolTipString(_("Define map series as condition for the loop"))
+
+        self.btnSeries = wx.Button(parent=self.panel, id=wx.ID_ANY,
+                                   label=_("Series"))
+        self.btnSeries.SetToolTipString(
+            _("Define map series as condition for the loop"))
         self.btnSeries.Bind(wx.EVT_BUTTON, self.OnSeries)
-        
+
         self._layout()
         self.SetMinSize(self.GetSize())
         self.SetSize((500, 400))
-        
+
     def _layout(self):
         """Do layout"""
         sizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         condSizer = wx.StaticBoxSizer(self.condBox, wx.HORIZONTAL)
-        condSizer.Add(item = self.condText, proportion = 1,
-                      flag = wx.ALL, border = 3)
-        condSizer.Add(item = self.btnSeries, proportion = 0,
-                      flag = wx.EXPAND)
+        condSizer.Add(item=self.condText, proportion=1,
+                      flag=wx.ALL, border=3)
+        condSizer.Add(item=self.btnSeries, proportion=0,
+                      flag=wx.EXPAND)
 
         listSizer = wx.StaticBoxSizer(self.listBox, wx.VERTICAL)
-        listSizer.Add(item = self.itemList, proportion = 1,
-                      flag = wx.EXPAND | wx.ALL, border = 3)
-        
+        listSizer.Add(item=self.itemList, proportion=1,
+                      flag=wx.EXPAND | wx.ALL, border=3)
+
         btnSizer = wx.StdDialogButtonSizer()
         btnSizer.AddButton(self.btnCancel)
         btnSizer.AddButton(self.btnOk)
         btnSizer.Realize()
 
-        sizer.Add(item = condSizer, proportion = 0,
-                  flag = wx.EXPAND | wx.ALL, border = 3)
-        sizer.Add(item = listSizer, proportion = 1,
-                  flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 3)
-        sizer.Add(item = btnSizer, proportion=0,
-                  flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
-        
+        sizer.Add(item=condSizer, proportion=0,
+                  flag=wx.EXPAND | wx.ALL, border=3)
+        sizer.Add(item=listSizer, proportion=1,
+                  flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=3)
+        sizer.Add(item=btnSizer, proportion=0,
+                  flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
+
         self.panel.SetSizer(sizer)
         sizer.Fit(self.panel)
-        
+
         self.Layout()
-        
+
     def GetItems(self):
         """Get list of selected actions"""
         return self.itemList.GetItems()
 
     def OnSeries(self, event):
         """Define map series as condition"""
-        dialog = MapLayersDialogForModeler(parent = self, title = _("Define series of maps"))
+        dialog = MapLayersDialogForModeler(
+            parent=self, title=_("Define series of maps"))
         if dialog.ShowModal() != wx.ID_OK:
             dialog.Destroy()
             return
-        
+
         cond = dialog.GetDSeries()
         if not cond:
             cond = 'map in %s' % map(lambda x: str(x), dialog.GetMapLayers())
-        
+
         self.condText.SetValue(cond)
-                               
+
         dialog.Destroy()
 
+
 class ModelConditionDialog(ModelItemDialog):
     """Condition properties dialog"""
-    def __init__(self, parent, shape, id = wx.ID_ANY, title = _("If-else properties"),
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
+
+    def __init__(self, parent, shape, id=wx.ID_ANY,
+                 title=_("If-else properties"),
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
         ModelItemDialog.__init__(self, parent, shape, title,
-                                 style = style, **kwargs)
-        
-        self.listBoxIf = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
-                                      label=" %s " % _("List of items in 'if' block"))
+                                 style=style, **kwargs)
+
+        self.listBoxIf = wx.StaticBox(
+            parent=self.panel, id=wx.ID_ANY, label=" %s " %
+            _("List of items in 'if' block"))
         self.itemListIf = self.itemList
         self.itemListIf.SetName('IfBlockList')
-        
-        self.listBoxElse = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
-                                        label=" %s " % _("List of items in 'else' block"))
-        self.itemListElse = ItemCheckListCtrl(parent = self.panel,
-                                              columns = [_("Label"),
-                                                         _("Command")],
-                                              shape = shape, frame = parent)
+
+        self.listBoxElse = wx.StaticBox(
+            parent=self.panel, id=wx.ID_ANY, label=" %s " %
+            _("List of items in 'else' block"))
+        self.itemListElse = ItemCheckListCtrl(parent=self.panel,
+                                              columns=[_("Label"),
+                                                       _("Command")],
+                                              shape=shape, frame=parent)
         self.itemListElse.SetName('ElseBlockList')
         self.itemListElse.Populate(self.parent.GetModel().GetItems())
-        
+
         self._layout()
         self.SetMinSize(self.GetSize())
         self.SetSize((500, 400))
-        
+
     def _layout(self):
         """Do layout"""
         sizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         condSizer = wx.StaticBoxSizer(self.condBox, wx.VERTICAL)
-        condSizer.Add(item = self.condText, proportion = 1,
-                      flag = wx.EXPAND)
-        
+        condSizer.Add(item=self.condText, proportion=1,
+                      flag=wx.EXPAND)
+
         listIfSizer = wx.StaticBoxSizer(self.listBoxIf, wx.VERTICAL)
-        listIfSizer.Add(item = self.itemListIf, proportion = 1,
-                        flag = wx.EXPAND)
+        listIfSizer.Add(item=self.itemListIf, proportion=1,
+                        flag=wx.EXPAND)
         listElseSizer = wx.StaticBoxSizer(self.listBoxElse, wx.VERTICAL)
-        listElseSizer.Add(item = self.itemListElse, proportion = 1,
-                          flag = wx.EXPAND)
-        
+        listElseSizer.Add(item=self.itemListElse, proportion=1,
+                          flag=wx.EXPAND)
+
         btnSizer = wx.StdDialogButtonSizer()
         btnSizer.AddButton(self.btnCancel)
         btnSizer.AddButton(self.btnOk)
         btnSizer.Realize()
 
-        sizer.Add(item = condSizer, proportion = 0,
-                  flag = wx.EXPAND | wx.ALL, border = 3)
-        sizer.Add(item = listIfSizer, proportion = 1,
-                  flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 3)
-        sizer.Add(item = listElseSizer, proportion = 1,
-                  flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 3)
-        sizer.Add(item = btnSizer, proportion=0,
-                  flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
-        
+        sizer.Add(item=condSizer, proportion=0,
+                  flag=wx.EXPAND | wx.ALL, border=3)
+        sizer.Add(item=listIfSizer, proportion=1,
+                  flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=3)
+        sizer.Add(item=listElseSizer, proportion=1,
+                  flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=3)
+        sizer.Add(item=btnSizer, proportion=0,
+                  flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
+
         self.panel.SetSizer(sizer)
         sizer.Fit(self.panel)
-        
+
         self.Layout()
 
     def OnCheckItemIf(self, index, flag):
         """Item in if-block checked/unchecked"""
         if flag is False:
             return
-        
+
         aId = int(self.itemListIf.GetItem(index, 0).GetText())
         if aId in self.itemListElse.GetItems()['checked']:
             self.itemListElse.CheckItemById(aId, False)
-            
+
     def OnCheckItemElse(self, index, flag):
         """Item in else-block checked/unchecked"""
         if flag is False:
             return
-        
+
         aId = int(self.itemListElse.GetItem(index, 0).GetText())
         if aId in self.itemListIf.GetItems()['checked']:
             self.itemListIf.CheckItemById(aId, False)
-        
+
     def GetItems(self):
         """Get items"""
-        return { 'if'   : self.itemListIf.GetItems(),
-                 'else' : self.itemListElse.GetItems() }
+        return {'if': self.itemListIf.GetItems(),
+                'else': self.itemListElse.GetItems()}
 
+
 class ModelListCtrl(wx.ListCtrl,
                     listmix.ListCtrlAutoWidthMixin,
                     listmix.TextEditMixin):
-    def __init__(self, parent, columns, frame, id = wx.ID_ANY, columnsNotEditable = [],
-                 style = wx.LC_REPORT | wx.BORDER_NONE |
-                 wx.LC_HRULES | wx.LC_VRULES, **kwargs):
+
+    def __init__(
+            self, parent, columns, frame, id=wx.ID_ANY, columnsNotEditable=[],
+            style=wx.LC_REPORT | wx.BORDER_NONE | wx.LC_HRULES | wx.LC_VRULES, **
+            kwargs):
         """List of model variables"""
         self.parent = parent
         self.columns = columns
         self.shape = None
-        self.frame  = frame
+        self.frame = frame
         self.columnNotEditable = columnsNotEditable
 
-        wx.ListCtrl.__init__(self, parent, id = id, style = style, **kwargs)
+        wx.ListCtrl.__init__(self, parent, id=id, style=style, **kwargs)
         listmix.ListCtrlAutoWidthMixin.__init__(self)
         listmix.TextEditMixin.__init__(self)
 
@@ -633,48 +693,52 @@
             self.InsertColumn(i, col)
             self.SetColumnWidth(i, wx.LIST_AUTOSIZE_USEHEADER)
             i += 1
-        
-        self.itemDataMap = {} # requested by sorter
-        self.itemCount   = 0
-        
+
+        self.itemDataMap = {}  # requested by sorter
+        self.itemCount = 0
+
         self.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT, self.OnBeginEdit)
         self.Bind(wx.EVT_LIST_END_LABEL_EDIT, self.OnEndEdit)
         self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick)
-        self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightUp) #wxMSW
-        self.Bind(wx.EVT_RIGHT_UP, self.OnRightUp)            #wxGTK
-                
+        self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightUp)  # wxMSW
+        self.Bind(wx.EVT_RIGHT_UP, self.OnRightUp)  # wxGTK
+
     def OnBeginEdit(self, event):
         """Editing of item started"""
         if self.columnNotEditable and event.m_col in self.columnNotEditable:
             event.Veto()
-            self.SetItemState(event.m_itemIndex,
-                              wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED)
+            self.SetItemState(
+                event.m_itemIndex,
+                wx.LIST_STATE_SELECTED,
+                wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED)
         else:
             event.Allow()
 
     def OnEndEdit(self, event):
         """Finish editing of item"""
         pass
-    
+
     def GetListCtrl(self):
         """Used by ColumnSorterMixin"""
         return self
-    
+
     def OnColClick(self, event):
         """Click on column header (order by)"""
         event.Skip()
 
+
 class VariableListCtrl(ModelListCtrl):
+
     def __init__(self, parent, columns, **kwargs):
         """List of model variables"""
         ModelListCtrl.__init__(self, parent, columns, **kwargs)
 
-        self.SetColumnWidth(2, 200) # default value
+        self.SetColumnWidth(2, 200)  # default value
 
     def GetData(self):
         """Get list data"""
         return self.itemDataMap
-    
+
     def Populate(self, data):
         """Populate the list"""
         self.itemDataMap = dict()
@@ -684,19 +748,19 @@
                                    values.get('value', ''),
                                    values.get('description', '')]
             i += 1
-        
+
         self.itemCount = len(self.itemDataMap.keys())
         self.DeleteAllItems()
         i = 0
         for name, vtype, value, desc in self.itemDataMap.itervalues():
-            index = self.InsertStringItem(sys.maxint, name)
+            index = self.InsertStringItem(sys.maxsize, name)
             self.SetStringItem(index, 0, name)
             self.SetStringItem(index, 1, vtype)
             self.SetStringItem(index, 2, value)
             self.SetStringItem(index, 3, desc)
             self.SetItemData(index, i)
             i += 1
-        
+
     def Append(self, name, vtype, value, desc):
         """Append new item to the list
 
@@ -707,17 +771,17 @@
             if iname == name:
                 return _("Variable <%s> already exists in the model. "
                          "Adding variable failed.") % name
-        
-        index = self.InsertStringItem(sys.maxint, name)
+
+        index = self.InsertStringItem(sys.maxsize, name)
         self.SetStringItem(index, 0, name)
         self.SetStringItem(index, 1, vtype)
         self.SetStringItem(index, 2, value)
         self.SetStringItem(index, 3, desc)
         self.SetItemData(index, self.itemCount)
-        
+
         self.itemDataMap[self.itemCount] = [name, vtype, value, desc]
         self.itemCount += 1
-        
+
         return None
 
     def OnRemove(self, event):
@@ -728,35 +792,37 @@
             del self.itemDataMap[item]
             item = self.GetFirstSelected()
         self.parent.UpdateModelVariables()
-        
+
         event.Skip()
-        
+
     def OnRemoveAll(self, event):
         """Remove all variable(s) from the model"""
-        dlg = wx.MessageBox(parent=self,
-                            message=_("Do you want to delete all variables from "
-                                      "the model?"),
-                            caption=_("Delete variables"),
-                            style=wx.YES_NO | wx.CENTRE)
+        dlg = wx.MessageBox(
+            parent=self,
+            message=_(
+                "Do you want to delete all variables from "
+                "the model?"),
+            caption=_("Delete variables"),
+            style=wx.YES_NO | wx.CENTRE)
         if dlg != wx.YES:
             return
-        
+
         self.DeleteAllItems()
         self.itemDataMap = dict()
-        
+
         self.parent.UpdateModelVariables()
-        
+
     def OnEndEdit(self, event):
         """Finish editing of item"""
         itemIndex = event.GetIndex()
         columnIndex = event.GetColumn()
         nameOld = self.GetItem(itemIndex, 0).GetText()
 
-        if columnIndex == 0: # TODO
+        if columnIndex == 0:  # TODO
             event.Veto()
-        
+
         self.itemDataMap[itemIndex][columnIndex] = event.GetText()
-        
+
         self.parent.UpdateModelVariables()
 
     def OnReload(self, event):
@@ -769,10 +835,10 @@
             self.popupID1 = wx.NewId()
             self.popupID2 = wx.NewId()
             self.popupID3 = wx.NewId()
-            self.Bind(wx.EVT_MENU, self.OnRemove,    id = self.popupID1)
-            self.Bind(wx.EVT_MENU, self.OnRemoveAll, id = self.popupID2)
-            self.Bind(wx.EVT_MENU, self.OnReload,    id = self.popupID3)
-        
+            self.Bind(wx.EVT_MENU, self.OnRemove, id=self.popupID1)
+            self.Bind(wx.EVT_MENU, self.OnRemoveAll, id=self.popupID2)
+            self.Bind(wx.EVT_MENU, self.OnReload, id=self.popupID3)
+
         # generate popup-menu
         menu = wx.Menu()
         menu.Append(self.popupID1, _("Delete selected"))
@@ -780,21 +846,23 @@
         if self.GetFirstSelected() == -1:
             menu.Enable(self.popupID1, False)
             menu.Enable(self.popupID2, False)
-        
+
         menu.AppendSeparator()
         menu.Append(self.popupID3, _("Reload"))
-        
+
         self.PopupMenu(menu)
         menu.Destroy()
 
+
 class ItemListCtrl(ModelListCtrl):
-    def __init__(self, parent, columns, frame, disablePopup = False, **kwargs):
+
+    def __init__(self, parent, columns, frame, disablePopup=False, **kwargs):
         """List of model actions"""
         self.disablePopup = disablePopup
 
         ModelListCtrl.__init__(self, parent, columns, frame, **kwargs)
         self.itemIdMap = list()
-        
+
         self.SetColumnWidth(0, 100)
         self.SetColumnWidth(1, 75)
         if len(self.columns) >= 3:
@@ -803,34 +871,40 @@
     def GetData(self):
         """Get list data"""
         return self.itemDataMap
-    
+
     def Populate(self, data):
         """Populate the list"""
         self.itemDataMap = dict()
         self.itemIdMap = list()
-        
+
         if self.shape:
             items = self.frame.GetModel().GetItems(objType=ModelAction)
             if isinstance(self.shape, ModelCondition):
                 if self.GetLabel() == 'ElseBlockList':
-                    shapeItems = map(lambda x: x.GetId(), self.shape.GetItems(items)['else'])
+                    shapeItems = map(
+                        lambda x: x.GetId(),
+                        self.shape.GetItems(items)['else'])
                 else:
-                    shapeItems = map(lambda x: x.GetId(), self.shape.GetItems(items)['if'])
+                    shapeItems = map(
+                        lambda x: x.GetId(),
+                        self.shape.GetItems(items)['if'])
             else:
-                shapeItems = map(lambda x: x.GetId(), self.shape.GetItems(items))
+                shapeItems = map(
+                    lambda x: x.GetId(),
+                    self.shape.GetItems(items))
         else:
             shapeItems = list()
-        
+
         i = 0
-        if len(self.columns) == 2: # ItemCheckList
+        if len(self.columns) == 2:  # ItemCheckList
             checked = list()
         for action in data:
             if isinstance(action, ModelData) or \
                     action == self.shape:
                 continue
-            
+
             self.itemIdMap.append(action.GetId())
-            
+
             if len(self.columns) == 2:
                 self.itemDataMap[i] = [action.GetLabel(),
                                        action.GetLog()]
@@ -856,15 +930,15 @@
                                        bId,
                                        ','.join(params),
                                        action.GetLog()]
-            
+
             i += 1
-        
+
         self.itemCount = len(self.itemDataMap.keys())
         self.DeleteAllItems()
         i = 0
         if len(self.columns) == 2:
             for name, desc in self.itemDataMap.itervalues():
-                index = self.InsertStringItem(sys.maxint, str(i))
+                index = self.InsertStringItem(sys.maxsize, str(i))
                 self.SetStringItem(index, 0, name)
                 self.SetStringItem(index, 1, desc)
                 self.SetItemData(index, i)
@@ -873,38 +947,38 @@
                 i += 1
         else:
             for name, inloop, param, desc in self.itemDataMap.itervalues():
-                index = self.InsertStringItem(sys.maxint, str(i))
+                index = self.InsertStringItem(sys.maxsize, str(i))
                 self.SetStringItem(index, 0, name)
                 self.SetStringItem(index, 1, inloop)
                 self.SetStringItem(index, 2, param)
                 self.SetStringItem(index, 3, desc)
                 self.SetItemData(index, i)
                 i += 1
-                
+
     def OnRemove(self, event):
         """Remove selected action(s) from the model"""
         model = self.frame.GetModel()
         canvas = self.frame.GetCanvas()
-        
+
         item = self.GetFirstSelected()
         while item != -1:
             self.DeleteItem(item)
             del self.itemDataMap[item]
-            
-            action = model.GetItem(item+1) # action indices starts at 1
+
+            action = model.GetItem(item + 1)  # action indices starts at 1
             if not action:
                 item = self.GetFirstSelected()
                 continue
-            
+
             canvas.RemoveShapes([action])
             self.frame.ModelChanged()
-            
+
             item = self.GetFirstSelected()
-        
+
         canvas.Refresh()
-        
+
         event.Skip()
-    
+
     def OnEndEdit(self, event):
         """Finish editing of item"""
         itemIndex = event.GetIndex()
@@ -915,10 +989,10 @@
             event.Veto()
             return
 
-        action.SetLabel(label = event.GetText())
+        action.SetLabel(label=event.GetText())
         self.frame.ModelChanged()
 
-    def OnReload(self, event = None):
+    def OnReload(self, event=None):
         """Reload list of actions"""
         self.Populate(self.frame.GetModel().GetItems(objType=ModelAction))
 
@@ -926,13 +1000,13 @@
         """Mouse right button up"""
         if self.disablePopup:
             return
-        
+
         if not hasattr(self, "popupId"):
             self.popupID = dict()
             self.popupID['remove'] = wx.NewId()
             self.popupID['reload'] = wx.NewId()
-            self.Bind(wx.EVT_MENU, self.OnRemove,    id = self.popupID['remove'])
-            self.Bind(wx.EVT_MENU, self.OnReload,    id = self.popupID['reload'])
+            self.Bind(wx.EVT_MENU, self.OnRemove, id=self.popupID['remove'])
+            self.Bind(wx.EVT_MENU, self.OnReload, id=self.popupID['reload'])
 
         # generate popup-menu
         menu = wx.Menu()
@@ -941,10 +1015,10 @@
             menu.Enable(self.popupID['remove'], False)
         menu.AppendSeparator()
         menu.Append(self.popupID['reload'], _("Reload"))
-        
+
         self.PopupMenu(menu)
         menu.Destroy()
-    
+
     def MoveItems(self, items, up):
         """Move items in the list
 
@@ -953,54 +1027,62 @@
         """
         if len(items) < 1:
             return
-        
+
         if items[0] == 0 and up:
             del items[0]
         if len(items) < 1:
             return
-        
-        if items[-1] == len(self.itemDataMap.keys())-1 and not up:
+
+        if items[-1] == len(self.itemDataMap.keys()) - 1 and not up:
             del items[-1]
         if len(items) < 1:
             return
 
-        model = self.frame.GetModel()        
+        model = self.frame.GetModel()
         modelActions = model.GetItems(objType=ModelAction)
         idxList = dict()
         itemsToSelect = list()
         for i in items:
             if up:
-                idx = i-1
+                idx = i - 1
             else:
-                idx = i+1
+                idx = i + 1
             itemsToSelect.append(idx)
-            idxList[model.GetItemIndex(modelActions[i])] = model.GetItemIndex(modelActions[idx])
-        
+            idxList[
+                model.GetItemIndex(
+                    modelActions[i])] = model.GetItemIndex(
+                modelActions[idx])
+
         # reorganize model items
         model.ReorderItems(idxList)
         model.Normalize()
         self.Populate(model.GetItems(objType=ModelAction))
-        
+
         # re-selected originaly selected item
         for item in itemsToSelect:
-            self.SetItemState(item,  wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED)
+            self.SetItemState(
+                item,
+                wx.LIST_STATE_SELECTED,
+                wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED)
 
+
 class ItemCheckListCtrl(ItemListCtrl, listmix.CheckListCtrlMixin):
+
     def __init__(self, parent, shape, columns, frame, **kwargs):
         self.parent = parent
-        self.frame  = frame
-        
+        self.frame = frame
+
         ItemListCtrl.__init__(self, parent, columns, frame,
-                              disablePopup = True, **kwargs)
+                              disablePopup=True, **kwargs)
         listmix.CheckListCtrlMixin.__init__(self)
         self.SetColumnWidth(0, 100)
-        
-        self.shape  = shape
-        
+
+        self.shape = shape
+
     def OnBeginEdit(self, event):
         """Disable editing"""
         event.Veto()
-        
+
     def OnCheckItem(self, index, flag):
         """Item checked/unchecked"""
         name = self.GetLabel()
@@ -1008,19 +1090,19 @@
             self.window.OnCheckItemIf(index, flag)
         elif name == 'ElseBlockList' and self.window:
             self.window.OnCheckItemElse(index, flag)
-        
+
     def GetItems(self):
         """Get list of selected actions"""
-        ids = { 'checked'   : list(),
-                'unchecked' : list() }
-        
+        ids = {'checked': list(),
+               'unchecked': list()}
+
         # action ids start at 1
         for i in range(self.GetItemCount()):
             if self.IsChecked(i):
                 ids['checked'].append(self.itemIdMap[i])
             else:
                 ids['unchecked'].append(self.itemIdMap[i])
-            
+
         return ids
 
     def CheckItemById(self, aId, flag):

Modified: grass/trunk/gui/wxpython/gmodeler/frame.py
===================================================================
--- grass/trunk/gui/wxpython/gmodeler/frame.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gmodeler/frame.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -29,40 +29,42 @@
 import random
 
 import wx
-from   wx.lib import ogl
-import wx.lib.flatnotebook    as FN
+from wx.lib import ogl
+import wx.lib.flatnotebook as FN
 
-from core                 import globalvar
+from core import globalvar
 from core.utils import _
-from gui_core.widgets     import GNotebook
+from gui_core.widgets import GNotebook
 from core.gconsole        import GConsole, \
     EVT_CMD_RUN, EVT_CMD_DONE, EVT_CMD_PREPARE
-from gui_core.goutput     import GConsoleWindow
-from core.debug           import Debug
-from core.gcmd            import GMessage, GException, GWarning, GError, RunCommand
-from gui_core.dialogs     import GetImageHandlers, TextEntryDialog
-from gui_core.ghelp       import ShowAboutDialog
+from gui_core.goutput import GConsoleWindow
+from core.debug import Debug
+from core.gcmd import GMessage, GException, GWarning, GError, RunCommand
+from gui_core.dialogs import GetImageHandlers, TextEntryDialog
+from gui_core.ghelp import ShowAboutDialog
 from gui_core.preferences import PreferencesBaseDialog
-from core.settings        import UserSettings
-from gui_core.menu        import Menu
-from gmodeler.menudata    import ModelerMenuData
-from gui_core.forms       import GUI
+from core.settings import UserSettings
+from gui_core.menu import Menu
+from gmodeler.menudata import ModelerMenuData
+from gui_core.forms import GUI
 from gmodeler.preferences import PreferencesDialog, PropertiesDialog
-from gmodeler.toolbars    import ModelerToolbar
+from gmodeler.toolbars import ModelerToolbar
 from core.giface import Notification
-from gui_core.pystc       import PyStc
+from gui_core.pystc import PyStc
 from gmodeler.giface import GraphicalModelerGrassInterface
-from gmodeler.model       import *
-from gmodeler.dialogs     import *
+from gmodeler.model import *
+from gmodeler.dialogs import *
 
 from grass.script.utils import try_remove
 from grass.script import core as grass
 
+
 class ModelFrame(wx.Frame):
-    def __init__(self, parent, giface, id = wx.ID_ANY,
-                 title = _("GRASS GIS Graphical Modeler"), **kwargs):
+
+    def __init__(self, parent, giface, id=wx.ID_ANY,
+                 title=_("GRASS GIS Graphical Modeler"), **kwargs):
         """Graphical modeler main window
-        
+
         :param parent: parent window
         :param id: window id
         :param title: window title
@@ -71,91 +73,121 @@
         """
         self.parent = parent
         self._giface = giface
-        self.searchDialog = None # module search dialog
+        self.searchDialog = None  # module search dialog
         self.baseTitle = title
         self.modelFile = None    # loaded model
         self.modelChanged = False
-        self.randomness = 40 # random layout
-        
+        self.randomness = 40  # random layout
+
         self.cursors = {
-            "default" : wx.StockCursor(wx.CURSOR_ARROW),
-            "cross"   : wx.StockCursor(wx.CURSOR_CROSS),
-            }
-        
-        wx.Frame.__init__(self, parent = parent, id = id, title = title, **kwargs)
+            "default": wx.StockCursor(wx.CURSOR_ARROW),
+            "cross": wx.StockCursor(wx.CURSOR_CROSS),
+        }
+
+        wx.Frame.__init__(self, parent=parent, id=id, title=title, **kwargs)
         self.SetName("Modeler")
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
-        
-        self.menubar = Menu(parent = self, model = ModelerMenuData().GetModel(separators=True))        
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass.ico'),
+                wx.BITMAP_TYPE_ICO))
+
+        self.menubar = Menu(
+            parent=self,
+            model=ModelerMenuData().GetModel(
+                separators=True))
         self.SetMenuBar(self.menubar)
-        
-        self.toolbar = ModelerToolbar(parent = self)
+
+        self.toolbar = ModelerToolbar(parent=self)
         # workaround for http://trac.wxwidgets.org/ticket/13888
         if sys.platform != 'darwin':
             self.SetToolBar(self.toolbar)
-        
-        self.statusbar = self.CreateStatusBar(number = 1)
-        
-        self.notebook = GNotebook(parent = self,
-                                  style = FN.FNB_FANCY_TABS | FN.FNB_BOTTOM |
+
+        self.statusbar = self.CreateStatusBar(number=1)
+
+        self.notebook = GNotebook(parent=self,
+                                  style=FN.FNB_FANCY_TABS | FN.FNB_BOTTOM |
                                   FN.FNB_NO_NAV_BUTTONS | FN.FNB_NO_X_BUTTON)
-        
+
         self.canvas = ModelCanvas(self)
         self.canvas.SetBackgroundColour(wx.WHITE)
         self.canvas.SetCursor(self.cursors["default"])
 
         self.model = Model(self.canvas)
-        
-        self.variablePanel = VariablePanel(parent = self)
-        
-        self.itemPanel = ItemPanel(parent = self)
-        
-        self.pythonPanel = PythonPanel(parent = self)
-        
-        self._gconsole = GConsole(guiparent = self)
-        self.goutput = GConsoleWindow(parent = self, gconsole = self._gconsole)
-        self.goutput.showNotification.connect(lambda message: self.SetStatusText(message))
 
+        self.variablePanel = VariablePanel(parent=self)
+
+        self.itemPanel = ItemPanel(parent=self)
+
+        self.pythonPanel = PythonPanel(parent=self)
+
+        self._gconsole = GConsole(guiparent=self)
+        self.goutput = GConsoleWindow(parent=self, gconsole=self._gconsole)
+        self.goutput.showNotification.connect(
+            lambda message: self.SetStatusText(message))
+
         # here events are binded twice
-        self._gconsole.Bind(EVT_CMD_RUN,
-            lambda event: self._switchPageHandler(event=event, notification=Notification.MAKE_VISIBLE))
-        self._gconsole.Bind(EVT_CMD_DONE,
-            lambda event: self._switchPageHandler(event=event, notification=Notification.RAISE_WINDOW))
+        self._gconsole.Bind(
+            EVT_CMD_RUN,
+            lambda event: self._switchPageHandler(
+                event=event,
+                notification=Notification.MAKE_VISIBLE))
+        self._gconsole.Bind(
+            EVT_CMD_DONE,
+            lambda event: self._switchPageHandler(
+                event=event,
+                notification=Notification.RAISE_WINDOW))
         self.Bind(EVT_CMD_RUN, self.OnCmdRun)
-        self._gconsole.Bind(EVT_CMD_DONE, self.OnCmdDone) # rewrite default method to avoid hiding progress bar
+        # rewrite default method to avoid hiding progress bar
+        self._gconsole.Bind(EVT_CMD_DONE, self.OnCmdDone)
         self.Bind(EVT_CMD_PREPARE, self.OnCmdPrepare)
-        
-        self.notebook.AddPage(page = self.canvas, text=_('Model'), name = 'model')
-        self.notebook.AddPage(page = self.itemPanel, text=_('Items'), name = 'items')
-        self.notebook.AddPage(page = self.variablePanel, text=_('Variables'), name = 'variables')
-        self.notebook.AddPage(page = self.pythonPanel, text=_('Python editor'), name = 'python')
-        self.notebook.AddPage(page = self.goutput, text=_('Command output'), name = 'output')
+
+        self.notebook.AddPage(page=self.canvas, text=_('Model'), name='model')
+        self.notebook.AddPage(
+            page=self.itemPanel,
+            text=_('Items'),
+            name='items')
+        self.notebook.AddPage(
+            page=self.variablePanel,
+            text=_('Variables'),
+            name='variables')
+        self.notebook.AddPage(
+            page=self.pythonPanel,
+            text=_('Python editor'),
+            name='python')
+        self.notebook.AddPage(
+            page=self.goutput,
+            text=_('Command output'),
+            name='output')
         wx.CallAfter(self.notebook.SetSelectionByName, 'model')
         wx.CallAfter(self.ModelChanged, False)
 
         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
         self.Bind(wx.EVT_SIZE, self.OnSize)
-        self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
-        
+        self.notebook.Bind(
+            FN.EVT_FLATNOTEBOOK_PAGE_CHANGED,
+            self.OnPageChanged)
+
         self._layout()
         self.SetMinSize((640, 300))
         self.SetSize((800, 600))
-        
+
         # fix goutput's pane size
         if self.goutput:
             self.goutput.SetSashPosition(int(self.GetSize()[1] * .75))
-        
+
     def _layout(self):
         """Do layout"""
         sizer = wx.BoxSizer(wx.VERTICAL)
 
-        sizer.Add(item = self.notebook, proportion = 1,
-                  flag = wx.EXPAND)
-        
+        sizer.Add(item=self.notebook, proportion=1,
+                  flag=wx.EXPAND)
+
         self.SetAutoLayout(True)
         self.SetSizer(sizer)
         sizer.Fit(self)
-        
+
         self.Layout()
 
     def _addEvent(self, item):
@@ -173,20 +205,29 @@
     def GetCanvas(self):
         """Get canvas"""
         return self.canvas
-    
+
     def GetModel(self):
         """Get model"""
         return self.model
-    
-    def ModelChanged(self, changed = True):
+
+    def ModelChanged(self, changed=True):
         """Update window title"""
         self.modelChanged = changed
-        
+
         if self.modelFile:
             if self.modelChanged:
-                self.SetTitle(self.baseTitle + " - " +  os.path.basename(self.modelFile) + '*')
+                self.SetTitle(
+                    self.baseTitle +
+                    " - " +
+                    os.path.basename(
+                        self.modelFile) +
+                    '*')
             else:
-                self.SetTitle(self.baseTitle + " - " +  os.path.basename(self.modelFile))
+                self.SetTitle(
+                    self.baseTitle +
+                    " - " +
+                    os.path.basename(
+                        self.modelFile))
         else:
             self.SetTitle(self.baseTitle)
 
@@ -196,25 +237,26 @@
         if page == self.notebook.GetPageIndexByName('python'):
             if self.pythonPanel.IsEmpty():
                 self.pythonPanel.RefreshScript()
-            
+
             if self.pythonPanel.IsModified():
-                self.SetStatusText(_('Python script contains local modifications'), 0)
+                self.SetStatusText(
+                    _('Python script contains local modifications'), 0)
             else:
                 self.SetStatusText(_('Python script is up-to-date'), 0)
         elif page == self.notebook.GetPageIndexByName('items'):
             self.itemPanel.Update()
-            
+
         event.Skip()
 
     def OnVariables(self, event):
         """Switch to variables page"""
         self.notebook.SetSelectionByName('variables')
-        
+
     def OnRemoveItem(self, event):
         """Remove shape
         """
         self.GetCanvas().RemoveSelected()
-        
+
     def OnCanvasRefresh(self, event):
         """Refresh canvas"""
         self.SetStatusText(_("Redrawing model..."), 0)
@@ -226,77 +268,77 @@
         try:
             action = self.GetModel().GetItems()[event.pid]
             if hasattr(action, "task"):
-                action.Update(running = True)
+                action.Update(running=True)
         except IndexError:
             pass
-        
+
     def OnCmdPrepare(self, event):
         """Prepare for running command"""
         if not event.userData:
             return
-        
-        event.onPrepare(item = event.userData['item'],
-                        params = event.userData['params'])
-        
+
+        event.onPrepare(item=event.userData['item'],
+                        params=event.userData['params'])
+
     def OnCmdDone(self, event):
         """Command done (or aborted)"""
         self.goutput.GetProgressBar().SetValue(0)
         try:
             action = self.GetModel().GetItems()[event.pid]
             if hasattr(action, "task"):
-                action.Update(running = True)
+                action.Update(running=True)
         except IndexError:
             pass
 
     def OnCloseWindow(self, event):
         """Close window"""
-        if self.modelChanged and \
-                UserSettings.Get(group='manager', key='askOnQuit', subkey='enabled'):
+        if self.modelChanged and UserSettings.Get(
+                group='manager', key='askOnQuit', subkey='enabled'):
             if self.modelFile:
                 message = _("Do you want to save changes in the model?")
             else:
                 message = _("Do you want to store current model settings "
                             "to model file?")
-            
+
             # ask user to save current settings
             dlg = wx.MessageDialog(self,
-                                   message = message,
+                                   message=message,
                                    caption=_("Quit Graphical Modeler"),
-                                   style = wx.YES_NO | wx.YES_DEFAULT |
+                                   style=wx.YES_NO | wx.YES_DEFAULT |
                                    wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
             ret = dlg.ShowModal()
             if ret == wx.ID_YES:
                 if not self.modelFile:
-                        self.OnWorkspaceSaveAs()
+                    self.OnWorkspaceSaveAs()
                 else:
                     self.WriteModelFile(self.modelFile)
             elif ret == wx.ID_CANCEL:
                 dlg.Destroy()
                 return
             dlg.Destroy()
-        
+
         self.Destroy()
 
     def OnSize(self, event):
         """Window resized, save to the model"""
         self.ModelChanged()
         event.Skip()
-        
+
     def OnPreferences(self, event):
         """Open preferences dialog"""
-        dlg = PreferencesDialog(parent = self, giface = self._giface)
+        dlg = PreferencesDialog(parent=self, giface=self._giface)
         dlg.CenterOnParent()
-        
+
         dlg.ShowModal()
         self.canvas.Refresh()
-        
+
     def OnHelp(self, event):
         """Show help"""
-        self._giface.Help(entry = 'wxGUI.gmodeler')
+        self._giface.Help(entry='wxGUI.gmodeler')
 
     def OnModelProperties(self, event):
         """Model properties dialog"""
-        dlg = PropertiesDialog(parent = self)
+        dlg = PropertiesDialog(parent=self)
         dlg.CentreOnParent()
         properties = self.model.GetProperties()
         dlg.Init(properties)
@@ -304,81 +346,86 @@
             self.ModelChanged()
             for key, value in dlg.GetValues().iteritems():
                 properties[key] = value
-            for action in self.model.GetItems(objType = ModelAction):
+            for action in self.model.GetItems(objType=ModelAction):
                 action.GetTask().set_flag('overwrite', properties['overwrite'])
-        
+
         dlg.Destroy()
-        
+
     def OnDeleteData(self, event):
         """Delete intermediate data"""
         rast, vect, rast3d, msg = self.model.GetIntermediateData()
-        
+
         if not rast and not vect and not rast3d:
-            GMessage(parent = self,
-                     message = _('No intermediate data to delete.'))
+            GMessage(parent=self,
+                     message=_('No intermediate data to delete.'))
             return
-        
-        dlg = wx.MessageDialog(parent = self,
-                               message= _("Do you want to permanently delete data?%s" % msg),
-                               caption=_("Delete intermediate data?"),
-                               style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
-        
+
+        dlg = wx.MessageDialog(
+            parent=self,
+            message=_(
+                "Do you want to permanently delete data?%s" %
+                msg),
+            caption=_("Delete intermediate data?"),
+            style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+
         ret = dlg.ShowModal()
         if ret == wx.ID_YES:
             dlg.Destroy()
-            
+
             if rast:
                 self._gconsole.RunCmd(['g.remove', '-f', 'type=raster',
-                                       'name=%s' %','.join(rast)])
+                                       'name=%s' % ','.join(rast)])
             if rast3d:
                 self._gconsole.RunCmd(['g.remove', '-f', 'type=raster_3d',
-                                       'name=%s' %','.join(rast3d)])
+                                       'name=%s' % ','.join(rast3d)])
             if vect:
                 self._gconsole.RunCmd(['g.remove', '-f', 'type=vector',
-                                       'name=%s' %','.join(vect)])
-            
-            self.SetStatusText(_("%d maps deleted from current mapset") % \
-                                 int(len(rast) + len(rast3d) + len(vect)))
+                                       'name=%s' % ','.join(vect)])
+
+            self.SetStatusText(_("%d maps deleted from current mapset") %
+                               int(len(rast) + len(rast3d) + len(vect)))
             return
-        
+
         dlg.Destroy()
-                
+
     def OnModelNew(self, event):
         """Create new model"""
         Debug.msg(4, "ModelFrame.OnModelNew():")
-        
+
         # ask user to save current model
         if self.modelFile and self.modelChanged:
             self.OnModelSave()
         elif self.modelFile is None and \
                 (self.model.GetNumItems() > 0 or len(self.model.GetData()) > 0):
-            dlg = wx.MessageDialog(self, message=_("Current model is not empty. "
-                                                   "Do you want to store current settings "
-                                                   "to model file?"),
-                                   caption=_("Create new model?"),
-                                   style=wx.YES_NO | wx.YES_DEFAULT |
-                                   wx.CANCEL | wx.ICON_QUESTION)
+            dlg = wx.MessageDialog(
+                self,
+                message=_(
+                    "Current model is not empty. "
+                    "Do you want to store current settings "
+                    "to model file?"),
+                caption=_("Create new model?"),
+                style=wx.YES_NO | wx.YES_DEFAULT | wx.CANCEL | wx.ICON_QUESTION)
             ret = dlg.ShowModal()
             if ret == wx.ID_YES:
                 self.OnModelSaveAs()
             elif ret == wx.ID_CANCEL:
                 dlg.Destroy()
                 return
-            
+
             dlg.Destroy()
-        
+
         # delete all items
         self.canvas.GetDiagram().DeleteAllShapes()
         self.model.Reset()
         self.canvas.Refresh()
         self.itemPanel.Update()
         self.variablePanel.Reset()
-        
+
         # no model file loaded
         self.modelFile = None
         self.modelChanged = False
         self.SetTitle(self.baseTitle)
-        
+
     def GetModelFile(self, ext=True):
         """Get model file
 
@@ -389,88 +436,110 @@
         if ext:
             return self.modelFile
         return os.path.splitext(self.modelFile)[0]
-    
+
     def OnModelOpen(self, event):
         """Load model from file"""
         filename = ''
-        dlg = wx.FileDialog(parent = self, message=_("Choose model file"),
-                            defaultDir = os.getcwd(),
+        dlg = wx.FileDialog(parent=self, message=_("Choose model file"),
+                            defaultDir=os.getcwd(),
                             wildcard=_("GRASS Model File (*.gxm)|*.gxm"))
         if dlg.ShowModal() == wx.ID_OK:
             filename = dlg.GetPath()
-                    
+
         if not filename:
             return
-        
+
         Debug.msg(4, "ModelFrame.OnModelOpen(): filename=%s" % filename)
-        
+
         # close current model
         self.OnModelClose()
-        
+
         self.LoadModelFile(filename)
-        
+
         self.modelFile = filename
-        self.SetTitle(self.baseTitle + " - " +  os.path.basename(self.modelFile))
-        self.SetStatusText(_('%(items)d items (%(actions)d actions) loaded into model') % \
-                               { 'items' : self.model.GetNumItems(),
-                                 'actions' : self.model.GetNumItems(actionOnly = True) }, 0)
-        
-    def OnModelSave(self, event = None):
+        self.SetTitle(
+            self.baseTitle +
+            " - " +
+            os.path.basename(
+                self.modelFile))
+        self.SetStatusText(
+            _('%(items)d items (%(actions)d actions) loaded into model') % {
+                'items': self.model.GetNumItems(),
+                'actions': self.model.GetNumItems(
+                    actionOnly=True)},
+            0)
+
+    def OnModelSave(self, event=None):
         """Save model to file"""
         if self.modelFile and self.modelChanged:
-            dlg = wx.MessageDialog(self, message=_("Model file <%s> already exists. "
-                                                   "Do you want to overwrite this file?") % \
-                                       self.modelFile,
-                                   caption=_("Save model"),
-                                   style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+            dlg = wx.MessageDialog(
+                self,
+                message=_(
+                    "Model file <%s> already exists. "
+                    "Do you want to overwrite this file?") %
+                self.modelFile,
+                caption=_("Save model"),
+                style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
             if dlg.ShowModal() == wx.ID_NO:
                 dlg.Destroy()
             else:
-                Debug.msg(4, "ModelFrame.OnModelSave(): filename=%s" % self.modelFile)
+                Debug.msg(
+                    4, "ModelFrame.OnModelSave(): filename=%s" %
+                    self.modelFile)
                 self.WriteModelFile(self.modelFile)
                 self.SetStatusText(_('File <%s> saved') % self.modelFile, 0)
-                self.SetTitle(self.baseTitle + " - " +  os.path.basename(self.modelFile))
+                self.SetTitle(
+                    self.baseTitle +
+                    " - " +
+                    os.path.basename(
+                        self.modelFile))
         elif not self.modelFile:
             self.OnModelSaveAs(None)
-        
+
     def OnModelSaveAs(self, event):
         """Create model to file as"""
         filename = ''
-        dlg = wx.FileDialog(parent = self,
-                            message = _("Choose file to save current model"),
-                            defaultDir = os.getcwd(),
+        dlg = wx.FileDialog(parent=self,
+                            message=_("Choose file to save current model"),
+                            defaultDir=os.getcwd(),
                             wildcard=_("GRASS Model File (*.gxm)|*.gxm"),
                             style=wx.FD_SAVE)
-        
-        
+
         if dlg.ShowModal() == wx.ID_OK:
             filename = dlg.GetPath()
-        
+
         if not filename:
             return
-        
+
         # check for extension
         if filename[-4:] != ".gxm":
             filename += ".gxm"
-        
+
         if os.path.exists(filename):
-            dlg = wx.MessageDialog(parent = self,
-                                   message=_("Model file <%s> already exists. "
-                                             "Do you want to overwrite this file?") % filename,
-                                   caption=_("File already exists"),
-                                   style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+            dlg = wx.MessageDialog(
+                parent=self,
+                message=_(
+                    "Model file <%s> already exists. "
+                    "Do you want to overwrite this file?") %
+                filename,
+                caption=_("File already exists"),
+                style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
             if dlg.ShowModal() != wx.ID_YES:
                 dlg.Destroy()
                 return
-        
+
         Debug.msg(4, "GMFrame.OnModelSaveAs(): filename=%s" % filename)
-        
+
         self.WriteModelFile(filename)
         self.modelFile = filename
-        self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile))
+        self.SetTitle(
+            self.baseTitle +
+            " - " +
+            os.path.basename(
+                self.modelFile))
         self.SetStatusText(_('File <%s> saved') % self.modelFile, 0)
 
-    def OnModelClose(self, event = None):
+    def OnModelClose(self, event=None):
         """Close model file"""
         Debug.msg(4, "ModelFrame.OnModelClose(): file=%s" % self.modelFile)
         # ask user to save current model
@@ -478,33 +547,35 @@
             self.OnModelSave()
         elif self.modelFile is None and \
                 (self.model.GetNumItems() > 0 or len(self.model.GetData()) > 0):
-            dlg = wx.MessageDialog(self, message=_("Current model is not empty. "
-                                                   "Do you want to store current settings "
-                                                   "to model file?"),
-                                   caption=_("Create new model?"),
-                                   style=wx.YES_NO | wx.YES_DEFAULT |
-                                   wx.CANCEL | wx.ICON_QUESTION)
+            dlg = wx.MessageDialog(
+                self,
+                message=_(
+                    "Current model is not empty. "
+                    "Do you want to store current settings "
+                    "to model file?"),
+                caption=_("Create new model?"),
+                style=wx.YES_NO | wx.YES_DEFAULT | wx.CANCEL | wx.ICON_QUESTION)
             ret = dlg.ShowModal()
             if ret == wx.ID_YES:
                 self.OnModelSaveAs()
             elif ret == wx.ID_CANCEL:
                 dlg.Destroy()
                 return
-            
+
             dlg.Destroy()
-        
+
         self.modelFile = None
         self.SetTitle(self.baseTitle)
-        
+
         self.canvas.GetDiagram().DeleteAllShapes()
         self.model.Reset()
-        
+
         self.canvas.Refresh()
-        
+
     def OnRunModel(self, event):
         """Run entire model"""
-        self.model.Run(self._gconsole, self.OnDone, parent = self)
-        
+        self.model.Run(self._gconsole, self.OnDone, parent=self)
+
     def OnDone(self, event):
         """Computation finished
 
@@ -518,33 +589,34 @@
                 data = self.model.fileInput[finput]
                 if not data:
                     continue
-                
+
                 fd = open(finput, "w")
                 try:
                     fd.write(data)
                 finally:
                     fd.close()
             del self.model.fileInput
-        
-    def OnValidateModel(self, event, showMsg = True):
+
+    def OnValidateModel(self, event, showMsg=True):
         """Validate entire model"""
         if self.model.GetNumItems() < 1:
-            GMessage(parent = self, 
-                     message = _('Model is empty. Nothing to validate.'))
+            GMessage(parent=self,
+                     message=_('Model is empty. Nothing to validate.'))
             return
-        
-        
+
         self.SetStatusText(_('Validating model...'), 0)
         errList = self.model.Validate()
         self.SetStatusText('', 0)
-        
+
         if errList:
-            GWarning(parent = self,
-                     message = _('Model is not valid.\n\n%s') % '\n'.join(errList))
+            GWarning(
+                parent=self,
+                message=_('Model is not valid.\n\n%s') %
+                '\n'.join(errList))
         else:
-            GMessage(parent = self,
-                     message = _('Model is valid.'))
-    
+            GMessage(parent=self,
+                     message=_('Model is valid.'))
+
     def OnExportImage(self, event):
         """Export model to image (default image)
         """
@@ -555,8 +627,8 @@
         # get current size of canvas
         for shape in self.canvas.GetDiagram().GetShapeList():
             w, h = shape.GetBoundingBoxMax()
-            x    = shape.GetX()
-            y    = shape.GetY()
+            x = shape.GetX()
+            y = shape.GetY()
             xmin = x - w / 2
             xmax = x + w / 2
             ymin = y - h / 2
@@ -571,54 +643,55 @@
                 ymaxImg = ymax
         size = wx.Size(int(xmaxImg - xminImg) + 50,
                        int(ymaxImg - yminImg) + 50)
-        bitmap = wx.EmptyBitmap(width = size.width, height = size.height)
-        
+        bitmap = wx.EmptyBitmap(width=size.width, height=size.height)
+
         filetype, ltype = GetImageHandlers(wx.ImageFromBitmap(bitmap))
-        
-        dlg = wx.FileDialog(parent = self,
-                            message = _("Choose a file name to save the image (no need to add extension)"),
-                            defaultDir = "",
-                            defaultFile = "",
-                            wildcard = filetype,
-                            style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
-        
+
+        dlg = wx.FileDialog(
+            parent=self,
+            message=_("Choose a file name to save the image (no need to add extension)"),
+            defaultDir="",
+            defaultFile="",
+            wildcard=filetype,
+            style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
+
         if dlg.ShowModal() == wx.ID_OK:
             path = dlg.GetPath()
             if not path:
                 dlg.Destroy()
                 return
-            
+
             base, ext = os.path.splitext(path)
             fileType = ltype[dlg.GetFilterIndex()]['type']
-            extType  = ltype[dlg.GetFilterIndex()]['ext']
+            extType = ltype[dlg.GetFilterIndex()]['ext']
             if ext != extType:
                 path = base + '.' + extType
-            
+
             dc = wx.MemoryDC(bitmap)
             dc.SetBackground(wx.WHITE_BRUSH)
             dc.SetBackgroundMode(wx.SOLID)
-            
+
             dc.BeginDrawing()
             self.canvas.GetDiagram().Clear(dc)
             self.canvas.GetDiagram().Redraw(dc)
             dc.EndDrawing()
-            
+
             bitmap.SaveFile(path, fileType)
             self.SetStatusText(_("Model exported to <%s>") % path)
-        
+
         dlg.Destroy()
-        
-    def OnExportPython(self, event = None, text = None):
+
+    def OnExportPython(self, event=None, text=None):
         """Export model to Python script"""
-        filename = self.pythonPanel.SaveAs(force = True)
+        filename = self.pythonPanel.SaveAs(force=True)
         self.SetStatusText(_("Model exported to <%s>") % filename)
 
     def OnDefineRelation(self, event):
         """Define relation between data and action items"""
         self.canvas.SetCursor(self.cursors["cross"])
-        self.defineRelation = { 'from' : None,
-                                'to'   : None }
-        
+        self.defineRelation = {'from': None,
+                               'to': None}
+
     def OnDefineLoop(self, event):
         """Define new loop in the model
 
@@ -626,18 +699,18 @@
             move to ModelCanvas?
         """
         self.ModelChanged()
-        
+
         width, height = self.canvas.GetSize()
-        loop = ModelLoop(self, x = width/2, y = height/2,
-                         id = self.model.GetNumItems() + 1)
+        loop = ModelLoop(self, x=width / 2, y=height / 2,
+                         id=self.model.GetNumItems() + 1)
         self.canvas.diagram.AddShape(loop)
         loop.Show(True)
-        
+
         self._addEvent(loop)
         self.model.AddItem(loop)
-        
+
         self.canvas.Refresh()
-        
+
     def OnDefineCondition(self, event):
         """Define new condition in the model
 
@@ -645,18 +718,18 @@
             move to ModelCanvas?
         """
         self.ModelChanged()
-        
+
         width, height = self.canvas.GetSize()
-        cond = ModelCondition(self, x = width/2, y = height/2,
-                              id = self.model.GetNumItems() + 1)
+        cond = ModelCondition(self, x=width / 2, y=height / 2,
+                              id=self.model.GetNumItems() + 1)
         self.canvas.diagram.AddShape(cond)
         cond.Show(True)
-        
+
         self._addEvent(cond)
         self.model.AddItem(cond)
-        
+
         self.canvas.Refresh()
-    
+
     def OnAddAction(self, event):
         """Add action to model"""
         if self.searchDialog is None:
@@ -664,105 +737,125 @@
             self.searchDialog.CentreOnParent()
         else:
             self.searchDialog.Reset()
-        
+
         if self.searchDialog.ShowModal() == wx.ID_CANCEL:
             self.searchDialog.Hide()
             return
-            
+
         cmd = self.searchDialog.GetCmd()
         self.searchDialog.Hide()
-        
+
         self.ModelChanged()
-        
+
         # add action to canvas
         x, y = self.canvas.GetNewShapePos()
         label, comment = self.searchDialog.GetLabel()
-        action = ModelAction(self.model, cmd = cmd,
-                             x = x + self._randomShift(),
-                             y = y + self._randomShift(),
-                             id = self.model.GetNextId(), label = label, comment = comment)
+        action = ModelAction(
+            self.model,
+            cmd=cmd,
+            x=x + self._randomShift(),
+            y=y + self._randomShift(),
+            id=self.model.GetNextId(),
+            label=label,
+            comment=comment)
         overwrite = self.model.GetProperties().get('overwrite', None)
         if overwrite is not None:
             action.GetTask().set_flag('overwrite', overwrite)
-        
+
         self.canvas.diagram.AddShape(action)
         action.Show(True)
-        
+
         self._addEvent(action)
         self.model.AddItem(action)
-        
+
         self.itemPanel.Update()
         self.canvas.Refresh()
         time.sleep(.1)
-        
+
         # show properties dialog
         win = action.GetPropDialog()
         if not win:
             cmdLength = len(action.GetLog(string=False))
             if cmdLength > 1 and action.IsValid():
-                self.GetOptData(dcmd = action.GetLog(string = False), layer = action,
-                                params = action.GetParams(), propwin = None)
+                self.GetOptData(dcmd=action.GetLog(string=False), layer=action,
+                                params=action.GetParams(), propwin=None)
             else:
-                gmodule = GUI(parent = self, show = True,
-                              giface = GraphicalModelerGrassInterface(self.model))
-                gmodule.ParseCommand(action.GetLog(string = False),
-                                     completed = (self.GetOptData, action, action.GetParams()))
+                gmodule = GUI(
+                    parent=self,
+                    show=True,
+                    giface=GraphicalModelerGrassInterface(
+                        self.model))
+                gmodule.ParseCommand(
+                    action.GetLog(
+                        string=False), completed=(
+                        self.GetOptData, action, action.GetParams()))
         elif win and not win.IsShown():
             win.Show()
-        
+
         if win:
             win.Raise()
-        
+
     def OnAddData(self, event):
         """Add data item to model
         """
         # add action to canvas
         width, height = self.canvas.GetSize()
-        data = ModelData(self, x = width/2 + self._randomShift(),
-                         y = height/2 + self._randomShift())
-       
-        dlg = ModelDataDialog(parent = self, shape = data)
+        data = ModelData(self, x=width / 2 + self._randomShift(),
+                         y=height / 2 + self._randomShift())
+
+        dlg = ModelDataDialog(parent=self, shape=data)
         data.SetPropDialog(dlg)
         dlg.CentreOnParent()
         ret = dlg.ShowModal()
         dlg.Destroy()
         if ret != wx.ID_OK:
             return
-        
+
         data.Update()
         self.canvas.diagram.AddShape(data)
         data.Show(True)
-        
+
         self.ModelChanged()
-        
+
         self._addEvent(data)
         self.model.AddItem(data)
-        
+
         self.canvas.Refresh()
 
     def OnAddComment(self, event):
         """Add comment to the model"""
-        dlg = TextEntryDialog(parent = self, message = _("Comment:"), caption = _("Add comment"),
-                              textStyle = wx.TE_MULTILINE, textSize = (300, 75))
-        
+        dlg = TextEntryDialog(
+            parent=self,
+            message=_("Comment:"),
+            caption=_("Add comment"),
+            textStyle=wx.TE_MULTILINE,
+            textSize=(
+                300,
+                75))
+
         if dlg.ShowModal() == wx.ID_OK:
             comment = dlg.GetValue()
             if not comment:
-                GError(_("Empty comment. Nothing to add to the model."), parent = self)
+                GError(
+                    _("Empty comment. Nothing to add to the model."),
+                    parent=self)
             else:
                 x, y = self.canvas.GetNewShapePos()
-                commentObj = ModelComment(self.model, x = x + self._randomShift(), y = y + self._randomShift(),
-                                          id = self.model.GetNextId(), label = comment)
+                commentObj = ModelComment(
+                    self.model, x=x + self._randomShift(),
+                    y=y + self._randomShift(),
+                    id=self.model.GetNextId(),
+                    label=comment)
                 self.canvas.diagram.AddShape(commentObj)
                 commentObj.Show(True)
                 self._addEvent(commentObj)
                 self.model.AddItem(commentObj)
-                
+
                 self.canvas.Refresh()
                 self.ModelChanged()
-        
+
         dlg.Destroy()
-        
+
     def _switchPageHandler(self, event, notification):
         self._switchPage(notification=notification)
         event.Skip()
@@ -781,54 +874,62 @@
     def OnAbout(self, event):
         """Display About window"""
         ShowAboutDialog(prgName=_('wxGUI Graphical Modeler'), startYear='2010')
-        
+
     def GetOptData(self, dcmd, layer, params, propwin):
         """Process action data"""
-        if params: # add data items
+        if params:  # add data items
             width, height = self.canvas.GetSize()
-            x = width/2 - 200 + self._randomShift()
-            y = height/2 + self._randomShift()
+            x = width / 2 - 200 + self._randomShift()
+            y = height / 2 + self._randomShift()
             for p in params['params']:
-                if p.get('prompt', '') not in ('raster', 'vector', 'raster_3d', 'dbtable'):
+                if p.get(
+                        'prompt', '') not in (
+                        'raster', 'vector', 'raster_3d', 'dbtable'):
                     continue
 
                 # add new data item if defined or required
-                if p.get('value', None) or \
-                   (p.get('age', 'old') != 'old' and p.get('required', 'no') == 'yes'):
+                if p.get(
+                        'value', None) or(
+                        p.get('age', 'old') != 'old' and p.get('required', 'no') ==
+                        'yes'):
                     data = layer.FindData(p.get('name', ''))
                     if data:
                         data.SetValue(p.get('value', ''))
                         data.Update()
                         continue
-                    
+
                     data = self.model.FindData(p.get('value', ''),
                                                p.get('prompt', ''))
                     if data:
                         if p.get('age', 'old') == 'old':
-                            rel = ModelRelation(parent = self, fromShape = data,
-                                                toShape = layer, param = p.get('name', ''))
+                            rel = ModelRelation(
+                                parent=self, fromShape=data, toShape=layer,
+                                param=p.get('name', ''))
                         else:
-                            rel = ModelRelation(parent = self, fromShape = layer,
-                                                toShape = data, param = p.get('name', ''))
+                            rel = ModelRelation(
+                                parent=self, fromShape=layer, toShape=data,
+                                param=p.get('name', ''))
                         layer.AddRelation(rel)
                         data.AddRelation(rel)
                         self.AddLine(rel)
                         data.Update()
                         continue
-                    
-                    data = ModelData(self, value = p.get('value', ''),
-                                     prompt = p.get('prompt', ''),
-                                     x = x, y = y)
+
+                    data = ModelData(self, value=p.get('value', ''),
+                                     prompt=p.get('prompt', ''),
+                                     x=x, y=y)
                     self._addEvent(data)
                     self.canvas.diagram.AddShape(data)
                     data.Show(True)
-                                                            
+
                     if p.get('age', 'old') == 'old':
-                        rel = ModelRelation(parent = self, fromShape = data,
-                                            toShape = layer, param = p.get('name', ''))
+                        rel = ModelRelation(
+                            parent=self, fromShape=data, toShape=layer,
+                            param=p.get('name', ''))
                     else:
-                        rel = ModelRelation(parent = self, fromShape = layer,
-                                            toShape = data, param = p.get('name', ''))
+                        rel = ModelRelation(
+                            parent=self, fromShape=layer, toShape=data,
+                            param=p.get('name', ''))
                     layer.AddRelation(rel)
                     data.AddRelation(rel)
                     self.AddLine(rel)
@@ -842,28 +943,28 @@
                         for item in remList:
                             self.canvas.diagram.RemoveShape(item)
                             item.__del__()
-            
+
                         for item in upList:
                             item.Update()
 
             # valid / parameterized ?
             layer.SetValid(params)
-            
+
             self.canvas.Refresh()
-        
+
         if dcmd:
             layer.SetProperties(params, propwin)
-            
+
         self.SetStatusText(layer.GetLog(), 0)
-        
+
     def AddLine(self, rel):
         """Add connection between model objects
-        
+
         :param rel: relation
         """
         fromShape = rel.GetFrom()
-        toShape   = rel.GetTo()
-        
+        toShape = rel.GetTo()
+
         rel.SetCanvas(self)
         rel.SetPen(wx.BLACK_PEN)
         rel.SetBrush(wx.BLACK_BRUSH)
@@ -872,37 +973,41 @@
         rel.MakeLineControlPoints(2)
         if points:
             for x, y in points:
-                rel.InsertLineControlPoint(point = wx.RealPoint(x, y))
-        
+                rel.InsertLineControlPoint(point=wx.RealPoint(x, y))
+
         self._addEvent(rel)
         try:
             fromShape.AddLine(rel, toShape)
         except TypeError:
-            pass # bug when connecting ModelCondition and ModelLoop - to be fixed
-        
+            pass  # bug when connecting ModelCondition and ModelLoop - to be fixed
+
         self.canvas.diagram.AddShape(rel)
         rel.Show(True)
-        
+
     def LoadModelFile(self, filename):
         """Load model definition stored in GRASS Model XML file (gxm)
         """
         try:
             self.model.LoadModel(filename)
         except GException as e:
-            GError(parent = self,
-                   message = _("Reading model file <%s> failed.\n"
-                               "Invalid file, unable to parse XML document.\n\n%s") % \
-                       (filename, e),
-                   showTraceback = False)
+            GError(
+                parent=self, message=_(
+                    "Reading model file <%s> failed.\n"
+                    "Invalid file, unable to parse XML document.\n\n%s") %
+                (filename, e), showTraceback=False)
             return
-        
+
         self.modelFile = filename
-        self.SetTitle(self.baseTitle + " - " +  os.path.basename(self.modelFile))
-        
+        self.SetTitle(
+            self.baseTitle +
+            " - " +
+            os.path.basename(
+                self.modelFile))
+
         self.SetStatusText(_("Please wait, loading model..."), 0)
-        
+
         # load actions
-        for item in self.model.GetItems(objType = ModelAction):
+        for item in self.model.GetItems(objType=ModelAction):
             self._addEvent(item)
             self.canvas.diagram.AddShape(item)
             item.Show(True)
@@ -916,116 +1021,128 @@
                 self.canvas.diagram.AddShape(dataItem)
                 self.AddLine(rel)
                 dataItem.Show(True)
-        
+
         # load loops
-        for item in self.model.GetItems(objType = ModelLoop):
+        for item in self.model.GetItems(objType=ModelLoop):
             self._addEvent(item)
             self.canvas.diagram.AddShape(item)
             item.Show(True)
-            
+
             # connect items in the loop
             self.DefineLoop(item)
 
         # load conditions
-        for item in self.model.GetItems(objType = ModelCondition):
+        for item in self.model.GetItems(objType=ModelCondition):
             self._addEvent(item)
             self.canvas.diagram.AddShape(item)
             item.Show(True)
-            
+
             # connect items in the condition
             self.DefineCondition(item)
-        
+
         # load comments
-        for item in self.model.GetItems(objType = ModelComment):
+        for item in self.model.GetItems(objType=ModelComment):
             self._addEvent(item)
             self.canvas.diagram.AddShape(item)
             item.Show(True)
-        
+
         # load variables
         self.variablePanel.Update()
         self.itemPanel.Update()
         self.SetStatusText('', 0)
-        
+
         # final updates
-        for action in self.model.GetItems(objType = ModelAction):
+        for action in self.model.GetItems(objType=ModelAction):
             action.SetValid(action.GetParams())
             action.Update()
-        
+
         self.canvas.Refresh(True)
-        
+
     def WriteModelFile(self, filename):
         """Save model to model file, recover original file on error.
-        
+
         :return: True on success
         :return: False on failure
         """
         self.ModelChanged(False)
         tmpfile = tempfile.TemporaryFile(mode='w+b')
         try:
-            WriteModelFile(fd = tmpfile, model = self.model)
-        except StandardError:
-            GError(parent = self,
-                   message = _("Writing current settings to model file failed."))
+            WriteModelFile(fd=tmpfile, model=self.model)
+        except Exception:
+            GError(parent=self,
+                   message=_("Writing current settings to model file failed."))
             return False
-        
+
         try:
             mfile = open(filename, "w")
             tmpfile.seek(0)
             for line in tmpfile.readlines():
                 mfile.write(line)
         except IOError:
-            wx.MessageBox(parent = self,
-                          message = _("Unable to open file <%s> for writing.") % filename,
-                          caption = _("Error"),
-                          style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
+            wx.MessageBox(
+                parent=self,
+                message=_("Unable to open file <%s> for writing.") %
+                filename,
+                caption=_("Error"),
+                style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
             return False
-        
+
         mfile.close()
-        
+
         return True
-    
+
     def DefineLoop(self, loop):
         """Define loop with given list of items"""
         parent = loop
         items = loop.GetItems(self.GetModel().GetItems())
         if not items:
             return
-        
+
         # remove defined relations first
         for rel in loop.GetRelations():
             self.canvas.GetDiagram().RemoveShape(rel)
         loop.Clear()
-        
+
         for item in items:
-            rel = ModelRelation(parent = self, fromShape = parent, toShape = item)
+            rel = ModelRelation(parent=self, fromShape=parent, toShape=item)
             dx = item.GetX() - parent.GetX()
             dy = item.GetY() - parent.GetY()
             loop.AddRelation(rel)
             if dx != 0:
-                rel.SetControlPoints(((parent.GetX(), parent.GetY() + dy / 2),
-                                      (parent.GetX() + dx, parent.GetY() + dy / 2)))
+                rel.SetControlPoints(
+                    ((parent.GetX(),
+                      parent.GetY() + dy / 2),
+                     (parent.GetX() + dx, parent.GetY() + dy / 2)))
             self.AddLine(rel)
             parent = item
-        
+
         # close loop
         item = items[-1]
-        rel = ModelRelation(parent = self, fromShape = item, toShape = loop)
+        rel = ModelRelation(parent=self, fromShape=item, toShape=loop)
         loop.AddRelation(rel)
         self.AddLine(rel)
         dx = (item.GetX() - loop.GetX()) + loop.GetWidth() / 2 + 50
         dy = item.GetHeight() / 2 + 50
         rel.MakeLineControlPoints(0)
-        rel.InsertLineControlPoint(point = wx.RealPoint(loop.GetX() - loop.GetWidth() / 2 ,
-                                                        loop.GetY()))
-        rel.InsertLineControlPoint(point = wx.RealPoint(item.GetX(),
-                                                        item.GetY() + item.GetHeight() / 2))
-        rel.InsertLineControlPoint(point = wx.RealPoint(item.GetX(),
-                                                        item.GetY() + dy))
-        rel.InsertLineControlPoint(point = wx.RealPoint(item.GetX() - dx,
-                                                        item.GetY() + dy))
-        rel.InsertLineControlPoint(point = wx.RealPoint(item.GetX() - dx,
-                                                        loop.GetY()))
-        
+        rel.InsertLineControlPoint(
+            point=wx.RealPoint(
+                loop.GetX() -
+                loop.GetWidth() /
+                2,
+                loop.GetY()))
+        rel.InsertLineControlPoint(
+            point=wx.RealPoint(
+                item.GetX(),
+                item.GetY() +
+                item.GetHeight() /
+                2))
+        rel.InsertLineControlPoint(point=wx.RealPoint(item.GetX(),
+                                                      item.GetY() + dy))
+        rel.InsertLineControlPoint(point=wx.RealPoint(item.GetX() - dx,
+                                                      item.GetY() + dy))
+        rel.InsertLineControlPoint(point=wx.RealPoint(item.GetX() - dx,
+                                                      loop.GetY()))
+
         self.canvas.Refresh()
 
     def DefineCondition(self, condition):
@@ -1033,55 +1150,63 @@
         items = condition.GetItems(self.model.GetItems(objType=ModelAction))
         if not items['if'] and not items['else']:
             return
-        
+
         parent = condition
-        
+
         # remove defined relations first
         for rel in condition.GetRelations():
             self.canvas.GetDiagram().RemoveShape(rel)
         condition.Clear()
-        dxIf   = condition.GetX() + condition.GetWidth() / 2
+        dxIf = condition.GetX() + condition.GetWidth() / 2
         dxElse = condition.GetX() - condition.GetWidth() / 2
-        dy     = condition.GetY()
+        dy = condition.GetY()
         for branch in items.keys():
             for item in items[branch]:
-                rel = ModelRelation(parent = self, fromShape = parent,
-                                    toShape = item)
+                rel = ModelRelation(parent=self, fromShape=parent,
+                                    toShape=item)
                 condition.AddRelation(rel)
                 self.AddLine(rel)
                 rel.MakeLineControlPoints(0)
                 if branch == 'if':
-                    rel.InsertLineControlPoint(point = wx.RealPoint(item.GetX() - item.GetWidth() / 2, item.GetY()))
-                    rel.InsertLineControlPoint(point = wx.RealPoint(dxIf, dy))
+                    rel.InsertLineControlPoint(
+                        point=wx.RealPoint(
+                            item.GetX() - item.GetWidth() / 2,
+                            item.GetY()))
+                    rel.InsertLineControlPoint(point=wx.RealPoint(dxIf, dy))
                 else:
-                    rel.InsertLineControlPoint(point = wx.RealPoint(dxElse, dy))
-                    rel.InsertLineControlPoint(point = wx.RealPoint(item.GetX() - item.GetWidth() / 2, item.GetY()))
+                    rel.InsertLineControlPoint(point=wx.RealPoint(dxElse, dy))
+                    rel.InsertLineControlPoint(
+                        point=wx.RealPoint(
+                            item.GetX() - item.GetWidth() / 2,
+                            item.GetY()))
                 parent = item
-        
+
         self.canvas.Refresh()
-        
+
+
 class ModelCanvas(ogl.ShapeCanvas):
     """Canvas where model is drawn"""
+
     def __init__(self, parent):
         self.parent = parent
         ogl.OGLInitialize()
         ogl.ShapeCanvas.__init__(self, parent)
-        
+
         self.diagram = ogl.Diagram()
         self.SetDiagram(self.diagram)
         self.diagram.SetCanvas(self)
-        
-        self.SetScrollbars(20, 20, 2000/20, 2000/20)
-        
-        self.Bind(wx.EVT_KEY_UP,  self.OnKeyUp)
-        self.Bind(wx.EVT_LEFT_DOWN,  self.OnLeftDown)
 
+        self.SetScrollbars(20, 20, 2000 / 20, 2000 / 20)
+
+        self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
+        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
+
     def OnKeyUp(self, event):
         """Key pressed"""
         kc = event.GetKeyCode()
         if kc == wx.WXK_DELETE:
             self.RemoveSelected()
-        
+
     def OnLeftDown(self, evt):
         self.SetFocus()
         evt.Skip()
@@ -1089,9 +1214,10 @@
     def RemoveSelected(self):
         """Remove selected shapes"""
         self.parent.ModelChanged()
-        
+
         diagram = self.GetDiagram()
-        shapes = [shape for shape in diagram.GetShapeList() if shape.Selected()]
+        shapes = [shape for shape in diagram.GetShapeList()
+                  if shape.Selected()]
         self.RemoveShapes(shapes)
 
     def RemoveShapes(self, shapes):
@@ -1106,12 +1232,12 @@
             for item in remList:
                 diagram.RemoveShape(item)
                 item.__del__()
-            
+
             for item in upList:
                 item.Update()
-        
+
         self.Refresh()
-        
+
     def GetNewShapePos(self):
         """Determine optimal position for newly added object
 
@@ -1119,7 +1245,7 @@
         """
         xNew, yNew = map(lambda x: x / 2, self.GetSize())
         diagram = self.GetDiagram()
-        
+
         for shape in diagram.GetShapeList():
             y = shape.GetY()
             yBox = shape.GetBoundingBoxMin()[1] / 2
@@ -1138,33 +1264,35 @@
 
         return selected
 
+
 class ModelEvtHandler(ogl.ShapeEvtHandler):
     """Model event handler class"""
+
     def __init__(self, log, frame):
         ogl.ShapeEvtHandler.__init__(self)
         self.log = log
         self.frame = frame
         self.x = self.y = None
-        
-    def OnLeftClick(self, x, y, keys = 0, attachment = 0):
+
+    def OnLeftClick(self, x, y, keys=0, attachment=0):
         """Left mouse button pressed -> select item & update statusbar"""
         shape = self.GetShape()
         canvas = shape.GetCanvas()
         dc = wx.ClientDC(canvas)
-        
+
         # probably does nothing, removed from wxPython 2.9
         # canvas.PrepareDC(dc)
-        
+
         if hasattr(self.frame, 'defineRelation'):
             drel = self.frame.defineRelation
             if drel['from'] is None:
                 drel['from'] = shape
             elif drel['to'] is None:
                 drel['to'] = shape
-                rel = ModelRelation(parent = self.frame, fromShape = drel['from'],
-                                    toShape = drel['to'])
-                dlg = ModelRelationDialog(parent = self.frame,
-                                          shape = rel)
+                rel = ModelRelation(parent=self.frame, fromShape=drel['from'],
+                                    toShape=drel['to'])
+                dlg = ModelRelationDialog(parent=self.frame,
+                                          shape=rel)
                 if dlg.IsValid():
                     ret = dlg.ShowModal()
                     if ret == wx.ID_OK:
@@ -1173,45 +1301,50 @@
                         drel['from'].AddRelation(rel)
                         drel['to'].AddRelation(rel)
                         drel['from'].Update()
-                        params = { 'params' : [{ 'name' : option,
-                                                 'value' : drel['from'].GetValue()}] }
+                        params = {'params': [
+                            {'name': option, 'value': drel['from'].GetValue()}]}
                         drel['to'].MergeParams(params)
                         self.frame.AddLine(rel)
-                
+
                     dlg.Destroy()
                 del self.frame.defineRelation
-        
+
         # select object
-        self._onSelectShape(shape, append = True if keys == 1 else False)
-        
+        self._onSelectShape(shape, append=True if keys == 1 else False)
+
         if hasattr(shape, "GetLog"):
             self.log.SetStatusText(shape.GetLog(), 0)
         else:
             self.log.SetStatusText('', 0)
-        
-    def OnLeftDoubleClick(self, x, y, keys = 0, attachment = 0):
+
+    def OnLeftDoubleClick(self, x, y, keys=0, attachment=0):
         """Left mouse button pressed (double-click) -> show properties"""
         self.OnProperties()
-        
-    def OnProperties(self, event = None):
+
+    def OnProperties(self, event=None):
         """Show properties dialog"""
         self.frame.ModelChanged()
         shape = self.GetShape()
         if isinstance(shape, ModelAction):
-            gmodule = GUI(parent = self.frame, show = True,
-                          giface = GraphicalModelerGrassInterface(self.frame.GetModel()))
-            gmodule.ParseCommand(shape.GetLog(string = False),
-                                 completed = (self.frame.GetOptData, shape, shape.GetParams()))
-        
+            gmodule = GUI(
+                parent=self.frame,
+                show=True,
+                giface=GraphicalModelerGrassInterface(
+                    self.frame.GetModel()))
+            gmodule.ParseCommand(
+                shape.GetLog(
+                    string=False), completed=(
+                    self.frame.GetOptData, shape, shape.GetParams()))
+
         elif isinstance(shape, ModelData):
             if shape.GetPrompt() in ('raster', 'vector', 'raster_3d'):
-                dlg = ModelDataDialog(parent = self.frame, shape = shape)
+                dlg = ModelDataDialog(parent=self.frame, shape=shape)
                 shape.SetPropDialog(dlg)
                 dlg.CentreOnParent()
                 dlg.Show()
-        
+
         elif isinstance(shape, ModelLoop):
-            dlg = ModelLoopDialog(parent = self.frame, shape = shape)
+            dlg = ModelLoopDialog(parent=self.frame, shape=shape)
             dlg.CentreOnParent()
             if dlg.ShowModal() == wx.ID_OK:
                 shape.SetLabel(dlg.GetCondition())
@@ -1231,11 +1364,11 @@
                 self.frame.DefineLoop(shape)
                 self.frame.SetStatusText(shape.GetLog(), 0)
             self.frame.GetCanvas().Refresh()
-            
+
             dlg.Destroy()
-        
+
         elif isinstance(shape, ModelCondition):
-            dlg = ModelConditionDialog(parent = self.frame, shape = shape)
+            dlg = ModelConditionDialog(parent=self.frame, shape=shape)
             dlg.CentreOnParent()
             if dlg.ShowModal() == wx.ID_OK:
                 shape.SetLabel(dlg.GetCondition())
@@ -1251,29 +1384,29 @@
                         action.SetBlock(shape)
                         if action:
                             alist.append(aId)
-                    shape.SetItems(alist, branch = b)
+                    shape.SetItems(alist, branch=b)
                 self.frame.DefineCondition(shape)
             self.frame.GetCanvas().Refresh()
-            
+
             dlg.Destroy()
-                   
-    def OnBeginDragLeft(self, x, y, keys = 0, attachment = 0):
+
+    def OnBeginDragLeft(self, x, y, keys=0, attachment=0):
         """Drag shape (begining)"""
         self.frame.ModelChanged()
         if self._previousHandler:
             self._previousHandler.OnBeginDragLeft(x, y, keys, attachment)
-        
-    def OnEndDragLeft(self, x, y, keys = 0, attachment = 0):
+
+    def OnEndDragLeft(self, x, y, keys=0, attachment=0):
         """Drag shape (end)"""
         if self._previousHandler:
             self._previousHandler.OnEndDragLeft(x, y, keys, attachment)
-        
+
         shape = self.GetShape()
         if isinstance(shape, ModelLoop):
             self.frame.DefineLoop(shape)
         elif isinstance(shape, ModelCondition):
             self.frame.DefineCondition(shape)
-        
+
         for mo in shape.GetBlock():
             if isinstance(mo, ModelLoop):
                 self.frame.DefineLoop(mo)
@@ -1289,79 +1422,109 @@
         self.frame.ModelChanged()
         if self._previousHandler:
             self._previousHandler.OnEndSize(x, y)
-        
-    def OnRightClick(self, x, y, keys = 0, attachment = 0):
+
+    def OnRightClick(self, x, y, keys=0, attachment=0):
         """Right click -> pop-up menu"""
-        if not hasattr (self, "popupID"):
+        if not hasattr(self, "popupID"):
             self.popupID = dict()
             for key in ('remove', 'enable', 'addPoint',
                         'delPoint', 'intermediate', 'props', 'id',
                         'label', 'comment'):
                 self.popupID[key] = wx.NewId()
-        
+
         # record coordinates
         self.x = x
         self.y = y
-        
+
         # select object
         shape = self.GetShape()
         self._onSelectShape(shape)
-        
+
         popupMenu = wx.Menu()
         popupMenu.Append(self.popupID['remove'], text=_('Remove'))
-        self.frame.Bind(wx.EVT_MENU, self.OnRemove, id = self.popupID['remove'])
+        self.frame.Bind(wx.EVT_MENU, self.OnRemove, id=self.popupID['remove'])
         if isinstance(shape, ModelAction) or isinstance(shape, ModelLoop):
             if shape.IsEnabled():
                 popupMenu.Append(self.popupID['enable'], text=_('Disable'))
-                self.frame.Bind(wx.EVT_MENU, self.OnDisable, id = self.popupID['enable'])
+                self.frame.Bind(
+                    wx.EVT_MENU,
+                    self.OnDisable,
+                    id=self.popupID['enable'])
             else:
                 popupMenu.Append(self.popupID['enable'], text=_('Enable'))
-                self.frame.Bind(wx.EVT_MENU, self.OnEnable, id = self.popupID['enable'])
+                self.frame.Bind(
+                    wx.EVT_MENU,
+                    self.OnEnable,
+                    id=self.popupID['enable'])
         if isinstance(shape, ModelAction) or isinstance(shape, ModelComment):
             popupMenu.AppendSeparator()
         if isinstance(shape, ModelAction):
             popupMenu.Append(self.popupID['label'], text=_('Set label'))
-            self.frame.Bind(wx.EVT_MENU, self.OnSetLabel, id = self.popupID['label'])
+            self.frame.Bind(
+                wx.EVT_MENU,
+                self.OnSetLabel,
+                id=self.popupID['label'])
         if isinstance(shape, ModelAction) or isinstance(shape, ModelComment):
             popupMenu.Append(self.popupID['comment'], text=_('Set comment'))
-            self.frame.Bind(wx.EVT_MENU, self.OnSetComment, id = self.popupID['comment'])
+            self.frame.Bind(
+                wx.EVT_MENU,
+                self.OnSetComment,
+                id=self.popupID['comment'])
 
         if isinstance(shape, ModelRelation):
             popupMenu.AppendSeparator()
-            popupMenu.Append(self.popupID['addPoint'], text=_('Add control point'))
-            self.frame.Bind(wx.EVT_MENU, self.OnAddPoint, id = self.popupID['addPoint'])
-            popupMenu.Append(self.popupID['delPoint'], text=_('Remove control point'))
-            self.frame.Bind(wx.EVT_MENU, self.OnRemovePoint, id = self.popupID['delPoint'])
+            popupMenu.Append(
+                self.popupID['addPoint'],
+                text=_('Add control point'))
+            self.frame.Bind(
+                wx.EVT_MENU,
+                self.OnAddPoint,
+                id=self.popupID['addPoint'])
+            popupMenu.Append(
+                self.popupID['delPoint'],
+                text=_('Remove control point'))
+            self.frame.Bind(
+                wx.EVT_MENU,
+                self.OnRemovePoint,
+                id=self.popupID['delPoint'])
             if len(shape.GetLineControlPoints()) == 2:
                 popupMenu.Enable(self.popupID['delPoint'], False)
-        
+
         if isinstance(shape, ModelData) and '@' not in shape.GetValue():
             popupMenu.AppendSeparator()
-            popupMenu.Append(self.popupID['intermediate'], text=_('Intermediate'),
-                             kind = wx.ITEM_CHECK)
+            popupMenu.Append(
+                self.popupID['intermediate'],
+                text=_('Intermediate'),
+                kind=wx.ITEM_CHECK)
             if self.GetShape().IsIntermediate():
                 popupMenu.Check(self.popupID['intermediate'], True)
-            
-            self.frame.Bind(wx.EVT_MENU, self.OnIntermediate, id = self.popupID['intermediate'])
-            
+
+            self.frame.Bind(
+                wx.EVT_MENU,
+                self.OnIntermediate,
+                id=self.popupID['intermediate'])
+
         if isinstance(shape, ModelData) or \
                 isinstance(shape, ModelAction) or \
                 isinstance(shape, ModelLoop):
             popupMenu.AppendSeparator()
             popupMenu.Append(self.popupID['props'], text=_('Properties'))
-            self.frame.Bind(wx.EVT_MENU, self.OnProperties, id = self.popupID['props'])
-        
+            self.frame.Bind(
+                wx.EVT_MENU,
+                self.OnProperties,
+                id=self.popupID['props'])
+
         self.frame.PopupMenu(popupMenu)
         popupMenu.Destroy()
 
     def OnDisable(self, event):
         """Disable action"""
         self._onEnable(False)
-        
+
     def OnEnable(self, event):
         """Disable action"""
         self._onEnable(True)
-        
+
     def _onEnable(self, enable):
         shape = self.GetShape()
         shape.Enable(enable)
@@ -1370,8 +1533,11 @@
 
     def OnSetLabel(self, event):
         shape = self.GetShape()
-        dlg = wx.TextEntryDialog(parent = self.frame, message = _("Label:"), caption = _("Set label"),
-                                 defaultValue = shape.GetLabel())
+        dlg = wx.TextEntryDialog(
+            parent=self.frame,
+            message=_("Label:"),
+            caption=_("Set label"),
+            defaultValue=shape.GetLabel())
         if dlg.ShowModal() == wx.ID_OK:
             label = dlg.GetValue()
             shape.SetLabel(label)
@@ -1379,12 +1545,14 @@
             self.frame.itemPanel.Update()
             self.frame.canvas.Refresh()
         dlg.Destroy()
-    
+
     def OnSetComment(self, event):
         shape = self.GetShape()
-        dlg = TextEntryDialog(parent = self.frame, message = _("Comment:"), caption = _("Set comment"),
-                              defaultValue = shape.GetComment(),
-                              textStyle = wx.TE_MULTILINE, textSize = (300, 75))
+        dlg = TextEntryDialog(
+            parent=self.frame, message=_("Comment:"),
+            caption=_("Set comment"),
+            defaultValue=shape.GetComment(),
+            textStyle=wx.TE_MULTILINE, textSize=(300, 75))
         if dlg.ShowModal() == wx.ID_OK:
             comment = dlg.GetValue()
             shape.SetComment(comment)
@@ -1395,35 +1563,35 @@
     def _onSelectShape(self, shape, append=False):
         canvas = shape.GetCanvas()
         dc = wx.ClientDC(canvas)
-        
+
         if shape.Selected():
             shape.Select(False, dc)
         else:
             redraw = False
             shapeList = canvas.GetDiagram().GetShapeList()
             toUnselect = list()
-            
+
             if not append:
                 for s in shapeList:
                     if s.Selected():
                         toUnselect.append(s)
-            
+
             shape.Select(True, dc)
-            
+
             for s in toUnselect:
                 s.Select(False, dc)
 
         canvas.Refresh(False)
-        
+
     def OnAddPoint(self, event):
         """Add control point"""
         shape = self.GetShape()
-        shape.InsertLineControlPoint(point = wx.RealPoint(self.x, self.y))
+        shape.InsertLineControlPoint(point=wx.RealPoint(self.x, self.y))
         shape.ResetShapes()
         shape.Select(True)
         self.frame.ModelChanged()
         self.frame.canvas.Refresh()
-        
+
     def OnRemovePoint(self, event):
         """Remove control point"""
         shape = self.GetShape()
@@ -1432,7 +1600,7 @@
         shape.Select(True)
         self.frame.ModelChanged()
         self.frame.canvas.Refresh()
-        
+
     def OnIntermediate(self, event):
         """Mark data as intermediate"""
         self.frame.ModelChanged()
@@ -1445,114 +1613,121 @@
         """
         self.frame.GetCanvas().RemoveShapes([self.GetShape()])
         self.frame.itemPanel.Update()
-       
+
+
 class VariablePanel(wx.Panel):
-    def __init__(self, parent, id = wx.ID_ANY,
+
+    def __init__(self, parent, id=wx.ID_ANY,
                  **kwargs):
         """Manage model variables panel
         """
         self.parent = parent
-        
-        wx.Panel.__init__(self, parent = parent, id = id, **kwargs)
-        
-        self.listBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                                    label=" %s " % _("List of variables - right-click to delete"))
-        
-        self.list = VariableListCtrl(parent = self,
-                                     columns = [_("Name"), _("Data type"),
-                                                _("Default value"), _("Description")],
-                                     frame = self.parent)
-        
+
+        wx.Panel.__init__(self, parent=parent, id=id, **kwargs)
+
+        self.listBox = wx.StaticBox(
+            parent=self, id=wx.ID_ANY, label=" %s " %
+            _("List of variables - right-click to delete"))
+
+        self.list = VariableListCtrl(
+            parent=self,
+            columns=[
+                _("Name"),
+                _("Data type"),
+                _("Default value"),
+                _("Description")],
+            frame=self.parent)
+
         # add new category
-        self.addBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                                   label = " %s " % _("Add new variable"))
-        self.name = wx.TextCtrl(parent = self, id = wx.ID_ANY)
+        self.addBox = wx.StaticBox(parent=self, id=wx.ID_ANY,
+                                   label=" %s " % _("Add new variable"))
+        self.name = wx.TextCtrl(parent=self, id=wx.ID_ANY)
         wx.CallAfter(self.name.SetFocus)
-        self.type = wx.Choice(parent = self, id = wx.ID_ANY,
-                              choices = [_("integer"),
-                                         _("float"),
-                                         _("string"),
-                                         _("raster"),
-                                         _("vector"),
-                                         _("region"),
-                                         _("mapset"),
-                                         _("file"),
-                                         _("dir")])
-        self.type.SetSelection(2) # string
-        self.value = wx.TextCtrl(parent = self, id = wx.ID_ANY)
-        self.desc = wx.TextCtrl(parent = self, id = wx.ID_ANY)
-        
+        self.type = wx.Choice(parent=self, id=wx.ID_ANY,
+                              choices=[_("integer"),
+                                       _("float"),
+                                       _("string"),
+                                       _("raster"),
+                                       _("vector"),
+                                       _("region"),
+                                       _("mapset"),
+                                       _("file"),
+                                       _("dir")])
+        self.type.SetSelection(2)  # string
+        self.value = wx.TextCtrl(parent=self, id=wx.ID_ANY)
+        self.desc = wx.TextCtrl(parent=self, id=wx.ID_ANY)
+
         # buttons
-        self.btnAdd = wx.Button(parent = self, id = wx.ID_ADD)
+        self.btnAdd = wx.Button(parent=self, id=wx.ID_ADD)
         self.btnAdd.SetToolTipString(_("Add new variable to the model"))
         self.btnAdd.Enable(False)
-        
+
         # bindings
         self.name.Bind(wx.EVT_TEXT, self.OnText)
         self.value.Bind(wx.EVT_TEXT, self.OnText)
         self.desc.Bind(wx.EVT_TEXT, self.OnText)
         self.btnAdd.Bind(wx.EVT_BUTTON, self.OnAdd)
-        
+
         self._layout()
 
     def _layout(self):
         """Layout dialog"""
         listSizer = wx.StaticBoxSizer(self.listBox, wx.VERTICAL)
-        listSizer.Add(item = self.list, proportion = 1,
-                      flag = wx.EXPAND)
-        
+        listSizer.Add(item=self.list, proportion=1,
+                      flag=wx.EXPAND)
+
         addSizer = wx.StaticBoxSizer(self.addBox, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
-        gridSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
-                                           label = "%s:" % _("Name")),
-                      flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (0, 0))
-        gridSizer.Add(item = self.name,
-                      pos = (0, 1),
-                      flag = wx.EXPAND)
-        gridSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
-                                           label = "%s:" % _("Data type")),
-                      flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (0, 2))
-        gridSizer.Add(item = self.type,
-                      pos = (0, 3))
-        gridSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
-                                           label = "%s:" % _("Default value")),
-                      flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (1, 0))
-        gridSizer.Add(item = self.value,
-                      pos = (1, 1), span = (1, 3),
-                      flag = wx.EXPAND)
-        gridSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
-                                           label = "%s:" % _("Description")),
-                      flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (2, 0))
-        gridSizer.Add(item = self.desc,
-                      pos = (2, 1), span = (1, 3),
-                      flag = wx.EXPAND)
+        gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
+        gridSizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY,
+                                         label="%s:" % _("Name")),
+                      flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(0, 0))
+        gridSizer.Add(item=self.name,
+                      pos=(0, 1),
+                      flag=wx.EXPAND)
+        gridSizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY,
+                                         label="%s:" % _("Data type")),
+                      flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(0, 2))
+        gridSizer.Add(item=self.type,
+                      pos=(0, 3))
+        gridSizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY,
+                                         label="%s:" % _("Default value")),
+                      flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(1, 0))
+        gridSizer.Add(item=self.value,
+                      pos=(1, 1), span=(1, 3),
+                      flag=wx.EXPAND)
+        gridSizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY,
+                                         label="%s:" % _("Description")),
+                      flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(2, 0))
+        gridSizer.Add(item=self.desc,
+                      pos=(2, 1), span=(1, 3),
+                      flag=wx.EXPAND)
         gridSizer.AddGrowableCol(1)
-        addSizer.Add(item = gridSizer,
-                     flag = wx.EXPAND)
-        addSizer.Add(item = self.btnAdd, proportion = 0,
-                     flag = wx.TOP | wx.ALIGN_RIGHT, border = 5)
-        
+        addSizer.Add(item=gridSizer,
+                     flag=wx.EXPAND)
+        addSizer.Add(item=self.btnAdd, proportion=0,
+                     flag=wx.TOP | wx.ALIGN_RIGHT, border=5)
+
         mainSizer = wx.BoxSizer(wx.VERTICAL)
-        mainSizer.Add(item = listSizer, proportion = 1,
-                      flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
-        mainSizer.Add(item = addSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALIGN_CENTER |
-                      wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
-        
+        mainSizer.Add(item=listSizer, proportion=1,
+                      flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
+        mainSizer.Add(item=addSizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALIGN_CENTER |
+                      wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
+
         self.SetSizer(mainSizer)
         mainSizer.Fit(self)
-        
+
     def OnText(self, event):
         """Text entered"""
         if self.name.GetValue():
             self.btnAdd.Enable()
         else:
             self.btnAdd.Enable(False)
-    
+
     def OnAdd(self, event):
         """Add new variable to the list"""
         msg = self.list.Append(self.name.GetValue(),
@@ -1561,89 +1736,99 @@
                                self.desc.GetValue())
         self.name.SetValue('')
         self.name.SetFocus()
-        
+
         if msg:
-            GError(parent = self,
-                   message = msg)
+            GError(parent=self,
+                   message=msg)
         else:
-            self.type.SetSelection(2) # string
+            self.type.SetSelection(2)  # string
             self.value.SetValue('')
             self.desc.SetValue('')
             self.UpdateModelVariables()
-        
+
     def UpdateModelVariables(self):
         """Update model variables"""
         variables = dict()
         for values in self.list.GetData().itervalues():
             name = values[0]
-            variables[name] = { 'type' : str(values[1]) }
+            variables[name] = {'type': str(values[1])}
             if values[2]:
                 variables[name]['value'] = values[2]
             if values[3]:
                 variables[name]['description'] = values[3]
-        
+
         self.parent.GetModel().SetVariables(variables)
         self.parent.ModelChanged()
 
     def Update(self):
         """Reload list of variables"""
         self.list.OnReload(None)
-        
+
     def Reset(self):
         """Remove all variables"""
         self.list.DeleteAllItems()
         self.parent.GetModel().SetVariables([])
-        
+
+
 class ItemPanel(wx.Panel):
-    def __init__(self, parent, id = wx.ID_ANY,
+
+    def __init__(self, parent, id=wx.ID_ANY,
                  **kwargs):
         """Manage model items
         """
         self.parent = parent
-        
-        wx.Panel.__init__(self, parent = parent, id = id, **kwargs)
-        
-        self.listBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                                    label=" %s " % _("List of items - right-click to delete"))
-        
-        self.list = ItemListCtrl(parent = self,
-                                 columns = [_("Label"), _("In loop"), _("Parameterized"),
-                                            _("Command")],
-                                 columnsNotEditable = [1, 2, 3],
-                                 frame = self.parent)
-        
+
+        wx.Panel.__init__(self, parent=parent, id=id, **kwargs)
+
+        self.listBox = wx.StaticBox(
+            parent=self, id=wx.ID_ANY, label=" %s " %
+            _("List of items - right-click to delete"))
+
+        self.list = ItemListCtrl(
+            parent=self,
+            columns=[
+                _("Label"),
+                _("In loop"),
+                _("Parameterized"),
+                _("Command")],
+            columnsNotEditable=[
+                1,
+                2,
+                3],
+            frame=self.parent)
+
         self.btnMoveUp = wx.Button(parent=self, id=wx.ID_UP)
         self.btnMoveDown = wx.Button(parent=self, id=wx.ID_DOWN)
         self.btnRefresh = wx.Button(parent=self, id=wx.ID_REFRESH)
-        
+
         self.btnMoveUp.Bind(wx.EVT_BUTTON, self.OnMoveItemsUp)
         self.btnMoveDown.Bind(wx.EVT_BUTTON, self.OnMoveItemsDown)
         self.btnRefresh.Bind(wx.EVT_BUTTON, self.list.OnReload)
-                
+
         self._layout()
 
     def _layout(self):
         """Layout dialog"""
         listSizer = wx.StaticBoxSizer(self.listBox, wx.VERTICAL)
-        listSizer.Add(item = self.list, proportion = 1,
-                      flag = wx.EXPAND)
-        
+        listSizer.Add(item=self.list, proportion=1,
+                      flag=wx.EXPAND)
+
         manageSizer = wx.BoxSizer(wx.VERTICAL)
-        manageSizer.Add(item=self.btnMoveUp, border = 5, flag = wx.ALL)
-        manageSizer.Add(item=self.btnMoveDown, border = 5,
-                        flag = wx.LEFT | wx.RIGHT | wx.BOTTOM)
-        manageSizer.Add(item=self.btnRefresh, border = 5,
-                        flag = wx.LEFT | wx.RIGHT)
-        
+        manageSizer.Add(item=self.btnMoveUp, border=5, flag=wx.ALL)
+        manageSizer.Add(item=self.btnMoveDown, border=5,
+                        flag=wx.LEFT | wx.RIGHT | wx.BOTTOM)
+        manageSizer.Add(item=self.btnRefresh, border=5,
+                        flag=wx.LEFT | wx.RIGHT)
+
         mainSizer = wx.BoxSizer(wx.HORIZONTAL)
-        mainSizer.Add(item = listSizer, proportion = 1,
-                      flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 3)
-        mainSizer.Add(item = manageSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 3)
+        mainSizer.Add(item=listSizer, proportion=1,
+                      flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=3)
+        mainSizer.Add(item=manageSizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=3)
 
         self.SetSizer(mainSizer)
         mainSizer.Fit(self)
-        
+
     def Update(self):
         """Reload list of variables"""
         self.list.OnReload(None)
@@ -1658,18 +1843,18 @@
                 break
             items.append(next)
             current = next
-        
+
         if not items:
-            GMessage(_("No items to selected."), parent = self)
-            
+            GMessage(_("No items to selected."), parent=self)
+
         return items
-    
+
     def OnMoveItemsUp(self, event):
         """Item moved up, update action ids"""
         items = self._getSelectedItems()
         if not items:
             return
-        self.list.MoveItems(items, up = True)
+        self.list.MoveItems(items, up=True)
         self.parent.GetCanvas().Refresh()
         self.parent.ModelChanged()
 
@@ -1678,59 +1863,61 @@
         items = self._getSelectedItems()
         if not items:
             return
-        self.list.MoveItems(items, up = False)
+        self.list.MoveItems(items, up=False)
         self.parent.GetCanvas().Refresh()
         self.parent.ModelChanged()
-    
+
+
 class PythonPanel(wx.Panel):
-    def __init__(self, parent, id = wx.ID_ANY,
+
+    def __init__(self, parent, id=wx.ID_ANY,
                  **kwargs):
         """Model as python script
         """
         self.parent = parent
-        
-        wx.Panel.__init__(self, parent = parent, id = id, **kwargs)
 
-        self.filename = None # temp file to run
-        
-        self.bodyBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                                    label = " %s " % _("Python script"))
-        self.body = PyStc(parent = self, statusbar = self.parent.GetStatusBar())
+        wx.Panel.__init__(self, parent=parent, id=id, **kwargs)
 
-        self.btnRun = wx.Button(parent = self, id = wx.ID_ANY, label = _("&Run"))
+        self.filename = None  # temp file to run
+
+        self.bodyBox = wx.StaticBox(parent=self, id=wx.ID_ANY,
+                                    label=" %s " % _("Python script"))
+        self.body = PyStc(parent=self, statusbar=self.parent.GetStatusBar())
+
+        self.btnRun = wx.Button(parent=self, id=wx.ID_ANY, label=_("&Run"))
         self.btnRun.SetToolTipString(_("Run python script"))
         self.Bind(wx.EVT_BUTTON, self.OnRun, self.btnRun)
-        self.btnSaveAs = wx.Button(parent = self, id = wx.ID_SAVEAS)
+        self.btnSaveAs = wx.Button(parent=self, id=wx.ID_SAVEAS)
         self.btnSaveAs.SetToolTipString(_("Save python script to file"))
         self.Bind(wx.EVT_BUTTON, self.OnSaveAs, self.btnSaveAs)
-        self.btnRefresh = wx.Button(parent = self, id = wx.ID_REFRESH)
+        self.btnRefresh = wx.Button(parent=self, id=wx.ID_REFRESH)
         self.btnRefresh.SetToolTipString(_("Refresh python script based on the model.\n"
                                            "It will discards all local changes."))
         self.Bind(wx.EVT_BUTTON, self.OnRefresh, self.btnRefresh)
-        
+
         self._layout()
-        
+
     def _layout(self):
         sizer = wx.BoxSizer(wx.VERTICAL)
         bodySizer = wx.StaticBoxSizer(self.bodyBox, wx.HORIZONTAL)
         btnSizer = wx.BoxSizer(wx.HORIZONTAL)
-        
-        bodySizer.Add(item = self.body, proportion = 1,
-                      flag = wx.EXPAND | wx.ALL, border = 3)
-        
-        btnSizer.Add(item = self.btnRefresh, proportion = 0,
-                     flag = wx.LEFT | wx.RIGHT, border = 5)
+
+        bodySizer.Add(item=self.body, proportion=1,
+                      flag=wx.EXPAND | wx.ALL, border=3)
+
+        btnSizer.Add(item=self.btnRefresh, proportion=0,
+                     flag=wx.LEFT | wx.RIGHT, border=5)
         btnSizer.AddStretchSpacer()
-        btnSizer.Add(item = self.btnSaveAs, proportion = 0,
-                     flag = wx.RIGHT | wx.ALIGN_RIGHT, border = 5)
-        btnSizer.Add(item = self.btnRun, proportion = 0,
-                     flag = wx.RIGHT | wx.ALIGN_RIGHT, border = 5)
-        
-        sizer.Add(item = bodySizer, proportion = 1,
-                  flag = wx.EXPAND | wx.ALL, border = 3)
-        sizer.Add(item = btnSizer, proportion = 0,
-                  flag = wx.EXPAND | wx.ALL, border = 3)
-        
+        btnSizer.Add(item=self.btnSaveAs, proportion=0,
+                     flag=wx.RIGHT | wx.ALIGN_RIGHT, border=5)
+        btnSizer.Add(item=self.btnRun, proportion=0,
+                     flag=wx.RIGHT | wx.ALIGN_RIGHT, border=5)
+
+        sizer.Add(item=bodySizer, proportion=1,
+                  flag=wx.EXPAND | wx.ALL, border=3)
+        sizer.Add(item=btnSizer, proportion=0,
+                  flag=wx.EXPAND | wx.ALL, border=3)
+
         sizer.Fit(self)
         sizer.SetSizeHints(self)
         self.SetSizer(sizer)
@@ -1743,56 +1930,65 @@
             fd.write(self.body.GetText())
         except IOError as e:
             GError(_("Unable to launch Python script. %s") % e,
-                   parent = self)
+                   parent=self)
             return
         finally:
             fd.close()
             mode = stat.S_IMODE(os.lstat(self.filename)[stat.ST_MODE])
             os.chmod(self.filename, mode | stat.S_IXUSR)
-        
-        self.parent._gconsole.RunCmd([fd.name], skipInterface=True, onDone=self.OnDone)
-        
+
+        self.parent._gconsole.RunCmd(
+            [fd.name],
+            skipInterface=True, onDone=self.OnDone)
+
         event.Skip()
 
     def OnDone(self, event):
         """Python script finished"""
         try_remove(self.filename)
         self.filename = None
-        
-    def SaveAs(self, force = False):
+
+    def SaveAs(self, force=False):
         """Save python script to file
 
         :return: filename
         """
         filename = ''
-        dlg = wx.FileDialog(parent = self,
-                            message = _("Choose file to save"),
-                            defaultFile = os.path.basename(self.parent.GetModelFile(ext=False)),
-                            defaultDir = os.getcwd(),
-                            wildcard = _("Python script (*.py)|*.py"),
-                            style = wx.FD_SAVE)
-        
+        dlg = wx.FileDialog(
+            parent=self,
+            message=_("Choose file to save"),
+            defaultFile=os.path.basename(
+                self.parent.GetModelFile(
+                    ext=False)),
+            defaultDir=os.getcwd(),
+            wildcard=_("Python script (*.py)|*.py"),
+            style=wx.FD_SAVE)
+
         if dlg.ShowModal() == wx.ID_OK:
             filename = dlg.GetPath()
-        
+
         if not filename:
             return ''
-        
+
         # check for extension
         if filename[-3:] != ".py":
             filename += ".py"
-        
+
         if os.path.exists(filename):
-            dlg = wx.MessageDialog(self, message=_("File <%s> already exists. "
-                                                   "Do you want to overwrite this file?") % filename,
-                                   caption=_("Save file"),
-                                   style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+            dlg = wx.MessageDialog(
+                self,
+                message=_(
+                    "File <%s> already exists. "
+                    "Do you want to overwrite this file?") %
+                filename,
+                caption=_("Save file"),
+                style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
             if dlg.ShowModal() == wx.ID_NO:
                 dlg.Destroy()
                 return ''
-            
+
             dlg.Destroy()
-        
+
         fd = open(filename, "w")
         try:
             if force:
@@ -1801,17 +1997,17 @@
                 fd.write(self.body.GetText())
         finally:
             fd.close()
-        
+
         # executable file
         os.chmod(filename, stat.S_IRWXU | stat.S_IWUSR)
-        
+
         return filename
-    
+
     def OnSaveAs(self, event):
         """Save python script to file"""
-        self.SaveAs(force = False)
+        self.SaveAs(force=False)
         event.Skip()
-        
+
     def RefreshScript(self):
         """Refresh Python script
 
@@ -1819,38 +2015,39 @@
         :return: False script hasn't been updated
         """
         if self.body.modified:
-            dlg = wx.MessageDialog(self,
-                                   message = _("Python script is locally modificated. "
-                                               "Refresh will discard all changes. "
-                                               "Do you really want to continue?"),
-                                   caption=_("Update"),
-                                   style = wx.YES_NO | wx.NO_DEFAULT |
-                                   wx.ICON_QUESTION | wx.CENTRE)
+            dlg = wx.MessageDialog(
+                self,
+                message=_(
+                    "Python script is locally modificated. "
+                    "Refresh will discard all changes. "
+                    "Do you really want to continue?"),
+                caption=_("Update"),
+                style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
             ret = dlg.ShowModal()
             dlg.Destroy()
             if ret == wx.ID_NO:
                 return False
-        
+
         fd = tempfile.TemporaryFile()
         WritePythonFile(fd, self.parent.GetModel())
         fd.seek(0)
         self.body.SetText(fd.read())
         fd.close()
-        
+
         self.body.modified = False
-        
+
         return True
-    
+
     def OnRefresh(self, event):
         """Refresh Python script"""
         if self.RefreshScript():
             self.parent.SetStatusText(_('Python script is up-to-date'), 0)
         event.Skip()
-        
+
     def IsModified(self):
         """Check if python script has been modified"""
         return self.body.modified
-    
+
     def IsEmpty(self):
         """Check if python script is empty"""
         return len(self.body.GetText()) == 0

Modified: grass/trunk/gui/wxpython/gmodeler/g.gui.gmodeler.py
===================================================================
--- grass/trunk/gui/wxpython/gmodeler/g.gui.gmodeler.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gmodeler/g.gui.gmodeler.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -36,14 +36,15 @@
 
 import grass.script as gscript
 
+
 def main():
     options, flags = gscript.parser()
 
     import wx
-    
+
     from grass.script.setup import set_gui_path
     set_gui_path()
-    
+
     from core.giface import StandaloneGrassInterface
     from core.globalvar import CheckWxVersion
     from gmodeler.frame import ModelFrame

Modified: grass/trunk/gui/wxpython/gmodeler/giface.py
===================================================================
--- grass/trunk/gui/wxpython/gmodeler/giface.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gmodeler/giface.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -16,17 +16,19 @@
 
 from grass.pydispatch.signal import Signal
 
+
 class GraphicalModelerGrassInterface():
     """@implements core::giface::GrassInterface"""
+
     def __init__(self, model):
         self._model = model
-    
+
         # Signal emitted to request updating of map (TODO)
         self.updateMap = Signal('GraphicalModelerGrassInterface.updateMap')
-        
+
     def GetLayerTree(self):
         return None
-    
+
     def GetLayerList(self, prompt):
         return self._model.GetMaps(prompt)
 

Modified: grass/trunk/gui/wxpython/gmodeler/menudata.py
===================================================================
--- grass/trunk/gui/wxpython/gmodeler/menudata.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gmodeler/menudata.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -17,12 +17,14 @@
 import os
 
 from core import globalvar
-from core.menutree  import MenuTreeModelBuilder
+from core.menutree import MenuTreeModelBuilder
 
+
 class ModelerMenuData(MenuTreeModelBuilder):
-    def __init__(self, filename = None):
+
+    def __init__(self, filename=None):
         if not filename:
-            filename = os.path.join(globalvar.WXGUIDIR, 'xml', 'menudata_modeler.xml')
-        
+            filename = os.path.join(
+                globalvar.WXGUIDIR, 'xml', 'menudata_modeler.xml')
+
         MenuTreeModelBuilder.__init__(self, filename)
-

Modified: grass/trunk/gui/wxpython/gmodeler/model.py
===================================================================
--- grass/trunk/gui/wxpython/gmodeler/model.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gmodeler/model.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -35,64 +35,67 @@
 try:
     import xml.etree.ElementTree as etree
 except ImportError:
-    import elementtree.ElementTree as etree # Python <= 2.4
+    import elementtree.ElementTree as etree  # Python <= 2.4
 
 import xml.sax.saxutils as saxutils
 
 import wx
 from wx.lib import ogl
 
-from core                import globalvar
-from core                import utils
+from core import globalvar
+from core import utils
 from core.utils import _
-from core.gcmd           import GMessage, GException, GError, RunCommand, EncodeString, GWarning, GetDefaultEncoding
-from core.settings       import UserSettings
-from gui_core.forms      import GUI, CmdPanel
-from gui_core.widgets    import GNotebook
+from core.gcmd import GMessage, GException, GError, RunCommand, EncodeString, GWarning, GetDefaultEncoding
+from core.settings import UserSettings
+from gui_core.forms import GUI, CmdPanel
+from gui_core.widgets import GNotebook
 from gmodeler.giface import GraphicalModelerGrassInterface
 
 from grass.script import core as grass
 from grass.script import task as gtask
 
+
 class Model(object):
     """Class representing the model"""
-    def __init__(self, canvas = None):
-        self.items   = list() # list of ordered items (action/loop/condition)
-        
+
+    def __init__(self, canvas=None):
+        self.items = list()  # list of ordered items (action/loop/condition)
+
         # model properties
-        self.properties = { 'name'        : _("model"),
-                            'description' : _("Script generated by wxGUI Graphical Modeler."),
-                            'author'      : getpass.getuser() }
+        self.properties = {
+            'name': _("model"),
+            'description': _("Script generated by wxGUI Graphical Modeler."),
+            'author': getpass.getuser()}
         # model variables
         self.variables = dict()
         self.variablesParams = dict()
-        
-        self.canvas  = canvas
-        
+
+        self.canvas = canvas
+
     def GetCanvas(self):
         """Get canvas or None"""
         return self.canvas
 
-    def GetItems(self, objType = None):
+    def GetItems(self, objType=None):
         """Get list of model items
 
         :param objType: Object type to filter model objects
         """
         if not objType:
             return self.items
-        
+
         result = list()
         for item in self.items:
             if isinstance(item, objType):
                 result.append(item)
-        
+
         return result
-    
+
     def GetItem(self, aId, objType=None):
         """Get item of given id
 
         :param aId: item id
-        
+
         :return: Model* instance
         :return: None if no item found
         """
@@ -106,12 +109,12 @@
     def GetItemIndex(self, item):
         """Return list index of given item"""
         return self.items.index(item)
-    
-    def GetNumItems(self, actionOnly = False):
+
+    def GetNumItems(self, actionOnly=False):
         """Get number of items"""
         if actionOnly:
-            return len(self.GetItems(objType = ModelAction))
-        
+            return len(self.GetItems(objType=ModelAction))
+
         return len(self.GetItems())
 
     def ReorderItems(self, idxList):
@@ -140,25 +143,25 @@
                     self.canvas.parent.DefineLoop(mo)
                 elif isinstance(mo, ModelCondition):
                     self.canvas.parent.DefineCondition(mo)
-            
+
     def Normalize(self):
         # check for inconsistecies
         for idx in range(1, len(self.items)):
             if not self.items[idx].GetBlock() and \
-                    isinstance(self.items[idx-1], ModelLoop):
+                    isinstance(self.items[idx - 1], ModelLoop):
                 # swap action not-in-block with previously defined
                 # loop
-                itemPrev = self.items[idx-1]
-                self.items[idx-1] = self.items[idx]
+                itemPrev = self.items[idx - 1]
+                self.items[idx - 1] = self.items[idx]
                 self.items[idx] = itemPrev
-        
+
         # update ids
         iId = 1
         for item in self.items:
             item.SetId(iId)
             item.SetLabel()
             iId += 1
-        
+
     def GetNextId(self):
         """Get next id (data ignored)
 
@@ -166,35 +169,35 @@
         """
         if len(self.items) < 1:
             return 1
-        
+
         currId = self.items[-1].GetId()
         if currId > 0:
             return currId + 1
-        
+
         return 1
 
     def GetProperties(self):
         """Get model properties"""
         return self.properties
 
-    def GetVariables(self, params = False):
+    def GetVariables(self, params=False):
         """Get model variables"""
         if params:
             return self.variablesParams
-        
+
         return self.variables
-    
+
     def SetVariables(self, data):
         """Set model variables"""
         self.variables = data
-    
+
     def Reset(self):
         """Reset model"""
         self.items = list()
 
     def RemoveItem(self, item, reference=None):
         """Remove item from model
-        
+
         :item: item to be removed
         :reference: reference item valid for deletion
 
@@ -212,13 +215,13 @@
                     relList.append(data)
                 else:
                     upList.append(data)
-            
+
         elif isinstance(item, ModelData):
             for rel in item.GetRelations():
                 otherItem = rel.GetTo() if rel.GetFrom() == item else rel.GetFrom()
                 if reference and reference != otherItem:
                     doRemove = False
-                    continue # avoid recursive deletion
+                    continue  # avoid recursive deletion
                 relList.append(rel)
                 if reference and reference != otherItem:
                     relList.append(otherItem)
@@ -233,16 +236,16 @@
 
         if doRemove and item in self.items:
             self.items.remove(item)
-        
+
         return relList, upList
-    
+
     def FindAction(self, aId):
         """Find action by id"""
-        alist = self.GetItems(objType = ModelAction)
+        alist = self.GetItems(objType=ModelAction)
         for action in alist:
             if action.GetId() == aId:
                 return action
-        
+
         return None
 
     def GetMaps(self, prompt):
@@ -254,28 +257,28 @@
             if prompt == data.GetPrompt():
                 mapName = data.GetValue()
                 if not mapName or mapName[0] is '%':
-                    continue # skip variables
+                    continue  # skip variables
                 maps.append(mapName)
-        
+
         return maps
 
     def GetData(self):
         """Get list of data items"""
         result = list()
-        dataItems = self.GetItems(objType = ModelData)
-        
-        for action in self.GetItems(objType = ModelAction):
+        dataItems = self.GetItems(objType=ModelData)
+
+        for action in self.GetItems(objType=ModelAction):
             for rel in action.GetRelations():
                 dataItem = rel.GetData()
                 if dataItem not in result:
                     result.append(dataItem)
                 if dataItem in dataItems:
                     dataItems.remove(dataItem)
-        
+
         # standalone data
         if dataItems:
             result += dataItems
-        
+
         return result
 
     def FindData(self, value, prompt):
@@ -291,104 +294,110 @@
             if data.GetValue() == value and \
                     data.GetPrompt() == prompt:
                 return data
-        
+
         return None
-                
+
     def LoadModel(self, filename):
         """Load model definition stored in GRASS Model XML file (gxm)
-        
+
         .. todo::
              Validate against DTD
-        
+
         Raise exception on error.
         """
         dtdFilename = os.path.join(globalvar.WXGUIDIR, "xml", "grass-gxm.dtd")
-        
+
         # parse workspace file
         try:
             gxmXml = ProcessModelFile(etree.parse(filename))
-        except StandardError as e:
+        except Exception as e:
             raise GException(unicode(e))
-        
+
         if self.canvas:
             win = self.canvas.parent
             if gxmXml.pos:
                 win.SetPosition(gxmXml.pos)
             if gxmXml.size:
                 win.SetSize(gxmXml.size)
-        
+
         # load properties
         self.properties = gxmXml.properties
-        self.variables  = gxmXml.variables
-        
+        self.variables = gxmXml.variables
+
         # load actions
         for action in gxmXml.actions:
-            actionItem = ModelAction(parent = self, 
-                                     x = action['pos'][0],
-                                     y = action['pos'][1],
-                                     width = action['size'][0],
-                                     height = action['size'][1],
-                                     task = action['task'],
-                                     id = action['id'],
-                                     label = action['label'],
-                                     comment = action['comment'])
-            
+            actionItem = ModelAction(parent=self,
+                                     x=action['pos'][0],
+                                     y=action['pos'][1],
+                                     width=action['size'][0],
+                                     height=action['size'][1],
+                                     task=action['task'],
+                                     id=action['id'],
+                                     label=action['label'],
+                                     comment=action['comment'])
+
             if action['disabled']:
                 actionItem.Enable(False)
-            
-            self.AddItem(actionItem, pos = actionItem.GetId()-1)
-            
+
+            self.AddItem(actionItem, pos=actionItem.GetId() - 1)
+
             actionItem.SetValid(actionItem.GetTask().get_options())
-            actionItem.GetLog() # substitute variables (-> valid/invalid)
+            actionItem.GetLog()  # substitute variables (-> valid/invalid)
 
         # load data & relations
         for data in gxmXml.data:
-            dataItem = ModelData(parent = self, 
-                                 x = data['pos'][0],
-                                 y = data['pos'][1],
-                                 width = data['size'][0],
-                                 height = data['size'][1],
-                                 prompt = data['prompt'],
-                                 value = data['value'])
+            dataItem = ModelData(parent=self,
+                                 x=data['pos'][0],
+                                 y=data['pos'][1],
+                                 width=data['size'][0],
+                                 height=data['size'][1],
+                                 prompt=data['prompt'],
+                                 value=data['value'])
             dataItem.SetIntermediate(data['intermediate'])
-            
+
             for rel in data['rels']:
                 actionItem = self.FindAction(rel['id'])
-                
+
                 if rel['dir'] == 'from':
-                    relation = ModelRelation(parent = self, fromShape = dataItem,
-                                             toShape = actionItem, param = rel['name'])
+                    relation = ModelRelation(
+                        parent=self,
+                        fromShape=dataItem,
+                        toShape=actionItem,
+                        param=rel['name'])
                 else:
-                    relation = ModelRelation(parent = self, fromShape = actionItem,
-                                             toShape = dataItem, param = rel['name'])
+                    relation = ModelRelation(
+                        parent=self,
+                        fromShape=actionItem,
+                        toShape=dataItem,
+                        param=rel['name'])
                 relation.SetControlPoints(rel['points'])
                 actionItem.AddRelation(relation)
                 dataItem.AddRelation(relation)
 
             if self.canvas:
                 dataItem.Update()
-           
+
         # load loops
         for loop in gxmXml.loops:
-            loopItem = ModelLoop(parent = self, 
-                                 x = loop['pos'][0],
-                                 y = loop['pos'][1],
-                                 width = loop['size'][0],
-                                 height = loop['size'][1],
-                                 label = loop['text'],
-                                 id = loop['id'])
-            self.AddItem(loopItem, pos = loopItem.GetId()-1)
-        
+            loopItem = ModelLoop(parent=self,
+                                 x=loop['pos'][0],
+                                 y=loop['pos'][1],
+                                 width=loop['size'][0],
+                                 height=loop['size'][1],
+                                 label=loop['text'],
+                                 id=loop['id'])
+            self.AddItem(loopItem, pos=loopItem.GetId() - 1)
+
         # load conditions
         for condition in gxmXml.conditions:
-            conditionItem = ModelCondition(parent = self, 
-                                           x = condition['pos'][0],
-                                           y = condition['pos'][1],
-                                           width = condition['size'][0],
-                                           height = condition['size'][1],
-                                           label = condition['text'],
-                                           id = condition['id'])
-            self.AddItem(conditionItem, pos = conditionItem.GetId()-1)
+            conditionItem = ModelCondition(parent=self,
+                                           x=condition['pos'][0],
+                                           y=condition['pos'][1],
+                                           width=condition['size'][0],
+                                           height=condition['size'][1],
+                                           label=condition['text'],
+                                           id=condition['id'])
+            self.AddItem(conditionItem, pos=conditionItem.GetId() - 1)
 
         # define loops & if/else items
         for loop in gxmXml.loops:
@@ -397,7 +406,7 @@
             for idx in loop['items']:
                 action = self.GetItem(idx, objType=ModelAction)
                 action.SetBlock(loopItem)
-        
+
         for condition in gxmXml.conditions:
             conditionItem = self.GetItem(condition['id'])
             for b in condition['items'].keys():
@@ -405,8 +414,8 @@
                 for aId in condition['items'][b]:
                     action = self.GetItem(aId)
                     alist.append(action)
-                conditionItem.SetItems(alist, branch = b)
-            
+                conditionItem.SetItems(alist, branch=b)
+
             items = conditionItem.GetItems()
             for b in items.keys():
                 for action in items[b]:
@@ -414,17 +423,17 @@
 
         # load comments
         for comment in gxmXml.comments:
-            commentItem = ModelComment(parent = self, 
-                                       x = comment['pos'][0],
-                                       y = comment['pos'][1],
-                                       width = comment['size'][0],
-                                       height = comment['size'][1],
-                                       id = comment['id'],
-                                       label = comment['text'])
-            
-            self.AddItem(commentItem, pos = commentItem.GetId()-1)
-        
-    def AddItem(self, newItem, pos = -1):
+            commentItem = ModelComment(parent=self,
+                                       x=comment['pos'][0],
+                                       y=comment['pos'][1],
+                                       width=comment['size'][0],
+                                       height=comment['size'][1],
+                                       id=comment['id'],
+                                       label=comment['text'])
+
+            self.AddItem(commentItem, pos=commentItem.GetId() - 1)
+
+    def AddItem(self, newItem, pos=-1):
         """Add item to the list"""
         if pos != -1:
             self.items.insert(pos, newItem)
@@ -434,14 +443,14 @@
         # for item in self.items:
         #     item.SetId(i)
         #     i += 1
-        
+
     def IsValid(self):
         """Return True if model is valid"""
         if self.Validate():
             return False
-        
+
         return True
-    
+
     def Validate(self):
         """Validate model, return None if model is valid otherwise
         error string"""
@@ -449,12 +458,12 @@
 
         variables = self.GetVariables().keys()
         pattern = re.compile(r'(.*)(%.+\s?)(.*)')
-        for action in self.GetItems(objType = ModelAction):
-            cmd = action.GetLog(string = False)
-            
-            task = GUI(show = None).ParseCommand(cmd = cmd)
+        for action in self.GetItems(objType=ModelAction):
+            cmd = action.GetLog(string=False)
+
+            task = GUI(show=None).ParseCommand(cmd=cmd)
             errList += map(lambda x: cmd[0] + ': ' + x, task.get_cmd_error())
-            
+
             # check also variables
             for opt in cmd[1:]:
                 if '=' not in opt:
@@ -462,7 +471,7 @@
                 key, value = opt.split('=', 1)
                 sval = pattern.search(value)
                 if sval:
-                    var = sval.group(2).strip()[1:] # strip '%' from beginning
+                    var = sval.group(2).strip()[1:]  # strip '%' from beginning
                     found = False
                     for v in variables:
                         if var.startswith(v):
@@ -470,28 +479,34 @@
                             break
                     if not found:
                         report = True
-                        for item in filter(lambda x: isinstance(x, ModelLoop), action.GetBlock()):
+                        for item in filter(
+                                lambda x: isinstance(x, ModelLoop),
+                                action.GetBlock()):
                             if var in item.GetLabel():
                                 report = False
                                 break
                         if report:
-                            errList.append(cmd[0] + ": " + _("undefined variable '%s'") % var)
-            ### TODO: check variables in file only optionally
+                            errList.append(
+                                cmd[0] +
+                                ": " +
+                                _("undefined variable '%s'") %
+                                var)
+            # TODO: check variables in file only optionally
             ### errList += self._substituteFile(action, checkOnly = True)
-        
+
         return errList
 
-    def _substituteFile(self, item, params = None, checkOnly = False):
+    def _substituteFile(self, item, params=None, checkOnly=False):
         """Subsitute variables in command file inputs
 
         :param bool checkOnly: tuble - True to check variable, don't touch files
-        
+
         :return: list of undefined variables
         """
         errList = list()
-        
+
         self.fileInput = dict()
-        
+
         # collect ascii inputs
         for p in item.GetParams()['params']:
             if p.get('element', '') == 'file' and \
@@ -501,7 +516,7 @@
                 if filename and \
                         mimetypes.guess_type(filename)[0] == 'text/plain':
                     self.fileInput[filename] = None
-        
+
         for finput in self.fileInput:
             # read lines
             fd = open(finput, "r")
@@ -509,7 +524,7 @@
                 data = self.fileInput[finput] = fd.read()
             finally:
                 fd.close()
-            
+
             # substitute variables
             write = False
             variables = self.GetVariables()
@@ -524,21 +539,21 @@
                             else:
                                 value = str(p.get('value', ''))
                             break
-                
+
                 if not value:
                     value = variables[variable].get('value', '')
-                
+
                 data = pattern.sub(value, data)
                 if not checkOnly:
                     write = True
-            
+
             pattern = re.compile(r'(.*)(%.+\s?)(.*)')
             sval = pattern.search(data)
             if sval:
-                var = sval.group(2).strip()[1:] # ignore '%'
-                cmd = item.GetLog(string = False)[0]
+                var = sval.group(2).strip()[1:]  # ignore '%'
+                cmd = item.GetLog(string=False)[0]
                 errList.append(cmd + ": " + _("undefined variable '%s'") % var)
-            
+
             if not checkOnly:
                 if write:
                     fd = open(finput, "w")
@@ -548,13 +563,14 @@
                         fd.close()
                 else:
                     self.fileInput[finput] = None
-        
+
         return errList
-    
+
     def OnPrepare(self, item, params):
-        self._substituteFile(item, params, checkOnly = False)
+        self._substituteFile(item, params, checkOnly=False)
 
-    def RunAction(self, item, params, log, onDone, onPrepare = None, statusbar = None):
+    def RunAction(self, item, params, log, onDone,
+                  onPrepare=None, statusbar=None):
         """Run given action
 
         :param item: action item
@@ -566,21 +582,21 @@
         """
         name = '({0}) {1}'.format(item.GetId(), item.GetLabel())
         if name in params:
-            paramsOrig = item.GetParams(dcopy = True)
+            paramsOrig = item.GetParams(dcopy=True)
             item.MergeParams(params[name])
-        
+
         if statusbar:
             statusbar.SetStatusText(_('Running model...'), 0)
-            
-        data = { 'item' : item,
-                 'params' : copy.deepcopy(params) }
-        log.RunCmd(command = item.GetLog(string = False, substitute = params),
-                   onDone = onDone, onPrepare = self.OnPrepare, userData = data)
-        
+
+        data = {'item': item,
+                'params': copy.deepcopy(params)}
+        log.RunCmd(command=item.GetLog(string=False, substitute=params),
+                   onDone=onDone, onPrepare=self.OnPrepare, userData=data)
+
         if name in params:
             item.SetParams(paramsOrig)
 
-    def Run(self, log, onDone, parent = None):
+    def Run(self, log, onDone, parent=None):
         """Run model
 
         :param log: logging window (see gconsole.GConsole)
@@ -588,14 +604,14 @@
         :param parent: window for messages or None
         """
         if self.GetNumItems() < 1:
-            GMessage(parent = parent,
-                     message = _('Model is empty. Nothing to run.'))
+            GMessage(parent=parent,
+                     message=_('Model is empty. Nothing to run.'))
             return
-        
+
         statusbar = None
         if isinstance(parent, wx.Frame):
             statusbar = parent.GetStatusBar()
-        
+
         # validation
         if statusbar:
             statusbar.SetStatusText(_('Validating model...'), 0)
@@ -603,49 +619,63 @@
         if statusbar:
             statusbar.SetStatusText('', 0)
         if errList:
-            dlg = wx.MessageDialog(parent = parent,
-                                   message = _('Model is not valid. Do you want to '
-                                               'run the model anyway?\n\n%s') % '\n'.join(errList),
-                                   caption = _("Run model?"),
-                                   style = wx.YES_NO | wx.NO_DEFAULT |
-                                   wx.ICON_QUESTION | wx.CENTRE)
+            dlg = wx.MessageDialog(
+                parent=parent,
+                message=_(
+                    'Model is not valid. Do you want to '
+                    'run the model anyway?\n\n%s') %
+                '\n'.join(errList),
+                caption=_("Run model?"),
+                style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
             ret = dlg.ShowModal()
             dlg.Destroy()
             if ret != wx.ID_YES:
                 return
-        
+
         # parametrization
         params = self.Parameterize()
         delInterData = False
         if params:
-            dlg = ModelParamDialog(parent = parent,
-                                   model = self,
-                                   params = params)
+            dlg = ModelParamDialog(parent=parent,
+                                   model=self,
+                                   params=params)
             dlg.CenterOnParent()
-            
+
             ret = dlg.ShowModal()
             if ret != wx.ID_OK:
                 dlg.Destroy()
                 return
-            
+
             err = dlg.GetErrors()
             delInterData = dlg.DeleteIntermediateData()
             dlg.Destroy()
             if err:
-                GError(parent = parent, message = unicode('\n'.join(err)))
+                GError(parent=parent, message=unicode('\n'.join(err)))
                 return
-            
+
             err = list()
             for key, item in params.iteritems():
                 for p in item['params']:
                     if p.get('value', '') == '':
-                        err.append((key, p.get('name', ''), p.get('description', '')))
+                        err.append(
+                            (key, p.get(
+                                'name', ''), p.get(
+                                'description', '')))
             if err:
-                GError(parent = parent,
-                       message = _("Variables below not defined:") + \
-                           "\n\n" + unicode('\n'.join(map(lambda x: "%s: %s (%s)" % (x[0], x[1], x[2]), err))))
+                GError(
+                    parent=parent,
+                    message=_("Variables below not defined:") +
+                    "\n\n" +
+                    unicode(
+                        '\n'.join(
+                            map(
+                                lambda x: "%s: %s (%s)" %
+                                (x[0],
+                                 x[1],
+                                    x[2]),
+                                err))))
                 return
-        
+
         log.cmdThread.SetId(-1)
         for item in self.GetItems():
             if not item.IsEnabled():
@@ -656,7 +686,7 @@
                 self.RunAction(item, params, log, onDone)
             elif isinstance(item, ModelLoop):
                 cond = item.GetLabel()
-                
+
                 # substitute variables in condition
                 variables = self.GetVariables()
                 for variable in variables:
@@ -668,71 +698,77 @@
                                 if variable == p.get('name', ''):
                                     value = p.get('value', '')
                                     break
-                        
+
                         if not value:
                             value = variables[variable].get('value', '')
-                        
+
                         if not value:
                             continue
-                        
+
                         vtype = variables[variable].get('type', 'string')
                         if vtype == 'string':
                             value = '"' + value + '"'
                         cond = pattern.sub(value, cond)
-                
+
                 # split condition
-                ### TODO: this part needs some better solution
-                condVar, condText = map(lambda x: x.strip(), re.split('\s* in \s*', cond))
+                # TODO: this part needs some better solution
+                condVar, condText = map(
+                    lambda x: x.strip(),
+                    re.split('\s* in \s*', cond))
                 pattern = re.compile('%' + condVar)
-                ### for vars()[condVar] in eval(condText): ?
+                # for vars()[condVar] in eval(condText): ?
                 vlist = list()
                 if condText[0] == '`' and condText[-1] == '`':
                     # run command
-                    cmd, dcmd = gtask.cmdlist_to_tuple(condText[1:-1].split(' '))
+                    cmd, dcmd = gtask.cmdlist_to_tuple(
+                        condText[1: -1].split(' '))
                     ret = RunCommand(cmd,
-                                     read = True,
+                                     read=True,
                                      **dcmd)
                     if ret:
                         vlist = ret.splitlines()
                 else:
                     vlist = eval(condText)
-                
+
                 if 'variables' not in params:
-                    params['variables'] = { 'params' : [] }
-                varDict = { 'name' : condVar, 'value' : '' }
+                    params['variables'] = {'params': []}
+                varDict = {'name': condVar, 'value': ''}
                 params['variables']['params'].append(varDict)
-                                
+
                 for var in vlist:
                     for action in item.GetItems(self.GetItems()):
                         if not action.IsEnabled():
                             continue
-                        
+
                         varDict['value'] = var
-                                                
-                        self.RunAction(item = action, params = params,
-                                       log = log, onDone = onDone)
+
+                        self.RunAction(item=action, params=params,
+                                       log=log, onDone=onDone)
                 params['variables']['params'].remove(varDict)
-        
+
         if delInterData:
             self.DeleteIntermediateData(log)
-        
+
         # discard values
         if params:
             for item in params.itervalues():
                 for p in item['params']:
                     p['value'] = ''
-        
+
     def DeleteIntermediateData(self, log):
         """Detele intermediate data"""
         rast, vect, rast3d, msg = self.GetIntermediateData()
-        
+
         if rast:
-            log.RunCmd(['g.remove', '-f', 'type=raster', 'name=%s' %','.join(rast)])
+            log.RunCmd(['g.remove', '-f', 'type=raster',
+                        'name=%s' % ','.join(rast)])
         if rast3d:
-            log.RunCmd(['g.remove', '-f', 'type=raster_3d', 'name=%s' %','.join(rast3d)])
+            log.RunCmd(['g.remove', '-f', 'type=raster_3d',
+                        'name=%s' % ','.join(rast3d)])
         if vect:
-            log.RunCmd(['g.remove', '-f', 'type=vector', 'name=%s' %','.join(vect)])
-        
+            log.RunCmd(['g.remove', '-f', 'type=vector',
+                        'name=%s' % ','.join(vect)])
+
     def GetIntermediateData(self):
         """Get info about intermediate data"""
         rast = list()
@@ -749,7 +785,7 @@
                 vect.append(name)
             elif prompt == 'raster_3d':
                 rast3d.append(name)
-        
+
         msg = ''
         if rast:
             msg += '\n\n%s: ' % _('Raster maps')
@@ -760,33 +796,34 @@
         if vect:
             msg += '\n\n%s: ' % _('Vector maps')
             msg += ', '.join(vect)
-        
+
         return rast, vect, rast3d, msg
 
     def Update(self):
         """Update model"""
         for item in self.items:
             item.Update()
-        
+
     def IsParameterized(self):
         """Return True if model is parameterized"""
         if self.Parameterize():
             return True
-        
+
         return False
-    
+
     def Parameterize(self):
         """Return parameterized options"""
         result = dict()
         idx = 0
         if self.variables:
             params = list()
-            result["variables"] = { 'flags'  : list(),
-                                    'params' : params,
-                                    'idx'    : idx }
+            result["variables"] = {'flags': list(),
+                                   'params': params,
+                                   'idx': idx}
             for name, values in self.variables.iteritems():
                 gtype = values.get('type', 'string')
-                if gtype in ('raster', 'vector', 'mapset', 'file', 'region', 'dir'):
+                if gtype in ('raster', 'vector', 'mapset',
+                             'file', 'region', 'dir'):
                     gisprompt = True
                     prompt = gtype
                     if gtype == 'raster':
@@ -799,65 +836,67 @@
                     prompt = None
                     element = None
                     ptype = gtype
-                params.append({ 'gisprompt' : gisprompt,
-                                'multiple'  : False,
-                                'description' : values.get('description', ''),
-                                'guidependency' : '',
-                                'default' : '',
-                                'age' : None,
-                                'required' : True,
-                                'value' : values.get('value', ''),
-                                'label' : '',
-                                'guisection' : '',
-                                'key_desc' : '',
-                                'values' : list(),
-                                'parameterized' : False,
-                                'values_desc' : list(),
-                                'prompt' : prompt,
-                                'element' : element,
-                                'type' : ptype,
-                                'name' : name })
-            
+                params.append({'gisprompt': gisprompt,
+                               'multiple': False,
+                               'description': values.get('description', ''),
+                               'guidependency': '',
+                               'default': '',
+                               'age': None,
+                               'required': True,
+                               'value': values.get('value', ''),
+                               'label': '',
+                               'guisection': '',
+                               'key_desc': '',
+                               'values': list(),
+                               'parameterized': False,
+                               'values_desc': list(),
+                               'prompt': prompt,
+                               'element': element,
+                               'type': ptype,
+                               'name': name})
+
             idx += 1
-        
-        for action in self.GetItems(objType = ModelAction):
+
+        for action in self.GetItems(objType=ModelAction):
             if not action.IsEnabled():
                 continue
-            name   = '({0}) {1}'.format(action.GetId(), action.GetLabel())
+            name = '({0}) {1}'.format(action.GetId(), action.GetLabel())
             params = action.GetParams()
             increment = False
             for f in params['flags']:
                 if f.get('parameterized', False):
                     if name not in result:
                         increment = True
-                        result[name] = { 'flags' : list(),
-                                         'params': list(),
-                                         'idx'   : idx }
+                        result[name] = {'flags': list(),
+                                        'params': list(),
+                                        'idx': idx}
                     result[name]['flags'].append(f)
             for p in params['params']:
                 if p.get('parameterized', False):
                     if name not in result:
                         increment = True
-                        result[name] = { 'flags' : list(),
-                                         'params': list(),
-                                         'idx'   : idx }
+                        result[name] = {'flags': list(),
+                                        'params': list(),
+                                        'idx': idx}
                     result[name]['params'].append(p)
             if increment:
                 idx += 1
-        
-        self.variablesParams = result # record parameters
-        
+
+        self.variablesParams = result  # record parameters
+
         return result
 
+
 class ModelObject(object):
-    def __init__(self, id = -1, label = ''):
-        self.id   = id     # internal id, should be not changed
+
+    def __init__(self, id=-1, label=''):
+        self.id = id     # internal id, should be not changed
         self.label = ''
-        self.rels = list() # list of ModelRelations
-        
+        self.rels = list()  # list of ModelRelations
+
         self.isEnabled = True
-        self.inBlock   = list() # list of related loops/conditions
-        
+        self.inBlock = list()  # list of related loops/conditions
+
     def __del__(self):
         pass
 
@@ -868,7 +907,7 @@
     def SetLabel(self, label=''):
         """Set label"""
         self.label = label
-        
+
     def GetId(self):
         """Get id"""
         return self.id
@@ -879,23 +918,22 @@
             for loop in self.inBlock:
                 # update block item
                 loop.UpdateItem(self.id, newId)
-        
+
         self.id = newId
 
-
     def AddRelation(self, rel):
         """Record new relation
         """
         self.rels.append(rel)
 
-    def GetRelations(self, fdir = None):
+    def GetRelations(self, fdir=None):
         """Get list of relations
-        
+
         :param bool fdir: True for 'from'
         """
         if fdir is None:
             return self.rels
-        
+
         result = list()
         for rel in self.rels:
             if fdir == 'from':
@@ -904,14 +942,14 @@
             else:
                 if rel.GetTo() == self:
                     result.append(rel)
-        
+
         return result
-    
+
     def IsEnabled(self):
         """Get True if action is enabled, otherwise False"""
         return self.isEnabled
-    
-    def Enable(self, enabled = True):
+
+    def Enable(self, enabled=True):
         """Enable/disable action"""
         self.isEnabled = enabled
         self.Update()
@@ -927,7 +965,7 @@
         """
         if item not in self.inBlock:
             self.inBlock.append(item)
-        
+
     def UnSetBlock(self, item):
         """Remove object from the block (loop/consition)
 
@@ -936,7 +974,7 @@
         """
         if item in self.inBlock:
             self.inBlock.remove(item)
-        
+
     def GetBlock(self):
         """Get list of related ModelObject(s) which defines block
         (loop/condition)
@@ -944,7 +982,7 @@
         :return: list of ModelObjects
         """
         return self.inBlock
-    
+
     def GetBlockId(self):
         """Get list of related ids which defines block
 
@@ -953,48 +991,55 @@
         ret = list()
         for mo in self.inBlock:
             ret.append(mo.GetId())
-        
+
         return ret
-    
+
+
 class ModelAction(ModelObject, ogl.DividedShape):
     """Action class (GRASS module)"""
-    def __init__(self, parent, x, y, id = -1, cmd = None, task = None,
-                 width = None, height = None, label = None, comment = ''):
+
+    def __init__(self, parent, x, y, id=-1, cmd=None, task=None,
+                 width=None, height=None, label=None, comment=''):
         ModelObject.__init__(self, id, label)
-        
-        self.parent  = parent
-        self.task    = task
+
+        self.parent = parent
+        self.task = task
         self.comment = comment
-        
+
         if not width:
-            width = UserSettings.Get(group='modeler', key='action', subkey=('size', 'width'))
+            width = UserSettings.Get(
+                group='modeler', key='action', subkey=(
+                    'size', 'width'))
         if not height:
-            height = UserSettings.Get(group='modeler', key='action', subkey=('size', 'height'))
-        
+            height = UserSettings.Get(
+                group='modeler', key='action', subkey=(
+                    'size', 'height'))
+
         if cmd:
-            self.task = GUI(show = None).ParseCommand(cmd = cmd)
+            self.task = GUI(show=None).ParseCommand(cmd=cmd)
         else:
             if task:
                 self.task = task
             else:
                 self.task = None
-        
+
         self.propWin = None
-        
+
         self.data = list()   # list of connected data items
-        
+
         self.isValid = False
         self.isParameterized = False
-        
+
         if self.parent.GetCanvas():
             ogl.DividedShape.__init__(self, width, height)
-        
+
             self.regionLabel = ogl.ShapeRegion()
-            self.regionLabel.SetFormatMode(ogl.FORMAT_CENTRE_HORIZ | ogl.FORMAT_CENTRE_VERT)
+            self.regionLabel.SetFormatMode(
+                ogl.FORMAT_CENTRE_HORIZ | ogl.FORMAT_CENTRE_VERT)
             self.AddRegion(self.regionLabel)
-            
+
             self.regionComment = None
-            
+
             self.SetCanvas(self.parent)
             self.SetX(x)
             self.SetY(y)
@@ -1003,14 +1048,14 @@
             self.SetLabel(label)
             if comment:
                 self.SetComment(comment)
-            
+
             self.SetRegionSizes()
             self.ReformatRegions()
 
         if self.task:
             self.SetValid(self.task.get_options())
-        
-    def _setBrush(self, running = False):
+
+    def _setBrush(self, running=False):
         """Set brush"""
         if running:
             color = UserSettings.Get(group='modeler', key='action',
@@ -1024,10 +1069,10 @@
         else:
             color = UserSettings.Get(group='modeler', key='action',
                                      subkey=('color', 'invalid'))
-        
+
         wxColor = wx.Colour(color[0], color[1], color[2])
         self.SetBrush(wx.Brush(wxColor))
-        
+
     def _setPen(self):
         """Set pen"""
         if self.isParameterized:
@@ -1040,14 +1085,14 @@
             style = wx.SOLID
         else:
             style = wx.DOT
-        
+
         pen = wx.Pen(wx.BLACK, width, style)
         self.SetPen(pen)
 
     def ReformatRegions(self):
         rnum = 0
         canvas = self.parent.GetCanvas()
-        
+
         dc = wx.ClientDC(canvas)  # used for measuring
 
         for region in self.GetRegions():
@@ -1067,15 +1112,15 @@
         :param label: if None use command string instead
         """
         if label:
-            self.label = label 
+            self.label = label
         elif self.label:
             label = self.label
         else:
             try:
-                label = self.task.get_cmd(ignoreErrors = True)[0]
+                label = self.task.get_cmd(ignoreErrors=True)[0]
             except:
                 label = _("unknown")
-        
+
         idx = self.GetId()
         self.regionLabel.SetText('(%d) %s' % (idx, label))
         self.SetRegionSizes()
@@ -1092,8 +1137,8 @@
             font.SetStyle(wx.ITALIC)
             self.regionComment.SetFont(font)
 
-        ### clear doesn't work
-        ### self.regionComment.ClearText()
+        # clear doesn't work
+        # self.regionComment.ClearText()
         self.regionComment.SetText(comment)
 
         self.ClearRegions()
@@ -1114,22 +1159,22 @@
     def SetProperties(self, params, propwin):
         """Record properties dialog"""
         self.task.params = params['params']
-        self.task.flags  = params['flags']
+        self.task.flags = params['flags']
         self.propWin = propwin
 
     def GetPropDialog(self):
         """Get properties dialog"""
         return self.propWin
 
-    def GetLog(self, string = True, substitute = None):
+    def GetLog(self, string=True, substitute=None):
         """Get logging info
 
         :param string: True to get cmd as a string otherwise a list
         :param substitute: dictionary of parameter to substitute or None
         """
-        cmd = self.task.get_cmd(ignoreErrors = True, ignoreRequired = True,
-                                ignoreDefault = False)
-        
+        cmd = self.task.get_cmd(ignoreErrors=True, ignoreRequired=True,
+                                ignoreDefault=False)
+
         # substitute variables
         if substitute:
             variables = []
@@ -1141,7 +1186,7 @@
 
             # order variables by length
             for variable in sorted(variables, key=len, reverse=True):
-                pattern= re.compile('%' + variable)
+                pattern = re.compile('%' + variable)
                 value = ''
                 if substitute and 'variables' in substitute:
                     for p in substitute['variables']['params']:
@@ -1151,54 +1196,54 @@
                             else:
                                 value = str(p.get('value', ''))
                             break
-                    
+
                 if not value:
                     value = variables[variable].get('value', '')
-                
+
                 if not value:
                     continue
-                
+
                 for idx in range(len(cmd)):
                     if pattern.search(cmd[idx]):
                         cmd[idx] = pattern.sub(value, cmd[idx])
                         break
                     idx += 1
-        
+
         if string:
             if cmd is None:
                 return ''
             else:
                 return ' '.join(cmd)
-        
+
         return cmd
-    
+
     def GetLabel(self):
         """Get name"""
         if self.label:
             return self.label
-        
-        cmd = self.task.get_cmd(ignoreErrors = True)
+
+        cmd = self.task.get_cmd(ignoreErrors=True)
         if cmd and len(cmd) > 0:
             return cmd[0]
-        
+
         return _('unknown')
 
-    def GetParams(self, dcopy = False):
+    def GetParams(self, dcopy=False):
         """Get dictionary of parameters"""
         if dcopy:
             return copy.deepcopy(self.task.get_options())
-        
+
         return self.task.get_options()
 
     def GetTask(self):
         """Get grassTask instance"""
         return self.task
-    
+
     def SetParams(self, params):
         """Set dictionary of parameters"""
         self.task.params = params['params']
-        self.task.flags  = params['flags']
-        
+        self.task.flags = params['flags']
+
     def MergeParams(self, params):
         """Merge dictionary of parameters"""
         if 'flags' in params:
@@ -1209,10 +1254,10 @@
             for p in params['params']:
                 self.task.set_param(p['name'],
                                     p.get('value', ''))
-        
+
     def SetValid(self, options):
         """Set validity for action
-        
+
         :param options: dictionary with flags and params (gtask)
         """
         self.isValid = True
@@ -1229,48 +1274,48 @@
                 self.isValid = False
             if not self.isParameterized and p.get('parameterized', False):
                 self.isParameterized = True
-        
+
         if self.parent.GetCanvas():
             self._setBrush()
             self._setPen()
-        
+
     def IsValid(self):
         """Check validity (all required parameters set)"""
         return self.isValid
-    
+
     def IsParameterized(self):
         """Check if action is parameterized"""
         return self.isParameterized
 
     def GetParameterizedParams(self):
         """Return parameterized flags and options"""
-        param = { 'flags': [], 'params' : [] }
-        
+        param = {'flags': [], 'params': []}
+
         options = self.GetParams()
-        
+
         for f in options['flags']:
             if f.get('parameterized', False):
                 param['flags'].append(f)
-        
+
         for p in options['params']:
             if p.get('parameterized', False):
                 param['params'].append(p)
-        
+
         return param
-        
+
     def FindData(self, name):
         """Find data item by name"""
         for rel in self.GetRelations():
             data = rel.GetData()
             if name == rel.GetLabel() and name in data.GetLabel():
                 return data
-        
+
         return None
 
-    def Update(self, running = False):
+    def Update(self, running=False):
         """Update action"""
         if running:
-            self._setBrush(running = True)
+            self._setBrush(running=True)
         else:
             self._setBrush()
         self._setPen()
@@ -1279,13 +1324,16 @@
         """Draw action in canvas"""
         self._setBrush()
         self._setPen()
-        ogl.RectangleShape.Recentre(self, dc) # re-center text
+        ogl.RectangleShape.Recentre(self, dc)  # re-center text
         ogl.RectangleShape.OnDraw(self, dc)
 
+
 class ModelData(ModelObject, ogl.EllipseShape):
-    def __init__(self, parent, x, y, value = '', prompt = '', width = None, height = None):
+
+    def __init__(self, parent, x, y, value='',
+                 prompt='', width=None, height=None):
         """Data item class
-        
+
         :param parent: window parent
         :param x, y: position of the shape
         :param fname, tname: list of parameter names from / to
@@ -1294,41 +1342,45 @@
         :param width, height: dimension of the shape
         """
         ModelObject.__init__(self)
-        
-        self.parent  = parent
-        self.value   = value
-        self.prompt  = prompt
+
+        self.parent = parent
+        self.value = value
+        self.prompt = prompt
         self.intermediate = False
         self.propWin = None
         if not width:
-            width = UserSettings.Get(group='modeler', key='data', subkey=('size', 'width'))
+            width = UserSettings.Get(
+                group='modeler', key='data', subkey=(
+                    'size', 'width'))
         if not height:
-            height = UserSettings.Get(group='modeler', key='data', subkey=('size', 'height'))
-        
+            height = UserSettings.Get(
+                group='modeler', key='data', subkey=(
+                    'size', 'height'))
+
         if self.parent.GetCanvas():
             ogl.EllipseShape.__init__(self, width, height)
-            
+
             self.SetCanvas(self.parent)
             self.SetX(x)
             self.SetY(y)
             self._setPen()
             self._setBrush()
             self.SetLabel()
-            
+
     def IsIntermediate(self):
         """Checks if data item is intermediate"""
         return self.intermediate
-    
+
     def SetIntermediate(self, im):
         """Set intermediate flag"""
         self.intermediate = im
-  
+
     def OnDraw(self, dc):
         self._setPen()
-        
+
         ogl.EllipseShape.OnDraw(self, dc)
-        
-    def GetLog(self, string = True):
+
+    def GetLog(self, string=True):
         """Get logging info"""
         name = list()
         for rel in self.GetRelations():
@@ -1343,20 +1395,20 @@
         name = list()
         for rel in self.GetRelations():
             name.append(rel.GetLabel())
-        
+
         return name
-    
+
     def GetPrompt(self):
         """Get prompt"""
         return self.prompt
 
     def SetPrompt(self, prompt):
         """Set prompt
-        
+
         :param prompt:
         """
         self.prompt = prompt
-        
+
     def GetValue(self):
         """Get value"""
         return self.value
@@ -1375,10 +1427,13 @@
                 else:
                     action = rel.GetFrom()
 
-                task = GUI(show = None).ParseCommand(cmd = action.GetLog(string = False))
+                task = GUI(
+                    show=None).ParseCommand(
+                    cmd=action.GetLog(
+                        string=False))
                 task.set_param(rel.GetLabel(), self.value)
                 action.MergeParams(task.get_options())
-        
+
     def GetPropDialog(self):
         """Get properties dialog"""
         return self.propWin
@@ -1390,23 +1445,23 @@
     def _setBrush(self):
         """Set brush"""
         if self.prompt == 'raster':
-            color = UserSettings.Get(group = 'modeler', key = 'data',
-                                     subkey = ('color', 'raster'))
+            color = UserSettings.Get(group='modeler', key='data',
+                                     subkey=('color', 'raster'))
         elif self.prompt == 'raster_3d':
-            color = UserSettings.Get(group = 'modeler', key = 'data',
-                                     subkey = ('color', 'raster3d'))
+            color = UserSettings.Get(group='modeler', key='data',
+                                     subkey=('color', 'raster3d'))
         elif self.prompt == 'vector':
-            color = UserSettings.Get(group = 'modeler', key = 'data',
-                                     subkey = ('color', 'vector'))
+            color = UserSettings.Get(group='modeler', key='data',
+                                     subkey=('color', 'vector'))
         elif self.prompt == 'dbtable':
-            color = UserSettings.Get(group = 'modeler', key = 'data',
-                                     subkey = ('color', 'dbtable'))
+            color = UserSettings.Get(group='modeler', key='data',
+                                     subkey=('color', 'dbtable'))
         else:
-            color = UserSettings.Get(group = 'modeler', key = 'action',
-                                     subkey = ('color', 'invalid'))
+            color = UserSettings.Get(group='modeler', key='action',
+                                     subkey=('color', 'invalid'))
         wxColor = wx.Colour(color[0], color[1], color[2])
         self.SetBrush(wx.Brush(wxColor))
-        
+
     def _setPen(self):
         """Set pen"""
         isParameterized = False
@@ -1421,19 +1476,19 @@
                     break
 
         if isParameterized:
-            width = int(UserSettings.Get(group = 'modeler', key = 'action',
-                                         subkey = ('width', 'parameterized')))
+            width = int(UserSettings.Get(group='modeler', key='action',
+                                         subkey=('width', 'parameterized')))
         else:
-            width = int(UserSettings.Get(group = 'modeler', key = 'action',
-                                         subkey = ('width', 'default')))
+            width = int(UserSettings.Get(group='modeler', key='action',
+                                         subkey=('width', 'default')))
         if self.intermediate:
             style = wx.DOT
         else:
             style = wx.SOLID
-        
+
         pen = wx.Pen(wx.BLACK, width, style)
         self.SetPen(pen)
-        
+
     def SetLabel(self):
         """Update text"""
         self.ClearText()
@@ -1445,26 +1500,28 @@
             self.AddText(self.value)
         else:
             self.AddText(_('<not defined>'))
-        
+
     def Update(self):
         """Update action"""
         self._setBrush()
         self._setPen()
         self.SetLabel()
 
+
 class ModelRelation(ogl.LineShape):
     """Data - action relation"""
-    def __init__(self, parent, fromShape, toShape, param = ''):
+
+    def __init__(self, parent, fromShape, toShape, param=''):
         self.fromShape = fromShape
-        self.toShape   = toShape
-        self.param     = param
-        self.parent    = parent
-        
-        self._points    = None
-        
-        if self.parent.GetCanvas():        
+        self.toShape = toShape
+        self.param = param
+        self.parent = parent
+
+        self._points = None
+
+        if self.parent.GetCanvas():
             ogl.LineShape.__init__(self)
-    
+
     def __del__(self):
         if self in self.fromShape.rels:
             self.fromShape.rels.remove(self)
@@ -1474,11 +1531,11 @@
     def GetFrom(self):
         """Get id of 'from' shape"""
         return self.fromShape
-    
+
     def GetTo(self):
         """Get id of 'to' shape"""
         return self.toShape
-    
+
     def GetData(self):
         """Get related ModelData instance
 
@@ -1489,45 +1546,48 @@
             return self.fromShape
         elif isinstance(self.toShape, ModelData):
             return self.toShape
-        
+
         return None
-    
+
     def GetLabel(self):
         """Get parameter name"""
         return self.param
-    
+
     def ResetShapes(self):
         """Reset related objects"""
         self.fromShape.ResetControlPoints()
         self.toShape.ResetControlPoints()
         self.ResetControlPoints()
-        
+
     def SetControlPoints(self, points):
         """Set control points"""
         self._points = points
-        
+
     def GetControlPoints(self):
         """Get list of control points"""
         return self._points
-    
+
     def _setPen(self):
         """Set pen"""
         pen = wx.Pen(wx.BLACK, 1, wx.SOLID)
         self.SetPen(pen)
-        
+
     def OnDraw(self, dc):
         """Draw relation"""
         self._setPen()
         ogl.LineShape.OnDraw(self, dc)
-    
+
     def SetName(self, param):
         self.param = param
 
+
 class ModelItem(ModelObject):
-    def __init__(self, parent, x, y, id = -1, width = None, height = None, label = '', items = []):
+
+    def __init__(self, parent, x, y, id=-1, width=None,
+                 height=None, label='', items=[]):
         """Abstract class for loops and conditions"""
         ModelObject.__init__(self, id, label)
-        self.parent  = parent
+        self.parent = parent
 
     def _setPen(self):
         """Set pen"""
@@ -1535,7 +1595,7 @@
             style = wx.SOLID
         else:
             style = wx.DOT
-        
+
         pen = wx.Pen(wx.BLACK, 1, style)
         self.SetPen(pen)
 
@@ -1560,25 +1620,32 @@
     def AddRelation(self, rel):
         """Record relation"""
         self.rels.append(rel)
-        
+
     def Clear(self):
         """Clear object, remove rels"""
         self.rels = list()
-   
+
+
 class ModelLoop(ModelItem, ogl.RectangleShape):
-    def __init__(self, parent, x, y, id=-1, idx=-1, width = None, height = None, label = '', items = []):
+
+    def __init__(self, parent, x, y, id=-1, idx=-1,
+                 width=None, height=None, label='', items=[]):
         """Defines a loop"""
         ModelItem.__init__(self, parent, x, y, id, width, height, label, items)
-        self.itemIds = list() # unordered        
+        self.itemIds = list()  # unordered
 
         if not width:
-            width = UserSettings.Get(group='modeler', key='loop', subkey=('size', 'width'))
+            width = UserSettings.Get(
+                group='modeler', key='loop', subkey=(
+                    'size', 'width'))
         if not height:
-            height = UserSettings.Get(group='modeler', key='loop', subkey=('size', 'height'))
-        
+            height = UserSettings.Get(
+                group='modeler', key='loop', subkey=(
+                    'size', 'height'))
+
         if self.parent.GetCanvas():
             ogl.RectangleShape.__init__(self, width, height)
-            
+
             self.SetCanvas(self.parent)
             self.SetX(x)
             self.SetY(y)
@@ -1595,17 +1662,17 @@
         else:
             color = UserSettings.Get(group='modeler', key='loop',
                                      subkey=('color', 'valid'))
-        
+
         wxColor = wx.Colour(color[0], color[1], color[2])
         self.SetBrush(wx.Brush(wxColor))
 
-    def Enable(self, enabled = True):
+    def Enable(self, enabled=True):
         """Enable/disable action"""
         for idx in self.itemIds:
             item = self.parent.FindAction(idx)
             if item:
                 item.Enable(enabled)
-        
+
         ModelObject.Enable(self, enabled)
         self.Update()
 
@@ -1619,7 +1686,7 @@
         for item in items:
             if item.GetId() in self.itemIds:
                 result.append(item)
-        
+
         return result
 
     def SetItems(self, items):
@@ -1631,38 +1698,50 @@
         idx = self.itemIds.index(oldId)
         if idx != -1:
             self.itemIds[idx] = newId
-        
+
     def OnDraw(self, dc):
         """Draw loop in canvas"""
         self._setBrush()
-        ogl.RectangleShape.Recentre(self, dc) # re-center text
+        ogl.RectangleShape.Recentre(self, dc)  # re-center text
         ogl.RectangleShape.OnDraw(self, dc)
 
+
 class ModelCondition(ModelItem, ogl.PolygonShape):
-    def __init__(self, parent, x, y, id = -1, width = None, height = None, label = '',
-                 items = { 'if' : [], 'else' : [] }):
+
+    def __init__(self, parent, x, y, id=-1, width=None, height=None, label='',
+                 items={'if': [], 'else': []}):
         """Defines a if-else condition"""
         ModelItem.__init__(self, parent, x, y, id, width, height, label, items)
-        self.itemIds = {'if' : [], 'else': []}
-        
+        self.itemIds = {'if': [], 'else': []}
+
         if not width:
-            self.width = UserSettings.Get(group='modeler', key='if-else', subkey=('size', 'width'))
+            self.width = UserSettings.Get(
+                group='modeler',
+                key='if-else',
+                subkey=(
+                    'size',
+                    'width'))
         else:
             self.width = width
         if not height:
-            self.height = UserSettings.Get(group='modeler', key='if-else', subkey=('size', 'height'))
+            self.height = UserSettings.Get(
+                group='modeler',
+                key='if-else',
+                subkey=(
+                    'size',
+                    'height'))
         else:
             self.height = height
-        
+
         if self.parent.GetCanvas():
             ogl.PolygonShape.__init__(self)
-            
+
             points = [(0, - self.height / 2),
                       (self.width / 2, 0),
                       (0, self.height / 2),
                       (- self.width / 2, 0)]
             self.Create(points)
-            
+
             self.SetCanvas(self.parent)
             self.SetX(x)
             self.SetY(y)
@@ -1686,16 +1765,16 @@
 
     def GetItems(self, items):
         """Get sorted items by id"""
-        result = {'if' : [], 'else': []}
+        result = {'if': [], 'else': []}
         for item in items:
             if item.GetId() in self.itemIds['if']:
                 result['if'].append(item)
             elif item.GetId() in self.itemIds['else']:
                 result['else'].append(item)
-        
+
         return result
 
-    def SetItems(self, items, branch = 'if'):
+    def SetItems(self, items, branch='if'):
         """Set items (id)
 
         :param items: list of items
@@ -1704,16 +1783,22 @@
         if branch in ['if', 'else']:
             self.itemIds[branch] = items
 
+
 class ModelComment(ModelObject, ogl.RectangleShape):
-    def __init__(self, parent, x, y, id = -1, width = None, height = None, label = ''):
+
+    def __init__(self, parent, x, y, id=-1, width=None, height=None, label=''):
         """Defines a model comment"""
         ModelObject.__init__(self, id, label)
 
         if not width:
-            width = UserSettings.Get(group='modeler', key='comment', subkey=('size', 'width'))
+            width = UserSettings.Get(
+                group='modeler', key='comment', subkey=(
+                    'size', 'width'))
         if not height:
-            height = UserSettings.Get(group='modeler', key='comment', subkey=('size', 'height'))
-        
+            height = UserSettings.Get(
+                group='modeler', key='comment', subkey=(
+                    'size', 'height'))
+
         if parent.GetCanvas():
             ogl.RectangleShape.__init__(self, width, height)
             self.SetCanvas(parent)
@@ -1726,10 +1811,10 @@
             self._setBrush()
             self.SetLabel(label)
 
-    def _setBrush(self, running = False):
+    def _setBrush(self, running=False):
         """Set brush"""
         color = UserSettings.Get(group='modeler', key='comment',
-                                     subkey='color')
+                                 subkey='color')
         wxColor = wx.Colour(color[0], color[1], color[2])
         self.SetBrush(wx.Brush(wxColor))
 
@@ -1744,13 +1829,13 @@
         :param label: if None use command string instead
         """
         if label:
-            self.label = label 
+            self.label = label
         elif self.label:
             label = self.label
         else:
             label = ''
         idx = self.GetId()
-        
+
         self.ClearText()
         self.AddText('(%d) %s' % (idx, label))
 
@@ -1761,8 +1846,10 @@
         self.SetLabel(comment)
         self.GetCanvas().Refresh()
 
+
 class ProcessModelFile:
     """Process GRASS model file (gxm)"""
+
     def __init__(self, tree):
         """A ElementTree handler for the GXM XML file, as defined in
         grass-gxm.dtd.
@@ -1775,14 +1862,15 @@
                 tagName = self.root.tag
             else:
                 tabName = _("empty")
-            raise GException(_("Details: unsupported tag name '{}'.").format(tagName))
-        
+            raise GException(
+                _("Details: unsupported tag name '{}'.").format(tagName))
+
         # list of actions, data
         self.properties = dict()
-        self.variables  = dict() 
+        self.variables = dict()
         self.actions = list()
-        self.data    = list()
-        self.loops   = list()
+        self.data = list()
+        self.loops = list()
         self.conditions = list()
         self.comments = list()
 
@@ -1791,18 +1879,18 @@
         self._processVariables()
         self._processItems()
         self._processData()
-        
+
     def _filterValue(self, value):
         """Filter value
-        
+
         :param value:
         """
         value = value.replace('<', '<')
         value = value.replace('>', '>')
-        
+
         return value
-        
-    def _getNodeText(self, node, tag, default = ''):
+
+    def _getNodeText(self, node, tag, default=''):
         """Get node text"""
         p = node.find(tag)
         if p is not None:
@@ -1810,18 +1898,18 @@
                 return utils.normalize_whitespace(p.text)
             else:
                 return ''
-        
+
         return default
-    
+
     def _processWindow(self):
         """Process window properties"""
         node = self.root.find('window')
         if node is None:
             self.pos = self.size = None
             return
-        
+
         self.pos, self.size = self._getDim(node)
-        
+
     def _processProperties(self):
         """Process model properties"""
         node = self.root.find('properties')
@@ -1829,12 +1917,12 @@
             return
         for key in ('name', 'description', 'author'):
             self._processProperty(node, key)
-        
+
         for f in node.findall('flag'):
             name = f.get('name', '')
             if name == 'overwrite':
                 self.properties['overwrite'] = True
-        
+
     def _processProperty(self, pnode, name):
         """Process given property"""
         node = pnode.find(name)
@@ -1851,11 +1939,11 @@
         for node in vnode.findall('variable'):
             name = node.get('name', '')
             if not name:
-                continue # should not happen
-            self.variables[name] = { 'type' : node.get('type', 'string') }
+                continue  # should not happen
+            self.variables[name] = {'type': node.get('type', 'string')}
             for key in ('description', 'value'):
                 self._processVariable(node, name, key)
-        
+
     def _processVariable(self, pnode, name, key):
         """Process given variable"""
         node = pnode.find(key)
@@ -1874,8 +1962,8 @@
         """Process model file"""
         for action in self.root.findall('action'):
             pos, size = self._getDim(action)
-            disabled  = False
-            
+            disabled = False
+
             task = action.find('task')
             if task is not None:
                 if task.find('disabled') is not None:
@@ -1883,7 +1971,7 @@
                 task = self._processTask(task)
             else:
                 task = None
-            
+
             aId = int(action.get('id', -1))
             label = action.get('name')
             comment = action.find('comment')
@@ -1891,15 +1979,15 @@
                 commentString = comment.text
             else:
                 commentString = ''
-            
-            self.actions.append({ 'pos'      : pos,
-                                  'size'     : size,
-                                  'task'     : task,
-                                  'id'       : aId,
-                                  'disabled' : disabled,
-                                  'label'    : label,
-                                  'comment'  : commentString})
 
+            self.actions.append({'pos': pos,
+                                 'size': size,
+                                 'task': task,
+                                 'id': aId,
+                                 'disabled': disabled,
+                                 'label': label,
+                                 'comment': commentString})
+
     def _getDim(self, node):
         """Get position and size of shape"""
         pos = size = None
@@ -1910,7 +1998,7 @@
                 pos = (posVal[0], posVal[1])
             except:
                 pos = None
-        
+
         sizeAttr = node.get('size', None)
         if sizeAttr:
             sizeVal = map(int, sizeAttr.split(','))
@@ -1918,9 +2006,9 @@
                 size = (sizeVal[0], sizeVal[1])
             except:
                 size = None
-        
-        return pos, size        
-    
+
+        return pos, size
+
     def _processData(self):
         """Process model file"""
         for data in self.root.findall('data'):
@@ -1930,17 +2018,17 @@
             if param is not None:
                 prompt = param.get('prompt', None)
                 value = self._filterValue(self._getNodeText(param, 'value'))
-            
+
             if data.find('intermediate') is None:
                 intermediate = False
             else:
                 intermediate = True
-            
+
             rels = list()
             for rel in data.findall('relation'):
-                defrel = { 'id'  : int(rel.get('id', -1)),
-                           'dir' : rel.get('dir', 'to'),
-                           'name' : rel.get('name', '') }
+                defrel = {'id': int(rel.get('id', -1)),
+                          'dir': rel.get('dir', 'to'),
+                          'name': rel.get('name', '')}
                 points = list()
                 for point in rel.findall('point'):
                     x = self._filterValue(self._getNodeText(point, 'x'))
@@ -1948,14 +2036,14 @@
                     points.append((float(x), float(y)))
                 defrel['points'] = points
                 rels.append(defrel)
-            
-            self.data.append({ 'pos' : pos,
-                               'size': size,
-                               'prompt' : prompt,
-                               'value' : value,
-                               'intermediate' : intermediate,
-                               'rels' : rels })
-        
+
+            self.data.append({'pos': pos,
+                              'size': size,
+                              'prompt': prompt,
+                              'value': value,
+                              'intermediate': intermediate,
+                              'rels': rels})
+
     def _processTask(self, node):
         """Process task
 
@@ -1964,13 +2052,13 @@
         """
         cmd = list()
         parameterized = list()
-        
+
         name = node.get('name', None)
         if not name:
             return None
-        
+
         cmd.append(name)
-        
+
         # flags
         for f in node.findall('flag'):
             flag = f.get('name', '')
@@ -1987,46 +2075,53 @@
             name = p.get('name', '')
             if p.find('parameterized') is not None:
                 parameterized.append(('param', name))
-            cmd.append('%s=%s' % (name,
-                                  self._filterValue(self._getNodeText(p, 'value'))))
-        
-        task, err = GUI(show = None, checkError = True).ParseCommand(cmd = cmd)
+            cmd.append(
+                '%s=%s' %
+                (name, self._filterValue(
+                    self._getNodeText(
+                        p, 'value'))))
+
+        task, err = GUI(show=None, checkError=True).ParseCommand(cmd=cmd)
         if err:
             GWarning(os.linesep.join(err))
-        
+
         for opt, name in parameterized:
             if opt == 'flag':
-                task.set_flag(name, True, element = 'parameterized')
+                task.set_flag(name, True, element='parameterized')
             else:
-                task.set_param(name, True, element = 'parameterized')
-        
+                task.set_param(name, True, element='parameterized')
+
         return task
 
     def _processLoops(self):
         """Process model loops"""
         for node in self.root.findall('loop'):
             pos, size = self._getDim(node)
-            text = self._filterValue(self._getNodeText(node, 'condition')).strip()
+            text = self._filterValue(
+                self._getNodeText(
+                    node, 'condition')).strip()
             aid = list()
             for anode in node.findall('item'):
                 try:
                     aid.append(int(anode.text))
                 except ValueError:
                     pass
-            
-            self.loops.append({ 'pos'     : pos,
-                                'size'    : size,
-                                'text'    : text,
-                                'id'      : int(node.get('id', -1)),
-                                'items'   : aid })
-        
+
+            self.loops.append({'pos': pos,
+                               'size': size,
+                               'text': text,
+                               'id': int(node.get('id', -1)),
+                               'items': aid})
+
     def _processConditions(self):
         """Process model conditions"""
         for node in self.root.findall('if-else'):
             pos, size = self._getDim(node)
-            text = self._filterValue(self._getNodeText(node, 'condition')).strip()
-            aid = { 'if'   : list(),
-                    'else' : list() }
+            text = self._filterValue(
+                self._getNodeText(
+                    node, 'condition')).strip()
+            aid = {'if': list(),
+                   'else': list()}
             for b in aid.keys():
                 bnode = node.find(b)
                 if bnode is None:
@@ -2036,51 +2131,53 @@
                         aid[b].append(int(anode.text))
                     except ValueError:
                         pass
-            
-            self.conditions.append({ 'pos'     : pos,
-                                     'size'    : size,
-                                     'text'    : text,
-                                     'id'      : int(node.get('id', -1)),
-                                     'items'   : aid })
 
+            self.conditions.append({'pos': pos,
+                                    'size': size,
+                                    'text': text,
+                                    'id': int(node.get('id', -1)),
+                                    'items': aid})
+
     def _processComments(self):
         """Process model comments"""
         for node in self.root.findall('comment'):
             pos, size = self._getDim(node)
             text = self._filterValue(node.text)
 
-            self.comments.append({ 'pos'     : pos,
-                                   'size'    : size,
-                                   'text'    : text,
-                                   'id'      : int(node.get('id', -1)),
-                                   'text'    : text })
-        
+            self.comments.append({'pos': pos,
+                                  'size': size,
+                                  'text': text,
+                                  'id': int(node.get('id', -1)),
+                                  'text': text})
+
+
 class WriteModelFile:
     """Generic class for writing model file"""
+
     def __init__(self, fd, model):
-        self.fd         = fd
-        self.model      = model
+        self.fd = fd
+        self.model = model
         self.properties = model.GetProperties()
-        self.variables  = model.GetVariables()
-        self.items      = model.GetItems()
-        
+        self.variables = model.GetVariables()
+        self.items = model.GetItems()
+
         self.indent = 0
-        
+
         self._header()
-        
+
         self._window()
         self._properties()
         self._variables()
         self._items()
-        
+
         dataList = list()
-        for action in model.GetItems(objType = ModelAction):
+        for action in model.GetItems(objType=ModelAction):
             for rel in action.GetRelations():
                 dataItem = rel.GetData()
                 if dataItem not in dataList:
                     dataList.append(dataItem)
         self._data(dataList)
-        
+
         self._footer()
 
     def _filterValue(self, value):
@@ -2091,14 +2188,17 @@
         """
         value = saxutils.escape(value)
         return value
-        
+
     def _header(self):
         """Write header"""
-        self.fd.write('<?xml version="1.0" encoding="%s"?>\n' % GetDefaultEncoding(forceUTF8 = True))
+        self.fd.write(
+            '<?xml version="1.0" encoding="%s"?>\n' %
+            GetDefaultEncoding(
+                forceUTF8=True))
         self.fd.write('<!DOCTYPE gxm SYSTEM "grass-gxm.dtd">\n')
         self.fd.write('%s<gxm>\n' % (' ' * self.indent))
         self.indent += 4
-                
+
     def _footer(self):
         """Write footer"""
         self.indent -= 4
@@ -2109,28 +2209,43 @@
         canvas = self.model.GetCanvas()
         if canvas is None:
             return
-        win  = canvas.parent
-        pos  = win.GetPosition()
+        win = canvas.parent
+        pos = win.GetPosition()
         size = win.GetSize()
-        self.fd.write('%s<window pos="%d,%d" size="%d,%d" />\n' % \
-                          (' ' * self.indent, pos[0], pos[1], size[0], size[1]))
-        
+        self.fd.write('%s<window pos="%d,%d" size="%d,%d" />\n' %
+                      (' ' * self.indent, pos[0], pos[1], size[0], size[1]))
+
     def _properties(self):
         """Write model properties"""
         self.fd.write('%s<properties>\n' % (' ' * self.indent))
         self.indent += 4
         if self.properties['name']:
-            self.fd.write('%s<name>%s</name>\n' % (' ' * self.indent, EncodeString(self.properties['name'])))
+            self.fd.write(
+                '%s<name>%s</name>\n' %
+                (' ' *
+                 self.indent,
+                 EncodeString(
+                     self.properties['name'])))
         if self.properties['description']:
-            self.fd.write('%s<description>%s</description>\n' % (' ' * self.indent,
-                                                                 EncodeString(self.properties['description'])))
+            self.fd.write(
+                '%s<description>%s</description>\n' %
+                (' ' *
+                 self.indent,
+                 EncodeString(
+                     self.properties['description'])))
         if self.properties['author']:
-            self.fd.write('%s<author>%s</author>\n' % (' ' * self.indent,
-                                                       EncodeString(self.properties['author'])))
-        
+            self.fd.write(
+                '%s<author>%s</author>\n' %
+                (' ' *
+                 self.indent,
+                 EncodeString(
+                     self.properties['author'])))
+
         if 'overwrite' in self.properties and \
                 self.properties['overwrite']:
-            self.fd.write('%s<flag name="overwrite" />\n' % (' ' * self.indent))
+            self.fd.write(
+                '%s<flag name="overwrite" />\n' %
+                (' ' * self.indent))
         self.indent -= 4
         self.fd.write('%s</properties>\n' % (' ' * self.indent))
 
@@ -2141,20 +2256,22 @@
         self.fd.write('%s<variables>\n' % (' ' * self.indent))
         self.indent += 4
         for name, values in self.variables.iteritems():
-            self.fd.write('%s<variable name="%s" type="%s">\n' % \
-                              (' ' * self.indent, EncodeString(name), values['type']))
+            self.fd.write(
+                '%s<variable name="%s" type="%s">\n' %
+                (' ' * self.indent, EncodeString(name), values['type']))
             self.indent += 4
             if 'value' in values:
-                self.fd.write('%s<value>%s</value>\n' % \
-                                  (' ' * self.indent, EncodeString(values['value'])))
+                self.fd.write('%s<value>%s</value>\n' %
+                              (' ' * self.indent, EncodeString(values['value'])))
             if 'description' in values:
-                self.fd.write('%s<description>%s</description>\n' % \
-                                  (' ' * self.indent, EncodeString(values['description'])))
+                self.fd.write(
+                    '%s<description>%s</description>\n' %
+                    (' ' * self.indent, EncodeString(values['description'])))
             self.indent -= 4
             self.fd.write('%s</variable>\n' % (' ' * self.indent))
         self.indent -= 4
         self.fd.write('%s</variables>\n' % (' ' * self.indent))
-        
+
     def _items(self):
         """Write actions/loops/conditions"""
         for item in self.items:
@@ -2166,17 +2283,28 @@
                 self._condition(item)
             elif isinstance(item, ModelComment):
                 self._comment(item)
-        
+
     def _action(self, action):
         """Write actions"""
-        self.fd.write('%s<action id="%d" name="%s" pos="%d,%d" size="%d,%d">\n' % \
-                          (' ' * self.indent, action.GetId(), EncodeString(action.GetLabel()), action.GetX(), action.GetY(),
-                           action.GetWidth(), action.GetHeight()))
+        self.fd.write(
+            '%s<action id="%d" name="%s" pos="%d,%d" size="%d,%d">\n' %
+            (' ' *
+             self.indent,
+             action.GetId(),
+             EncodeString(
+                 action.GetLabel()),
+                action.GetX(),
+                action.GetY(),
+                action.GetWidth(),
+                action.GetHeight()))
         self.indent += 4
         comment = action.GetComment()
         if comment:
-            self.fd.write('%s<comment>%s</comment>\n' % (' ' * self.indent, EncodeString(comment)))
-        self.fd.write('%s<task name="%s">\n' % (' ' * self.indent, action.GetLog(string = False)[0]))
+            self.fd.write(
+                '%s<comment>%s</comment>\n' %
+                (' ' * self.indent, EncodeString(comment)))
+        self.fd.write('%s<task name="%s">\n' %
+                      (' ' * self.indent, action.GetLog(string=False)[0]))
         self.indent += 4
         if not action.IsEnabled():
             self.fd.write('%s<disabled />\n' % (' ' * self.indent))
@@ -2186,47 +2314,72 @@
                     if f.get('value', False) or f.get('parameterized', False):
                         if f.get('parameterized', False):
                             if f.get('value', False) == False:
-                                self.fd.write('%s<flag name="%s" value="0" parameterized="1" />\n' %
-                                              (' ' * self.indent, f.get('name', '')))
+                                self.fd.write(
+                                    '%s<flag name="%s" value="0" parameterized="1" />\n' %
+                                    (' ' *
+                                     self.indent,
+                                     f.get(
+                                         'name',
+                                         '')))
                             else:
-                                self.fd.write('%s<flag name="%s" parameterized="1" />\n' %
-                                              (' ' * self.indent, f.get('name', '')))
+                                self.fd.write(
+                                    '%s<flag name="%s" parameterized="1" />\n' %
+                                    (' ' *
+                                     self.indent,
+                                     f.get(
+                                         'name',
+                                         '')))
                         else:
-                            self.fd.write('%s<flag name="%s" />\n' %
-                                          (' ' * self.indent, f.get('name', '')))
-            else: # parameter
+                            self.fd.write(
+                                '%s<flag name="%s" />\n' %
+                                (' ' * self.indent, f.get('name', '')))
+            else:  # parameter
                 for p in val:
-                    if not p.get('value', '') and not p.get('parameterized', False):
+                    if not p.get(
+                            'value', '') and not p.get(
+                            'parameterized', False):
                         continue
                     self.fd.write('%s<parameter name="%s">\n' %
                                   (' ' * self.indent, p.get('name', '')))
                     self.indent += 4
                     if p.get('parameterized', False):
-                        self.fd.write('%s<parameterized />\n' % (' ' * self.indent))
-                    self.fd.write('%s<value>%s</value>\n' %
-                                  (' ' * self.indent, self._filterValue(p.get('value', ''))))
+                        self.fd.write(
+                            '%s<parameterized />\n' %
+                            (' ' * self.indent))
+                    self.fd.write(
+                        '%s<value>%s</value>\n' %
+                        (' ' *
+                         self.indent,
+                         self._filterValue(
+                             p.get(
+                                 'value',
+                                 ''))))
                     self.indent -= 4
                     self.fd.write('%s</parameter>\n' % (' ' * self.indent))
         self.indent -= 4
         self.fd.write('%s</task>\n' % (' ' * self.indent))
         self.indent -= 4
         self.fd.write('%s</action>\n' % (' ' * self.indent))
-                
+
     def _data(self, dataList):
         """Write data"""
         for data in dataList:
-            self.fd.write('%s<data pos="%d,%d" size="%d,%d">\n' % \
-                              (' ' * self.indent, data.GetX(), data.GetY(),
-                               data.GetWidth(), data.GetHeight()))
+            self.fd.write('%s<data pos="%d,%d" size="%d,%d">\n' %
+                          (' ' * self.indent, data.GetX(), data.GetY(),
+                           data.GetWidth(), data.GetHeight()))
             self.indent += 4
-            self.fd.write('%s<data-parameter prompt="%s">\n' % \
-                              (' ' * self.indent, data.GetPrompt()))
+            self.fd.write('%s<data-parameter prompt="%s">\n' %
+                          (' ' * self.indent, data.GetPrompt()))
             self.indent += 4
-            self.fd.write('%s<value>%s</value>\n' %
-                          (' ' * self.indent, self._filterValue(data.GetValue())))
+            self.fd.write(
+                '%s<value>%s</value>\n' %
+                (' ' *
+                 self.indent,
+                 self._filterValue(
+                     data.GetValue())))
             self.indent -= 4
             self.fd.write('%s</data-parameter>\n' % (' ' * self.indent))
-            
+
             if data.IsIntermediate():
                 self.fd.write('%s<intermediate />\n' % (' ' * self.indent))
 
@@ -2236,29 +2389,39 @@
                     if ft == 'from':
                         aid = rel.GetTo().GetId()
                     else:
-                        aid  = rel.GetFrom().GetId()
-                    self.fd.write('%s<relation dir="%s" id="%d" name="%s">\n' % \
-                                      (' ' * self.indent, ft, aid, rel.GetLabel()))
+                        aid = rel.GetFrom().GetId()
+                    self.fd.write('%s<relation dir="%s" id="%d" name="%s">\n' %
+                                  (' ' * self.indent, ft, aid, rel.GetLabel()))
                     self.indent += 4
                     for point in rel.GetLineControlPoints()[1:-1]:
                         self.fd.write('%s<point>\n' % (' ' * self.indent))
                         self.indent += 4
                         x, y = point.Get()
-                        self.fd.write('%s<x>%d</x>\n' % (' ' * self.indent, int(x)))
-                        self.fd.write('%s<y>%d</y>\n' % (' ' * self.indent, int(y)))
+                        self.fd.write(
+                            '%s<x>%d</x>\n' %
+                            (' ' * self.indent, int(x)))
+                        self.fd.write(
+                            '%s<y>%d</y>\n' %
+                            (' ' * self.indent, int(y)))
                         self.indent -= 4
                         self.fd.write('%s</point>\n' % (' ' * self.indent))
                     self.indent -= 4
                     self.fd.write('%s</relation>\n' % (' ' * self.indent))
-                
+
             self.indent -= 4
             self.fd.write('%s</data>\n' % (' ' * self.indent))
 
     def _loop(self, loop):
         """Write loops"""
-        self.fd.write('%s<loop id="%d" pos="%d,%d" size="%d,%d">\n' % \
-                          (' ' * self.indent, loop.GetId(), loop.GetX(), loop.GetY(),
-                           loop.GetWidth(), loop.GetHeight()))
+        self.fd.write(
+            '%s<loop id="%d" pos="%d,%d" size="%d,%d">\n' %
+            (' ' *
+             self.indent,
+             loop.GetId(),
+             loop.GetX(),
+             loop.GetY(),
+             loop.GetWidth(),
+             loop.GetHeight()))
         self.indent += 4
         cond = loop.GetLabel()
         if cond:
@@ -2273,9 +2436,15 @@
     def _condition(self, condition):
         """Write conditions"""
         bbox = condition.GetBoundingBoxMin()
-        self.fd.write('%s<if-else id="%d" pos="%d,%d" size="%d,%d">\n' % \
-                          (' ' * self.indent, condition.GetId(), condition.GetX(), condition.GetY(),
-                           bbox[0], bbox[1]))
+        self.fd.write(
+            '%s<if-else id="%d" pos="%d,%d" size="%d,%d">\n' %
+            (' ' *
+             self.indent,
+             condition.GetId(),
+             condition.GetX(),
+             condition.GetY(),
+             bbox[0],
+                bbox[1]))
         text = condition.GetLabel()
         self.indent += 4
         if text:
@@ -2292,24 +2461,34 @@
                               (' ' * self.indent, item.GetId()))
             self.indent -= 4
             self.fd.write('%s</%s>\n' % (' ' * self.indent, b))
-        
+
         self.indent -= 4
         self.fd.write('%s</if-else>\n' % (' ' * self.indent))
 
     def _comment(self, comment):
         """Write comment"""
-        self.fd.write('%s<comment id="%d" pos="%d,%d" size="%d,%d">%s</comment>\n' % \
-                          (' ' * self.indent, comment.GetId(), comment.GetX(), comment.GetY(),
-                           comment.GetWidth(), comment.GetHeight(), EncodeString(comment.GetLabel())))
-        
+        self.fd.write(
+            '%s<comment id="%d" pos="%d,%d" size="%d,%d">%s</comment>\n' %
+            (' ' *
+             self.indent,
+             comment.GetId(),
+             comment.GetX(),
+             comment.GetY(),
+             comment.GetWidth(),
+             comment.GetHeight(),
+             EncodeString(
+                 comment.GetLabel())))
+
+
 class WritePythonFile:
+
     def __init__(self, fd, model):
         """Class for exporting model to Python script
 
         :param fd: file descriptor
         """
-        self.fd     = fd
-        self.model  = model
+        self.fd = fd
+        self.model = model
         self.indent = 4
 
         self._writePython()
@@ -2327,111 +2506,118 @@
             return 'G_OPT_M_DIR'
         elif string == 'region':
             return 'G_OPT_M_REGION'
-        
+
         return ''
 
     def _writePython(self):
         """Write model to file"""
         properties = self.model.GetProperties()
-        
+
         # header
         self.fd.write(
-r"""#!/usr/bin/env python
+            r"""#!/usr/bin/env python
 #
 #%s
 #
 # MODULE:       %s
 #
 # AUTHOR(S):    %s
-#               
+#
 # PURPOSE:      %s
 #
 # DATE:         %s
 #
 #%s
-"""% ('#' * 77,
-       EncodeString(properties['name']),
-       EncodeString(properties['author']),
-       EncodeString('\n# '.join(properties['description'].splitlines())),
-       time.asctime(),
-       '#' * 77))
-        
+""" %
+            ('#' *
+             77,
+             EncodeString(
+                 properties['name']),
+                EncodeString(
+                 properties['author']),
+                EncodeString(
+                 '\n# '.join(
+                     properties['description'].splitlines())),
+                time.asctime(),
+                '#' *
+                77))
+
         # UI
         self.fd.write(
-r"""
+            r"""
 #%%module
 #%% description: %s
 #%%end
-"""% (EncodeString(' '.join(properties['description'].splitlines()))))
+""" % (EncodeString(' '.join(properties['description'].splitlines()))))
 
         variables = self.model.GetVariables()
         for key, data in variables.iteritems():
             otype = self._getStandardizedOption(data['type'])
             self.fd.write(
-r"""
+                r"""
 #%%option %s
 #%% key: %s
 #%% description: %s
 #%% required: yes
-"""% (otype, key, data['description']))
+""" % (otype, key, data['description']))
             if 'value' in data:
                 self.fd.write("#%% answer: %s\n" % data['value'])
             self.fd.write("#% end\n")
-        
+
         # import modules
         self.fd.write(
-r"""
+            r"""
 import sys
 import os
 import atexit
 
 from grass.script import parser, run_command
 """)
-        
+
         # cleanup()
         rast, vect, rast3d, msg = self.model.GetIntermediateData()
         self.fd.write(
-r"""
+            r"""
 def cleanup():
 """)
         if rast:
             self.fd.write(
-r"""  run_command('g.remove', flags='f', type='raster',
+                r"""  run_command('g.remove', flags='f', type='raster',
                       name=%s)
-"""% ','.join(map(lambda x: "'" + x + "'", rast)))
+""" % ','.join(map(lambda x: "'" + x + "'", rast)))
         if vect:
             self.fd.write(
-r"""  run_command('g.remove', flags='f', type='vector',
+                r"""  run_command('g.remove', flags='f', type='vector',
                       name=%s)
-"""% ','.join(map(lambda x: "'" + x + "'", vect)))
+""" % ','.join(map(lambda x: "'" + x + "'", vect)))
         if rast3d:
             self.fd.write(
-r"""  run_command('g.remove', flags='f', type='raster_3d',
+                r"""  run_command('g.remove', flags='f', type='raster_3d',
                       name=%s)
-"""% ','.join(map(lambda x: "'" + x + "'", rast3d)))
+""" % ','.join(map(lambda x: "'" + x + "'", rast3d)))
         if not rast and not vect and not rast3d:
             self.fd.write('    pass\n')
-        
+
         self.fd.write("\ndef main():\n")
         for item in self.model.GetItems():
-            self._writePythonItem(item, variables = self.model.GetVariables())
-        
+            self._writePythonItem(item, variables=self.model.GetVariables())
+
         self.fd.write("\n    return 0\n")
-        
+
         self.fd.write(
-r"""
+            r"""
 if __name__ == "__main__":
     options, flags = parser()
     atexit.register(cleanup)
     sys.exit(main())
 """)
-        
-    def _writePythonItem(self, item, ignoreBlock = True, variables = {}):
+
+    def _writePythonItem(self, item, ignoreBlock=True, variables={}):
         """Write model object to Python file"""
         if isinstance(item, ModelAction):
-            if ignoreBlock and item.GetBlockId(): # ignore items in loops of conditions
+            if ignoreBlock and item.GetBlockId():  # ignore items in loops of conditions
                 return
-            self._writePythonAction(item, variables = variables)
+            self._writePythonAction(item, variables=variables)
         elif isinstance(item, ModelLoop) or isinstance(item, ModelCondition):
             # substitute condition
             cond = item.GetLabel()
@@ -2443,51 +2629,68 @@
                         value = '"' + value + '"'
                     cond = pattern.sub(value, cond)
             if isinstance(item, ModelLoop):
-                condVar, condText = map(lambda x: x.strip(), re.split('\s* in \s*', cond))
+                condVar, condText = map(
+                    lambda x: x.strip(),
+                    re.split('\s* in \s*', cond))
                 cond = "%sfor %s in " % (' ' * self.indent, condVar)
                 if condText[0] == '`' and condText[-1] == '`':
-                    task = GUI(show = None).ParseCommand(cmd = utils.split(condText[1:-1]))
+                    task = GUI(
+                        show=None).ParseCommand(
+                        cmd=utils.split(
+                            condText[
+                                1:-
+                                1]))
                     cond += "grass.read_command("
-                    cond += self._getPythonActionCmd(task, len(cond), variables = [condVar]) + ".splitlines()"
+                    cond += self._getPythonActionCmd(task,
+                                                     len(cond),
+                                                     variables=[condVar]) + ".splitlines()"
                 else:
                     cond += condText
                 self.fd.write('%s:\n' % cond)
                 self.indent += 4
                 variablesLoop = variables.copy()
                 variablesLoop[condVar] = None
-                for action in item.GetItems(self.model.GetItems(objType=ModelAction)):
-                    self._writePythonItem(action, ignoreBlock = False, variables = variablesLoop)
+                for action in item.GetItems(
+                        self.model.GetItems(objType=ModelAction)):
+                    self._writePythonItem(
+                        action, ignoreBlock=False, variables=variablesLoop)
                 self.indent -= 4
             if isinstance(item, ModelCondition):
                 self.fd.write('%sif %s:\n' % (' ' * self.indent, cond))
                 self.indent += 4
                 condItems = item.GetItems()
                 for action in condItems['if']:
-                    self._writePythonItem(action, ignoreBlock = False)
+                    self._writePythonItem(action, ignoreBlock=False)
                 if condItems['else']:
                     self.indent -= 4
                     self.fd.write('%selse:\n' % (' ' * self.indent))
                     self.indent += 4
                     for action in condItems['else']:
-                        self._writePythonItem(action, ignoreBlock = False)
+                        self._writePythonItem(action, ignoreBlock=False)
                 self.indent += 4
         self.fd.write('\n')
         if isinstance(item, ModelComment):
             self._writePythonComment(item)
-        
-    def _writePythonAction(self, item, variables = {}):
+
+    def _writePythonAction(self, item, variables={}):
         """Write model action to Python file"""
-        task = GUI(show = None).ParseCommand(cmd = item.GetLog(string = False))
+        task = GUI(show=None).ParseCommand(cmd=item.GetLog(string=False))
         strcmd = "%srun_command(" % (' ' * self.indent)
-        self.fd.write(strcmd + self._getPythonActionCmd(task, len(strcmd), variables) + '\n')
-        
-    def _getPythonActionCmd(self, task, cmdIndent, variables = {}):
+        self.fd.write(
+            strcmd +
+            self._getPythonActionCmd(
+                task,
+                len(strcmd),
+                variables) +
+            '\n')
+
+    def _getPythonActionCmd(self, task, cmdIndent, variables={}):
         opts = task.get_options()
-        
+
         ret = ''
         flags = ''
         params = list()
-        
+
         for f in opts['flags']:
             if f.get('value', False):
                 name = f.get('name', '')
@@ -2495,14 +2698,14 @@
                     params.append('%s = True' % name)
                 else:
                     flags += name
-        
+
         for p in opts['params']:
             name = p.get('name', None)
             value = p.get('value', None)
             if name and value:
                 ptype = p.get('type', 'string')
                 foundVar = False
-                
+
                 for var in sorted(variables, key=len, reverse=True):
                     data = variables[var]
                     if '%' + var in value:
@@ -2513,7 +2716,7 @@
                     params.append("%s = %s" % (name, value))
                 else:
                     params.append('%s = "%s"' % (name, value))
-        
+
         ret += '"%s"' % task.get_name()
         if flags:
             ret += ",\n%sflags = '%s'" % (' ' * cmdIndent, flags)
@@ -2524,7 +2727,7 @@
             ret += "%s%s)" % (' ' * cmdIndent, params[-1])
         else:
             ret += ")"
-        
+
         return ret
 
     def _writePythonComment(self, item):
@@ -2538,22 +2741,22 @@
         :param string: string to be modified
         :param variable: variable to be substituted
         :param data: data related to the variable
-        
+
         :return: modified string
         """
         result = ''
-        ss = re.split("\w*(%"+variable+")w*", string)
-        
+        ss = re.split("\w*(%" + variable + ")w*", string)
+
         if not ss[0] and not ss[-1]:
             if data:
                 return "options['%s']" % variable
             else:
                 return variable
-        
+
         for s in ss:
             if not s or s == '"':
                 continue
-            
+
             if s == '%' + variable:
                 if data:
                     result += "+options['%s']+" % variable
@@ -2561,74 +2764,84 @@
                     result += '+%s+' % variable
             else:
                 result += '"' + s
-                if not s.endswith(']'): # options
+                if not s.endswith(']'):  # options
                     result += '"'
-        
+
         return result.strip('+')
 
 
 class ModelParamDialog(wx.Dialog):
-    def __init__(self, parent, model, params, id = wx.ID_ANY, title = _("Model parameters"),
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
+
+    def __init__(
+            self, parent, model, params, id=wx.ID_ANY,
+            title=_("Model parameters"),
+            style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
         """Model parameters dialog
         """
         self.parent = parent
-        self._model  = model
+        self._model = model
         self.params = params
-        self.tasks  = list() # list of tasks/pages
-        
-        wx.Dialog.__init__(self, parent = parent, id = id, title = title, style = style, **kwargs)
-        
-        self.notebook = GNotebook(parent = self, 
-                                  style = globalvar.FNPageDStyle)
-        
+        self.tasks = list()  # list of tasks/pages
+
+        wx.Dialog.__init__(
+            self,
+            parent=parent,
+            id=id,
+            title=title,
+            style=style,
+            **kwargs)
+
+        self.notebook = GNotebook(parent=self,
+                                  style=globalvar.FNPageDStyle)
+
         panel = self._createPages()
         wx.CallAfter(self.notebook.SetSelection, 0)
 
         # intermediate data?
-        self.interData = wx.CheckBox(parent = self, label = _("Delete intermediate data when finish"))
+        self.interData = wx.CheckBox(parent=self, label=_(
+            "Delete intermediate data when finish"))
         self.interData.SetValue(True)
         rast, vect, rast3d, msg = self._model.GetIntermediateData()
         if not rast and not vect and not rast3d:
             self.interData.Hide()
-        
-        self.btnCancel = wx.Button(parent = self, id = wx.ID_CANCEL)
-        self.btnRun    = wx.Button(parent = self, id = wx.ID_OK,
-                                   label = _("&Run"))
+
+        self.btnCancel = wx.Button(parent=self, id=wx.ID_CANCEL)
+        self.btnRun = wx.Button(parent=self, id=wx.ID_OK,
+                                label=_("&Run"))
         self.btnRun.SetDefault()
-        
+
         self._layout()
-        
+
         size = self.GetBestSize()
         self.SetMinSize(size)
         self.SetSize((size.width, size.height +
                       panel.constrained_size[1] -
                       panel.panelMinHeight))
-                
+
     def _layout(self):
         btnSizer = wx.StdDialogButtonSizer()
         btnSizer.AddButton(self.btnCancel)
         btnSizer.AddButton(self.btnRun)
         btnSizer.Realize()
-        
+
         mainSizer = wx.BoxSizer(wx.VERTICAL)
-        mainSizer.Add(item = self.notebook, proportion = 1,
-                      flag = wx.EXPAND)
+        mainSizer.Add(item=self.notebook, proportion=1,
+                      flag=wx.EXPAND)
         if self.interData.IsShown():
-            mainSizer.Add(item = self.interData, proportion = 0,
-                          flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
+            mainSizer.Add(item=self.interData, proportion=0,
+                          flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
 
-            mainSizer.Add(item = wx.StaticLine(parent = self, id = wx.ID_ANY,
-                                               style = wx.LI_HORIZONTAL),
-                          proportion = 0,
-                          flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5) 
-        
-        mainSizer.Add(item = btnSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
-        
+            mainSizer.Add(item=wx.StaticLine(parent=self, id=wx.ID_ANY,
+                                             style=wx.LI_HORIZONTAL),
+                          proportion=0,
+                          flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5)
+
+        mainSizer.Add(item=btnSizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
+
         self.SetSizer(mainSizer)
         mainSizer.Fit(self)
-        
+
     def _createPages(self):
         """Create for each parameterized module its own page"""
         nameOrdered = [''] * len(self.params.keys())
@@ -2639,23 +2852,23 @@
             panel = self._createPage(name, params)
             if name == 'variables':
                 name = _('Variables')
-            self.notebook.AddPage(page = panel, text = name)
-        
+            self.notebook.AddPage(page=panel, text=name)
+
         return panel
-    
+
     def _createPage(self, name, params):
         """Define notebook page"""
         if name in globalvar.grassCmd:
             task = gtask.grassTask(name)
         else:
             task = gtask.grassTask()
-        task.flags  = params['flags']
+        task.flags = params['flags']
         task.params = params['params']
-        
-        panel = CmdPanel(parent = self, id = wx.ID_ANY, task = task,
-                         giface = GraphicalModelerGrassInterface(self._model))
+
+        panel = CmdPanel(parent=self, id=wx.ID_ANY, task=task,
+                         giface=GraphicalModelerGrassInterface(self._model))
         self.tasks.append(task)
-        
+
         return panel
 
     def GetErrors(self):
@@ -2663,12 +2876,12 @@
         errList = list()
         for task in self.tasks:
             errList += task.get_cmd_error()
-        
+
         return errList
 
     def DeleteIntermediateData(self):
         """Check if to detele intermediate data"""
         if self.interData.IsShown() and self.interData.IsChecked():
             return True
-        
+
         return False

Modified: grass/trunk/gui/wxpython/gmodeler/preferences.py
===================================================================
--- grass/trunk/gui/wxpython/gmodeler/preferences.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gmodeler/preferences.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -16,613 +16,755 @@
 """
 
 import wx
-import wx.lib.colourselect    as csel
+import wx.lib.colourselect as csel
 
-from core                 import globalvar
+from core import globalvar
 from gui_core.preferences import PreferencesBaseDialog
-from core.settings        import UserSettings
+from core.settings import UserSettings
 from core.utils import _
 
+
 class PreferencesDialog(PreferencesBaseDialog):
     """User preferences dialog"""
-    def __init__(self, parent, giface, settings = UserSettings,
-                 title = _("Modeler settings")):
-        
-        PreferencesBaseDialog.__init__(self, parent = parent, giface = giface, title = title,
-                                       settings = settings)
-        
+
+    def __init__(self, parent, giface, settings=UserSettings,
+                 title=_("Modeler settings")):
+
+        PreferencesBaseDialog.__init__(
+            self,
+            parent=parent,
+            giface=giface,
+            title=title,
+            settings=settings)
+
         # create notebook pages
         self._createGeneralPage(self.notebook)
         self._createActionPage(self.notebook)
         self._createDataPage(self.notebook)
         self._createLoopPage(self.notebook)
         self._createCommentPage(self.notebook)
-        
+
         self.SetMinSize(self.GetBestSize())
         self.SetSize(self.size)
 
     def _createGeneralPage(self, notebook):
         """Create notebook page for action settings"""
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY)
-        notebook.AddPage(page = panel, text = _("General"))
-        
+        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
+        notebook.AddPage(page=panel, text=_("General"))
+
         # colors
         border = wx.BoxSizer(wx.VERTICAL)
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                              label = " %s " % _("Item properties"))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % _("Item properties"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
-        gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
-        
+
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
+
         row = 0
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                           label = _("Disabled:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Disabled:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        rColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
-                                   colour = self.settings.Get(group='modeler', key='disabled', subkey='color'),
-                                   size = globalvar.DIALOG_COLOR_SIZE)
+                      pos=(row, 0))
+        rColor = csel.ColourSelect(
+            parent=panel,
+            id=wx.ID_ANY,
+            colour=self.settings.Get(
+                group='modeler',
+                key='disabled',
+                subkey='color'),
+            size=globalvar.DIALOG_COLOR_SIZE)
         rColor.SetName('GetColour')
         self.winId['modeler:disabled:color'] = rColor.GetId()
-        
-        gridSizer.Add(item = rColor,
-                      flag = wx.ALIGN_RIGHT |
+
+        gridSizer.Add(item=rColor,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
-        
+                      pos=(row, 1))
+
         gridSizer.AddGrowableCol(0)
-        sizer.Add(item = gridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.LEFT |
+                   wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
 
         panel.SetSizer(border)
-        
+
         return panel
 
     def _createActionPage(self, notebook):
         """Create notebook page for action settings"""
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY)
-        notebook.AddPage(page = panel, text = _("Command"))
-        
+        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
+        notebook.AddPage(page=panel, text=_("Command"))
+
         # colors
         border = wx.BoxSizer(wx.VERTICAL)
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                              label = " %s " % _("Color"))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % _("Color"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
-        gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
-        
+
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
+
         row = 0
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Valid:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Valid:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        vColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
-                                   colour = self.settings.Get(group='modeler', key='action', subkey=('color', 'valid')),
-                                   size = globalvar.DIALOG_COLOR_SIZE)
+                      pos=(row, 0))
+        vColor = csel.ColourSelect(
+            parent=panel, id=wx.ID_ANY, colour=self.settings.Get(
+                group='modeler', key='action', subkey=(
+                    'color', 'valid')), size=globalvar.DIALOG_COLOR_SIZE)
         vColor.SetName('GetColour')
         self.winId['modeler:action:color:valid'] = vColor.GetId()
-        
-        gridSizer.Add(item = vColor,
-                      flag = wx.ALIGN_RIGHT |
+
+        gridSizer.Add(item=vColor,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
+                      pos=(row, 1))
 
         row += 1
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Invalid:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Invalid:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        iColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
-                                   colour = self.settings.Get(group='modeler', key='action', subkey=('color', 'invalid')),
-                                   size = globalvar.DIALOG_COLOR_SIZE)
+                      pos=(row, 0))
+        iColor = csel.ColourSelect(
+            parent=panel, id=wx.ID_ANY, colour=self.settings.Get(
+                group='modeler', key='action', subkey=(
+                    'color', 'invalid')), size=globalvar.DIALOG_COLOR_SIZE)
         iColor.SetName('GetColour')
         self.winId['modeler:action:color:invalid'] = iColor.GetId()
-        
-        gridSizer.Add(item = iColor,
-                      flag = wx.ALIGN_RIGHT |
+
+        gridSizer.Add(item=iColor,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
+                      pos=(row, 1))
 
         row += 1
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Running:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Running:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        rColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
-                                   colour = self.settings.Get(group='modeler', key='action', subkey=('color', 'running')),
-                                   size = globalvar.DIALOG_COLOR_SIZE)
+                      pos=(row, 0))
+        rColor = csel.ColourSelect(
+            parent=panel, id=wx.ID_ANY, colour=self.settings.Get(
+                group='modeler', key='action', subkey=(
+                    'color', 'running')), size=globalvar.DIALOG_COLOR_SIZE)
         rColor.SetName('GetColour')
         self.winId['modeler:action:color:running'] = rColor.GetId()
-        
-        gridSizer.Add(item = rColor,
-                      flag = wx.ALIGN_RIGHT |
+
+        gridSizer.Add(item=rColor,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
-        
+                      pos=(row, 1))
+
         gridSizer.AddGrowableCol(0)
-        sizer.Add(item = gridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
-        
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.LEFT |
+                   wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
+
         # size
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                              label = " %s " % _("Shape size"))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % _("Shape size"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
-        gridSizer = wx.GridBagSizer (hgap=3, vgap=3)
 
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
+
         row = 0
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Width:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Width:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        
-        width = wx.SpinCtrl(parent = panel, id = wx.ID_ANY,
-                            min = 0, max = 500,
-                            initial = self.settings.Get(group='modeler', key='action', subkey=('size', 'width')))
+                      pos=(row, 0))
+
+        width = wx.SpinCtrl(
+            parent=panel,
+            id=wx.ID_ANY,
+            min=0,
+            max=500,
+            initial=self.settings.Get(
+                group='modeler',
+                key='action',
+                subkey=(
+                    'size',
+                    'width')))
         width.SetName('GetValue')
         self.winId['modeler:action:size:width'] = width.GetId()
-        
-        gridSizer.Add(item = width,
-                      flag = wx.ALIGN_RIGHT |
+
+        gridSizer.Add(item=width,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
+                      pos=(row, 1))
 
         row += 1
-        gridSizer.Add(item = wx.StaticText(parent=panel, id=wx.ID_ANY,
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
                                          label=_("Height:")),
-                      flag = wx.ALIGN_LEFT |
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
                       pos=(row, 0))
-        
-        height = wx.SpinCtrl(parent = panel, id = wx.ID_ANY,
-                             min = 0, max = 500,
-                             initial = self.settings.Get(group='modeler', key='action', subkey=('size', 'height')))
+
+        height = wx.SpinCtrl(
+            parent=panel,
+            id=wx.ID_ANY,
+            min=0,
+            max=500,
+            initial=self.settings.Get(
+                group='modeler',
+                key='action',
+                subkey=(
+                    'size',
+                    'height')))
         height.SetName('GetValue')
         self.winId['modeler:action:size:height'] = height.GetId()
-        
-        gridSizer.Add(item = height,
-                      flag = wx.ALIGN_RIGHT |
+
+        gridSizer.Add(item=height,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
-        
+                      pos=(row, 1))
+
         gridSizer.AddGrowableCol(0)
-        sizer.Add(item=gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)
-        border.Add(item=sizer, proportion=0, flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
-                
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.LEFT |
+                   wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
+
         panel.SetSizer(border)
-        
+
         return panel
 
     def _createDataPage(self, notebook):
         """Create notebook page for data settings"""
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY)
-        notebook.AddPage(page = panel, text = _("Data"))
-        
+        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
+        notebook.AddPage(page=panel, text=_("Data"))
+
         # colors
         border = wx.BoxSizer(wx.VERTICAL)
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                              label = " %s " % _("Type"))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % _("Type"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
-        gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
-        
+
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
+
         row = 0
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Raster:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Raster:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        rColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
-                                   colour = self.settings.Get(group='modeler', key='data', subkey=('color', 'raster')),
-                                   size = globalvar.DIALOG_COLOR_SIZE)
+                      pos=(row, 0))
+        rColor = csel.ColourSelect(
+            parent=panel, id=wx.ID_ANY, colour=self.settings.Get(
+                group='modeler', key='data', subkey=(
+                    'color', 'raster')), size=globalvar.DIALOG_COLOR_SIZE)
         rColor.SetName('GetColour')
         self.winId['modeler:data:color:raster'] = rColor.GetId()
-        
-        gridSizer.Add(item = rColor,
-                      flag = wx.ALIGN_RIGHT |
+
+        gridSizer.Add(item=rColor,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
+                      pos=(row, 1))
 
         row += 1
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("3D raster:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("3D raster:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        r3Color = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
-                                    colour = self.settings.Get(group='modeler', key='data', subkey=('color', 'raster3d')),
-                                    size = globalvar.DIALOG_COLOR_SIZE)
+                      pos=(row, 0))
+        r3Color = csel.ColourSelect(
+            parent=panel, id=wx.ID_ANY, colour=self.settings.Get(
+                group='modeler', key='data', subkey=(
+                    'color', 'raster3d')), size=globalvar.DIALOG_COLOR_SIZE)
         r3Color.SetName('GetColour')
         self.winId['modeler:data:color:raster3d'] = r3Color.GetId()
-        
-        gridSizer.Add(item = r3Color,
-                      flag = wx.ALIGN_RIGHT |
+
+        gridSizer.Add(item=r3Color,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
-        
+                      pos=(row, 1))
+
         row += 1
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Vector:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Vector:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        vColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
-                                   colour = self.settings.Get(group='modeler', key='data', subkey=('color', 'vector')),
-                                   size = globalvar.DIALOG_COLOR_SIZE)
+                      pos=(row, 0))
+        vColor = csel.ColourSelect(
+            parent=panel, id=wx.ID_ANY, colour=self.settings.Get(
+                group='modeler', key='data', subkey=(
+                    'color', 'vector')), size=globalvar.DIALOG_COLOR_SIZE)
         vColor.SetName('GetColour')
         self.winId['modeler:data:color:vector'] = vColor.GetId()
-        
-        gridSizer.Add(item = vColor,
-                      flag = wx.ALIGN_RIGHT |
+
+        gridSizer.Add(item=vColor,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
+                      pos=(row, 1))
 
         row += 1
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Table:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Table:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        tColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
-                                   colour = self.settings.Get(group='modeler', key='data', subkey=('color', 'dbtable')),
-                                   size = globalvar.DIALOG_COLOR_SIZE)
+                      pos=(row, 0))
+        tColor = csel.ColourSelect(
+            parent=panel, id=wx.ID_ANY, colour=self.settings.Get(
+                group='modeler', key='data', subkey=(
+                    'color', 'dbtable')), size=globalvar.DIALOG_COLOR_SIZE)
         tColor.SetName('GetColour')
         self.winId['modeler:data:color:dbtable'] = tColor.GetId()
-        
-        gridSizer.Add(item = tColor,
-                      flag = wx.ALIGN_RIGHT |
+
+        gridSizer.Add(item=tColor,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
+                      pos=(row, 1))
 
         gridSizer.AddGrowableCol(0)
-        sizer.Add(item = gridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.LEFT |
+                   wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
 
         # size
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                              label = " %s " % _("Shape size"))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % _("Shape size"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
-        gridSizer = wx.GridBagSizer (hgap=3, vgap=3)
-        
+
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
+
         row = 0
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Width:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Width:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        
-        width = wx.SpinCtrl(parent = panel, id = wx.ID_ANY,
-                            min = 0, max = 500,
-                            initial = self.settings.Get(group='modeler', key='data', subkey=('size', 'width')))
+                      pos=(row, 0))
+
+        width = wx.SpinCtrl(
+            parent=panel,
+            id=wx.ID_ANY,
+            min=0,
+            max=500,
+            initial=self.settings.Get(
+                group='modeler',
+                key='data',
+                subkey=(
+                    'size',
+                    'width')))
         width.SetName('GetValue')
         self.winId['modeler:data:size:width'] = width.GetId()
-        
-        gridSizer.Add(item = width,
-                      flag = wx.ALIGN_RIGHT |
+
+        gridSizer.Add(item=width,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
+                      pos=(row, 1))
 
         row += 1
-        gridSizer.Add(item = wx.StaticText(parent=panel, id=wx.ID_ANY,
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
                                          label=_("Height:")),
-                      flag = wx.ALIGN_LEFT |
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
                       pos=(row, 0))
-        
-        height = wx.SpinCtrl(parent = panel, id = wx.ID_ANY,
-                             min = 0, max = 500,
-                             initial = self.settings.Get(group='modeler', key='data', subkey=('size', 'height')))
+
+        height = wx.SpinCtrl(
+            parent=panel,
+            id=wx.ID_ANY,
+            min=0,
+            max=500,
+            initial=self.settings.Get(
+                group='modeler',
+                key='data',
+                subkey=(
+                    'size',
+                    'height')))
         height.SetName('GetValue')
         self.winId['modeler:data:size:height'] = height.GetId()
-        
-        gridSizer.Add(item = height,
-                      flag = wx.ALIGN_RIGHT |
+
+        gridSizer.Add(item=height,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
-        
+                      pos=(row, 1))
+
         gridSizer.AddGrowableCol(0)
-        sizer.Add(item=gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)
-        border.Add(item=sizer, proportion=0, flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
-        
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.LEFT |
+                   wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
+
         panel.SetSizer(border)
-        
+
         return panel
 
     def _createLoopPage(self, notebook):
         """Create notebook page for loop settings"""
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY)
-        notebook.AddPage(page = panel, text = _("Loop"))
-        
+        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
+        notebook.AddPage(page=panel, text=_("Loop"))
+
         # colors
         border = wx.BoxSizer(wx.VERTICAL)
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                              label = " %s " % _("Color"))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % _("Color"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
-        gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
-        
+
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
+
         row = 0
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Valid:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Valid:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        vColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
-                                   colour = self.settings.Get(group='modeler', key='loop', subkey=('color', 'valid')),
-                                   size = globalvar.DIALOG_COLOR_SIZE)
+                      pos=(row, 0))
+        vColor = csel.ColourSelect(
+            parent=panel, id=wx.ID_ANY, colour=self.settings.Get(
+                group='modeler', key='loop', subkey=(
+                    'color', 'valid')), size=globalvar.DIALOG_COLOR_SIZE)
         vColor.SetName('GetColour')
         self.winId['modeler:loop:color:valid'] = vColor.GetId()
-        
-        gridSizer.Add(item = vColor,
-                      flag = wx.ALIGN_RIGHT |
+
+        gridSizer.Add(item=vColor,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
-        
+                      pos=(row, 1))
+
         gridSizer.AddGrowableCol(0)
-        sizer.Add(item = gridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
-        
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.LEFT |
+                   wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
+
         # size
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                              label = " %s " % _("Shape size"))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % _("Shape size"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
-        gridSizer = wx.GridBagSizer (hgap=3, vgap=3)
 
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
+
         row = 0
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Width:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Width:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        
-        width = wx.SpinCtrl(parent = panel, id = wx.ID_ANY,
-                            min = 0, max = 500,
-                            initial = self.settings.Get(group='modeler', key='loop', subkey=('size', 'width')))
+                      pos=(row, 0))
+
+        width = wx.SpinCtrl(
+            parent=panel,
+            id=wx.ID_ANY,
+            min=0,
+            max=500,
+            initial=self.settings.Get(
+                group='modeler',
+                key='loop',
+                subkey=(
+                    'size',
+                    'width')))
         width.SetName('GetValue')
         self.winId['modeler:loop:size:width'] = width.GetId()
-        
-        gridSizer.Add(item = width,
-                      flag = wx.ALIGN_RIGHT |
+
+        gridSizer.Add(item=width,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
+                      pos=(row, 1))
 
         row += 1
-        gridSizer.Add(item = wx.StaticText(parent=panel, id=wx.ID_ANY,
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
                                          label=_("Height:")),
-                      flag = wx.ALIGN_LEFT |
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
                       pos=(row, 0))
-        
-        height = wx.SpinCtrl(parent = panel, id = wx.ID_ANY,
-                             min = 0, max = 500,
-                             initial = self.settings.Get(group='modeler', key='loop', subkey=('size', 'height')))
+
+        height = wx.SpinCtrl(
+            parent=panel,
+            id=wx.ID_ANY,
+            min=0,
+            max=500,
+            initial=self.settings.Get(
+                group='modeler',
+                key='loop',
+                subkey=(
+                    'size',
+                    'height')))
         height.SetName('GetValue')
         self.winId['modeler:loop:size:height'] = height.GetId()
-        
-        gridSizer.Add(item = height,
-                      flag = wx.ALIGN_RIGHT |
+
+        gridSizer.Add(item=height,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
-        
+                      pos=(row, 1))
+
         gridSizer.AddGrowableCol(0)
-        sizer.Add(item=gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)
-        border.Add(item=sizer, proportion=0, flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
-                
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.LEFT |
+                   wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
+
         panel.SetSizer(border)
-        
+
         return panel
 
     def _createCommentPage(self, notebook):
         """Create notebook page for comment settings"""
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY)
-        notebook.AddPage(page = panel, text = _("Comment"))
-        
+        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
+        notebook.AddPage(page=panel, text=_("Comment"))
+
         # colors
         border = wx.BoxSizer(wx.VERTICAL)
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                              label = " %s " % _("Color"))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % _("Color"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
-        gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
-        
+
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
+
         row = 0
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Valid:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Valid:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        vColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
-                                   colour = self.settings.Get(group='modeler', key='comment', subkey='color'),
-                                   size = globalvar.DIALOG_COLOR_SIZE)
+                      pos=(row, 0))
+        vColor = csel.ColourSelect(
+            parent=panel,
+            id=wx.ID_ANY,
+            colour=self.settings.Get(
+                group='modeler',
+                key='comment',
+                subkey='color'),
+            size=globalvar.DIALOG_COLOR_SIZE)
         vColor.SetName('GetColour')
         self.winId['modeler:comment:color'] = vColor.GetId()
-        
-        gridSizer.Add(item = vColor,
-                      flag = wx.ALIGN_RIGHT |
+
+        gridSizer.Add(item=vColor,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
-        
+                      pos=(row, 1))
+
         gridSizer.AddGrowableCol(0)
-        sizer.Add(item = gridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
-        
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.LEFT |
+                   wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
+
         # size
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                              label = " %s " % _("Shape size"))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % _("Shape size"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
-        gridSizer = wx.GridBagSizer (hgap=3, vgap=3)
 
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
+
         row = 0
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Width:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Width:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        
-        width = wx.SpinCtrl(parent = panel, id = wx.ID_ANY,
-                            min = 0, max = 500,
-                            initial = self.settings.Get(group='modeler', key='comment', subkey=('size', 'width')))
+                      pos=(row, 0))
+
+        width = wx.SpinCtrl(
+            parent=panel,
+            id=wx.ID_ANY,
+            min=0,
+            max=500,
+            initial=self.settings.Get(
+                group='modeler',
+                key='comment',
+                subkey=(
+                    'size',
+                    'width')))
         width.SetName('GetValue')
         self.winId['modeler:comment:size:width'] = width.GetId()
-        
-        gridSizer.Add(item = width,
-                      flag = wx.ALIGN_RIGHT |
+
+        gridSizer.Add(item=width,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
+                      pos=(row, 1))
 
         row += 1
-        gridSizer.Add(item = wx.StaticText(parent=panel, id=wx.ID_ANY,
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
                                          label=_("Height:")),
-                      flag = wx.ALIGN_LEFT |
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
                       pos=(row, 0))
-        
-        height = wx.SpinCtrl(parent = panel, id = wx.ID_ANY,
-                             min = 0, max = 500,
-                             initial = self.settings.Get(group='modeler', key='comment', subkey=('size', 'height')))
+
+        height = wx.SpinCtrl(
+            parent=panel,
+            id=wx.ID_ANY,
+            min=0,
+            max=500,
+            initial=self.settings.Get(
+                group='modeler',
+                key='comment',
+                subkey=(
+                    'size',
+                    'height')))
         height.SetName('GetValue')
         self.winId['modeler:comment:size:height'] = height.GetId()
-        
-        gridSizer.Add(item = height,
-                      flag = wx.ALIGN_RIGHT |
+
+        gridSizer.Add(item=height,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
-        
+                      pos=(row, 1))
+
         gridSizer.AddGrowableCol(0)
-        sizer.Add(item=gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)
-        border.Add(item=sizer, proportion=0, flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
-                
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.LEFT |
+                   wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
+
         panel.SetSizer(border)
-        
+
         return panel
 
     def OnApply(self, event):
         """Button 'Apply' pressed"""
         PreferencesBaseDialog.OnApply(self, event)
-        
+
         self.parent.GetModel().Update()
         self.parent.GetCanvas().Refresh()
 
     def OnSave(self, event):
         """Button 'Save' pressed"""
         PreferencesBaseDialog.OnSave(self, event)
-        
+
         self.parent.GetModel().Update()
         self.parent.GetCanvas().Refresh()
 
+
 class PropertiesDialog(wx.Dialog):
     """Model properties dialog
     """
-    def __init__(self, parent, id = wx.ID_ANY,
-                 title = _('Model properties'),
-                 size = (350, 400),
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
-        wx.Dialog.__init__(self, parent, id, title, size = size,
-                           style = style)
-        
-        self.metaBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
+
+    def __init__(self, parent, id=wx.ID_ANY,
+                 title=_('Model properties'),
+                 size=(350, 400),
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
+        wx.Dialog.__init__(self, parent, id, title, size=size,
+                           style=style)
+
+        self.metaBox = wx.StaticBox(parent=self, id=wx.ID_ANY,
                                     label=" %s " % _("Metadata"))
-        self.cmdBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
+        self.cmdBox = wx.StaticBox(parent=self, id=wx.ID_ANY,
                                    label=" %s " % _("Commands"))
-        
-        self.name = wx.TextCtrl(parent = self, id = wx.ID_ANY,
-                                size = (300, 25))
-        self.desc = wx.TextCtrl(parent = self, id = wx.ID_ANY,
-                                style = wx.TE_MULTILINE,
-                                size = (300, 50))
-        self.author = wx.TextCtrl(parent = self, id = wx.ID_ANY,
-                                size = (300, 25))
-        
+
+        self.name = wx.TextCtrl(parent=self, id=wx.ID_ANY,
+                                size=(300, 25))
+        self.desc = wx.TextCtrl(parent=self, id=wx.ID_ANY,
+                                style=wx.TE_MULTILINE,
+                                size=(300, 50))
+        self.author = wx.TextCtrl(parent=self, id=wx.ID_ANY,
+                                  size=(300, 25))
+
         # commands
-        self.overwrite = wx.CheckBox(parent = self, id=wx.ID_ANY,
-                                     label=_("Allow output files to overwrite existing files"))
-        self.overwrite.SetValue(UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))
-        
+        self.overwrite = wx.CheckBox(parent=self, id=wx.ID_ANY, label=_(
+            "Allow output files to overwrite existing files"))
+        self.overwrite.SetValue(
+            UserSettings.Get(
+                group='cmd',
+                key='overwrite',
+                subkey='enabled'))
+
         # buttons
-        self.btnOk     = wx.Button(self, wx.ID_OK)
+        self.btnOk = wx.Button(self, wx.ID_OK)
         self.btnCancel = wx.Button(self, wx.ID_CANCEL)
         self.btnOk.SetDefault()
-        
+
         self.btnOk.SetToolTipString(_("Apply properties"))
         self.btnOk.SetDefault()
         self.btnCancel.SetToolTipString(_("Close dialog and ignore changes"))
-        
+
         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
-        
+
         self._layout()
 
     def _layout(self):
         metaSizer = wx.StaticBoxSizer(self.metaBox, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(hgap = 3, vgap = 3)
-        gridSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
-                                         label = _("Name:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
+        gridSizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY,
+                                         label=_("Name:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (0, 0))
-        gridSizer.Add(item = self.name,
-                      flag = wx.ALIGN_LEFT |
+                      pos=(0, 0))
+        gridSizer.Add(item=self.name,
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
-                      pos = (0, 1))
-        gridSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
-                                         label = _("Description:")),
-                      flag = wx.ALIGN_LEFT |
+                      pos=(0, 1))
+        gridSizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY,
+                                         label=_("Description:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (1, 0))
-        gridSizer.Add(item = self.desc,
-                      flag = wx.ALIGN_LEFT |
+                      pos=(1, 0))
+        gridSizer.Add(item=self.desc,
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
-                      pos = (1, 1))
-        gridSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
-                                         label = _("Author(s):")),
-                      flag = wx.ALIGN_LEFT |
+                      pos=(1, 1))
+        gridSizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY,
+                                         label=_("Author(s):")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (2, 0))
-        gridSizer.Add(item = self.author,
-                      flag = wx.ALIGN_LEFT |
+                      pos=(2, 0))
+        gridSizer.Add(item=self.author,
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
-                      pos = (2, 1))
+                      pos=(2, 1))
         gridSizer.AddGrowableCol(1)
         gridSizer.AddGrowableRow(1)
-        metaSizer.Add(item = gridSizer, proportion = 1, flag = wx.EXPAND)
-        
+        metaSizer.Add(item=gridSizer, proportion=1, flag=wx.EXPAND)
+
         cmdSizer = wx.StaticBoxSizer(self.cmdBox, wx.VERTICAL)
-        cmdSizer.Add(item = self.overwrite,
-                     flag = wx.EXPAND | wx.ALL, border = 3)
-        
+        cmdSizer.Add(item=self.overwrite,
+                     flag=wx.EXPAND | wx.ALL, border=3)
+
         btnStdSizer = wx.StdDialogButtonSizer()
         btnStdSizer.AddButton(self.btnCancel)
         btnStdSizer.AddButton(self.btnOk)
         btnStdSizer.Realize()
-        
+
         mainSizer = wx.BoxSizer(wx.VERTICAL)
         mainSizer.Add(item=metaSizer, proportion=1,
                       flag=wx.EXPAND | wx.ALL, border=5)
-        mainSizer.Add(item=cmdSizer, proportion=0,
-                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
+        mainSizer.Add(
+            item=cmdSizer,
+            proportion=0,
+            flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+            border=5)
         mainSizer.Add(item=btnStdSizer, proportion=0,
                       flag=wx.EXPAND | wx.ALL | wx.ALIGN_RIGHT, border=5)
-        
+
         self.SetSizer(mainSizer)
         mainSizer.Fit(self)
 
     def OnCloseWindow(self, event):
         self.Hide()
-        
+
     def GetValues(self):
         """Get values"""
-        return { 'name'        : self.name.GetValue(),
-                 'description' : self.desc.GetValue(),
-                 'author'      : self.author.GetValue(),
-                 'overwrite'   : self.overwrite.IsChecked() }
-    
+        return {'name': self.name.GetValue(),
+                'description': self.desc.GetValue(),
+                'author': self.author.GetValue(),
+                'overwrite': self.overwrite.IsChecked()}
+
     def Init(self, prop):
         """Initialize dialog"""
         self.name.SetValue(prop['name'])

Modified: grass/trunk/gui/wxpython/gmodeler/toolbars.py
===================================================================
--- grass/trunk/gui/wxpython/gmodeler/toolbars.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gmodeler/toolbars.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -19,15 +19,17 @@
 
 import wx
 
-from core              import globalvar
+from core import globalvar
 from core.utils import _
 from gui_core.toolbars import BaseToolbar, BaseIcons
 
-from icons.icon        import MetaIcon
+from icons.icon import MetaIcon
 
+
 class ModelerToolbar(BaseToolbar):
     """Graphical modeler toolbaro (see gmodeler.py)
     """
+
     def __init__(self, parent):
         BaseToolbar.__init__(self, parent)
 
@@ -36,47 +38,47 @@
             parent.SetToolBar(self)
 
         self.InitToolbar(self._toolbarData())
-        
+
         # realize the toolbar
         self.Realize()
-        
+
     def _toolbarData(self):
         """Toolbar data"""
         icons = {
-            'new'        : MetaIcon(img = 'create',
-                                    label = _('Create new model (Ctrl+N)')),
-            'open'       : MetaIcon(img = 'open',
-                                    label = _('Load model from file (Ctrl+O)')),
-            'save'       : MetaIcon(img = 'save',
-                                    label = _('Save current model to file (Ctrl+S)')),
-            'toImage'    : MetaIcon(img = 'image-export',
-                                    label = _('Export model to image')),
-            'toPython'   : MetaIcon(img = 'python-export',
-                                    label = _('Export model to Python script')),
-            'actionAdd'  : MetaIcon(img = 'module-add',
-                                    label = _('Add command (GRASS module) to model')),
-            'dataAdd'    : MetaIcon(img = 'data-add',
-                                    label = _('Add data to model')),
-            'relation'   : MetaIcon(img = 'relation-create',
-                                    label = _('Manually define relation between data and commands')),
-            'loop'       : MetaIcon(img = 'loop-add',
-                                    label = _('Add loop/series to model')),
-            'comment'    : MetaIcon(img = 'label-add',
-                                    label = _('Add comment to model')),
-            'run'        : MetaIcon(img = 'execute',
-                                    label = _('Run model')),
-            'validate'   : MetaIcon(img = 'check',
-                                    label = _('Validate model')),
-            'settings'   : BaseIcons['settings'].SetLabel(_('Modeler settings')),
-            'properties' : MetaIcon(img = 'options',
-                                    label = _('Show model properties')),
-            'variables'  : MetaIcon(img = 'modeler-variables',
-                                    label = _('Manage model variables')),
-            'redraw'     : MetaIcon(img = 'redraw',
-                                    label = _('Redraw model canvas')),
-            'quit'       : BaseIcons['quit'].SetLabel(_('Quit Graphical Modeler')),
-            }
-        
+            'new': MetaIcon(img='create',
+                            label=_('Create new model (Ctrl+N)')),
+            'open': MetaIcon(img='open',
+                             label=_('Load model from file (Ctrl+O)')),
+            'save': MetaIcon(img='save',
+                             label=_('Save current model to file (Ctrl+S)')),
+            'toImage': MetaIcon(img='image-export',
+                                label=_('Export model to image')),
+            'toPython': MetaIcon(img='python-export',
+                                 label=_('Export model to Python script')),
+            'actionAdd': MetaIcon(img='module-add',
+                                  label=_('Add command (GRASS module) to model')),
+            'dataAdd': MetaIcon(img='data-add',
+                                label=_('Add data to model')),
+            'relation': MetaIcon(img='relation-create',
+                                 label=_('Manually define relation between data and commands')),
+            'loop': MetaIcon(img='loop-add',
+                             label=_('Add loop/series to model')),
+            'comment': MetaIcon(img='label-add',
+                                label=_('Add comment to model')),
+            'run': MetaIcon(img='execute',
+                            label=_('Run model')),
+            'validate': MetaIcon(img='check',
+                                 label=_('Validate model')),
+            'settings': BaseIcons['settings'].SetLabel(_('Modeler settings')),
+            'properties': MetaIcon(img='options',
+                                   label=_('Show model properties')),
+            'variables': MetaIcon(img='modeler-variables',
+                                  label=_('Manage model variables')),
+            'redraw': MetaIcon(img='redraw',
+                               label=_('Redraw model canvas')),
+            'quit': BaseIcons['quit'].SetLabel(_('Quit Graphical Modeler')),
+        }
+
         return self._getToolbarData((('new', icons['new'],
                                       self.parent.OnModelNew),
                                      ('open', icons['open'],

Modified: grass/trunk/gui/wxpython/gui_core/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gui_core/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -13,4 +13,4 @@
     'forms',
     'toolbars',
     'treeview',
-    ]
+]

Modified: grass/trunk/gui/wxpython/gui_core/dialogs.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/dialogs.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gui_core/dialogs.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -41,71 +41,81 @@
 from core import globalvar
 from core.gcmd import GError, RunCommand, GMessage
 from gui_core.gselect import LocationSelect, MapsetSelect, Select, \
-                             OgrTypeSelect, SubGroupSelect
+    OgrTypeSelect, SubGroupSelect
 from gui_core.widgets import SingleSymbolPanel, GListCtrl, SimpleValidator, MapValidator
 from core.utils import _
 from core.settings import UserSettings
 from core.debug import Debug
 
+
 class SimpleDialog(wx.Dialog):
-    def __init__(self, parent, title, id = wx.ID_ANY,
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
+
+    def __init__(self, parent, title, id=wx.ID_ANY,
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
                  **kwargs):
         """General dialog to choose given element (location, mapset, vector map, etc.)
-        
+
         :param parent: window
         :param title: window title
         """
-        wx.Dialog.__init__(self, parent, id, title, style = style, **kwargs)
+        wx.Dialog.__init__(self, parent, id, title, style=style, **kwargs)
         self.SetExtraStyle(wx.WS_EX_VALIDATE_RECURSIVELY)
-        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
-        
-        self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
-        self.btnOK     = wx.Button(parent = self.panel, id = wx.ID_OK)
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
+        self.btnCancel = wx.Button(parent=self.panel, id=wx.ID_CANCEL)
+        self.btnOK = wx.Button(parent=self.panel, id=wx.ID_OK)
         self.btnOK.SetDefault()
-                
+
         self.__layout()
         self.warning = _("Required item is not set.")
 
     def __layout(self):
         """Do layout"""
         self.sizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         self.dataSizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         # self.informLabel = wx.StaticText(self.panel, id = wx.ID_ANY)
         # buttons
         btnSizer = wx.StdDialogButtonSizer()
         btnSizer.AddButton(self.btnCancel)
         btnSizer.AddButton(self.btnOK)
         btnSizer.Realize()
-        
-        self.sizer.Add(item = self.dataSizer, proportion = 1,
-                       flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
-        
+
+        self.sizer.Add(item=self.dataSizer, proportion=1,
+                       flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
+
         # self.sizer.Add(item = self.informLabel, proportion = 0, flag = wx.ALL, border = 5)
-        self.sizer.Add(item = btnSizer, proportion = 0,
-                       flag = wx.EXPAND | wx.ALL, border = 5)
+        self.sizer.Add(item=btnSizer, proportion=0,
+                       flag=wx.EXPAND | wx.ALL, border=5)
 
     def ValidatorCallback(self, win):
-        GMessage(parent = self, message = self.warning)
+        GMessage(parent=self, message=self.warning)
         # self.informLabel.SetForegroundColour(wx.Colour(255, 0, 0))
         # self.informLabel.SetLabel(self.warning)
 
 
 class LocationDialog(SimpleDialog):
     """Dialog used to select location"""
-    def __init__(self, parent, title = _("Select GRASS location and mapset")):
+
+    def __init__(self, parent, title=_("Select GRASS location and mapset")):
         SimpleDialog.__init__(self, parent, title)
 
-        self.element1 = LocationSelect(parent = self.panel, id = wx.ID_ANY,
-                                      size = globalvar.DIALOG_GSELECT_SIZE,
-                                      validator = SimpleValidator(callback = self.ValidatorCallback))
+        self.element1 = LocationSelect(
+            parent=self.panel,
+            id=wx.ID_ANY,
+            size=globalvar.DIALOG_GSELECT_SIZE,
+            validator=SimpleValidator(
+                callback=self.ValidatorCallback))
         self.element1.Bind(wx.EVT_TEXT, self.OnLocation)
-        self.element2 = MapsetSelect(parent = self.panel, id = wx.ID_ANY,
-                                     size = globalvar.DIALOG_GSELECT_SIZE,
-                                     setItems = False, skipCurrent = True,
-                                     validator = SimpleValidator(callback = self.ValidatorCallback))
+        self.element2 = MapsetSelect(
+            parent=self.panel,
+            id=wx.ID_ANY,
+            size=globalvar.DIALOG_GSELECT_SIZE,
+            setItems=False,
+            skipCurrent=True,
+            validator=SimpleValidator(
+                callback=self.ValidatorCallback))
         self.element1.SetFocus()
         self.warning = _("Location or mapset is not defined.")
         self._layout()
@@ -113,102 +123,126 @@
 
     def _layout(self):
         """Do layout"""
-        self.dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                                label = _("Name of GRASS location:")),
-                           proportion = 0, flag = wx.ALL, border = 1)
-        self.dataSizer.Add(self.element1, proportion = 0,
-                           flag = wx.EXPAND | wx.ALL, border = 1)
- 
-        self.dataSizer.Add(wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                         label = _("Name of mapset:")), proportion = 0,
-                           flag = wx.EXPAND | wx.ALL, border = 1)
+        self.dataSizer.Add(
+            item=wx.StaticText(
+                parent=self.panel,
+                id=wx.ID_ANY,
+                label=_("Name of GRASS location:")),
+            proportion=0,
+            flag=wx.ALL,
+            border=1)
+        self.dataSizer.Add(self.element1, proportion=0,
+                           flag=wx.EXPAND | wx.ALL, border=1)
 
-        self.dataSizer.Add(self.element2, proportion = 0,
-                           flag = wx.EXPAND | wx.ALL, border = 1)
-       
+        self.dataSizer.Add(
+            wx.StaticText(
+                parent=self.panel,
+                id=wx.ID_ANY,
+                label=_("Name of mapset:")),
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=1)
+
+        self.dataSizer.Add(self.element2, proportion=0,
+                           flag=wx.EXPAND | wx.ALL, border=1)
+
         self.panel.SetSizer(self.sizer)
         self.sizer.Fit(self)
 
     def OnLocation(self, event):
         """Select mapset given location name"""
         location = event.GetString()
-        
+
         if location:
             dbase = grass.gisenv()['GISDBASE']
-            self.element2.UpdateItems(dbase = dbase, location = location)
+            self.element2.UpdateItems(dbase=dbase, location=location)
             self.element2.SetSelection(0)
             mapset = self.element2.GetStringSelection()
 
     def GetValues(self):
         """Get location, mapset"""
         return (self.element1.GetValue(), self.element2.GetValue())
-    
+
+
 class MapsetDialog(SimpleDialog):
     """Dialog used to select mapset"""
-    def __init__(self, parent, title = _("Select mapset in GRASS location"),
-                 location = None):
+
+    def __init__(self, parent, title=_("Select mapset in GRASS location"),
+                 location=None):
         SimpleDialog.__init__(self, parent, title)
 
         if location:
             self.SetTitle(self.GetTitle() + ' <%s>' % location)
         else:
-            self.SetTitle(self.GetTitle() + ' <%s>' % grass.gisenv()['LOCATION_NAME'])
-        
-        self.element = MapsetSelect(parent = self.panel, id = wx.ID_ANY, skipCurrent = True,
-                                    size = globalvar.DIALOG_GSELECT_SIZE,
-                                    validator = SimpleValidator(callback = self.ValidatorCallback))
-        
+            self.SetTitle(
+                self.GetTitle() + ' <%s>' %
+                grass.gisenv()['LOCATION_NAME'])
+
+        self.element = MapsetSelect(
+            parent=self.panel,
+            id=wx.ID_ANY,
+            skipCurrent=True,
+            size=globalvar.DIALOG_GSELECT_SIZE,
+            validator=SimpleValidator(
+                callback=self.ValidatorCallback))
+
         self.element.SetFocus()
         self.warning = _("Name of mapset is missing.")
-        
+
         self._layout()
         self.SetMinSize(self.GetSize())
 
     def _layout(self):
         """Do layout"""
-        self.dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                                label = _("Name of mapset:")),
-                           proportion = 0, flag = wx.ALL, border = 1)
-        self.dataSizer.Add(self.element, proportion = 0,
-                           flag = wx.EXPAND | wx.ALL, border = 1)
+        self.dataSizer.Add(item=wx.StaticText(parent=self.panel, id=wx.ID_ANY,
+                                              label=_("Name of mapset:")),
+                           proportion=0, flag=wx.ALL, border=1)
+        self.dataSizer.Add(self.element, proportion=0,
+                           flag=wx.EXPAND | wx.ALL, border=1)
         self.panel.SetSizer(self.sizer)
         self.sizer.Fit(self)
 
     def GetMapset(self):
         return self.element.GetValue()
 
+
 class VectorDialog(SimpleDialog):
-    def __init__(self, parent, title = _("Select vector map"), layerTree = None):
+
+    def __init__(self, parent, title=_("Select vector map"), layerTree=None):
         """Dialog for selecting existing vector map
 
         :param parent: parent window
         :param title: window title
         :param layerTree: show only vector maps in given layer tree if not None
-        
+
         :return: dialog instance
         """
         SimpleDialog.__init__(self, parent, title)
-        
-        self.element = Select(parent = self.panel, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
-                              type = 'vector', layerTree = layerTree,
-                              validator = MapValidator())
+
+        self.element = Select(
+            parent=self.panel,
+            id=wx.ID_ANY,
+            size=globalvar.DIALOG_GSELECT_SIZE,
+            type='vector',
+            layerTree=layerTree,
+            validator=MapValidator())
         self.element.SetFocus()
-        
+
         self.warning = _("Name of vector map is missing.")
         wx.CallAfter(self._layout)
-        
+
     def _layout(self):
         """Do layout"""
-        self.dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                                label = _("Name of vector map:")),
-                           proportion = 0, flag = wx.ALL, border = 1)
-        self.dataSizer.Add(item = self.element, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL, border = 1)
-        
+        self.dataSizer.Add(item=wx.StaticText(parent=self.panel, id=wx.ID_ANY,
+                                              label=_("Name of vector map:")),
+                           proportion=0, flag=wx.ALL, border=1)
+        self.dataSizer.Add(item=self.element, proportion=0,
+                           flag=wx.EXPAND | wx.ALL, border=1)
+
         self.panel.SetSizer(self.sizer)
         self.sizer.Fit(self)
 
-    def GetName(self, full = False):
+    def GetName(self, full=False):
         """Get name of vector map to be created
 
         :param full: True to get fully qualified name
@@ -219,12 +253,14 @@
                 return name
             else:
                 return name + '@' + grass.gisenv()['MAPSET']
-        
+
         return name.split('@', 1)[0]
 
+
 class NewVectorDialog(VectorDialog):
-    def __init__(self, parent, title = _("Create new vector map"),
-                 disableAdd = False, disableTable = False, showType = False):
+
+    def __init__(self, parent, title=_("Create new vector map"),
+                 disableAdd=False, disableTable=False, showType=False):
         """Dialog for creating new vector map
 
         :param parent: parent window
@@ -232,80 +268,98 @@
         :param disableAdd: disable 'add layer' checkbox
         :param disableTable: disable 'create table' checkbox
         :param showType: True to show feature type selector (used for creating new empty OGR layers)
-        
+
         :return: dialog instance
         """
         VectorDialog.__init__(self, parent, title)
-        
+
         # determine output format
         if showType:
-            self.ftype = OgrTypeSelect(parent = self, panel = self.panel)
+            self.ftype = OgrTypeSelect(parent=self, panel=self.panel)
         else:
             self.ftype = None
-        
+
         # create attribute table
-        self.table = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
-                                 label = _("Create attribute table"))
+        self.table = wx.CheckBox(parent=self.panel, id=wx.ID_ANY,
+                                 label=_("Create attribute table"))
         self.table.SetValue(True)
         if disableTable:
             self.table.Enable(False)
-        
+
         if showType:
             self.keycol = None
         else:
-            self.keycol = wx.TextCtrl(parent = self.panel, id =  wx.ID_ANY,
-                                      size = globalvar.DIALOG_SPIN_SIZE)
-            self.keycol.SetValue(UserSettings.Get(group = 'atm', key = 'keycolumn', subkey = 'value'))
+            self.keycol = wx.TextCtrl(parent=self.panel, id=wx.ID_ANY,
+                                      size=globalvar.DIALOG_SPIN_SIZE)
+            self.keycol.SetValue(
+                UserSettings.Get(
+                    group='atm',
+                    key='keycolumn',
+                    subkey='value'))
             if disableTable:
                 self.keycol.Enable(False)
-        
-        self.addbox = wx.CheckBox(parent = self.panel,
-                                  label = _('Add created map into layer tree'), style = wx.NO_BORDER)
+
+        self.addbox = wx.CheckBox(
+            parent=self.panel,
+            label=_('Add created map into layer tree'),
+            style=wx.NO_BORDER)
         if disableAdd:
             self.addbox.SetValue(True)
             self.addbox.Enable(False)
         else:
-            self.addbox.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
+            self.addbox.SetValue(
+                UserSettings.Get(
+                    group='cmd',
+                    key='addNewLayer',
+                    subkey='enabled'))
 
         self.table.Bind(wx.EVT_CHECKBOX, self.OnTable)
-        
+
         self.warning = _("Name of new vector map is missing.")
-        
+
     def OnTable(self, event):
         if self.keycol:
             self.keycol.Enable(event.IsChecked())
-        
+
     def _layout(self):
         """Do layout"""
-        self.dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                                label = _("Name for new vector map:")),
-                           proportion = 0, flag = wx.ALL, border = 1)
-        self.dataSizer.Add(item = self.element, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL, border = 1)
+        self.dataSizer.Add(
+            item=wx.StaticText(
+                parent=self.panel,
+                id=wx.ID_ANY,
+                label=_("Name for new vector map:")),
+            proportion=0,
+            flag=wx.ALL,
+            border=1)
+        self.dataSizer.Add(item=self.element, proportion=0,
+                           flag=wx.EXPAND | wx.ALL, border=1)
         if self.ftype:
             self.dataSizer.AddSpacer(1)
-            self.dataSizer.Add(item = self.ftype, proportion = 0,
-                               flag = wx.EXPAND | wx.ALL, border = 1)
-        
-        self.dataSizer.Add(item = self.table, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL, border = 1)
-        
+            self.dataSizer.Add(item=self.ftype, proportion=0,
+                               flag=wx.EXPAND | wx.ALL, border=1)
+
+        self.dataSizer.Add(item=self.table, proportion=0,
+                           flag=wx.EXPAND | wx.ALL, border=1)
+
         if self.keycol:
             keySizer = wx.BoxSizer(wx.HORIZONTAL)
-            keySizer.Add(item = wx.StaticText(parent = self.panel, label = _("Key column:")),
-                         proportion = 0,
-                         flag = wx.ALIGN_CENTER_VERTICAL)
+            keySizer.Add(
+                item=wx.StaticText(
+                    parent=self.panel,
+                    label=_("Key column:")),
+                proportion=0,
+                flag=wx.ALIGN_CENTER_VERTICAL)
             keySizer.AddSpacer(10)
-            keySizer.Add(item = self.keycol, proportion = 0,
-                         flag = wx.ALIGN_RIGHT)
-            self.dataSizer.Add(item = keySizer, proportion = 1,
-                               flag = wx.EXPAND | wx.ALL, border = 1)
-            
+            keySizer.Add(item=self.keycol, proportion=0,
+                         flag=wx.ALIGN_RIGHT)
+            self.dataSizer.Add(item=keySizer, proportion=1,
+                               flag=wx.EXPAND | wx.ALL, border=1)
+
         self.dataSizer.AddSpacer(5)
-        
-        self.dataSizer.Add(item = self.addbox, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL, border = 1)
-        
+
+        self.dataSizer.Add(item=self.addbox, proportion=0,
+                           flag=wx.EXPAND | wx.ALL, border=1)
+
         self.panel.SetSizer(self.sizer)
         self.sizer.Fit(self)
         self.SetMinSize(self.GetSize())
@@ -314,8 +368,8 @@
         """Get key column name"""
         if self.keycol:
             return self.keycol.GetValue()
-        return UserSettings.Get(group = 'atm', key = 'keycolumn', subkey = 'value')
-    
+        return UserSettings.Get(group='atm', key='keycolumn', subkey='value')
+
     def IsChecked(self, key):
         """Get dialog properties
 
@@ -328,9 +382,9 @@
             return self.addbox.IsChecked()
         elif key == 'table':
             return self.table.IsChecked()
-        
+
         return None
-    
+
     def GetFeatureType(self):
         """Get feature type for OGR
 
@@ -343,9 +397,9 @@
         return None
 
 
-def CreateNewVector(parent, cmd, title = _('Create new vector map'),
+def CreateNewVector(parent, cmd, title=_('Create new vector map'),
                     exceptMap=None, giface=None,
-                    disableAdd = False, disableTable = False):
+                    disableAdd=False, disableTable=False):
     """Create new vector map layer
 
     :param cmd: (prog, \*\*kwargs)
@@ -364,29 +418,29 @@
         showType = True
     else:
         showType = False
-    dlg = NewVectorDialog(parent, title = title,
-                          disableAdd = disableAdd, disableTable = disableTable,
-                          showType = showType)
-    
+    dlg = NewVectorDialog(parent, title=title,
+                          disableAdd=disableAdd, disableTable=disableTable,
+                          showType=showType)
+
     if dlg.ShowModal() != wx.ID_OK:
         dlg.Destroy()
         return None
 
     outmap = dlg.GetName()
-    key    = dlg.GetKey()
+    key = dlg.GetKey()
     if outmap == exceptMap:
-        GError(parent = parent,
-               message = _("Unable to create vector map <%s>.") % outmap)
+        GError(parent=parent,
+               message=_("Unable to create vector map <%s>.") % outmap)
         dlg.Destroy()
         return None
     if dlg.table.IsEnabled() and not key:
-        GError(parent = parent,
-               message = _("Invalid or empty key column.\n"
-                           "Unable to create vector map <%s>.") % outmap)
+        GError(parent=parent,
+               message=_("Invalid or empty key column.\n"
+                         "Unable to create vector map <%s>.") % outmap)
         dlg.Destroy()
         return
-        
-    if outmap == '': # should not happen
+
+    if outmap == '':  # should not happen
         dlg.Destroy()
         return None
 
@@ -394,135 +448,162 @@
     cmd[1][cmd[2]] = outmap
     if showType:
         cmd[1]['type'] = dlg.GetFeatureType()
-        
+
     curMapset = grass.gisenv()['MAPSET']
     if isNative:
         listOfVectors = grass.list_grouped('vector')[curMapset]
     else:
         listOfVectors = RunCommand('v.external',
-                                   quiet = True,
-                                   parent = parent,
-                                   read = True,
-                                   flags = 'l',
-                                   input = vExternalOut['dsn']).splitlines()
-    
+                                   quiet=True,
+                                   parent=parent,
+                                   read=True,
+                                   flags='l',
+                                   input=vExternalOut['dsn']).splitlines()
+
     overwrite = False
-    if not UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled') and \
-            outmap in listOfVectors:
-        dlgOw = wx.MessageDialog(parent, message = _("Vector map <%s> already exists "
-                                                     "in the current mapset. "
-                                                     "Do you want to overwrite it?") % outmap,
-                                 caption = _("Overwrite?"),
-                                 style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+    if not UserSettings.Get(group='cmd', key='overwrite',
+                            subkey='enabled') and outmap in listOfVectors:
+        dlgOw = wx.MessageDialog(
+            parent,
+            message=_(
+                "Vector map <%s> already exists "
+                "in the current mapset. "
+                "Do you want to overwrite it?") %
+            outmap,
+            caption=_("Overwrite?"),
+            style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
         if dlgOw.ShowModal() == wx.ID_YES:
             overwrite = True
         else:
             dlgOw.Destroy()
             dlg.Destroy()
             return None
-        
-    if UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'):
+
+    if UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'):
         overwrite = True
-        
-    ret = RunCommand(prog = cmd[0],
-                     parent = parent,
-                     overwrite = overwrite,
+
+    ret = RunCommand(prog=cmd[0],
+                     parent=parent,
+                     overwrite=overwrite,
                      **cmd[1])
     if ret != 0:
         dlg.Destroy()
         return None
-    
-    if not isNative and \
-            not grass.find_file(outmap, element = 'vector', mapset = curMapset)['fullname']:
+
+    if not isNative and not grass.find_file(
+            outmap, element='vector', mapset=curMapset)['fullname']:
         # create link for OGR layers
         RunCommand('v.external',
-                   overwrite = overwrite,
-                   parent = parent,
-                   input = vExternalOut['dsn'],
-                   layer = outmap)
-        
+                   overwrite=overwrite,
+                   parent=parent,
+                   input=vExternalOut['dsn'],
+                   layer=outmap)
+
     # create attribute table
     if dlg.table.IsEnabled() and dlg.table.IsChecked():
         if isNative:
             sql = 'CREATE TABLE %s (%s INTEGER)' % (outmap, key)
-            
+
             RunCommand('db.connect',
-                       flags = 'c')
-            
+                       flags='c')
+
             Debug.msg(1, "SQL: %s" % sql)
             RunCommand('db.execute',
-                       quiet = True,
-                       parent = parent,
-                       input = '-',
-                       stdin = sql)
-            
+                       quiet=True,
+                       parent=parent,
+                       input='-',
+                       stdin=sql)
+
             RunCommand('v.db.connect',
-                       quiet = True,
-                       parent = parent,
-                       map = outmap,
-                       table = outmap,
-                       key = key,
-                       layer = '1')
+                       quiet=True,
+                       parent=parent,
+                       map=outmap,
+                       table=outmap,
+                       key=key,
+                       layer='1')
         # TODO: how to deal with attribute tables for OGR layers?
-            
+
     # return fully qualified map name
     if '@' not in outmap:
         outmap += '@' + grass.gisenv()['MAPSET']
-    
+
     # if giface:
     #     giface.WriteLog(_("New vector map <%s> created") % outmap)
-        
+
     return dlg
 
+
 class SavedRegion(wx.Dialog):
-    def __init__(self, parent, title, id = wx.ID_ANY, loadsave = 'load',
+
+    def __init__(self, parent, title, id=wx.ID_ANY, loadsave='load',
                  **kwargs):
         """Loading or saving of display extents to saved region file
 
         :param loadsave: load or save region?
         """
         wx.Dialog.__init__(self, parent, id, title, **kwargs)
-        
+
         self.loadsave = loadsave
         self.wind = ''
-        
+
         sizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         box = wx.BoxSizer(wx.HORIZONTAL)
-        label = wx.StaticText(parent = self, id = wx.ID_ANY)
-        box.Add(item = label, proportion = 0, flag = wx.ALIGN_CENTRE | wx.ALL, border = 5)
+        label = wx.StaticText(parent=self, id=wx.ID_ANY)
+        box.Add(
+            item=label,
+            proportion=0,
+            flag=wx.ALIGN_CENTRE | wx.ALL,
+            border=5)
         if loadsave == 'load':
             label.SetLabel(_("Load region:"))
-            self._selection = Select(parent=self, size=globalvar.DIALOG_GSELECT_SIZE,
-                                     type='windows')
+            self._selection = Select(
+                parent=self,
+                size=globalvar.DIALOG_GSELECT_SIZE,
+                type='windows')
         elif loadsave == 'save':
             label.SetLabel(_("Save region:"))
-            self._selection = Select(parent=self, size=globalvar.DIALOG_GSELECT_SIZE,
-                                     type='windows', mapsets=[grass.gisenv()['MAPSET']], fullyQualified = False)
-        
-        box.Add(item=self._selection, proportion=0, flag=wx.ALIGN_CENTRE | wx.ALL, border=5)
+            self._selection = Select(
+                parent=self,
+                size=globalvar.DIALOG_GSELECT_SIZE,
+                type='windows',
+                mapsets=[
+                    grass.gisenv()['MAPSET']],
+                fullyQualified=False)
+
+        box.Add(
+            item=self._selection,
+            proportion=0,
+            flag=wx.ALIGN_CENTRE | wx.ALL,
+            border=5)
         self._selection.SetFocus()
         self._selection.Bind(wx.EVT_TEXT, self.OnRegion)
-        
-        sizer.Add(item = box, proportion = 0, flag = wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
-                  border = 5)
-        
-        line = wx.StaticLine(parent = self, id = wx.ID_ANY, size = (20, -1), style = wx.LI_HORIZONTAL)
-        sizer.Add(item = line, proportion = 0,
-                  flag = wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, border = 5)
-        
+
+        sizer.Add(item=box, proportion=0, flag=wx.GROW |
+                  wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
+
+        line = wx.StaticLine(
+            parent=self, id=wx.ID_ANY, size=(
+                20, -1), style=wx.LI_HORIZONTAL)
+        sizer.Add(item=line, proportion=0, flag=wx.GROW |
+                  wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, border=5)
+
         btnsizer = wx.StdDialogButtonSizer()
-        
-        btn = wx.Button(parent = self, id = wx.ID_OK)
+
+        btn = wx.Button(parent=self, id=wx.ID_OK)
         btn.SetDefault()
         btnsizer.AddButton(btn)
-        
-        btn = wx.Button(parent = self, id = wx.ID_CANCEL)
+
+        btn = wx.Button(parent=self, id=wx.ID_CANCEL)
         btnsizer.AddButton(btn)
         btnsizer.Realize()
-        
-        sizer.Add(item = btnsizer, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
-        
+
+        sizer.Add(
+            item=btnsizer,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT | wx.ALL,
+            border=5)
+
         self.SetSizer(sizer)
         sizer.Fit(self)
         self.Layout()
@@ -547,13 +628,14 @@
 
 class GroupDialog(wx.Dialog):
     """Dialog for creating/editing groups"""
-    def __init__(self, parent = None, defaultGroup = None,  defaultSubgroup = None, 
-                 title = _("Create or edit imagery groups"),
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
-                     
-        wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY, title = title,
-                            style = style, **kwargs)
-                            
+
+    def __init__(self, parent=None, defaultGroup=None, defaultSubgroup=None,
+                 title=_("Create or edit imagery groups"),
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
+
+        wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=title,
+                           style=style, **kwargs)
+
         self.parent = parent
         self.defaultGroup = defaultGroup
         self.defaultSubgroup = defaultSubgroup
@@ -575,18 +657,19 @@
         self.flt_pattern = ''
 
         self.bodySizer = self._createDialogBody()
-        
+
         # buttons
-        btnOk = wx.Button(parent = self, id = wx.ID_OK)
-        btnApply = wx.Button(parent = self, id = wx.ID_APPLY)
-        btnClose = wx.Button(parent = self, id = wx.ID_CANCEL)
-        
-        btnOk.SetToolTipString(_("Apply changes to selected group and close dialog"))
+        btnOk = wx.Button(parent=self, id=wx.ID_OK)
+        btnApply = wx.Button(parent=self, id=wx.ID_APPLY)
+        btnClose = wx.Button(parent=self, id=wx.ID_CANCEL)
+
+        btnOk.SetToolTipString(
+            _("Apply changes to selected group and close dialog"))
         btnApply.SetToolTipString(_("Apply changes to selected group"))
         btnClose.SetToolTipString(_("Close dialog, changes are not applied"))
 
-        #btnOk.SetDefault()
-        
+        # btnOk.SetDefault()
+
         # sizers & do layout
         # btnSizer = wx.BoxSizer(wx.HORIZONTAL)
         # btnSizer.Add(item = btnClose, proportion = 0,
@@ -598,20 +681,20 @@
         btnSizer.AddButton(btnApply)
         btnSizer.AddButton(btnClose)
         btnSizer.Realize()
-        
+
         mainSizer = wx.BoxSizer(wx.VERTICAL)
-        mainSizer.Add(item = self.bodySizer, proportion = 1,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 10)
-        mainSizer.Add(item = wx.StaticLine(parent = self, id = wx.ID_ANY,
-                      style = wx.LI_HORIZONTAL), proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 10) 
-        
-        mainSizer.Add(item = btnSizer, proportion = 0,
-                      flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.ALIGN_RIGHT, border = 10)
+        mainSizer.Add(item=self.bodySizer, proportion=1,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=10)
+        mainSizer.Add(item=wx.StaticLine(parent=self, id=wx.ID_ANY,
+                                         style=wx.LI_HORIZONTAL), proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=10)
 
+        mainSizer.Add(item=btnSizer, proportion=0, flag=wx.LEFT |
+                      wx.RIGHT | wx.BOTTOM | wx.ALIGN_RIGHT, border=10)
+
         self.SetSizer(mainSizer)
         mainSizer.Fit(self)
-        
+
         btnOk.Bind(wx.EVT_BUTTON, self.OnOk)
         btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
         btnClose.Bind(wx.EVT_BUTTON, self.OnClose)
@@ -622,7 +705,7 @@
 
     def _createDialogBody(self):
         bodySizer = wx.BoxSizer(wx.VERTICAL)
-        #TODO same text in MapLayersDialogBase
+        # TODO same text in MapLayersDialogBase
 
         filter_tooltip = _("Put here a regular expression."
                            " Characters '.*' stand for anything,"
@@ -630,130 +713,164 @@
                            " and '$' for the end.")
 
         # group selection
-        bodySizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
-                                           label = _("Select existing group or "
-                                                     "enter name of new group:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL | wx.TOP, border = 10)
-        self.groupSelect = Select(parent = self, type = 'group',
-                                  mapsets = [grass.gisenv()['MAPSET']],
-                                  size = globalvar.DIALOG_GSELECT_SIZE,
-                                  fullyQualified = False) # searchpath?
-    
-        bodySizer.Add(item = self.groupSelect, flag = wx.TOP | wx.EXPAND, border = 5)
+        bodySizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY,
+                                         label=_("Select existing group or "
+                                                 "enter name of new group:")),
+                      flag=wx.ALIGN_CENTER_VERTICAL | wx.TOP, border=10)
+        self.groupSelect = Select(parent=self, type='group',
+                                  mapsets=[grass.gisenv()['MAPSET']],
+                                  size=globalvar.DIALOG_GSELECT_SIZE,
+                                  fullyQualified=False)  # searchpath?
 
-        self.subg_chbox = wx.CheckBox(parent = self, id = wx.ID_ANY,
-                                      label = _("Edit/create subgroup"))
+        bodySizer.Add(item=self.groupSelect, flag=wx.TOP | wx.EXPAND, border=5)
 
-        bodySizer.Add(item = self.subg_chbox,
-                      flag = wx.ALIGN_CENTER_VERTICAL | wx.TOP, border = 10)
+        self.subg_chbox = wx.CheckBox(parent=self, id=wx.ID_ANY,
+                                      label=_("Edit/create subgroup"))
 
+        bodySizer.Add(item=self.subg_chbox,
+                      flag=wx.ALIGN_CENTER_VERTICAL | wx.TOP, border=10)
+
         self.subg_panel = wx.Panel(self)
         subg_sizer = wx.BoxSizer(wx.VERTICAL)
 
-        subg_sizer.Add(item = wx.StaticText(parent=self.subg_panel, id = wx.ID_ANY,
-                       label = _("Select existing subgroup or "
-                                 "enter name of new subgroup:")),
-                       flag = wx.ALIGN_CENTER_VERTICAL)
+        subg_sizer.Add(
+            item=wx.StaticText(
+                parent=self.subg_panel,
+                id=wx.ID_ANY,
+                label=_(
+                    "Select existing subgroup or "
+                    "enter name of new subgroup:")),
+            flag=wx.ALIGN_CENTER_VERTICAL)
 
-        self.subGroupSelect = SubGroupSelect(parent = self.subg_panel)
+        self.subGroupSelect = SubGroupSelect(parent=self.subg_panel)
 
-        subg_sizer.Add(item=self.subGroupSelect, flag=wx.EXPAND | wx.TOP, border = 5)
+        subg_sizer.Add(
+            item=self.subGroupSelect,
+            flag=wx.EXPAND | wx.TOP,
+            border=5)
 
         self.subg_panel.SetSizer(subg_sizer)
 
-        bodySizer.Add(item = self.subg_panel, flag = wx.TOP | wx.EXPAND, border = 5)
-        
+        bodySizer.Add(item=self.subg_panel, flag=wx.TOP | wx.EXPAND, border=5)
+
         bodySizer.AddSpacer(10)
 
         buttonSizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         # layers in group
         self.gListPanel = wx.Panel(self)
 
-        gListSizer  = wx.GridBagSizer(vgap=3, hgap=2)
+        gListSizer = wx.GridBagSizer(vgap=3, hgap=2)
 
         self.g_sel_all = wx.CheckBox(parent=self.gListPanel, id=wx.ID_ANY,
-                                  label=_("Select all"))
+                                     label=_("Select all"))
 
         gListSizer.Add(item=self.g_sel_all,
                        flag=wx.ALIGN_CENTER_VERTICAL,
-                       pos=(0,1))
+                       pos=(0, 1))
 
-        gListSizer.Add(item = wx.StaticText(parent = self.gListPanel, label = _("Pattern:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (1,0))
-        
+        gListSizer.Add(
+            item=wx.StaticText(
+                parent=self.gListPanel,
+                label=_("Pattern:")),
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                1,
+                0))
+
         self.gfilter = wx.TextCtrl(parent=self.gListPanel, id=wx.ID_ANY,
-                                  value="",
-                                  size=(250,-1))
+                                   value="",
+                                   size=(250, -1))
         self.gfilter.SetToolTipString(filter_tooltip)
-        
 
         gListSizer.Add(item=self.gfilter,
                        flag=wx.EXPAND,
-                       pos=(1,1))
+                       pos=(1, 1))
 
-        gListSizer.Add(item = wx.StaticText(parent = self.gListPanel, 
-                                           label = _("List of maps:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM, border = 5, pos=(2,0))
+        gListSizer.Add(
+            item=wx.StaticText(
+                parent=self.gListPanel,
+                label=_("List of maps:")),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM,
+            border=5,
+            pos=(
+                2,
+                0))
 
         sizer = wx.BoxSizer(wx.HORIZONTAL)
 
-        self.gLayerBox = wx.ListBox(parent = self.gListPanel,  id = wx.ID_ANY, size = (-1, 150),
-                                   style = wx.LB_MULTIPLE | wx.LB_NEEDED_SB)
-        sizer.Add(item = self.gLayerBox, proportion = 1, flag = wx.EXPAND)
-        
-        self.addLayer = wx.Button(self.gListPanel, id = wx.ID_ADD)
-        self.addLayer.SetToolTipString(_("Select map layers and add them to the list."))
-        buttonSizer.Add(item = self.addLayer, flag = wx.BOTTOM, border = 10)
-        
-        self.removeLayer = wx.Button(self.gListPanel, id = wx.ID_REMOVE)
-        self.removeLayer.SetToolTipString(_("Remove selected layer(s) from list."))
-        buttonSizer.Add(item = self.removeLayer)
-        sizer.Add(item = buttonSizer, flag = wx.LEFT, border = 5)
-        
-        gListSizer.Add(item=sizer, flag=wx.EXPAND, pos=(2,1))
+        self.gLayerBox = wx.ListBox(
+            parent=self.gListPanel, id=wx.ID_ANY, size=(-1, 150),
+            style=wx.LB_MULTIPLE | wx.LB_NEEDED_SB)
+        sizer.Add(item=self.gLayerBox, proportion=1, flag=wx.EXPAND)
+
+        self.addLayer = wx.Button(self.gListPanel, id=wx.ID_ADD)
+        self.addLayer.SetToolTipString(
+            _("Select map layers and add them to the list."))
+        buttonSizer.Add(item=self.addLayer, flag=wx.BOTTOM, border=10)
+
+        self.removeLayer = wx.Button(self.gListPanel, id=wx.ID_REMOVE)
+        self.removeLayer.SetToolTipString(
+            _("Remove selected layer(s) from list."))
+        buttonSizer.Add(item=self.removeLayer)
+        sizer.Add(item=buttonSizer, flag=wx.LEFT, border=5)
+
+        gListSizer.Add(item=sizer, flag=wx.EXPAND, pos=(2, 1))
         gListSizer.AddGrowableCol(1)
         gListSizer.AddGrowableRow(2)
 
         self.gListPanel.SetSizer(gListSizer)
         bodySizer.Add(item=self.gListPanel, proportion=1, flag=wx.EXPAND)
-        
+
         # layers in subgroup
         self.subgListPanel = wx.Panel(self)
 
-        subgListSizer  = wx.GridBagSizer(vgap=3, hgap=2)
+        subgListSizer = wx.GridBagSizer(vgap=3, hgap=2)
 
         # select toggle
-        self.subg_sel_all = wx.CheckBox(parent=self.subgListPanel, id=wx.ID_ANY,
-                                  label=_("Select all"))
+        self.subg_sel_all = wx.CheckBox(
+            parent=self.subgListPanel,
+            id=wx.ID_ANY,
+            label=_("Select all"))
 
         subgListSizer.Add(item=self.subg_sel_all,
                           flag=wx.ALIGN_CENTER_VERTICAL,
-                          pos=(0,1))
+                          pos=(0, 1))
 
-        subgListSizer.Add(item = wx.StaticText(parent=self.subgListPanel, label=_("Pattern:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (1,0))
-        
+        subgListSizer.Add(
+            item=wx.StaticText(
+                parent=self.subgListPanel,
+                label=_("Pattern:")),
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                1,
+                0))
+
         self.subgfilter = wx.TextCtrl(parent=self.subgListPanel, id=wx.ID_ANY,
-                                  value="",
-                                  size=(250,-1))
+                                      value="",
+                                      size=(250, -1))
         self.subgfilter.SetToolTipString(filter_tooltip)
-        
+
         subgListSizer.Add(item=self.subgfilter,
-                      flag=wx.EXPAND,
-                      pos=(1,1))
+                          flag=wx.EXPAND,
+                          pos=(1, 1))
 
-        subgListSizer.Add(item = wx.StaticText(parent = self.subgListPanel, 
-                                           label = _("List of maps:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM, border = 5, pos=(2,0))
+        subgListSizer.Add(
+            item=wx.StaticText(
+                parent=self.subgListPanel,
+                label=_("List of maps:")),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM,
+            border=5,
+            pos=(
+                2,
+                0))
 
-        self.subgListBox = wx.CheckListBox(parent = self.subgListPanel, id = wx.ID_ANY,
-                                           size = (250, 100))
-        self.subgListBox.SetToolTipString(_("Check maps from group to be included into subgroup."))
+        self.subgListBox = wx.CheckListBox(
+            parent=self.subgListPanel, id=wx.ID_ANY, size=(250, 100))
+        self.subgListBox.SetToolTipString(
+            _("Check maps from group to be included into subgroup."))
 
-        subgListSizer.Add(item=self.subgListBox, flag=wx.EXPAND, pos=(2,1))
+        subgListSizer.Add(item=self.subgListBox, flag=wx.EXPAND, pos=(2, 1))
         subgListSizer.AddGrowableCol(1)
         subgListSizer.AddGrowableRow(2)
 
@@ -761,8 +878,10 @@
         bodySizer.Add(item=self.subgListPanel, proportion=1, flag=wx.EXPAND)
 
         self.infoLabel = wx.StaticText(parent=self, id=wx.ID_ANY)
-        bodySizer.Add(item = self.infoLabel, 
-                      flag = wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.BOTTOM, border = 5)
+        bodySizer.Add(
+            item=self.infoLabel,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.BOTTOM,
+            border=5)
 
         # bindings
         self.gfilter.Bind(wx.EVT_TEXT, self.OnGroupFilter)
@@ -773,13 +892,14 @@
         self.addLayer.Bind(wx.EVT_BUTTON, self.OnAddLayer)
         self.removeLayer.Bind(wx.EVT_BUTTON, self.OnRemoveLayer)
         self.subg_chbox.Bind(wx.EVT_CHECKBOX, self.OnSubgChbox)
-        self.subGroupSelect.Bind(wx.EVT_TEXT, lambda event : self.SubGroupSelected())
+        self.subGroupSelect.Bind(
+            wx.EVT_TEXT, lambda event: self.SubGroupSelected())
         self.subg_sel_all.Bind(wx.EVT_CHECKBOX, self.OnSubgSelAll)
         self.g_sel_all.Bind(wx.EVT_CHECKBOX, self.OnGSelAll)
 
         if self.defaultGroup:
             self.groupSelect.SetValue(self.defaultGroup)
-        
+
         if self.defaultSubgroup is not None:
             self.subGroupSelect.SetValue(self.defaultSubgroup)
             self.subg_chbox.SetValue(1)
@@ -787,7 +907,7 @@
         else:
             self.subg_chbox.SetValue(0)
             self.SubgChbox(False)
-        
+
         return bodySizer
 
     def OnGLayerCheck(self, event):
@@ -829,13 +949,13 @@
             for item in range(self.subgListBox.GetCount()):
                 if not self.subgListBox.IsChecked(item):
                     not_all_checked = True
-        
+
         self.subg_sel_all.SetValue(not not_all_checked)
 
     def OnSubgroupFilter(self, event):
         text = event.GetString()
         self.gfilter.ChangeValue(text)
-        self.flt_pattern = text 
+        self.flt_pattern = text
 
         self.FilterGroup()
         self.FilterSubgroup()
@@ -866,8 +986,8 @@
         self.dataChanged = val
 
     def DisableSubgroupEdit(self):
-        """Disable editation of subgroups in the dialog 
-        
+        """Disable editation of subgroups in the dialog
+
         .. todo::
             used by gcp manager, maybe the gcp m should also support subgroups
         """
@@ -877,7 +997,7 @@
         self.subgListBox.Hide()
 
         self.Layout()
-    
+
     def OnSubgChbox(self, event):
         edit_subg = self.subg_chbox.GetValue()
         self.SubgChbox(edit_subg)
@@ -911,19 +1031,19 @@
 
     def OnAddLayer(self, event):
         """Add new layer to listbox"""
-        dlg = MapLayersDialogForGroups(parent = self, title = _("Add selected map layers into group"))
-        
+        dlg = MapLayersDialogForGroups(
+            parent=self, title=_("Add selected map layers into group"))
+
         if dlg.ShowModal() != wx.ID_OK:
             dlg.Destroy()
             return
-        
+
         layers = dlg.GetMapLayers()
         for layer in layers:
             if layer not in self.gmaps:
                 self.gLayerBox.Append(layer)
                 self.gmaps.append(layer)
                 self.dataChanged = True
-            
 
     def OnRemoveLayer(self, event):
         """Remove layer from listbox"""
@@ -933,7 +1053,7 @@
             self.gLayerBox.Delete(sel)
             self.gmaps.remove(m)
             self.dataChanged = True
-                
+
     def GetLayers(self):
         """Get layers"""
         if self.edit_subg:
@@ -945,7 +1065,7 @@
             layers = self.gmaps[:]
 
         return layers
-        
+
     def OnGroupSelected(self, event):
         """Text changed in group selector"""
         # callAfter must be called to close popup before other actions
@@ -959,9 +1079,9 @@
         groups = self.GetExistGroups()
         if group in groups:
             maps = self.GetGroupLayers(group)
-        
+
         self.subGroupSelect.Insert(group)
-        
+
         self.gmaps = maps
         maps = self._filter(maps)
 
@@ -994,7 +1114,7 @@
 
         subgroup = self.subGroupSelect.GetValue().strip()
         group = self.currentGroup
-        
+
         gmaps = list()
         groups = self.GetExistGroups()
 
@@ -1013,7 +1133,7 @@
         self.subgListBox.Set(gmaps)
 
         for i, m in enumerate(gmaps):
-            if self.subgmaps.has_key(m):
+            if m in self.subgmaps:
                 self.subgListBox.Check(i)
             else:
                 self.subgListBox.Check(i, False)
@@ -1028,7 +1148,7 @@
         if len(self.flt_pattern) == 0:
             flt_data = data[:]
             return flt_data
-        
+
         for dt in data:
             try:
                 if re.compile(self.flt_pattern).search(dt):
@@ -1045,48 +1165,56 @@
             self._checkGroupChange()
 
     def _checkGroupChange(self):
-        if  self.currentGroup and self.dataChanged:
-            dlg = wx.MessageDialog(self, message = _("Group <%s> was changed, "
-                                                     "do you want to apply changes?") % self.currentGroup,
-                                   caption = _("Unapplied changes"),
-                                   style = wx.YES_NO | wx.ICON_QUESTION | wx.YES_DEFAULT)
+        if self.currentGroup and self.dataChanged:
+            dlg = wx.MessageDialog(
+                self,
+                message=_(
+                    "Group <%s> was changed, "
+                    "do you want to apply changes?") %
+                self.currentGroup,
+                caption=_("Unapplied changes"),
+                style=wx.YES_NO | wx.ICON_QUESTION | wx.YES_DEFAULT)
             if dlg.ShowModal() == wx.ID_YES:
                 self.ApplyChanges()
-                
+
             dlg.Destroy()
         self.dataChanged = False
 
     def _checkSubgroupChange(self):
         if self.currentSubgroup and self.dataChanged:
-            dlg = wx.MessageDialog(self, message = _("Subgroup <%s> was changed, "
-                                                     "do you want to apply changes?") % self.currentSubgroup,
-                                   caption = _("Unapplied changes"),
-                                   style = wx.YES_NO | wx.ICON_QUESTION | wx.YES_DEFAULT)
+            dlg = wx.MessageDialog(
+                self,
+                message=_(
+                    "Subgroup <%s> was changed, "
+                    "do you want to apply changes?") %
+                self.currentSubgroup,
+                caption=_("Unapplied changes"),
+                style=wx.YES_NO | wx.ICON_QUESTION | wx.YES_DEFAULT)
             if dlg.ShowModal() == wx.ID_YES:
                 self.ApplyChanges()
-                
+
             dlg.Destroy()
         self.dataChanged = False
 
     def ShowGroupLayers(self, mapList):
         """Show map layers in currently selected group"""
         self.gLayerBox.Set(mapList)
-                
+
     def EditGroup(self, group, subgroup=None):
         """Edit selected group"""
         layersNew = self.GetLayers()
         layersOld = self.GetGroupLayers(group, subgroup)
-        
+
         add = []
         remove = []
         for layerNew in layersNew:
             if layerNew not in layersOld:
                 add.append(layerNew)
-                
+
         for layerOld in layersOld:
             if layerOld not in layersNew:
                 remove.append(layerOld)
-                
+
         kwargs = {}
         if subgroup:
             kwargs["subgroup"] = subgroup
@@ -1094,39 +1222,39 @@
         ret = None
         if remove:
             ret = RunCommand('i.group',
-                             parent = self,
-                             group = group,
-                             flags = 'r',
-                             input = ','.join(remove),
+                             parent=self,
+                             group=group,
+                             flags='r',
+                             input=','.join(remove),
                              **kwargs)
-                        
+
         if add:
             ret = RunCommand('i.group',
-                             parent = self,
-                             group = group,
-                             input = ','.join(add),
+                             parent=self,
+                             group=group,
+                             input=','.join(add),
                              **kwargs)
-                            
+
         return ret
-        
+
     def CreateNewGroup(self, group, subgroup):
         """Create new group"""
         layers = self.GetLayers()
         if not layers:
-            GMessage(parent = self,
-                     message = _("No raster maps selected."))
+            GMessage(parent=self,
+                     message=_("No raster maps selected."))
             return 1
-        
+
         kwargs = {}
         if subgroup:
             kwargs["subgroup"] = subgroup
 
         ret = RunCommand('i.group',
-                          parent = self,
-                          group = group,
-                          input = layers,
-                          **kwargs)
-        #update subgroup select
+                         parent=self,
+                         group=group,
+                         input=layers,
+                         **kwargs)
+        # update subgroup select
         self.SubGroupSelected()
         return ret
 
@@ -1137,8 +1265,8 @@
     def GetExistSubgroups(self, group):
         """Returns existing subgroups in a group"""
         return RunCommand('i.group', group=group,
-                           read=True, flags='sg').splitlines()
-        
+                          read=True, flags='sg').splitlines()
+
     def ShowResult(self, group, returnCode, create):
         """Show if operation was successfull."""
         group += '@' + grass.gisenv()['MAPSET']
@@ -1154,15 +1282,15 @@
                 label = _("Creating of new group <%s> failed.") % group
             else:
                 label = _("Changing of group <%s> failed.") % group
-            
+
         self.infoLabel.SetLabel(label)
         wx.FutureCall(4000, self.ClearNotification)
-        
+
     def GetSelectedGroup(self):
         """Return currently selected group (without mapset)"""
         g = self.groupSelect.GetValue().split('@')[0]
         if self.edit_subg:
-            s = self.subGroupSelect.GetValue() 
+            s = self.subGroupSelect.GetValue()
         else:
             s = None
         return g, s
@@ -1175,31 +1303,30 @@
             kwargs['subgroup'] = subgroup
 
         res = RunCommand('i.group',
-                         parent = self,
-                         flags = 'g',
-                         read = True, **kwargs)
+                         parent=self,
+                         flags='g',
+                         read=True, **kwargs)
         if not res:
             return []
         return res.splitlines()
-    
+
     def ClearNotification(self):
         """Clear notification string"""
         self.infoLabel.SetLabel("")
-       
+
     def ApplyChanges(self):
         """Create or edit group"""
         group = self.currentGroup
         if not group:
-            GMessage(parent = self,
-                     message = _("No group selected."))
+            GMessage(parent=self,
+                     message=_("No group selected."))
             return False
 
-
         if self.edit_subg and not self.currentSubgroup:
-            GMessage(parent = self,
-                     message = _("No subgroup selected."))
+            GMessage(parent=self,
+                     message=_("No subgroup selected."))
             return 0
-        
+
         if self.edit_subg:
             subgroup = self.currentSubgroup
         else:
@@ -1208,76 +1335,79 @@
         groups = self.GetExistGroups()
         if group in groups:
             ret = self.EditGroup(group, subgroup)
-            self.ShowResult(group = group, returnCode = ret, create = False)
-            
+            self.ShowResult(group=group, returnCode=ret, create=False)
+
         else:
             ret = self.CreateNewGroup(group, subgroup)
-            self.ShowResult(group = group, returnCode = ret, create = True)
-            
+            self.ShowResult(group=group, returnCode=ret, create=True)
+
         self.dataChanged = False
-        
+
         return True
-        
+
     def OnApply(self, event):
         """Apply changes"""
         self.ApplyChanges()
-        
+
     def OnOk(self, event):
         """Apply changes and close dialog"""
         if self.ApplyChanges():
             self.OnClose(event)
-        
+
     def OnClose(self, event):
         """Close dialog"""
         if not self.IsModal():
             self.Destroy()
         event.Skip()
-        
+
+
 class MapLayersDialogBase(wx.Dialog):
     """Base dialog for selecting map layers (raster, vector).
 
     There are 3 subclasses: MapLayersDialogForGroups, MapLayersDialogForModeler,
     MapLayersDialog. Base class contains core functionality.
     """
-    def __init__(self, parent, title, 
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
-        wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY, title = title,
-                           style = style, **kwargs)
-        
-        self.parent = parent # GMFrame or ?
-        
-        self.applyAddingMapLayers = Signal('MapLayersDialogBase.applyAddingMapLayers')
-        
+
+    def __init__(self, parent, title,
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
+        wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=title,
+                           style=style, **kwargs)
+
+        self.parent = parent  # GMFrame or ?
+
+        self.applyAddingMapLayers = Signal(
+            'MapLayersDialogBase.applyAddingMapLayers')
+
         self.mainSizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         # dialog body
         self.bodySizer = self._createDialogBody()
-        self.mainSizer.Add(item = self.bodySizer, proportion = 1,
-                      flag = wx.EXPAND | wx.ALL, border = 5)
-        
+        self.mainSizer.Add(item=self.bodySizer, proportion=1,
+                           flag=wx.EXPAND | wx.ALL, border=5)
+
         # update list of layer to be loaded
-        self.map_layers = [] # list of map layers (full list type/mapset)
-        self.LoadMapLayers(self.GetLayerType(cmd = True),
+        self.map_layers = []  # list of map layers (full list type/mapset)
+        self.LoadMapLayers(self.GetLayerType(cmd=True),
                            self.mapset.GetStringSelection())
 
         self._fullyQualifiedNames()
         self._modelerDSeries()
 
         # buttons
-        btnCancel = wx.Button(parent = self, id = wx.ID_CANCEL)
-        btnOk = wx.Button(parent = self, id = wx.ID_OK)
+        btnCancel = wx.Button(parent=self, id=wx.ID_CANCEL)
+        btnOk = wx.Button(parent=self, id=wx.ID_OK)
         btnOk.SetDefault()
-        
+
         # sizers & do layout
         self.btnSizer = wx.StdDialogButtonSizer()
         self.btnSizer.AddButton(btnCancel)
         self.btnSizer.AddButton(btnOk)
         self._addApplyButton()
         self.btnSizer.Realize()
-        
-        self.mainSizer.Add(item = self.btnSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
 
+        self.mainSizer.Add(item=self.btnSizer, proportion=0,
+                           flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
+
         self.SetSizer(self.mainSizer)
         self.mainSizer.Fit(self)
 
@@ -1299,11 +1429,12 @@
     def _fullyQualifiedNames(self):
         """Adds CheckBox which determines is fully qualified names are retuned.
         """
-        self.fullyQualified = wx.CheckBox(parent = self, id = wx.ID_ANY,
-                                           label = _("Use fully-qualified map names"))
+        self.fullyQualified = wx.CheckBox(
+            parent=self, id=wx.ID_ANY,
+            label=_("Use fully-qualified map names"))
         self.fullyQualified.SetValue(True)
-        self.mainSizer.Add(item = self.fullyQualified, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
+        self.mainSizer.Add(item=self.fullyQualified, proportion=0,
+                           flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5)
 
     def _useFullyQualifiedNames(self):
         return self.fullyQualified.IsChecked()
@@ -1323,79 +1454,86 @@
         return True
 
     def _createDialogBody(self):
-        bodySizer = wx.GridBagSizer(vgap = 3, hgap = 3)
-        
+        bodySizer = wx.GridBagSizer(vgap=3, hgap=3)
+
         # layer type
-        bodySizer.Add(item = wx.StaticText(parent = self, label = _("Map type:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (0,0))
-        
-        self.layerType = wx.Choice(parent = self, id = wx.ID_ANY,
-                                   choices = self._layerTypes(), size = (100,-1))
+        bodySizer.Add(item=wx.StaticText(parent=self, label=_("Map type:")),
+                      flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(0, 0))
 
+        self.layerType = wx.Choice(parent=self, id=wx.ID_ANY,
+                                   choices=self._layerTypes(), size=(100, -1))
+
         self.layerType.SetSelection(0)
-            
-        bodySizer.Add(item = self.layerType,
-                           pos = (0,1))
+
+        bodySizer.Add(item=self.layerType,
+                      pos=(0, 1))
         self.layerType.Bind(wx.EVT_CHOICE, self.OnChangeParams)
 
         # select toggle
-        self.toggle = wx.CheckBox(parent = self, id = wx.ID_ANY,
-                                  label = _("Select toggle"))
+        self.toggle = wx.CheckBox(parent=self, id=wx.ID_ANY,
+                                  label=_("Select toggle"))
         self.toggle.SetValue(self._selectAll())
-        bodySizer.Add(item = self.toggle,
-                      flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (0,2))
-        
+        bodySizer.Add(item=self.toggle,
+                      flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(0, 2))
+
         # mapset filter
-        bodySizer.Add(item = wx.StaticText(parent = self, label = _("Mapset:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (1,0))
-        
-        self.mapset = MapsetSelect(parent = self, searchPath = True)
+        bodySizer.Add(item=wx.StaticText(parent=self, label=_("Mapset:")),
+                      flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(1, 0))
+
+        self.mapset = MapsetSelect(parent=self, searchPath=True)
         self.mapset.SetStringSelection(grass.gisenv()['MAPSET'])
-        bodySizer.Add(item = self.mapset,
-                      pos = (1,1), span = (1, 2))
-        
+        bodySizer.Add(item=self.mapset,
+                      pos=(1, 1), span=(1, 2))
+
         # map name filter
-        bodySizer.Add(item = wx.StaticText(parent = self, label = _("Pattern:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (2,0))
-        
-        self.filter = wx.TextCtrl(parent = self, id = wx.ID_ANY,
-                                  value = "",
-                                  size = (250,-1))
-        bodySizer.Add(item = self.filter,
-                      flag = wx.EXPAND,
-                      pos = (2,1), span = (1, 2))
+        bodySizer.Add(item=wx.StaticText(parent=self, label=_("Pattern:")),
+                      flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(2, 0))
 
+        self.filter = wx.TextCtrl(parent=self, id=wx.ID_ANY,
+                                  value="",
+                                  size=(250, -1))
+        bodySizer.Add(item=self.filter,
+                      flag=wx.EXPAND,
+                      pos=(2, 1), span=(1, 2))
+
         self.filter.SetFocus()
-        #TODO same text in GroupDialog
-        self.filter.SetToolTipString(_("Put here a regular expression."
-                                       " Characters '.*' stand for anything,"
-                                       " character '^' stands for the beginning"
-                                       " and '$' for the end."))
+        # TODO same text in GroupDialog
+        self.filter.SetToolTipString(
+            _(
+                "Put here a regular expression."
+                " Characters '.*' stand for anything,"
+                " character '^' stands for the beginning"
+                " and '$' for the end."))
 
-        # layer list 
-        bodySizer.Add(item = wx.StaticText(parent = self, label = _("List of maps:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_TOP,
-                      pos = (3,0))
-        self.layers = wx.CheckListBox(parent = self, id = wx.ID_ANY,
-                                      size = (250, 100),
-                                      choices = [])
-        bodySizer.Add(item = self.layers,
-                      flag = wx.EXPAND,
-                      pos = (3,1), span = (1, 2))
-        
+        # layer list
+        bodySizer.Add(
+            item=wx.StaticText(
+                parent=self,
+                label=_("List of maps:")),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_TOP,
+            pos=(
+                3,
+                0))
+        self.layers = wx.CheckListBox(parent=self, id=wx.ID_ANY,
+                                      size=(250, 100),
+                                      choices=[])
+        bodySizer.Add(item=self.layers,
+                      flag=wx.EXPAND,
+                      pos=(3, 1), span=(1, 2))
+
         bodySizer.AddGrowableCol(1)
         bodySizer.AddGrowableRow(3)
-        
+
         # bindings
         self.mapset.Bind(wx.EVT_TEXT, self.OnChangeParams)
         self.layers.Bind(wx.EVT_RIGHT_DOWN, self.OnMenu)
         self.filter.Bind(wx.EVT_TEXT, self.OnFilter)
         self.toggle.Bind(wx.EVT_CHECKBOX, self.OnToggle)
-        
+
         return bodySizer
 
     def LoadMapLayers(self, type, mapset):
@@ -1404,22 +1542,22 @@
         :param str type: layer type ('raster' or 'vector')
         :param str mapset: mapset name
         """
-        self.map_layers = grass.list_grouped(type = type)[mapset]
+        self.map_layers = grass.list_grouped(type=type)[mapset]
         self.layers.Set(natural_sort(self.map_layers))
-        
+
         # check all items by default
         for item in range(self.layers.GetCount()):
-            
-            self.layers.Check(item, check = self._selectAll())
-        
+
+            self.layers.Check(item, check=self._selectAll())
+
     def OnChangeParams(self, event):
         """Filter parameters changed by user"""
         # update list of layer to be loaded
-        self.LoadMapLayers(self.GetLayerType(cmd = True),
+        self.LoadMapLayers(self.GetLayerType(cmd=True),
                            self.mapset.GetStringSelection())
-        
+
         event.Skip()
-        
+
     def OnMenu(self, event):
         """Table description area, context menu"""
         if not hasattr(self, "popupID1"):
@@ -1427,16 +1565,16 @@
             self.popupDataID2 = wx.NewId()
             self.popupDataID3 = wx.NewId()
 
-            self.Bind(wx.EVT_MENU, self.OnSelectAll,    id = self.popupDataID1)
-            self.Bind(wx.EVT_MENU, self.OnSelectInvert, id = self.popupDataID2)
-            self.Bind(wx.EVT_MENU, self.OnDeselectAll,  id = self.popupDataID3)
-        
+            self.Bind(wx.EVT_MENU, self.OnSelectAll, id=self.popupDataID1)
+            self.Bind(wx.EVT_MENU, self.OnSelectInvert, id=self.popupDataID2)
+            self.Bind(wx.EVT_MENU, self.OnDeselectAll, id=self.popupDataID3)
+
         # generate popup-menu
         menu = wx.Menu()
         menu.Append(self.popupDataID1, _("Select all"))
         menu.Append(self.popupDataID2, _("Invert selection"))
         menu.Append(self.popupDataID3, _("Deselect all"))
-        
+
         self.PopupMenu(menu)
         menu.Destroy()
 
@@ -1444,7 +1582,7 @@
         """Select all map layer from list"""
         for item in range(self.layers.GetCount()):
             self.layers.Check(item, True)
-        
+
     def OnSelectInvert(self, event):
         """Invert current selection"""
         for item in range(self.layers.GetCount()):
@@ -1452,18 +1590,18 @@
                 self.layers.Check(item, False)
             else:
                 self.layers.Check(item, True)
-        
+
     def OnDeselectAll(self, event):
         """Select all map layer from list"""
         for item in range(self.layers.GetCount()):
             self.layers.Check(item, False)
-        
+
     def OnFilter(self, event):
         """Apply filter for map names"""
         if len(event.GetString()) == 0:
-            self.layers.Set(self.map_layers) 
-            return 
-        
+            self.layers.Set(self.map_layers)
+            return
+
         list = []
         for layer in self.map_layers:
             try:
@@ -1475,17 +1613,17 @@
 
         self.layers.Set(list)
         self.OnSelectAll(None)
-        
+
         event.Skip()
-        
+
     def OnToggle(self, event):
         """Select toggle (check or uncheck all layers)"""
         check = event.Checked()
         for item in range(self.layers.GetCount()):
             self.layers.Check(item, check)
-        
+
         event.Skip()
-        
+
     def GetMapLayers(self):
         """Return list of checked map layers"""
         layerNames = []
@@ -1501,17 +1639,17 @@
                 layerNames.append(self.layers.GetString(item) + '@' + mapset)
             else:
                 layerNames.append(self.layers.GetString(item))
-        
+
         return layerNames
-    
-    def GetLayerType(self, cmd = False):
+
+    def GetLayerType(self, cmd=False):
         """Get selected layer type
 
         :param bool cmd: True for g.list
         """
         if not cmd:
             return self.layerType.GetStringSelection()
-        
+
         sel = self.layerType.GetSelection()
         if sel == 0:
             ltype = 'raster'
@@ -1519,36 +1657,42 @@
             ltype = 'raster_3d'
         else:
             ltype = 'vector'
-        
+
         return ltype
 
+
 class MapLayersDialog(MapLayersDialogBase):
-    """Subclass of MapLayersDialogBase used in Layer Manager. 
+    """Subclass of MapLayersDialogBase used in Layer Manager.
 
     Contains apply button, which sends wxApplyMapLayers event.
     """
+
     def __init__(self, parent, title, **kwargs):
-        MapLayersDialogBase.__init__(self, parent = parent, title = title, **kwargs)
+        MapLayersDialogBase.__init__(
+            self, parent=parent, title=title, **kwargs)
 
     def _addApplyButton(self):
-        btnApply = wx.Button(parent = self, id = wx.ID_APPLY)
+        btnApply = wx.Button(parent=self, id=wx.ID_APPLY)
         self.btnSizer.AddButton(btnApply)
         btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
 
     def OnApply(self, event):
-        self.applyAddingMapLayers.emit(mapLayers = self.GetMapLayers(),
-                                       ltype = self.GetLayerType(cmd = True))
+        self.applyAddingMapLayers.emit(mapLayers=self.GetMapLayers(),
+                                       ltype=self.GetLayerType(cmd=True))
 
+
 class MapLayersDialogForGroups(MapLayersDialogBase):
-    """Subclass of MapLayersDialogBase used for specyfying maps in an imagery group. 
+    """Subclass of MapLayersDialogBase used for specyfying maps in an imagery group.
 
     Shows only raster maps.
     """
+
     def __init__(self, parent, title, **kwargs):
-        MapLayersDialogBase.__init__(self, parent = parent, title = title, **kwargs)
+        MapLayersDialogBase.__init__(
+            self, parent=parent, title=title, **kwargs)
 
     def _layerTypes(self):
-        return [_('raster'),]
+        return [_('raster'), ]
 
     def _selectAll(self):
         """Could be overriden"""
@@ -1562,17 +1706,19 @@
 
 
 class MapLayersDialogForModeler(MapLayersDialogBase):
-    """Subclass of MapLayersDialogBase used in Modeler. 
+    """Subclass of MapLayersDialogBase used in Modeler.
     """
+
     def __init__(self, parent, title, **kwargs):
-        MapLayersDialogBase.__init__(self, parent = parent, title = title, **kwargs)
+        MapLayersDialogBase.__init__(
+            self, parent=parent, title=title, **kwargs)
 
     def _modelerDSeries(self):
-        self.dseries = wx.CheckBox(parent = self, id = wx.ID_ANY,
-                                   label = _("Dynamic series (%s)") % 'g.list')
+        self.dseries = wx.CheckBox(parent=self, id=wx.ID_ANY,
+                                   label=_("Dynamic series (%s)") % 'g.list')
         self.dseries.SetValue(False)
-        self.mainSizer.Add(item = self.dseries, proportion = 0,
-                           flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
+        self.mainSizer.Add(item=self.dseries, proportion=0,
+                           flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5)
 
     def GetDSeries(self):
         """Used by modeler only
@@ -1581,76 +1727,84 @@
         """
         if not self.dseries or not self.dseries.IsChecked():
             return ''
-        
-        cond = 'map in `g.list type=%s ' % self.GetLayerType(cmd = True)
+
+        cond = 'map in `g.list type=%s ' % self.GetLayerType(cmd=True)
         patt = self.filter.GetValue()
         if patt:
             cond += 'pattern=%s ' % patt
         cond += 'mapset=%s`' % self.mapset.GetStringSelection()
-        
+
         return cond
 
+
 class SetOpacityDialog(wx.Dialog):
     """Set opacity of map layers.
-    Dialog expects opacity between 0 and 1 and returns this range, too.    
+    Dialog expects opacity between 0 and 1 and returns this range, too.
     """
-    def __init__(self, parent, id = wx.ID_ANY, title = _("Set Map Layer Opacity"),
-                 size = wx.DefaultSize, pos = wx.DefaultPosition,
-                 style = wx.DEFAULT_DIALOG_STYLE, opacity = 1):
 
+    def __init__(self, parent, id=wx.ID_ANY, title=_("Set Map Layer Opacity"),
+                 size=wx.DefaultSize, pos=wx.DefaultPosition,
+                 style=wx.DEFAULT_DIALOG_STYLE, opacity=1):
+
         self.parent = parent    # GMFrame
         self.opacity = opacity  # current opacity
 
-        super(SetOpacityDialog, self).__init__(parent, id = id, pos = pos,
-                                               size = size, style = style, title = title)
+        super(
+            SetOpacityDialog,
+            self).__init__(
+            parent,
+            id=id,
+            pos=pos,
+            size=size,
+            style=style,
+            title=title)
 
         self.applyOpacity = Signal('SetOpacityDialog.applyOpacity')
-        panel = wx.Panel(parent = self, id = wx.ID_ANY)
-        
+        panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
         sizer = wx.BoxSizer(wx.VERTICAL)
 
-        box = wx.GridBagSizer(vgap = 5, hgap = 5)
-        self.value = wx.Slider(panel, id = wx.ID_ANY, value = int(self.opacity * 100),
-                               style = wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | \
-                                   wx.SL_TOP | wx.SL_LABELS,
-                               minValue = 0, maxValue = 100,
-                               size = (350, -1))
+        box = wx.GridBagSizer(vgap=5, hgap=5)
+        self.value = wx.Slider(
+            panel, id=wx.ID_ANY, value=int(self.opacity * 100),
+            style=wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_TOP | wx.SL_LABELS,
+            minValue=0, maxValue=100, size=(350, -1))
 
-        box.Add(item = self.value,
-                flag = wx.ALIGN_CENTRE, pos = (0, 0), span = (1, 2))
-        box.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                   label = _("transparent")),
-                pos = (1, 0))
-        box.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                   label = _("opaque")),
-                flag = wx.ALIGN_RIGHT,
-                pos = (1, 1))
+        box.Add(item=self.value,
+                flag=wx.ALIGN_CENTRE, pos=(0, 0), span=(1, 2))
+        box.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                   label=_("transparent")),
+                pos=(1, 0))
+        box.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                   label=_("opaque")),
+                flag=wx.ALIGN_RIGHT,
+                pos=(1, 1))
 
-        sizer.Add(item = box, proportion = 0,
-                  flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
+        sizer.Add(item=box, proportion=0,
+                  flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
 
-        line = wx.StaticLine(parent = panel, id = wx.ID_ANY,
-                             style = wx.LI_HORIZONTAL)
-        sizer.Add(item = line, proportion = 0,
-                  flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
+        line = wx.StaticLine(parent=panel, id=wx.ID_ANY,
+                             style=wx.LI_HORIZONTAL)
+        sizer.Add(item=line, proportion=0,
+                  flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
 
         # buttons
         btnsizer = wx.StdDialogButtonSizer()
 
-        btnOK = wx.Button(parent = panel, id = wx.ID_OK)
+        btnOK = wx.Button(parent=panel, id=wx.ID_OK)
         btnOK.SetDefault()
         btnsizer.AddButton(btnOK)
 
-        btnCancel = wx.Button(parent = panel, id = wx.ID_CANCEL)
+        btnCancel = wx.Button(parent=panel, id=wx.ID_CANCEL)
         btnsizer.AddButton(btnCancel)
 
-        btnApply = wx.Button(parent = panel, id = wx.ID_APPLY)
+        btnApply = wx.Button(parent=panel, id=wx.ID_APPLY)
         btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
         btnsizer.AddButton(btnApply)
         btnsizer.Realize()
 
-        sizer.Add(item = btnsizer, proportion = 0,
-                  flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
+        sizer.Add(item=btnsizer, proportion=0,
+                  flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
 
         panel.SetSizer(sizer)
         sizer.Fit(panel)
@@ -1666,7 +1820,7 @@
         return opacity
 
     def OnApply(self, event):
-        self.applyOpacity.emit(value = self.GetOpacity())
+        self.applyOpacity.emit(value=self.GetOpacity())
 
 
 def GetImageHandlers(image):
@@ -1675,131 +1829,139 @@
     ltype = list()
     for h in image.GetHandlers():
         lext.append(h.GetExtension())
-        
+
     filetype = ''
     if 'png' in lext:
         filetype += "PNG file (*.png)|*.png|"
-        ltype.append({ 'type' : wx.BITMAP_TYPE_PNG,
-                       'ext'  : 'png' })
-    filetype +=  "BMP file (*.bmp)|*.bmp|"
-    ltype.append({ 'type' : wx.BITMAP_TYPE_BMP,
-                   'ext'  : 'bmp' })
+        ltype.append({'type': wx.BITMAP_TYPE_PNG,
+                      'ext': 'png'})
+    filetype += "BMP file (*.bmp)|*.bmp|"
+    ltype.append({'type': wx.BITMAP_TYPE_BMP,
+                  'ext': 'bmp'})
     if 'gif' in lext:
         filetype += "GIF file (*.gif)|*.gif|"
-        ltype.append({ 'type' : wx.BITMAP_TYPE_GIF,
-                       'ext'  : 'gif' })
-        
+        ltype.append({'type': wx.BITMAP_TYPE_GIF,
+                      'ext': 'gif'})
+
     if 'jpg' in lext:
         filetype += "JPG file (*.jpg)|*.jpg|"
-        ltype.append({ 'type' : wx.BITMAP_TYPE_JPEG,
-                       'ext'  : 'jpg' })
+        ltype.append({'type': wx.BITMAP_TYPE_JPEG,
+                      'ext': 'jpg'})
 
     if 'pcx' in lext:
         filetype += "PCX file (*.pcx)|*.pcx|"
-        ltype.append({ 'type' : wx.BITMAP_TYPE_PCX,
-                       'ext'  : 'pcx' })
-        
+        ltype.append({'type': wx.BITMAP_TYPE_PCX,
+                      'ext': 'pcx'})
+
     if 'pnm' in lext:
         filetype += "PNM file (*.pnm)|*.pnm|"
-        ltype.append({ 'type' : wx.BITMAP_TYPE_PNM,
-                       'ext'  : 'pnm' })
+        ltype.append({'type': wx.BITMAP_TYPE_PNM,
+                      'ext': 'pnm'})
 
     if 'tif' in lext:
         filetype += "TIF file (*.tif)|*.tif|"
-        ltype.append({ 'type' : wx.BITMAP_TYPE_TIF,
-                       'ext'  : 'tif' })
+        ltype.append({'type': wx.BITMAP_TYPE_TIF,
+                      'ext': 'tif'})
 
     if 'xpm' in lext:
         filetype += "XPM file (*.xpm)|*.xpm"
-        ltype.append({ 'type' : wx.BITMAP_TYPE_XPM,
-                       'ext'  : 'xpm' })
-    
+        ltype.append({'type': wx.BITMAP_TYPE_XPM,
+                      'ext': 'xpm'})
+
     return filetype, ltype
 
+
 class ImageSizeDialog(wx.Dialog):
     """Set size for saved graphic file"""
-    def __init__(self, parent, id = wx.ID_ANY, title = _("Set image size"),
-                 style = wx.DEFAULT_DIALOG_STYLE, **kwargs):
+
+    def __init__(self, parent, id=wx.ID_ANY, title=_("Set image size"),
+                 style=wx.DEFAULT_DIALOG_STYLE, **kwargs):
         self.parent = parent
-        
-        wx.Dialog.__init__(self, parent, id = id, style = style, title = title, **kwargs)
-        
-        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
-        
-        self.box = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
-                                label = ' % s' % _("Image size"))
-        
+
+        wx.Dialog.__init__(
+            self,
+            parent,
+            id=id,
+            style=style,
+            title=title,
+            **kwargs)
+
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
+        self.box = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
+                                label=' % s' % _("Image size"))
+
         size = self.parent.GetWindow().GetClientSize()
-        self.width = wx.SpinCtrl(parent = self.panel, id = wx.ID_ANY,
-                                 style = wx.SP_ARROW_KEYS)
+        self.width = wx.SpinCtrl(parent=self.panel, id=wx.ID_ANY,
+                                 style=wx.SP_ARROW_KEYS)
         self.width.SetRange(20, 1e6)
         self.width.SetValue(size.width)
         wx.CallAfter(self.width.SetFocus)
-        self.height = wx.SpinCtrl(parent = self.panel, id = wx.ID_ANY,
-                                  style = wx.SP_ARROW_KEYS)
+        self.height = wx.SpinCtrl(parent=self.panel, id=wx.ID_ANY,
+                                  style=wx.SP_ARROW_KEYS)
         self.height.SetRange(20, 1e6)
         self.height.SetValue(size.height)
-        self.template = wx.Choice(parent = self.panel, id = wx.ID_ANY,
-                                  size = (125, -1),
-                                  choices = [ "",
-                                              "640x480",
-                                              "800x600",
-                                              "1024x768",
-                                              "1280x960",
-                                              "1600x1200",
-                                              "1920x1440" ])
-        
-        self.btnOK = wx.Button(parent = self.panel, id = wx.ID_OK)
+        self.template = wx.Choice(parent=self.panel, id=wx.ID_ANY,
+                                  size=(125, -1),
+                                  choices=["",
+                                           "640x480",
+                                           "800x600",
+                                           "1024x768",
+                                           "1280x960",
+                                           "1600x1200",
+                                           "1920x1440"])
+
+        self.btnOK = wx.Button(parent=self.panel, id=wx.ID_OK)
         self.btnOK.SetDefault()
-        self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
-        
+        self.btnCancel = wx.Button(parent=self.panel, id=wx.ID_CANCEL)
+
         self.template.Bind(wx.EVT_CHOICE, self.OnTemplate)
-        
+
         self._layout()
         self.SetSize(self.GetBestSize())
-        
+
     def _layout(self):
         """Do layout"""
         sizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         # body
         box = wx.StaticBoxSizer(self.box, wx.HORIZONTAL)
-        fbox = wx.FlexGridSizer(cols = 2, vgap = 5, hgap = 5)
-        fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                      label = _("Width:")),
-                 flag = wx.ALIGN_CENTER_VERTICAL)
-        fbox.Add(item = self.width)
-        fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                      label = _("Height:")),
-                 flag = wx.ALIGN_CENTER_VERTICAL)
-        fbox.Add(item = self.height)
-        fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                      label = _("Template:")),
-                 flag = wx.ALIGN_CENTER_VERTICAL)
-        fbox.Add(item = self.template)
-        
-        box.Add(item = fbox, proportion = 1,
-                flag = wx.EXPAND | wx.ALL, border = 5)
-        sizer.Add(item = box, proportion = 1,
-                  flag=wx.EXPAND | wx.ALL, border = 3)
-        
+        fbox = wx.FlexGridSizer(cols=2, vgap=5, hgap=5)
+        fbox.Add(item=wx.StaticText(parent=self.panel, id=wx.ID_ANY,
+                                    label=_("Width:")),
+                 flag=wx.ALIGN_CENTER_VERTICAL)
+        fbox.Add(item=self.width)
+        fbox.Add(item=wx.StaticText(parent=self.panel, id=wx.ID_ANY,
+                                    label=_("Height:")),
+                 flag=wx.ALIGN_CENTER_VERTICAL)
+        fbox.Add(item=self.height)
+        fbox.Add(item=wx.StaticText(parent=self.panel, id=wx.ID_ANY,
+                                    label=_("Template:")),
+                 flag=wx.ALIGN_CENTER_VERTICAL)
+        fbox.Add(item=self.template)
+
+        box.Add(item=fbox, proportion=1,
+                flag=wx.EXPAND | wx.ALL, border=5)
+        sizer.Add(item=box, proportion=1,
+                  flag=wx.EXPAND | wx.ALL, border=3)
+
         # buttons
         btnsizer = wx.StdDialogButtonSizer()
         btnsizer.AddButton(self.btnOK)
         btnsizer.AddButton(self.btnCancel)
         btnsizer.Realize()
 
-        sizer.Add(item = btnsizer, proportion = 0,
-                  flag = wx.EXPAND | wx.ALIGN_RIGHT | wx.ALL, border=5)
-        
+        sizer.Add(item=btnsizer, proportion=0,
+                  flag=wx.EXPAND | wx.ALIGN_RIGHT | wx.ALL, border=5)
+
         self.panel.SetSizer(sizer)
         sizer.Fit(self.panel)
         self.Layout()
-    
+
     def GetValues(self):
         """Get width/height values"""
         return self.width.GetValue(), self.height.GetValue()
-    
+
     def OnTemplate(self, event):
         """Template selected"""
         sel = event.GetString()
@@ -1809,53 +1971,60 @@
             width, height = map(int, sel.split('x'))
         self.width.SetValue(width)
         self.height.SetValue(height)
-        
+
+
 class SqlQueryFrame(wx.Frame):
-    def __init__(self, parent, id = wx.ID_ANY,
-                 title = _("GRASS GIS SQL Query Utility"),
+
+    def __init__(self, parent, id=wx.ID_ANY,
+                 title=_("GRASS GIS SQL Query Utility"),
                  *kwargs):
         """SQL Query Utility window
         """
         self.parent = parent
 
-        wx.Frame.__init__(self, parent = parent, id = id, title = title, *kwargs)
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass_sql.ico'), wx.BITMAP_TYPE_ICO))
-        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
-        
-        self.sqlBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
-                                   label = _(" SQL statement "))
-        self.sql = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
-                               style = wx.TE_MULTILINE)
-        
-        self.btnApply = wx.Button(parent = self.panel, id = wx.ID_APPLY)
-        self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
+        wx.Frame.__init__(self, parent=parent, id=id, title=title, *kwargs)
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass_sql.ico'),
+                wx.BITMAP_TYPE_ICO))
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
+        self.sqlBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
+                                   label=_(" SQL statement "))
+        self.sql = wx.TextCtrl(parent=self.panel, id=wx.ID_ANY,
+                               style=wx.TE_MULTILINE)
+
+        self.btnApply = wx.Button(parent=self.panel, id=wx.ID_APPLY)
+        self.btnCancel = wx.Button(parent=self.panel, id=wx.ID_CANCEL)
         self.Bind(wx.EVT_BUTTON, self.OnCloseWindow, self.btnCancel)
-        
+
         self._layout()
 
         self.SetMinSize(wx.Size(300, 150))
         self.SetSize(wx.Size(500, 200))
-        
+
     def _layout(self):
         """Do layout"""
         sizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         sqlSizer = wx.StaticBoxSizer(self.sqlBox, wx.HORIZONTAL)
-        sqlSizer.Add(item = self.sql, proportion = 1,
-                     flag = wx.EXPAND)
+        sqlSizer.Add(item=self.sql, proportion=1,
+                     flag=wx.EXPAND)
 
         btnSizer = wx.StdDialogButtonSizer()
         btnSizer.AddButton(self.btnApply)
         btnSizer.AddButton(self.btnCancel)
         btnSizer.Realize()
-        
-        sizer.Add(item = sqlSizer, proportion = 1,
-                  flag = wx.EXPAND | wx.ALL, border = 5) 
-        sizer.Add(item = btnSizer, proportion = 0,
-                  flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
-       
+
+        sizer.Add(item=sqlSizer, proportion=1,
+                  flag=wx.EXPAND | wx.ALL, border=5)
+        sizer.Add(item=btnSizer, proportion=0,
+                  flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
+
         self.panel.SetSizer(sizer)
-        
+
         self.Layout()
 
     def OnCloseWindow(self, event):
@@ -1863,83 +2032,99 @@
         """
         self.Close()
 
+
 class SymbolDialog(wx.Dialog):
     """Dialog for GRASS symbols selection.
-    
+
     Dialog is called in gui_core::forms module.
     """
-    def __init__(self, parent, symbolPath, currentSymbol = None, title = _("Symbols")):
+
+    def __init__(self, parent, symbolPath,
+                 currentSymbol=None, title=_("Symbols")):
         """Dialog constructor.
-        
+
         It is assumed that symbolPath contains folders with symbols.
-        
+
         :param parent: dialog parent
         :param symbolPath: absolute path to symbols
         :param currentSymbol: currently selected symbol (e.g. 'basic/x')
         :param title: dialog title
         """
-        wx.Dialog.__init__(self, parent = parent, title = title, id = wx.ID_ANY)
-        
+        wx.Dialog.__init__(self, parent=parent, title=title, id=wx.ID_ANY)
+
         self.symbolPath = symbolPath
-        self.currentSymbol = currentSymbol # default basic/x
+        self.currentSymbol = currentSymbol  # default basic/x
         self.selected = None
         self.selectedDir = None
-        
+
         self._layout()
-        
+
     def _layout(self):
-        mainPanel = wx.Panel(self, id = wx.ID_ANY)
+        mainPanel = wx.Panel(self, id=wx.ID_ANY)
         mainSizer = wx.BoxSizer(wx.VERTICAL)
-        vSizer = wx.BoxSizer( wx.VERTICAL)
-        fgSizer = wx.FlexGridSizer(rows = 2, vgap = 5, hgap = 5)
-        self.folderChoice = wx.Choice(mainPanel, id = wx.ID_ANY, choices = os.listdir(self.symbolPath))
+        vSizer = wx.BoxSizer(wx.VERTICAL)
+        fgSizer = wx.FlexGridSizer(rows=2, vgap=5, hgap=5)
+        self.folderChoice = wx.Choice(
+            mainPanel,
+            id=wx.ID_ANY,
+            choices=os.listdir(
+                self.symbolPath))
         self.folderChoice.Bind(wx.EVT_CHOICE, self.OnFolderSelect)
-        
-        fgSizer.Add(item = wx.StaticText(mainPanel, id = wx.ID_ANY, label = _("Symbol directory:")),
-                   proportion = 0,
-                   flag = wx.ALIGN_CENTER_VERTICAL)
-                   
-        fgSizer.Add(item = self.folderChoice, proportion = 0,
-                   flag = wx.ALIGN_CENTER, border = 0)
-                   
-        self.infoLabel = wx.StaticText(mainPanel, id = wx.ID_ANY)
-        fgSizer.Add(wx.StaticText(mainPanel, id = wx.ID_ANY, label = _("Symbol name:")), 
-                    flag = wx.ALIGN_CENTRE_VERTICAL)
-        fgSizer.Add(self.infoLabel, proportion = 0, 
-                    flag = wx.ALIGN_CENTRE_VERTICAL)
-        vSizer.Add(fgSizer, proportion = 0, flag = wx.ALL, border = 5)
-        
+
+        fgSizer.Add(
+            item=wx.StaticText(
+                mainPanel,
+                id=wx.ID_ANY,
+                label=_("Symbol directory:")),
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL)
+
+        fgSizer.Add(item=self.folderChoice, proportion=0,
+                    flag=wx.ALIGN_CENTER, border=0)
+
+        self.infoLabel = wx.StaticText(mainPanel, id=wx.ID_ANY)
+        fgSizer.Add(
+            wx.StaticText(
+                mainPanel,
+                id=wx.ID_ANY,
+                label=_("Symbol name:")),
+            flag=wx.ALIGN_CENTRE_VERTICAL)
+        fgSizer.Add(self.infoLabel, proportion=0,
+                    flag=wx.ALIGN_CENTRE_VERTICAL)
+        vSizer.Add(fgSizer, proportion=0, flag=wx.ALL, border=5)
+
         self.panels = self._createSymbolPanels(mainPanel)
         for panel in self.panels:
-            vSizer.Add(panel, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
-        mainSizer.Add(vSizer, proportion = 1, flag = wx.ALL| wx.EXPAND, border = 5)
-        self.btnCancel = wx.Button(parent = mainPanel, id = wx.ID_CANCEL)
-        self.btnOK     = wx.Button(parent = mainPanel, id = wx.ID_OK)
+            vSizer.Add(panel, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
+        mainSizer.Add(vSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)
+        self.btnCancel = wx.Button(parent=mainPanel, id=wx.ID_CANCEL)
+        self.btnOK = wx.Button(parent=mainPanel, id=wx.ID_OK)
         self.btnOK.SetDefault()
         self.btnOK.Enable(False)
-        
+
         # buttons
         btnSizer = wx.StdDialogButtonSizer()
         btnSizer.AddButton(self.btnCancel)
         btnSizer.AddButton(self.btnOK)
         btnSizer.Realize()
-        mainSizer.Add(item = btnSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL, border = 5)
-                      
+        mainSizer.Add(item=btnSizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALL, border=5)
+
         # show panel with the largest number of images and fit size
         count = []
         for folder in os.listdir(self.symbolPath):
-            count.append(len(os.listdir(os.path.join(self.symbolPath, folder))))
-            
+            count.append(
+                len(os.listdir(os.path.join(self.symbolPath, folder))))
+
         index = count.index(max(count))
         self.folderChoice.SetSelection(index)
         self.OnFolderSelect(None)
         self.infoLabel.Show()
-        
+
         mainPanel.SetSizerAndFit(mainSizer)
         self.SetSize(self.GetBestSize())
-        
+
         # show currently selected symbol
         if self.currentSymbol:
             # set directory
@@ -1952,60 +2137,62 @@
                     panel.Select()
         else:
             self.folderChoice.SetSelection(0)
-            
+
         self.OnFolderSelect(None)
-        
+
     def _createSymbolPanels(self, parent):
         """Creates multiple panels with symbols.
-        
+
         Panels are shown/hidden according to selected folder."""
         folders = os.listdir(self.symbolPath)
-        
+
         panels = []
         self.symbolPanels = []
-        
+
         for folder in folders:
-            panel = wx.Panel(parent, style = wx.BORDER_RAISED)
-            sizer = wx.GridSizer(cols = 6, vgap = 3, hgap = 3)
-            images = self._getSymbols(path = os.path.join(self.symbolPath, folder))
-        
+            panel = wx.Panel(parent, style=wx.BORDER_RAISED)
+            sizer = wx.GridSizer(cols=6, vgap=3, hgap=3)
+            images = self._getSymbols(
+                path=os.path.join(
+                    self.symbolPath, folder))
+
             symbolPanels = []
             for img in images:
-                iP = SingleSymbolPanel(parent = panel, symbolPath = img)
+                iP = SingleSymbolPanel(parent=panel, symbolPath=img)
                 iP.symbolSelectionChanged.connect(self.SelectionChanged)
-                sizer.Add(item = iP, proportion = 0, flag = wx.ALIGN_CENTER)
+                sizer.Add(item=iP, proportion=0, flag=wx.ALIGN_CENTER)
                 symbolPanels.append(iP)
-            
+
             panel.SetSizerAndFit(sizer)
             panel.Hide()
             panels.append(panel)
             self.symbolPanels.append(symbolPanels)
-            
+
         return panels
-        
+
     def _getSymbols(self, path):
         # we assume that images are in subfolders (1 level only)
         imageList = []
         for image in os.listdir(path):
             imageList.append(os.path.join(path, image))
-                
+
         return sorted(imageList)
-            
+
     def OnFolderSelect(self, event):
         """Selected folder with symbols changed."""
         idx = self.folderChoice.GetSelection()
         for i in range(len(self.panels)):
             sizer = self.panels[i].GetContainingSizer()
-            sizer.Show(self.panels[i], i == idx, recursive = True)
+            sizer.Show(self.panels[i], i == idx, recursive=True)
             sizer.Layout()
-        
+
         if self.selectedDir == self.folderChoice.GetStringSelection():
             self.btnOK.Enable()
             self.infoLabel.SetLabel(self.selected)
         else:
             self.btnOK.Disable()
             self.infoLabel.SetLabel('')
-        
+
     def SelectionChanged(self, name, doubleClick):
         """Selected symbol changed."""
         if doubleClick:
@@ -2015,14 +2202,14 @@
             for panel in self.symbolPanels[i]:
                 if panel.GetName() != name:
                     panel.Deselect()
-                
+
         self.btnOK.Enable()
-        
+
         self.selected = name
         self.selectedDir = self.folderChoice.GetStringSelection()
-        
+
         self.infoLabel.SetLabel(name)
-        
+
     def GetSelectedSymbolName(self):
         """Returns currently selected symbol name (e.g. 'basic/x').
         """
@@ -2036,34 +2223,49 @@
 
 
 class TextEntryDialog(wx.Dialog):
-    """Simple dialog with text field. 
+    """Simple dialog with text field.
 
     It differs from wx.TextEntryDialog because it allows adding validator.
     """
-    def __init__(self, parent, message, caption='',
-                 defaultValue='', validator=wx.DefaultValidator, 
-                 style=wx.OK | wx.CANCEL | wx.CENTRE, textStyle=0, textSize=(300, -1),
-                 **kwargs):
-        wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=caption, **kwargs)
 
+    def __init__(
+            self, parent, message, caption='', defaultValue='',
+            validator=wx.DefaultValidator, style=wx.OK | wx.CANCEL | wx.CENTRE,
+            textStyle=0, textSize=(300, -1),
+            **kwargs):
+        wx.Dialog.__init__(
+            self,
+            parent=parent,
+            id=wx.ID_ANY,
+            title=caption,
+            **kwargs)
+
         vbox = wx.BoxSizer(wx.VERTICAL)
 
         stline = wx.StaticText(self, id=wx.ID_ANY, label=message)
         vbox.Add(item=stline, proportion=0, flag=wx.EXPAND | wx.ALL, border=10)
 
-        self._textCtrl = wx.TextCtrl(self, id=wx.ID_ANY,
-                                     value=defaultValue, validator=validator, style=textStyle)
+        self._textCtrl = wx.TextCtrl(
+            self,
+            id=wx.ID_ANY,
+            value=defaultValue,
+            validator=validator,
+            style=textStyle)
         self._textCtrl.SetInitialSize(textSize)
         wx.CallAfter(self._textCtrl.SetFocus)
-        
-        vbox.Add(item=self._textCtrl, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=10)
+
+        vbox.Add(
+            item=self._textCtrl,
+            proportion=0,
+            flag=wx.EXPAND | wx.LEFT | wx.RIGHT,
+            border=10)
         self._textCtrl.SetFocus()
 
         sizer = self.CreateSeparatedButtonSizer(style)
         vbox.Add(item=sizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)
 
         self.SetSizerAndFit(vbox)
-        
+
     def GetValue(self):
         return self._textCtrl.GetValue()
 
@@ -2073,11 +2275,12 @@
 
 class HyperlinkDialog(wx.Dialog):
     """Dialog for displaying message with hyperlink."""
+
     def __init__(self, parent, title, message, hyperlink,
-                hyperlinkLabel=None, style=wx.OK):
+                 hyperlinkLabel=None, style=wx.OK):
         """Constructor
 
-        :param parent: gui parent         
+        :param parent: gui parent
         :param title: dialog title
         :param message: message
         :param hyperlink: url
@@ -2090,74 +2293,92 @@
         sizer = wx.BoxSizer(wx.VERTICAL)
 
         label = wx.StaticText(self, label=message)
-        sizer.Add(item=label, proportion=0, flag=wx.ALIGN_CENTRE|wx.ALL, border=10)
+        sizer.Add(
+            item=label,
+            proportion=0,
+            flag=wx.ALIGN_CENTRE | wx.ALL,
+            border=10)
         hyperlinkLabel = hyperlinkLabel if hyperlinkLabel else hyperlink
-        hyperlinkCtrl = wx.HyperlinkCtrl(self, id=wx.ID_ANY,
-                                         label=hyperlinkLabel, url=hyperlink,
-                                         style=wx.HL_ALIGN_LEFT|wx.HL_CONTEXTMENU)
-        sizer.Add(item=hyperlinkCtrl, proportion=0, flag=wx.EXPAND|wx.ALL, border=10)        
+        hyperlinkCtrl = wx.HyperlinkCtrl(
+            self, id=wx.ID_ANY, label=hyperlinkLabel, url=hyperlink,
+            style=wx.HL_ALIGN_LEFT | wx.HL_CONTEXTMENU)
+        sizer.Add(
+            item=hyperlinkCtrl,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=10)
 
         btnsizer = self.CreateSeparatedButtonSizer(style)
-        sizer.Add(item=btnsizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)
-    
+        sizer.Add(
+            item=btnsizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=10)
+
         self.SetSizer(sizer)
         sizer.Fit(self)
 
+
 class QuitDialog(wx.Dialog):
+
     def __init__(self, parent, title=_("Quit GRASS GIS"), id=wx.ID_ANY,
                  style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
         """Dialog to quit GRASS
-        
+
         :param parent: window
         """
         wx.Dialog.__init__(self, parent, id, title, style=style, **kwargs)
-        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
 
-        self._icon = wx.StaticBitmap(parent=self.panel, id=wx.ID_ANY,
-                                     bitmap=wx.ArtProvider().GetBitmap(wx.ART_QUESTION, client=wx.ART_MESSAGE_BOX))
+        self._icon = wx.StaticBitmap(
+            parent=self.panel,
+            id=wx.ID_ANY,
+            bitmap=wx.ArtProvider().GetBitmap(
+                wx.ART_QUESTION,
+                client=wx.ART_MESSAGE_BOX))
 
-        self.informLabel = wx.StaticText(parent=self.panel, id=wx.ID_ANY,
-                                         label=_("Do you want to quit GRASS including shell "
-                                                 "prompt or just close the GUI?"))
-        self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
-        self.btnClose = wx.Button(parent = self.panel, id = wx.ID_NO,
-                                   label=_("Close GUI"))
+        self.informLabel = wx.StaticText(
+            parent=self.panel, id=wx.ID_ANY, label=_(
+                "Do you want to quit GRASS including shell "
+                "prompt or just close the GUI?"))
+        self.btnCancel = wx.Button(parent=self.panel, id=wx.ID_CANCEL)
+        self.btnClose = wx.Button(parent=self.panel, id=wx.ID_NO,
+                                  label=_("Close GUI"))
         self.btnClose.SetFocus()
-        self.btnQuit = wx.Button(parent = self.panel, id = wx.ID_YES,
-                                   label=_("Quit GRASS GIS"))
+        self.btnQuit = wx.Button(parent=self.panel, id=wx.ID_YES,
+                                 label=_("Quit GRASS GIS"))
         self.btnQuit.SetMinSize((130, self.btnQuit.GetSize()[1]))
         self.btnQuit.SetForegroundColour(wx.Colour(35, 142, 35))
-        
+
         self.btnClose.Bind(wx.EVT_BUTTON, self.OnClose)
         self.btnQuit.Bind(wx.EVT_BUTTON, self.OnQuit)
-        
+
         self.__layout()
 
     def __layout(self):
         """Do layout"""
         sizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         btnSizer = wx.BoxSizer(wx.HORIZONTAL)
         btnSizer.Add(item=self.btnCancel, flag=wx.RIGHT, border=5)
         btnSizer.Add(item=self.btnClose, flag=wx.RIGHT, border=5)
         btnSizer.Add(item=self.btnQuit, flag=wx.RIGHT, border=5)
-        
+
         bodySizer = wx.BoxSizer(wx.HORIZONTAL)
         bodySizer.Add(item=self._icon, flag=wx.RIGHT, border=10)
         bodySizer.Add(item=self.informLabel, proportion=1, flag=wx.EXPAND)
-        
-        sizer.Add(item = bodySizer, proportion = 1,
-                  flag = wx.EXPAND | wx.ALL, border = 15)
-        sizer.Add(item = btnSizer, proportion = 0,
-                  flag = wx.ALL | wx.ALIGN_RIGHT, border = 5)
 
+        sizer.Add(item=bodySizer, proportion=1,
+                  flag=wx.EXPAND | wx.ALL, border=15)
+        sizer.Add(item=btnSizer, proportion=0,
+                  flag=wx.ALL | wx.ALIGN_RIGHT, border=5)
+
         self.panel.SetSizer(sizer)
         sizer.Fit(self)
         self.Layout()
-        
+
     def OnClose(self, event):
         self.EndModal(wx.ID_NO)
 
     def OnQuit(self, event):
         self.EndModal(wx.ID_YES)
-        

Modified: grass/trunk/gui/wxpython/gui_core/forms.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/forms.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gui_core/forms.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -68,14 +68,14 @@
     import wx.lib.agw.flatnotebook as FN
 except ImportError:
     import wx.lib.flatnotebook as FN
-import wx.lib.colourselect     as csel
+import wx.lib.colourselect as csel
 import wx.lib.filebrowsebutton as filebrowse
 from wx.lib.newevent import NewEvent
 
 try:
     import xml.etree.ElementTree as etree
 except ImportError:
-    import elementtree.ElementTree as etree # Python <= 2.4
+    import elementtree.ElementTree as etree  # Python <= 2.4
 
 from grass.pydispatch.signal import Signal
 
@@ -87,13 +87,13 @@
 
 from core import globalvar
 from gui_core.widgets import StaticWrapText, ScrolledPanel, ColorTablesComboBox, \
-                             BarscalesComboBox, NArrowsComboBox
-from gui_core.ghelp   import HelpPanel
-from gui_core         import gselect
-from core             import gcmd
-from core             import utils
+    BarscalesComboBox, NArrowsComboBox
+from gui_core.ghelp import HelpPanel
+from gui_core import gselect
+from core import gcmd
+from core import utils
 from core.utils import _
-from core.settings    import UserSettings
+from core.settings import UserSettings
 from gui_core.widgets import FloatValidator, GNotebook, FormNotebook, FormListbook
 from core.giface import Notification
 from gui_core.widgets import LayersList
@@ -105,39 +105,47 @@
 #_blackList = { 'enabled' : False,
 #               'items'   : { 'r.buffer' : {'params' : ['input', 'output'],
 #                                           'flags' : ['z', 'overwrite']}}}
-_blackList = { 'enabled' : False,
-               'items'   : {} }
+_blackList = {'enabled': False,
+              'items': {}}
 
 
-def text_beautify(someString , width = 70):
+def text_beautify(someString, width=70):
     """Make really long texts shorter, clean up whitespace and remove
     trailing punctuation.
     """
     if width > 0:
-        return escape_ampersand(string.strip(
-                os.linesep.join(textwrap.wrap(utils.normalize_whitespace(someString), width)),
+        return escape_ampersand(
+            string.strip(
+                os.linesep.join(
+                    textwrap.wrap(
+                        utils.normalize_whitespace(someString),
+                        width)),
                 ".,;:"))
     else:
-        return escape_ampersand(string.strip(utils.normalize_whitespace(someString), ".,;:"))
-    
+        return escape_ampersand(string.strip(
+            utils.normalize_whitespace(someString), ".,;:"))
+
+
 def escape_ampersand(text):
     """Escapes ampersands with additional ampersand for GUI"""
     return string.replace(text, "&", "&&")
 
+
 class UpdateThread(Thread):
     """Update dialog widgets in the thread"""
+
     def __init__(self, parent, event, eventId, task):
         Thread.__init__(self)
-        
+
         self.parent = parent
         self.event = event
         self.eventId = eventId
         self.task = task
         self.setDaemon(True)
-        
+
         # list of functions which updates the dialog
         self.data = {}
-        
+
     def run(self):
         # get widget id
         if not self.eventId:
@@ -151,8 +159,8 @@
                         self.eventId = p['wxId'][0]
             if self.eventId is None:
                 return
-        
-        p = self.task.get_param(self.eventId, element = 'wxId', raiseError = False)
+
+        p = self.task.get_param(self.eventId, element='wxId', raiseError=False)
         if not p or 'wxId-bind' not in p:
             return
 
@@ -161,40 +169,42 @@
         # pType = p.get('prompt', '')
         # if not pType:
         #     return
-        
+
         # check for map/input parameter
-        pMap = self.task.get_param('map', raiseError = False)
-        
+        pMap = self.task.get_param('map', raiseError=False)
+
         if not pMap:
-            pMap = self.task.get_param('input', raiseError = False)
-        
+            pMap = self.task.get_param('input', raiseError=False)
+
         if pMap:
             map = pMap.get('value', '')
         else:
             map = None
-        
+
         # avoid running db.describe several times
         cparams = dict()
-        cparams[map] = { 'dbInfo' : None,
-                         'layers' : None, }
-        
+        cparams[map] = {'dbInfo': None,
+                        'layers': None, }
+
         # update reference widgets
         for uid in p['wxId-bind']:
             win = self.parent.FindWindowById(uid)
             if not win:
                 continue
-            
+
             name = win.GetName()
-            
-            ### @todo: replace name by isinstance() and signals
 
-            pBind = self.task.get_param(uid, element = 'wxId', raiseError = False)
+            # @todo: replace name by isinstance() and signals
+
+            pBind = self.task.get_param(uid, element='wxId', raiseError=False)
             if pBind:
                 pBind['value'] = ''
-            
-            # set appropriate types in t.* modules and g.list/remove element selections
+
+            # set appropriate types in t.* modules and g.list/remove element
+            # selections
             if name == 'Select':
-                type_param = self.task.get_param('type', element='name', raiseError=False)
+                type_param = self.task.get_param(
+                    'type', element='name', raiseError=False)
 
                 if 'all' in type_param.get('value'):
                     etype = type_param.get('values')[:]
@@ -210,25 +220,33 @@
                     self.data[win.GetParent().SetElementList] = {'type': etype}
 
                 # t.(un)register has one type for 'input', 'maps'
-                maps_param = self.task.get_param('maps', element='name', raiseError=False)
+                maps_param = self.task.get_param(
+                    'maps', element='name', raiseError=False)
                 if self.task.get_name().startswith('t') and maps_param is not None:
                     if maps_param['wxId'][0] != uid:
-                        element_dict = {'raster': 'strds', 'vector': 'stvds', 'raster_3d': 'str3ds'}
-                        self.data[win.GetParent().SetType] = {'etype': element_dict[type_param.get('value')]}
+                        element_dict = {
+                            'raster': 'strds',
+                            'vector': 'stvds',
+                            'raster_3d': 'str3ds'}
+                        self.data[
+                            win.GetParent().SetType] = {
+                            'etype': element_dict[
+                                type_param.get('value')]}
 
             map = layer = None
             driver = db = None
             if name in ('LayerSelect', 'ColumnSelect'):
-                if p.get('element', '') == 'vector': # -> vector
+                if p.get('element', '') == 'vector':  # -> vector
                     # get map name
                     map = p.get('value', '')
-                    
+
                     # get layer
                     for bid in p['wxId-bind']:
-                        p = self.task.get_param(bid, element = 'wxId', raiseError = False)
+                        p = self.task.get_param(
+                            bid, element='wxId', raiseError=False)
                         if not p:
                             continue
-                        
+
                         if p.get('element', '') in ['layer', 'layer_all']:
                             layer = p.get('value', '')
                             if layer != '':
@@ -236,39 +254,43 @@
                             else:
                                 layer = p.get('default', '')
                             break
-                        
-                elif p.get('element', '') in ['layer', 'layer_all']: # -> layer
+
+                elif p.get('element', '') in ['layer', 'layer_all']:  # -> layer
                     # get layer
                     layer = p.get('value', '')
                     if layer != '':
                         layer = p.get('value', '')
                     else:
                         layer = p.get('default', '')
-                    
+
                     # get map name
-                    pMapL = self.task.get_param(p['wxId'][0], element = 'wxId-bind', raiseError = False)
+                    pMapL = self.task.get_param(
+                        p['wxId'][0], element='wxId-bind', raiseError=False)
                     if pMapL:
                         map = pMapL.get('value', '')
-            
+
             if name == 'TableSelect' or \
                     (name == 'ColumnSelect' and not map):
-                pDriver = self.task.get_param('dbdriver', element = 'prompt', raiseError = False)
+                pDriver = self.task.get_param(
+                    'dbdriver', element='prompt', raiseError=False)
                 if pDriver:
                     driver = pDriver.get('value', '')
-                pDb = self.task.get_param('dbname', element = 'prompt', raiseError = False)
+                pDb = self.task.get_param(
+                    'dbname', element='prompt', raiseError=False)
                 if pDb:
                     db = pDb.get('value', '')
                 if name == 'ColumnSelect':
-                    pTable = self.task.get_param('dbtable', element = 'element', raiseError = False)
+                    pTable = self.task.get_param(
+                        'dbtable', element='element', raiseError=False)
                     if pTable:
                         table = pTable.get('value', '')
 
             if name == 'LayerSelect':
                 # determine format
                 native = True
-                
+
                 for id in pMap['wxId']:
-                    winVec  = self.parent.FindWindowById(id)
+                    winVec = self.parent.FindWindowById(id)
                     if winVec.GetName() == 'VectorFormat' and \
                             winVec.GetSelection() != 0:
                         native = False
@@ -276,114 +298,138 @@
                 # TODO: update only if needed
                 if native:
                     if map:
-                        self.data[win.InsertLayers] = { 'vector' : map }
+                        self.data[win.InsertLayers] = {'vector': map}
                     else:
-                        self.data[win.InsertLayers] = { }
+                        self.data[win.InsertLayers] = {}
                 else:
                     if map:
-                        self.data[win.InsertLayers] = { 'dsn' : map.rstrip('@OGR') }
+                        self.data[win.InsertLayers] = {
+                            'dsn': map.rstrip('@OGR')}
                     else:
-                        self.data[win.InsertLayers] = { }
-            
+                        self.data[win.InsertLayers] = {}
+
             elif name == 'TableSelect':
-                self.data[win.InsertTables] = { 'driver' : driver,
-                                                'database' : db }
-                
+                self.data[win.InsertTables] = {'driver': driver,
+                                               'database': db}
+
             elif name == 'ColumnSelect':
                 if map:
                     if map in cparams:
                         if not cparams[map]['dbInfo']:
                             cparams[map]['dbInfo'] = gselect.VectorDBInfo(map)
-                        self.data[win.GetParent().InsertColumns] = { 'vector' : map, 'layer' : layer,
-                                                                     'dbInfo' : cparams[map]['dbInfo'] }
-                else: # table
+                        self.data[win.GetParent().InsertColumns] = {
+                            'vector': map, 'layer': layer,
+                            'dbInfo': cparams[map]['dbInfo']}
+                else:  # table
                     if driver and db:
-                        self.data[win.GetParent().InsertTableColumns] = { 'table' : pTable.get('value'),
-                                                                          'driver' : driver,
-                                                                          'database' : db }
+                        self.data[win.GetParent().InsertTableColumns] = {
+                            'table': pTable.get('value'),
+                            'driver': driver, 'database': db}
                     elif pTable:
-                        self.data[win.GetParent().InsertTableColumns] = { 'table'  : pTable.get('value') }
-            
+                        self.data[win.GetParent().InsertTableColumns] = {
+                            'table': pTable.get('value')}
+
             elif name == 'SubGroupSelect':
-                self.data[win.Insert] = { 'group' : p.get('value', '')}
+                self.data[win.Insert] = {'group': p.get('value', '')}
 
             elif name == 'SignatureSelect':
                 if p.get('prompt', 'group') == 'group':
                     group = p.get('value', '')
-                    pSubGroup = self.task.get_param('subgroup', element = 'prompt', raiseError = False)
+                    pSubGroup = self.task.get_param(
+                        'subgroup', element='prompt', raiseError=False)
                     if pSubGroup:
                         subgroup = pSubGroup.get('value', '')
                     else:
                         subgroup = None
                 else:
                     subgroup = p.get('value', '')
-                    pGroup = self.task.get_param('group', element = 'prompt', raiseError = False)
+                    pGroup = self.task.get_param(
+                        'group', element='prompt', raiseError=False)
                     if pGroup:
                         group = pGroup.get('value', '')
                     else:
                         group = None
-                
-                self.data[win.Insert] = { 'group' : group,
-                                          'subgroup' : subgroup}
-                
+
+                self.data[win.Insert] = {'group': group,
+                                         'subgroup': subgroup}
+
             elif name == 'LocationSelect':
-                pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
+                pDbase = self.task.get_param(
+                    'dbase', element='element', raiseError=False)
                 if pDbase:
-                    self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', '')}
+                    self.data[
+                        win.UpdateItems] = {
+                        'dbase': pDbase.get(
+                            'value', '')}
 
             elif name == 'MapsetSelect':
-                pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
-                pLocation = self.task.get_param('location', element = 'element', raiseError = False)
+                pDbase = self.task.get_param(
+                    'dbase', element='element', raiseError=False)
+                pLocation = self.task.get_param(
+                    'location', element='element', raiseError=False)
                 if pDbase and pLocation:
-                    self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', ''),
-                                                   'location' : pLocation.get('value', '')}
+                    self.data[
+                        win.UpdateItems] = {
+                        'dbase': pDbase.get(
+                            'value', ''), 'location': pLocation.get(
+                            'value', '')}
 
             elif name == 'ProjSelect':
-                pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
-                pLocation = self.task.get_param('location', element = 'element', raiseError = False)
-                pMapset = self.task.get_param('mapset', element = 'element', raiseError = False)
+                pDbase = self.task.get_param(
+                    'dbase', element='element', raiseError=False)
+                pLocation = self.task.get_param(
+                    'location', element='element', raiseError=False)
+                pMapset = self.task.get_param(
+                    'mapset', element='element', raiseError=False)
                 if pDbase and pLocation and pMapset:
-                    self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', ''),
-                                                   'location' : pLocation.get('value', ''),
-                                                   'mapset' : pMapset.get('value', '')}
+                    self.data[
+                        win.UpdateItems] = {
+                        'dbase': pDbase.get(
+                            'value', ''), 'location': pLocation.get(
+                            'value', ''), 'mapset': pMapset.get(
+                            'value', '')}
 
+
 def UpdateDialog(parent, event, eventId, task):
     return UpdateThread(parent, event, eventId, task)
 
+
 class UpdateQThread(Thread):
     """Update dialog widgets in the thread"""
     requestId = 0
+
     def __init__(self, parent, requestQ, resultQ, **kwds):
         Thread.__init__(self, **kwds)
-        
-        self.parent = parent # cmdPanel
+
+        self.parent = parent  # cmdPanel
         self.setDaemon(True)
-        
+
         self.requestQ = requestQ
         self.resultQ = resultQ
-        
+
         self.start()
-        
+
     def Update(self, callable, *args, **kwds):
-        UpdateQThread.requestId +=  1
-        
+        UpdateQThread.requestId += 1
+
         self.request = None
         self.requestQ.put((UpdateQThread.requestId, callable, args, kwds))
-        
+
         return UpdateQThread.requestId
-    
+
     def run(self):
         while True:
             requestId, callable, args, kwds = self.requestQ.get()
-            
+
             self.request = callable(*args, **kwds)
 
             self.resultQ.put((requestId, self.request.run()))
-           
+
             if self.request:
-                event = wxUpdateDialog(data = self.request.data)
+                event = wxUpdateDialog(data=self.request.data)
                 wx.PostEvent(self.parent, event)
 
+
 class TaskFrame(wx.Frame):
     """This is the Frame containing the dialog for options input.
 
@@ -398,87 +444,101 @@
     The command is checked and sent to the clipboard when clicking
     'Copy'.
     """
-    def __init__(self, parent, giface, task_description, id = wx.ID_ANY,
-                 get_dcmd = None, layer = None,
-                 style = wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL, **kwargs):
+
+    def __init__(self, parent, giface, task_description, id=wx.ID_ANY,
+                 get_dcmd=None, layer=None,
+                 style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL, **kwargs):
         self.get_dcmd = get_dcmd
-        self.layer    = layer
-        self.task     = task_description
-        self.parent   = parent             # LayerTree | Modeler | None | ...
-        self._giface  = giface
+        self.layer = layer
+        self.task = task_description
+        self.parent = parent             # LayerTree | Modeler | None | ...
+        self._giface = giface
 
         self.dialogClosing = Signal('TaskFrame.dialogClosing')
-        
+
         # module name + keywords
         title = self.task.get_name()
         try:
-            if self.task.keywords !=  ['']:
-                title +=   " [" + ', '.join(self.task.keywords) + "]"
+            if self.task.keywords != ['']:
+                title += " [" + ', '.join(self.task.keywords) + "]"
         except ValueError:
             pass
-        
-        wx.Frame.__init__(self, parent = parent, id = id, title = title,
-                          name = "MainFrame", style = style, **kwargs)
-        
-        self.locale = wx.Locale(language = wx.LANGUAGE_DEFAULT)
-        
-        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
-        
+
+        wx.Frame.__init__(self, parent=parent, id=id, title=title,
+                          name="MainFrame", style=style, **kwargs)
+
+        self.locale = wx.Locale(language=wx.LANGUAGE_DEFAULT)
+
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
         # statusbar
         self.CreateStatusBar()
-        
+
         # icon
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass_dialog.ico'), wx.BITMAP_TYPE_ICO))
-        
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass_dialog.ico'),
+                wx.BITMAP_TYPE_ICO))
+
         guisizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         # set apropriate output window
         if self.parent:
             self.standalone = False
         else:
             self.standalone = True
-        
+
         # logo + description
         topsizer = wx.BoxSizer(wx.HORIZONTAL)
-        
+
         # GRASS logo
-        self.logo = wx.StaticBitmap(parent = self.panel,
-                                    bitmap = wx.Bitmap(name = os.path.join(globalvar.IMGDIR,
-                                                                           'grass_form.png'),
-                                                     type = wx.BITMAP_TYPE_PNG))
-        topsizer.Add(item = self.logo, proportion = 0, border = 3,
-                     flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL)
-        
+        self.logo = wx.StaticBitmap(
+            parent=self.panel,
+            bitmap=wx.Bitmap(
+                name=os.path.join(
+                    globalvar.IMGDIR,
+                    'grass_form.png'),
+                type=wx.BITMAP_TYPE_PNG))
+        topsizer.Add(item=self.logo, proportion=0, border=3,
+                     flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)
+
         # add module description
         if self.task.label:
             module_desc = self.task.label + ' ' + self.task.description
         else:
             module_desc = self.task.description
-        
+
         self.description = StaticWrapText(parent=self.panel,
                                           label=module_desc)
-        topsizer.Add(item = self.description, proportion = 1, border = 5,
-                     flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
-        
-        guisizer.Add(item = topsizer, proportion = 0, flag = wx.EXPAND)
-        
+        topsizer.Add(item=self.description, proportion=1, border=5,
+                     flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
+
+        guisizer.Add(item=topsizer, proportion=0, flag=wx.EXPAND)
+
         self.panel.SetSizerAndFit(guisizer)
         self.Layout()
-        
+
         # notebooks
-        self.notebookpanel = CmdPanel(parent = self.panel, giface = self._giface, task = self.task,
-                                      frame = self)
+        self.notebookpanel = CmdPanel(
+            parent=self.panel,
+            giface=self._giface,
+            task=self.task,
+            frame=self)
         self._gconsole = self.notebookpanel._gconsole
         if self._gconsole:
             self._gconsole.mapCreated.connect(self.OnMapCreated)
-            self._gconsole.updateMap.connect(lambda: self._giface.updateMap.emit())
+            self._gconsole.updateMap.connect(
+                lambda: self._giface.updateMap.emit())
         self.goutput = self.notebookpanel.goutput
         if self.goutput:
-            self.goutput.showNotification.connect(lambda message: self.SetStatusText(message))
-        
+            self.goutput.showNotification.connect(
+                lambda message: self.SetStatusText(message))
+
         self.notebookpanel.OnUpdateValues = self.updateValuesHook
-        guisizer.Add(item = self.notebookpanel, proportion = 1, flag = wx.EXPAND)
-        
+        guisizer.Add(item=self.notebookpanel, proportion=1, flag=wx.EXPAND)
+
         # status bar
         status_text = _("Enter parameters for '") + self.task.name + "'"
         try:
@@ -486,13 +546,18 @@
             self.updateValuesHook()
         except ValueError:
             self.SetStatusText(status_text)
-        
+
         # buttons
-        btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
+        btnsizer = wx.BoxSizer(orient=wx.HORIZONTAL)
         # cancel
-        self.btn_cancel = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
-        self.btn_cancel.SetToolTipString(_("Close this window without executing the command (Ctrl+Q)"))
-        btnsizer.Add(item = self.btn_cancel, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 10)
+        self.btn_cancel = wx.Button(parent=self.panel, id=wx.ID_CLOSE)
+        self.btn_cancel.SetToolTipString(
+            _("Close this window without executing the command (Ctrl+Q)"))
+        btnsizer.Add(
+            item=self.btn_cancel,
+            proportion=0,
+            flag=wx.ALL | wx.ALIGN_CENTER,
+            border=10)
         self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
         # bind closing to ESC and CTRL+Q
         self.Bind(wx.EVT_MENU, self.OnCancel, id=wx.ID_CLOSE)
@@ -500,58 +565,68 @@
         accelTableList = [(wx.ACCEL_CTRL, ord('Q'), wx.ID_CLOSE)]
         # TODO: bind Ctrl-t for tile windows here (trac #2004)
 
-        if self.get_dcmd is not None: # A callback has been set up
-            btn_apply = wx.Button(parent = self.panel, id = wx.ID_APPLY)
-            btn_ok = wx.Button(parent = self.panel, id = wx.ID_OK)
+        if self.get_dcmd is not None:  # A callback has been set up
+            btn_apply = wx.Button(parent=self.panel, id=wx.ID_APPLY)
+            btn_ok = wx.Button(parent=self.panel, id=wx.ID_OK)
             btn_ok.SetDefault()
 
-            btnsizer.Add(item = btn_apply, proportion = 0,
-                         flag = wx.ALL | wx.ALIGN_CENTER,
-                         border = 10)
-            btnsizer.Add(item = btn_ok, proportion = 0,
-                         flag = wx.ALL | wx.ALIGN_CENTER,
-                         border = 10)
-            
+            btnsizer.Add(item=btn_apply, proportion=0,
+                         flag=wx.ALL | wx.ALIGN_CENTER,
+                         border=10)
+            btnsizer.Add(item=btn_ok, proportion=0,
+                         flag=wx.ALL | wx.ALIGN_CENTER,
+                         border=10)
+
             btn_apply.Bind(wx.EVT_BUTTON, self.OnApply)
             btn_ok.Bind(wx.EVT_BUTTON, self.OnOK)
-        else: # We're standalone
+        else:  # We're standalone
             # run
-            self.btn_run = wx.Button(parent = self.panel, id = wx.ID_OK, label =  _("&Run"))
+            self.btn_run = wx.Button(
+                parent=self.panel, id=wx.ID_OK, label=_("&Run"))
             self.btn_run.SetToolTipString(_("Run the command (Ctrl+R)"))
             self.btn_run.SetDefault()
             self.btn_run.SetForegroundColour(wx.Colour(35, 142, 35))
-            
-            btnsizer.Add(item = self.btn_run, proportion = 0,
-                         flag = wx.ALL | wx.ALIGN_CENTER,
-                         border = 10)
 
+            btnsizer.Add(item=self.btn_run, proportion=0,
+                         flag=wx.ALL | wx.ALIGN_CENTER,
+                         border=10)
+
             self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
             self.Bind(wx.EVT_MENU, self.OnRun, id=wx.ID_OK)
             accelTableList.append((wx.ACCEL_CTRL, ord('R'), wx.ID_OK))
 
         # copy
         self.btn_clipboard = wx.Button(parent=self.panel, id=wx.ID_COPY)
-        self.btn_clipboard.SetToolTipString(_("Copy the current command string to the clipboard"))
+        self.btn_clipboard.SetToolTipString(
+            _("Copy the current command string to the clipboard"))
         btnsizer.Add(item=self.btn_clipboard, proportion=0,
-                         flag=wx.ALL | wx.ALIGN_CENTER,
-                         border=10)
+                     flag=wx.ALL | wx.ALIGN_CENTER,
+                     border=10)
         self.btn_clipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
 
         # help
-        self.btn_help = wx.Button(parent = self.panel, id = wx.ID_HELP)
-        self.btn_help.SetToolTipString(_("Show manual page of the command (Ctrl+H)"))
+        self.btn_help = wx.Button(parent=self.panel, id=wx.ID_HELP)
+        self.btn_help.SetToolTipString(
+            _("Show manual page of the command (Ctrl+H)"))
         self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
         self.Bind(wx.EVT_MENU, self.OnHelp, id=wx.ID_HELP)
         accelTableList.append((wx.ACCEL_CTRL, ord('H'), wx.ID_HELP))
 
         if self.notebookpanel.notebook.GetPageIndexByName('manual') < 0:
             self.btn_help.Hide()
-        
+
         # add help button
-        btnsizer.Add(item = self.btn_help, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 10)
-        
-        guisizer.Add(item = btnsizer, proportion = 0, flag = wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT,
-                     border = 30)
+        btnsizer.Add(
+            item=self.btn_help,
+            proportion=0,
+            flag=wx.ALL | wx.ALIGN_CENTER,
+            border=10)
+
+        guisizer.Add(
+            item=btnsizer,
+            proportion=0,
+            flag=wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT,
+            border=30)
         # abort key bindings
         abortId = wx.NewId()
         self.Bind(wx.EVT_MENU, self.OnAbort, id=abortId)
@@ -559,78 +634,101 @@
         # set accelerator table
         accelTable = wx.AcceleratorTable(accelTableList)
         self.SetAcceleratorTable(accelTable)
-        
+
         if self._giface and self._giface.GetLayerTree():
             addLayer = False
             for p in self.task.params:
                 if p.get('age', 'old') == 'new' and \
                    p.get('prompt', '') in ('raster', 'vector', 'raster_3d'):
                     addLayer = True
-            
+
             if addLayer:
                 # add newly created map into layer tree
-                self.addbox = wx.CheckBox(parent = self.panel,
-                                          label = _('Add created map(s) into layer tree'), style = wx.NO_BORDER)
-                self.addbox.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
-                guisizer.Add(item = self.addbox, proportion = 0,
-                             flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                             border = 5)
-        
+                self.addbox = wx.CheckBox(
+                    parent=self.panel,
+                    label=_('Add created map(s) into layer tree'),
+                    style=wx.NO_BORDER)
+                self.addbox.SetValue(
+                    UserSettings.Get(
+                        group='cmd',
+                        key='addNewLayer',
+                        subkey='enabled'))
+                guisizer.Add(item=self.addbox, proportion=0,
+                             flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                             border=5)
+
         hasNew = False
         for p in self.task.params:
             if p.get('age', 'old') == 'new':
                 hasNew = True
                 break
-        
+
         if self.get_dcmd is None and hasNew:
             # close dialog when command is terminated
-            self.closebox = wx.CheckBox(parent = self.panel,
-                                        label = _('Close dialog on finish'), style = wx.NO_BORDER)
-            self.closebox.SetValue(UserSettings.Get(group = 'cmd', key = 'closeDlg', subkey = 'enabled'))
-            self.closebox.SetToolTipString(_("Close dialog when command is successfully finished. "
-                                             "Change this settings in Preferences dialog ('Command' tab)."))
-            guisizer.Add(item = self.closebox, proportion = 0,
-                         flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                         border = 5)
+            self.closebox = wx.CheckBox(
+                parent=self.panel,
+                label=_('Close dialog on finish'),
+                style=wx.NO_BORDER)
+            self.closebox.SetValue(
+                UserSettings.Get(
+                    group='cmd',
+                    key='closeDlg',
+                    subkey='enabled'))
+            self.closebox.SetToolTipString(
+                _(
+                    "Close dialog when command is successfully finished. "
+                    "Change this settings in Preferences dialog ('Command' tab)."))
+            guisizer.Add(item=self.closebox, proportion=0,
+                         flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                         border=5)
         # bindings
-        self.Bind(wx.EVT_CLOSE,  self.OnCancel)
-        
+        self.Bind(wx.EVT_CLOSE, self.OnCancel)
+
         # do layout
         # called automatically by SetSizer()
-        self.panel.SetAutoLayout(True) 
+        self.panel.SetAutoLayout(True)
         self.panel.SetSizerAndFit(guisizer)
-        
+
         sizeFrame = self.GetBestSize()
         self.SetMinSize(sizeFrame)
-        
+
         if hasattr(self, "closebox"):
             scale = 0.33
         else:
             scale = 0.50
-        self.SetSize(wx.Size(sizeFrame[0], sizeFrame[1] + scale * max(self.notebookpanel.panelMinHeight,
-                                                                      self.notebookpanel.constrained_size[1])))
-        
+        self.SetSize(
+            wx.Size(
+                sizeFrame[0],
+                sizeFrame[1] + scale * max(
+                    self.notebookpanel.panelMinHeight,
+                    self.notebookpanel.constrained_size[1])))
+
         # thread to update dialog
         # create queues
         self.requestQ = Queue.Queue()
         self.resultQ = Queue.Queue()
-        self.updateThread = UpdateQThread(self.notebookpanel, self.requestQ, self.resultQ)
-        
+        self.updateThread = UpdateQThread(
+            self.notebookpanel, self.requestQ, self.resultQ)
+
         self.Layout()
-        
+
         # keep initial window size limited for small screens
         width, height = self.GetSizeTuple()
         self.SetSize(wx.Size(min(width, 650),
                              min(height, 500)))
-        
+
         # fix goutput's pane size (required for Mac OSX)
         if self.goutput:
             self.goutput.SetSashPosition(int(self.GetSize()[1] * .75))
-        
-    def updateValuesHook(self, event = None):
+
+    def updateValuesHook(self, event=None):
         """Update status bar data"""
-        self.SetStatusText(' '.join([gcmd.DecodeString(each) if isinstance(each, str) else each
-                                     for each in self.notebookpanel.createCmd(ignoreErrors=True)]))
+        self.SetStatusText(
+            ' '.join(
+                [gcmd.DecodeString(each)
+                 if isinstance(each, str) else each
+                 for each in self.notebookpanel.createCmd(
+                     ignoreErrors=True)]))
         if event:
             event.Skip()
 
@@ -651,10 +749,10 @@
             self.btn_run.Enable(True)
 
         if hasattr(self, "get_dcmd") and \
-                    self.get_dcmd is None and \
-                    hasattr(self, "closebox") and \
-                    self.closebox.IsChecked() and \
-                    (event.returncode == 0):
+                self.get_dcmd is None and \
+                hasattr(self, "closebox") and \
+                self.closebox.IsChecked() and \
+                (event.returncode == 0):
             # was closed also when aborted but better is leave it open
             wx.FutureCall(2000, self.Close)
 
@@ -668,10 +766,10 @@
             add = True
         else:
             add = False
-        
+
         if self._giface:
             self._giface.mapCreated.emit(name=name, ltype=ltype, add=add)
-    
+
     def OnOK(self, event):
         """OK button pressed"""
         cmd = self.OnApply(event)
@@ -681,14 +779,14 @@
     def OnApply(self, event):
         """Apply the command"""
         if self._giface and hasattr(self._giface, "_model"):
-            cmd = self.createCmd(ignoreErrors = True, ignoreRequired = True)
+            cmd = self.createCmd(ignoreErrors=True, ignoreRequired=True)
         else:
             cmd = self.createCmd()
-        
+
         if cmd is not None and self.get_dcmd is not None:
             # return d.* command to layer tree for rendering
-            self.get_dcmd(cmd, self.layer, {"params": self.task.params, 
-                                            "flags" : self.task.flags},
+            self.get_dcmd(cmd, self.layer, {"params": self.task.params,
+                                            "flags": self.task.flags},
                           self)
             # echo d.* command to output console
             # self.parent.writeDCommand(cmd)
@@ -698,62 +796,64 @@
     def OnRun(self, event):
         """Run the command"""
         cmd = self.createCmd()
-        
+
         if not cmd or len(cmd) < 1:
             return
-        
+
         ret = 0
-        if self.standalone or cmd[0][0:2] !=  "d.":
+        if self.standalone or cmd[0][0:2] != "d.":
             # Send any non-display command to parent window (probably wxgui.py)
             # put to parents switch to 'Command output'
             self.notebookpanel.notebook.SetSelectionByName('output')
-            
+
             try:
                 if self.task.path:
-                    cmd[0] = self.task.path # full path
-                
-                ret = self._gconsole.RunCmd(cmd, onDone = self.OnDone)
+                    cmd[0] = self.task.path  # full path
+
+                ret = self._gconsole.RunCmd(cmd, onDone=self.OnDone)
             except AttributeError as e:
-                print >> sys.stderr, "%s: Probably not running in wxgui.py session?" % (e)
-                print >> sys.stderr, "parent window is: %s" % (str(self.parent))
+                print >> sys.stderr, "%s: Probably not running in wxgui.py session?" % (
+                    e)
+                print >>sys.stderr, "parent window is: %s" % (
+                    str(self.parent))
         else:
             gcmd.Command(cmd)
-        
+
         if ret != 0:
             self.notebookpanel.notebook.SetSelection(0)
             return
-        
+
         # update buttons status
         for btn in (self.btn_run,
                     self.btn_cancel,
                     self.btn_clipboard,
                     self.btn_help):
             btn.Enable(False)
-        
+
     def OnAbort(self, event):
         """Abort running command"""
         from core.gconsole import wxCmdAbort
-        event = wxCmdAbort(aborted = True)
+        event = wxCmdAbort(aborted=True)
         wx.PostEvent(self._gconsole, event)
 
     def OnCopy(self, event):
         """Copy the command"""
         cmddata = wx.TextDataObject()
         # list -> string
-        cmdlist = self.createCmd(ignoreErrors = True)
+        cmdlist = self.createCmd(ignoreErrors=True)
         # TODO: better protect whitespace with quotes
         for i in range(1, len(cmdlist)):
             if ' ' in cmdlist[i]:
-                optname, val =  cmdlist[i].split("=", 1)
+                optname, val = cmdlist[i].split("=", 1)
                 cmdlist[i] = '%s="%s"' % (optname, val)
         cmdstring = ' '.join(cmdlist)
         cmddata.SetText(cmdstring)
         if wx.TheClipboard.Open():
-#            wx.TheClipboard.UsePrimarySelection(True)
+            #            wx.TheClipboard.UsePrimarySelection(True)
             wx.TheClipboard.SetData(cmddata)
             wx.TheClipboard.Close()
-            self.SetStatusText(_("'%s' copied to clipboard") % \
-                                    (cmdstring))
+            self.SetStatusText(_("'%s' copied to clipboard") %
+                               (cmdstring))
 
     def OnCancel(self, event):
         """Cancel button pressed"""
@@ -763,17 +863,18 @@
                 self.parent and \
                 self.parent.GetName() in ('LayerTree',
                                           'MapWindow'):
-            # display decorations and 
+            # display decorations and
             # pressing OK or cancel after setting layer properties
-            if self.task.name in ['d.barscale','d.legend', 'd.northarrow', 'd.histogram'] \
-                or len(self.parent.GetLayerInfo(self.layer, key = 'cmd')) >=  1:
+            if self.task.name in ['d.barscale', 'd.legend', 'd.northarrow', 'd.histogram'] \
+                    or len(self.parent.GetLayerInfo(self.layer, key='cmd')) >= 1:
                 self.Hide()
             # canceled layer with nothing set
-            elif len(self.parent.GetLayerInfo(self.layer, key = 'cmd')) < 1:
+            elif len(self.parent.GetLayerInfo(self.layer, key='cmd')) < 1:
                 try:
                     self.parent.Delete(self.layer)
                 except ValueError:
-                    # happens when closing dialog of a new layer which was removed from tree
+                    # happens when closing dialog of a new layer which was
+                    # removed from tree
                     pass
                 self.Destroy()
         else:
@@ -785,172 +886,200 @@
         if self.notebookpanel.notebook.GetPageIndexByName('manual') > -1:
             self.notebookpanel.notebook.SetSelectionByName('manual')
             self.notebookpanel.OnPageChange(None)
-        
-        if event:    
+
+        if event:
             event.Skip()
-        
-    def createCmd(self, ignoreErrors = False, ignoreRequired = False):
+
+    def createCmd(self, ignoreErrors=False, ignoreRequired=False):
         """Create command string (python list)"""
-        return self.notebookpanel.createCmd(ignoreErrors = ignoreErrors,
-                                            ignoreRequired = ignoreRequired)
+        return self.notebookpanel.createCmd(ignoreErrors=ignoreErrors,
+                                            ignoreRequired=ignoreRequired)
 
+
 class CmdPanel(wx.Panel):
     """A panel containing a notebook dividing in tabs the different
     guisections of the GRASS cmd.
     """
-    def __init__(self, parent, giface, task, id = wx.ID_ANY, frame = None, *args, **kwargs):
+
+    def __init__(self, parent, giface, task, id=wx.ID_ANY,
+                 frame=None, *args, **kwargs):
         if frame:
             self.parent = frame
         else:
             self.parent = parent
         self.task = task
         self._giface = giface
-        
-        wx.Panel.__init__(self, parent, id = id, *args, **kwargs)
 
+        wx.Panel.__init__(self, parent, id=id, *args, **kwargs)
+
         self.mapCreated = Signal
-        self.updateMap  = Signal
+        self.updateMap = Signal
 
         # Determine tab layout
         sections = []
         is_section = {}
-        not_hidden = [ p for p in self.task.params + self.task.flags if not p.get('hidden', False) == True ]
+        not_hidden = [
+            p for p in self.task.params +
+            self.task.flags if not p.get(
+                'hidden',
+                False) == True]
 
-        self.label_id = [] # wrap titles on resize
+        self.label_id = []  # wrap titles on resize
 
         self.Bind(wx.EVT_SIZE, self.OnSize)
-        
+
         for task in not_hidden:
             if task.get('required', False) and not task.get('guisection', ''):
-                # All required go into Main, even if they had defined another guisection
+                # All required go into Main, even if they had defined another
+                # guisection
                 task['guisection'] = _('Required')
-            if task.get('guisection','') == '':
+            if task.get('guisection', '') == '':
                 # Undefined guisections end up into Options
                 task['guisection'] = _('Optional')
             if task['guisection'] not in is_section:
-                # We do it like this to keep the original order, except for Main which goes first
+                # We do it like this to keep the original order, except for
+                # Main which goes first
                 is_section[task['guisection']] = 1
                 sections.append(task['guisection'])
             else:
-                is_section[ task['guisection'] ] +=  1
+                is_section[task['guisection']] += 1
         del is_section
 
         # 'Required' tab goes first, 'Optional' as the last one
-        for (newidx,content) in [ (0,_('Required')), (len(sections)-1,_('Optional')) ]:
+        for (newidx, content) in [(0, _('Required')),
+                                  (len(sections) - 1, _('Optional'))]:
             if content in sections:
                 idx = sections.index(content)
-                sections[idx:idx+1] = []
-                sections[newidx:newidx] =  [content]
+                sections[idx:idx + 1] = []
+                sections[newidx:newidx] = [content]
 
-        panelsizer = wx.BoxSizer(orient = wx.VERTICAL)
+        panelsizer = wx.BoxSizer(orient=wx.VERTICAL)
 
         # build notebook
-        style = UserSettings.Get(group = 'appearance', key = 'commandNotebook', subkey = 'selection')
-        if style == 0: # basic top
-            self.notebook = FormNotebook(self, style = wx.BK_TOP)
+        style = UserSettings.Get(
+            group='appearance',
+            key='commandNotebook',
+            subkey='selection')
+        if style == 0:  # basic top
+            self.notebook = FormNotebook(self, style=wx.BK_TOP)
             self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChange)
-        elif style == 1: # basic left
-            self.notebook = FormNotebook(self, style = wx.BK_LEFT)
+        elif style == 1:  # basic left
+            self.notebook = FormNotebook(self, style=wx.BK_LEFT)
             self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChange)
-        elif style == 2: # fancy green
-            self.notebook = GNotebook(self, style = globalvar.FNPageStyle | FN.FNB_NO_X_BUTTON )
+        elif style == 2:  # fancy green
+            self.notebook = GNotebook(
+                self, style=globalvar.FNPageStyle | FN.FNB_NO_X_BUTTON)
             self.notebook.SetTabAreaColour(globalvar.FNPageColor)
-            self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChange)
+            self.notebook.Bind(
+                FN.EVT_FLATNOTEBOOK_PAGE_CHANGED,
+                self.OnPageChange)
         elif style == 3:
-            self.notebook = FormListbook(self, style = wx.BK_LEFT)
+            self.notebook = FormListbook(self, style=wx.BK_LEFT)
             self.notebook.Bind(wx.EVT_LISTBOOK_PAGE_CHANGED, self.OnPageChange)
         self.notebook.Refresh()
 
         tab = {}
         tabsizer = {}
         for section in sections:
-            tab[section] = ScrolledPanel(parent = self.notebook)
+            tab[section] = ScrolledPanel(parent=self.notebook)
             tab[section].SetScrollRate(10, 10)
-            tabsizer[section] = wx.BoxSizer(orient = wx.VERTICAL)
-        
+            tabsizer[section] = wx.BoxSizer(orient=wx.VERTICAL)
 
         #
         # flags
         #
-        visible_flags = [ f for f in self.task.flags if not f.get('hidden', False) == True ]
+        visible_flags = [
+            f for f in self.task.flags if not f.get(
+                'hidden', False) == True]
         for f in visible_flags:
             # we don't want another help (checkbox appeared in r58783)
             if f['name'] == 'help':
                 continue
-            which_sizer = tabsizer[ f['guisection'] ]
-            which_panel = tab[ f['guisection'] ]
+            which_sizer = tabsizer[f['guisection']]
+            which_panel = tab[f['guisection']]
             # if label is given: description -> tooltip
-            if f.get('label','') !=  '':
+            if f.get('label', '') != '':
                 title = text_beautify(f['label'])
-                tooltip = text_beautify(f['description'], width = -1)
+                tooltip = text_beautify(f['description'], width=-1)
             else:
                 title = text_beautify(f['description'])
                 tooltip = None
             title_sizer = wx.BoxSizer(wx.HORIZONTAL)
-            rtitle_txt = wx.StaticText(parent = which_panel,
-                                       label = '(' + f['name'] + ')')
-            chk = wx.CheckBox(parent = which_panel, label = title, style = wx.NO_BORDER)
+            rtitle_txt = wx.StaticText(parent=which_panel,
+                                       label='(' + f['name'] + ')')
+            chk = wx.CheckBox(
+                parent=which_panel,
+                label=title,
+                style=wx.NO_BORDER)
             self.label_id.append(chk.GetId())
             if tooltip:
                 chk.SetToolTipString(tooltip)
             chk.SetValue(f.get('value', False))
-            title_sizer.Add(item = chk, proportion = 1,
-                            flag = wx.EXPAND)
-            title_sizer.Add(item = rtitle_txt, proportion = 0,
-                            flag = wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
-            which_sizer.Add(item = title_sizer, proportion = 0,
-                            flag = wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border = 5)
-            f['wxId'] = [ chk.GetId(), ]
+            title_sizer.Add(item=chk, proportion=1,
+                            flag=wx.EXPAND)
+            title_sizer.Add(item=rtitle_txt, proportion=0,
+                            flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
+            which_sizer.Add(
+                item=title_sizer,
+                proportion=0,
+                flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT,
+                border=5)
+            f['wxId'] = [chk.GetId(), ]
             chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
-            
-            if self.parent.GetName() == 'MainFrame' and (self._giface and hasattr(self._giface, "_model")):
-                parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
-                                     label = _("Parameterized in model"))
+
+            if self.parent.GetName() == 'MainFrame' and (
+                    self._giface and hasattr(self._giface, "_model")):
+                parChk = wx.CheckBox(parent=which_panel, id=wx.ID_ANY,
+                                     label=_("Parameterized in model"))
                 parChk.SetName('ModelParam')
                 parChk.SetValue(f.get('parameterized', False))
                 if 'wxId' in f:
                     f['wxId'].append(parChk.GetId())
                 else:
-                    f['wxId'] = [ parChk.GetId() ]
+                    f['wxId'] = [parChk.GetId()]
                 parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
-                which_sizer.Add(item = parChk, proportion = 0,
-                                flag = wx.LEFT, border = 20)
-            
+                which_sizer.Add(item=parChk, proportion=0,
+                                flag=wx.LEFT, border=20)
+
             if f['name'] in ('verbose', 'quiet'):
                 chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
-                vq = UserSettings.Get(group = 'cmd', key = 'verbosity', subkey = 'selection')
+                vq = UserSettings.Get(
+                    group='cmd', key='verbosity', subkey='selection')
                 if f['name'] == vq:
                     chk.SetValue(True)
                     f['value'] = True
-            
+
             if f['name'] == 'overwrite':
-                value = UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled')
-                if value: # override only when enabled
+                value = UserSettings.Get(
+                    group='cmd', key='overwrite', subkey='enabled')
+                if value:  # override only when enabled
                     f['value'] = value
                     chk.SetValue(f['value'])
-        
+
         #
         # parameters
         #
-        visible_params = [ p for p in self.task.params if not p.get('hidden', False) == True ]
-        
+        visible_params = [
+            p for p in self.task.params if not p.get(
+                'hidden', False) == True]
+
         try:
             first_param = visible_params[0]
         except IndexError:
             first_param = None
-        
+
         for p in visible_params:
             which_sizer = tabsizer[p['guisection']]
             which_panel = tab[p['guisection']]
             # if label is given -> label and description -> tooltip
             # otherwise description -> lavel
-            if p.get('label','') !=  '':
+            if p.get('label', '') != '':
                 title = text_beautify(p['label'])
-                tooltip = text_beautify(p['description'], width = -1)
+                tooltip = text_beautify(p['description'], width=-1)
             else:
                 title = text_beautify(p['description'])
                 tooltip = None
-            
+
             prompt = p.get('prompt', '')
 
             # title sizer (description, name, type)
@@ -958,10 +1087,10 @@
                     p.get('multiple', False) and \
                     p.get('gisprompt', False) == False and \
                     p.get('type', '') == 'string':
-                title_txt = wx.StaticBox(parent = which_panel, id = wx.ID_ANY)
+                title_txt = wx.StaticBox(parent=which_panel, id=wx.ID_ANY)
             else:
                 title_sizer = wx.BoxSizer(wx.HORIZONTAL)
-                title_txt = wx.StaticText(parent = which_panel)
+                title_txt = wx.StaticText(parent=which_panel)
                 if p['key_desc']:
                     ltype = ','.join(p['key_desc'])
                 else:
@@ -973,223 +1102,263 @@
                     required_txt.SetToolTipString(_("This option is required"))
                 else:
                     required_txt = wx.StaticText(parent=which_panel, label="")
-                rtitle_txt = wx.StaticText(parent = which_panel,
-                                           label = '(' + p['name'] + '=' + ltype + ')')
-                title_sizer.Add(item = title_txt, proportion = 0,
-                                flag = wx.LEFT | wx.TOP | wx.EXPAND, border = 5)
-                title_sizer.Add(item = required_txt, proportion=1,
-                                flag = wx.EXPAND, border=0)
-                title_sizer.Add(item = rtitle_txt, proportion = 0,
-                                flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
-                which_sizer.Add(item = title_sizer, proportion = 0,
-                                flag = wx.EXPAND)
+                rtitle_txt = wx.StaticText(
+                    parent=which_panel,
+                    label='(' + p['name'] + '=' + ltype + ')')
+                title_sizer.Add(item=title_txt, proportion=0,
+                                flag=wx.LEFT | wx.TOP | wx.EXPAND, border=5)
+                title_sizer.Add(item=required_txt, proportion=1,
+                                flag=wx.EXPAND, border=0)
+                title_sizer.Add(
+                    item=rtitle_txt,
+                    proportion=0,
+                    flag=wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP,
+                    border=5)
+                which_sizer.Add(item=title_sizer, proportion=0,
+                                flag=wx.EXPAND)
             self.label_id.append(title_txt.GetId())
 
             # title expansion
-            if p.get('multiple', False) and len(p.get('values','')) == 0:
+            if p.get('multiple', False) and len(p.get('values', '')) == 0:
                 title = _("[multiple]") + " " + title
-                if p.get('value','') ==  '' :
-                    p['value'] = p.get('default','')
+                if p.get('value', '') == '':
+                    p['value'] = p.get('default', '')
 
             if (len(p.get('values', [])) > 0):
-                valuelist      = map(str, p.get('values',[]))
-                valuelist_desc = map(unicode, p.get('values_desc',[]))
+                valuelist = map(str, p.get('values', []))
+                valuelist_desc = map(unicode, p.get('values_desc', []))
                 required_text = "*" if p.get('required', False) else ""
                 if p.get('multiple', False) and \
-                        p.get('gisprompt',False) == False and \
+                        p.get('gisprompt', False) == False and \
                         p.get('type', '') == 'string':
-                    title_txt.SetLabel(" %s:%s  (%s=%s) " % (title, required_text, p['name'], p['type']))
-                    stSizer = wx.StaticBoxSizer(box = title_txt, orient = wx.VERTICAL)
+                    title_txt.SetLabel(
+                        " %s:%s  (%s=%s) " %
+                        (title, required_text, p['name'], p['type']))
+                    stSizer = wx.StaticBoxSizer(
+                        box=title_txt, orient=wx.VERTICAL)
                     if valuelist_desc:
-                        hSizer = wx.FlexGridSizer(cols = 1, vgap = 1)
+                        hSizer = wx.FlexGridSizer(cols=1, vgap=1)
                     else:
-                        hSizer = wx.FlexGridSizer(cols = 6, vgap = 1, hgap = 1)
+                        hSizer = wx.FlexGridSizer(cols=6, vgap=1, hgap=1)
                     isEnabled = {}
                     # copy default values
                     if p['value'] == '':
                         p['value'] = p.get('default', '')
-                        
+
                     for defval in p.get('value', '').split(','):
-                        isEnabled[ defval ] = 'yes'
+                        isEnabled[defval] = 'yes'
                         # for multi checkboxes, this is an array of all wx IDs
                         # for each individual checkbox
-                        p[ 'wxId' ] = list()
+                        p['wxId'] = list()
                     idx = 0
                     for val in valuelist:
                         try:
                             label = valuelist_desc[idx]
                         except IndexError:
                             label = val
-                        
-                        chkbox = wx.CheckBox(parent = which_panel,
-                                             label = text_beautify(label))
-                        p[ 'wxId' ].append(chkbox.GetId())
+
+                        chkbox = wx.CheckBox(parent=which_panel,
+                                             label=text_beautify(label))
+                        p['wxId'].append(chkbox.GetId())
                         if val in isEnabled:
                             chkbox.SetValue(True)
-                        hSizer.Add(item = chkbox, proportion = 0)
+                        hSizer.Add(item=chkbox, proportion=0)
                         chkbox.Bind(wx.EVT_CHECKBOX, self.OnUpdateSelection)
                         chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
-                        idx +=  1
-                        
-                    stSizer.Add(item = hSizer, proportion = 0,
-                                flag = wx.ADJUST_MINSIZE | wx.ALL, border = 1)
-                    which_sizer.Add(item = stSizer, proportion = 0,
-                                    flag = wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border = 5)
+                        idx += 1
+
+                    stSizer.Add(item=hSizer, proportion=0,
+                                flag=wx.ADJUST_MINSIZE | wx.ALL, border=1)
+                    which_sizer.Add(
+                        item=stSizer,
+                        proportion=0,
+                        flag=wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT,
+                        border=5)
                 elif p.get('gisprompt', False) is False:
-                    if len(valuelist) == 1: # -> textctrl
-                        title_txt.SetLabel("%s (%s %s):" % (title, _('valid range'),
-                                                            str(valuelist[0])))
+                    if len(valuelist) == 1:  # -> textctrl
+                        title_txt.SetLabel(
+                            "%s (%s %s):" %
+                            (title, _('valid range'),
+                             str(valuelist[0])))
                         if p.get('type', '') == 'integer' and \
                                 not p.get('multiple', False):
 
-                            # for multiple integers use textctrl instead of spinsctrl
+                            # for multiple integers use textctrl instead of
+                            # spinsctrl
                             try:
-                                minValue, maxValue = map(int, valuelist[0].rsplit('-', 1))
+                                minValue, maxValue = map(
+                                    int, valuelist[0].rsplit('-', 1))
                             except ValueError:
                                 minValue = -1e6
                                 maxValue = 1e6
-                            txt2 = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY, size = globalvar.DIALOG_SPIN_SIZE,
-                                               min = minValue, max = maxValue)
+                            txt2 = wx.SpinCtrl(
+                                parent=which_panel,
+                                id=wx.ID_ANY,
+                                size=globalvar.DIALOG_SPIN_SIZE,
+                                min=minValue,
+                                max=maxValue)
                             style = wx.BOTTOM | wx.LEFT
                         else:
-                            txt2 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
+                            txt2 = wx.TextCtrl(
+                                parent=which_panel, value=p.get(
+                                    'default', ''))
                             style = wx.EXPAND | wx.BOTTOM | wx.LEFT
-                        
+
                         value = self._getValue(p)
                         # parameter previously set
                         if value:
                             if isinstance(txt2, wx.SpinCtrl):
-                                txt2.SetValue(int(value)) 
+                                txt2.SetValue(int(value))
                             else:
                                 txt2.SetValue(value)
-                        
-                        which_sizer.Add(item = txt2, proportion = 0,
-                                        flag = style, border = 5)
 
-                        p['wxId'] = [ txt2.GetId(), ]
+                        which_sizer.Add(item=txt2, proportion=0,
+                                        flag=style, border=5)
+
+                        p['wxId'] = [txt2.GetId(), ]
                         txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
                     else:
-                        
+
                         title_txt.SetLabel(title + ':')
                         value = self._getValue(p)
-                        
-                        if p['name'] == 'icon': # symbols
-                            bitmap = wx.Bitmap(os.path.join(globalvar.SYMBDIR, value) + '.png')
-                            bb = wx.BitmapButton(parent = which_panel, id = wx.ID_ANY,
-                                                 bitmap = bitmap)
-                            iconLabel = wx.StaticText(parent = which_panel, id = wx.ID_ANY)
+
+                        if p['name'] == 'icon':  # symbols
+                            bitmap = wx.Bitmap(
+                                os.path.join(
+                                    globalvar.SYMBDIR,
+                                    value) + '.png')
+                            bb = wx.BitmapButton(
+                                parent=which_panel, id=wx.ID_ANY, bitmap=bitmap)
+                            iconLabel = wx.StaticText(
+                                parent=which_panel, id=wx.ID_ANY)
                             iconLabel.SetLabel(value)
                             p['value'] = value
                             p['wxId'] = [bb.GetId(), iconLabel.GetId()]
                             bb.Bind(wx.EVT_BUTTON, self.OnSetSymbol)
                             this_sizer = wx.BoxSizer(wx.HORIZONTAL)
-                            this_sizer.Add(item = bb, proportion = 0,
-                                            flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
-                            this_sizer.Add(item = iconLabel, proportion = 0,
-                                            flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border = 5)
-                            which_sizer.Add(item = this_sizer, proportion = 0,
-                                            flag = wx.ADJUST_MINSIZE, border = 0)
+                            this_sizer.Add(
+                                item=bb, proportion=0, flag=wx.ADJUST_MINSIZE |
+                                wx.BOTTOM | wx.LEFT, border=5)
+                            this_sizer.Add(
+                                item=iconLabel,
+                                proportion=0,
+                                flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.ALIGN_CENTER_VERTICAL,
+                                border=5)
+                            which_sizer.Add(item=this_sizer, proportion=0,
+                                            flag=wx.ADJUST_MINSIZE, border=0)
                         else:
                             # list of values (combo)
-                            cb = wx.ComboBox(parent=which_panel, id=wx.ID_ANY, value=p.get('default',''),
-                                             size=globalvar.DIALOG_COMBOBOX_SIZE,
-                                             choices=valuelist, style=wx.CB_DROPDOWN)
+                            cb = wx.ComboBox(
+                                parent=which_panel, id=wx.ID_ANY, value=p.get(
+                                    'default', ''),
+                                size=globalvar.DIALOG_COMBOBOX_SIZE,
+                                choices=valuelist, style=wx.CB_DROPDOWN)
                             if value:
-                                cb.SetValue(value) # parameter previously set
-                            which_sizer.Add(item = cb, proportion = 0,
-                                            flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
-                            p['wxId'] = [cb.GetId(),]
+                                cb.SetValue(value)  # parameter previously set
+                            which_sizer.Add(
+                                item=cb, proportion=0, flag=wx.ADJUST_MINSIZE |
+                                wx.BOTTOM | wx.LEFT, border=5)
+                            p['wxId'] = [cb.GetId(), ]
                             cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
                             cb.Bind(wx.EVT_TEXT, self.OnSetValue)
                             if p.get('guidependency', ''):
-                                cb.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
-            
+                                cb.Bind(
+                                    wx.EVT_COMBOBOX, self.OnUpdateSelection)
+
             # text entry
-            if (p.get('type','string') in ('string','integer','float')
-                and len(p.get('values',[])) == 0
-                and p.get('gisprompt',False) == False
-                and p.get('prompt','') !=  'color'):
+            if (p.get('type', 'string') in ('string', 'integer', 'float')
+                    and len(p.get('values', [])) == 0
+                    and p.get('gisprompt', False) == False
+                    and p.get('prompt', '') != 'color'):
 
                 title_txt.SetLabel(title + ':')
-                
+
                 if p.get('multiple', False) or \
                         p.get('type', 'string') == 'string' or \
                         len(p.get('key_desc', [])) > 1:
-                    win = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
-                    
+                    win = wx.TextCtrl(
+                        parent=which_panel, value=p.get(
+                            'default', ''))
+
                     value = self._getValue(p)
                     if value:
                         # parameter previously set
                         win.SetValue(str(value))
-                        
+
                     win.Bind(wx.EVT_TEXT, self.OnSetValue)
                     style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
                 elif p.get('type', '') == 'integer':
                     minValue = -1e9
                     maxValue = 1e9
                     value = self._getValue(p)
-                    
-                    win = wx.SpinCtrl(parent = which_panel, value = p.get('default', ''),
-                                       size = globalvar.DIALOG_SPIN_SIZE,
-                                       min = minValue, max = maxValue)
+
+                    win = wx.SpinCtrl(
+                        parent=which_panel,
+                        value=p.get(
+                            'default',
+                            ''),
+                        size=globalvar.DIALOG_SPIN_SIZE,
+                        min=minValue,
+                        max=maxValue)
                     if value:
-                        win.SetValue(int(value)) # parameter previously set
+                        win.SetValue(int(value))  # parameter previously set
                         win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
 
                     style = wx.BOTTOM | wx.LEFT | wx.RIGHT
-                else: # float
-                    win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
-                                       validator = FloatValidator())
+                else:  # float
+                    win = wx.TextCtrl(
+                        parent=which_panel, value=p.get(
+                            'default', ''), validator=FloatValidator())
                     style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
-                    
+
                     value = self._getValue(p)
                     if value:
-                        win.SetValue(str(value)) # parameter previously set
-                
+                        win.SetValue(str(value))  # parameter previously set
+
                 win.Bind(wx.EVT_TEXT, self.OnSetValue)
-                
-                which_sizer.Add(item = win, proportion = 0,
-                                flag = style, border = 5)
+
+                which_sizer.Add(item=win, proportion=0,
+                                flag=style, border=5)
                 p['wxId'] = [win.GetId()]
-            
+
             #
             # element selection tree combobox (maps, icons, regions, etc.)
             #
             if p.get('gisprompt', False):
                 title_txt.SetLabel(title + ':')
                 # GIS element entry
-                if p.get('prompt','') not in ('color',
-                                              'cat',
-                                              'cats',
-                                              'subgroup',
-                                              'sigfile',
-                                              'separator',
-                                              'dbdriver',
-                                              'dbname',
-                                              'dbtable',
-                                              'dbcolumn',
-                                              'layer',
-                                              'location',
-                                              'mapset',
-                                              'dbase',
-                                              'coords',
-                                              'file',
-                                              'dir',
-                                              'colortable',
-                                              'barscale',
-                                              'northarrow',
-                                              'datasource',
-                                              'datasource_layer'):
+                if p.get('prompt', '') not in ('color',
+                                               'cat',
+                                               'cats',
+                                               'subgroup',
+                                               'sigfile',
+                                               'separator',
+                                               'dbdriver',
+                                               'dbname',
+                                               'dbtable',
+                                               'dbcolumn',
+                                               'layer',
+                                               'location',
+                                               'mapset',
+                                               'dbase',
+                                               'coords',
+                                               'file',
+                                               'dir',
+                                               'colortable',
+                                               'barscale',
+                                               'northarrow',
+                                               'datasource',
+                                               'datasource_layer'):
                     multiple = p.get('multiple', False)
                     if p.get('age', '') == 'new':
-                        mapsets = [grass.gisenv()['MAPSET'],]
+                        mapsets = [grass.gisenv()['MAPSET'], ]
                     else:
                         mapsets = None
                     if self.task.name in ('r.proj', 'v.proj') \
                             and p.get('name', '') == 'input':
-                        selection = gselect.ProjSelect(parent = which_panel,
-                                                       isRaster = self.task.name == 'r.proj')
-                        p['wxId'] = [ selection.GetId(), ]
+                        selection = gselect.ProjSelect(
+                            parent=which_panel, isRaster=self.task.name == 'r.proj')
+                        p['wxId'] = [selection.GetId(), ]
                         selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
                         selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
                     else:
@@ -1197,38 +1366,46 @@
                         # hack for t.* modules
                         if elem in ('stds', 'map'):
                             orig_elem = elem
-                            type_param = self.task.get_param('type', element = 'name', raiseError = False)
+                            type_param = self.task.get_param(
+                                'type', element='name', raiseError=False)
                             if type_param:
                                 elem = type_param.get('default', None)
                                 # for t.(un)register:
-                                maps_param = self.task.get_param('maps', element = 'name', raiseError = False)
+                                maps_param = self.task.get_param(
+                                    'maps', element='name', raiseError=False)
                                 if maps_param and orig_elem == 'stds':
-                                    element_dict = {'raster': 'strds', 'vector': 'stvds', 'raster_3d': 'str3ds'}
-                                    elem = element_dict[type_param.get('default')]
+                                    element_dict = {
+                                        'raster': 'strds', 'vector': 'stvds', 'raster_3d': 'str3ds'}
+                                    elem = element_dict[
+                                        type_param.get('default')]
 
                         extraItems = None
                         if self._giface:
                             if hasattr(self._giface, "_model"):
-                                extraItems = {_('Graphical Modeler') : self._giface.GetLayerList(p.get('prompt'))}
+                                extraItems = {
+                                    _('Graphical Modeler'): self._giface.GetLayerList(
+                                        p.get('prompt'))}
                             else:
                                 layers = self._giface.GetLayerList()
                                 if len(layers) > 0:
                                     mapList = []
-                                    extraItems = {_('Map Display') : mapList}
+                                    extraItems = {_('Map Display'): mapList}
                                     for layer in layers:
                                         if layer.type != p.get('prompt'):
                                             continue
                                         mapList.append(str(layer))
-                        selection = gselect.Select(parent = which_panel, id = wx.ID_ANY,
-                                                   size = globalvar.DIALOG_GSELECT_SIZE,
-                                                   type = elem, multiple = multiple, nmaps = len(p.get('key_desc', [])),
-                                                   mapsets = mapsets, fullyQualified = p.get('age', 'old') == 'old',
-                                                   extraItems = extraItems)
-                        
+                        selection = gselect.Select(
+                            parent=which_panel, id=wx.ID_ANY,
+                            size=globalvar.DIALOG_GSELECT_SIZE, type=elem,
+                            multiple=multiple, nmaps=len(
+                                p.get('key_desc', [])),
+                            mapsets=mapsets, fullyQualified=p.get(
+                                'age', 'old') == 'old', extraItems=extraItems)
+
                         value = self._getValue(p)
                         if value:
                             selection.SetValue(value)
-                        
+
                         formatSelector = True
                         # A gselect.Select is a combobox with two children: a textctl and a popupwindow;
                         # we target the textctl here
@@ -1238,23 +1415,26 @@
                         else:
                             p['wxId'] = [textWin.GetId(), ]
                         if prompt != 'vector':
-                            self.FindWindowById(p['wxId'][0]).Bind(wx.EVT_TEXT, self.OnSetValue)
+                            self.FindWindowById(
+                                p['wxId'][0]).Bind(
+                                wx.EVT_TEXT, self.OnSetValue)
 
                     if prompt == 'vector':
                         win = self.FindWindowById(p['wxId'][0])
                         # handlers should be bound in this order
-                        # OnUpdateSelection depends on calling OnSetValue first which is bad
+                        # OnUpdateSelection depends on calling OnSetValue first
+                        # which is bad
                         win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
                         win.Bind(wx.EVT_TEXT, self.OnSetValue)
 
                         # if formatSelector and p.get('age', 'old') == 'old':
                         #     # OGR supported (read-only)
                         #     self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
-                            
+
                         #     self.hsizer.Add(item = selection,
                         #                     flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
                         #                     border = 5)
-                            
+
                         #     # format (native / ogr)
                         #     rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
                         #                        label = " %s " % _("Format"),
@@ -1264,38 +1444,42 @@
                         #         rbox.SetSelection(1)
                         #     rbox.SetName('VectorFormat')
                         #     rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
-                            
+
                         #     self.hsizer.Add(item = rbox,
                         #                     flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
                         #                     wx.RIGHT | wx.ALIGN_TOP,
                         #                     border = 5)
-                            
+
                         #     ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True,
                         #                                       default = 'dir',
                         #                                       exclude = ['file'])
                         #     self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection)
                         #     self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue)
-                            
+
                         #     ogrSelection.SetName('OgrSelect')
                         #     ogrSelection.Hide()
-                            
+
                         #     which_sizer.Add(item = self.hsizer, proportion = 0)
-                            
+
                         #     p['wxId'].append(rbox.GetId())
                         #     p['wxId'].append(ogrSelection.GetId())
                         #     for win in ogrSelection.GetDsnWin():
                         #         p['wxId'].append(win.GetId())
                         # else:
-                        which_sizer.Add(item = selection, proportion = 0,
-                                        flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
-                                        border = 5)
+                        which_sizer.Add(
+                            item=selection,
+                            proportion=0,
+                            flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
+                            border=5)
                     elif prompt == 'group':
                         win = self.FindWindowById(p['wxId'][0])
                         win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
                         win.Bind(wx.EVT_TEXT, self.OnSetValue)
-                        which_sizer.Add(item = selection, proportion = 0,
-                                        flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
-                                        border = 5)
+                        which_sizer.Add(
+                            item=selection,
+                            proportion=0,
+                            flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
+                            border=5)
                     else:
                         if prompt in ('stds', 'strds', 'stvds', 'str3ds'):
                             showButton = True
@@ -1308,58 +1492,77 @@
                         else:
                             showButton = False
                         if showButton:
-                            iconTheme = UserSettings.Get(group='appearance', key='iconTheme', subkey='type')
-                            bitmap = wx.Bitmap(os.path.join(globalvar.ICONDIR, iconTheme, 'map-info.png'))
-                            bb = wx.BitmapButton(parent=which_panel, bitmap=bitmap)
+                            iconTheme = UserSettings.Get(
+                                group='appearance', key='iconTheme', subkey='type')
+                            bitmap = wx.Bitmap(
+                                os.path.join(
+                                    globalvar.ICONDIR, iconTheme,
+                                    'map-info.png'))
+                            bb = wx.BitmapButton(
+                                parent=which_panel, bitmap=bitmap)
                             bb.Bind(wx.EVT_BUTTON, self.OnTimelineTool)
-                            bb.SetToolTipString(_("Show graphical representation of temporal extent of dataset(s) ."))
+                            bb.SetToolTipString(
+                                _("Show graphical representation of temporal extent of dataset(s) ."))
                             p['wxId'].append(bb.GetId())
 
                             hSizer = wx.BoxSizer(wx.HORIZONTAL)
-                            hSizer.Add(item=selection, proportion=0,
-                                       flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
-                                       border=5)
-                            hSizer.Add(item=bb, proportion=0,
-                                       flag=wx.EXPAND|wx.BOTTOM | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
-                                       border=5)
+                            hSizer.Add(
+                                item=selection,
+                                proportion=0,
+                                flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
+                                border=5)
+                            hSizer.Add(
+                                item=bb,
+                                proportion=0,
+                                flag=wx.EXPAND | wx.BOTTOM | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
+                                border=5)
                             which_sizer.Add(hSizer)
                         else:
-                            which_sizer.Add(item=selection, proportion=0,
-                                            flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
-                                            border=5)
+                            which_sizer.Add(
+                                item=selection,
+                                proportion=0,
+                                flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
+                                border=5)
 
                 # subgroup
                 elif prompt == 'subgroup':
-                    selection = gselect.SubGroupSelect(parent = which_panel)
-                    p['wxId'] = [ selection.GetId() ]
+                    selection = gselect.SubGroupSelect(parent=which_panel)
+                    p['wxId'] = [selection.GetId()]
                     selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
                     selection.Bind(wx.EVT_TEXT, self.OnSetValue)
-                    which_sizer.Add(item = selection, proportion = 0,
-                                    flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
-                                    border = 5)
+                    which_sizer.Add(
+                        item=selection,
+                        proportion=0,
+                        flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
+                        border=5)
 
                 # sigrature file
                 elif prompt == 'sigfile':
-                    selection = gselect.SignatureSelect(parent = which_panel, element = p.get('element', 'sig'))
-                    p['wxId'] = [ selection.GetId() ]
+                    selection = gselect.SignatureSelect(
+                        parent=which_panel, element=p.get('element', 'sig'))
+                    p['wxId'] = [selection.GetId()]
                     selection.Bind(wx.EVT_TEXT, self.OnSetValue)
                     selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
-                    which_sizer.Add(item = selection, proportion = 0,
-                                    flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
-                                    border = 5)
+                    which_sizer.Add(
+                        item=selection,
+                        proportion=0,
+                        flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
+                        border=5)
 
                 # separator
                 elif prompt == 'separator':
-                    win = gselect.SeparatorSelect(parent = which_panel)
+                    win = gselect.SeparatorSelect(parent=which_panel)
                     value = self._getValue(p)
                     win.SetValue(value)
-                    p['wxId'] = [ win.GetId() ]
+                    p['wxId'] = [win.GetId()]
                     win.Bind(wx.EVT_TEXT, self.OnSetValue)
                     win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
-                    which_sizer.Add(item = win, proportion = 0,
-                                    flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
-                                    border = 5)
-                
+                    which_sizer.Add(
+                        item=win,
+                        proportion=0,
+                        flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
+                        border=5)
+
                 # layer, dbdriver, dbname, dbcolumn, dbtable entry
                 elif prompt in ('dbdriver',
                                 'dbname',
@@ -1370,116 +1573,128 @@
                                 'mapset',
                                 'dbase'):
                     if p.get('multiple', 'no') == 'yes':
-                        win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
-                                          size = globalvar.DIALOG_TEXTCTRL_SIZE)
+                        win = wx.TextCtrl(
+                            parent=which_panel, value=p.get(
+                                'default', ''), size=globalvar.DIALOG_TEXTCTRL_SIZE)
                         win.Bind(wx.EVT_TEXT, self.OnSetValue)
                     else:
                         value = self._getValue(p)
-                        
+
                         if prompt == 'layer':
                             if p.get('element', 'layer') == 'layer_all':
                                 all = True
                             else:
                                 all = False
                             if p.get('age', 'old') == 'old':
-                                win = gselect.LayerSelect(parent = which_panel,
-                                                          all = all,
-                                                          default = p['default'])
+                                win = gselect.LayerSelect(parent=which_panel,
+                                                          all=all,
+                                                          default=p['default'])
                                 win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
                                 win.Bind(wx.EVT_TEXT, self.OnSetValue)
-                                win.SetValue(str(value))    # default or previously set value
+                                win.SetValue(
+                                    str(value))    # default or previously set value
                             else:
-                                win = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY,
-                                                  min = 1, max = 100, initial = int(p['default']))
+                                win = wx.SpinCtrl(
+                                    parent=which_panel, id=wx.ID_ANY, min=1,
+                                    max=100, initial=int(p['default']))
                                 win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
-                                win.SetValue(int(value))    # default or previously set value
+                                win.SetValue(
+                                    int(value))    # default or previously set value
 
-                            p['wxId'] = [ win.GetId() ]
+                            p['wxId'] = [win.GetId()]
 
                         elif prompt == 'dbdriver':
-                            win = gselect.DriverSelect(parent = which_panel,
-                                                       choices = p.get('values', []),
-                                                       value = value)
+                            win = gselect.DriverSelect(
+                                parent=which_panel, choices=p.get(
+                                    'values', []),
+                                value=value)
                             win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
                             win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
                         elif prompt == 'dbname':
-                            win = gselect.DatabaseSelect(parent = which_panel,
-                                                         value = value)
+                            win = gselect.DatabaseSelect(parent=which_panel,
+                                                         value=value)
                             win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
                             win.Bind(wx.EVT_TEXT, self.OnSetValue)
                         elif prompt == 'dbtable':
                             if p.get('age', 'old') == 'old':
-                                win = gselect.TableSelect(parent = which_panel)
-                                win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
+                                win = gselect.TableSelect(parent=which_panel)
+                                win.Bind(
+                                    wx.EVT_COMBOBOX, self.OnUpdateSelection)
                                 win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
                             else:
-                                win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
-                                                  size = globalvar.DIALOG_TEXTCTRL_SIZE)
+                                win = wx.TextCtrl(
+                                    parent=which_panel, value=p.get(
+                                        'default', ''),
+                                    size=globalvar.DIALOG_TEXTCTRL_SIZE)
                                 win.Bind(wx.EVT_TEXT, self.OnSetValue)
                         elif prompt == 'dbcolumn':
-                            win = gselect.ColumnSelect(parent = which_panel,
-                                                       value = value,
-                                                       param = p,
-                                                       multiple =  p.get('multiple', False))
-                        
+                            win = gselect.ColumnSelect(
+                                parent=which_panel, value=value, param=p,
+                                multiple=p.get('multiple', False))
+
                             # A gselect.ColumnSelect is a combobox
                             # with two children: a textctl and a
                             # popupwindow; we target the textctl here
                             textWin = win.GetTextCtrl()
-                            p['wxId'] = [ textWin.GetId(), ]
-                            
+                            p['wxId'] = [textWin.GetId(), ]
+
                             textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
                             win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
 
                         elif prompt == 'location':
-                            win = gselect.LocationSelect(parent = which_panel,
-                                                         value = value)
-                            win.Bind(wx.EVT_COMBOBOX,     self.OnUpdateSelection)
-                            win.Bind(wx.EVT_COMBOBOX,     self.OnSetValue)
-                        
+                            win = gselect.LocationSelect(parent=which_panel,
+                                                         value=value)
+                            win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
+                            win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
+
                         elif prompt == 'mapset':
                             if p.get('age', 'old') == 'old':
                                 new = False
                             else:
                                 new = True
-                            
-                            win = gselect.MapsetSelect(parent = which_panel,
-                                                       value = value, new = new,
-                                                       multiple = p.get('multiple', False))
+
+                            win = gselect.MapsetSelect(
+                                parent=which_panel, value=value, new=new,
+                                multiple=p.get('multiple', False))
                             textWin = win.GetTextCtrl()
-                            p['wxId'] = [ textWin.GetId(), win.GetId() ]
-                            
+                            p['wxId'] = [textWin.GetId(), win.GetId()]
+
                             textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
                             win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
-                            
+
                         elif prompt == 'dbase':
-                            win = gselect.DbaseSelect(parent = which_panel,
-                                                      changeCallback = self.OnSetValue)
+                            win = gselect.DbaseSelect(
+                                parent=which_panel, changeCallback=self.OnSetValue)
                             win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
-                            p['wxId'] = [ win.GetChildren()[1].GetId() ]
-                            
+                            p['wxId'] = [win.GetChildren()[1].GetId()]
+
                     if 'wxId' not in p:
                         try:
-                            p['wxId'] = [ win.GetId(), ]
+                            p['wxId'] = [win.GetId(), ]
                         except AttributeError:
                             pass
-                    
+
                     flags = wx.BOTTOM | wx.LEFT | wx.RIGHT
                     if prompt == 'dbname':
                         flags |= wx.EXPAND
-                    which_sizer.Add(item = win, proportion = 0,
-                                    flag = flags, border = 5)
+                    which_sizer.Add(item=win, proportion=0,
+                                    flag=flags, border=5)
                 # color entry
                 elif prompt == 'color':
-                    default_color = (200,200,200)
+                    default_color = (200, 200, 200)
                     label_color = _("Select Color")
-                    if p.get('default','') !=  '':
-                        default_color, label_color = utils.color_resolve(p['default'])
-                    if p.get('value','') !=  '' and p.get('value','') != 'none': # parameter previously set
+                    if p.get('default', '') != '':
+                        default_color, label_color = utils.color_resolve(p[
+                                                                         'default'])
+                    if p.get('value', '') != '' and p.get(
+                            'value', '') != 'none':  # parameter previously set
                         if not p.get('multiple', False):
-                            default_color, label_color = utils.color_resolve(p['value'])
-                    if p.get('element', '') == 'color_none' or p.get('multiple', False):
-                        this_sizer = wx.BoxSizer(orient = wx.HORIZONTAL)
+                            default_color, label_color = utils.color_resolve(p[
+                                                                             'value'])
+                    if p.get(
+                            'element', '') == 'color_none' or p.get(
+                            'multiple', False):
+                        this_sizer = wx.BoxSizer(orient=wx.HORIZONTAL)
                     else:
                         this_sizer = which_sizer
                     colorSize = 150
@@ -1488,202 +1703,251 @@
                     # and either a "transparent" checkbox or None
                     p['wxId'] = [None] * 3
                     if p.get('multiple', False):
-                        txt = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY)
-                        this_sizer.Add(item = txt, proportion = 1,
-                                       flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.TOP, border = 5)
+                        txt = wx.TextCtrl(parent=which_panel, id=wx.ID_ANY)
+                        this_sizer.Add(
+                            item=txt,
+                            proportion=1,
+                            flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.TOP,
+                            border=5)
                         txt.Bind(wx.EVT_TEXT, self.OnSetValue)
                         if p.get('value', ''):
                             txt.SetValue(p['value'])
                         colorSize = 40
                         label_color = ''
                         p['wxId'][1] = txt.GetId()
-                        which_sizer.Add(this_sizer, flag = wx.EXPAND | wx.RIGHT, border = 5)
+                        which_sizer.Add(
+                            this_sizer, flag=wx.EXPAND | wx.RIGHT, border=5)
 
-                    btn_colour = csel.ColourSelect(parent = which_panel, id = wx.ID_ANY,
-                                                   label = label_color, colour = default_color,
-                                                   pos = wx.DefaultPosition, size = (colorSize, 32))
-                    this_sizer.Add(item = btn_colour, proportion = 0,
-                                   flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
-                    btn_colour.Bind(csel.EVT_COLOURSELECT,  self.OnColorChange)
+                    btn_colour = csel.ColourSelect(
+                        parent=which_panel, id=wx.ID_ANY, label=label_color,
+                        colour=default_color, pos=wx.DefaultPosition,
+                        size=(colorSize, 32))
+                    this_sizer.Add(
+                        item=btn_colour,
+                        proportion=0,
+                        flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT,
+                        border=5)
+                    btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange)
                     p['wxId'][0] = btn_colour.GetId()
 
                     if p.get('element', '') == 'color_none':
-                        none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent"))
-                        if p.get('value','')  == "none":
+                        none_check = wx.CheckBox(
+                            which_panel, wx.ID_ANY, _("Transparent"))
+                        if p.get('value', '') == "none":
                             none_check.SetValue(True)
                         else:
                             none_check.SetValue(False)
-                        this_sizer.Add(item = none_check, proportion = 0,
-                                       flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border = 5)
+                        this_sizer.Add(
+                            item=none_check, proportion=0,
+                            flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP,
+                            border=5)
                         which_sizer.Add(this_sizer)
                         none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
                         p['wxId'][2] = none_check.GetId()
 
-
                 # file selector
-                elif p.get('prompt','') !=  'color' and p.get('prompt', '') == 'file':
+                elif p.get('prompt', '') != 'color' and p.get('prompt', '') == 'file':
                     if p.get('age', 'new') == 'new':
                         fmode = wx.FD_SAVE
                     else:
                         fmode = wx.FD_OPEN
                     # check wildcard
                     try:
-                        fExt = os.path.splitext(p.get('key_desc', ['*.*'])[0])[1]
+                        fExt = os.path.splitext(
+                            p.get('key_desc', ['*.*'])[0])[1]
                     except:
                         fExt = None
                     if not fExt:
                         fMask = '*'
                     else:
-                        fMask = '%s files (*%s)|*%s|Files (*)|*' % (fExt[1:].upper(), fExt, fExt)
-                    fbb = filebrowse.FileBrowseButton(parent = which_panel, id = wx.ID_ANY, fileMask = fMask,
-                                                      size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
-                                                      dialogTitle = _('Choose %s') % \
-                                                          p.get('description', _('file')).lower(),
-                                                      buttonText = _('Browse'),
-                                                      startDirectory = os.getcwd(), fileMode = fmode,
-                                                      changeCallback = self.OnSetValue)
+                        fMask = '%s files (*%s)|*%s|Files (*)|*' % (
+                            fExt[1:].upper(), fExt, fExt)
+                    fbb = filebrowse.FileBrowseButton(
+                        parent=which_panel,
+                        id=wx.ID_ANY,
+                        fileMask=fMask,
+                        size=globalvar.DIALOG_GSELECT_SIZE,
+                        labelText='',
+                        dialogTitle=_('Choose %s') %
+                        p.get(
+                            'description',
+                            _('file')).lower(),
+                        buttonText=_('Browse'),
+                        startDirectory=os.getcwd(),
+                        fileMode=fmode,
+                        changeCallback=self.OnSetValue)
                     value = self._getValue(p)
                     if value:
-                        fbb.SetValue(value) # parameter previously set
-                    which_sizer.Add(item = fbb, proportion = 0,
-                                    flag = wx.EXPAND | wx.RIGHT, border = 5)
-                    
+                        fbb.SetValue(value)  # parameter previously set
+                    which_sizer.Add(item=fbb, proportion=0,
+                                    flag=wx.EXPAND | wx.RIGHT, border=5)
+
                     # A file browse button is a combobox with two children:
                     # a textctl and a button;
                     # we have to target the button here
-                    p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
-                    if p.get('age', 'new') == 'old' and \
-                            p.get('prompt', '') == 'file' and p.get('element', '') == 'file' and \
-                            UserSettings.Get(group = 'cmd', key = 'interactiveInput', subkey = 'enabled'):
+                    p['wxId'] = [fbb.GetChildren()[1].GetId()]
+                    if p.get(
+                            'age', 'new') == 'old' and p.get(
+                            'prompt', '') == 'file' and p.get(
+                            'element', '') == 'file' and UserSettings.Get(
+                            group='cmd', key='interactiveInput', subkey='enabled'):
                         # widget for interactive input
-                        ifbb = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY,
-                                           style = wx.TE_MULTILINE,
-                                           size = (-1, 75))
+                        ifbb = wx.TextCtrl(parent=which_panel, id=wx.ID_ANY,
+                                           style=wx.TE_MULTILINE,
+                                           size=(-1, 75))
                         if p.get('value', '') and os.path.isfile(p['value']):
                             f = open(p['value'])
                             ifbb.SetValue(''.join(f.readlines()))
                             f.close()
-                        
+
                         ifbb.Bind(wx.EVT_TEXT, self.OnFileText)
-                        
-                        btnLoad = wx.Button(parent = which_panel, id = wx.ID_ANY, label = _("&Load"))
-                        btnLoad.SetToolTipString(_("Load and edit content of a file"))
+
+                        btnLoad = wx.Button(
+                            parent=which_panel, id=wx.ID_ANY, label=_("&Load"))
+                        btnLoad.SetToolTipString(
+                            _("Load and edit content of a file"))
                         btnLoad.Bind(wx.EVT_BUTTON, self.OnFileLoad)
-                        btnSave = wx.Button(parent = which_panel, id = wx.ID_ANY, label = _("&Save as"))
-                        btnSave.SetToolTipString(_("Save content to a file for further use"))
+                        btnSave = wx.Button(
+                            parent=which_panel, id=wx.ID_ANY, label=_("&Save as"))
+                        btnSave.SetToolTipString(
+                            _("Save content to a file for further use"))
                         btnSave.Bind(wx.EVT_BUTTON, self.OnFileSave)
-                        
-                        fileContentLabel = wx.StaticText(parent=which_panel,
-                            id=wx.ID_ANY,
+
+                        fileContentLabel = wx.StaticText(
+                            parent=which_panel, id=wx.ID_ANY,
                             label=_('or enter values directly:'))
                         fileContentLabel.SetToolTipString(
                             _("Enter file content directly instead of specifying"
                               " a file."
                               " Temporary file will be automatically created."))
-                        which_sizer.Add(item=fileContentLabel,
-                                        proportion = 0,
-                                        flag = wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM, border = 5)
-                        which_sizer.Add(item = ifbb, proportion = 1,
-                                        flag = wx.EXPAND | wx.RIGHT | wx.LEFT, border = 5)
+                        which_sizer.Add(
+                            item=fileContentLabel,
+                            proportion=0,
+                            flag=wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM,
+                            border=5)
+                        which_sizer.Add(
+                            item=ifbb,
+                            proportion=1,
+                            flag=wx.EXPAND | wx.RIGHT | wx.LEFT,
+                            border=5)
                         btnSizer = wx.BoxSizer(wx.HORIZONTAL)
-                        btnSizer.Add(item = btnLoad, proportion = 0,
-                                     flag = wx.ALIGN_RIGHT | wx.RIGHT, border = 10)
-                        btnSizer.Add(item = btnSave, proportion = 0,
-                                     flag = wx.ALIGN_RIGHT)
-                        which_sizer.Add(item = btnSizer, proportion = 0,
-                                        flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
-                        
+                        btnSizer.Add(item=btnLoad, proportion=0,
+                                     flag=wx.ALIGN_RIGHT | wx.RIGHT, border=10)
+                        btnSizer.Add(item=btnSave, proportion=0,
+                                     flag=wx.ALIGN_RIGHT)
+                        which_sizer.Add(
+                            item=btnSizer,
+                            proportion=0,
+                            flag=wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP,
+                            border=5)
+
                         p['wxId'].append(ifbb.GetId())
                         p['wxId'].append(btnLoad.GetId())
                         p['wxId'].append(btnSave.GetId())
-                
+
                 # directory selector
-                elif p.get('prompt','') != 'color' and p.get('prompt', '') == 'dir':
-                    fbb = filebrowse.DirBrowseButton(parent = which_panel, id = wx.ID_ANY,
-                                                     size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
-                                                     dialogTitle = _('Choose %s') % \
-                                                         p.get('description', _('Directory')),
-                                                     buttonText = _('Browse'),
-                                                     startDirectory = os.getcwd(),
-                                                     changeCallback = self.OnSetValue)
+                elif p.get('prompt', '') != 'color' and p.get('prompt', '') == 'dir':
+                    fbb = filebrowse.DirBrowseButton(
+                        parent=which_panel,
+                        id=wx.ID_ANY,
+                        size=globalvar.DIALOG_GSELECT_SIZE,
+                        labelText='',
+                        dialogTitle=_('Choose %s') %
+                        p.get(
+                            'description',
+                            _('Directory')),
+                        buttonText=_('Browse'),
+                        startDirectory=os.getcwd(),
+                        changeCallback=self.OnSetValue)
                     value = self._getValue(p)
                     if value:
-                        fbb.SetValue(value) # parameter previously set
-                    which_sizer.Add(item = fbb, proportion = 0,
-                                    flag = wx.EXPAND | wx.RIGHT, border = 5)
-                    
+                        fbb.SetValue(value)  # parameter previously set
+                    which_sizer.Add(item=fbb, proportion=0,
+                                    flag=wx.EXPAND | wx.RIGHT, border=5)
+
                     # A file browse button is a combobox with two children:
                     # a textctl and a button;
                     # we have to target the button here
-                    p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
-                    
+                    p['wxId'] = [fbb.GetChildren()[1].GetId()]
+
                 # interactive inserting of coordinates from map window
                 elif prompt == 'coords':
                     # interactive inserting if layer manager is accessible
                     if self._giface:
-                        win = gselect.CoordinatesSelect(parent = which_panel,
-                                                        giface = self._giface,
-                                                        multiple =  p.get('multiple', False),
-                                                        param = p)
+                        win = gselect.CoordinatesSelect(
+                            parent=which_panel, giface=self._giface, multiple=p.get(
+                                'multiple', False), param=p)
                         p['wxId'] = [win.GetTextWin().GetId()]
                         win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
-                        # bind closing event because destructor is not working properly
+                        # bind closing event because destructor is not working
+                        # properly
                         if hasattr(self.parent, 'dialogClosing'):
                             self.parent.dialogClosing.connect(win.OnClose)
-                    
+
                     # normal text field
                     else:
-                        win = wx.TextCtrl(parent = which_panel)
+                        win = wx.TextCtrl(parent=which_panel)
                         p['wxId'] = [win.GetId()]
                         win.Bind(wx.EVT_TEXT, self.OnSetValue)
-                    
-                    which_sizer.Add(item = win, 
-                                    proportion = 0,
-                                    flag = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT, 
-                                    border = 5)
 
+                    which_sizer.Add(
+                        item=win,
+                        proportion=0,
+                        flag=wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
+                        border=5)
+
                 elif prompt in ('cat', 'cats'):
-                    # interactive selection of vector categories if layer manager is accessible
+                    # interactive selection of vector categories if layer
+                    # manager is accessible
                     if self._giface:
-                        win = gselect.VectorCategorySelect(parent = which_panel, giface = self._giface, task=self.task)
-                        
+                        win = gselect.VectorCategorySelect(
+                            parent=which_panel, giface=self._giface, task=self.task)
+
                         p['wxId'] = [win.GetTextWin().GetId()]
                         win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
-                        # bind closing event because destructor is not working properly
+                        # bind closing event because destructor is not working
+                        # properly
                         if hasattr(self.parent, 'dialogClosing'):
                             self.parent.dialogClosing.connect(win.OnClose)
                     # normal text field
                     else:
-                        win = wx.TextCtrl(parent = which_panel)
+                        win = wx.TextCtrl(parent=which_panel)
                         value = self._getValue(p)
                         win.SetValue(value)
                         p['wxId'] = [win.GetId()]
                         win.Bind(wx.EVT_TEXT, self.OnSetValue)
-                    
-                    which_sizer.Add(item = win,
-                                    proportion = 0,
-                                    flag = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
-                                    border = 5)
-                    
+
+                    which_sizer.Add(
+                        item=win,
+                        proportion=0,
+                        flag=wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
+                        border=5)
+
                 elif prompt in ('colortable', 'barscale', 'northarrow'):
                     if prompt == 'colortable':
-                        cb = ColorTablesComboBox(parent=which_panel, value=p.get('default',''),
-                                                 size=globalvar.DIALOG_COMBOBOX_SIZE,
-                                                 choices=valuelist)
+                        cb = ColorTablesComboBox(
+                            parent=which_panel, value=p.get('default', ''),
+                            size=globalvar.DIALOG_COMBOBOX_SIZE,
+                            choices=valuelist)
                     elif prompt == 'barscale':
-                        cb = BarscalesComboBox(parent=which_panel, value=p.get('default',''),
-                                               size=globalvar.DIALOG_COMBOBOX_SIZE,
-                                               choices=valuelist)
+                        cb = BarscalesComboBox(
+                            parent=which_panel, value=p.get('default', ''),
+                            size=globalvar.DIALOG_COMBOBOX_SIZE,
+                            choices=valuelist)
                     elif prompt == 'northarrow':
-                        cb = NArrowsComboBox(parent=which_panel, value=p.get('default',''),
-                                             size=globalvar.DIALOG_COMBOBOX_SIZE,
-                                             choices=valuelist)
-                    
+                        cb = NArrowsComboBox(
+                            parent=which_panel, value=p.get('default', ''),
+                            size=globalvar.DIALOG_COMBOBOX_SIZE,
+                            choices=valuelist)
+
                     value = self._getValue(p)
                     if value:
-                        cb.SetValue(value) # parameter previously set
-                    which_sizer.Add(item = cb, proportion = 0,
-                                    flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
+                        cb.SetValue(value)  # parameter previously set
+                    which_sizer.Add(
+                        item=cb,
+                        proportion=0,
+                        flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT,
+                        border=5)
                     p['wxId'] = [cb.GetId(), cb.GetTextCtrl().GetId()]
                     cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
                     cb.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnSetValue)
@@ -1691,65 +1955,77 @@
                         cb.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
 
                 elif prompt == 'datasource':
-                    win = gselect.GdalSelect(parent = parent, panel = which_panel,
-                                             ogr = True)
+                    win = gselect.GdalSelect(parent=parent, panel=which_panel,
+                                             ogr=True)
                     win.Bind(wx.EVT_TEXT, self.OnSetValue)
                     win.Bind(wx.EVT_CHOICE, self.OnSetValue)
-                    p['wxId'] = [win.GetId(),
-                                 win.fileWidgets['browse'].GetChildren()[1].GetId(),
-                                 win.dirWidgets['browse'].GetChildren()[1].GetId(),
-                                 win.dbWidgets['choice'].GetId()]
+                    p['wxId'] = [
+                        win.GetId(),
+                        win.fileWidgets['browse'].GetChildren()[1].GetId(),
+                        win.dirWidgets['browse'].GetChildren()[1].GetId(),
+                        win.dbWidgets['choice'].GetId()]
                     value = self._getValue(p)
                     if value:
-                        win.fileWidgets['browse'].GetChildren()[1].SetValue(value) # parameter previously set
-                    which_sizer.Add(item = win, proportion = 0,
-                                    flag = wx.EXPAND)
+                        win.fileWidgets['browse'].GetChildren()[1].SetValue(
+                            value)  # parameter previously set
+                    which_sizer.Add(item=win, proportion=0,
+                                    flag=wx.EXPAND)
 
                 elif prompt == 'datasource_layer':
-                    self.win1 = LayersList(parent = which_panel, columns = [_('Layer id'),
-                                                                            _('Layer name'),
-                                                                            _('Feature type'),
-                                                                            _('Projection match')])
-                    which_sizer.Add(item = self.win1, proportion = 0,
-                                    flag = wx.EXPAND | wx.ALL, border = 3)
-                    porf = self.task.get_param('input', element = 'name', raiseError = False)
+                    self.win1 = LayersList(
+                        parent=which_panel,
+                        columns=[
+                            _('Layer id'),
+                            _('Layer name'),
+                            _('Feature type'),
+                            _('Projection match')])
+                    which_sizer.Add(item=self.win1, proportion=0,
+                                    flag=wx.EXPAND | wx.ALL, border=3)
+                    porf = self.task.get_param(
+                        'input', element='name', raiseError=False)
                     if porf and 'wxId' in porf:
                         winDataSource = self.FindWindowById(porf['wxId'][0])
-                        winDataSource.reloadDataRequired.connect(lambda listData: self.win1.LoadData(listData, False))
+                        winDataSource.reloadDataRequired.connect(
+                            lambda listData: self.win1.LoadData(
+                                listData, False))
                         p['wxId'] = [self.win1.GetId()]
+
                         def OnCheckItem(index, flag):
                             layers = list()
                             for layer, match, listId in self.win1.GetLayers():
                                 layers.append(layer)
-                            porf = self.task.get_param('layer', element = 'name', raiseError = False)
+                            porf = self.task.get_param(
+                                'layer', element='name', raiseError=False)
                             porf['value'] = ','.join(layers)
-                            self.OnUpdateValues() # TODO: replace by signal
+                            self.OnUpdateValues()  # TODO: replace by signal
 
                         self.win1.OnCheckItem = OnCheckItem
-                          
-            if self.parent.GetName() == 'MainFrame' and (self._giface and hasattr(self._giface, "_model")):
-                parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
-                                     label = _("Parameterized in model"))
+
+            if self.parent.GetName() == 'MainFrame' and (
+                    self._giface and hasattr(self._giface, "_model")):
+                parChk = wx.CheckBox(parent=which_panel, id=wx.ID_ANY,
+                                     label=_("Parameterized in model"))
                 parChk.SetName('ModelParam')
                 parChk.SetValue(p.get('parameterized', False))
                 if 'wxId' in p:
                     p['wxId'].append(parChk.GetId())
                 else:
-                    p['wxId'] = [ parChk.GetId() ]
+                    p['wxId'] = [parChk.GetId()]
                 parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
-                which_sizer.Add(item = parChk, proportion = 0,
-                                flag = wx.LEFT, border = 20)
-                
+                which_sizer.Add(item=parChk, proportion=0,
+                                flag=wx.LEFT, border=20)
+
             if title_txt is not None:
                 # create tooltip if given
                 if len(p['values_desc']) > 0:
                     if tooltip:
-                        tooltip +=  2 * os.linesep
+                        tooltip += 2 * os.linesep
                     else:
                         tooltip = ''
                     if len(p['values']) == len(p['values_desc']):
                         for i in range(len(p['values'])):
-                            tooltip +=  p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
+                            tooltip += p['values'][i] + ': ' + \
+                                p['values_desc'][i] + os.linesep
                     tooltip.strip(os.linesep)
                 if tooltip:
                     title_txt.SetToolTipString(tooltip)
@@ -1758,7 +2034,7 @@
                 if 'wxId' in p and len(p['wxId']) > 0:
                     win = self.FindWindowById(p['wxId'][0])
                     win.SetFocus()
-        
+
         #
         # set widget relations for OnUpdateSelection
         #
@@ -1776,20 +2052,21 @@
         pMapset = None
         for p in self.task.params:
             guidep = p.get('guidependency', '')
-            
+
             if guidep:
                 # fixed options dependency defined
                 options = guidep.split(',')
                 for opt in options:
-                    pOpt = self.task.get_param(opt, element = 'name', raiseError = False)
+                    pOpt = self.task.get_param(
+                        opt, element='name', raiseError=False)
                     if pOpt and id:
                         if 'wxId-bind' not in p:
                             p['wxId-bind'] = list()
-                        p['wxId-bind'] +=  pOpt['wxId']
+                        p['wxId-bind'] += pOpt['wxId']
                 continue
             if p.get('gisprompt', False) == False:
                 continue
-            
+
             prompt = p.get('prompt', '')
             if prompt in ('raster', 'vector'):
                 name = p.get('name', '')
@@ -1817,7 +2094,7 @@
                 pLocation = p
             elif prompt == 'mapset':
                 pMapset = p
-        
+
         # collect ids
         pColumnIds = []
         for p in pColumn:
@@ -1828,17 +2105,17 @@
         pSigFileIds = []
         for p in pSigFile:
             pSigFileIds += p['wxId']
-        
+
         # set wxId-bindings
         if pMap:
             pMap['wxId-bind'] = []
             if pLayer:
-                pMap['wxId-bind'] +=  pLayerIds
+                pMap['wxId-bind'] += pLayerIds
             pMap['wxId-bind'] += copy.copy(pColumnIds)
         if pLayer:
             for p in pLayer:
                 p['wxId-bind'] = copy.copy(pColumnIds)
-        
+
         if pDriver and pTable:
             pDriver['wxId-bind'] = pTable['wxId']
 
@@ -1847,24 +2124,24 @@
 
         if pTable and pColumnIds:
             pTable['wxId-bind'] = pColumnIds
-        
+
         if pGroup and pSubGroup:
             if pSigFile:
                 pGroup['wxId-bind'] = pSigFileIds + pSubGroup['wxId']
                 pSubGroup['wxId-bind'] = pSigFileIds
             else:
                 pGroup['wxId-bind'] = pSubGroup['wxId']
-        
+
         if pDbase and pLocation:
             pDbase['wxId-bind'] = pLocation['wxId']
 
         if pLocation and pMapset:
             pLocation['wxId-bind'] = pMapset['wxId']
-        
+
         if pLocation and pMapset and pMap:
             # pLocation['wxId-bind'] +=  pMap['wxId']
             pMapset['wxId-bind'] = pMap['wxId']
-        
+
         #
         # determine panel size
         #
@@ -1878,57 +2155,72 @@
 
         # TODO: be less arbitrary with these 600
         self.panelMinHeight = 100
-        self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
+        self.constrained_size = (
+            min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
         for section in sections:
-            tab[section].SetMinSize((self.constrained_size[0], self.panelMinHeight))
-        
-        
+            tab[section].SetMinSize(
+                (self.constrained_size[0], self.panelMinHeight))
+
         # add pages to notebook
         imageList = wx.ImageList(16, 16)
         self.notebook.AssignImageList(imageList)
 
         for section in sections:
-            self.notebook.AddPage(page = tab[section], text = section, name = section)
+            self.notebook.AddPage(
+                page=tab[section],
+                text=section, name=section)
             index = self.AddBitmapToImageList(section, imageList)
             if index >= 0:
                 self.notebook.SetPageImage(section, index)
 
         # are we running from command line?
-        ### add 'command output' tab regardless standalone dialog
+        # add 'command output' tab regardless standalone dialog
         if self.parent.GetName() == "MainFrame" and self.parent.get_dcmd is None:
             from core.gconsole import GConsole, EVT_CMD_RUN, EVT_CMD_DONE
             from gui_core.goutput import GConsoleWindow
-            self._gconsole = GConsole(guiparent = self.notebook, giface = self._giface)
-            self.goutput = GConsoleWindow(parent = self.notebook, gconsole = self._gconsole, margin = False)
-            self._gconsole.Bind(EVT_CMD_RUN,
-                                lambda event:
-                                    self._switchPageHandler(event=event, notification=Notification.MAKE_VISIBLE))
-            self._gconsole.Bind(EVT_CMD_DONE,
-                                lambda event:
-                                    self._switchPageHandler(event = event, notification=Notification.RAISE_WINDOW))
-            self.outpage = self.notebook.AddPage(page = self.goutput, text = _("Command output"), name = 'output')
+            self._gconsole = GConsole(
+                guiparent=self.notebook, giface=self._giface)
+            self.goutput = GConsoleWindow(
+                parent=self.notebook,
+                gconsole=self._gconsole,
+                margin=False)
+            self._gconsole.Bind(
+                EVT_CMD_RUN, lambda event: self._switchPageHandler(
+                    event=event, notification=Notification.MAKE_VISIBLE))
+            self._gconsole.Bind(
+                EVT_CMD_DONE, lambda event: self._switchPageHandler(
+                    event=event, notification=Notification.RAISE_WINDOW))
+            self.outpage = self.notebook.AddPage(
+                page=self.goutput, text=_("Command output"), name='output')
         else:
             self.goutput = None
             self._gconsole = None
 
-        self.manualTab = HelpPanel(parent = self.notebook, command = self.task.get_name())
+        self.manualTab = HelpPanel(
+            parent=self.notebook,
+            command=self.task.get_name())
         if not self.manualTab.GetFile():
             self.manualTab.Hide()
         else:
-            self.notebook.AddPage(page = self.manualTab, text = _("Manual"), name = 'manual')
-            index = self.AddBitmapToImageList(section = 'manual', imageList = imageList)
+            self.notebook.AddPage(
+                page=self.manualTab,
+                text=_("Manual"),
+                name='manual')
+            index = self.AddBitmapToImageList(
+                section='manual', imageList=imageList)
             if index >= 0:
                 self.notebook.SetPageImage('manual', index)
-        
+
         if self.manualTab.IsLoaded():
-            self.manualTab.SetMinSize((self.constrained_size[0], self.panelMinHeight))
+            self.manualTab.SetMinSize(
+                (self.constrained_size[0], self.panelMinHeight))
 
         self.notebook.SetSelection(0)
 
-        panelsizer.Add(item = self.notebook, proportion = 1, flag = wx.EXPAND)
+        panelsizer.Add(item=self.notebook, proportion=1, flag=wx.EXPAND)
         self.SetSizer(panelsizer)
         panelsizer.Fit(self.notebook)
-        
+
         self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
 
     def _getValue(self, p):
@@ -1936,10 +2228,10 @@
 
         :param p: parameter directory
         """
-        if p.get('value', '') !=  '':
+        if p.get('value', '') != '':
             return p['value']
         return p.get('default', '')
-        
+
     def OnFileLoad(self, event):
         """Load file to interactive input"""
         me = event.GetId()
@@ -1949,31 +2241,31 @@
                 win['file'] = self.FindWindowById(p['wxId'][0])
                 win['text'] = self.FindWindowById(p['wxId'][1])
                 break
-        
+
         if not win:
             return
-        
+
         path = win['file'].GetValue()
         if not path:
-            gcmd.GMessage(parent = self,
-                          message = _("Nothing to load."))
+            gcmd.GMessage(parent=self,
+                          message=_("Nothing to load."))
             return
-        
+
         data = ''
         try:
             f = open(path, "r")
         except IOError as e:
-            gcmd.GError(parent = self, showTraceback = False,
-                        message = _("Unable to load file.\n\nReason: %s") % e)
+            gcmd.GError(parent=self, showTraceback=False,
+                        message=_("Unable to load file.\n\nReason: %s") % e)
             return
-        
+
         try:
             data = f.read()
         finally:
             f.close()
-        
+
         win['text'].SetValue(data)
-        
+
     def OnFileSave(self, event):
         """Save interactive input to the file"""
         wId = event.GetId()
@@ -1983,49 +2275,53 @@
                 win['file'] = self.FindWindowById(p['wxId'][0])
                 win['text'] = self.FindWindowById(p['wxId'][1])
                 break
-        
+
         if not win:
             return
 
         text = win['text'].GetValue()
         if not text:
-            gcmd.GMessage(parent = self,
-                          message = _("Nothing to save."))
+            gcmd.GMessage(parent=self,
+                          message=_("Nothing to save."))
             return
-        
-        dlg = wx.FileDialog(parent = self,
-                            message = _("Save input as..."),
-                            defaultDir = os.getcwd(),
-                            style = wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
 
+        dlg = wx.FileDialog(parent=self,
+                            message=_("Save input as..."),
+                            defaultDir=os.getcwd(),
+                            style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
+
         if dlg.ShowModal() == wx.ID_OK:
             path = dlg.GetPath()
             enc = locale.getdefaultlocale()[1]
-            f = codecs.open(path, encoding = enc, mode = 'w', errors='replace')
+            f = codecs.open(path, encoding=enc, mode='w', errors='replace')
             try:
                 f.write(text + os.linesep)
             finally:
                 f.close()
-            
+
             win['file'].SetValue(path)
-        
+
         dlg.Destroy()
-        
+
     def OnFileText(self, event):
         """File input interactively entered"""
         text = event.GetString()
-        p = self.task.get_param(value = event.GetId(), element = 'wxId', raiseError = False)
+        p = self.task.get_param(
+            value=event.GetId(),
+            element='wxId',
+            raiseError=False)
         if not p:
-            return # should not happen
+            return  # should not happen
         win = self.FindWindowById(p['wxId'][0])
         if text:
             filename = win.GetValue()
-            if not filename or filename == p['default']:  # m.proj has - as default
+            if not filename or filename == p[
+                    'default']:  # m.proj has - as default
                 filename = grass.tempfile()
                 win.SetValue(filename)
-                
+
             enc = locale.getdefaultlocale()[1]
-            f = codecs.open(filename, encoding = enc, mode = 'w', errors='replace')
+            f = codecs.open(filename, encoding=enc, mode='w', errors='replace')
             try:
                 f.write(text)
                 if text[-1] != os.linesep:
@@ -2034,18 +2330,21 @@
                 f.close()
         else:
             win.SetValue('')
-        
+
     def OnVectorFormat(self, event):
         """Change vector format (native / ogr).
 
-        Currently unused.        
+        Currently unused.
         """
         sel = event.GetSelection()
         idEvent = event.GetId()
-        p = self.task.get_param(value = idEvent, element = 'wxId', raiseError = False)
+        p = self.task.get_param(
+            value=idEvent,
+            element='wxId',
+            raiseError=False)
         if not p:
-            return # should not happen
-        
+            return  # should not happen
+
         # detect windows
         winNative = None
         winOgr = None
@@ -2054,53 +2353,56 @@
                 continue
             name = self.FindWindowById(id).GetName()
             if name == 'Select':
-                winNative = self.FindWindowById(id + 1)  # fix the mystery (also in nviz_tools.py)
+                # fix the mystery (also in nviz_tools.py)
+                winNative = self.FindWindowById(id + 1)
             elif name == 'OgrSelect':
                 winOgr = self.FindWindowById(id)
-        
+
         # enable / disable widgets & update values
         rbox = self.FindWindowByName('VectorFormat')
         self.hsizer.Remove(rbox)
         if sel == 0:   # -> native
             winOgr.Hide()
             self.hsizer.Remove(winOgr)
-            
-            self.hsizer.Add(item = winNative,
-                            flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
-                            border = 5)
+
+            self.hsizer.Add(
+                item=winNative,
+                flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
+                border=5)
             winNative.Show()
             p['value'] = winNative.GetValue()
-        
-        elif sel == 1: # -> OGR
+
+        elif sel == 1:  # -> OGR
             sizer = wx.BoxSizer(wx.VERTICAL)
-            
+
             winNative.Hide()
             self.hsizer.Remove(winNative)
 
-            sizer.Add(item = winOgr)
+            sizer.Add(item=winOgr)
             winOgr.Show()
             p['value'] = winOgr.GetDsn()
-            
-            self.hsizer.Add(item = sizer,
-                            flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
-                            border = 5)
-        
-        self.hsizer.Add(item = rbox,
-                        flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
+
+            self.hsizer.Add(
+                item=sizer,
+                flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
+                border=5)
+
+        self.hsizer.Add(item=rbox,
+                        flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
                         wx.RIGHT | wx.ALIGN_TOP,
-                        border = 5)
-        
+                        border=5)
+
         self.hsizer.Layout()
         self.Layout()
         self.OnUpdateValues()
         self.OnUpdateSelection(event)
-        
+
     def OnUpdateDialog(self, event):
         for fn, kwargs in event.data.iteritems():
             fn(**kwargs)
-        
+
         self.parent.updateValuesHook()
-        
+
     def OnVerbosity(self, event):
         """Verbosity level changed"""
         verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
@@ -2122,7 +2424,7 @@
             sel = self.notebook.GetSelection()
         else:
             sel = event.GetSelection()
-        
+
         idx = self.notebook.GetPageIndexByName('manual')
         if idx > -1 and sel == idx:
             # calling LoadPage() is strangely time-consuming (only first call)
@@ -2159,13 +2461,14 @@
         myId = event.GetId()
         for p in self.task.params:
             if 'wxId' in p and myId in p['wxId']:
-                multiple = p['wxId'][1] is not None # multiple colors
+                multiple = p['wxId'][1] is not None  # multiple colors
                 hasTansp = p['wxId'][2] is not None
                 if multiple:
                     # selected color is added at the end of textCtrl
                     colorchooser = wx.FindWindowById(p['wxId'][0])
                     new_color = colorchooser.GetValue()[:]
-                    new_label = utils.rgb2str.get(new_color, ':'.join(map(str, new_color)))
+                    new_label = utils.rgb2str.get(
+                        new_color, ':'.join(map(str, new_color)))
                     textCtrl = wx.FindWindowById(p['wxId'][1])
                     val = textCtrl.GetValue()
                     sep = ','
@@ -2173,22 +2476,23 @@
                         val += sep
                     val += new_label
                     textCtrl.SetValue(val)
-                    p[ 'value' ] = val
+                    p['value'] = val
                 elif hasTansp and wx.FindWindowById(p['wxId'][2]).GetValue():
-                    p[ 'value' ] = 'none'
+                    p['value'] = 'none'
                 else:
                     colorchooser = wx.FindWindowById(p['wxId'][0])
                     new_color = colorchooser.GetValue()[:]
                     # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
                     # under wx2.8.1
-                    new_label = utils.rgb2str.get(new_color, ':'.join(map(str,new_color)))
+                    new_label = utils.rgb2str.get(
+                        new_color, ':'.join(map(str, new_color)))
                     colorchooser.SetLabel(new_label)
                     colorchooser.SetColour(new_color)
                     colorchooser.Refresh()
-                    p[ 'value' ] = colorchooser.GetLabel()
+                    p['value'] = colorchooser.GetLabel()
         self.OnUpdateValues()
 
-    def OnUpdateValues(self, event = None):
+    def OnUpdateValues(self, event=None):
         """If we were part of a richer interface, report back the
         current command being built.
 
@@ -2216,12 +2520,12 @@
         theValue = theParam['values'][myIndex]
 
         if event.Checked():
-            currentValues[ theValue ] = 1
+            currentValues[theValue] = 1
         else:
-            del currentValues[ theValue ]
+            del currentValues[theValue]
 
         # Keep the original order, so that some defaults may be recovered
-        currentValueList = [] 
+        currentValueList = []
         for v in theParam['values']:
             if v in currentValues:
                 currentValueList.append(v)
@@ -2242,19 +2546,19 @@
         myId = event.GetId()
         me = wx.FindWindowById(myId)
         name = me.GetName()
-        
+
         found = False
         for porf in self.task.params + self.task.flags:
             if 'wxId' not in porf:
                 continue
-            
+
             if myId in porf['wxId']:
                 found = True
                 break
-        
+
         if not found:
             return
-        
+
         if name == 'GdalSelect':
             porf['value'] = event.dsn
         elif name == 'ModelParam':
@@ -2262,7 +2566,8 @@
         elif name == 'GdalSelectDataSource':
             win = self.FindWindowById(porf['wxId'][0])
             porf['value'] = win.GetDsn()
-            pLayer = self.task.get_param('layer', element = 'name', raiseError = False)
+            pLayer = self.task.get_param(
+                'layer', element='name', raiseError=False)
             if pLayer:
                 pLayer['value'] = ''
         else:
@@ -2271,42 +2576,42 @@
             elif isinstance(me, wx.ComboBox):
                 porf['value'] = me.GetValue()
             elif isinstance(me, wx.Choice):
-                porf['value'] = me.GetStringSelection()                    
+                porf['value'] = me.GetStringSelection()
             else:
                 porf['value'] = me.GetValue()
-        
+
         self.OnUpdateValues(event)
-        
+
         event.Skip()
-        
+
     def OnSetSymbol(self, event):
         """Shows dialog for symbol selection"""
         myId = event.GetId()
-        
+
         for p in self.task.params:
             if 'wxId' in p and myId in p['wxId']:
                 from gui_core.dialogs import SymbolDialog
-                dlg = SymbolDialog(self, symbolPath = globalvar.SYMBDIR,
-                                   currentSymbol = p['value'])
+                dlg = SymbolDialog(self, symbolPath=globalvar.SYMBDIR,
+                                   currentSymbol=p['value'])
                 if dlg.ShowModal() == wx.ID_OK:
                     img = dlg.GetSelectedSymbolPath()
                     p['value'] = dlg.GetSelectedSymbolName()
-                    
+
                     bitmapButton = wx.FindWindowById(p['wxId'][0])
                     label = wx.FindWindowById(p['wxId'][1])
-                    
+
                     bitmapButton.SetBitmapLabel(wx.Bitmap(img + '.png'))
                     label.SetLabel(p['value'])
-                    
+
                     self.OnUpdateValues(event)
-                    
+
                 dlg.Destroy()
 
     def OnTimelineTool(self, event):
         """Show Timeline Tool with dataset(s) from gselect.
 
         .. todo::
-            update from gselect automatically        
+            update from gselect automatically
         """
         myId = event.GetId()
 
@@ -2339,8 +2644,8 @@
                                             None,
                                             None,
                                             self.task)
-            
-    def createCmd(self, ignoreErrors = False, ignoreRequired = False):
+
+    def createCmd(self, ignoreErrors=False, ignoreRequired=False):
         """Produce a command line string (list) or feeding into GRASS.
 
         :param ignoreErrors: True then it will return whatever has been
@@ -2348,37 +2653,46 @@
                              a correct command for GRASS
         """
         try:
-            cmd = self.task.get_cmd(ignoreErrors = ignoreErrors,
-                                   ignoreRequired = ignoreRequired)
+            cmd = self.task.get_cmd(ignoreErrors=ignoreErrors,
+                                    ignoreRequired=ignoreRequired)
         except ValueError as err:
-            dlg = wx.MessageDialog(parent = self,
-                                   message = gcmd.DecodeString(str(err)),
-                                   caption = _("Error in %s") % self.task.name,
-                                   style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
+            dlg = wx.MessageDialog(parent=self,
+                                   message=gcmd.DecodeString(str(err)),
+                                   caption=_("Error in %s") % self.task.name,
+                                   style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
             dlg.ShowModal()
             dlg.Destroy()
             cmd = None
-        
+
         return cmd
-    
+
     def OnSize(self, event):
         width = event.GetSize()[0]
         fontsize = self.GetFont().GetPointSize()
         text_width = max(width / (fontsize - 3), 70)
-        
+
         for id in self.label_id:
             win = self.FindWindowById(id)
             label = win.GetLabel()
             label_new = '\n'.join(textwrap.wrap(label, text_width))
             win.SetLabel(label_new)
-            
+
         event.Skip()
-        
+
     def AddBitmapToImageList(self, section, imageList):
-        iconTheme = UserSettings.Get(group = 'appearance', key = 'iconTheme', subkey = 'type')
-        iconSectionDict = {'manual': os.path.join(globalvar.ICONDIR, iconTheme, 'help.png')}
+        iconTheme = UserSettings.Get(
+            group='appearance',
+            key='iconTheme',
+            subkey='type')
+        iconSectionDict = {
+            'manual': os.path.join(
+                globalvar.ICONDIR,
+                iconTheme,
+                'help.png')}
         if section in iconSectionDict.keys():
-            image = wx.Image(iconSectionDict[section]).Scale(16, 16, wx.IMAGE_QUALITY_HIGH)
+            image = wx.Image(
+                iconSectionDict[section]).Scale(
+                16, 16, wx.IMAGE_QUALITY_HIGH)
             idx = imageList.Add(wx.BitmapFromImage(image))
             return idx
 
@@ -2386,42 +2700,43 @@
 
 
 class GUI:
-    def __init__(self, parent = None, giface = None, show = True, modal = False,
-                 centreOnParent = False, checkError = False):
+
+    def __init__(self, parent=None, giface=None, show=True, modal=False,
+                 centreOnParent=False, checkError=False):
         """Parses GRASS commands when module is imported and used from
         Layer Manager.
         """
         self.parent = parent
-        self.show   = show
-        self.modal  = modal
+        self.show = show
+        self.modal = modal
         self._giface = giface
         self.centreOnParent = centreOnParent
-        self.checkError     = checkError
-        
+        self.checkError = checkError
+
         self.grass_task = None
         self.cmd = list()
-        
+
         global _blackList
         if self.parent:
             _blackList['enabled'] = True
         else:
             _blackList['enabled'] = False
-        
+
     def GetCmd(self):
         """Get validated command"""
         return self.cmd
-    
-    def ParseCommand(self, cmd, completed = None):
+
+    def ParseCommand(self, cmd, completed=None):
         """Parse command
-        
+
         Note: cmd is given as list
-        
+
         If command is given with options, return validated cmd list:
          - add key name for first parameter if not given
          - change mapname to mapname at mapset
         """
         dcmd_params = {}
-        if completed == None:
+        if completed is None:
             get_dcmd = None
             layer = None
             dcmd_params = None
@@ -2430,75 +2745,79 @@
             layer = completed[1]
             if completed[2]:
                 dcmd_params.update(completed[2])
-        
+
         # parse the interface decription
         try:
             global _blackList
             self.grass_task = gtask.parse_interface(cmd[0],
-                                                    blackList = _blackList)
+                                                    blackList=_blackList)
         except (grass.ScriptError, ValueError) as e:
             raise gcmd.GException(e.value)
-        
+
         # if layer parameters previously set, re-insert them into dialog
         if completed is not None:
             if 'params' in dcmd_params:
                 self.grass_task.params = dcmd_params['params']
             if 'flags' in dcmd_params:
                 self.grass_task.flags = dcmd_params['flags']
-        
+
         err = list()
         # update parameters if needed && validate command
         if len(cmd) > 1:
             i = 0
             cmd_validated = [cmd[0]]
             for option in cmd[1:]:
-                if option[0] == '-': # flag
+                if option[0] == '-':  # flag
                     if len(option) == 1:  # catch typo like 'g.proj - w'
-                        raise gcmd.GException, _("Unable to parse command '%s'") % ' '.join(cmd)
+                        raise gcmd.GException(
+                            _("Unable to parse command '%s'") %
+                            ' '.join(cmd))
                     if option[1] == '-':
                         self.grass_task.set_flag(option[2:], True)
                     else:
                         self.grass_task.set_flag(option[1], True)
                     cmd_validated.append(option)
-                else: # parameter
+                else:  # parameter
                     try:
                         key, value = option.split('=', 1)
                     except ValueError:
                         if self.grass_task.firstParam:
-                            if i == 0: # add key name of first parameter if not given
+                            if i == 0:  # add key name of first parameter if not given
                                 key = self.grass_task.firstParam
                                 value = option
                             else:
-                                raise gcmd.GException, _("Unable to parse command '%s'") % ' '.join(cmd)
+                                raise gcmd.GException(
+                                    _("Unable to parse command '%s'") % ' '.join(cmd))
                         else:
                             continue
-                    
-                    task = self.grass_task.get_param(key, raiseError = False)
+
+                    task = self.grass_task.get_param(key, raiseError=False)
                     if not task:
-                        err.append(_("%(cmd)s: parameter '%(key)s' not available") % \
-                                       { 'cmd' : cmd[0],
-                                         'key' : key })
+                        err.append(
+                            _("%(cmd)s: parameter '%(key)s' not available") % {
+                                'cmd': cmd[0],
+                                'key': key})
                         continue
-                    
+
                     self.grass_task.set_param(key, value)
                     cmd_validated.append(key + '=' + value)
                     i += 1
-            
+
             # update original command list
             cmd = cmd_validated
-        
+
         if self.show is not None:
-            self.mf = TaskFrame(parent = self.parent, giface = self._giface,
-                                task_description = self.grass_task,
-                                get_dcmd = get_dcmd, layer = layer)
+            self.mf = TaskFrame(parent=self.parent, giface=self._giface,
+                                task_description=self.grass_task,
+                                get_dcmd=get_dcmd, layer=layer)
         else:
             self.mf = None
-        
+
         if get_dcmd is not None:
             # update only propwin reference
-            get_dcmd(dcmd = None, layer = layer, params = None,
-                     propwin = self.mf)
-        
+            get_dcmd(dcmd=None, layer=layer, params=None,
+                     propwin=self.mf)
+
         if self.show is not None:
             self.mf.notebookpanel.OnUpdateSelection(None)
             if self.show is True:
@@ -2510,19 +2829,19 @@
                 self.mf.MakeModal(self.modal)
             else:
                 self.mf.OnApply(None)
-        
+
         self.cmd = cmd
-        
+
         if self.checkError:
             return self.grass_task, err
         else:
             return self.grass_task
-    
+
     def GetCommandInputMapParamKey(self, cmd):
         """Get parameter key for input raster/vector map
-        
+
         :param cmd: module name
-        
+
         :return: parameter key
         :return: None on failure
         """
@@ -2530,37 +2849,44 @@
         if not self.grass_task:
             tree = etree.fromstring(gtask.get_interface_description(cmd))
             self.grass_task = gtask.processTask(tree).get_task()
-            
+
             for p in self.grass_task.params:
                 if p.get('name', '') in ('input', 'map'):
                     age = p.get('age', '')
                     prompt = p.get('prompt', '')
-                    element = p.get('element', '') 
+                    element = p.get('element', '')
                     if age == 'old' and \
                             element in ('cell', 'grid3', 'vector') and \
                             prompt in ('raster', 'raster_3d', 'vector'):
                         return p.get('name', None)
         return None
 
+
 class GrassGUIApp(wx.App):
     """Stand-alone GRASS command GUI
     """
+
     def __init__(self, grass_task):
         self.grass_task = grass_task
         wx.App.__init__(self, False)
-        
+
     def OnInit(self):
         msg = self.grass_task.get_error_msg()
         if msg:
-            gcmd.GError(msg + '\n\n' +
-                        _('Try to set up GRASS_ADDON_PATH or GRASS_ADDON_BASE variable.'))
+            gcmd.GError(
+                msg +
+                '\n\n' +
+                _('Try to set up GRASS_ADDON_PATH or GRASS_ADDON_BASE variable.'))
             return True
-        
-        self.mf = TaskFrame(parent = None, giface = None, task_description = self.grass_task)
+
+        self.mf = TaskFrame(
+            parent=None,
+            giface=None,
+            task_description=self.grass_task)
         self.mf.CentreOnScreen()
         self.mf.Show(True)
         self.SetTopWindow(self.mf)
-        
+
         return True
 
 
@@ -2576,21 +2902,22 @@
 
 
 if __name__ == "__main__":
-    
+
     if len(sys.argv) == 1:
         sys.exit(_(USAGE_MESSAGE).format(name=sys.argv[0]))
 
-    if sys.argv[1] !=  'test':
-        q = wx.LogNull()        
+    if sys.argv[1] != 'test':
+        q = wx.LogNull()
         from core.debug import Debug
         Debug.msg(1, "forms.py called using command: %s" % sys.argv[1])
         cmd = utils.split(sys.argv[1])
         task = gtask.grassTask(cmd[0])
         task.set_options(cmd[1:])
-        Debug.msg(1, "forms.py opening form for: %s" % task.get_cmd(ignoreErrors=True, ignoreRequired=True))
+        Debug.msg(1, "forms.py opening form for: %s" %
+                  task.get_cmd(ignoreErrors=True, ignoreRequired=True))
         app = GrassGUIApp(task)
         app.MainLoop()
-    else: #Test
+    else:  # Test
         # Test grassTask from within a GRASS session
         if os.getenv("GISBASE") is not None:
             task = gtask.grassTask("d.vect")
@@ -2599,7 +2926,8 @@
             task.get_param('layer')['value'] = 1
             task.get_param('label_bcolor')['value'] = "red"
             # the default parameter display is added automatically
-            assert ' '.join(task.get_cmd()) == "d.vect -i map=map_name layer=1 display=shape label_bcolor=red"
+            assert ' '.join(
+                task.get_cmd()) == "d.vect -i map=map_name layer=1 display=shape label_bcolor=red"
             print "Creation of task successful"
         # Test interface building with handmade grassTask,
         # possibly outside of a GRASS session.
@@ -2607,105 +2935,98 @@
         task = gtask.grassTask()
         task.name = "TestTask"
         task.description = "This is an artificial grassTask() object intended for testing purposes."
-        task.keywords = ["grass","test","task"]
+        task.keywords = ["grass", "test", "task"]
         task.params = [
             {
-            "name" : "text",
-            "description" : "Descriptions go into tooltips if labels are present, like this one",
-            "label" : "Enter some text",
-            "key_desc": ["value"],
-            "values_desc": []
-            },{
-            "name" : "hidden_text",
-            "description" : "This text should not appear in the form",
-            "hidden" : True,
-            "key_desc": ["value"],
-            "values_desc": []
-            },{
-            "name" : "text_default",
-            "description" : "Enter text to override the default",
-            "default" : "default text",
-            "key_desc": ["value"],
-            "values_desc": []
-            },{
-            "name" : "text_prefilled",
-            "description" : "You should see a friendly welcome message here",
-            "value" : "hello, world",
-            "key_desc": ["value"],
-            "values_desc": []
-            },{
-            "name" : "plain_color",
-            "description" : "This is a plain color, and it is a compulsory parameter",
-            "required" : False,
-            "gisprompt" : True,
-            "prompt" : "color",
-            "key_desc": ["value"],
-            "values_desc": []
-            },{
-            "name" : "transparent_color",
-            "description" : "This color becomes transparent when set to none",
-            "guisection" : "tab",
-            "gisprompt" : True,
-            "prompt" : "color",
-            "key_desc": ["value"],
-            "values_desc": []
-            },{
-            "name" : "multi",
-            "description" : "A multiple selection",
-            'default': u'red,green,blue',
-            'gisprompt': False,
-            'guisection': 'tab',
-            'multiple': u'yes',
-            'type': u'string',
-            'value': '',
-            'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
-            "key_desc": ["value"],
-            "values_desc": []
-            },{
-            "name" : "single",
-            "description" : "A single multiple-choice selection",
-            'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
-            "guisection" : "tab",
-            "key_desc": ["value"],
-            "values_desc": []
-            },{
-            "name" : "large_multi",
-            "description" : "A large multiple selection",
-            "gisprompt" : False,
-            "multiple" : "yes",
-            # values must be an array of strings
-            "values" : utils.str2rgb.keys() + map(str, utils.str2rgb.values()),
-            "key_desc": ["value"],
-            "values_desc": []
-            },{
-            "name" : "a_file",
-            "description" : "A file selector",
-            "gisprompt" : True,
-            "element" : "file",
-            "key_desc": ["value"],
-            "values_desc": []
+                "name": "text",
+                "description": "Descriptions go into tooltips if labels are present, like this one",
+                "label": "Enter some text",
+                "key_desc": ["value"],
+                "values_desc": []
+            }, {
+                "name": "hidden_text",
+                "description": "This text should not appear in the form",
+                "hidden": True,
+                "key_desc": ["value"],
+                "values_desc": []
+            }, {
+                "name": "text_default",
+                "description": "Enter text to override the default",
+                "default": "default text",
+                "key_desc": ["value"],
+                "values_desc": []
+            }, {
+                "name": "text_prefilled",
+                "description": "You should see a friendly welcome message here",
+                "value": "hello, world",
+                "key_desc": ["value"],
+                "values_desc": []
+            }, {
+                "name": "plain_color",
+                "description": "This is a plain color, and it is a compulsory parameter",
+                "required": False,
+                "gisprompt": True,
+                "prompt": "color",
+                "key_desc": ["value"],
+                "values_desc": []
+            }, {
+                "name": "transparent_color",
+                "description": "This color becomes transparent when set to none",
+                "guisection": "tab",
+                "gisprompt": True,
+                "prompt": "color",
+                "key_desc": ["value"],
+                "values_desc": []
+            }, {
+                "name": "multi",
+                "description": "A multiple selection",
+                'default': u'red,green,blue',
+                'gisprompt': False,
+                'guisection': 'tab',
+                'multiple': u'yes',
+                'type': u'string',
+                'value': '',
+                'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
+                "key_desc": ["value"],
+                "values_desc": []
+            }, {
+                "name": "single",
+                "description": "A single multiple-choice selection",
+                'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
+                "guisection": "tab",
+                "key_desc": ["value"],
+                "values_desc": []
+            }, {
+                "name": "large_multi",
+                "description": "A large multiple selection",
+                "gisprompt": False,
+                "multiple": "yes",
+                # values must be an array of strings
+                "values": utils.str2rgb.keys() + map(str, utils.str2rgb.values()),
+                "key_desc": ["value"],
+                "values_desc": []
+            }, {
+                "name": "a_file",
+                "description": "A file selector",
+                "gisprompt": True,
+                "element": "file",
+                "key_desc": ["value"],
+                "values_desc": []
             }
-            ]
-        task.flags = [
-            {
-            "name" : "a",
-            "description" : "Some flag, will appear in Main since it is required",
-            "required" : True,
-            "value" : False,
-            "suppress_required": False
-            },{
-            "name" : "b",
-            "description" : "pre-filled flag, will appear in options since it is not required",
-            "value" : True,
-            "suppress_required": False
-            },{
-            "name" : "hidden_flag",
-            "description" : "hidden flag, should not be changeable",
-            "hidden" : "yes",
-            "value" : True,
-            "suppress_required": False
-            }
-            ]
+        ]
+        task.flags = [{"name": "a",
+                       "description": "Some flag, will appear in Main since it is required",
+                       "required": True,
+                       "value": False,
+                       "suppress_required": False},
+                      {"name": "b",
+                       "description": "pre-filled flag, will appear in options since it is not required",
+                       "value": True,
+                       "suppress_required": False},
+                      {"name": "hidden_flag",
+                       "description": "hidden flag, should not be changeable",
+                       "hidden": "yes",
+                       "value": True,
+                       "suppress_required": False}]
         q = wx.LogNull()
         GrassGUIApp(task).MainLoop()
-

Modified: grass/trunk/gui/wxpython/gui_core/ghelp.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/ghelp.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gui_core/ghelp.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -33,138 +33,151 @@
 
 import grass.script as grass
 
-from core             import globalvar
+from core import globalvar
 from core.utils import _
-from core.gcmd        import GError, DecodeString
+from core.gcmd import GError, DecodeString
 from gui_core.widgets import FormNotebook, ScrolledPanel
-from core.debug       import Debug
+from core.debug import Debug
 
 
 class AboutWindow(wx.Frame):
     """Create custom About Window
     """
-    def __init__(self, parent, size = (770, 460), 
-                 title = _('About GRASS GIS'), **kwargs):
-        wx.Frame.__init__(self, parent = parent, id = wx.ID_ANY, title = title, size = size, **kwargs)
-        
-        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
-        
+
+    def __init__(self, parent, size=(770, 460),
+                 title=_('About GRASS GIS'), **kwargs):
+        wx.Frame.__init__(
+            self,
+            parent=parent,
+            id=wx.ID_ANY,
+            title=title,
+            size=size,
+            **kwargs)
+
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
         # icon
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass.ico'),
+                wx.BITMAP_TYPE_ICO))
 
         # notebook
-        self.aboutNotebook = FormNotebook(self.panel, style = wx.BK_LEFT)
-        
+        self.aboutNotebook = FormNotebook(self.panel, style=wx.BK_LEFT)
+
         for title, win in ((_("Info"), self._pageInfo()),
                            (_("Copyright"), self._pageCopyright()),
                            (_("License"), self._pageLicense()),
                            (_("Authors"), self._pageCredit()),
                            (_("Contributors"), self._pageContributors()),
-                           (_("Extra contributors"), self._pageContributors(extra = True)),
+                           (_("Extra contributors"), self._pageContributors(extra=True)),
                            (_("Translators"), self._pageTranslators()),
                            (_("Translation status"), self._pageStats())):
-            self.aboutNotebook.AddPage(page = win, text = title)
+            self.aboutNotebook.AddPage(page=win, text=title)
         wx.CallAfter(self.aboutNotebook.SetSelection, 0)
         wx.CallAfter(self.aboutNotebook.Refresh)
-        
+
         # buttons
-        self.btnClose = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
+        self.btnClose = wx.Button(parent=self.panel, id=wx.ID_CLOSE)
         self.btnClose.Bind(wx.EVT_BUTTON, self.OnCloseWindow)
 
         self._doLayout()
-        
+
     def _doLayout(self):
         btnSizer = wx.BoxSizer(wx.HORIZONTAL)
-        btnSizer.Add(item = self.btnClose, proportion = 0,
-                     flag = wx.ALL | wx.ALIGN_RIGHT,
-                     border = 5)
-        
+        btnSizer.Add(item=self.btnClose, proportion=0,
+                     flag=wx.ALL | wx.ALIGN_RIGHT,
+                     border=5)
+
         sizer = wx.BoxSizer(wx.VERTICAL)
-        sizer.Add(item = self.aboutNotebook, proportion = 1,
-                  flag = wx.EXPAND | wx.ALL, border = 1)
-        sizer.Add(item = btnSizer, proportion = 0,
-                  flag = wx.ALL | wx.ALIGN_RIGHT, border = 1)
-        
+        sizer.Add(item=self.aboutNotebook, proportion=1,
+                  flag=wx.EXPAND | wx.ALL, border=1)
+        sizer.Add(item=btnSizer, proportion=0,
+                  flag=wx.ALL | wx.ALIGN_RIGHT, border=1)
+
         self.SetMinSize((400, 400))
-        
+
         self.panel.SetSizer(sizer)
         sizer.Fit(self.panel)
-                
+
         self.Layout()
-        
+
     def _pageInfo(self):
         """Info page"""
         # get version and web site
         vInfo = grass.version()
         if not vInfo:
             sys.stderr.write(_("Unable to get GRASS version\n"))
-        
+
         infoTxt = ScrolledPanel(self.aboutNotebook)
         infoTxt.SetBackgroundColour('WHITE')
         infoTxt.SetupScrolling()
         infoSizer = wx.BoxSizer(wx.VERTICAL)
-        infoGridSizer = wx.GridBagSizer(vgap = 5, hgap = 5)
+        infoGridSizer = wx.GridBagSizer(vgap=5, hgap=5)
         logo = os.path.join(globalvar.ICONDIR, "grass-64x64.png")
-        logoBitmap = wx.StaticBitmap(parent = infoTxt, id = wx.ID_ANY,
-                                     bitmap = wx.Bitmap(name = logo,
-                                                        type = wx.BITMAP_TYPE_PNG))
-        infoSizer.Add(item = logoBitmap, proportion = 0,
-                      flag = wx.ALL | wx.ALIGN_CENTER, border = 20)
-        
+        logoBitmap = wx.StaticBitmap(parent=infoTxt, id=wx.ID_ANY,
+                                     bitmap=wx.Bitmap(name=logo,
+                                                      type=wx.BITMAP_TYPE_PNG))
+        infoSizer.Add(item=logoBitmap, proportion=0,
+                      flag=wx.ALL | wx.ALIGN_CENTER, border=20)
+
         infoLabel = 'GRASS GIS %s' % vInfo.get('version', _('unknown version'))
         if 'x86_64' in vInfo.get('build_platform', ''):
             infoLabel += ' (64bit)'
-        info = wx.StaticText(parent = infoTxt, id = wx.ID_ANY,
-                             label = infoLabel + os.linesep)
+        info = wx.StaticText(parent=infoTxt, id=wx.ID_ANY,
+                             label=infoLabel + os.linesep)
         info.SetFont(wx.Font(13, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
         info.SetForegroundColour(wx.Colour(35, 142, 35))
-        infoSizer.Add(item = info, proportion = 0,
-                      flag = wx.BOTTOM | wx.ALIGN_CENTER, border = 1)
+        infoSizer.Add(item=info, proportion=0,
+                      flag=wx.BOTTOM | wx.ALIGN_CENTER, border=1)
 
         team = wx.StaticText(parent=infoTxt, label=_grassDevTeam(1999) + '\n')
-        infoSizer.Add(item = team, proportion = 0,
-                      flag = wx.BOTTOM | wx.ALIGN_CENTER, border = 1)
-        
+        infoSizer.Add(item=team, proportion=0,
+                      flag=wx.BOTTOM | wx.ALIGN_CENTER, border=1)
+
         row = 0
-        infoGridSizer.Add(item = wx.StaticText(parent = infoTxt, id = wx.ID_ANY,
-                                               label = _('Official GRASS site:')),
-                          pos = (row, 0),
-                          flag = wx.ALIGN_RIGHT)
+        infoGridSizer.Add(item=wx.StaticText(parent=infoTxt, id=wx.ID_ANY,
+                                             label=_('Official GRASS site:')),
+                          pos=(row, 0),
+                          flag=wx.ALIGN_RIGHT)
 
-        infoGridSizer.Add(item = HyperLinkCtrl(parent = infoTxt, id = wx.ID_ANY,
-                                               label = 'http://grass.osgeo.org'),
-                          pos = (row, 1),
-                          flag = wx.ALIGN_LEFT)
+        infoGridSizer.Add(item=HyperLinkCtrl(parent=infoTxt, id=wx.ID_ANY,
+                                             label='http://grass.osgeo.org'),
+                          pos=(row, 1),
+                          flag=wx.ALIGN_LEFT)
 
         row += 2
-        infoGridSizer.Add(item = wx.StaticText(parent = infoTxt, id = wx.ID_ANY,
-                                               label = '%s:' % _('Code Revision')),
-                          pos = (row, 0),
-                          flag = wx.ALIGN_RIGHT)
-        
-        infoGridSizer.Add(item = wx.StaticText(parent = infoTxt, id = wx.ID_ANY,
-                                               label = vInfo.get('revision', '?')),
-                          pos = (row, 1),
-                          flag = wx.ALIGN_LEFT)
-        
+        infoGridSizer.Add(item=wx.StaticText(parent=infoTxt, id=wx.ID_ANY,
+                                             label='%s:' % _('Code Revision')),
+                          pos=(row, 0),
+                          flag=wx.ALIGN_RIGHT)
+
+        infoGridSizer.Add(item=wx.StaticText(parent=infoTxt, id=wx.ID_ANY,
+                                             label=vInfo.get('revision', '?')),
+                          pos=(row, 1),
+                          flag=wx.ALIGN_LEFT)
+
         row += 1
-        infoGridSizer.Add(item = wx.StaticText(parent = infoTxt, id = wx.ID_ANY,
-                                               label = '%s:' % _('Build Date')),
-                          pos = (row, 0),
-                          flag = wx.ALIGN_RIGHT)
-        
-        infoGridSizer.Add(item = wx.StaticText(parent = infoTxt, id = wx.ID_ANY,
-                                               label = vInfo.get('build_date', '?')),
-                          pos = (row, 1),
-                          flag = wx.ALIGN_LEFT)
-        
-        ### show only basic info
+        infoGridSizer.Add(item=wx.StaticText(parent=infoTxt, id=wx.ID_ANY,
+                                             label='%s:' % _('Build Date')),
+                          pos=(row, 0),
+                          flag=wx.ALIGN_RIGHT)
+
+        infoGridSizer.Add(
+            item=wx.StaticText(
+                parent=infoTxt, id=wx.ID_ANY, label=vInfo.get(
+                    'build_date', '?')), pos=(
+                row, 1), flag=wx.ALIGN_LEFT)
+
+        # show only basic info
         # row += 1
         # infoGridSizer.Add(item = wx.StaticText(parent = infoTxt, id = wx.ID_ANY,
         #                                        label = '%s:' % _('GIS Library Revision')),
         #                   pos = (row, 0),
         #                   flag = wx.ALIGN_RIGHT)
-        
+
         # infoGridSizer.Add(item = wx.StaticText(parent = infoTxt, id = wx.ID_ANY,
         #                                        label = vInfo['libgis_revision'] + ' (' +
         #                                        vInfo['libgis_date'].split(' ')[0] + ')'),
@@ -172,38 +185,39 @@
         #                   flag = wx.ALIGN_LEFT)
 
         row += 2
-        infoGridSizer.Add(item = wx.StaticText(parent = infoTxt, id = wx.ID_ANY,
-                                               label = 'Python:'),
-                          pos = (row, 0),
-                          flag = wx.ALIGN_RIGHT)
-        
-        infoGridSizer.Add(item = wx.StaticText(parent = infoTxt, id = wx.ID_ANY,
-                                               label = platform.python_version()),
-                          pos = (row, 1),
-                          flag = wx.ALIGN_LEFT)
+        infoGridSizer.Add(item=wx.StaticText(parent=infoTxt, id=wx.ID_ANY,
+                                             label='Python:'),
+                          pos=(row, 0),
+                          flag=wx.ALIGN_RIGHT)
 
+        infoGridSizer.Add(item=wx.StaticText(parent=infoTxt, id=wx.ID_ANY,
+                                             label=platform.python_version()),
+                          pos=(row, 1),
+                          flag=wx.ALIGN_LEFT)
+
         row += 1
-        infoGridSizer.Add(item = wx.StaticText(parent = infoTxt, id = wx.ID_ANY,
-                                               label =  'wxPython:'),
-                          pos = (row, 0),
-                          flag = wx.ALIGN_RIGHT)
-        
-        infoGridSizer.Add(item = wx.StaticText(parent = infoTxt, id = wx.ID_ANY,
-                                               label = wx.__version__),
-                          pos = (row, 1),
-                          flag = wx.ALIGN_LEFT)
-        
+        infoGridSizer.Add(item=wx.StaticText(parent=infoTxt, id=wx.ID_ANY,
+                                             label='wxPython:'),
+                          pos=(row, 0),
+                          flag=wx.ALIGN_RIGHT)
+
+        infoGridSizer.Add(item=wx.StaticText(parent=infoTxt, id=wx.ID_ANY,
+                                             label=wx.__version__),
+                          pos=(row, 1),
+                          flag=wx.ALIGN_LEFT)
+
         infoGridSizer.AddGrowableCol(0)
         infoGridSizer.AddGrowableCol(1)
-        infoSizer.Add(item = infoGridSizer,
-                      proportion = 1,
-                      flag = wx.EXPAND | wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL)
-        
+        infoSizer.Add(
+            item=infoGridSizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL)
+
         row += 2
-        infoGridSizer.Add(item = wx.StaticText(parent = infoTxt, id = wx.ID_ANY,
-                                               label = "%s:" % _('Language')),
-                          pos = (row, 0),
-                          flag = wx.ALIGN_RIGHT)
+        infoGridSizer.Add(item=wx.StaticText(parent=infoTxt, id=wx.ID_ANY,
+                                             label="%s:" % _('Language')),
+                          pos=(row, 0),
+                          flag=wx.ALIGN_RIGHT)
         self.langUsed = grass.gisenv().get('LANG', None)
         if not self.langUsed:
             import locale
@@ -212,16 +226,16 @@
                 self.langUsed = _('unknown')
             else:
                 self.langUsed = u'%s.%s' % (loc[0], loc[1])
-        infoGridSizer.Add(item = wx.StaticText(parent = infoTxt, id = wx.ID_ANY,
-                                               label = self.langUsed),
-                          pos = (row, 1),
-                          flag = wx.ALIGN_LEFT)        
-        
+        infoGridSizer.Add(item=wx.StaticText(parent=infoTxt, id=wx.ID_ANY,
+                                             label=self.langUsed),
+                          pos=(row, 1),
+                          flag=wx.ALIGN_LEFT)
+
         infoTxt.SetSizer(infoSizer)
         infoSizer.Fit(infoTxt)
-       
+
         return infoTxt
-    
+
     def _pageCopyright(self):
         """Copyright information"""
         copyfile = os.path.join(os.getenv("GISBASE"), "COPYING")
@@ -231,21 +245,22 @@
             copyrightFile.close()
         else:
             copytext = _('%s file missing') % 'COPYING'
-        
+
         # put text into a scrolling panel
         copyrightwin = ScrolledPanel(self.aboutNotebook)
         copyrightwin.SetBackgroundColour('WHITE')
-        copyrighttxt = wx.StaticText(copyrightwin, id = wx.ID_ANY, label = copytext)
+        copyrighttxt = wx.StaticText(
+            copyrightwin, id=wx.ID_ANY, label=copytext)
         copyrightwin.SetAutoLayout(True)
         copyrightwin.sizer = wx.BoxSizer(wx.VERTICAL)
-        copyrightwin.sizer.Add(item = copyrighttxt, proportion = 1,
-                               flag = wx.EXPAND | wx.ALL, border = 3)
+        copyrightwin.sizer.Add(item=copyrighttxt, proportion=1,
+                               flag=wx.EXPAND | wx.ALL, border=3)
         copyrightwin.SetSizer(copyrightwin.sizer)
         copyrightwin.Layout()
         copyrightwin.SetupScrolling()
-        
+
         return copyrightwin
-    
+
     def _pageLicense(self):
         """Licence about"""
         licfile = os.path.join(os.getenv("GISBASE"), "GPL.TXT")
@@ -258,20 +273,20 @@
         # put text into a scrolling panel
         licensewin = ScrolledPanel(self.aboutNotebook)
         licensewin.SetBackgroundColour('WHITE')
-        licensetxt = wx.StaticText(licensewin, id = wx.ID_ANY, label = license)
+        licensetxt = wx.StaticText(licensewin, id=wx.ID_ANY, label=license)
         licensewin.SetAutoLayout(True)
         licensewin.sizer = wx.BoxSizer(wx.VERTICAL)
-        licensewin.sizer.Add(item = licensetxt, proportion = 1,
-                flag = wx.EXPAND | wx.ALL, border = 3)
+        licensewin.sizer.Add(item=licensetxt, proportion=1,
+                             flag=wx.EXPAND | wx.ALL, border=3)
         licensewin.SetSizer(licensewin.sizer)
         licensewin.Layout()
         licensewin.SetupScrolling()
-        
+
         return licensewin
-    
+
     def _pageCredit(self):
         """Credit about"""
-                # credits
+        # credits
         authfile = os.path.join(os.getenv("GISBASE"), "AUTHORS")
         if os.path.exists(authfile):
             authorsFile = open(authfile, 'r')
@@ -281,25 +296,29 @@
             authors = _('%s file missing') % 'AUTHORS'
         authorwin = ScrolledPanel(self.aboutNotebook)
         authorwin.SetBackgroundColour('WHITE')
-        authortxt = wx.StaticText(authorwin, id = wx.ID_ANY, label = authors)
+        authortxt = wx.StaticText(authorwin, id=wx.ID_ANY, label=authors)
         authorwin.SetAutoLayout(True)
         authorwin.SetupScrolling()
         authorwin.sizer = wx.BoxSizer(wx.VERTICAL)
-        authorwin.sizer.Add(item = authortxt, proportion = 1,
-                flag = wx.EXPAND | wx.ALL, border = 3)
+        authorwin.sizer.Add(item=authortxt, proportion=1,
+                            flag=wx.EXPAND | wx.ALL, border=3)
         authorwin.SetSizer(authorwin.sizer)
-        authorwin.Layout()      
-        
+        authorwin.Layout()
+
         return authorwin
 
-    def _pageContributors(self, extra = False):
+    def _pageContributors(self, extra=False):
         """Contributors info"""
         if extra:
-            contribfile = os.path.join(os.getenv("GISBASE"), "contributors_extra.csv")
+            contribfile = os.path.join(
+                os.getenv("GISBASE"),
+                "contributors_extra.csv")
         else:
-            contribfile = os.path.join(os.getenv("GISBASE"), "contributors.csv")
+            contribfile = os.path.join(
+                os.getenv("GISBASE"),
+                "contributors.csv")
         if os.path.exists(contribfile):
-            contribFile = codecs.open(contribfile, encoding = 'utf-8', mode = 'r')
+            contribFile = codecs.open(contribfile, encoding='utf-8', mode='r')
             contribs = list()
             errLines = list()
             for line in contribFile.readlines()[1:]:
@@ -308,7 +327,8 @@
                     if extra:
                         name, email, country, rfc2_agreed = line.split(',')
                     else:
-                        cvs_id, name, email, country, osgeo_id, rfc2_agreed = line.split(',')
+                        cvs_id, name, email, country, osgeo_id, rfc2_agreed = line.split(
+                            ',')
                 except ValueError:
                     errLines.append(line)
                     continue
@@ -316,49 +336,61 @@
                     contribs.append((name, email, country))
                 else:
                     contribs.append((name, email, country, osgeo_id))
-            
+
             contribFile.close()
-            
+
             if errLines:
-                GError(parent = self,
-                       message = _("Error when reading file '%s'.") % contribfile + \
-                           "\n\n" + _("Lines:") + " %s" % \
-                           os.linesep.join(map(DecodeString, errLines)))
+                GError(parent=self, message=_("Error when reading file '%s'.") %
+                       contribfile + "\n\n" + _("Lines:") + " %s" %
+                       os.linesep.join(map(DecodeString, errLines)))
         else:
             contribs = None
-        
+
         contribwin = ScrolledPanel(self.aboutNotebook)
         contribwin.SetBackgroundColour('WHITE')
         contribwin.SetAutoLayout(True)
         contribwin.SetupScrolling()
         contribwin.sizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         if not contribs:
-            contribtxt = wx.StaticText(contribwin, id = wx.ID_ANY,
-                                       label = _('%s file missing') % contribfile)
-            contribwin.sizer.Add(item = contribtxt, proportion = 1,
-                                 flag = wx.EXPAND | wx.ALL, border = 3)
+            contribtxt = wx.StaticText(
+                contribwin,
+                id=wx.ID_ANY,
+                label=_('%s file missing') %
+                contribfile)
+            contribwin.sizer.Add(item=contribtxt, proportion=1,
+                                 flag=wx.EXPAND | wx.ALL, border=3)
         else:
             if extra:
                 items = (_('Name'), _('E-mail'), _('Country'))
             else:
                 items = (_('Name'), _('E-mail'), _('Country'), _('OSGeo_ID'))
-            contribBox = wx.FlexGridSizer(cols = len(items), vgap = 5, hgap = 5)
+            contribBox = wx.FlexGridSizer(cols=len(items), vgap=5, hgap=5)
             for item in items:
-                text = wx.StaticText(parent = contribwin, id = wx.ID_ANY,
-                                        label = item)
-                text.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
-                contribBox.Add(item = text)
-            for vals in sorted(contribs, key = lambda x: x[0]):
+                text = wx.StaticText(parent=contribwin, id=wx.ID_ANY,
+                                     label=item)
+                text.SetFont(
+                    wx.Font(
+                        10,
+                        wx.DEFAULT,
+                        wx.NORMAL,
+                        wx.BOLD,
+                        0,
+                        ""))
+                contribBox.Add(item=text)
+            for vals in sorted(contribs, key=lambda x: x[0]):
                 for item in vals:
-                    contribBox.Add(item = wx.StaticText(parent = contribwin, id = wx.ID_ANY,
-                                                        label = item))
-            contribwin.sizer.Add(item = contribBox, proportion = 1,
-                                 flag = wx.EXPAND | wx.ALL, border = 3)
-        
+                    contribBox.Add(
+                        item=wx.StaticText(
+                            parent=contribwin,
+                            id=wx.ID_ANY,
+                            label=item))
+            contribwin.sizer.Add(item=contribBox, proportion=1,
+                                 flag=wx.EXPAND | wx.ALL, border=3)
+
         contribwin.SetSizer(contribwin.sizer)
-        contribwin.Layout()      
-        
+        contribwin.Layout()
+
         return contribwin
 
     def _pageTranslators(self):
@@ -380,71 +412,88 @@
                         translators[language] = list()
                     translators[language].append((name, email))
             translatorsFile.close()
-            
+
             if errLines:
-                GError(parent = self,
-                       message = _("Error when reading file '%s'.") % translatorsfile + \
-                           "\n\n" + _("Lines:") + " %s" % \
-                           os.linesep.join(map(DecodeString, errLines)))
+                GError(parent=self, message=_("Error when reading file '%s'.") %
+                       translatorsfile + "\n\n" + _("Lines:") + " %s" %
+                       os.linesep.join(map(DecodeString, errLines)))
         else:
             translators = None
-        
+
         translatorswin = ScrolledPanel(self.aboutNotebook)
         translatorswin.SetBackgroundColour('WHITE')
         translatorswin.SetAutoLayout(True)
         translatorswin.SetupScrolling()
         translatorswin.sizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         if not translators:
-            translatorstxt = wx.StaticText(translatorswin, id = wx.ID_ANY,
-                                           label = _('%s file missing') % 'translators.csv')
-            translatorswin.sizer.Add(item = translatorstxt, proportion = 1,
-                                 flag = wx.EXPAND | wx.ALL, border = 3)
+            translatorstxt = wx.StaticText(
+                translatorswin,
+                id=wx.ID_ANY,
+                label=_('%s file missing') %
+                'translators.csv')
+            translatorswin.sizer.Add(item=translatorstxt, proportion=1,
+                                     flag=wx.EXPAND | wx.ALL, border=3)
         else:
-            translatorsBox = wx.FlexGridSizer(cols = 4, vgap = 5, hgap = 5)
-            languages = translators.keys()
-            languages.sort()
-            tname = wx.StaticText(parent = translatorswin, id = wx.ID_ANY,
-                                label = _('Name'))
+            translatorsBox = wx.FlexGridSizer(cols=4, vgap=5, hgap=5)
+            languages = sorted(translators.keys())
+            tname = wx.StaticText(parent=translatorswin, id=wx.ID_ANY,
+                                  label=_('Name'))
             tname.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
-            translatorsBox.Add(item = tname)
-            temail = wx.StaticText(parent = translatorswin, id = wx.ID_ANY,
-                                label = _('E-mail'))
+            translatorsBox.Add(item=tname)
+            temail = wx.StaticText(parent=translatorswin, id=wx.ID_ANY,
+                                   label=_('E-mail'))
             temail.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
-            translatorsBox.Add(item = temail)
-            tlang = wx.StaticText(parent = translatorswin, id = wx.ID_ANY,
-                                label = _('Language'))
+            translatorsBox.Add(item=temail)
+            tlang = wx.StaticText(parent=translatorswin, id=wx.ID_ANY,
+                                  label=_('Language'))
             tlang.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
-            translatorsBox.Add(item = tlang)
-            tnat = wx.StaticText(parent = translatorswin, id = wx.ID_ANY,
-                                label = _('Nation'))
+            translatorsBox.Add(item=tlang)
+            tnat = wx.StaticText(parent=translatorswin, id=wx.ID_ANY,
+                                 label=_('Nation'))
             tnat.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
-            translatorsBox.Add(item = tnat)           
+            translatorsBox.Add(item=tnat)
             for lang in languages:
                 for translator in translators[lang]:
                     name, email = translator
-                    translatorsBox.Add(item = wx.StaticText(parent = translatorswin, id = wx.ID_ANY,
-                                                            label =  unicode(name, "utf-8")))
-                    translatorsBox.Add(item = wx.StaticText(parent = translatorswin, id = wx.ID_ANY,
-                                                            label = email))
-                    translatorsBox.Add(item = wx.StaticText(parent = translatorswin, id = wx.ID_ANY,
-                                                            label = lang))                                                            
-                    flag = os.path.join(globalvar.ICONDIR, "flags", "%s.png" % lang.lower())
+                    translatorsBox.Add(
+                        item=wx.StaticText(
+                            parent=translatorswin,
+                            id=wx.ID_ANY,
+                            label=unicode(
+                                name,
+                                "utf-8")))
+                    translatorsBox.Add(
+                        item=wx.StaticText(
+                            parent=translatorswin,
+                            id=wx.ID_ANY,
+                            label=email))
+                    translatorsBox.Add(
+                        item=wx.StaticText(
+                            parent=translatorswin,
+                            id=wx.ID_ANY,
+                            label=lang))
+                    flag = os.path.join(
+                        globalvar.ICONDIR, "flags", "%s.png" %
+                        lang.lower())
                     if os.path.exists(flag):
-                        flagBitmap = wx.StaticBitmap(parent = translatorswin, id = wx.ID_ANY,
-                                     bitmap = wx.Bitmap(name = flag,
-                                                        type = wx.BITMAP_TYPE_PNG))
-                        translatorsBox.Add(item = flagBitmap)
+                        flagBitmap = wx.StaticBitmap(
+                            parent=translatorswin, id=wx.ID_ANY, bitmap=wx.Bitmap(
+                                name=flag, type=wx.BITMAP_TYPE_PNG))
+                        translatorsBox.Add(item=flagBitmap)
                     else:
-                        translatorsBox.Add(item = wx.StaticText(parent = translatorswin, 
-                                        id = wx.ID_ANY, label = lang))
-            
-            translatorswin.sizer.Add(item = translatorsBox, proportion = 1,
-                                 flag = wx.EXPAND | wx.ALL, border = 3)
-        
+                        translatorsBox.Add(
+                            item=wx.StaticText(
+                                parent=translatorswin,
+                                id=wx.ID_ANY,
+                                label=lang))
+
+            translatorswin.sizer.Add(item=translatorsBox, proportion=1,
+                                     flag=wx.EXPAND | wx.ALL, border=3)
+
         translatorswin.SetSizer(translatorswin.sizer)
-        translatorswin.Layout()      
-        
+        translatorswin.Layout()
+
         return translatorswin
 
     def _langString(self, k, v):
@@ -463,60 +512,61 @@
         except:
             pass
         return allStr
- 
+
     def _langBox(self, par, k, v):
         """Return box"""
-        langBox = wx.FlexGridSizer(cols = 4, vgap = 5, hgap = 5)
-        tkey = wx.StaticText(parent = par, id = wx.ID_ANY,
-                            label = k.upper())
-        langBox.Add(item = tkey)
+        langBox = wx.FlexGridSizer(cols=4, vgap=5, hgap=5)
+        tkey = wx.StaticText(parent=par, id=wx.ID_ANY,
+                             label=k.upper())
+        langBox.Add(item=tkey)
         try:
-            tgood = wx.StaticText(parent = par, id = wx.ID_ANY,
-                                label = _("%d translated" % v['good']))
+            tgood = wx.StaticText(parent=par, id=wx.ID_ANY,
+                                  label=_("%d translated" % v['good']))
             tgood.SetForegroundColour(wx.Colour(35, 142, 35))
-            langBox.Add(item = tgood)           
+            langBox.Add(item=tgood)
         except:
-            tgood = wx.StaticText(parent = par, id = wx.ID_ANY,
-                                label = "")
-            langBox.Add(item = tgood)
+            tgood = wx.StaticText(parent=par, id=wx.ID_ANY,
+                                  label="")
+            langBox.Add(item=tgood)
         try:
-            tfuzzy = wx.StaticText(parent = par, id = wx.ID_ANY,
-                                label = _("   %d fuzzy" % v['fuzzy']))
-            tfuzzy.SetForegroundColour(wx.Colour(255, 142, 0))                    
-            langBox.Add(item = tfuzzy)
+            tfuzzy = wx.StaticText(parent=par, id=wx.ID_ANY,
+                                   label=_("   %d fuzzy" % v['fuzzy']))
+            tfuzzy.SetForegroundColour(wx.Colour(255, 142, 0))
+            langBox.Add(item=tfuzzy)
         except:
-            tfuzzy = wx.StaticText(parent = par, id = wx.ID_ANY,
-                                label = "")
-            langBox.Add(item = tfuzzy)
+            tfuzzy = wx.StaticText(parent=par, id=wx.ID_ANY,
+                                   label="")
+            langBox.Add(item=tfuzzy)
         try:
-            tbad = wx.StaticText(parent = par, id = wx.ID_ANY,
-                                label = _("   %d untranslated" % v['bad']))
+            tbad = wx.StaticText(parent=par, id=wx.ID_ANY,
+                                 label=_("   %d untranslated" % v['bad']))
             tbad.SetForegroundColour(wx.Colour(255, 0, 0))
-            langBox.Add(item = tbad)
+            langBox.Add(item=tbad)
         except:
-            tbad = wx.StaticText(parent = par, id = wx.ID_ANY,
-                                label = "")
-            langBox.Add(item = tbad)                           
+            tbad = wx.StaticText(parent=par, id=wx.ID_ANY,
+                                 label="")
+            langBox.Add(item=tbad)
         return langBox
-        
+
     def _langPanel(self, lang, js):
         """Create panel for each languages"""
         text = self._langString(lang, js['total'])
-        panel = wx.CollapsiblePane(self.statswin, -1, label=text, style=wx.CP_DEFAULT_STYLE|wx.CP_NO_TLW_RESIZE)
+        panel = wx.CollapsiblePane(
+            self.statswin, -1, label=text, style=wx.CP_DEFAULT_STYLE | wx.CP_NO_TLW_RESIZE)
         panel.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnPaneChanged)
         win = panel.GetPane()
         # TODO IT DOESN'T WORK
         # TO ADD ONLY WHEN TAB IS OPENED
-        #if lang == self.langUsed.split('_')[0]:
-            #panel.Collapse(False)
-        #else:
-            #panel.Collapse(True)        
+        # if lang == self.langUsed.split('_')[0]:
+        # panel.Collapse(False)
+        # else:
+        # panel.Collapse(True)
         pageSizer = wx.BoxSizer(wx.VERTICAL)
-        for k,v in js.iteritems():
-            if k != 'total' and k!= 'name':
-                box = self._langBox(win, k,v)
-                pageSizer.Add(item = box, proportion = 1,
-                                 flag = wx.EXPAND | wx.ALL, border = 3)
+        for k, v in js.iteritems():
+            if k != 'total' and k != 'name':
+                box = self._langBox(win, k, v)
+                pageSizer.Add(item=box, proportion=1,
+                              flag=wx.EXPAND | wx.ALL, border=3)
 
         win.SetSizer(pageSizer)
         pageSizer.SetSizeHints(win)
@@ -526,7 +576,7 @@
     def OnPaneChanged(self, evt):
         """Redo the layout"""
         # TODO better to test on Windows
-        self.statswin.SetupScrolling(scrollToTop = False)
+        self.statswin.SetupScrolling(scrollToTop=False)
 
     def _pageStats(self):
         """Translation statistics info"""
@@ -545,30 +595,30 @@
         if not jsStats:
             Debug.msg(5, _("File <%s> not found") % fname)
             statsSizer = wx.BoxSizer(wx.VERTICAL)
-            statstext = wx.StaticText(self.statswin, id = wx.ID_ANY,
-                                           label = _('%s file missing') % fname)
-            statsSizer.Add(item = statstext, proportion = 1,
-                                 flag = wx.EXPAND | wx.ALL, border = 3)
+            statstext = wx.StaticText(self.statswin, id=wx.ID_ANY,
+                                      label=_('%s file missing') % fname)
+            statsSizer.Add(item=statstext, proportion=1,
+                           flag=wx.EXPAND | wx.ALL, border=3)
         else:
-            languages = jsStats['langs'].keys()
-            languages.sort()
-            
+            languages = sorted(jsStats['langs'].keys())
+
             statsSizer = wx.BoxSizer(wx.VERTICAL)
             for lang in languages:
                 v = jsStats['langs'][lang]
                 panel = self._langPanel(lang, v)
                 statsSizer.Add(panel)
-        
+
         self.statswin.SetSizer(statsSizer)
-        self.statswin.SetupScrolling(scroll_x = False, scroll_y = True)
+        self.statswin.SetupScrolling(scroll_x=False, scroll_y=True)
         self.statswin.Layout()
         self.statswin.Fit()
         return self.statswin
-    
+
     def OnCloseWindow(self, event):
         """Close window"""
         self.Close()
 
+
 class HelpFrame(wx.Dialog):
     """GRASS Quickstart help window
 
@@ -580,29 +630,33 @@
     Currently not used (was in location wizard before)
     due to unsolved problems - window sometimes does not respond.
     """
+
     def __init__(self, parent, id, title, size, file):
-        wx.Dialog.__init__(self, parent = parent, id = id, title = title,
-                           size = size, style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER | wx.MINIMIZE_BOX)
-        
+        wx.Dialog.__init__(
+            self, parent=parent, id=id, title=title, size=size,
+            style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER | wx.MINIMIZE_BOX)
+
         sizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         # text
-        content = HelpPanel(parent = self)
+        content = HelpPanel(parent=self)
         content.LoadPage(file)
-        
-        sizer.Add(item = content, proportion = 1, flag = wx.EXPAND)
-        
+
+        sizer.Add(item=content, proportion=1, flag=wx.EXPAND)
+
         self.SetAutoLayout(True)
         self.SetSizer(sizer)
         self.Layout()
 
+
 class HelpWindow(HtmlWindow):
     """This panel holds the text from GRASS docs.
-    
+
     GISBASE must be set in the environment to find the html docs dir.
     The SYNOPSIS section is skipped, since this Panel is supposed to
     be integrated into the cmdPanel and options are obvious there.
     """
+
     def __init__(self, parent, command, text, skipDescription,
                  **kwargs):
         """If command is given, the corresponding HTML help
@@ -619,31 +673,31 @@
         self.parent = parent
         if not globalvar.CheckWxVersion([2, 9]):
             wx.InitAllImageHandlers()
-        HtmlWindow.__init__(self, parent = parent, **kwargs)
-        
+        HtmlWindow.__init__(self, parent=parent, **kwargs)
+
         self.loaded = False
         self.history = list()
         self.historyIdx = 0
         self.fspath = os.path.join(os.getenv("GISBASE"), "docs", "html")
-        
-        self.SetStandardFonts (size = 10)
+
+        self.SetStandardFonts(size=10)
         self.SetBorders(10)
-        
+
         if text is None:
             if skipDescription:
                 url = os.path.join(self.fspath, command + ".html")
                 self.fillContentsFromFile(url,
-                                          skipDescription = skipDescription)
+                                          skipDescription=skipDescription)
                 self.history.append(url)
                 self.loaded = True
             else:
-                ### FIXME: calling LoadPage() is strangely time-consuming (only first call)
+                # FIXME: calling LoadPage() is strangely time-consuming (only first call)
                 # self.LoadPage(self.fspath + command + ".html")
                 self.loaded = False
         else:
             self.SetPage(text)
             self.loaded = True
-        
+
     def OnLinkClicked(self, linkinfo):
         url = linkinfo.GetHref()
         if url[:4] != 'http':
@@ -651,13 +705,13 @@
         self.history.append(url)
         self.historyIdx += 1
         self.parent.OnHistory()
-        
+
         super(HelpWindow, self).OnLinkClicked(linkinfo)
-        
-    def fillContentsFromFile(self, htmlFile, skipDescription = True):
+
+    def fillContentsFromFile(self, htmlFile, skipDescription=True):
         """Load content from file.
-        
-        Currently not used.        
+
+        Currently not used.
         """
         aLink = re.compile(r'(<a href="?)(.+\.html?["\s]*>)', re.IGNORECASE)
         imgLink = re.compile(r'(<img src="?)(.+\.[png|gif])', re.IGNORECASE)
@@ -674,82 +728,92 @@
                     else:
                         # FIXME: find only first item
                         findALink = aLink.search(l)
-                        if findALink is not None: 
-                            contents.append(aLink.sub(findALink.group(1)+
-                                                      self.fspath+findALink.group(2),l))
+                        if findALink is not None:
+                            contents.append(
+                                aLink.sub(
+                                    findALink.group(1) +
+                                    self.fspath +
+                                    findALink.group(2),
+                                    l))
                         findImgLink = imgLink.search(l)
-                        if findImgLink is not None: 
-                            contents.append(imgLink.sub(findImgLink.group(1)+
-                                                        self.fspath+findImgLink.group(2),l))
-                        
+                        if findImgLink is not None:
+                            contents.append(
+                                imgLink.sub(
+                                    findImgLink.group(1) +
+                                    self.fspath +
+                                    findImgLink.group(2),
+                                    l))
+
                         if findALink is None and findImgLink is None:
                             contents.append(l)
             self.SetPage("".join(contents))
             self.loaded = True
-        except: # The Manual file was not found
+        except:  # The Manual file was not found
             self.loaded = False
-        
+
+
 class HelpPanel(wx.Panel):
-    def __init__(self, parent, command = "index", text = None,
-                 skipDescription = False, **kwargs):
+
+    def __init__(self, parent, command="index", text=None,
+                 skipDescription=False, **kwargs):
         self.command = command
-        wx.Panel.__init__(self, parent = parent, id = wx.ID_ANY)
-        
+        wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)
+
         self.content = HelpWindow(self, command, text, skipDescription)
-        
-        self.btnNext = wx.Button(parent = self, id = wx.ID_ANY,
-                                 label = _("&Next"))
+
+        self.btnNext = wx.Button(parent=self, id=wx.ID_ANY,
+                                 label=_("&Next"))
         self.btnNext.Enable(False)
-        self.btnPrev = wx.Button(parent = self, id = wx.ID_ANY,
-                                 label = _("&Previous"))
+        self.btnPrev = wx.Button(parent=self, id=wx.ID_ANY,
+                                 label=_("&Previous"))
         self.btnPrev.Enable(False)
-        
+
         self.btnNext.Bind(wx.EVT_BUTTON, self.OnNext)
         self.btnPrev.Bind(wx.EVT_BUTTON, self.OnPrev)
-        
+
         self._layout()
 
     def _layout(self):
         """Do layout"""
         sizer = wx.BoxSizer(wx.VERTICAL)
         btnSizer = wx.BoxSizer(wx.HORIZONTAL)
-        
-        btnSizer.Add(item = self.btnPrev, proportion = 0,
-                     flag = wx.ALL, border = 5)
-        btnSizer.Add(item = wx.Size(1, 1), proportion = 1)
-        btnSizer.Add(item = self.btnNext, proportion = 0,
-                     flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
-        
-        sizer.Add(item = self.content, proportion = 1,
-                  flag = wx.EXPAND)
-        sizer.Add(item = btnSizer, proportion = 0,
-                  flag = wx.EXPAND)
-        
+
+        btnSizer.Add(item=self.btnPrev, proportion=0,
+                     flag=wx.ALL, border=5)
+        btnSizer.Add(item=wx.Size(1, 1), proportion=1)
+        btnSizer.Add(item=self.btnNext, proportion=0,
+                     flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
+
+        sizer.Add(item=self.content, proportion=1,
+                  flag=wx.EXPAND)
+        sizer.Add(item=btnSizer, proportion=0,
+                  flag=wx.EXPAND)
+
         self.SetSizer(sizer)
         sizer.Fit(self)
 
-    def LoadPage(self, path = None):
+    def LoadPage(self, path=None):
         """Load page"""
         if not path:
             path = self.GetFile()
         self.content.history.append(path)
         self.content.LoadPage(path)
-        
+
     def GetFile(self):
         """Get HTML file"""
         fMan = os.path.join(self.content.fspath, self.command + ".html")
         if os.path.isfile(fMan):
             return fMan
-        
+
         # check also addons
         faMan = os.path.join(os.getenv('GRASS_ADDON_BASE'), "docs", "html",
                              self.command + ".html")
         if os.getenv('GRASS_ADDON_BASE') and \
                 os.path.isfile(faMan):
             return faMan
-        
+
         return None
-    
+
     def IsLoaded(self):
         return self.content.loaded
 
@@ -773,9 +837,9 @@
         path = self.content.history[idx]
         self.content.LoadPage(path)
         self.OnHistory()
-        
+
         event.Skip()
-        
+
     def OnPrev(self, event):
         """Load previous page"""
         self.content.historyIdx -= 1
@@ -783,9 +847,10 @@
         path = self.content.history[idx]
         self.content.LoadPage(path)
         self.OnHistory()
-        
+
         event.Skip()
 
+
 def ShowAboutDialog(prgName, startYear):
     """Displays About window.
 
@@ -793,23 +858,35 @@
     :param startYear: the first year of existence of the program
     """
     info = wx.AboutDialogInfo()
-    
-    info.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
+
+    info.SetIcon(
+        wx.Icon(
+            os.path.join(
+                globalvar.ICONDIR,
+                'grass.ico'),
+            wx.BITMAP_TYPE_ICO))
     info.SetName(prgName)
     info.SetWebSite('http://grass.osgeo.org')
-    info.SetDescription(_grassDevTeam(startYear) + '\n\n' +
-                        '\n'.join(textwrap.wrap('This program is free software under the GNU General Public License'
-                                                '(>=v2). Read the file COPYING that comes with GRASS for details.', 75)))
-    
+    info.SetDescription(
+        _grassDevTeam(startYear) +
+        '\n\n' +
+        '\n'.join(
+            textwrap.wrap(
+                'This program is free software under the GNU General Public License'
+                '(>=v2). Read the file COPYING that comes with GRASS for details.',
+                75)))
+
     wx.AboutBox(info)
 
+
 def _grassDevTeam(start):
     try:
         end = grass.version()['date']
     except KeyError:
         sys.stderr.write(_("Unable to get GRASS version\n"))
-        
+
         from datetime import date
         end = date.today().year
-    
-    return '%(c)s %(start)s-%(end)s by the GRASS Development Team' % {'c': unichr(169), 'start': start, 'end': end}
+
+    return '%(c)s %(start)s-%(end)s by the GRASS Development Team' % {
+        'c': unichr(169), 'start': start, 'end': end}

Modified: grass/trunk/gui/wxpython/gui_core/goutput.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/goutput.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gui_core/goutput.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -23,16 +23,16 @@
 import textwrap
 
 import wx
-from   wx import stc
+from wx import stc
 
 from grass.pydispatch.signal import Signal
 
-from core.gcmd       import GError, EncodeString
+from core.gcmd import GError, EncodeString
 from core.gconsole   import GConsole, \
     EVT_CMD_OUTPUT, EVT_CMD_PROGRESS, EVT_CMD_RUN, EVT_CMD_DONE, \
     Notification
 from gui_core.prompt import GPromptSTC
-from core.settings   import UserSettings
+from core.settings import UserSettings
 from core.utils import _
 from gui_core.widgets import SearchModuleWidget
 
@@ -45,9 +45,10 @@
 class GConsoleWindow(wx.SplitterWindow):
     """Create and manage output console for commands run by GUI.
     """
-    def __init__(self, parent, gconsole, menuModel = None, margin = False,
-                 style = wx.TAB_TRAVERSAL | wx.FULL_REPAINT_ON_RESIZE,
-                 gcstyle = GC_EMPTY,
+
+    def __init__(self, parent, gconsole, menuModel=None, margin=False,
+                 style=wx.TAB_TRAVERSAL | wx.FULL_REPAINT_ON_RESIZE,
+                 gcstyle=GC_EMPTY,
                  **kwargs):
         """
         :param parent: gui parent
@@ -59,19 +60,23 @@
                         (GC_EMPTY, GC_PROMPT to show command prompt,
                         GC_SEARCH to show search widget)
         """
-        wx.SplitterWindow.__init__(self, parent, id = wx.ID_ANY, style = style, **kwargs)
+        wx.SplitterWindow.__init__(
+            self, parent, id=wx.ID_ANY, style=style, **kwargs)
         self.SetName("GConsole")
-        
+
         self.panelOutput = wx.Panel(parent=self, id=wx.ID_ANY)
-        self.panelProgress = wx.Panel(parent=self.panelOutput, id=wx.ID_ANY, name='progressPanel')
+        self.panelProgress = wx.Panel(
+            parent=self.panelOutput,
+            id=wx.ID_ANY,
+            name='progressPanel')
         self.panelPrompt = wx.Panel(parent=self, id=wx.ID_ANY)
         # initialize variables
-        self.parent = parent # GMFrame | CmdPanel | ?
+        self.parent = parent  # GMFrame | CmdPanel | ?
         self._gconsole = gconsole
         self._menuModel = menuModel
 
         self._gcstyle = gcstyle
-        self.lineWidth       = 80
+        self.lineWidth = 80
 
         # signal which requests showing of a notification
         self.showNotification = Signal("GConsoleWindow.showNotification")
@@ -81,9 +86,9 @@
         self.contentChanged = Signal("GConsoleWindow.contentChanged")
 
         # progress bar
-        self.progressbar = wx.Gauge(parent = self.panelProgress, id = wx.ID_ANY,
-                                    range = 100, pos = (110, 50), size = (-1, 25),
-                                    style = wx.GA_HORIZONTAL)
+        self.progressbar = wx.Gauge(parent=self.panelProgress, id=wx.ID_ANY,
+                                    range=100, pos=(110, 50), size=(-1, 25),
+                                    style=wx.GA_HORIZONTAL)
         self._gconsole.Bind(EVT_CMD_PROGRESS, self.OnCmdProgress)
         self._gconsole.Bind(EVT_CMD_OUTPUT, self.OnCmdOutput)
         self._gconsole.Bind(EVT_CMD_RUN, self.OnCmdRun)
@@ -95,8 +100,11 @@
         self._gconsole.writeError.connect(self.WriteError)
 
         # text control for command output
-        self.cmdOutput = GStc(parent = self.panelOutput, id = wx.ID_ANY, margin = margin,
-                               wrap = None)
+        self.cmdOutput = GStc(
+            parent=self.panelOutput,
+            id=wx.ID_ANY,
+            margin=margin,
+            wrap=None)
 
         # search & command prompt
         # move to the if below
@@ -109,58 +117,68 @@
         if not self._gcstyle & GC_PROMPT:
             self.cmdPrompt.Hide()
 
-
         if self._gcstyle & GC_SEARCH:
-            self.infoCollapseLabelExp = _("Click here to show search module engine")
-            self.infoCollapseLabelCol = _("Click here to hide search module engine")
-            self.searchPane = wx.CollapsiblePane(parent = self.panelOutput,
-                                                 label = self.infoCollapseLabelExp,
-                                                 style = wx.CP_DEFAULT_STYLE |
-                                                 wx.CP_NO_TLW_RESIZE | wx.EXPAND)
-            self.MakeSearchPaneContent(self.searchPane.GetPane(), self._menuModel)
+            self.infoCollapseLabelExp = _(
+                "Click here to show search module engine")
+            self.infoCollapseLabelCol = _(
+                "Click here to hide search module engine")
+            self.searchPane = wx.CollapsiblePane(
+                parent=self.panelOutput, label=self.infoCollapseLabelExp,
+                style=wx.CP_DEFAULT_STYLE | wx.CP_NO_TLW_RESIZE | wx.EXPAND)
+            self.MakeSearchPaneContent(
+                self.searchPane.GetPane(), self._menuModel)
             self.searchPane.Collapse(True)
-            self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnSearchPaneChanged, self.searchPane) 
-            self.search.moduleSelected.connect(lambda name:
-                                               self.cmdPrompt.SetTextAndFocus(name + ' '))
+            self.Bind(
+                wx.EVT_COLLAPSIBLEPANE_CHANGED,
+                self.OnSearchPaneChanged,
+                self.searchPane)
+            self.search.moduleSelected.connect(
+                lambda name: self.cmdPrompt.SetTextAndFocus(name + ' '))
         else:
             self.search = None
 
-
         if self._gcstyle & GC_PROMPT:
             cmdLabel = _("Command prompt")
-            self.outputBox = wx.StaticBox(parent = self.panelOutput, id = wx.ID_ANY,
-                                          label = " %s " % _("Output window"))
+            self.outputBox = wx.StaticBox(
+                parent=self.panelOutput,
+                id=wx.ID_ANY,
+                label=" %s " %
+                _("Output window"))
 
-            self.cmdBox = wx.StaticBox(parent = self.panelOutput, id = wx.ID_ANY,
-                                       label = " %s " % cmdLabel)
+            self.cmdBox = wx.StaticBox(parent=self.panelOutput, id=wx.ID_ANY,
+                                       label=" %s " % cmdLabel)
 
         # buttons
-        self.btnOutputClear = wx.Button(parent = self.panelOutput, id = wx.ID_CLEAR)
+        self.btnOutputClear = wx.Button(
+            parent=self.panelOutput, id=wx.ID_CLEAR)
         self.btnOutputClear.SetToolTipString(_("Clear output window content"))
-        self.btnCmdClear = wx.Button(parent = self.panelOutput, id = wx.ID_CLEAR)
+        self.btnCmdClear = wx.Button(parent=self.panelOutput, id=wx.ID_CLEAR)
         self.btnCmdClear.SetToolTipString(_("Clear command prompt content"))
-        self.btnOutputSave  = wx.Button(parent = self.panelOutput, id = wx.ID_SAVE)
-        self.btnOutputSave.SetToolTipString(_("Save output window content to the file"))
-        self.btnCmdAbort = wx.Button(parent = self.panelProgress, id = wx.ID_STOP)
+        self.btnOutputSave = wx.Button(parent=self.panelOutput, id=wx.ID_SAVE)
+        self.btnOutputSave.SetToolTipString(
+            _("Save output window content to the file"))
+        self.btnCmdAbort = wx.Button(parent=self.panelProgress, id=wx.ID_STOP)
         self.btnCmdAbort.SetToolTipString(_("Abort running command"))
-        self.btnCmdProtocol = wx.ToggleButton(parent = self.panelOutput, id = wx.ID_ANY,
-                                              label = _("&Log file"),
-                                              size = self.btnCmdClear.GetSize())
+        self.btnCmdProtocol = wx.ToggleButton(
+            parent=self.panelOutput,
+            id=wx.ID_ANY,
+            label=_("&Log file"),
+            size=self.btnCmdClear.GetSize())
         self.btnCmdProtocol.SetToolTipString(_("Toggle to save list of executed commands into "
                                                "a file; content saved when switching off."))
-        
+
         if not self._gcstyle & GC_PROMPT:
             self.btnCmdClear.Hide()
             self.btnCmdProtocol.Hide()
-        
-        self.btnCmdClear.Bind(wx.EVT_BUTTON,     self.cmdPrompt.OnCmdErase)
-        self.btnOutputClear.Bind(wx.EVT_BUTTON,  self.OnOutputClear)
-        self.btnOutputSave.Bind(wx.EVT_BUTTON,   self.OnOutputSave)
-        self.btnCmdAbort.Bind(wx.EVT_BUTTON,     self._gconsole.OnCmdAbort)
+
+        self.btnCmdClear.Bind(wx.EVT_BUTTON, self.cmdPrompt.OnCmdErase)
+        self.btnOutputClear.Bind(wx.EVT_BUTTON, self.OnOutputClear)
+        self.btnOutputSave.Bind(wx.EVT_BUTTON, self.OnOutputSave)
+        self.btnCmdAbort.Bind(wx.EVT_BUTTON, self._gconsole.OnCmdAbort)
         self.btnCmdProtocol.Bind(wx.EVT_TOGGLEBUTTON, self.OnCmdProtocol)
-        
+
         self._layout()
-        
+
     def _layout(self):
         """Do layout"""
         self.outputSizer = wx.BoxSizer(wx.VERTICAL)
@@ -172,56 +190,73 @@
         else:
             outBtnSizer = wx.BoxSizer(wx.HORIZONTAL)
             cmdBtnSizer = wx.BoxSizer(wx.HORIZONTAL)
-            
-        
+
         if self._gcstyle & GC_PROMPT:
             promptSizer = wx.BoxSizer(wx.VERTICAL)
-            promptSizer.Add(item = self.cmdPrompt, proportion = 1,
-                        flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border = 3)
-            helpText = wx.StaticText(self.panelPrompt, id = wx.ID_ANY,
-                                 label = "Press Tab to display command help, Ctrl+Space to autocomplete")
-            helpText.SetForegroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_GRAYTEXT))
-            promptSizer.Add(item = helpText,
-                            proportion = 0, flag = wx.EXPAND | wx.LEFT, border = 5)
-        
+            promptSizer.Add(
+                item=self.cmdPrompt,
+                proportion=1,
+                flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP,
+                border=3)
+            helpText = wx.StaticText(
+                self.panelPrompt, id=wx.ID_ANY,
+                label="Press Tab to display command help, Ctrl+Space to autocomplete")
+            helpText.SetForegroundColour(
+                wx.SystemSettings_GetColour(
+                    wx.SYS_COLOUR_GRAYTEXT))
+            promptSizer.Add(item=helpText,
+                            proportion=0, flag=wx.EXPAND | wx.LEFT, border=5)
+
         if self._gcstyle & GC_SEARCH:
-            self.outputSizer.Add(item = self.searchPane, proportion = 0,
-                            flag = wx.EXPAND | wx.ALL, border = 3)
-        self.outputSizer.Add(item = self.cmdOutput, proportion = 1,
-                        flag = wx.EXPAND | wx.ALL, border = 3)
+            self.outputSizer.Add(item=self.searchPane, proportion=0,
+                                 flag=wx.EXPAND | wx.ALL, border=3)
+        self.outputSizer.Add(item=self.cmdOutput, proportion=1,
+                             flag=wx.EXPAND | wx.ALL, border=3)
         if self._gcstyle & GC_PROMPT:
             proportion = 1
         else:
             proportion = 0
             outBtnSizer.AddStretchSpacer()
 
-        outBtnSizer.Add(item = self.btnOutputClear, proportion = proportion,
-                        flag = wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
+        outBtnSizer.Add(
+            item=self.btnOutputClear,
+            proportion=proportion,
+            flag=wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+            border=5)
 
-        outBtnSizer.Add(item = self.btnOutputSave, proportion = proportion,
-                        flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.BOTTOM, border = 5)
+        outBtnSizer.Add(item=self.btnOutputSave, proportion=proportion,
+                        flag=wx.ALIGN_RIGHT | wx.RIGHT | wx.BOTTOM, border=5)
 
-        cmdBtnSizer.Add(item = self.btnCmdProtocol, proportion = 1,
-                        flag = wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
-        cmdBtnSizer.Add(item = self.btnCmdClear, proportion = 1,
-                        flag = wx.ALIGN_CENTER | wx.RIGHT | wx.BOTTOM, border = 5)
-        progressSizer.Add(item = self.btnCmdAbort, proportion = 0,
-                          flag = wx.ALL|wx.ALIGN_CENTER, border = 5)
-        progressSizer.Add(item = self.progressbar, proportion = 1,
-                          flag = wx.ALIGN_CENTER | wx.RIGHT | wx.TOP | wx.BOTTOM, border = 5)
-                          
+        cmdBtnSizer.Add(
+            item=self.btnCmdProtocol,
+            proportion=1,
+            flag=wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+            border=5)
+        cmdBtnSizer.Add(item=self.btnCmdClear, proportion=1,
+                        flag=wx.ALIGN_CENTER | wx.RIGHT | wx.BOTTOM, border=5)
+        progressSizer.Add(item=self.btnCmdAbort, proportion=0,
+                          flag=wx.ALL | wx.ALIGN_CENTER, border=5)
+        progressSizer.Add(
+            item=self.progressbar,
+            proportion=1,
+            flag=wx.ALIGN_CENTER | wx.RIGHT | wx.TOP | wx.BOTTOM,
+            border=5)
+
         self.panelProgress.SetSizer(progressSizer)
         progressSizer.Fit(self.panelProgress)
-        
-        btnSizer.Add(item = outBtnSizer, proportion = 1,
-                     flag = wx.ALL | wx.ALIGN_CENTER, border = 5)
-        btnSizer.Add(item = cmdBtnSizer, proportion = 1,
-                     flag = wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM | wx.RIGHT, border = 5)
-        self.outputSizer.Add(item = self.panelProgress, proportion = 0,
-                        flag = wx.EXPAND)
-        self.outputSizer.Add(item = btnSizer, proportion = 0,
-                        flag = wx.EXPAND)
-        
+
+        btnSizer.Add(item=outBtnSizer, proportion=1,
+                     flag=wx.ALL | wx.ALIGN_CENTER, border=5)
+        btnSizer.Add(
+            item=cmdBtnSizer,
+            proportion=1,
+            flag=wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM | wx.RIGHT,
+            border=5)
+        self.outputSizer.Add(item=self.panelProgress, proportion=0,
+                             flag=wx.EXPAND)
+        self.outputSizer.Add(item=btnSizer, proportion=0,
+                             flag=wx.EXPAND)
+
         self.outputSizer.Fit(self)
         self.outputSizer.SetSizeHints(self)
         self.panelOutput.SetSizer(self.outputSizer)
@@ -229,12 +264,12 @@
         # avoid to use a deprecated method in wxPython >= 2.9
         getattr(self.outputSizer, 'FitInside',
                 self.outputSizer.SetVirtualSizeHints)(self.panelOutput)
-        
+
         if self._gcstyle & GC_PROMPT:
             promptSizer.Fit(self)
             promptSizer.SetSizeHints(self)
             self.panelPrompt.SetSizer(promptSizer)
-        
+
         # split window
         if self._gcstyle & GC_PROMPT:
             self.SplitHorizontally(self.panelOutput, self.panelPrompt, -50)
@@ -242,9 +277,9 @@
             self.SplitHorizontally(self.panelOutput, self.panelPrompt, -45)
             self.Unsplit()
         self.SetMinimumPaneSize(self.btnCmdClear.GetSize()[1] + 25)
-        
+
         self.SetSashGravity(1.0)
-        
+
         self.outputSizer.Hide(self.panelProgress)
         # layout
         self.SetAutoLayout(True)
@@ -253,29 +288,29 @@
     def MakeSearchPaneContent(self, pane, model):
         """Create search pane"""
         border = wx.BoxSizer(wx.VERTICAL)
-        
-        self.search = SearchModuleWidget(parent = pane,
-                                         model = model)
 
+        self.search = SearchModuleWidget(parent=pane,
+                                         model=model)
+
         self.search.showNotification.connect(self.showNotification)
 
-        border.Add(item = self.search, proportion = 0,
-                   flag = wx.EXPAND | wx.ALL, border = 1)
-        
+        border.Add(item=self.search, proportion=0,
+                   flag=wx.EXPAND | wx.ALL, border=1)
+
         pane.SetSizer(border)
         border.Fit(pane)
-        
+
     def OnSearchPaneChanged(self, event):
         """Collapse search module box"""
         if self.searchPane.IsExpanded():
             self.searchPane.SetLabel(self.infoCollapseLabelCol)
         else:
             self.searchPane.SetLabel(self.infoCollapseLabelExp)
-        
+
         self.panelOutput.Layout()
         self.panelOutput.SendSizeEvent()
-        
-    def GetPanel(self, prompt = True):
+
+    def GetPanel(self, prompt=True):
         """Get panel
 
         :param prompt: get prompt / output panel
@@ -289,8 +324,8 @@
 
     def WriteLog(self, text, style=None, wrap=None,
                  notification=Notification.HIGHLIGHT):
-        """Generic method for writing log message in 
-        given style. 
+        """Generic method for writing log message in
+        given style.
 
         Emits contentChanged signal.
 
@@ -308,47 +343,53 @@
 
         if not style:
             style = self.cmdOutput.StyleDefault
-        
+
         # p1 = self.cmdOutput.GetCurrentPos()
         p1 = self.cmdOutput.GetEndStyled()
         # self.cmdOutput.GotoPos(p1)
         self.cmdOutput.DocumentEnd()
-        
+
         for line in text.splitlines():
             # fill space
             if len(line) < self.lineWidth:
-                diff = self.lineWidth - len(line) 
+                diff = self.lineWidth - len(line)
                 line += diff * ' '
-            
-            self.cmdOutput.AddTextWrapped(line, wrap = wrap) # adds '\n'
-            
+
+            self.cmdOutput.AddTextWrapped(line, wrap=wrap)  # adds '\n'
+
             p2 = self.cmdOutput.GetCurrentPos()
-            
+
             self.cmdOutput.StartStyling(p1, 0xff)
             self.cmdOutput.SetStyling(p2 - p1, style)
-        
+
         self.cmdOutput.EnsureCaretVisible()
 
         self.contentChanged.emit(notification=notification)
-        
-    def WriteCmdLog(self, text, pid=None, notification=Notification.MAKE_VISIBLE):
+
+    def WriteCmdLog(self, text, pid=None,
+                    notification=Notification.MAKE_VISIBLE):
         """Write message in selected style
-        
+
         :param text: message to be printed
         :param pid: process pid or None
         :param switchPage: True to switch page
         """
         if pid:
             text = '(' + str(pid) + ') ' + text
-        self.WriteLog(text, style=self.cmdOutput.StyleCommand, notification=notification)
+        self.WriteLog(
+            text,
+            style=self.cmdOutput.StyleCommand,
+            notification=notification)
 
     def WriteWarning(self, text):
         """Write message in warning style"""
-        self.WriteLog(text, style=self.cmdOutput.StyleWarning, notification=Notification.MAKE_VISIBLE)
+        self.WriteLog(text, style=self.cmdOutput.StyleWarning,
+                      notification=Notification.MAKE_VISIBLE)
 
     def WriteError(self, text):
         """Write message in error style"""
-        self.WriteLog(text, style=self.cmdOutput.StyleError, notification=Notification.MAKE_VISIBLE)
+        self.WriteLog(text, style=self.cmdOutput.StyleError,
+                      notification=Notification.MAKE_VISIBLE)
 
     def OnOutputClear(self, event):
         """Clear content of output window"""
@@ -366,43 +407,52 @@
         text = self.cmdOutput.GetSelectedText()
         if not text:
             text = self.cmdOutput.GetText()
-        
+
         # add newline if needed
         if len(text) > 0 and text[-1] != '\n':
             text += '\n'
-        
-        dlg = wx.FileDialog(self, message = _("Save file as..."),
-                            defaultFile = "grass_cmd_output.txt",
-                            wildcard = _("%(txt)s (*.txt)|*.txt|%(files)s (*)|*") % 
-                            {'txt': _("Text files"), 'files': _("Files")},
-                            style = wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
-        
+
+        dlg = wx.FileDialog(
+            self, message=_("Save file as..."),
+            defaultFile="grass_cmd_output.txt",
+            wildcard=_("%(txt)s (*.txt)|*.txt|%(files)s (*)|*") %
+            {'txt': _("Text files"),
+             'files': _("Files")},
+            style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
+
         # Show the dialog and retrieve the user response. If it is the OK response,
         # process the data.
         if dlg.ShowModal() == wx.ID_OK:
             path = dlg.GetPath()
-            
+
             try:
                 output = open(path, "w")
                 output.write(EncodeString(text))
             except IOError as e:
-                GError(_("Unable to write file '%(path)s'.\n\nDetails: %(error)s") % {'path': path, 'error': e})
+                GError(
+                    _("Unable to write file '%(path)s'.\n\nDetails: %(error)s") % {
+                        'path': path,
+                        'error': e})
             finally:
                 output.close()
             message = _("Command output saved into '%s'") % path
-            self.showNotification.emit(message = message)
-        
+            self.showNotification.emit(message=message)
+
         dlg.Destroy()
 
     def SetCopyingOfSelectedText(self, copy):
         """Enable or disable copying of selected text in to clipboard.
         Effects prompt and output.
-        
+
         :param bool copy: True for enable, False for disable
         """
         if copy:
-            self.cmdPrompt.Bind(stc.EVT_STC_PAINTED, self.cmdPrompt.OnTextSelectionChanged)
-            self.cmdOutput.Bind(stc.EVT_STC_PAINTED, self.cmdOutput.OnTextSelectionChanged)
+            self.cmdPrompt.Bind(
+                stc.EVT_STC_PAINTED,
+                self.cmdPrompt.OnTextSelectionChanged)
+            self.cmdOutput.Bind(
+                stc.EVT_STC_PAINTED,
+                self.cmdOutput.OnTextSelectionChanged)
         else:
             self.cmdPrompt.Unbind(stc.EVT_STC_PAINTED)
             self.cmdOutput.Unbind(stc.EVT_STC_PAINTED)
@@ -413,7 +463,7 @@
         Emits contentChanged signal.
         """
         message = event.text
-        type  = event.type
+        type = event.type
 
         self.cmdOutput.AddStyledMessage(message, type)
 
@@ -430,8 +480,8 @@
     def CmdProtocolSave(self):
         """Save list of manually entered commands into a text log file"""
         if not hasattr(self, 'cmdFileProtocol'):
-            return # it should not happen
-        
+            return  # it should not happen
+
         try:
             output = open(self.cmdFileProtocol, "a")
             cmds = self.cmdPrompt.GetCommands()
@@ -439,16 +489,16 @@
             if len(cmds) > 0:
                 output.write('\n')
         except IOError as e:
-            GError(_("Unable to write file '%(filePath)s'.\n\nDetails: %(error)s") % 
-                    {'filePath': self.cmdFileProtocol, 'error': e})
+            GError(_("Unable to write file '%(filePath)s'.\n\nDetails: %(error)s") %
+                   {'filePath': self.cmdFileProtocol, 'error': e})
         finally:
             output.close()
-        
+
         message = _("Command log saved to '%s'") % self.cmdFileProtocol
-        self.showNotification.emit(message = message)
+        self.showNotification.emit(message=message)
         del self.cmdFileProtocol
-        
-    def OnCmdProtocol(self, event = None):
+
+    def OnCmdProtocol(self, event=None):
         """Save commands into file"""
         if not event.IsChecked():
             # stop capturing commands, save list of commands to the
@@ -458,18 +508,20 @@
             # start capturing commands
             self.cmdPrompt.ClearCommands()
             # ask for the file
-            dlg = wx.FileDialog(self, message = _("Save file as..."),
-                                defaultFile = "grass_cmd_log.txt",
-                                wildcard = _("%(txt)s (*.txt)|*.txt|%(files)s (*)|*") % 
-                                            {'txt': _("Text files"), 'files': _("Files")},
-                                style = wx.FD_SAVE)
+            dlg = wx.FileDialog(
+                self, message=_("Save file as..."),
+                defaultFile="grass_cmd_log.txt",
+                wildcard=_("%(txt)s (*.txt)|*.txt|%(files)s (*)|*") %
+                {'txt': _("Text files"),
+                 'files': _("Files")},
+                style=wx.FD_SAVE)
             if dlg.ShowModal() == wx.ID_OK:
                 self.cmdFileProtocol = dlg.GetPath()
             else:
                 wx.CallAfter(self.btnCmdProtocol.SetValue, False)
-            
+
             dlg.Destroy()
-            
+
         event.Skip()
 
     def OnCmdRun(self, event):
@@ -481,7 +533,7 @@
     def OnCmdDone(self, event):
         """Command done (or aborted)
         """
-        self.progressbar.SetValue(0) # reset progress bar on '0%'
+        self.progressbar.SetValue(0)  # reset progress bar on '0%'
         wx.CallLater(100, self._hideProgress)
         event.Skip()
 
@@ -492,7 +544,7 @@
     def ResetFocus(self):
         """Reset focus"""
         self.cmdPrompt.SetFocus()
-        
+
     def GetPrompt(self):
         """Get prompt"""
         return self.cmdPrompt
@@ -508,21 +560,22 @@
     Author:    Jean-Michel Fauth, Switzerland
     Copyright: (c) 2005-2007 Jean-Michel Fauth
     Licence:   GPL
-    """  
-    def __init__(self, parent, id, margin = False, wrap = None):
+    """
+
+    def __init__(self, parent, id, margin=False, wrap=None):
         stc.StyledTextCtrl.__init__(self, parent, id)
         self.parent = parent
         self.SetUndoCollection(True)
         self.SetReadOnly(True)
 
         # remember position of line begining (used for '\r')
-        self.linePos         = -1
+        self.linePos = -1
 
         #
         # styles
-        #                
+        #
         self.SetStyle()
-        
+
         #
         # line margins
         #
@@ -549,64 +602,80 @@
         # bindings
         #
         self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
-        
+
     def OnTextSelectionChanged(self, event):
         """Copy selected text to clipboard and skip event.
         The same function is in TextCtrlAutoComplete class (prompt.py).
         """
         wx.CallAfter(self.Copy)
         event.Skip()
-        
+
     def SetStyle(self):
-        """Set styles for styled text output windows with type face 
+        """Set styles for styled text output windows with type face
         and point size selected by user (Courier New 10 is default)"""
-        
-        typeface = UserSettings.Get(group = 'appearance', key = 'outputfont', subkey = 'type')   
+
+        typeface = UserSettings.Get(
+            group='appearance',
+            key='outputfont',
+            subkey='type')
         if typeface == "":
             typeface = "Courier New"
-        
-        typesize = UserSettings.Get(group = 'appearance', key = 'outputfont', subkey = 'size')
-        if typesize == None or typesize <= 0:
+
+        typesize = UserSettings.Get(
+            group='appearance',
+            key='outputfont',
+            subkey='size')
+        if typesize is None or typesize <= 0:
             typesize = 10
         typesize = float(typesize)
-        
-        self.StyleDefault     = 0
-        self.StyleDefaultSpec = "face:%s,size:%d,fore:#000000,back:#FFFFFF" % (typeface, typesize)
-        self.StyleCommand     = 1
-        self.StyleCommandSpec = "face:%s,size:%d,,fore:#000000,back:#bcbcbc" % (typeface, typesize)
-        self.StyleOutput      = 2
-        self.StyleOutputSpec  = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
+
+        self.StyleDefault = 0
+        self.StyleDefaultSpec = "face:%s,size:%d,fore:#000000,back:#FFFFFF" % (
+            typeface,
+            typesize)
+        self.StyleCommand = 1
+        self.StyleCommandSpec = "face:%s,size:%d,,fore:#000000,back:#bcbcbc" % (
+            typeface, typesize)
+        self.StyleOutput = 2
+        self.StyleOutputSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (
+            typeface,
+            typesize)
         # fatal error
-        self.StyleError       = 3
-        self.StyleErrorSpec   = "face:%s,size:%d,,fore:#7F0000,back:#FFFFFF" % (typeface, typesize)
+        self.StyleError = 3
+        self.StyleErrorSpec = "face:%s,size:%d,,fore:#7F0000,back:#FFFFFF" % (
+            typeface,
+            typesize)
         # warning
-        self.StyleWarning     = 4
-        self.StyleWarningSpec = "face:%s,size:%d,,fore:#0000FF,back:#FFFFFF" % (typeface, typesize)
+        self.StyleWarning = 4
+        self.StyleWarningSpec = "face:%s,size:%d,,fore:#0000FF,back:#FFFFFF" % (
+            typeface, typesize)
         # message
-        self.StyleMessage     = 5
-        self.StyleMessageSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
+        self.StyleMessage = 5
+        self.StyleMessageSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (
+            typeface, typesize)
         # unknown
-        self.StyleUnknown     = 6
-        self.StyleUnknownSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
-        
+        self.StyleUnknown = 6
+        self.StyleUnknownSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (
+            typeface, typesize)
+
         # default and clear => init
         self.StyleSetSpec(stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
         self.StyleClearAll()
         self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
-        self.StyleSetSpec(self.StyleOutput,  self.StyleOutputSpec)
-        self.StyleSetSpec(self.StyleError,   self.StyleErrorSpec)
+        self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
+        self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
         self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
         self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
-        self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)        
+        self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
 
     def OnDestroy(self, evt):
         """The clipboard contents can be preserved after
         the app has exited"""
-        
+
         wx.TheClipboard.Flush()
         evt.Skip()
 
-    def AddTextWrapped(self, txt, wrap = None):
+    def AddTextWrapped(self, txt, wrap=None):
         """Add string to text area.
 
         String is wrapped and linesep is also added to the end
@@ -631,24 +700,27 @@
                     self.AddText(seg)
         else:
             self.linePos = self.GetCurrentPos()
-            
+
             try:
                 self.AddText(txt)
             except UnicodeDecodeError:
-                enc = UserSettings.Get(group = 'atm', key = 'encoding', subkey = 'value')
+                enc = UserSettings.Get(
+                    group='atm', key='encoding', subkey='value')
                 if enc:
-                    txt = unicode(txt, enc, errors = 'replace')
+                    txt = unicode(txt, enc, errors='replace')
                 elif 'GRASS_DB_ENCODING' in os.environ:
-                    txt = unicode(txt, os.environ['GRASS_DB_ENCODING'], errors = 'replace')
+                    txt = unicode(
+                        txt, os.environ['GRASS_DB_ENCODING'],
+                        errors='replace')
                 else:
                     txt = EncodeString(txt)
-                
+
                 self.AddText(txt)
 
         # reset output window to read only
         self.SetReadOnly(True)
 
-    def AddStyledMessage(self, message, style = None):
+    def AddStyledMessage(self, message, style=None):
         """Add message to text area.
 
         Handles messages with progress percentages.
@@ -662,10 +734,10 @@
             message = 'WARNING: ' + message
         elif style == 'error':
             message = 'ERROR: ' + message
-        
+
         p1 = self.GetEndStyled()
         self.GotoPos(p1)
-        
+
         # is this still needed?
         if '\b' in message:
             if self.linePos < 0:
@@ -685,48 +757,53 @@
                     if c != ' ':
                         last_c = c
             if last_c not in ('0123456789'):
-                self.AddTextWrapped('\n', wrap = None)
+                self.AddTextWrapped('\n', wrap=None)
                 self.linePos = -1
         else:
-            self.linePos = -1 # don't force position
+            self.linePos = -1  # don't force position
             if '\n' not in message:
-                self.AddTextWrapped(message, wrap = 60)
+                self.AddTextWrapped(message, wrap=60)
             else:
-                self.AddTextWrapped(message, wrap = None)
+                self.AddTextWrapped(message, wrap=None)
         p2 = self.GetCurrentPos()
-        
+
         if p2 >= p1:
             self.StartStyling(p1, 0xff)
-        
+
             if style == 'error':
                 self.SetStyling(p2 - p1, self.StyleError)
             elif style == 'warning':
                 self.SetStyling(p2 - p1, self.StyleWarning)
             elif style == 'message':
                 self.SetStyling(p2 - p1, self.StyleMessage)
-            else: # unknown
+            else:  # unknown
                 self.SetStyling(p2 - p1, self.StyleUnknown)
-        
+
         self.EnsureCaretVisible()
 
 
 class GConsoleFrame(wx.Frame):
     """Standalone GConsole for testing only"""
-    def __init__(self, parent, id = wx.ID_ANY, title = "GConsole Test Frame",
-                 style = wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL, **kwargs):
-        wx.Frame.__init__(self, parent = parent, id = id, title = title, style = style)
 
-        panel = wx.Panel(self, id = wx.ID_ANY)
-        
+    def __init__(self, parent, id=wx.ID_ANY, title="GConsole Test Frame",
+                 style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL, **kwargs):
+        wx.Frame.__init__(self, parent=parent, id=id, title=title, style=style)
+
+        panel = wx.Panel(self, id=wx.ID_ANY)
+
         from lmgr.menudata import LayerManagerMenuData
         menuTreeBuilder = LayerManagerMenuData()
         self.gconsole = GConsole(guiparent=self)
-        self.goutput = GConsoleWindow(parent = panel, gconsole = self.gconsole,
+        self.goutput = GConsoleWindow(parent=panel, gconsole=self.gconsole,
                                       menuModel=menuTreeBuilder.GetModel(),
-                                      gcstyle = GC_SEARCH | GC_PROMPT)
+                                      gcstyle=GC_SEARCH | GC_PROMPT)
 
         mainSizer = wx.BoxSizer(wx.VERTICAL)
-        mainSizer.Add(item = self.goutput, proportion = 1, flag = wx.EXPAND, border = 0)
+        mainSizer.Add(
+            item=self.goutput,
+            proportion=1,
+            flag=wx.EXPAND,
+            border=0)
 
         panel.SetSizer(mainSizer)
         mainSizer.Fit(panel)
@@ -735,7 +812,7 @@
 
 def testGConsole():
     app = wx.App()
-    frame = GConsoleFrame(parent = None)
+    frame = GConsoleFrame(parent=None)
     frame.Show()
     app.MainLoop()
 

Modified: grass/trunk/gui/wxpython/gui_core/gselect.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/gselect.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gui_core/gselect.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -47,13 +47,13 @@
 
 import wx
 import wx.combo
-import wx.lib.buttons          as  buttons
+import wx.lib.buttons as buttons
 import wx.lib.filebrowsebutton as filebrowse
 
 from core import globalvar
 
 import grass.script as grass
-from   grass.script import task as gtask
+from grass.script import task as gtask
 from grass.exceptions import CalledModuleError
 try:
     from grass.pygrass import messages
@@ -61,25 +61,28 @@
     print >> sys.stderr, _("Unable to import pyGRASS: %s\n"
                            "Some functionality will be not accessible") % e
 
-from gui_core.widgets  import ManageSettingsWidget, CoordinatesValidator
+from gui_core.widgets import ManageSettingsWidget, CoordinatesValidator
 
-from core.gcmd     import RunCommand, GError, GMessage, GWarning
+from core.gcmd import RunCommand, GError, GMessage, GWarning
 from core.utils    import GetListOfLocations, GetListOfMapsets, \
-                          GetFormats, rasterFormatExtension, vectorFormatExtension
-from core.utils    import GetSettingsPath, GetValidLayerName, ListSortLower
-from core.utils    import GetVectorNumberOfLayers, _
+    GetFormats, rasterFormatExtension, vectorFormatExtension
+from core.utils import GetSettingsPath, GetValidLayerName, ListSortLower
+from core.utils import GetVectorNumberOfLayers, _
 from core.settings import UserSettings
-from core.debug    import Debug
+from core.debug import Debug
 from gui_core.vselect import VectorSelectBase
 
 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,
-                 mapsets = None, updateOnPopup = True, onPopup = None,
-                 fullyQualified = True, extraItems = {}, layerTree = None,
-                 validator = wx.DefaultValidator):
+
+    def __init__(
+            self, parent, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
+            type=None, multiple=False, nmaps=1, mapsets=None,
+            updateOnPopup=True, onPopup=None, fullyQualified=True,
+            extraItems={},
+            layerTree=None, validator=wx.DefaultValidator):
         """Custom control to create a ComboBox with a tree control to
         display and select GIS elements within acessible mapsets.
         Elements can be selected with mouse. Can allow multiple
@@ -97,22 +100,33 @@
         :param layerTree: show only elements from given layer tree if not None
         :param validator: validator for TextCtrl
         """
-        wx.combo.ComboCtrl.__init__(self, parent=parent, id=id, size=size, validator=validator)
+        wx.combo.ComboCtrl.__init__(
+            self,
+            parent=parent,
+            id=id,
+            size=size,
+            validator=validator)
         if globalvar.CheckWxVersion([3]):
             self.SetName("Select")
         else:
             self.GetChildren()[0].SetName("Select")
-            
+
         self.GetChildren()[0].type = type
 
         self.tcp = TreeCtrlComboPopup()
         self.SetPopupControl(self.tcp)
         self.SetPopupExtents(0, 100)
         if type:
-            self.tcp.SetData(type = type, mapsets = mapsets,
-                             multiple = multiple, nmaps = nmaps,
-                             updateOnPopup = updateOnPopup, onPopup = onPopup,
-                             fullyQualified = fullyQualified, extraItems = extraItems, layerTree = layerTree)
+            self.tcp.SetData(
+                type=type,
+                mapsets=mapsets,
+                multiple=multiple,
+                nmaps=nmaps,
+                updateOnPopup=updateOnPopup,
+                onPopup=onPopup,
+                fullyQualified=fullyQualified,
+                extraItems=extraItems,
+                layerTree=layerTree)
         self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
 
     def OnKeyDown(self, event):
@@ -127,29 +141,31 @@
                 self.ShowPopup()
             event.Skip()
 
-    def SetElementList(self, type, mapsets = None):
+    def SetElementList(self, type, mapsets=None):
         """Set element list
 
         :param type: GIS element type
         :param mapsets: list of acceptable mapsets (None for all in search path)
         """
-        self.tcp.SetData(type = type, mapsets = mapsets)
+        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):
+    def SetType(self, etype, multiple=False, nmaps=1,
+                mapsets=None, updateOnPopup=True, onPopup=None):
         """Param set element type for widget
 
         :param etype: element type, see gselect.ElementSelect
         """
-        self.tcp.SetData(type = etype, mapsets = mapsets,
-                         multiple = multiple, nmaps = nmaps,
-                         updateOnPopup = updateOnPopup, onPopup = onPopup)
+        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
@@ -157,8 +173,8 @@
 
         :param ftype: filter vector maps based on feature type
         """
-        Select.__init__(self, parent = parent, id = wx.ID_ANY,
-                        type = 'vector', **kwargs)
+        Select.__init__(self, parent=parent, id=wx.ID_ANY,
+                        type='vector', **kwargs)
 
         self.ftype = ftype
 
@@ -186,22 +202,23 @@
 
     """
     # overridden ComboPopup methods
+
     def Init(self):
         self.value = []            # for multiple is False ->
-                                   # len(self.value) in [0,1]
+        # len(self.value) in [0,1]
         self.curitem = None
         self.multiple = False
         self.updateOnPopup = True
         self.filterItems = []      # limit items based on this list,
-                                   # see layerTree parameter
+        # see layerTree parameter
 
     def Create(self, parent):
         self.seltree = wx.TreeCtrl(parent, style=wx.TR_HIDE_ROOT
-                                   |wx.TR_HAS_BUTTONS
-                                   |wx.TR_SINGLE
-                                   |wx.TR_LINES_AT_ROOT
-                                   |wx.SIMPLE_BORDER
-                                   |wx.TR_FULL_ROW_HIGHLIGHT)
+                                   | wx.TR_HAS_BUTTONS
+                                   | wx.TR_SINGLE
+                                   | wx.TR_LINES_AT_ROOT
+                                   | wx.SIMPLE_BORDER
+                                   | wx.TR_FULL_ROW_HIGHLIGHT)
         self.seltree.Bind(wx.EVT_MOTION, self.OnMotion)
         self.seltree.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
         # the following dummy handler are needed to keep tree events
@@ -213,9 +230,12 @@
         self.seltree.Bind(wx.EVT_TREE_BEGIN_DRAG, lambda x: None)
         self.seltree.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, lambda x: None)
         # navigation in list/tree is handled automatically since wxPython 3
-        # for older versions, we have to workaround it and write our own navigation
+        # for older versions, we have to workaround it and write our own
+        # navigation
         if globalvar.CheckWxVersion(version=[3]):
-            self.seltree.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self._onItemConfirmed)
+            self.seltree.Bind(
+                wx.EVT_TREE_ITEM_ACTIVATED,
+                self._onItemConfirmed)
             self.seltree.Bind(wx.EVT_TREE_KEY_DOWN, self._onDismissPopup)
         else:
             self.seltree.Bind(wx.EVT_TREE_ITEM_ACTIVATED, lambda x: None)
@@ -239,7 +259,7 @@
         if winValue:
             self.value = winValue.split(',')
 
-    def OnPopup(self, force = False):
+    def OnPopup(self, force=False):
         """Limited only for first selected
         """
         if not force and not self.updateOnPopup:
@@ -249,7 +269,7 @@
         inputText = self.GetCombo().GetValue().strip()
         if inputText:
             root = self.seltree.GetRootItem()
-            match = self.FindItem(root, inputText, startLetters = True)
+            match = self.FindItem(root, inputText, startLetters=True)
             if match.IsOk():
                 self.seltree.EnsureVisible(match)
                 self.seltree.SelectItem(match)
@@ -257,10 +277,13 @@
     def GetAdjustedSize(self, minWidth, prefHeight, maxHeight):
         """Reads UserSettings to get height (which was 200 in old implementation).
         """
-        height = UserSettings.Get(group = 'appearance', key = 'gSelectPopupHeight', subkey = 'value')
+        height = UserSettings.Get(
+            group='appearance',
+            key='gSelectPopupHeight',
+            subkey='value')
         return wx.Size(minWidth, min(height, maxHeight))
 
-    def FindItem(self, parentItem, text, startLetters = False):
+    def FindItem(self, parentItem, text, startLetters=False):
         """Finds item with given name or starting with given text
         """
         startletters = startLetters
@@ -269,7 +292,7 @@
             if self.seltree.GetItemText(item) == text:
                 return item
             if self.seltree.ItemHasChildren(item):
-                item = self.FindItem(item, text, startLetters = startletters)
+                item = self.FindItem(item, text, startLetters=startletters)
                 if wx.TreeItemId.IsOk(item):
                     return item
             elif startletters and self.seltree.GetItemText(item).startswith(text.split('@', 1)[0]):
@@ -281,18 +304,18 @@
         root = self.seltree.GetRootItem()
         if not root:
             root = self.seltree.AddRoot("<hidden root>")
-        self.seltree.AppendItem(root, text = value)
+        self.seltree.AppendItem(root, text=value)
 
     def SetItems(self, items):
         root = self.seltree.GetRootItem()
         if not root:
             root = self.seltree.AddRoot("<hidden root>")
         for item in items:
-            self.seltree.AppendItem(root, text = item)
+            self.seltree.AppendItem(root, text=item)
 
     def OnKeyUp(self, event):
         """Enable to select items using keyboard.
-        
+
         Unused with wxPython 3, can be removed in the future.
         """
         item = self.seltree.GetSelection()
@@ -359,9 +382,10 @@
         if 'onPopup' in kargs:
             self.onPopup = kargs['onPopup']
         if kargs.get('layerTree', None):
-            self.filterItems = [] # reset
+            self.filterItems = []  # reset
             ltype = kargs['type']
-            for layer in kargs['layerTree'].GetVisibleLayers(skipDigitized = True):
+            for layer in kargs['layerTree'].GetVisibleLayers(
+                    skipDigitized=True):
                 if layer.GetType() != ltype:
                     continue
                 self.filterItems.append(layer.GetName())
@@ -370,11 +394,13 @@
         """Delete all items in popup"""
         self.seltree.DeleteAllItems()
 
+
 class TreeCtrlComboPopup(ListCtrlComboPopup):
     """Create a tree ComboBox for selecting maps and other GIS elements
     in accessible mapsets within the current location
     """
     # overridden ComboPopup methods
+
     def Init(self):
 
         ListCtrlComboPopup.Init(self)
@@ -392,7 +418,7 @@
         """Set filter for GIS elements, see e.g. VectorSelect"""
         self.filterElements = filter
 
-    def OnPopup(self, force = False):
+    def OnPopup(self, force=False):
         """Limited only for first selected"""
         if not force and not self.updateOnPopup:
             return
@@ -400,13 +426,13 @@
             selected, exclude = self.onPopup(self.type)
         else:
             selected = None
-            exclude  = False
+            exclude = False
 
         self.GetElementList(selected, exclude)
 
         ListCtrlComboPopup.OnPopup(self, force)
 
-    def GetElementList(self, elements = None, exclude = False):
+    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
         beneath each mapset branch
@@ -415,7 +441,7 @@
         self.seltree.DeleteAllItems()
         if self.type:
             self._getElementList(self.type, self.mapsets, elements, exclude)
-        
+
         if len(self.value) > 0:
             root = self.seltree.GetRootItem()
             if not root:
@@ -427,7 +453,8 @@
             except:
                 pass
 
-    def _getElementList(self, element, mapsets = None, elements = None, exclude = False):
+    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
 
@@ -438,7 +465,7 @@
         """
         # get current mapset
         curr_mapset = grass.gisenv()['MAPSET']
-        
+
         # map element types to g.list types
         elementdict = {'cell': 'raster',
                        'raster': 'raster',
@@ -460,7 +487,7 @@
         renamed_elements = []
         for elem in element_list:
             if elem not in elementdict:
-                self.AddItem(_('Not selectable element'), node = False)
+                self.AddItem(_('Not selectable element'), node=False)
                 return
             else:
                 renamed_elements.append(elementdict[elem])
@@ -468,7 +495,8 @@
         if element in ('stds', 'strds', 'str3ds', 'stvds'):
             if self.tgis_error is False:
                 import grass.temporal as tgis
-                filesdict = tgis.tlist_grouped(elementdict[element], element == 'stds')
+                filesdict = tgis.tlist_grouped(
+                    elementdict[element], element == 'stds')
             else:
                 filesdict = None
         else:
@@ -478,15 +506,15 @@
         # add extra items first
         if self.extraItems:
             for group, items in self.extraItems.iteritems():
-                node = self.AddItem(group, node = True)
+                node = self.AddItem(group, node=True)
                 self.seltree.SetItemTextColour(node, wx.Colour(50, 50, 200))
                 for item in items:
-                    self.AddItem(item, node = False, parent = node)
+                    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)
+            mapsets = grass.mapsets(search_path=True)
 
         # current mapset first
         if curr_mapset in mapsets and mapsets[0] != curr_mapset:
@@ -495,7 +523,8 @@
 
         first_mapset = None
         for mapset in mapsets:
-            mapset_node = self.AddItem(_('Mapset') + ': ' + mapset, node = True, mapset = mapset)
+            mapset_node = self.AddItem(
+                _('Mapset') + ': ' + mapset, node=True, mapset=mapset)
             node = mapset_node
             if not first_mapset:
                 first_mapset = mapset_node
@@ -504,39 +533,49 @@
             if mapset not in filesdict:
                 continue
             try:
-                if type(filesdict[mapset]) == dict:
+                if isinstance(filesdict[mapset], dict):
                     for elementType in filesdict[mapset].keys():
-                        node = self.AddItem(_('Type: ') + elementType, mapset = mapset,
-                                            node = True, parent = mapset_node)
-                        self.seltree.SetItemTextColour(node, wx.Colour(50, 50, 200))
+                        node = self.AddItem(
+                            _('Type: ') + elementType,
+                            mapset=mapset,
+                            node=True,
+                            parent=mapset_node)
+                        self.seltree.SetItemTextColour(
+                            node, wx.Colour(50, 50, 200))
                         elem_list = filesdict[mapset][elementType]
-                        self._addItems(elist = elem_list, elements = elements,
-                                       mapset = mapset, exclude = exclude, node = node)
+                        self._addItems(
+                            elist=elem_list,
+                            elements=elements,
+                            mapset=mapset,
+                            exclude=exclude,
+                            node=node)
                 else:
                     elem_list = filesdict[mapset]
-                    self._addItems(elist = elem_list, elements = elements,
-                                   mapset = mapset, exclude = exclude, node = node)
-            except StandardError as e:
+                    self._addItems(elist=elem_list, elements=elements,
+                                   mapset=mapset, exclude=exclude, node=node)
+            except Exception 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')
+                sel = UserSettings.Get(
+                    group='appearance',
+                    key='elementListExpand',
+                    subkey='selection')
                 collapse = True
 
-                if sel == 0: # collapse all except PERMANENT and current
+                if sel == 0:  # collapse all except PERMANENT and current
                     if mapset in ('PERMANENT', curr_mapset):
                         collapse = False
-                elif sel == 1: # collapse all except PERMANENT
+                elif sel == 1:  # collapse all except PERMANENT
                     if mapset == 'PERMANENT':
                         collapse = False
-                elif sel == 2: # collapse all except current
+                elif sel == 2:  # collapse all except current
                     if mapset == curr_mapset:
                         collapse = False
-                elif sel == 3: # collapse all
+                elif sel == 3:  # collapse all
                     pass
-                elif sel == 4: # expand all
+                elif sel == 4:  # expand all
                     collapse = False
 
                 if collapse:
@@ -563,7 +602,7 @@
             if elem != '':
                 fullqElem = elem + '@' + mapset
                 if self.filterItems and fullqElem not in self.filterItems:
-                    continue # skip items missed in self.filterItems
+                    continue  # skip items missed in self.filterItems
 
                 if elements is not None:
                     if (exclude and fullqElem in elements) or \
@@ -572,11 +611,12 @@
 
                 if self.filterElements:
                     if self.filterElements(fullqElem):
-                        self.AddItem(elem, mapset = mapset, node = False, parent = node)
+                        self.AddItem(
+                            elem, mapset=mapset, node=False, parent=node)
                 else:
-                    self.AddItem(elem, mapset = mapset, node = False, parent = node)
+                    self.AddItem(elem, mapset=mapset, node=False, parent=node)
 
-    def AddItem(self, value, mapset = None, node = True, parent = None):
+    def AddItem(self, value, mapset=None, node=True, parent=None):
         if not parent:
             root = self.seltree.GetRootItem()
             if not root:
@@ -585,13 +625,14 @@
 
         data = {'node': node, 'mapset': mapset}
 
-        item = self.seltree.AppendItem(parent, text = value, data = wx.TreeItemData(data))
+        item = self.seltree.AppendItem(
+            parent, text=value, data=wx.TreeItemData(data))
         return item
 
     def OnKeyUp(self, event):
         """Enables to select items using keyboard
 
-        Unused with wxPython 3, can be removed in the future.        
+        Unused with wxPython 3, can be removed in the future.
         """
 
         item = self.seltree.GetSelection()
@@ -600,13 +641,16 @@
 
         # 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))
+            if self.seltree.ItemHasChildren(item) and self.seltree.IsExpanded(
+                    self.seltree.GetPrevSibling(item)):
+                itemPrev = self.seltree.GetLastChild(
+                    self.seltree.GetPrevSibling(item))
             else:
                 itemPrev = self.seltree.GetPrevSibling(item)
                 if not wx.TreeItemId.IsOk(itemPrev):
                     itemPrev = self.seltree.GetItemParent(item)
-                    if item == self.seltree.GetFirstChild(self.seltree.GetRootItem())[0]:
+                    if item == self.seltree.GetFirstChild(
+                            self.seltree.GetRootItem())[0]:
                         itemPrev = item
             self.seltree.SelectItem(itemPrev)
 
@@ -619,10 +663,14 @@
                 parent = self.seltree.GetItemParent(selected)
             nextSibling = self.seltree.GetNextSibling(parent)
             if wx.TreeItemId.IsOk(nextSibling):
-                match = self.FindItem(nextSibling, self.GetCombo().GetValue().strip(), True)
+                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)
+                match = self.FindItem(
+                    self.seltree.GetFirstChild(
+                        self.seltree.GetItemParent(parent))[0],
+                    self.GetCombo().GetValue().strip(),
+                    True)
             self.seltree.SelectItem(match)
 
         elif event.GetKeyCode() == wx.WXK_RIGHT:
@@ -714,26 +762,30 @@
         """
         return self.type
 
+
 class VectorDBInfo:
     """Class providing information about attribute tables
     linked to a vector map"""
+
     def __init__(self, map):
         self.map = map
 
         # dictionary of layer number and associated (driver, database, table)
         self.layers = {}
-         # dictionary of table and associated columns (type, length, values, ids)
+        # dictionary of table and associated columns (type, length, values,
+        # ids)
         self.tables = {}
 
-        if not self._CheckDBConnection(): # -> self.layers
+        if not self._CheckDBConnection():  # -> self.layers
             return
 
-        self._DescribeTables() # -> self.tables
+        self._DescribeTables()  # -> self.tables
 
     def _CheckDBConnection(self):
         """Check DB connection"""
         nuldev = file(os.devnull, 'w+')
-        # if map is not defined (happens with vnet initialization) or it doesn't exist
+        # if map is not defined (happens with vnet initialization) or it
+        # doesn't exist
         try:
             self.layers = grass.vector_db(map=self.map, stderr=nuldev)
         except CalledModuleError:
@@ -748,14 +800,18 @@
         for layer in self.layers.keys():
             # determine column names and types
             table = self.layers[layer]["table"]
-            columns = {} # {name: {type, length, [values], [ids]}}
+            columns = {}  # {name: {type, length, [values], [ids]}}
             i = 0
-            Debug.msg(1, "gselect.VectorDBInfo._DescribeTables(): table=%s driver=%s database=%s" % \
-                          (self.layers[layer]["table"], self.layers[layer]["driver"],
-                           self.layers[layer]["database"]))
-            for item in grass.db_describe(table = self.layers[layer]["table"],
-                                          driver = self.layers[layer]["driver"],
-                                          database = self.layers[layer]["database"])['cols']:
+            Debug.msg(
+                1,
+                "gselect.VectorDBInfo._DescribeTables(): table=%s driver=%s database=%s" %
+                (self.layers[layer]["table"],
+                 self.layers[layer]["driver"],
+                 self.layers[layer]["database"]))
+            for item in grass.db_describe(
+                    table=self.layers[layer]["table"],
+                    driver=self.layers[layer]["driver"],
+                    database=self.layers[layer]["database"])['cols']:
                 name, type, length = item
                 # FIXME: support more datatypes
                 if type.lower() == "integer":
@@ -765,12 +821,12 @@
                 else:
                     ctype = str
 
-                columns[name.strip()] = { 'index'  : i,
-                                          'type'   : type.lower(),
-                                          'ctype'  : ctype,
-                                          'length' : int(length),
-                                          'values' : [],
-                                          'ids'    : []}
+                columns[name.strip()] = {'index': i,
+                                         'type': type.lower(),
+                                         'ctype': ctype,
+                                         'length': int(length),
+                                         'values': [],
+                                         'ids': []}
                 i += 1
 
             # check for key column
@@ -788,10 +844,10 @@
     def Reset(self):
         """Reset"""
         for layer in self.layers:
-            table = self.layers[layer]["table"] # get table desc
+            table = self.layers[layer]["table"]  # get table desc
             for name in self.tables[table].keys():
                 self.tables[table][name]['values'] = []
-                self.tables[table][name]['ids']    = []
+                self.tables[table][name]['ids'] = []
 
     def GetName(self):
         """Get vector name"""
@@ -827,16 +883,24 @@
         """
         return self.tables[table]
 
+
 class LayerSelect(wx.ComboBox):
-    def __init__(self, parent, id = wx.ID_ANY,
-                 size = globalvar.DIALOG_COMBOBOX_SIZE,
-                 vector = None, dsn = None, choices = [], all = False, default = None):
+
+    def __init__(self, parent, id=wx.ID_ANY,
+                 size=globalvar.DIALOG_COMBOBOX_SIZE,
+                 vector=None, dsn=None, choices=[], all=False, default=None):
         """Creates combo box for selecting vector map layer names
 
         :param str vector: vector map name (native or connected via v.external)
         :param str dsn: OGR data source name
         """
-        super(LayerSelect, self).__init__(parent, id, size = size, choices = choices)
+        super(
+            LayerSelect,
+            self).__init__(
+            parent,
+            id,
+            size=size,
+            choices=choices)
 
         self.all = all
 
@@ -845,9 +909,9 @@
         # default value
         self.default = default
 
-        self.InsertLayers(vector = vector, dsn = dsn)
+        self.InsertLayers(vector=vector, dsn=dsn)
 
-    def InsertLayers(self, vector = None, dsn = None):
+    def InsertLayers(self, vector=None, dsn=None):
         """Insert layers for a vector into the layer combobox
 
         :param str vector: vector map name (native or connected via v.external)
@@ -859,10 +923,10 @@
             layers = GetVectorNumberOfLayers(vector)
         elif dsn:
             ret = RunCommand('v.in.ogr',
-                             read = True,
-                             quiet = True,
-                             flags = 'l',
-                             input = dsn)
+                             read=True,
+                             quiet=True,
+                             flags='l',
+                             input=dsn)
             if ret:
                 layers = ret.splitlines()
 
@@ -885,9 +949,11 @@
         if self.default and self.default in layers:
             self.SetValue(self.default)
 
+
 class DriverSelect(wx.ComboBox):
     """Creates combo box for selecting database driver.
     """
+
     def __init__(self, parent, choices, value,
                  id=wx.ID_ANY, pos=wx.DefaultPosition,
                  size=globalvar.DIALOG_LAYER_SIZE, **kargs):
@@ -899,28 +965,47 @@
 
         self.SetStringSelection(value)
 
+
 class DatabaseSelect(wx.TextCtrl):
     """Creates combo box for selecting database driver.
     """
-    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)
+
+    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 = '',
-                 size = globalvar.DIALOG_COMBOBOX_SIZE, choices = [], **kargs):
-        super(TableSelect, self).__init__(parent, id, value, size = size, choices = choices,
-                                          style = wx.CB_READONLY, **kargs)
+                 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):
+    def InsertTables(self, driver=None, database=None):
         """Insert attribute tables into combobox"""
         items = []
 
@@ -931,10 +1016,10 @@
             database = connect['database']
 
         ret = RunCommand('db.tables',
-                         flags = 'p',
-                         read = True,
-                         driver = driver,
-                         database = database)
+                         flags='p',
+                         read=True,
+                         driver=driver,
+                         database=database)
 
         if ret:
             for table in ret.splitlines():
@@ -958,10 +1043,11 @@
     :param param: parameters list (see menuform.py)
     :param kwags: wx.ComboBox parameters
     """
-    def __init__(self, parent, id = wx.ID_ANY, value = '',
-                 size = globalvar.DIALOG_COMBOBOX_SIZE,
-                 vector = None, layer = 1, multiple = False,
-                 param = None, **kwargs):
+
+    def __init__(self, parent, id=wx.ID_ANY, value='',
+                 size=globalvar.DIALOG_COMBOBOX_SIZE,
+                 vector=None, layer=1, multiple=False,
+                 param=None, **kwargs):
         self.defaultValue = value
         self.param = param
         self.columns = []
@@ -972,7 +1058,7 @@
 
         self.tcp = ListCtrlComboPopup()
         self.SetPopupControl(self.tcp)
-        self.tcp.SetData(multiple = multiple)
+        self.tcp.SetData(multiple=multiple)
 
         if vector:
             self.InsertColumns(vector, layer)
@@ -992,7 +1078,8 @@
         self.tcp.DeleteAllItems()
         self.SetValue('')
 
-    def InsertColumns(self, vector, layer, excludeKey = False, excludeCols = None, type = None, dbInfo = None):
+    def InsertColumns(self, vector, layer, excludeKey=False,
+                      excludeCols=None, type=None, dbInfo=None):
         """Insert columns for a vector attribute table into the columns combobox
 
         :param str vector: vector name
@@ -1016,13 +1103,13 @@
             self.columns = len(columnchoices.keys()) * ['']
             for key, val in columnchoices.iteritems():
                 self.columns[val['index']] = key
-            if excludeKey: # exclude key column
+            if excludeKey:  # exclude key column
                 self.columns.remove(keyColumn)
-            if excludeCols: # exclude key column
+            if excludeCols:  # exclude key column
                 for key in columnchoices.iterkeys():
                     if key in excludeCols:
                         self.columns.remove(key)
-            if type: # only selected column types
+            if type:  # only selected column types
                 for key, value in columnchoices.iteritems():
                     if value['type'] not in type:
                         try:
@@ -1054,10 +1141,10 @@
         self.columns[:] = []
 
         ret = RunCommand('db.columns',
-                         read = True,
-                         driver = driver,
-                         database = database,
-                         table = table)
+                         read=True,
+                         driver=driver,
+                         database=database,
+                         table=table)
 
         if ret:
             self.columns = ret.splitlines()
@@ -1073,22 +1160,32 @@
             if value != '' and value in self.columns:
                 self.SetValue(value)
 
+
 class DbaseSelect(wx.lib.filebrowsebutton.DirBrowseButton):
     """Widget for selecting GRASS Database"""
+
     def __init__(self, parent, **kwargs):
-        super(DbaseSelect, self).__init__(parent, id = wx.ID_ANY,
-                                          size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
-                                          dialogTitle = _('Choose GIS Data Directory'),
-                                          buttonText = _('Browse'),
-                                          startDirectory = grass.gisenv()['GISDBASE'],
-                                          **kwargs)
+        super(
+            DbaseSelect,
+            self).__init__(
+            parent,
+            id=wx.ID_ANY,
+            size=globalvar.DIALOG_GSELECT_SIZE,
+            labelText='',
+            dialogTitle=_('Choose GIS Data Directory'),
+            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,
-                 gisdbase = None, **kwargs):
-        super(LocationSelect, self).__init__(parent, id, size = size,
-                                             style = wx.CB_READONLY, **kwargs)
+
+    def __init__(
+            self, parent, id=wx.ID_ANY, size=globalvar.DIALOG_COMBOBOX_SIZE,
+            gisdbase=None, **kwargs):
+        super(LocationSelect, self).__init__(parent, id, size=size,
+                                             style=wx.CB_READONLY, **kwargs)
         self.SetName("LocationSelect")
 
         if not gisdbase:
@@ -1109,19 +1206,22 @@
         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,
-                 gisdbase = None, location = None, setItems = True,
-                 searchPath = False, new = False, skipCurrent = False, multiple = False, **kwargs):
+
+    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:
+        # 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,
-                                    style = style, **kwargs)
-        self.searchPath  = searchPath
+        wx.combo.ComboCtrl.__init__(self, parent, id, size=size,
+                                    style=style, **kwargs)
+        self.searchPath = searchPath
         self.skipCurrent = skipCurrent
         self.SetName("MapsetSelect")
         if not gisdbase:
@@ -1136,12 +1236,12 @@
 
         self.tcp = ListCtrlComboPopup()
         self.SetPopupControl(self.tcp)
-        self.tcp.SetData(multiple = multiple)
+        self.tcp.SetData(multiple=multiple)
 
         if setItems:
             self.tcp.SetItems(self._getMapsets())
 
-    def UpdateItems(self, location, dbase = None):
+    def UpdateItems(self, location, dbase=None):
         """Update list of mapsets for given location
 
         :param str dbase: path to GIS database (None to use currently
@@ -1162,11 +1262,11 @@
     def _getMapsets(self):
         if self.searchPath:
             mlist = RunCommand('g.mapsets',
-                               read = True, flags = 'p',
-                               sep = 'newline').splitlines()
+                               read=True, flags='p',
+                               sep='newline').splitlines()
         else:
             mlist = GetListOfMapsets(self.gisdbase, self.location,
-                                     selectable = False)
+                                     selectable=False)
 
         gisenv = grass.gisenv()
         if self.skipCurrent and \
@@ -1192,7 +1292,7 @@
         """For backward compatibility. MapsetSelect changed to allow
         multiple selection, this required to change super-class from
         wx.ComboBox to wx.combo.ComboCtrl"""
-        self.SetValue('') # TODO: implement SetSelection()
+        self.SetValue('')  # TODO: implement SetSelection()
 
     def SetItems(self, items):
         """For backward compatibility. MapsetSelect changed to allow
@@ -1201,11 +1301,13 @@
         self.tcp.DeleteAllItems()
         self.tcp.SetItems(items)
 
+
 class SubGroupSelect(wx.ComboBox):
     """Widget for selecting subgroups"""
-    def __init__(self, parent, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
-                 **kwargs):
-        super(SubGroupSelect, self).__init__(parent, id, size = size,
+
+    def __init__(self, parent, id=wx.ID_ANY,
+                 size=globalvar.DIALOG_GSELECT_SIZE, **kwargs):
+        super(SubGroupSelect, self).__init__(parent, id, size=size,
                                              **kwargs)
         self.SetName("SubGroupSelect")
 
@@ -1227,7 +1329,9 @@
         except OSError:
             self.SetItems([])
 
+
 class FormatSelect(wx.Choice):
+
     def __init__(self, parent, srcType, ogr=False,
                  size=globalvar.DIALOG_SPIN_SIZE,
                  **kwargs):
@@ -1259,7 +1363,9 @@
 
         return formatToExt.get(name, '')
 
+
 class GdalSelect(wx.Panel):
+
     def __init__(self, parent, panel, ogr=False, link=False, dest=False,
                  exclude=None, settings=True):
         """Widget for selecting GDAL/OGR datasource, format
@@ -1284,7 +1390,6 @@
 
         self.reloadDataRequired = Signal('GdalSelect.reloadDataRequired')
 
-
         self.inputBox = wx.StaticBox(parent=self)
         if dest:
             self.inputBox.SetLabel(" %s " % _("Output settings"))
@@ -1293,11 +1398,11 @@
 
         # source type
         sources = list()
-        self.sourceMap = { 'file'   : -1,
-                           'dir'    : -1,
-                           'db'     : -1,
-                           'pro'    : -1,
-                           'native' : -1 }
+        self.sourceMap = {'file': -1,
+                          'dir': -1,
+                          'db': -1,
+                          'pro': -1,
+                          'native': -1}
         idx = 0
         if dest:
             sources.append(_("Native"))
@@ -1323,7 +1428,7 @@
             idx += 1
         self.sourceMapByIdx = {}
         for name, idx in self.sourceMap.items():
-            self.sourceMapByIdx[ idx ] = name
+            self.sourceMapByIdx[idx] = name
 
         self.source = wx.RadioBox(parent=self, id=wx.ID_ANY,
                                   style=wx.RA_SPECIFY_COLS,
@@ -1334,10 +1439,12 @@
             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.source.Bind(
+            wx.EVT_RADIOBOX,
+            lambda evt: self.SetSourceType(
+                self.sourceMapByIdx[
+                    evt.GetInt()]))
 
-
         self.nativeWidgets = {}
         self.fileWidgets = {}
         self.dirWidgets = {}
@@ -1355,18 +1462,18 @@
         if not ogr:
             extList = rasterFormatExtension
             fileMask += ('%(name)s (*.%(low1)s;*.%(low2)s;*.%(up1)s;*.%(up2)s)|'
-                        '*.%(low1)s;*.%(low2)s;*.%(up1)s;*.%(up2)s|' %
-                        {'name': 'GeoTIFF', 'low1': 'tif', 'low2': 'tiff', 'up1': 'TIF', 'up2': 'TIFF'})
+                         '*.%(low1)s;*.%(low2)s;*.%(up1)s;*.%(up2)s|' %
+                         {'name': 'GeoTIFF', 'low1': 'tif', 'low2': 'tiff', 'up1': 'TIF', 'up2': 'TIFF'})
         else:
             extList = vectorFormatExtension
-            fileMask += '%(name)s (*.%(low)s;*.%(up)s)|*.%(low)s;*.%(up)s|' % {'name': 'ESRI Shapefile', 'low': 'shp', 'up': 'SHP'}
-        
+            fileMask += '%(name)s (*.%(low)s;*.%(up)s)|*.%(low)s;*.%(up)s|' % {
+                'name': 'ESRI Shapefile', 'low': 'shp', 'up': 'SHP'}
+
         for name, ext in sorted(extList.items()):
             if name in ('ESRI Shapefile', 'GeoTIFF'):
                 continue
-            fileMask += '%(name)s (*.%(low)s;*.%(up)s)|*.%(low)s;*.%(up)s|' % {'name': name,
-                                                                               'low': ext.lower(),
-                                                                               'up': ext.upper()}
+            fileMask += '%(name)s (*.%(low)s;*.%(up)s)|*.%(low)s;*.%(up)s|' % {
+                'name': name, 'low': ext.lower(), 'up': ext.upper()}
         fileMask += '%s (*.zip;*.ZIP)|*.zip;*.ZIP|' % _('ZIP files')
         fileMask += '%s (*.gz;*.GZ)|*.gz;*.GZ|' % _('GZIP files')
         fileMask += '%s (*.tar;*.TAR)|*.tar;*.TAR|' % _('TAR files')
@@ -1375,27 +1482,31 @@
         # only contains formats with extensions hardcoded
 
         self.filePanel = wx.Panel(parent=self)
-        browse = filebrowse.FileBrowseButton(parent=self.filePanel, id=wx.ID_ANY,
-                                             size=globalvar.DIALOG_GSELECT_SIZE,
-                                             labelText = _('File:'),
-                                             dialogTitle=_('Choose file to import'),
-                                             buttonText=_('Browse'),
-                                             startDirectory=os.getcwd(),
-                                             changeCallback=self.OnUpdate,
-                                             fileMask=fileMask)
+        browse = filebrowse.FileBrowseButton(
+            parent=self.filePanel,
+            id=wx.ID_ANY,
+            size=globalvar.DIALOG_GSELECT_SIZE,
+            labelText=_('File:'),
+            dialogTitle=_('Choose file to import'),
+            buttonText=_('Browse'),
+            startDirectory=os.getcwd(),
+            changeCallback=self.OnUpdate,
+            fileMask=fileMask)
         browse.GetChildren()[1].SetName('GdalSelectDataSource')
         self.fileWidgets['browse'] = browse
         self.fileWidgets['options'] = wx.TextCtrl(parent=self.filePanel)
 
         # directory
         self.dirPanel = wx.Panel(parent=self)
-        browse = filebrowse.DirBrowseButton(parent=self.dirPanel, id=wx.ID_ANY,
-                                            size=globalvar.DIALOG_GSELECT_SIZE,
-                                            labelText=_('Directory:'),
-                                            dialogTitle=_('Choose input directory'),
-                                            buttonText=_('Browse'),
-                                            startDirectory=os.getcwd(),
-                                            changeCallback=self.OnUpdate)
+        browse = filebrowse.DirBrowseButton(
+            parent=self.dirPanel,
+            id=wx.ID_ANY,
+            size=globalvar.DIALOG_GSELECT_SIZE,
+            labelText=_('Directory:'),
+            dialogTitle=_('Choose input directory'),
+            buttonText=_('Browse'),
+            startDirectory=os.getcwd(),
+            changeCallback=self.OnUpdate)
         browse.GetChildren()[1].SetName('GdalSelectDataSource')
 
         self.dirWidgets['browse'] = browse
@@ -1403,11 +1514,13 @@
         self.dirWidgets['format'] = formatSelect
         fileFormats = GetFormats(writableOnly=dest)[fType]['file']
         formatSelect.SetItems(sorted(list(fileFormats)))
-        formatSelect.Bind(wx.EVT_CHOICE, lambda evt: self.SetExtension(self.dirWidgets['format'].GetStringSelection()))
+        formatSelect.Bind(
+            wx.EVT_CHOICE, lambda evt: self.SetExtension(
+                self.dirWidgets['format'].GetStringSelection()))
         formatSelect.Bind(wx.EVT_CHOICE, self.OnUpdate)
 
-        self.dirWidgets['extensionLabel'] = wx.StaticText(parent=self.dirPanel,
-                                                          label = _("Extension:"))
+        self.dirWidgets['extensionLabel'] = wx.StaticText(
+            parent=self.dirPanel, label=_("Extension:"))
         self.dirWidgets['extension'] = wx.TextCtrl(parent=self.dirPanel)
         self.dirWidgets['extension'].Bind(wx.EVT_TEXT, self.ExtensionChanged)
         self.dirWidgets['options'] = wx.TextCtrl(parent=self.dirPanel)
@@ -1426,60 +1539,79 @@
         self.dbPanel = wx.Panel(parent=self)
         self.dbFormats = GetFormats(writableOnly=dest)[fType]['database']
         dbChoice = wx.Choice(parent=self.dbPanel, choices=self.dbFormats)
-        dbChoice.Bind(wx.EVT_CHOICE, lambda evt: self.SetDatabase(db=dbChoice.GetStringSelection()))
+        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,
-                                             size=globalvar.DIALOG_GSELECT_SIZE,
-                                             labelText=_("Name:"),
-                                             dialogTitle=_('Choose file'),
-                                             buttonText=_('Browse'),
-                                             startDirectory=os.getcwd(),
-                                             changeCallback=self.OnUpdate)
+        browse = filebrowse.FileBrowseButton(
+            parent=self.dbPanel,
+            id=wx.ID_ANY,
+            size=globalvar.DIALOG_GSELECT_SIZE,
+            labelText=_("Name:"),
+            dialogTitle=_('Choose file'),
+            buttonText=_('Browse'),
+            startDirectory=os.getcwd(),
+            changeCallback=self.OnUpdate)
         browse.GetChildren()[1].SetName('GdalSelectDataSource')
-        
+
         self.dbWidgets['browse'] = browse
-        self.dbWidgets['choice'] = wx.Choice(parent=self.dbPanel, name='GdalSelectDataSource')
+        self.dbWidgets['choice'] = wx.Choice(
+            parent=self.dbPanel, name='GdalSelectDataSource')
         self.dbWidgets['choice'].Bind(wx.EVT_CHOICE, self.OnUpdate)
-        self.dbWidgets['text'] = wx.TextCtrl(parent=self.dbPanel, name='GdalSelectDataSource')
+        self.dbWidgets['text'] = wx.TextCtrl(
+            parent=self.dbPanel, name='GdalSelectDataSource')
         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,
-                                                 label = " %s " % _("Feature type:"),
-                                                 choices = [_("simple features"), _("topological")],
-                                                 majorDimension=2,
-                                                 style = wx.RA_SPECIFY_COLS)
+        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,
+            label=" %s " %
+            _("Feature type:"),
+            choices=[
+                _("simple features"),
+                _("topological")],
+            majorDimension=2,
+            style=wx.RA_SPECIFY_COLS)
         if dest:
             self.dbWidgets['featType'].Disable()
         else:
             self.dbWidgets['featType'].Hide()
-        browse = filebrowse.DirBrowseButton(parent=self.dbPanel, id=wx.ID_ANY,
-                                            size=globalvar.DIALOG_GSELECT_SIZE,
-                                            labelText=_('Directory:'),
-                                            dialogTitle=_('Choose input directory'),
-                                            buttonText=_('Browse'),
-                                            startDirectory=os.getcwd(),
-                                            changeCallback=self.OnUpdate)
+        browse = filebrowse.DirBrowseButton(
+            parent=self.dbPanel,
+            id=wx.ID_ANY,
+            size=globalvar.DIALOG_GSELECT_SIZE,
+            labelText=_('Directory:'),
+            dialogTitle=_('Choose input directory'),
+            buttonText=_('Browse'),
+            startDirectory=os.getcwd(),
+            changeCallback=self.OnUpdate)
         self.dbWidgets['dirbrowse'] = browse
         self.dbWidgets['options'] = wx.TextCtrl(parent=self.dbPanel)
 
         # protocol
         self.protocolPanel = wx.Panel(parent=self)
         protocolFormats = GetFormats(writableOnly=self.dest)[fType]['protocol']
-        protocolChoice = wx.Choice(parent=self.protocolPanel, choices=protocolFormats)
+        protocolChoice = wx.Choice(
+            parent=self.protocolPanel,
+            choices=protocolFormats)
         self.protocolWidgets['format'] = protocolChoice
 
         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)
+        self.protocolWidgets['options'] = wx.TextCtrl(
+            parent=self.protocolPanel)
 
         # native
         self.nativePanel = wx.Panel(parent=self)
 
         self._layout()
         sourceType = 'file'
-        self.SetSourceType(sourceType) # needed always to fit dialog size
+        self.SetSourceType(sourceType)  # needed always to fit dialog size
         if self.dest:
             current = RunCommand('v.external.out',
                                  parent=self,
@@ -1500,11 +1632,11 @@
         format = data.get('format', '')
         pg = 'conninfo' in data.keys()
         if pg:
-            dsn=''
+            dsn = ''
             for item in data.get('conninfo').split(' '):
                 k, v = item.split('=')
                 if k == 'dbname':
-                    dsn=v
+                    dsn = v
                     break
             optList = list()
             for k, v in data.iteritems():
@@ -1519,7 +1651,7 @@
         self.SetSourceType(sourceType)
         self.source.SetSelection(self.sourceMap[sourceType])
 
-        dsn = os.path.expandvars(dsn) # v.external.out uses $HOME
+        dsn = os.path.expandvars(dsn)  # v.external.out uses $HOME
         # fill in default values
         if sourceType == 'dir':
             self.dirWidgets['format'].SetStringSelection(format)
@@ -1553,11 +1685,11 @@
         sizer.AddGrowableCol(0)
         if self.dest:
             sizer.Add(item=wx.StaticText(parent=self.filePanel,
-                                         label = _("Creation options:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (1, 0))
+                                         label=_("Creation options:")),
+                      flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(1, 0))
             sizer.Add(item=self.fileWidgets['options'],
-                      flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND,
+                      flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
                       pos=(1, 1))
 
         else:
@@ -1567,11 +1699,11 @@
         # directory
         sizer = wx.GridBagSizer(vgap=3, hgap=10)
         sizer.Add(item=wx.StaticText(parent=self.dirPanel,
-                                       label = _("Format:")),
-                          flag=wx.ALIGN_CENTER_VERTICAL,
-                          pos=(0, 0))
+                                     label=_("Format:")),
+                  flag=wx.ALIGN_CENTER_VERTICAL,
+                  pos=(0, 0))
         sizer.Add(item=self.dirWidgets['format'],
-                  flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND,
+                  flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
                   pos=(0, 1))
         sizer.Add(item=self.dirWidgets['extensionLabel'],
                   flag=wx.ALIGN_CENTER_VERTICAL,
@@ -1580,20 +1712,20 @@
                   flag=wx.ALIGN_CENTER_VERTICAL,
                   pos=(0, 3))
         sizer.Add(item=self.dirWidgets['browse'],
-                  flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND,
+                  flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
                   pos=(1, 0), span=(1, 4))
         if self.dest:
             sizer.Add(item=wx.StaticText(parent=self.dirPanel,
-                                         label = _("Creation options:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (2, 0))
+                                         label=_("Creation options:")),
+                      flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(2, 0))
             sizer.Add(item=self.dirWidgets['options'],
-                      flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND,
+                      flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
                       pos=(2, 1))
             helpBtn = wx.Button(parent=self.dirPanel, id=wx.ID_HELP)
             helpBtn.Bind(wx.EVT_BUTTON, self.OnHelp)
             sizer.Add(item=helpBtn,
-                      flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND,
+                      flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
                       pos=(2, 2))
 
             self.dirWidgets['extensionLabel'].Hide()
@@ -1606,9 +1738,9 @@
         # database
         sizer = wx.GridBagSizer(vgap=1, hgap=5)
         sizer.Add(item=wx.StaticText(parent=self.dbPanel,
-                                       label = _("Format:")),
-                          flag=wx.ALIGN_CENTER_VERTICAL,
-                          pos=(0, 0))
+                                     label=_("Format:")),
+                  flag=wx.ALIGN_CENTER_VERTICAL,
+                  pos=(0, 0))
         sizer.Add(item=self.dbWidgets['format'],
                   flag=wx.ALIGN_CENTER_VERTICAL,
                   pos=(0, 1))
@@ -1616,30 +1748,30 @@
                   flag=wx.ALIGN_CENTER_VERTICAL,
                   pos=(1, 0))
         sizer.Add(item=self.dbWidgets['text'],
-                  flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND,
+                  flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
                   pos=(1, 1), span=(1, 2))
         sizer.Add(item=self.dbWidgets['browse'],
-                  flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND,
+                  flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
                   pos=(2, 0), span=(1, 3))
         sizer.Add(item=self.dbWidgets['dirbrowse'],
-                  flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND,
+                  flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
                   pos=(3, 0), span=(1, 2))
         sizer.Add(item=self.dbWidgets['textLabel2'],
                   flag=wx.ALIGN_CENTER_VERTICAL,
                   pos=(4, 0))
         sizer.Add(item=self.dbWidgets['choice'],
-                  flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND,
+                  flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
                   pos=(4, 1), span=(1, 2))
         if self.dest:
             sizer.Add(item=self.dbWidgets['featType'],
                       pos=(0, 2), flag=wx.EXPAND)
 
             sizer.Add(item=wx.StaticText(parent=self.dbPanel,
-                                         label = _("Creation options:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (5, 0))
+                                         label=_("Creation options:")),
+                      flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(5, 0))
             sizer.Add(item=self.dbWidgets['options'],
-                      flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND,
+                      flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
                       pos=(5, 1), span=(1, 2))
 
             # help button
@@ -1658,26 +1790,26 @@
         # protocol
         sizer = wx.GridBagSizer(vgap=3, hgap=3)
         sizer.Add(item=wx.StaticText(parent=self.protocolPanel,
-                                       label = _("Format:")),
-                          flag=wx.ALIGN_CENTER_VERTICAL,
-                          pos=(0, 0))
+                                     label=_("Format:")),
+                  flag=wx.ALIGN_CENTER_VERTICAL,
+                  pos=(0, 0))
         sizer.Add(item=self.protocolWidgets['format'],
                   flag=wx.ALIGN_CENTER_VERTICAL,
                   pos=(0, 1))
         sizer.Add(item=wx.StaticText(parent=self.protocolPanel,
-                                     label = _("Protocol:")),
-                          flag=wx.ALIGN_CENTER_VERTICAL,
-                          pos=(1, 0))
+                                     label=_("Protocol:")),
+                  flag=wx.ALIGN_CENTER_VERTICAL,
+                  pos=(1, 0))
         sizer.Add(item=self.protocolWidgets['text'],
-                  flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND,
+                  flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
                   pos=(1, 1))
         if self.dest:
             sizer.Add(item=wx.StaticText(parent=self.protocolPanel,
-                                         label = _("Creation options:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (2, 0))
+                                         label=_("Creation options:")),
+                      flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(2, 0))
             sizer.Add(item=self.protocolWidgets['options'],
-                      flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND,
+                      flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
                       pos=(2, 1))
 
         else:
@@ -1688,8 +1820,8 @@
         # native
         sizer = wx.BoxSizer(wx.VERTICAL)
         sizer.Add(item=wx.StaticText(parent=self.nativePanel,
-                                     label = _("No settings available")),
-                          flag=wx.ALIGN_CENTER_VERTICAL|wx.ALL|wx.EXPAND, border=5)
+                                     label=_("No settings available")),
+                  flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND, border=5)
         self.nativePanel.SetSizer(sizer)
 
         for panel in (self.nativePanel, self.filePanel,
@@ -1700,9 +1832,9 @@
                                    flag=wx.EXPAND)
 
         self.mainSizer.Add(item=self.source, proportion=0,
-                      flag=wx.LEFT | wx.RIGHT | wx.EXPAND, border=5)
+                           flag=wx.LEFT | wx.RIGHT | wx.EXPAND, border=5)
         self.mainSizer.Add(item=self.changingSizer, proportion=1,
-                      flag=wx.ALL | wx.EXPAND, border=5)
+                           flag=wx.ALL | wx.EXPAND, border=5)
         self.SetSizer(self.mainSizer)
         self.mainSizer.Fit(self)
 
@@ -1718,10 +1850,16 @@
         """Set source type (db, file, dir, ...).
         Does not switch radioboxes."""
         self._sourceType = sourceType
-        self.changingSizer.Show(item=self.filePanel, show=(sourceType == 'file'))
-        self.changingSizer.Show(item=self.nativePanel, show=(sourceType == 'native'))
+        self.changingSizer.Show(
+            item=self.filePanel, show=(
+                sourceType == 'file'))
+        self.changingSizer.Show(
+            item=self.nativePanel, show=(
+                sourceType == 'native'))
         self.changingSizer.Show(item=self.dirPanel, show=(sourceType == 'dir'))
-        self.changingSizer.Show(item=self.protocolPanel, show=(sourceType == 'pro'))
+        self.changingSizer.Show(
+            item=self.protocolPanel, show=(
+                sourceType == 'pro'))
         self.changingSizer.Show(item=self.dbPanel, show=(sourceType is 'db'))
 
         self.changingSizer.Layout()
@@ -1766,7 +1904,7 @@
             self.protocolWidgets['options'].SetValue(data[3])
         elif data[0] == 'db':
             name = self._getCurrentDbWidgetName()
-            if name =='choice':
+            if name == 'choice':
                 if len(data[1].split(':', 1)) > 1:
                     for item in data[1].split(':', 1)[1].split(','):
                         key, value = item.split('=', 1)
@@ -1788,7 +1926,7 @@
             settingsFile = os.path.join(GetSettingsPath(), 'wxOGR')
         else:
             settingsFile = os.path.join(GetSettingsPath(), 'wxGDAL')
-            
+
         self.settsManager = ManageSettingsWidget(parent=self,
                                                  settingsFile=settingsFile)
         self.settsManager.settingsChanged.connect(self.OnSettingsChanged)
@@ -1801,8 +1939,8 @@
     def OnSettingsSaving(self, name):
         """Saving data"""
         if not self.GetDsn():
-            GMessage(parent = self,
-                     message = _("No data source defined, settings are not saved."))
+            GMessage(parent=self, message=_(
+                "No data source defined, settings are not saved."))
             return
 
         self.settsManager.SetDataToSave((self._sourceType, self.GetDsn(),
@@ -1826,10 +1964,11 @@
         """Get datasource name
         """
         if self._sourceType == 'db':
-            if self.dbWidgets['format'].GetStringSelection() in ('PostgreSQL',
-                                                                 'PostGIS Raster driver'):
+            if self.dbWidgets['format'].GetStringSelection() in(
+                    'PostgreSQL', 'PostGIS Raster driver'):
 
-                dsn = 'PG:dbname=%s' % self.dbWidgets['choice'].GetStringSelection()
+                dsn = 'PG:dbname=%s' % self.dbWidgets[
+                    'choice'].GetStringSelection()
             else:
                 name = self._getCurrentDbWidgetName()
                 if name == 'choice':
@@ -1866,7 +2005,7 @@
         sizer = self.dbPanel.GetSizer()
         showBrowse = db in ('SQLite', 'Rasterlite')
         showDirbrowse = db in ('FileGDB')
-        showChoice = db in ('PostgreSQL','PostGIS WKT Raster driver',
+        showChoice = db in ('PostgreSQL', 'PostGIS WKT Raster driver',
                             'PostGIS Raster driver')
         enableFeatType = self.dest and self.ogr and db in ('PostgreSQL')
         showText = not(showBrowse or showChoice or showDirbrowse)
@@ -1880,14 +2019,18 @@
         self.dbWidgets['featType'].Enable(enableFeatType)
         if showChoice:
             # try to get list of PG databases
-            dbNames = RunCommand('db.databases', parent=self, quiet=True, read=True,
-                                 driver='pg').splitlines()
+            dbNames = RunCommand(
+                'db.databases',
+                parent=self,
+                quiet=True,
+                read=True,
+                driver='pg').splitlines()
             if dbNames is not None:
                 self.dbWidgets['choice'].SetItems(sorted(dbNames))
                 self.dbWidgets['choice'].SetSelection(0)
             elif grass.find_program('psql', '--help'):
                 if not self.dbWidgets['choice'].GetItems():
-                    p = grass.Popen(['psql', '-ltA'], stdout = grass.PIPE)
+                    p = grass.Popen(['psql', '-ltA'], stdout=grass.PIPE)
                     ret = p.communicate()[0]
                     if ret:
                         dbNames = list()
@@ -1919,18 +2062,19 @@
         def hasRastSameProjAsLocation(dsn):
 
             ret = RunCommand('r.external',
-                             quiet = True,
-                             read = True,
-                             flags = 't',
-                             input = dsn)
+                             quiet=True,
+                             read=True,
+                             flags='t',
+                             input=dsn)
 
             # v.external returns info for individual bands, however projection is shared by all bands ->
             # (it is possible to take first line)
-            
+
             lines = ret.splitlines()
             projectionMatch = '0'
             if lines:
-                bandNumber, bandType, projectionMatch = map(lambda x: x.strip(), lines[0].split(','))
+                bandNumber, bandType, projectionMatch = map(
+                    lambda x: x.strip(), lines[0].split(','))
 
             return projectionMatch
 
@@ -1953,23 +2097,34 @@
 
         if self.ogr:
             ret = RunCommand('v.external',
-                             quiet = True,
-                             read = True,
-                             flags = 't',
-                             input = dsn)
+                             quiet=True,
+                             read=True,
+                             flags='t',
+                             input=dsn)
             if not ret:
                 self.reloadDataRequired.emit(listData=None, data=None)
                 return
 
             layerId = 1
             for line in ret.splitlines():
-                layerName, featureType, projectionMatch, geometryColumn = map(lambda x: x.strip(), line.split(','))
+                layerName, featureType, projectionMatch, geometryColumn = map(
+                    lambda x: x.strip(), line.split(','))
                 projectionMatchCaption = getProjMatchCaption(projectionMatch)
                 grassName = GetValidLayerName(layerName)
                 if geometryColumn:
                     featureType = geometryColumn + '/' + featureType
-                listData.append((layerId, layerName, featureType, projectionMatchCaption, grassName))
-                data.append((layerId, layerName, featureType, int(projectionMatch), grassName))
+                listData.append(
+                    (layerId,
+                     layerName,
+                     featureType,
+                     projectionMatchCaption,
+                     grassName))
+                data.append(
+                    (layerId,
+                     layerName,
+                     featureType,
+                     int(projectionMatch),
+                        grassName))
                 layerId += 1
         else:
             if self._sourceType == 'file':
@@ -1977,19 +2132,25 @@
                 grassName = GetValidLayerName(baseName.split('.', -1)[0])
                 projectionMatch = hasRastSameProjAsLocation(dsn)
                 projectionMatchCaption = getProjMatchCaption(projectionMatch)
-                listData.append((layerId, baseName, projectionMatchCaption, grassName))
-                data.append((layerId, baseName, int(projectionMatch), grassName))
+                listData.append(
+                    (layerId, baseName, projectionMatchCaption, grassName))
+                data.append(
+                    (layerId, baseName, int(projectionMatch), grassName))
             elif self._sourceType == 'dir':
                 ext = self.dirWidgets['extension'].GetValue()
-                for filename in glob.glob(os.path.join(dsn, "%s") % self._getExtPatternGlob(ext)):
+                for filename in glob.glob(os.path.join(
+                        dsn, "%s") % self._getExtPatternGlob(ext)):
                     baseName = os.path.basename(filename)
                     grassName = GetValidLayerName(baseName.split('.', -1)[0])
                     projectionMatch = hasRastSameProjAsLocation(dsn)
-                    projectionMatchCaption = getProjMatchCaption(projectionMatch)
-                    listData.append((layerId, baseName, projectionMatchCaption, grassName))
-                    data.append((layerId, baseName,  int(projectionMatch), grassName))
+                    projectionMatchCaption = getProjMatchCaption(
+                        projectionMatch)
+                    listData.append(
+                        (layerId, baseName, projectionMatchCaption, grassName))
+                    data.append(
+                        (layerId, baseName, int(projectionMatch), grassName))
                     layerId += 1
-        
+
         # emit signal
         self.reloadDataRequired.emit(listData=listData, data=data)
 
@@ -2054,22 +2215,24 @@
                 if self.ogr:
                     cmd = 'v.external'
                 else:
-                    cmd =  'r.external'
+                    cmd = 'r.external'
             else:
                 if self.ogr:
                     cmd = 'v.in.ogr'
                 else:
                     cmd = 'r.in.gdal'
 
-        RunCommand('g.manual', entry = cmd)
+        RunCommand('g.manual', entry=cmd)
 
+
 class ProjSelect(wx.ComboBox):
     """Widget for selecting input raster/vector map used by
     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,
-                                         style = wx.CB_READONLY, **kwargs)
+
+    def __init__(self, parent, isRaster, id=wx.ID_ANY,
+                 size=globalvar.DIALOG_COMBOBOX_SIZE, **kwargs):
+        super(ProjSelect, self).__init__(parent, id, size=size,
+                                         style=wx.CB_READONLY, **kwargs)
         self.SetName("ProjSelect")
         self.isRaster = isRaster
 
@@ -2083,20 +2246,20 @@
             mapset = grass.gisenv()['MAPSET']
         if self.isRaster:
             ret = RunCommand('r.proj',
-                             quiet = True,
-                             read = True,
-                             flags = 'l',
-                             dbase = dbase,
-                             location = location,
-                             mapset = mapset)
+                             quiet=True,
+                             read=True,
+                             flags='l',
+                             dbase=dbase,
+                             location=location,
+                             mapset=mapset)
         else:
             ret = RunCommand('v.proj',
-                             quiet = True,
-                             read = True,
-                             flags = 'l',
-                             dbase = dbase,
-                             location = location,
-                             mapset = mapset)
+                             quiet=True,
+                             read=True,
+                             flags='l',
+                             dbase=dbase,
+                             location=location,
+                             mapset=mapset)
         listMaps = list()
         if ret:
             for line in ret.splitlines():
@@ -2106,24 +2269,26 @@
         self.SetItems(listMaps)
         self.SetValue('')
 
+
 class ElementSelect(wx.Choice):
-    def __init__(self, parent, id = wx.ID_ANY, elements = None,
-                 size = globalvar.DIALOG_COMBOBOX_SIZE,
+
+    def __init__(self, parent, id=wx.ID_ANY, elements=None,
+                 size=globalvar.DIALOG_COMBOBOX_SIZE,
                  **kwargs):
         """Widget for selecting GIS element
 
         :param parent: parent window
         :param elements: filter elements
         """
-        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')
+        p = task.get_param(value='type')
         self.values = p.get('values', [])
         self.valuesDesc = p.get('values_desc', [])
-        
+
         if elements:
             values = []
             valuesDesc = []
@@ -2134,7 +2299,7 @@
                     valuesDesc.append(self.valuesDesc[idx])
             self.values = values
             self.valuesDesc = valuesDesc
-        
+
         self.SetItems(self.valuesDesc)
 
     def GetValue(self, name):
@@ -2147,32 +2312,33 @@
             return self.values[idx]
         return ''
 
+
 class OgrTypeSelect(wx.Panel):
+
     def __init__(self, parent, panel, **kwargs):
         """Widget to choose OGR feature type
 
         :param parent: parent window
         :param panel: wx.Panel instance used as parent window
         """
-        wx.Panel.__init__(self, parent = panel, id = wx.ID_ANY)
+        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")))
+        self.ftype = wx.Choice(parent=self, id=wx.ID_ANY, size=(
+            200, -1), choices=(_("Point"), _("LineString"), _("Polygon")))
         self._layout()
 
     def _layout(self):
         """Do layout"""
         sizer = wx.BoxSizer(wx.HORIZONTAL)
-        sizer.Add(item = wx.StaticText(parent = self,
-                                       id = wx.ID_ANY,
-                                       label = _("Feature type:")),
-                  proportion = 1,
-                  flag = wx.ALIGN_CENTER_VERTICAL,
-                  border  = 5)
-        sizer.Add(item = self.ftype,
-                  proportion = 0,
-                  flag = wx.EXPAND | wx.ALIGN_RIGHT)
+        sizer.Add(item=wx.StaticText(parent=self,
+                                     id=wx.ID_ANY,
+                                     label=_("Feature type:")),
+                  proportion=1,
+                  flag=wx.ALIGN_CENTER_VERTICAL,
+                  border=5)
+        sizer.Add(item=self.ftype,
+                  proportion=0,
+                  flag=wx.EXPAND | wx.ALIGN_RIGHT)
 
         self.SetSizer(sizer)
         sizer.Fit(self)
@@ -2190,8 +2356,10 @@
         elif sel == 2:
             return 'boundary'
 
+
 class CoordinatesSelect(wx.Panel):
-    def __init__(self, parent, giface, multiple = False, **kwargs):
+
+    def __init__(self, parent, giface, multiple=False, **kwargs):
         """Widget to get coordinates from map window  by mouse click
 
         :param parent: parent window
@@ -2200,7 +2368,7 @@
         """
         self._giface = giface
         self.multiple = multiple
-        self.mapWin   = None
+        self.mapWin = None
         self.drawMapWin = None
 
         super(CoordinatesSelect, self).__init__(parent=parent, id=wx.ID_ANY)
@@ -2209,28 +2377,32 @@
                                        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,
-                                                                   size=globalvar.DIALOG_COLOR_SIZE)
+        icon = wx.Bitmap(
+            os.path.join(
+                globalvar.ICONDIR,
+                "grass",
+                "pointer.png"))
+        self.buttonInsCoords = buttons.ThemedGenBitmapToggleButton(
+            parent=self, id=wx.ID_ANY, bitmap=icon, size=globalvar.DIALOG_COLOR_SIZE)
         self.registered = False
         self.buttonInsCoords.Bind(wx.EVT_BUTTON, self._onClick)
 
         mapdisp = self._giface.GetMapDisplay()
         if mapdisp:
             switcher = mapdisp.GetToolSwitcher()
-            switcher.AddCustomToolToGroup(group='mouseUse',
-                                          btnId=self.buttonInsCoords.GetId(),
-                                          toggleHandler=self.buttonInsCoords.SetValue)
+            switcher.AddCustomToolToGroup(
+                group='mouseUse',
+                btnId=self.buttonInsCoords.GetId(),
+                toggleHandler=self.buttonInsCoords.SetValue)
         self._doLayout()
-        self.coordsField.Bind(wx.EVT_TEXT, lambda event : self._draw(delay=1))
+        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,
-                             flag = wx.EXPAND)
-        self.dialogSizer.Add(item = self.buttonInsCoords)
+        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):
@@ -2248,9 +2420,8 @@
             self.registered = True
             self._giface.GetMapDisplay().Raise()
         else:
-            if self.mapWin and \
-               self.mapWin.UnregisterMouseEventHandler(wx.EVT_LEFT_DOWN,
-                                                       self._onMapClickHandler):
+            if self.mapWin and self.mapWin.UnregisterMouseEventHandler(
+                    wx.EVT_LEFT_DOWN, self._onMapClickHandler):
                 self.registered = False
                 return
 
@@ -2264,20 +2435,23 @@
             self.drawCleanUp()
             if self.mapWin:
                 self.drawMapWin = self.mapWin
-                self.pointsToDraw = self.drawMapWin.RegisterGraphicsToDraw(graphicsType="point")
+                self.pointsToDraw = self.drawMapWin.RegisterGraphicsToDraw(
+                    graphicsType="point")
 
         if self.drawMapWin:
-                items = self.pointsToDraw.GetAllItems()
-                for i in items:
-                    self.pointsToDraw.DeleteItem(i)
+            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):
-                        i = i * 2
-                        self.pointsToDraw.AddItem(coords=(coords[i], coords[i + 1]))
+            coords = self._getCoords()
+            if coords is not None:
+                for i in range(len(coords) / 2):
+                    i = i * 2
+                    self.pointsToDraw.AddItem(
+                        coords=(coords[i], coords[i + 1]))
 
-                self._giface.updateMap.emit(render=False, renderVector=False, delay=delay)
+            self._giface.updateMap.emit(
+                render=False, renderVector=False, delay=delay)
 
     def _getCoords(self):
         """Get list of coordinates.
@@ -2325,36 +2499,41 @@
         """Get TextCtrl widget"""
         return self.coordsField
 
+
 class VectorCategorySelect(wx.Panel):
     """Widget that allows interactive selection of vector features"""
+
     def __init__(self, parent, giface, task=None):
         super(VectorCategorySelect, self).__init__(parent=parent, id=wx.ID_ANY)
-        self.task=task
+        self.task = task
         self.parent = parent
         self.giface = giface
-        
+
         self.selectedFeatures = None
         self.registered = False
         self._vectorSelect = None
 
         self.mapdisp = self.giface.GetMapDisplay()
-        
+
         self.catsField = wx.TextCtrl(parent=self, id=wx.ID_ANY,
                                      size=globalvar.DIALOG_TEXTCTRL_SIZE)
-        
-        icon = wx.Bitmap(os.path.join(globalvar.ICONDIR, "grass", "select.png"))
-        self.buttonVecSelect = buttons.ThemedGenBitmapToggleButton(parent=self, id=wx.ID_ANY,
-                                                                   bitmap=icon,
-                                                                   size=globalvar.DIALOG_COLOR_SIZE)
+
+        icon = wx.Bitmap(
+            os.path.join(
+                globalvar.ICONDIR,
+                "grass",
+                "select.png"))
+        self.buttonVecSelect = buttons.ThemedGenBitmapToggleButton(
+            parent=self, id=wx.ID_ANY, bitmap=icon, size=globalvar.DIALOG_COLOR_SIZE)
         self.buttonVecSelect.Bind(wx.EVT_BUTTON, self._onClick)
 
-        
         if self.mapdisp:
             switcher = self.mapdisp.GetToolSwitcher()
-            switcher.AddCustomToolToGroup(group='mouseUse',
-                                          btnId=self.buttonVecSelect.GetId(),
-                                          toggleHandler=self.buttonVecSelect.SetValue)
-        
+            switcher.AddCustomToolToGroup(
+                group='mouseUse',
+                btnId=self.buttonVecSelect.GetId(),
+                toggleHandler=self.buttonVecSelect.SetValue)
+
         self._layout()
 
     def _isMapSelected(self):
@@ -2363,9 +2542,10 @@
         layerList = self.giface.GetLayerList()
         layerSelected = layerList.GetSelectedLayer()
         if layerSelected is None:
-            GWarning(_("No vector map selected in layer manager. Operation canceled."))
+            GWarning(
+                _("No vector map selected in layer manager. Operation canceled."))
             return False
-        
+
         return True
 
     def _chckMap(self):
@@ -2373,13 +2553,16 @@
         if self._isMapSelected():
             layerList = self.giface.GetLayerList()
             layerSelected = layerList.GetSelectedLayer()
-            inputName=self.task.get_param('input')
+            inputName = self.task.get_param('input')
             if inputName['value'] != str(layerSelected):
                 if inputName['value'] == '' or inputName['value'] is None:
                     GWarning(_("Input vector map is not selected"))
                     return False
-                GWarning(_("Input vector map <%s> and selected map <%s> in layer manager are different. "
-                           "Operation canceled.") % (inputName['value'], str(layerSelected)))
+                GWarning(
+                    _(
+                        "Input vector map <%s> and selected map <%s> in layer manager are different. "
+                        "Operation canceled.") %
+                    (inputName['value'], str(layerSelected)))
                 return False
             return True
         return False
@@ -2400,10 +2583,10 @@
                     switcher = self.mapdisp.GetToolSwitcher()
                     switcher.ToolChanged(self.buttonVecSelect.GetId())
 
-                self._vectorSelect = VectorSelectBase(self.mapdisp, self.giface)
-                if self.mapdisp.GetWindow().RegisterMouseEventHandler(wx.EVT_LEFT_DOWN,
-                                                                      self._onMapClickHandler,
-                                                                      'cross') == False:
+                self._vectorSelect = VectorSelectBase(
+                    self.mapdisp, self.giface)
+                if self.mapdisp.GetWindow().RegisterMouseEventHandler(
+                        wx.EVT_LEFT_DOWN, self._onMapClickHandler, 'cross') == False:
                     return
                 self.registered = True
                 self.mapdisp.Raise()
@@ -2413,7 +2596,7 @@
     def OnClose(self, event=None):
         if not self.mapdisp:
             return
-        
+
         switcher = self.mapdisp.GetToolSwitcher()
         switcher.RemoveCustomToolFromGroup(self.buttonVecSelect.GetId())
         if self._vectorSelect is not None:
@@ -2431,12 +2614,14 @@
             if not self._isMapSelected():
                 self.OnClose()
             else:
-                self.catsField.SetValue(self._vectorSelect.GetLineStringSelectedCats())
+                self.catsField.SetValue(
+                    self._vectorSelect.GetLineStringSelectedCats())
         else:
             if not self._chckMap():
                 self.OnClose()
             else:
-                self.catsField.SetValue(self._vectorSelect.GetLineStringSelectedCats())
+                self.catsField.SetValue(
+                    self._vectorSelect.GetLineStringSelectedCats())
 
     def GetTextWin(self):
         return self.catsField
@@ -2456,16 +2641,18 @@
         self.dialogSizer.Add(item=self.buttonVecSelect)
         self.SetSizer(self.dialogSizer)
 
+
 class SignatureSelect(wx.ComboBox):
     """Widget for selecting signatures"""
-    def __init__(self, parent, element, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
-                 **kwargs):
-        super(SignatureSelect, self).__init__(parent, id, size = size,
+
+    def __init__(self, parent, element, id=wx.ID_ANY,
+                 size=globalvar.DIALOG_GSELECT_SIZE, **kwargs):
+        super(SignatureSelect, self).__init__(parent, id, size=size,
                                               **kwargs)
         self.element = element
         self.SetName("SignatureSelect")
 
-    def Insert(self, group, subgroup = None):
+    def Insert(self, group, subgroup=None):
         """Insert signatures for defined group/subgroup
 
         :param group: group name (can be fully-qualified)
@@ -2480,8 +2667,10 @@
             name = group
             mapset = gisenv['MAPSET']
 
-        path = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'], mapset,
-                            'group', name)
+        path = os.path.join(
+            gisenv['GISDBASE'],
+            gisenv['LOCATION_NAME'],
+            mapset, 'group', name)
 
         if subgroup:
             path = os.path.join(path, 'subgroup', subgroup)
@@ -2494,11 +2683,13 @@
             self.SetItems([])
         self.SetValue('')
 
+
 class SeparatorSelect(wx.ComboBox):
     """Widget for selecting seperator"""
-    def __init__(self, parent, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
-                 **kwargs):
-        super(SeparatorSelect, self).__init__(parent, id, size = size,
+
+    def __init__(self, parent, id=wx.ID_ANY,
+                 size=globalvar.DIALOG_GSELECT_SIZE, **kwargs):
+        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/mapdisp.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/mapdisp.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gui_core/mapdisp.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -24,8 +24,8 @@
 
 import wx
 
-from core        import globalvar
-from core.debug  import Debug
+from core import globalvar
+from core.debug import Debug
 from core.utils import _
 from gui_core.toolbars import ToolSwitcher
 
@@ -34,14 +34,14 @@
 
 class MapFrameBase(wx.Frame):
     """Base class for map display window
-    
+
     Derived class must use (create and initialize) \c statusbarManager
     or override
     GetProperty(), SetProperty() and HasProperty() methods.
-    
+
     Several methods has to be overriden or
     \c NotImplementedError("MethodName") will be raised.
-    
+
     If derived class enables and disables auto-rendering,
     it should override IsAutoRendered method.
 
@@ -52,17 +52,18 @@
     one map will be current.
     Current instances of map window and map renderer should be returned
     by methods GetWindow() and GetMap() respectively.
-    
+
     AUI manager is stored in \c self._mgr.
     """
-    def __init__(self, parent = None, id = wx.ID_ANY, title = '',
-                 style = wx.DEFAULT_FRAME_STYLE,
-                 auimgr = None, name = '', **kwargs):
+
+    def __init__(self, parent=None, id=wx.ID_ANY, title='',
+                 style=wx.DEFAULT_FRAME_STYLE,
+                 auimgr=None, name='', **kwargs):
         """
 
         .. warning::
             Use \a auimgr parameter only if you know what you are doing.
-        
+
         :param parent: gui parent
         :param id: wx id
         :param title: window title
@@ -72,42 +73,57 @@
         :param name: frame name
         :param kwargs: arguments passed to \c wx.Frame
         """
-        
-        self.parent     = parent
-        
-        wx.Frame.__init__(self, parent, id, title, style = style, name = name, **kwargs)
-                
+
+        self.parent = parent
+
+        wx.Frame.__init__(
+            self,
+            parent,
+            id,
+            title,
+            style=style,
+            name=name,
+            **kwargs)
+
         #
         # set the size & system icon
         #
         self.SetClientSize(self.GetSize())
         self.iconsize = (16, 16)
 
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass_map.ico'), wx.BITMAP_TYPE_ICO))
-        
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass_map.ico'),
+                wx.BITMAP_TYPE_ICO))
+
         # toolbars
         self.toolbars = {}
-        
+
         #
         # Fancy gui
         #
-        if auimgr == None:
+        if auimgr is None:
             from wx.aui import AuiManager
             self._mgr = AuiManager(self)
         else:
             self._mgr = auimgr
-        
+
         # handles switching between tools in different toolbars
         self._toolSwitcher = ToolSwitcher()
         self._toolSwitcher.toggleToolChanged.connect(self._onToggleTool)
 
         # set accelerator table (fullscreen, close window)
         accelTable = []
-        for wxId, handler, entry, kdb in ((wx.NewId(), self.OnFullScreen, wx.ACCEL_NORMAL, wx.WXK_F11),
-                                          (wx.NewId(), self.OnCloseWindow, wx.ACCEL_CTRL, ord('W'))):
+        for wxId, handler, entry, kdb in (
+            (wx.NewId(),
+             self.OnFullScreen, wx.ACCEL_NORMAL, wx.WXK_F11),
+            (wx.NewId(),
+             self.OnCloseWindow, wx.ACCEL_CTRL, ord('W'))):
             self.Bind(wx.EVT_MENU, handler, id=wxId)
             accelTable.append((entry, kdb, wxId))
-        
+
         self.SetAcceleratorTable(wx.AcceleratorTable(accelTable))
 
     def _initMap(self, Map):
@@ -116,10 +132,10 @@
         if not grass.find_program('g.region', '--help'):
             sys.exit(_("GRASS module '%s' not found. Unable to start map "
                        "display window.") % 'g.region')
-        
+
         Debug.msg(2, "MapFrame._initMap():")
         Map.ChangeMapSize(self.GetClientSize())
-        Map.region = Map.GetRegion() # g.region -upgc
+        Map.region = Map.GetRegion()  # g.region -upgc
         # self.Map.SetRegion() # adjust region to match display window
 
     def _resize(self):
@@ -138,7 +154,7 @@
         """Adjust statusbar on changing size"""
         # reposition checkbox in statusbar
         self.StatusbarReposition()
-        
+
         # update statusbar
         self.StatusbarUpdate()
 
@@ -152,89 +168,89 @@
 
     def OnCloseWindow(self, event):
         self.Destroy()
-        
+
     def GetToolSwitcher(self):
         return self._toolSwitcher
 
     def SetProperty(self, name, value):
         """Sets property"""
         self.statusbarManager.SetProperty(name, value)
-        
+
     def GetProperty(self, name):
         """Returns property"""
         return self.statusbarManager.GetProperty(name)
-        
+
     def HasProperty(self, name):
         """Checks whether object has property"""
         return self.statusbarManager.HasProperty(name)
-    
+
     def GetPPM(self):
         """Get pixel per meter
-        
+
         .. todo::
             now computed every time, is it necessary?
-        
+
         .. todo::
             enable user to specify ppm (and store it in UserSettings)
         """
         # TODO: need to be fixed...
-        ### screen X region problem
-        ### user should specify ppm
+        # screen X region problem
+        # user should specify ppm
         dc = wx.ScreenDC()
         dpSizePx = wx.DisplaySize()   # display size in pixels
-        dpSizeMM = wx.DisplaySizeMM() # display size in mm (system)
-        dpSizeIn = (dpSizeMM[0] / 25.4, dpSizeMM[1] / 25.4) # inches
-        sysPpi  = dc.GetPPI()
+        dpSizeMM = wx.DisplaySizeMM()  # display size in mm (system)
+        dpSizeIn = (dpSizeMM[0] / 25.4, dpSizeMM[1] / 25.4)  # inches
+        sysPpi = dc.GetPPI()
         comPpi = (dpSizePx[0] / dpSizeIn[0],
                   dpSizePx[1] / dpSizeIn[1])
 
         ppi = comPpi                  # pixel per inch
-        ppm = ((ppi[0] / 2.54) * 100, # pixel per meter
-                    (ppi[1] / 2.54) * 100)
-        
+        ppm = ((ppi[0] / 2.54) * 100,  # pixel per meter
+               (ppi[1] / 2.54) * 100)
+
         Debug.msg(4, "MapFrameBase.GetPPM(): size: px=%d,%d mm=%f,%f "
-                  "in=%f,%f ppi: sys=%d,%d com=%d,%d; ppm=%f,%f" % \
+                  "in=%f,%f ppi: sys=%d,%d com=%d,%d; ppm=%f,%f" %
                   (dpSizePx[0], dpSizePx[1], dpSizeMM[0], dpSizeMM[1],
                    dpSizeIn[0], dpSizeIn[1],
                    sysPpi[0], sysPpi[1], comPpi[0], comPpi[1],
                    ppm[0], ppm[1]))
-        
+
         return ppm
-    
-    def SetMapScale(self, value, map = None):
+
+    def SetMapScale(self, value, map=None):
         """Set current map scale
-        
+
         :param value: scale value (n if scale is 1:n)
         :param map: Map instance (if none self.Map is used)
         """
         if not map:
             map = self.Map
-        
+
         region = self.Map.region
         dEW = value * (region['cols'] / self.GetPPM()[0])
         dNS = value * (region['rows'] / self.GetPPM()[1])
         region['n'] = region['center_northing'] + dNS / 2.
         region['s'] = region['center_northing'] - dNS / 2.
-        region['w'] = region['center_easting']  - dEW / 2.
-        region['e'] = region['center_easting']  + dEW / 2.
-        
+        region['w'] = region['center_easting'] - dEW / 2.
+        region['e'] = region['center_easting'] + dEW / 2.
+
         # add to zoom history
         self.GetWindow().ZoomHistory(region['n'], region['s'],
-                                   region['e'], region['w'])
-    
-    def GetMapScale(self, map = None):
+                                     region['e'], region['w'])
+
+    def GetMapScale(self, map=None):
         """Get current map scale
-        
+
         :param map: Map instance (if none self.Map is used)
         """
         if not map:
             map = self.GetMap()
-        
+
         region = map.region
         ppm = self.GetPPM()
 
         heightCm = region['rows'] / ppm[1] * 100
-        widthCm  = region['cols'] / ppm[0] * 100
+        widthCm = region['cols'] / ppm[0] * 100
 
         Debug.msg(4, "MapFrame.GetMapScale(): width_cm=%f, height_cm=%f" %
                   (widthCm, heightCm))
@@ -242,19 +258,20 @@
         xscale = (region['e'] - region['w']) / (region['cols'] / ppm[0])
         yscale = (region['n'] - region['s']) / (region['rows'] / ppm[1])
         scale = (xscale + yscale) / 2.
-        
-        Debug.msg(3, "MapFrame.GetMapScale(): xscale=%f, yscale=%f -> scale=%f" % \
-                      (xscale, yscale, scale))
-        
+
+        Debug.msg(
+            3, "MapFrame.GetMapScale(): xscale=%f, yscale=%f -> scale=%f" %
+            (xscale, yscale, scale))
+
         return scale
-        
+
     def GetProgressBar(self):
         """Returns progress bar
-        
+
         Progress bar can be used by other classes.
         """
         return self.statusbarManager.GetProgressBar()
-        
+
     def GetMap(self):
         """Returns current map (renderer) instance"""
         raise NotImplementedError("GetMap")
@@ -266,7 +283,7 @@
     def GetWindows(self):
         """Returns list of map windows"""
         raise NotImplementedError("GetWindows")
-        
+
     def GetMapToolbar(self):
         """Returns toolbar with zooming tools"""
         raise NotImplementedError("GetMapToolbar")
@@ -284,7 +301,7 @@
         if self.statusbarManager:
             Debug.msg(5, "MapFrameBase.StatusbarUpdate()")
             self.statusbarManager.Update()
-        
+
     def IsAutoRendered(self):
         """Check if auto-rendering is enabled"""
         # TODO: this is now not the right place to access this attribute
@@ -292,7 +309,7 @@
         # and pass the right object in the init of derived class?
         # or do not use this method at all, let mapwindow decide
         return self.mapWindowProperties.autoRender
-        
+
     def CoordinatesChanged(self):
         """Shows current coordinates on statusbar.
         """
@@ -301,40 +318,40 @@
         if self.statusbarManager:
             if self.statusbarManager.GetMode() == 0:
                 self.statusbarManager.ShowItem('coordinates')
-        
+
     def StatusbarReposition(self):
         """Reposition items in statusbar"""
         if self.statusbarManager:
             self.statusbarManager.Reposition()
-        
-    def StatusbarEnableLongHelp(self, enable = True):
+
+    def StatusbarEnableLongHelp(self, enable=True):
         """Enable/disable toolbars long help"""
         for toolbar in self.toolbars.itervalues():
             toolbar.EnableLongHelp(enable)
-        
+
     def IsStandalone(self):
         """Check if map frame is standalone"""
         raise NotImplementedError("IsStandalone")
-   
+
     def OnRender(self, event):
         """Re-render map composition (each map layer)
         """
         raise NotImplementedError("OnRender")
-        
+
     def OnDraw(self, event):
         """Re-display current map composition
         """
-        self.MapWindow.UpdateMap(render = False)
-        
+        self.MapWindow.UpdateMap(render=False)
+
     def OnErase(self, event):
         """Erase the canvas
         """
         self.MapWindow.EraseMap()
-        
+
     def OnZoomIn(self, event):
         """Zoom in the map."""
         self.MapWindow.SetModeZoomIn()
-        
+
     def OnZoomOut(self, event):
         """Zoom out the map."""
         self.MapWindow.SetModeZoomOut()
@@ -364,20 +381,20 @@
         """Zoom last (previously stored position)
         """
         self.MapWindow.ZoomBack()
-        
+
     def OnZoomToMap(self, event):
         """
         Set display extents to match selected raster (including NULLs)
         or vector map.
         """
-        self.MapWindow.ZoomToMap(layers = self.Map.GetListOfLayers())
-    
+        self.MapWindow.ZoomToMap(layers=self.Map.GetListOfLayers())
+
     def OnZoomToWind(self, event):
         """Set display geometry to match computational region
         settings (set with g.region)
         """
         self.MapWindow.ZoomToWind()
-        
+
     def OnZoomToDefault(self, event):
         """Set display geometry to match default region settings
         """
@@ -386,21 +403,22 @@
 
 class SingleMapFrame(MapFrameBase):
     """Frame with one map window.
-    
+
     It is base class for frames which needs only one map.
-    
+
     Derived class should have \c self.MapWindow or
     it has to override GetWindow() methods.
-    
+
     @note To access maps use getters only
     (when using class or when writing class itself).
     """
-    def __init__(self, parent = None, giface = None, id = wx.ID_ANY, title = '',
-                 style = wx.DEFAULT_FRAME_STYLE,
-                 Map = None,
-                 auimgr = None, name = '', **kwargs):
+
+    def __init__(self, parent=None, giface=None, id=wx.ID_ANY, title='',
+                 style=wx.DEFAULT_FRAME_STYLE,
+                 Map=None,
+                 auimgr=None, name='', **kwargs):
         """
-        
+
         :param parent: gui parent
         :param id: wx id
         :param title: window title
@@ -410,9 +428,9 @@
         :param kwargs: arguments passed to MapFrameBase
         """
 
-        MapFrameBase.__init__(self, parent = parent, id = id, title = title,
-                              style = style,
-                              auimgr = auimgr, name = name, **kwargs)
+        MapFrameBase.__init__(self, parent=parent, id=id, title=title,
+                              style=style,
+                              auimgr=auimgr, name=name, **kwargs)
 
         self.Map = Map       # instance of render.Map
 
@@ -420,8 +438,8 @@
         # initialize region values
         #
         if self.Map:
-            self._initMap(Map = self.Map)
-        
+            self._initMap(Map=self.Map)
+
     def GetMap(self):
         """Returns map (renderer) instance"""
         return self.Map
@@ -429,7 +447,7 @@
     def GetWindow(self):
         """Returns map window"""
         return self.MapWindow
-        
+
     def GetWindows(self):
         """Returns list of map windows"""
         return [self.MapWindow]
@@ -437,42 +455,43 @@
     def OnRender(self, event):
         """Re-render map composition (each map layer)
         """
-        self.GetWindow().UpdateMap(render = True, renderVector = True)
-        
+        self.GetWindow().UpdateMap(render=True, renderVector=True)
+
         # update statusbar
         self.StatusbarUpdate()
-        
 
+
 class DoubleMapFrame(MapFrameBase):
     """Frame with two map windows.
-    
+
     It is base class for frames which needs two maps.
     There is no primary and secondary map. Both maps are equal.
     However, one map is current.
-    
+
     It is expected that derived class will call _bindWindowsActivation()
     when both map windows will be initialized.
-    
+
     Drived class should have method GetMapToolbar() returns toolbar
     which has methods SetActiveMap() and Enable().
-    
+
     @note To access maps use getters only
     (when using class or when writing class itself).
-    
+
     .. todo:
         Use it in GCP manager (probably changes to both DoubleMapFrame
         and GCP MapFrame will be neccessary).
     """
-    def __init__(self, parent = None, id = wx.ID_ANY, title = None,
-                 style = wx.DEFAULT_FRAME_STYLE,
-                 firstMap = None, secondMap = None,
-                 auimgr = None, name = None, **kwargs):
+
+    def __init__(self, parent=None, id=wx.ID_ANY, title=None,
+                 style=wx.DEFAULT_FRAME_STYLE,
+                 firstMap=None, secondMap=None,
+                 auimgr=None, name=None, **kwargs):
         """
-        
+
         \a firstMap is set as active (by assign it to \c self.Map).
         Derived class should assging to \c self.MapWindow to make one
         map window current by dafault.
-        
+
         :param parent: gui parent
         :param id: wx id
         :param title: window title
@@ -480,11 +499,11 @@
         :param name: frame name
         :param kwargs: arguments passed to MapFrameBase
         """
-        
-        MapFrameBase.__init__(self, parent = parent, id = id, title = title,
-                              style = style,
-                              auimgr = auimgr, name = name, **kwargs)
-        
+
+        MapFrameBase.__init__(self, parent=parent, id=id, title=title,
+                              style=style,
+                              auimgr=auimgr, name=name, **kwargs)
+
         self.firstMap = firstMap
         self.secondMap = secondMap
         self.Map = firstMap
@@ -492,15 +511,15 @@
         #
         # initialize region values
         #
-        self._initMap(Map = self.firstMap)
-        self._initMap(Map = self.secondMap)
+        self._initMap(Map=self.firstMap)
+        self._initMap(Map=self.secondMap)
         self._bindRegions = False
-    
+
     def _bindWindowsActivation(self):
         self.GetFirstWindow().Bind(wx.EVT_ENTER_WINDOW, self.ActivateFirstMap)
         self.GetSecondWindow().Bind(wx.EVT_ENTER_WINDOW, self.ActivateSecondMap)
-    
-    def _onToggleTool(self, id): 
+
+    def _onToggleTool(self, id):
         if self._toolSwitcher.IsToolInGroup(id, 'mouseUse'):
             self.GetFirstWindow().UnregisterAllHandlers()
             self.GetSecondWindow().UnregisterAllHandlers()
@@ -509,41 +528,41 @@
         """Returns first Map instance
         """
         return self.firstMap
-        
+
     def GetSecondMap(self):
         """Returns second Map instance
         """
         return self.secondMap
-        
+
     def GetFirstWindow(self):
         """Get first map window"""
         return self.firstMapWindow
-    
+
     def GetSecondWindow(self):
         """Get second map window"""
         return self.secondMapWindow
-    
+
     def GetMap(self):
         """Returns current map (renderer) instance
-        
+
         @note Use this method to access current map renderer.
         (It is not guarented that current map will be stored in
         \c self.Map in future versions.)
         """
         return self.Map
-    
+
     def GetWindow(self):
         """Returns current map window
-        
+
         :func:`GetMap()`
         """
         return self.MapWindow
-    
+
     def GetWindows(self):
         """Return list of all windows"""
         return [self.firstMapWindow, self.secondMapWindow]
-    
-    def ActivateFirstMap(self, event = None):
+
+    def ActivateFirstMap(self, event=None):
         """Make first Map and MapWindow active and (un)bind regions of the two Maps."""
         if self.MapWindow == self.firstMapWindow:
             return
@@ -555,20 +574,23 @@
         # bind/unbind regions
         if self._bindRegions:
             self.firstMapWindow.zoomChanged.connect(self.OnZoomChangedFirstMap)
-            self.secondMapWindow.zoomChanged.disconnect(self.OnZoomChangedSecondMap)
+            self.secondMapWindow.zoomChanged.disconnect(
+                self.OnZoomChangedSecondMap)
 
-    def ActivateSecondMap(self, event = None):
+    def ActivateSecondMap(self, event=None):
         """Make second Map and MapWindow active and (un)bind regions of the two Maps."""
         if self.MapWindow == self.secondMapWindow:
-            return        
+            return
 
         self.Map = self.secondMap
         self.MapWindow = self.secondMapWindow
         self.GetMapToolbar().SetActiveMap(1)
 
         if self._bindRegions:
-            self.secondMapWindow.zoomChanged.connect(self.OnZoomChangedSecondMap)
-            self.firstMapWindow.zoomChanged.disconnect(self.OnZoomChangedFirstMap)
+            self.secondMapWindow.zoomChanged.connect(
+                self.OnZoomChangedSecondMap)
+            self.firstMapWindow.zoomChanged.disconnect(
+                self.OnZoomChangedFirstMap)
 
     def SetBindRegions(self, on):
         """Set or unset binding display regions."""
@@ -576,14 +598,18 @@
 
         if on:
             if self.MapWindow == self.firstMapWindow:
-                self.firstMapWindow.zoomChanged.connect(self.OnZoomChangedFirstMap)
+                self.firstMapWindow.zoomChanged.connect(
+                    self.OnZoomChangedFirstMap)
             else:
-                self.secondMapWindow.zoomChanged.connect(self.OnZoomChangedSecondMap)
+                self.secondMapWindow.zoomChanged.connect(
+                    self.OnZoomChangedSecondMap)
         else:
             if self.MapWindow == self.firstMapWindow:
-                self.firstMapWindow.zoomChanged.disconnect(self.OnZoomChangedFirstMap)
+                self.firstMapWindow.zoomChanged.disconnect(
+                    self.OnZoomChangedFirstMap)
             else:
-                self.secondMapWindow.zoomChanged.disconnect(self.OnZoomChangedSecondMap)
+                self.secondMapWindow.zoomChanged.disconnect(
+                    self.OnZoomChangedSecondMap)
 
     def OnZoomChangedFirstMap(self):
         """Display region of the first window (Map) changed.
@@ -593,7 +619,7 @@
         """
         region = self.GetFirstMap().GetCurrentRegion()
         self.GetSecondMap().region.update(region)
-        self.Render(mapToRender = self.GetSecondWindow())
+        self.Render(mapToRender=self.GetSecondWindow())
 
     def OnZoomChangedSecondMap(self):
         """Display region of the second window (Map) changed.
@@ -603,7 +629,7 @@
         """
         region = self.GetSecondMap().GetCurrentRegion()
         self.GetFirstMap().region.update(region)
-        self.Render(mapToRender = self.GetFirstWindow())
+        self.Render(mapToRender=self.GetFirstWindow())
 
     def OnZoomIn(self, event):
         """Zoom in the map."""
@@ -614,7 +640,7 @@
         """Zoom out the map."""
         self.GetFirstWindow().SetModeZoomOut()
         self.GetSecondWindow().SetModeZoomOut()
-        
+
     def OnPan(self, event):
         """Panning, set mouse to pan"""
         self.GetFirstWindow().SetModePan()
@@ -633,35 +659,36 @@
     def OnRender(self, event):
         """Re-render map composition (each map layer)
         """
-        self.Render(mapToRender = self.GetFirstWindow())
-        self.Render(mapToRender = self.GetSecondWindow())
-    
+        self.Render(mapToRender=self.GetFirstWindow())
+        self.Render(mapToRender=self.GetSecondWindow())
+
     def Render(self, mapToRender):
         """Re-render map composition"""
-        mapToRender.UpdateMap(render = True,
-                              renderVector = mapToRender == self.GetFirstWindow())
-        
+        mapToRender.UpdateMap(
+            render=True,
+            renderVector=mapToRender == self.GetFirstWindow())
+
         # update statusbar
         self.StatusbarUpdate()
-        
+
     def OnErase(self, event):
         """Erase the canvas
         """
-        self.Erase(mapToErase = self.GetFirstWindow())
-        self.Erase(mapToErase = self.GetSecondWindow())
-        
+        self.Erase(mapToErase=self.GetFirstWindow())
+        self.Erase(mapToErase=self.GetSecondWindow())
+
     def Erase(self, mapToErase):
         """Erase the canvas
         """
         mapToErase.EraseMap()
-        
+
     def OnDraw(self, event):
         """Re-display current map composition
         """
-        self.Draw(mapToDraw = self.GetFirstWindow())
-        self.Draw(mapToDraw = self.GetSecondWindow())
-        
+        self.Draw(mapToDraw=self.GetFirstWindow())
+        self.Draw(mapToDraw=self.GetSecondWindow())
+
     def Draw(self, mapToDraw):
         """Re-display current map composition
         """
-        mapToDraw.UpdateMap(render = False)
+        mapToDraw.UpdateMap(render=False)

Modified: grass/trunk/gui/wxpython/gui_core/menu.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/menu.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gui_core/menu.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -21,17 +21,19 @@
 import re
 import wx
 
-from core              import globalvar
-from core              import utils
-from core.gcmd         import EncodeString
+from core import globalvar
+from core import utils
+from core.gcmd import EncodeString
 from core.utils import _
-from gui_core.widgets  import SearchModuleWidget
+from gui_core.widgets import SearchModuleWidget
 from gui_core.treeview import CTreeView
 from icons.icon import MetaIcon
 
 from grass.pydispatch.signal import Signal
 
+
 class Menu(wx.MenuBar):
+
     def __init__(self, parent, model):
         """Creates menubar"""
         wx.MenuBar.__init__(self)
@@ -42,7 +44,7 @@
 
         for child in self.model.root.children:
             self.Append(self._createMenu(child), child.label)
-        
+
     def _createMenu(self, node):
         """Creates menu"""
         menu = wx.Menu()
@@ -54,15 +56,16 @@
             else:
                 data = child.data.copy()
                 data.pop('label')
-                
+
                 self._createMenuItem(menu, label=child.label, **data)
-        
+
         self.parent.Bind(wx.EVT_MENU_HIGHLIGHT_ALL, self.OnMenuHighlight)
-        
+
         return menu
 
-    def _createMenuItem(self, menu, label, description, handler, command, keywords,
-                        shortcut = '', icon = '', wxId = wx.ID_ANY, kind = wx.ITEM_NORMAL):
+    def _createMenuItem(
+            self, menu, label, description, handler, command, keywords,
+            shortcut='', icon='', wxId=wx.ID_ANY, kind=wx.ITEM_NORMAL):
         """Creates menu items
         There are three menu styles (menu item text styles).
         1 -- label only, 2 -- label and cmd name, 3 -- cmd name only
@@ -70,51 +73,52 @@
         if not label:
             menu.AppendSeparator()
             return
-        
+
         if command:
             helpString = command + ' -- ' + description
         else:
             helpString = description
-        
+
         if shortcut:
             label += '\t' + shortcut
-        
+
         menuItem = wx.MenuItem(menu, wxId, label, helpString, kind)
         if icon:
-            menuItem.SetBitmap(MetaIcon(img = icon).GetBitmap(self.bmpsize))
+            menuItem.SetBitmap(MetaIcon(img=icon).GetBitmap(self.bmpsize))
         menu.AppendItem(menuItem)
-        
+
         self.menucmd[menuItem.GetId()] = command
-        
-        if command: 
-            try: 
-                cmd = utils.split(str(command)) 
-            except UnicodeError: 
+
+        if command:
+            try:
+                cmd = utils.split(str(command))
+            except UnicodeError:
                 cmd = utils.split(EncodeString((command)))
-            # disable only grass commands which are not present (e.g. r.in.lidar)
+            # disable only grass commands which are not present (e.g.
+            # r.in.lidar)
             if cmd and cmd[0] not in globalvar.grassCmd and \
                re.match('[rvdipmgt][3bs]?\.([a-z0-9\.])+', cmd[0]):
                 menuItem.Enable(False)
 
         rhandler = eval('self.parent.' + handler)
         self.parent.Bind(wx.EVT_MENU, rhandler, menuItem)
-        
+
     def GetData(self):
         """Get menu data"""
         return self.model
-    
+
     def GetCmd(self):
         """Get dictionary of commands (key is id)
 
         :return: dictionary of commands
         """
         return self.menucmd
-        
+
     def OnMenuHighlight(self, event):
         """
         Default menu help handler
         """
-         # Show how to get menu item info from this event handler
+        # Show how to get menu item info from this event handler
         id = event.GetMenuId()
         item = self.FindItemById(id)
         if item:
@@ -124,22 +128,25 @@
         # but in this case just call Skip so the default is done
         event.Skip()
 
+
 class SearchModuleWindow(wx.Panel):
     """Menu tree and search widget for searching modules.
-    
+
     Signal:
         showNotification - attribute 'message'
     """
-    def __init__(self, parent, handlerObj, model, id = wx.ID_ANY, **kwargs):
+
+    def __init__(self, parent, handlerObj, model, id=wx.ID_ANY, **kwargs):
         self.parent = parent
         self.handlerObj = handlerObj
-        
+
         self.showNotification = Signal('SearchModuleWindow.showNotification')
-        wx.Panel.__init__(self, parent = parent, id = id, **kwargs)
-        
+        wx.Panel.__init__(self, parent=parent, id=id, **kwargs)
+
         # tree
         self._tree = CTreeView(model=model, parent=self)
-        self._tree.SetToolTipString(_("Double-click or Ctrl-Enter to run selected module"))
+        self._tree.SetToolTipString(
+            _("Double-click or Ctrl-Enter to run selected module"))
 
 #        self._dataBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
 #                                     label = " %s " % _("Module tree"))
@@ -148,65 +155,69 @@
         self._search = SearchModuleWidget(parent=self,
                                           model=model,
                                           showChoice=False)
-        self._search.showSearchResult.connect(lambda result: self._tree.Select(result))
+        self._search.showSearchResult.connect(
+            lambda result: self._tree.Select(result))
         self._search.showNotification.connect(self.showNotification)
-        
-        self._helpText = wx.StaticText(parent=self, id=wx.ID_ANY,
-                                       label="Press Enter for next match, Ctrl+Enter to run command")
-        self._helpText.SetForegroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_GRAYTEXT))
-        
+
+        self._helpText = wx.StaticText(
+            parent=self, id=wx.ID_ANY,
+            label="Press Enter for next match, Ctrl+Enter to run command")
+        self._helpText.SetForegroundColour(
+            wx.SystemSettings_GetColour(
+                wx.SYS_COLOUR_GRAYTEXT))
+
         # buttons
         self._btnRun = wx.Button(self, id=wx.ID_OK, label=_("&Run"))
         self._btnRun.SetToolTipString(_("Run selected module from the tree"))
-        
+
         # bindings
         self._btnRun.Bind(wx.EVT_BUTTON, lambda evt: self.Run())
-        self.Bind(wx.EVT_KEY_UP,  self.OnKeyUp)
-        
+        self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
+
         self._tree.selectionChanged.connect(self.OnItemSelected)
         self._tree.itemActivated.connect(lambda node: self.Run(node))
 
         self._layout()
-        
+
         self._search.SetFocus()
-        
+
     def _layout(self):
         """Do dialog layout"""
         sizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         # body
         dataSizer = wx.BoxSizer(wx.HORIZONTAL)
-        dataSizer.Add(item = self._tree, proportion =1,
-                      flag = wx.EXPAND)
-        
+        dataSizer.Add(item=self._tree, proportion=1,
+                      flag=wx.EXPAND)
+
         # buttons
         btnSizer = wx.BoxSizer(wx.HORIZONTAL)
-        btnSizer.Add(item = self._btnRun, proportion = 0)
-        
-        sizer.Add(item = dataSizer, proportion = 1,
-                  flag = wx.EXPAND | wx.ALL, border = 5)
+        btnSizer.Add(item=self._btnRun, proportion=0)
 
-        sizer.Add(item = self._search, proportion = 0,
-                  flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
-        
-        sizer.Add(item = btnSizer, proportion = 0,
-                  flag = wx.ALIGN_RIGHT | wx.BOTTOM | wx.RIGHT, border = 5)
-        
+        sizer.Add(item=dataSizer, proportion=1,
+                  flag=wx.EXPAND | wx.ALL, border=5)
+
+        sizer.Add(item=self._search, proportion=0,
+                  flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
+
+        sizer.Add(item=btnSizer, proportion=0,
+                  flag=wx.ALIGN_RIGHT | wx.BOTTOM | wx.RIGHT, border=5)
+
         sizer.Add(item=self._helpText,
                   proportion=0, flag=wx.EXPAND | wx.LEFT, border=5)
-        
+
         sizer.Fit(self)
         sizer.SetSizeHints(self)
-        
+
         self.SetSizer(sizer)
-        
+
         self.Fit()
-        self.SetAutoLayout(True)        
+        self.SetAutoLayout(True)
         self.Layout()
-        
+
     def Run(self, module=None):
         """Run selected command.
-        
+
         :param module: module (represented by tree node)
         """
         if module is None:
@@ -230,18 +241,18 @@
         if event.ControlDown() and \
                 event.GetKeyCode() in (wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER):
             self.Run()
-        
+
     def OnItemSelected(self, node):
-        """Item selected"""    
+        """Item selected"""
         data = node.data
         if not data or 'command' not in data:
             return
-        
+
         if data['command']:
             label = data['command']
             if data['description']:
                 label += ' -- ' + data['description']
         else:
             label = data['description']
-        
+
         self.showNotification.emit(message=label)

Modified: grass/trunk/gui/wxpython/gui_core/preferences.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/preferences.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gui_core/preferences.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -36,7 +36,7 @@
     havePwd = False
 
 import wx
-import wx.lib.colourselect    as csel
+import wx.lib.colourselect as csel
 import wx.lib.mixins.listctrl as listmix
 import wx.lib.scrolledpanel as SP
 
@@ -44,53 +44,58 @@
 from grass.script import core as grass
 from grass.exceptions import OpenError
 
-from core          import globalvar
-from core.gcmd     import RunCommand, GError
-from core.utils    import ListOfMapsets, GetColorTables, ReadEpsgCodes, _
+from core import globalvar
+from core.gcmd import RunCommand, GError
+from core.utils import ListOfMapsets, GetColorTables, ReadEpsgCodes, _
 from core.settings import UserSettings
 from gui_core.dialogs import SymbolDialog
 from gui_core.widgets import IntegerValidator, ColorTablesComboBox
-from core.debug       import Debug
+from core.debug import Debug
 
+
 class PreferencesBaseDialog(wx.Dialog):
     """Base preferences dialog"""
-    def __init__(self, parent, giface, settings, title = _("User settings"),
-                 size = (500, 475),
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
-        self.parent = parent # ModelerFrame
-        self.title  = title
-        self.size   = size
+
+    def __init__(self, parent, giface, settings, title=_("User settings"),
+                 size=(500, 475),
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
+        self.parent = parent  # ModelerFrame
+        self.title = title
+        self.size = size
         self.settings = settings
         self._giface = giface
-        
-        wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY, title = title,
-                           style = style)
-        
+
+        wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=title,
+                           style=style)
+
         self.settingsChanged = Signal('PreferencesBaseDialog.settingsChanged')
-        
+
         # notebook
-        self.notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
-        
+        self.notebook = wx.Notebook(
+            parent=self, id=wx.ID_ANY, style=wx.BK_DEFAULT)
+
         # dict for window ids
         self.winId = {}
-        
+
         # create notebook pages
-        
+
         # buttons
         self.btnDefault = wx.Button(self, wx.ID_ANY, _("Set to default"))
         self.btnSave = wx.Button(self, wx.ID_SAVE)
         self.btnApply = wx.Button(self, wx.ID_APPLY)
         self.btnCancel = wx.Button(self, wx.ID_CANCEL)
         self.btnSave.SetDefault()
-        
+
         # bindigs
         self.btnDefault.Bind(wx.EVT_BUTTON, self.OnDefault)
         self.btnDefault.SetToolTipString(_("Revert settings to default"))
         self.btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
-        self.btnApply.SetToolTipString(_("Apply changes for the current session only and close"))
+        self.btnApply.SetToolTipString(
+            _("Apply changes for the current session only and close"))
         self.btnApply.SetLabel(_("Save for this session only"))
         self.btnSave.Bind(wx.EVT_BUTTON, self.OnSave)
-        self.btnSave.SetToolTipString(_("Apply and save changes to user settings file (default for next sessions)"))
+        self.btnSave.SetToolTipString(
+            _("Apply and save changes to user settings file (default for next sessions)"))
         self.btnSave.SetDefault()
         self.btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel)
         self.btnCancel.SetToolTipString(_("Close dialog and ignore changes"))
@@ -98,26 +103,30 @@
         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
 
         self._layout()
-        
+
     def _layout(self):
         """Layout window"""
         # sizers
         btnSizer = wx.BoxSizer(wx.HORIZONTAL)
-        btnSizer.Add(item = self.btnDefault, proportion = 1,
-                     flag = wx.ALL, border = 5)
+        btnSizer.Add(item=self.btnDefault, proportion=1,
+                     flag=wx.ALL, border=5)
         btnStdSizer = wx.StdDialogButtonSizer()
         btnStdSizer.AddButton(self.btnCancel)
         btnStdSizer.AddButton(self.btnSave)
         btnStdSizer.AddButton(self.btnApply)
         btnStdSizer.Realize()
-        
+
         mainSizer = wx.BoxSizer(wx.VERTICAL)
-        mainSizer.Add(item = self.notebook, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
-        mainSizer.Add(item = btnSizer, proportion = 0,
-                      flag = wx.EXPAND, border = 0)
-        mainSizer.Add(item = btnStdSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL | wx.ALIGN_RIGHT, border = 5)
-        
+        mainSizer.Add(
+            item=self.notebook,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        mainSizer.Add(item=btnSizer, proportion=0,
+                      flag=wx.EXPAND, border=0)
+        mainSizer.Add(item=btnStdSizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALL | wx.ALIGN_RIGHT, border=5)
+
         self.SetSizer(mainSizer)
         mainSizer.Fit(self)
 
@@ -127,10 +136,13 @@
         for gks in self.winId.keys():
             try:
                 group, key, subkey = gks.split(':')
-                value = self.settings.Get(group, key, subkey, settings_type='default')
+                value = self.settings.Get(
+                    group, key, subkey, settings_type='default')
             except ValueError:
                 group, key, subkey, subkey1 = gks.split(':')
-                value = self.settings.Get(group, key, [subkey, subkey1], settings_type='default')
+                value = self.settings.Get(
+                    group, key, [subkey, subkey1],
+                    settings_type='default')
             win = self.FindWindowById(self.winId[gks])
 
             if win.GetName() in ('GetValue', 'IsChecked'):
@@ -149,34 +161,48 @@
         Emits signal settingsChanged.
         """
         if self._updateSettings():
-            self._giface.WriteLog(_('Settings applied to current session but not saved'))
+            self._giface.WriteLog(
+                _('Settings applied to current session but not saved'))
             self.settingsChanged.emit()
             self.Close()
 
     def OnCloseWindow(self, event):
         event.Skip()
         self.Destroy()
-        
+
     def OnCancel(self, event):
         """Button 'Cancel' pressed"""
         self.Close()
-    
+
     def OnSave(self, event):
         """Button 'Save' pressed
         Emits signal settingsChanged.
         """
         if self._updateSettings():
-            lang = self.settings.Get(group = 'language', key = 'locale', subkey = 'lc_all')
+            lang = self.settings.Get(
+                group='language', key='locale', subkey='lc_all')
             if lang == 'system':
-                # Most fool proof way to use system locale is to not provide any locale info at all
-                self.settings.Set(group = 'language', key = 'locale', subkey = 'lc_all', value = None)
+                # Most fool proof way to use system locale is to not provide
+                # any locale info at all
+                self.settings.Set(
+                    group='language',
+                    key='locale',
+                    subkey='lc_all',
+                    value=None)
                 lang = None
             if lang == 'en':
-                # GRASS doesn't ship EN translation, default texts have to be used instead
-                self.settings.Set(group = 'language', key = 'locale', subkey = 'lc_all', value = 'C')
+                # GRASS doesn't ship EN translation, default texts have to be
+                # used instead
+                self.settings.Set(
+                    group='language',
+                    key='locale',
+                    subkey='lc_all',
+                    value='C')
                 lang = 'C'
             self.settings.SaveToFile()
-            Debug.msg(1, "Settings saved to file '%s'" % self.settings.filePath)
+            Debug.msg(
+                1, "Settings saved to file '%s'" %
+                self.settings.filePath)
             self.settingsChanged.emit()
             self.Close()
 
@@ -188,7 +214,7 @@
                 subkey1 = None
             except ValueError:
                 group, key, subkey, subkey1 = item.split(':')
-            
+
             id = self.winId[item]
             win = self.FindWindowById(id)
             if win.GetName() == 'GetValue':
@@ -207,10 +233,14 @@
                 value = win.GetValue()
 
             if key == 'keycolumn' and value == '':
-                wx.MessageBox(parent = self,
-                              message = _("Key column cannot be empty string."),
-                              caption = _("Error"), style = wx.OK | wx.ICON_ERROR)
-                win.SetValue(self.settings.Get(group = 'atm', key = 'keycolumn', subkey = 'value'))
+                wx.MessageBox(parent=self,
+                              message=_("Key column cannot be empty string."),
+                              caption=_("Error"), style=wx.OK | wx.ICON_ERROR)
+                win.SetValue(
+                    self.settings.Get(
+                        group='atm',
+                        key='keycolumn',
+                        subkey='value'))
                 return False
             if subkey1:
                 self.settings.Set(group, value, key, [subkey, subkey1])
@@ -222,11 +252,16 @@
 
 class PreferencesDialog(PreferencesBaseDialog):
     """User preferences dialog"""
-    def __init__(self, parent, giface, title = _("GUI Settings"),
-                 settings = UserSettings):
-        PreferencesBaseDialog.__init__(self, parent = parent, giface = giface, title = title,
-                                       settings = settings)
-        
+
+    def __init__(self, parent, giface, title=_("GUI Settings"),
+                 settings=UserSettings):
+        PreferencesBaseDialog.__init__(
+            self,
+            parent=parent,
+            giface=giface,
+            title=title,
+            settings=settings)
+
         # create notebook pages
         self._createGeneralPage(self.notebook)
         self._createAppearancePage(self.notebook)
@@ -235,189 +270,269 @@
         self._createLayersPage(self.notebook)
         self._createAttributeManagerPage(self.notebook)
         self._createProjectionPage(self.notebook)
-        
+
         self.SetMinSize(self.GetBestSize())
         self.SetSize(self.size)
-        
+
     def _createGeneralPage(self, notebook):
         """Create notebook page for general settings"""
-        panel = SP.ScrolledPanel(parent = notebook, id = wx.ID_ANY)
-        panel.SetupScrolling(scroll_x = False, scroll_y = True)
-        notebook.AddPage(page = panel, text = _("General"))
-        
+        panel = SP.ScrolledPanel(parent=notebook, id=wx.ID_ANY)
+        panel.SetupScrolling(scroll_x=False, scroll_y=True)
+        notebook.AddPage(page=panel, text=_("General"))
+
         border = wx.BoxSizer(wx.VERTICAL)
         #
         # Layer Manager settings
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Layer Manager settings"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Layer Manager settings"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
 
-        gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
-        
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
+
         #
         # ask when removing map layer from layer tree
         #
         row = 0
-        askOnRemoveLayer = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                       label = _("Ask when removing map layer from layer tree"),
-                                       name = 'IsChecked')
-        askOnRemoveLayer.SetValue(self.settings.Get(group = 'manager', key = 'askOnRemoveLayer', subkey = 'enabled'))
+        askOnRemoveLayer = wx.CheckBox(parent=panel, id=wx.ID_ANY, label=_(
+            "Ask when removing map layer from layer tree"), name='IsChecked')
+        askOnRemoveLayer.SetValue(
+            self.settings.Get(
+                group='manager',
+                key='askOnRemoveLayer',
+                subkey='enabled'))
         self.winId['manager:askOnRemoveLayer:enabled'] = askOnRemoveLayer.GetId()
-        
-        gridSizer.Add(item = askOnRemoveLayer,
-                      pos = (row, 0), span = (1, 2))
-        
+
+        gridSizer.Add(item=askOnRemoveLayer,
+                      pos=(row, 0), span=(1, 2))
+
         row += 1
-        askOnQuit = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                label = _("Ask when quiting wxGUI or closing display"),
-                                name = 'IsChecked')
-        askOnQuit.SetValue(self.settings.Get(group = 'manager', key = 'askOnQuit', subkey = 'enabled'))
+        askOnQuit = wx.CheckBox(parent=panel, id=wx.ID_ANY, label=_(
+            "Ask when quiting wxGUI or closing display"), name='IsChecked')
+        askOnQuit.SetValue(
+            self.settings.Get(
+                group='manager',
+                key='askOnQuit',
+                subkey='enabled'))
         self.winId['manager:askOnQuit:enabled'] = askOnQuit.GetId()
-        
-        gridSizer.Add(item = askOnQuit,
-                      pos = (row, 0), span = (1, 2))
 
+        gridSizer.Add(item=askOnQuit,
+                      pos=(row, 0), span=(1, 2))
+
         row += 1
-        hideSearch = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                 label = _("Hide '%s' tab (requires GUI restart)") % _("Modules"),
-                                 name = 'IsChecked')
-        hideSearch.SetValue(self.settings.Get(group = 'manager', key = 'hideTabs', subkey = 'search'))
+        hideSearch = wx.CheckBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Hide '%s' tab (requires GUI restart)") %
+            _("Modules"),
+            name='IsChecked')
+        hideSearch.SetValue(
+            self.settings.Get(
+                group='manager',
+                key='hideTabs',
+                subkey='search'))
         self.winId['manager:hideTabs:search'] = hideSearch.GetId()
-        
-        gridSizer.Add(item = hideSearch,
-                      pos = (row, 0), span = (1, 2))
-        
+
+        gridSizer.Add(item=hideSearch,
+                      pos=(row, 0), span=(1, 2))
+
         row += 1
-        hidePyShell = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                  label = _("Hide '%s' tab (requires GUI restart)") % _("Python"),
-                                  name = 'IsChecked')
-        hidePyShell.SetValue(self.settings.Get(group = 'manager', key = 'hideTabs', subkey = 'pyshell'))
+        hidePyShell = wx.CheckBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Hide '%s' tab (requires GUI restart)") %
+            _("Python"),
+            name='IsChecked')
+        hidePyShell.SetValue(
+            self.settings.Get(
+                group='manager',
+                key='hideTabs',
+                subkey='pyshell'))
         self.winId['manager:hideTabs:pyshell'] = hidePyShell.GetId()
-        
-        gridSizer.Add(item = hidePyShell,
-                      pos = (row, 0), span = (1, 2))
-        
+
+        gridSizer.Add(item=hidePyShell,
+                      pos=(row, 0), span=(1, 2))
+
         #
         # Selected text is copied to clipboard
         #
         row += 1
-        copySelectedTextToClipboard = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                                  label = _("Automatically copy selected text to clipboard (in the Console tab)"),
-                                                  name = 'IsChecked')
-        copySelectedTextToClipboard.SetValue(self.settings.Get(group = 'manager', key = 'copySelectedTextToClipboard', subkey = 'enabled'))
-        self.winId['manager:copySelectedTextToClipboard:enabled'] = copySelectedTextToClipboard.GetId()
-        
-        gridSizer.Add(item = copySelectedTextToClipboard,
-                      pos = (row, 0), span = (1, 2))
-        
+        copySelectedTextToClipboard = wx.CheckBox(
+            parent=panel, id=wx.ID_ANY,
+            label=_(
+                "Automatically copy selected text to clipboard (in the Console tab)"),
+            name='IsChecked')
+        copySelectedTextToClipboard.SetValue(
+            self.settings.Get(
+                group='manager',
+                key='copySelectedTextToClipboard',
+                subkey='enabled'))
+        self.winId[
+            'manager:copySelectedTextToClipboard:enabled'] = copySelectedTextToClipboard.GetId()
+
+        gridSizer.Add(item=copySelectedTextToClipboard,
+                      pos=(row, 0), span=(1, 2))
+
         gridSizer.AddGrowableCol(0)
-        sizer.Add(item = gridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 3)
-        
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=3)
+
         #
         # workspace
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Workspace settings"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Workspace settings"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
-        gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
-        
+
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
+
         row = 0
-        posDisplay = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                 label = _("Suppress positioning Map Display Window(s)"),
-                                 name = 'IsChecked')
-        posDisplay.SetValue(self.settings.Get(group = 'general', key = 'workspace',
-                                              subkey = ['posDisplay', 'enabled']))
+        posDisplay = wx.CheckBox(parent=panel, id=wx.ID_ANY, label=_(
+            "Suppress positioning Map Display Window(s)"), name='IsChecked')
+        posDisplay.SetValue(
+            self.settings.Get(
+                group='general',
+                key='workspace',
+                subkey=[
+                    'posDisplay',
+                    'enabled']))
         self.winId['general:workspace:posDisplay:enabled'] = posDisplay.GetId()
-        
-        gridSizer.Add(item = posDisplay,
-                      pos = (row, 0), span = (1, 2))
-        
-        row += 1 
-        
-        posManager = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                 label = _("Suppress positioning Layer Manager window"),
-                                 name = 'IsChecked')
-        posManager.SetValue(self.settings.Get(group = 'general', key = 'workspace',
-                                              subkey = ['posManager', 'enabled']))
+
+        gridSizer.Add(item=posDisplay,
+                      pos=(row, 0), span=(1, 2))
+
+        row += 1
+
+        posManager = wx.CheckBox(parent=panel, id=wx.ID_ANY, label=_(
+            "Suppress positioning Layer Manager window"), name='IsChecked')
+        posManager.SetValue(
+            self.settings.Get(
+                group='general',
+                key='workspace',
+                subkey=[
+                    'posManager',
+                    'enabled']))
         self.winId['general:workspace:posManager:enabled'] = posManager.GetId()
-        
-        gridSizer.Add(item = posManager,
-                      pos = (row, 0), span = (1, 2))
-        
+
+        gridSizer.Add(item=posManager,
+                      pos=(row, 0), span=(1, 2))
+
         row += 1
-        defaultPos = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                 label = _("Save current window layout as default"),
-                                 name = 'IsChecked')
-        defaultPos.SetValue(self.settings.Get(group = 'general', key = 'defWindowPos', subkey = 'enabled'))
-        defaultPos.SetToolTip(wx.ToolTip (_("Save current position and size of Layer Manager window and opened "
-                                            "Map Display window(s) and use as default for next sessions.")))
+        defaultPos = wx.CheckBox(parent=panel, id=wx.ID_ANY, label=_(
+            "Save current window layout as default"), name='IsChecked')
+        defaultPos.SetValue(
+            self.settings.Get(
+                group='general',
+                key='defWindowPos',
+                subkey='enabled'))
+        defaultPos.SetToolTip(
+            wx.ToolTip(
+                _(
+                    "Save current position and size of Layer Manager window and opened "
+                    "Map Display window(s) and use as default for next sessions.")))
         self.winId['general:defWindowPos:enabled'] = defaultPos.GetId()
-        
-        gridSizer.Add(item = defaultPos,
-                      pos = (row, 0), span = (1, 2))
-        
+
+        gridSizer.Add(item=defaultPos,
+                      pos=(row, 0), span=(1, 2))
+
         gridSizer.AddGrowableCol(0)
-        sizer.Add(item = gridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 3)
-        
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=3)
+
         panel.SetSizer(border)
-        
+
         return panel
 
     def _createAppearancePage(self, notebook):
         """Create notebook page for display settings"""
-        panel = SP.ScrolledPanel(parent = notebook, id = wx.ID_ANY)
-        panel.SetupScrolling(scroll_x = False, scroll_y = True)
-        notebook.AddPage(page = panel, text = _("Appearance"))
+        panel = SP.ScrolledPanel(parent=notebook, id=wx.ID_ANY)
+        panel.SetupScrolling(scroll_x=False, scroll_y=True)
+        notebook.AddPage(page=panel, text=_("Appearance"))
 
         border = wx.BoxSizer(wx.VERTICAL)
 
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Font settings"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Font settings"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
 
-        gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
 
         #
         # font settings
         #
-        sizer.Add(item = gridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 3)
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=3)
 
         row = 0
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Font for command output:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Font for command output:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        outfontButton = wx.Button(parent = panel, id = wx.ID_ANY,
-                                  label = _("Set font"))
-        gridSizer.Add(item = outfontButton,
-                      flag = wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
+                      pos=(row, 0))
+        outfontButton = wx.Button(parent=panel, id=wx.ID_ANY,
+                                  label=_("Set font"))
+        gridSizer.Add(item=outfontButton,
+                      flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL,
+                      pos=(row, 1))
         gridSizer.AddGrowableCol(0)
 
         #
         # languages
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Language settings"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Language settings"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
 
-        gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
-        sizer.Add(item = gridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 3)
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=3)
 
         row = 0
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Choose language (requires to save and GRASS restart):")),
-                      flag = wx.ALIGN_LEFT |
-                      wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        locales = self.settings.Get(group = 'language', key = 'locale', 
-                                         subkey = 'choices', settings_type='internal')
-        loc = self.settings.Get(group = 'language', key = 'locale', subkey = 'lc_all')
-        elementList = wx.Choice(parent = panel, id = wx.ID_ANY, size = (325, -1),
-                                choices = locales, name = "GetStringSelection")
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_("Choose language (requires to save and GRASS restart):")),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                row,
+                0))
+        locales = self.settings.Get(group='language', key='locale',
+                                    subkey='choices', settings_type='internal')
+        loc = self.settings.Get(
+            group='language',
+            key='locale',
+            subkey='lc_all')
+        elementList = wx.Choice(parent=panel, id=wx.ID_ANY, size=(325, -1),
+                                choices=locales, name="GetStringSelection")
         if loc in locales:
             elementList.SetStringSelection(loc)
         if loc == 'C':
@@ -426,914 +541,1254 @@
             elementList.SetStringSelection('system')
         self.winId['language:locale:lc_all'] = elementList.GetId()
 
-        gridSizer.Add(item = elementList,
-                      flag = wx.ALIGN_RIGHT |
+        gridSizer.Add(item=elementList,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
+                      pos=(row, 1))
         gridSizer.AddGrowableCol(0)
         #
         # appearence
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Appearance settings"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Appearance settings"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
 
-        gridSizer  =  wx.GridBagSizer (hgap = 3, vgap = 3)
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
 
         #
         # element list
         #
         row = 0
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                           label = _("Element list:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Element list:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        elementList = wx.Choice(parent = panel, id = wx.ID_ANY, size = (325, -1),
-                                choices = self.settings.Get(group = 'appearance', key = 'elementListExpand',
-                                                            subkey = 'choices', settings_type='internal'),
-                                name = "GetSelection")
-        elementList.SetSelection(self.settings.Get(group = 'appearance', key = 'elementListExpand',
-                                                   subkey = 'selection'))
+                      pos=(row, 0))
+        elementList = wx.Choice(
+            parent=panel, id=wx.ID_ANY, size=(325, -1),
+            choices=self.settings.Get(
+                group='appearance', key='elementListExpand', subkey='choices',
+                settings_type='internal'),
+            name="GetSelection")
+        elementList.SetSelection(
+            self.settings.Get(
+                group='appearance',
+                key='elementListExpand',
+                subkey='selection'))
         self.winId['appearance:elementListExpand:selection'] = elementList.GetId()
 
-        gridSizer.Add(item = elementList,
-                      flag = wx.ALIGN_RIGHT |
+        gridSizer.Add(item=elementList,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
-        
+                      pos=(row, 1))
+
         #
         # menu style
         #
         row += 1
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                           label = _("Menu style (requires to save and GUI restart):")),
-                      flag = wx.ALIGN_LEFT |
-                      wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        listOfStyles = self.settings.Get(group = 'appearance', key = 'menustyle',
-                                         subkey='choices', settings_type='internal')
-        
-        menuItemText = wx.Choice(parent = panel, id = wx.ID_ANY, size = (325, -1),
-                                 choices = listOfStyles,
-                                 name = "GetSelection")
-        menuItemText.SetSelection(self.settings.Get(group = 'appearance', key = 'menustyle', subkey = 'selection'))
-        
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_("Menu style (requires to save and GUI restart):")),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                row,
+                0))
+        listOfStyles = self.settings.Get(
+            group='appearance',
+            key='menustyle',
+            subkey='choices',
+            settings_type='internal')
+
+        menuItemText = wx.Choice(parent=panel, id=wx.ID_ANY, size=(325, -1),
+                                 choices=listOfStyles,
+                                 name="GetSelection")
+        menuItemText.SetSelection(
+            self.settings.Get(
+                group='appearance',
+                key='menustyle',
+                subkey='selection'))
+
         self.winId['appearance:menustyle:selection'] = menuItemText.GetId()
-        
-        gridSizer.Add(item = menuItemText,
-                      flag = wx.ALIGN_RIGHT,
-                      pos = (row, 1))
-        
+
+        gridSizer.Add(item=menuItemText,
+                      flag=wx.ALIGN_RIGHT,
+                      pos=(row, 1))
+
         #
         # gselect.TreeCtrlComboPopup height
         #
         row += 1
-        
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Height of map selection popup window (in pixels):")),
-                      flag = wx.ALIGN_LEFT |
-                      wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        min = self.settings.Get(group = 'appearance', key = 'gSelectPopupHeight', subkey = 'min', settings_type='internal')
-        max = self.settings.Get(group = 'appearance', key = 'gSelectPopupHeight', subkey = 'max', settings_type='internal')
-        value = self.settings.Get(group = 'appearance', key = 'gSelectPopupHeight', subkey = 'value')
-        
-        popupHeightSpin = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (100, -1))
-        popupHeightSpin.SetRange(min,max)
+
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_("Height of map selection popup window (in pixels):")),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                row,
+                0))
+        min = self.settings.Get(
+            group='appearance',
+            key='gSelectPopupHeight',
+            subkey='min',
+            settings_type='internal')
+        max = self.settings.Get(
+            group='appearance',
+            key='gSelectPopupHeight',
+            subkey='max',
+            settings_type='internal')
+        value = self.settings.Get(
+            group='appearance',
+            key='gSelectPopupHeight',
+            subkey='value')
+
+        popupHeightSpin = wx.SpinCtrl(
+            parent=panel, id=wx.ID_ANY, size=(100, -1))
+        popupHeightSpin.SetRange(min, max)
         popupHeightSpin.SetValue(value)
-        
-        self.winId['appearance:gSelectPopupHeight:value'] = popupHeightSpin.GetId()
-        
-        gridSizer.Add(item = popupHeightSpin,
-                      flag = wx.ALIGN_RIGHT,
-                      pos = (row, 1))
-        
-        
+
+        self.winId[
+            'appearance:gSelectPopupHeight:value'] = popupHeightSpin.GetId()
+
+        gridSizer.Add(item=popupHeightSpin,
+                      flag=wx.ALIGN_RIGHT,
+                      pos=(row, 1))
+
         #
         # icon theme
         #
         row += 1
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                           label = _("Icon theme (requires GUI restart):")),
-                      flag = wx.ALIGN_LEFT |
-                      wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        iconTheme = wx.Choice(parent = panel, id = wx.ID_ANY, size = (100, -1),
-                              choices = self.settings.Get(group = 'appearance', key = 'iconTheme',
-                                                        subkey = 'choices', settings_type='internal'),
-                              name = "GetStringSelection")
-        iconTheme.SetStringSelection(self.settings.Get(group = 'appearance', key = 'iconTheme', subkey = 'type'))
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_("Icon theme (requires GUI restart):")),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                row,
+                0))
+        iconTheme = wx.Choice(
+            parent=panel, id=wx.ID_ANY, size=(100, -1),
+            choices=self.settings.Get(
+                group='appearance', key='iconTheme', subkey='choices',
+                settings_type='internal'),
+            name="GetStringSelection")
+        iconTheme.SetStringSelection(
+            self.settings.Get(
+                group='appearance',
+                key='iconTheme',
+                subkey='type'))
         self.winId['appearance:iconTheme:type'] = iconTheme.GetId()
 
-        gridSizer.Add(item = iconTheme,
-                      flag = wx.ALIGN_RIGHT |
+        gridSizer.Add(item=iconTheme,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
+                      pos=(row, 1))
         #
         # command dialog style
         #
         row += 1
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                           label = _("Module dialog style:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Module dialog style:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        styleList = wx.Choice(parent = panel, id = wx.ID_ANY, size = (325, -1),
-                                choices = self.settings.Get(group = 'appearance', key = 'commandNotebook',
-                                                            subkey = 'choices', settings_type='internal'),
-                                name = "GetSelection")
-        styleList.SetSelection(self.settings.Get(group = 'appearance', key = 'commandNotebook',
-                                                   subkey = 'selection'))
+                      pos=(row, 0))
+        styleList = wx.Choice(
+            parent=panel, id=wx.ID_ANY, size=(325, -1),
+            choices=self.settings.Get(
+                group='appearance', key='commandNotebook', subkey='choices',
+                settings_type='internal'),
+            name="GetSelection")
+        styleList.SetSelection(
+            self.settings.Get(
+                group='appearance',
+                key='commandNotebook',
+                subkey='selection'))
         self.winId['appearance:commandNotebook:selection'] = styleList.GetId()
 
-        gridSizer.Add(item = styleList,
-                      flag = wx.ALIGN_RIGHT |
+        gridSizer.Add(item=styleList,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
+                      pos=(row, 1))
 
         gridSizer.AddGrowableCol(0)
-        sizer.Add(item = gridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
-        
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.LEFT |
+                   wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
+
         panel.SetSizer(border)
-                
+
         # bindings
         outfontButton.Bind(wx.EVT_BUTTON, self.OnSetOutputFont)
-        
+
         return panel
-    
+
     def _createDisplayPage(self, notebook):
         """Create notebook page for display settings"""
-   
-        panel = SP.ScrolledPanel(parent = notebook, id = wx.ID_ANY)
-        panel.SetupScrolling(scroll_x = False, scroll_y = True)
-        notebook.AddPage(page = panel, text = _("Map Display"))
 
+        panel = SP.ScrolledPanel(parent=notebook, id=wx.ID_ANY)
+        panel.SetupScrolling(scroll_x=False, scroll_y=True)
+        notebook.AddPage(page=panel, text=_("Map Display"))
+
         border = wx.BoxSizer(wx.VERTICAL)
 
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Font settings"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Font settings"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
 
-        gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
 
         #
         # font settings
         #
         row = 0
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Default font for GRASS displays:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_("Default font for GRASS displays:")),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                row,
+                0))
+        fontButton = wx.Button(parent=panel, id=wx.ID_ANY,
+                               label=_("Set font"))
+        gridSizer.Add(item=fontButton,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        fontButton = wx.Button(parent = panel, id = wx.ID_ANY,
-                               label = _("Set font"))
-        gridSizer.Add(item = fontButton,
-                      flag = wx.ALIGN_RIGHT |
-                      wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 1))
+                      pos=(row, 1))
 
         gridSizer.AddGrowableCol(0)
-        sizer.Add(item = gridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 3)
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=3)
 
         #
         # display settings
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Default display settings"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Default display settings"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
 
-        gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
-        
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
+
         #
         # display driver
         #
         row = 0
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Display driver:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Display driver:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        listOfDrivers = self.settings.Get(group = 'display', key = 'driver', subkey = 'choices', settings_type='internal')
-        driver = wx.Choice(parent = panel, id = wx.ID_ANY, size = (150, -1),
-                           choices = listOfDrivers,
-                           name = "GetStringSelection")
-        driver.SetStringSelection(self.settings.Get(group = 'display', key = 'driver', subkey = 'type'))
+                      pos=(row, 0))
+        listOfDrivers = self.settings.Get(
+            group='display', key='driver', subkey='choices',
+            settings_type='internal')
+        driver = wx.Choice(parent=panel, id=wx.ID_ANY, size=(150, -1),
+                           choices=listOfDrivers,
+                           name="GetStringSelection")
+        driver.SetStringSelection(
+            self.settings.Get(
+                group='display',
+                key='driver',
+                subkey='type'))
         self.winId['display:driver:type'] = driver.GetId()
-        
-        gridSizer.Add(item = driver,
-                      flag = wx.ALIGN_RIGHT,
-                      pos = (row, 1))
-        
+
+        gridSizer.Add(item=driver,
+                      flag=wx.ALIGN_RIGHT,
+                      pos=(row, 1))
+
         #
         # Statusbar mode
         #
         row += 1
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Statusbar mode:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Statusbar mode:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        listOfModes = self.settings.Get(group = 'display', key = 'statusbarMode', subkey = 'choices', settings_type='internal')
-        statusbarMode = wx.Choice(parent = panel, id = wx.ID_ANY, size = (150, -1),
-                                  choices = listOfModes,
-                                  name = "GetSelection")
-        statusbarMode.SetSelection(self.settings.Get(group = 'display', key = 'statusbarMode', subkey = 'selection'))
+                      pos=(row, 0))
+        listOfModes = self.settings.Get(
+            group='display',
+            key='statusbarMode',
+            subkey='choices',
+            settings_type='internal')
+        statusbarMode = wx.Choice(parent=panel, id=wx.ID_ANY, size=(150, -1),
+                                  choices=listOfModes,
+                                  name="GetSelection")
+        statusbarMode.SetSelection(
+            self.settings.Get(
+                group='display',
+                key='statusbarMode',
+                subkey='selection'))
         self.winId['display:statusbarMode:selection'] = statusbarMode.GetId()
 
-        gridSizer.Add(item = statusbarMode,
-                      flag = wx.ALIGN_RIGHT,
-                      pos = (row, 1))
+        gridSizer.Add(item=statusbarMode,
+                      flag=wx.ALIGN_RIGHT,
+                      pos=(row, 1))
 
         #
         # Background color
         #
         row += 1
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Background color:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Background color:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        bgColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
-                                    colour = self.settings.Get(group = 'display', key = 'bgcolor', subkey = 'color'),
-                                    size = globalvar.DIALOG_COLOR_SIZE)
+                      pos=(row, 0))
+        bgColor = csel.ColourSelect(
+            parent=panel,
+            id=wx.ID_ANY,
+            colour=self.settings.Get(
+                group='display',
+                key='bgcolor',
+                subkey='color'),
+            size=globalvar.DIALOG_COLOR_SIZE)
         bgColor.SetName('GetColour')
         self.winId['display:bgcolor:color'] = bgColor.GetId()
-        
-        gridSizer.Add(item = bgColor,
-                      flag = wx.ALIGN_RIGHT,
-                      pos = (row, 1))
-        
+
+        gridSizer.Add(item=bgColor,
+                      flag=wx.ALIGN_RIGHT,
+                      pos=(row, 1))
+
         #
         # Align extent to display size
         #
         row += 1
-        alignExtent = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                  label = _("Align region extent based on display size"),
-                                  name = "IsChecked")
-        alignExtent.SetValue(self.settings.Get(group = 'display', key = 'alignExtent', subkey = 'enabled'))
+        alignExtent = wx.CheckBox(parent=panel, id=wx.ID_ANY, label=_(
+            "Align region extent based on display size"), name="IsChecked")
+        alignExtent.SetValue(
+            self.settings.Get(
+                group='display',
+                key='alignExtent',
+                subkey='enabled'))
         self.winId['display:alignExtent:enabled'] = alignExtent.GetId()
 
-        gridSizer.Add(item = alignExtent,
-                      pos = (row, 0), span = (1, 2))
-        
+        gridSizer.Add(item=alignExtent,
+                      pos=(row, 0), span=(1, 2))
+
         #
         # Use computation resolution
         #
         row += 1
-        compResolution = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                     label = _("Constrain display resolution to computational settings"),
-                                     name = "IsChecked")
-        compResolution.SetValue(self.settings.Get(group = 'display', key = 'compResolution', subkey = 'enabled'))
+        compResolution = wx.CheckBox(parent=panel, id=wx.ID_ANY, label=_(
+            "Constrain display resolution to computational settings"), name="IsChecked")
+        compResolution.SetValue(
+            self.settings.Get(
+                group='display',
+                key='compResolution',
+                subkey='enabled'))
         self.winId['display:compResolution:enabled'] = compResolution.GetId()
 
-        gridSizer.Add(item = compResolution,
-                      pos = (row, 0), span = (1, 2))
+        gridSizer.Add(item=compResolution,
+                      pos=(row, 0), span=(1, 2))
 
         #
         # auto-rendering
         #
         row += 1
-        autoRendering = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                    label = _("Enable auto-rendering"),
-                                    name = "IsChecked")
-        autoRendering.SetValue(self.settings.Get(group = 'display', key = 'autoRendering', subkey = 'enabled'))
+        autoRendering = wx.CheckBox(parent=panel, id=wx.ID_ANY,
+                                    label=_("Enable auto-rendering"),
+                                    name="IsChecked")
+        autoRendering.SetValue(
+            self.settings.Get(
+                group='display',
+                key='autoRendering',
+                subkey='enabled'))
         self.winId['display:autoRendering:enabled'] = autoRendering.GetId()
 
-        gridSizer.Add(item = autoRendering,
-                      pos = (row, 0), span = (1, 2))
-        
+        gridSizer.Add(item=autoRendering,
+                      pos=(row, 0), span=(1, 2))
+
         #
         # auto-zoom
         #
         row += 1
-        autoZooming = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                  label = _("Enable auto-zooming to selected map layer"),
-                                  name = "IsChecked")
-        autoZooming.SetValue(self.settings.Get(group = 'display', key = 'autoZooming', subkey = 'enabled'))
+        autoZooming = wx.CheckBox(parent=panel, id=wx.ID_ANY, label=_(
+            "Enable auto-zooming to selected map layer"), name="IsChecked")
+        autoZooming.SetValue(
+            self.settings.Get(
+                group='display',
+                key='autoZooming',
+                subkey='enabled'))
         self.winId['display:autoZooming:enabled'] = autoZooming.GetId()
 
-        gridSizer.Add(item = autoZooming,
-                      pos = (row, 0), span = (1, 2))
-        
+        gridSizer.Add(item=autoZooming,
+                      pos=(row, 0), span=(1, 2))
+
         #
         # mouse wheel zoom
         #
         row += 1
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                          label = _("Mouse wheel action:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Mouse wheel action:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        listOfModes = self.settings.Get(group = 'display', key = 'mouseWheelZoom', subkey = 'choices', settings_type='internal')
-        zoomAction = wx.Choice(parent = panel, id = wx.ID_ANY, size = (200, -1),
-                               choices = listOfModes,
-                               name = "GetSelection")
-        zoomAction.SetSelection(self.settings.Get(group = 'display', key = 'mouseWheelZoom', subkey = 'selection'))
+                      pos=(row, 0))
+        listOfModes = self.settings.Get(
+            group='display',
+            key='mouseWheelZoom',
+            subkey='choices',
+            settings_type='internal')
+        zoomAction = wx.Choice(parent=panel, id=wx.ID_ANY, size=(200, -1),
+                               choices=listOfModes,
+                               name="GetSelection")
+        zoomAction.SetSelection(
+            self.settings.Get(
+                group='display',
+                key='mouseWheelZoom',
+                subkey='selection'))
         self.winId['display:mouseWheelZoom:selection'] = zoomAction.GetId()
-        gridSizer.Add(item = zoomAction,
-                      flag = wx.ALIGN_RIGHT,
-                      pos = (row, 1))
+        gridSizer.Add(item=zoomAction,
+                      flag=wx.ALIGN_RIGHT,
+                      pos=(row, 1))
         row += 1
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                          label = _("Mouse scrolling direction:")),
-                      flag = wx.ALIGN_LEFT |
-                      wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        listOfModes = self.settings.Get(group = 'display', key = 'scrollDirection', subkey = 'choices', settings_type='internal')
-        scrollDir = wx.Choice(parent = panel, id = wx.ID_ANY, size = (200, -1),
-                               choices = listOfModes,
-                               name = "GetSelection")
-        scrollDir.SetSelection(self.settings.Get(group = 'display', key = 'scrollDirection', subkey = 'selection'))
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_("Mouse scrolling direction:")),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                row,
+                0))
+        listOfModes = self.settings.Get(
+            group='display',
+            key='scrollDirection',
+            subkey='choices',
+            settings_type='internal')
+        scrollDir = wx.Choice(parent=panel, id=wx.ID_ANY, size=(200, -1),
+                              choices=listOfModes,
+                              name="GetSelection")
+        scrollDir.SetSelection(
+            self.settings.Get(
+                group='display',
+                key='scrollDirection',
+                subkey='selection'))
         self.winId['display:scrollDirection:selection'] = scrollDir.GetId()
-        gridSizer.Add(item = scrollDir,
-                      flag = wx.ALIGN_RIGHT,
-                      pos = (row, 1))
+        gridSizer.Add(item=scrollDir,
+                      flag=wx.ALIGN_RIGHT,
+                      pos=(row, 1))
 
         gridSizer.AddGrowableCol(0)
-        sizer.Add(item = gridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
-        
-        
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.LEFT |
+                   wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
+
         #
         # advanced
         #
-        
+
         # see initialization of nviz GLWindow
         if globalvar.CheckWxVersion(version=[2, 8, 11]) and \
            sys.platform not in ('win32', 'darwin'):
-            box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Advanced display settings"))
+            box = wx.StaticBox(
+                parent=panel, id=wx.ID_ANY, label=" %s " %
+                _("Advanced display settings"))
             sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-    
-            gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
+
+            gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
             row = 0
-            gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                               label = _("3D view depth buffer (possible values are 16, 24, 32):")),
-                          flag = wx.ALIGN_LEFT |
-                          wx.ALIGN_CENTER_VERTICAL,
-                          pos = (row, 0))
-            value = self.settings.Get(group='display', key='nvizDepthBuffer', subkey='value')
-            textCtrl = wx.TextCtrl(parent=panel, id=wx.ID_ANY, value=str(value), validator=IntegerValidator(),
-                                   name='GetValue')
+            gridSizer.Add(
+                item=wx.StaticText(
+                    parent=panel,
+                    id=wx.ID_ANY,
+                    label=_("3D view depth buffer (possible values are 16, 24, 32):")),
+                flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
+                pos=(
+                    row,
+                    0))
+            value = self.settings.Get(
+                group='display',
+                key='nvizDepthBuffer',
+                subkey='value')
+            textCtrl = wx.TextCtrl(
+                parent=panel,
+                id=wx.ID_ANY,
+                value=str(value),
+                validator=IntegerValidator(),
+                name='GetValue')
             self.winId['display:nvizDepthBuffer:value'] = textCtrl.GetId()
-            gridSizer.Add(item = textCtrl,
-                          flag = wx.ALIGN_RIGHT |
+            gridSizer.Add(item=textCtrl,
+                          flag=wx.ALIGN_RIGHT |
                           wx.ALIGN_CENTER_VERTICAL,
-                          pos = (row, 1))
-    
+                          pos=(row, 1))
+
             gridSizer.AddGrowableCol(0)
-            sizer.Add(item = gridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
-            border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 3)
-        
+            sizer.Add(
+                item=gridSizer,
+                proportion=1,
+                flag=wx.ALL | wx.EXPAND,
+                border=5)
+            border.Add(
+                item=sizer,
+                proportion=0,
+                flag=wx.ALL | wx.EXPAND,
+                border=3)
+
         panel.SetSizer(border)
-                
+
         # bindings
         fontButton.Bind(wx.EVT_BUTTON, self.OnSetFont)
         zoomAction.Bind(wx.EVT_CHOICE, self.OnEnableWheelZoom)
-        
+
         # enable/disable controls according to settings
         self.OnEnableWheelZoom(None)
-        
+
         return panel
 
     def _createCmdPage(self, notebook):
         """Create notebook page for commad dialog settings"""
-        panel = SP.ScrolledPanel(parent = notebook, id = wx.ID_ANY)
-        panel.SetupScrolling(scroll_x = False, scroll_y = True)
-        notebook.AddPage(page = panel, text = _("Modules"))
-        
+        panel = SP.ScrolledPanel(parent=notebook, id=wx.ID_ANY)
+        panel.SetupScrolling(scroll_x=False, scroll_y=True)
+        notebook.AddPage(page=panel, text=_("Modules"))
+
         border = wx.BoxSizer(wx.VERTICAL)
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Module dialog settings"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Module dialog settings"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
-        gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
-        
+
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
+
         #
         # command dialog settings
         #
         row = 0
         # overwrite
-        overwrite = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                label = _("Allow output files to overwrite existing files"),
-                                name = "IsChecked")
-        overwrite.SetValue(self.settings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'))
+        overwrite = wx.CheckBox(parent=panel, id=wx.ID_ANY, label=_(
+            "Allow output files to overwrite existing files"), name="IsChecked")
+        overwrite.SetValue(
+            self.settings.Get(
+                group='cmd',
+                key='overwrite',
+                subkey='enabled'))
         self.winId['cmd:overwrite:enabled'] = overwrite.GetId()
-        
-        gridSizer.Add(item = overwrite,
-                      pos = (row, 0), span = (1, 2))
+
+        gridSizer.Add(item=overwrite,
+                      pos=(row, 0), span=(1, 2))
         row += 1
         # close
-        close = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                            label = _("Close dialog when module is successfully finished"),
-                            name = "IsChecked")
-        close.SetValue(self.settings.Get(group = 'cmd', key = 'closeDlg', subkey = 'enabled'))
+        close = wx.CheckBox(
+            parent=panel, id=wx.ID_ANY,
+            label=_("Close dialog when module is successfully finished"),
+            name="IsChecked")
+        close.SetValue(
+            self.settings.Get(
+                group='cmd',
+                key='closeDlg',
+                subkey='enabled'))
         self.winId['cmd:closeDlg:enabled'] = close.GetId()
-        
-        gridSizer.Add(item = close,
-                      pos = (row, 0), span = (1, 2))
+
+        gridSizer.Add(item=close,
+                      pos=(row, 0), span=(1, 2))
         row += 1
         # add layer
-        add = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                          label = _("Add created map into layer tree"),
-                          name = "IsChecked")
-        add.SetValue(self.settings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
+        add = wx.CheckBox(parent=panel, id=wx.ID_ANY,
+                          label=_("Add created map into layer tree"),
+                          name="IsChecked")
+        add.SetValue(
+            self.settings.Get(
+                group='cmd',
+                key='addNewLayer',
+                subkey='enabled'))
         self.winId['cmd:addNewLayer:enabled'] = add.GetId()
-    
-        gridSizer.Add(item = add,
-                      pos = (row, 0), span = (1, 2))
-        
+
+        gridSizer.Add(item=add,
+                      pos=(row, 0), span=(1, 2))
+
         row += 1
         # interactive input
-        interactive = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                  label = _("Allow interactive input"),
-                                  name = "IsChecked")
-        interactive.SetValue(self.settings.Get(group = 'cmd', key = 'interactiveInput', subkey = 'enabled'))
+        interactive = wx.CheckBox(parent=panel, id=wx.ID_ANY,
+                                  label=_("Allow interactive input"),
+                                  name="IsChecked")
+        interactive.SetValue(
+            self.settings.Get(
+                group='cmd',
+                key='interactiveInput',
+                subkey='enabled'))
         self.winId['cmd:interactiveInput:enabled'] = interactive.GetId()
-        gridSizer.Add(item = interactive,
-                      pos = (row, 0), span = (1, 2))
-        
+        gridSizer.Add(item=interactive,
+                      pos=(row, 0), span=(1, 2))
+
         row += 1
         # verbosity
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Verbosity level:")),
-                      flag = wx.ALIGN_LEFT |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Verbosity level:")),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        verbosity = wx.Choice(parent = panel, id = wx.ID_ANY, size = (200, -1),
-                              choices = self.settings.Get(group = 'cmd', key = 'verbosity', subkey = 'choices', settings_type='internal'),
-                              name = "GetStringSelection")
-        verbosity.SetStringSelection(self.settings.Get(group = 'cmd', key = 'verbosity', subkey = 'selection'))
+                      pos=(row, 0))
+        verbosity = wx.Choice(
+            parent=panel, id=wx.ID_ANY, size=(200, -1),
+            choices=self.settings.Get(
+                group='cmd', key='verbosity', subkey='choices',
+                settings_type='internal'),
+            name="GetStringSelection")
+        verbosity.SetStringSelection(
+            self.settings.Get(
+                group='cmd',
+                key='verbosity',
+                subkey='selection'))
         self.winId['cmd:verbosity:selection'] = verbosity.GetId()
-        
-        gridSizer.Add(item = verbosity,
-                      pos = (row, 1), flag = wx.ALIGN_RIGHT)
-        
+
+        gridSizer.Add(item=verbosity,
+                      pos=(row, 1), flag=wx.ALIGN_RIGHT)
+
         gridSizer.AddGrowableCol(0)
-        sizer.Add(item = gridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 3)
-        
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=3)
+
         panel.SetSizer(border)
-        
+
         return panel
 
     def _createLayersPage(self, notebook):
         """Create notebook page for layer settings"""
-        panel = SP.ScrolledPanel(parent = notebook, id = wx.ID_ANY)
-        panel.SetupScrolling(scroll_x = False, scroll_y = True)
-        notebook.AddPage(page = panel, text = _("Layers"))
-        
+        panel = SP.ScrolledPanel(parent=notebook, id=wx.ID_ANY)
+        panel.SetupScrolling(scroll_x=False, scroll_y=True)
+        notebook.AddPage(page=panel, text=_("Layers"))
+
         border = wx.BoxSizer(wx.VERTICAL)
         #
         # raster settings
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Default raster settings"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Default raster settings"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
-        gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
-        
+
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
+
         #
         # raster overlay
         #
         row = 0
-        rasterOpaque = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                    label = _("Make null cells opaque"),
-                                    name = 'IsChecked')
-        rasterOpaque.SetValue(self.settings.Get(group = 'rasterLayer', key = 'opaque', subkey = 'enabled'))
+        rasterOpaque = wx.CheckBox(parent=panel, id=wx.ID_ANY,
+                                   label=_("Make null cells opaque"),
+                                   name='IsChecked')
+        rasterOpaque.SetValue(
+            self.settings.Get(
+                group='rasterLayer',
+                key='opaque',
+                subkey='enabled'))
         self.winId['rasterLayer:opaque:enabled'] = rasterOpaque.GetId()
-        
-        gridSizer.Add(item = rasterOpaque,
-                      pos = (row, 0), span = (1, 2))
 
+        gridSizer.Add(item=rasterOpaque,
+                      pos=(row, 0), span=(1, 2))
+
         # default color table
         row += 1
-        rasterCTCheck = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                    label = _("Default color table"),
-                                    name = 'IsChecked')
-        rasterCTCheck.SetValue(self.settings.Get(group = 'rasterLayer', key = 'colorTable', subkey = 'enabled'))
+        rasterCTCheck = wx.CheckBox(parent=panel, id=wx.ID_ANY,
+                                    label=_("Default color table"),
+                                    name='IsChecked')
+        rasterCTCheck.SetValue(
+            self.settings.Get(
+                group='rasterLayer',
+                key='colorTable',
+                subkey='enabled'))
         self.winId['rasterLayer:colorTable:enabled'] = rasterCTCheck.GetId()
         rasterCTCheck.Bind(wx.EVT_CHECKBOX, self.OnCheckColorTable)
-        
-        gridSizer.Add(item = rasterCTCheck, flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 0))
-        
-        rasterCTName = ColorTablesComboBox(parent=panel, size=globalvar.DIALOG_COMBOBOX_SIZE,
-                                           choices=GetColorTables(),
-                                           name="GetStringSelection")
-        rasterCTName.SetStringSelection(self.settings.Get(group = 'rasterLayer', key = 'colorTable', subkey = 'selection'))
+
+        gridSizer.Add(item=rasterCTCheck, flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(row, 0))
+
+        rasterCTName = ColorTablesComboBox(
+            parent=panel,
+            size=globalvar.DIALOG_COMBOBOX_SIZE,
+            choices=GetColorTables(),
+            name="GetStringSelection")
+        rasterCTName.SetStringSelection(
+            self.settings.Get(
+                group='rasterLayer',
+                key='colorTable',
+                subkey='selection'))
         self.winId['rasterLayer:colorTable:selection'] = rasterCTName.GetId()
         if not rasterCTCheck.IsChecked():
             rasterCTName.Enable(False)
-        
-        gridSizer.Add(item = rasterCTName,
-                      pos = (row, 1))
-        
+
+        gridSizer.Add(item=rasterCTName,
+                      pos=(row, 1))
+
         gridSizer.AddGrowableCol(0)
-        sizer.Add(item = gridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
-        
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.LEFT |
+                   wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
+
         #
         # vector settings
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Default vector settings"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Default vector settings"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
-        gridSizer = wx.FlexGridSizer (cols = 7, hgap = 10, vgap = 3)
-        
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Display:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        
+
+        gridSizer = wx.FlexGridSizer(cols=7, hgap=10, vgap=3)
+
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Display:")),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
+
         for type in ('point', 'line', 'centroid', 'boundary',
                      'area', 'face'):
-            chkbox = wx.CheckBox(parent = panel, label = type)
-            checked = self.settings.Get(group = 'vectorLayer', key = 'showType',
-                                        subkey = [type, 'enabled'])
+            chkbox = wx.CheckBox(parent=panel, label=type)
+            checked = self.settings.Get(group='vectorLayer', key='showType',
+                                        subkey=[type, 'enabled'])
             chkbox.SetValue(checked)
-            self.winId['vectorLayer:showType:%s:enabled' % type] = chkbox.GetId()
-            gridSizer.Add(item = chkbox)
+            self.winId[
+                'vectorLayer:showType:%s:enabled' %
+                type] = chkbox.GetId()
+            gridSizer.Add(item=chkbox)
 
-        sizer.Add(item = gridSizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
+        sizer.Add(
+            item=gridSizer,
+            proportion=0,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
 
         row = col = 0
-        gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
 
         # feature color
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                           label = _("Feature color:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL, pos = (row, 0))
-        featureColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
-                                         colour = self.settings.Get(group = 'vectorLayer',
-                                                                    key = 'featureColor',
-                                                                    subkey = 'color'),
-                                         size = globalvar.DIALOG_COLOR_SIZE)
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Feature color:")),
+                      flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
+        featureColor = csel.ColourSelect(
+            parent=panel,
+            id=wx.ID_ANY,
+            colour=self.settings.Get(
+                group='vectorLayer',
+                key='featureColor',
+                subkey='color'),
+            size=globalvar.DIALOG_COLOR_SIZE)
         featureColor.SetName('GetColour')
         self.winId['vectorLayer:featureColor:color'] = featureColor.GetId()
-        gridSizer.Add(item = featureColor, pos = (row, col + 2), flag = wx.ALIGN_RIGHT)
-        
-        transpFeature = wx.CheckBox(parent  = panel, id = wx.ID_ANY,
-                                    label = _("Transparent"), name = "IsChecked")
-        transpFeature.SetValue(self.settings.Get(group = 'vectorLayer', key = 'featureColor',
-                                                     subkey =  ['transparent', 'enabled']))
-        self.winId['vectorLayer:featureColor:transparent:enabled'] = transpFeature.GetId()
-        gridSizer.Add(item = transpFeature, pos = (row, col + 1), flag = wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=featureColor,
+            pos=(
+                row,
+                col + 2),
+            flag=wx.ALIGN_RIGHT)
 
+        transpFeature = wx.CheckBox(parent=panel, id=wx.ID_ANY,
+                                    label=_("Transparent"), name="IsChecked")
+        transpFeature.SetValue(
+            self.settings.Get(
+                group='vectorLayer',
+                key='featureColor',
+                subkey=[
+                    'transparent',
+                    'enabled']))
+        self.winId[
+            'vectorLayer:featureColor:transparent:enabled'] = transpFeature.GetId()
+        gridSizer.Add(
+            item=transpFeature,
+            pos=(
+                row,
+                col + 1),
+            flag=wx.ALIGN_CENTER_VERTICAL)
 
         # area fill color
         row += 1
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                           label = _("Area fill color:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL, pos = (row, col))
-        fillColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
-                                      colour = self.settings.Get(group = 'vectorLayer',
-                                                                 key = 'areaFillColor',
-                                                                 subkey = 'color'),
-                                      size = globalvar.DIALOG_COLOR_SIZE)
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Area fill color:")),
+                      flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, col))
+        fillColor = csel.ColourSelect(
+            parent=panel,
+            id=wx.ID_ANY,
+            colour=self.settings.Get(
+                group='vectorLayer',
+                key='areaFillColor',
+                subkey='color'),
+            size=globalvar.DIALOG_COLOR_SIZE)
         fillColor.SetName('GetColour')
         self.winId['vectorLayer:areaFillColor:color'] = fillColor.GetId()
-        gridSizer.Add(item = fillColor, pos = (row, col + 2), flag = wx.ALIGN_RIGHT)
+        gridSizer.Add(item=fillColor, pos=(row, col + 2), flag=wx.ALIGN_RIGHT)
 
-        transpArea = wx.CheckBox(parent  = panel, id = wx.ID_ANY,
-                                 label = _("Transparent"), name = "IsChecked")
-        transpArea.SetValue(self.settings.Get(group = 'vectorLayer', key = 'areaFillColor',
-                                              subkey = ['transparent', 'enabled']))
-        self.winId['vectorLayer:areaFillColor:transparent:enabled'] = transpArea.GetId()
-        gridSizer.Add(item = transpArea, pos = (row, col + 1), flag = wx.ALIGN_CENTER_VERTICAL)
+        transpArea = wx.CheckBox(parent=panel, id=wx.ID_ANY,
+                                 label=_("Transparent"), name="IsChecked")
+        transpArea.SetValue(
+            self.settings.Get(
+                group='vectorLayer',
+                key='areaFillColor',
+                subkey=[
+                    'transparent',
+                    'enabled']))
+        self.winId[
+            'vectorLayer:areaFillColor:transparent:enabled'] = transpArea.GetId()
+        gridSizer.Add(
+            item=transpArea, pos=(row, col + 1),
+            flag=wx.ALIGN_CENTER_VERTICAL)
 
         # line
         row += 1
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                           label = _("Line width:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL, pos = (row, col))
-        hlWidth = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (50, -1),
-                              initial = self.settings.Get(group = 'vectorLayer', key = 'line', subkey = 'width'),
-                              min = 1, max = 1e6, name = "GetValue")
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Line width:")),
+                      flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, col))
+        hlWidth = wx.SpinCtrl(
+            parent=panel, id=wx.ID_ANY, size=(50, -1),
+            initial=self.settings.Get(
+                group='vectorLayer', key='line', subkey='width'),
+            min=1, max=1e6, name="GetValue")
         self.winId['vectorLayer:line:width'] = hlWidth.GetId()
-        gridSizer.Add(item = hlWidth, pos = (row, col + 1), span = (1, 2), flag = wx.ALIGN_RIGHT)
+        gridSizer.Add(
+            item=hlWidth, pos=(row, col + 1),
+            span=(1, 2),
+            flag=wx.ALIGN_RIGHT)
 
         # symbol
         row = 0
         col = 4
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                           label = _("Symbol size:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL, pos = (row, col))
-        ptSize = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (50, -1),
-                              initial = self.settings.Get(group = 'vectorLayer', key = 'point', subkey = 'size'),
-                              min = 1, max = 1e6, name = "GetValue")
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Symbol size:")),
+                      flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, col))
+        ptSize = wx.SpinCtrl(
+            parent=panel, id=wx.ID_ANY, size=(50, -1),
+            initial=self.settings.Get(
+                group='vectorLayer', key='point', subkey='size'),
+            min=1, max=1e6, name="GetValue")
         self.winId['vectorLayer:point:size'] = ptSize.GetId()
-        gridSizer.Add(item = ptSize, pos = (row, col + 2), flag = wx.ALIGN_RIGHT)
+        gridSizer.Add(item=ptSize, pos=(row, col + 2), flag=wx.ALIGN_RIGHT)
 
         row += 1
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                           label = _("Symbol:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL, pos = (row, col))
-        symbolPath = self.settings.Get(group = 'vectorLayer', key = 'point', subkey = 'symbol')
-        symbolLabel = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                    label = symbolPath, name = 'GetLabel')
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Symbol:")),
+                      flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, col))
+        symbolPath = self.settings.Get(
+            group='vectorLayer', key='point', subkey='symbol')
+        symbolLabel = wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                    label=symbolPath, name='GetLabel')
         symbolLabel.SetMinSize((150, -1))
         self.winId['vectorLayer:point:symbol'] = symbolLabel.GetId()
-        gridSizer.Add(item = symbolLabel, flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT, pos = (row, col + 1))
+        gridSizer.Add(
+            item=symbolLabel,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT,
+            pos=(
+                row,
+                col + 1))
 
-        bitmap = wx.Bitmap(os.path.join(globalvar.SYMBDIR, symbolPath) + '.png')
-        bb = wx.BitmapButton(parent = panel, id = wx.ID_ANY, bitmap = bitmap, name = "symbolButton")
+        bitmap = wx.Bitmap(
+            os.path.join(
+                globalvar.SYMBDIR,
+                symbolPath) + '.png')
+        bb = wx.BitmapButton(
+            parent=panel,
+            id=wx.ID_ANY,
+            bitmap=bitmap,
+            name="symbolButton")
         bb.Bind(wx.EVT_BUTTON, self.OnSetSymbol)
-        gridSizer.Add(item = bb, pos = (row, col + 2))
+        gridSizer.Add(item=bb, pos=(row, col + 2))
 
         gridSizer.AddGrowableCol(0)
         gridSizer.AddGrowableCol(3)
-        sizer.Add(item = gridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
-        
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.LEFT |
+                   wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
+
         panel.SetSizer(border)
-        
+
         return panel
 
     def _createAttributeManagerPage(self, notebook):
         """Create notebook page for 'Attribute Table Manager' settings"""
-        panel = SP.ScrolledPanel(parent = notebook, id = wx.ID_ANY)
-        panel.SetupScrolling(scroll_x = False, scroll_y = True)
-        notebook.AddPage(page = panel, text = _("Attributes"))
+        panel = SP.ScrolledPanel(parent=notebook, id=wx.ID_ANY)
+        panel.SetupScrolling(scroll_x=False, scroll_y=True)
+        notebook.AddPage(page=panel, text=_("Attributes"))
 
         pageSizer = wx.BoxSizer(wx.VERTICAL)
 
         #
         # highlighting
         #
-        highlightBox = wx.StaticBox(parent = panel, id = wx.ID_ANY,
-                                    label = " %s " % _("Highlight selected features"))
+        highlightBox = wx.StaticBox(
+            parent=panel, id=wx.ID_ANY, label=" %s " %
+            _("Highlight selected features"))
         highlightSizer = wx.StaticBoxSizer(highlightBox, wx.VERTICAL)
 
-        flexSizer = wx.FlexGridSizer (cols = 2, hgap = 5, vgap = 5)
+        flexSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
         flexSizer.AddGrowableCol(0)
-        
+
         # color
-        label = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Color:"))
-        hlColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
-                                    colour = self.settings.Get(group = 'atm', key = 'highlight', subkey = 'color'),
-                                    size = globalvar.DIALOG_COLOR_SIZE)
+        label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Color:"))
+        hlColor = csel.ColourSelect(
+            parent=panel,
+            id=wx.ID_ANY,
+            colour=self.settings.Get(
+                group='atm',
+                key='highlight',
+                subkey='color'),
+            size=globalvar.DIALOG_COLOR_SIZE)
         hlColor.SetName('GetColour')
         self.winId['atm:highlight:color'] = hlColor.GetId()
 
-        flexSizer.Add(label, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL)
-        flexSizer.Add(hlColor, proportion = 0, flag = wx.ALIGN_RIGHT | wx.FIXED_MINSIZE)
+        flexSizer.Add(label, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
+        flexSizer.Add(
+            hlColor,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT | wx.FIXED_MINSIZE)
 
         # width
-        label = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Line width (in pixels):"))
-        hlWidth = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (50, -1),
-                              initial = self.settings.Get(group = 'atm', key = 'highlight',subkey = 'width'),
-                              min = 1, max = 1e6)
+        label = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Line width (in pixels):"))
+        hlWidth = wx.SpinCtrl(
+            parent=panel, id=wx.ID_ANY, size=(50, -1),
+            initial=self.settings.Get(
+                group='atm', key='highlight', subkey='width'),
+            min=1, max=1e6)
         self.winId['atm:highlight:width'] = hlWidth.GetId()
 
-        flexSizer.Add(label, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL)
-        flexSizer.Add(hlWidth, proportion = 0, flag = wx.ALIGN_RIGHT | wx.FIXED_MINSIZE)
+        flexSizer.Add(label, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
+        flexSizer.Add(
+            hlWidth,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT | wx.FIXED_MINSIZE)
 
         # auto
-        autoHighlight = wx.CheckBox(parent = panel, id = wx.ID_ANY, label = _("Automatically hightlight selected features in map display"))
-        autoHighlight.SetValue(self.settings.Get(group = 'atm', key = 'highlight', subkey = 'auto'))
+        autoHighlight = wx.CheckBox(parent=panel, id=wx.ID_ANY, label=_(
+            "Automatically hightlight selected features in map display"))
+        autoHighlight.SetValue(
+            self.settings.Get(
+                group='atm',
+                key='highlight',
+                subkey='auto'))
         self.winId['atm:highlight:auto'] = autoHighlight.GetId()
-        
-        flexSizer.Add(autoHighlight, proportion = 1)
-        
-        highlightSizer.Add(item = flexSizer,
-                           proportion = 0,
-                           flag = wx.ALL | wx.EXPAND,
-                           border = 5)
 
-        pageSizer.Add(item = highlightSizer,
-                      proportion = 0,
-                      flag = wx.ALL | wx.EXPAND,
-                      border = 5)
+        flexSizer.Add(autoHighlight, proportion=1)
 
+        highlightSizer.Add(item=flexSizer,
+                           proportion=0,
+                           flag=wx.ALL | wx.EXPAND,
+                           border=5)
+
+        pageSizer.Add(item=highlightSizer,
+                      proportion=0,
+                      flag=wx.ALL | wx.EXPAND,
+                      border=5)
+
         #
         # data browser related settings
         #
-        dataBrowserBox = wx.StaticBox(parent = panel, id = wx.ID_ANY,
-                                    label = " %s " % _("Data browser"))
+        dataBrowserBox = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                                      label=" %s " % _("Data browser"))
         dataBrowserSizer = wx.StaticBoxSizer(dataBrowserBox, wx.VERTICAL)
 
-        flexSizer = wx.FlexGridSizer (cols = 2, hgap = 5, vgap = 5)
+        flexSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
         flexSizer.AddGrowableCol(0)
-        label = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Left mouse double click:"))
-        leftDbClick = wx.Choice(parent = panel, id = wx.ID_ANY,
-                                choices = self.settings.Get(group = 'atm', key = 'leftDbClick', subkey = 'choices', settings_type='internal'),
-                                name = "GetSelection")
-        leftDbClick.SetSelection(self.settings.Get(group = 'atm', key = 'leftDbClick', subkey = 'selection'))
+        label = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Left mouse double click:"))
+        leftDbClick = wx.Choice(
+            parent=panel,
+            id=wx.ID_ANY,
+            choices=self.settings.Get(
+                group='atm',
+                key='leftDbClick',
+                subkey='choices',
+                settings_type='internal'),
+            name="GetSelection")
+        leftDbClick.SetSelection(
+            self.settings.Get(
+                group='atm',
+                key='leftDbClick',
+                subkey='selection'))
         self.winId['atm:leftDbClick:selection'] = leftDbClick.GetId()
 
-        flexSizer.Add(label, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL)
-        flexSizer.Add(leftDbClick, proportion = 0, flag = wx.ALIGN_RIGHT | wx.FIXED_MINSIZE)
+        flexSizer.Add(label, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
+        flexSizer.Add(
+            leftDbClick,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT | wx.FIXED_MINSIZE)
 
         # encoding
-        label = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                              label = _("Encoding (e.g. utf-8, ascii, iso8859-1, koi8-r):"))
-        encoding = wx.TextCtrl(parent = panel, id = wx.ID_ANY,
-                               value = self.settings.Get(group = 'atm', key = 'encoding', subkey = 'value'),
-                               name = "GetValue", size = (200, -1))
+        label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_(
+            "Encoding (e.g. utf-8, ascii, iso8859-1, koi8-r):"))
+        encoding = wx.TextCtrl(
+            parent=panel, id=wx.ID_ANY, value=self.settings.Get(
+                group='atm', key='encoding', subkey='value'), name="GetValue", size=(
+                200, -1))
         self.winId['atm:encoding:value'] = encoding.GetId()
 
-        flexSizer.Add(label, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL)
-        flexSizer.Add(encoding, proportion = 0, flag = wx.ALIGN_RIGHT | wx.FIXED_MINSIZE)
+        flexSizer.Add(label, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
+        flexSizer.Add(
+            encoding,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT | wx.FIXED_MINSIZE)
 
         # ask on delete record
-        askOnDeleteRec = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                     label = _("Ask when deleting data record(s) from table"),
-                                     name = 'IsChecked')
-        askOnDeleteRec.SetValue(self.settings.Get(group = 'atm', key = 'askOnDeleteRec', subkey = 'enabled'))
+        askOnDeleteRec = wx.CheckBox(parent=panel, id=wx.ID_ANY, label=_(
+            "Ask when deleting data record(s) from table"), name='IsChecked')
+        askOnDeleteRec.SetValue(
+            self.settings.Get(
+                group='atm',
+                key='askOnDeleteRec',
+                subkey='enabled'))
         self.winId['atm:askOnDeleteRec:enabled'] = askOnDeleteRec.GetId()
 
-        flexSizer.Add(askOnDeleteRec, proportion = 0)
+        flexSizer.Add(askOnDeleteRec, proportion=0)
 
-        dataBrowserSizer.Add(item = flexSizer,
-                           proportion = 0,
-                           flag = wx.ALL | wx.EXPAND,
-                           border = 5)
+        dataBrowserSizer.Add(item=flexSizer,
+                             proportion=0,
+                             flag=wx.ALL | wx.EXPAND,
+                             border=5)
 
-        pageSizer.Add(item = dataBrowserSizer,
-                      proportion = 0,
-                      flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
-                      border = 3)
+        pageSizer.Add(item=dataBrowserSizer,
+                      proportion=0,
+                      flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
+                      border=3)
 
         #
         # create table
         #
-        createTableBox = wx.StaticBox(parent = panel, id = wx.ID_ANY,
-                                    label = " %s " % _("Create table"))
+        createTableBox = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                                      label=" %s " % _("Create table"))
         createTableSizer = wx.StaticBoxSizer(createTableBox, wx.VERTICAL)
 
-        flexSizer = wx.FlexGridSizer (cols = 2, hgap = 5, vgap = 5)
+        flexSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
         flexSizer.AddGrowableCol(0)
 
-        label = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                              label = _("Key column:"))
-        keyColumn = wx.TextCtrl(parent = panel, id = wx.ID_ANY,
-                                size = (250, -1))
-        keyColumn.SetValue(self.settings.Get(group = 'atm', key = 'keycolumn', subkey = 'value'))
+        label = wx.StaticText(parent=panel, id=wx.ID_ANY,
+                              label=_("Key column:"))
+        keyColumn = wx.TextCtrl(parent=panel, id=wx.ID_ANY,
+                                size=(250, -1))
+        keyColumn.SetValue(
+            self.settings.Get(
+                group='atm',
+                key='keycolumn',
+                subkey='value'))
         self.winId['atm:keycolumn:value'] = keyColumn.GetId()
-        
-        flexSizer.Add(label, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL)
-        flexSizer.Add(keyColumn, proportion = 0, flag = wx.ALIGN_RIGHT | wx.FIXED_MINSIZE)
 
-        createTableSizer.Add(item = flexSizer,
-                             proportion = 0,
-                             flag = wx.ALL | wx.EXPAND,
-                             border = 5)
+        flexSizer.Add(label, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
+        flexSizer.Add(
+            keyColumn,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT | wx.FIXED_MINSIZE)
 
-        pageSizer.Add(item = createTableSizer,
-                      proportion = 0,
-                      flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
-                      border = 3)
-        
+        createTableSizer.Add(item=flexSizer,
+                             proportion=0,
+                             flag=wx.ALL | wx.EXPAND,
+                             border=5)
+
+        pageSizer.Add(item=createTableSizer,
+                      proportion=0,
+                      flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
+                      border=3)
+
         panel.SetSizer(pageSizer)
 
         return panel
 
     def _createProjectionPage(self, notebook):
         """Create notebook page for workspace settings"""
-        panel = SP.ScrolledPanel(parent = notebook, id = wx.ID_ANY)
-        panel.SetupScrolling(scroll_x = False, scroll_y = True)
-        notebook.AddPage(page = panel, text = _("Projection"))
-        
+        panel = SP.ScrolledPanel(parent=notebook, id=wx.ID_ANY)
+        panel.SetupScrolling(scroll_x=False, scroll_y=True)
+        notebook.AddPage(page=panel, text=_("Projection"))
+
         border = wx.BoxSizer(wx.VERTICAL)
-        
+
         #
         # projections statusbar settings
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Projection statusbar settings"))
+        box = wx.StaticBox(
+            parent=panel, id=wx.ID_ANY, label=" %s " %
+            _("Projection statusbar settings"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
 
-        gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
 
         # note for users expecting on-the-fly data reprojection
         row = 0
-        note0 = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                             label = _("\nNote: This only controls the coordinates "
-                                       "displayed in the lower-left of the Map "
-                                       "Display\nwindow's status bar. It is purely "
-                                       "cosmetic and does not affect the working "
-                                       "location's\nprojection in any way. You will "
-                                       "need to enable the Projection check box in "
-                                       "the drop-down\nmenu located at the bottom "
-                                       "of the Map Display window.\n"))
-        gridSizer.Add(item = note0,
-                      span = (1, 2),
-                      pos = (row, 0))
+        note0 = wx.StaticText(
+            parent=panel, id=wx.ID_ANY, label=_(
+                "\nNote: This only controls the coordinates "
+                "displayed in the lower-left of the Map "
+                "Display\nwindow's status bar. It is purely "
+                "cosmetic and does not affect the working "
+                "location's\nprojection in any way. You will "
+                "need to enable the Projection check box in "
+                "the drop-down\nmenu located at the bottom "
+                "of the Map Display window.\n"))
+        gridSizer.Add(item=note0,
+                      span=(1, 2),
+                      pos=(row, 0))
 
         # epsg
         row += 1
-        label = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                              label = _("EPSG code:"))
-        epsgCode = wx.ComboBox(parent = panel, id = wx.ID_ANY,
-                               name = "GetValue",
-                               size = (150, -1))
+        label = wx.StaticText(parent=panel, id=wx.ID_ANY,
+                              label=_("EPSG code:"))
+        epsgCode = wx.ComboBox(parent=panel, id=wx.ID_ANY,
+                               name="GetValue",
+                               size=(150, -1))
         self.epsgCodeDict = dict()
-        epsgCode.SetValue(str(self.settings.Get(group = 'projection', key = 'statusbar', subkey = 'epsg')))
+        epsgCode.SetValue(str(self.settings.Get(
+            group='projection', key='statusbar', subkey='epsg')))
         self.winId['projection:statusbar:epsg'] = epsgCode.GetId()
-        
-        gridSizer.Add(item = label,
-                      pos = (row, 0),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = epsgCode,
-                      pos = (row, 1), span = (1, 2))
 
+        gridSizer.Add(item=label,
+                      pos=(row, 0),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(item=epsgCode,
+                      pos=(row, 1), span=(1, 2))
+
         # proj
         row += 1
-        label = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                              label = _("Proj.4 string (required):"))
-        projString = wx.TextCtrl(parent = panel, id = wx.ID_ANY,
-                                 value = self.settings.Get(group = 'projection', key = 'statusbar', subkey = 'proj4'),
-                                 name = "GetValue", size = (400, -1))
+        label = wx.StaticText(parent=panel, id=wx.ID_ANY,
+                              label=_("Proj.4 string (required):"))
+        projString = wx.TextCtrl(
+            parent=panel, id=wx.ID_ANY, value=self.settings.Get(
+                group='projection', key='statusbar', subkey='proj4'), name="GetValue", size=(
+                400, -1))
         self.winId['projection:statusbar:proj4'] = projString.GetId()
 
-        gridSizer.Add(item = label,
-                      pos = (row, 0),
-                      flag  =  wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = projString,
-                      pos = (row, 1), span = (1, 2),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        
+        gridSizer.Add(item=label,
+                      pos=(row, 0),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(item=projString,
+                      pos=(row, 1), span=(1, 2),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
+
         # epsg file
         row += 1
-        label = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                              label = _("EPSG file:"))
-        projFile = wx.TextCtrl(parent = panel, id = wx.ID_ANY,
-                               value  =  self.settings.Get(group = 'projection', key = 'statusbar', subkey = 'projFile'),
-                               name = "GetValue", size = (400, -1))
+        label = wx.StaticText(parent=panel, id=wx.ID_ANY,
+                              label=_("EPSG file:"))
+        projFile = wx.TextCtrl(
+            parent=panel, id=wx.ID_ANY, value=self.settings.Get(
+                group='projection', key='statusbar', subkey='projFile'),
+            name="GetValue", size=(400, -1))
         self.winId['projection:statusbar:projFile'] = projFile.GetId()
-        gridSizer.Add(item = label,
-                      pos = (row, 0),
-                      flag  =  wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = projFile,
-                      pos = (row, 1),
-                      flag  =  wx.ALIGN_CENTER_VERTICAL)
-        
+        gridSizer.Add(item=label,
+                      pos=(row, 0),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(item=projFile,
+                      pos=(row, 1),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
+
         # note + button
         row += 1
-        note = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                             label = _("Load EPSG codes (be patient), enter EPSG code or "
-                                       "insert Proj.4 string directly."))
-        gridSizer.Add(item = note,
-                      span = (1, 2),
-                      pos = (row, 0))
+        note = wx.StaticText(
+            parent=panel, id=wx.ID_ANY, label=_(
+                "Load EPSG codes (be patient), enter EPSG code or "
+                "insert Proj.4 string directly."))
+        gridSizer.Add(item=note,
+                      span=(1, 2),
+                      pos=(row, 0))
 
         row += 1
-        epsgLoad = wx.Button(parent = panel, id = wx.ID_ANY,
-                             label = _("&Load EPSG codes"))
-        gridSizer.Add(item = epsgLoad,
-                      flag = wx.ALIGN_RIGHT,
-                      pos = (row, 1))
-        
+        epsgLoad = wx.Button(parent=panel, id=wx.ID_ANY,
+                             label=_("&Load EPSG codes"))
+        gridSizer.Add(item=epsgLoad,
+                      flag=wx.ALIGN_RIGHT,
+                      pos=(row, 1))
+
         gridSizer.AddGrowableCol(1)
-        sizer.Add(item = gridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 3)
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=3)
 
         #
         # format
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Coordinates format"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Coordinates format"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
-        gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
 
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
+
         row = 0
         # ll format
-        ll = wx.RadioBox(parent = panel, id = wx.ID_ANY,
-                         label = " %s " % _("Lat/long projections"),
-                         choices = ["DMS", "DEG"],
-                         name = "GetStringSelection")
+        ll = wx.RadioBox(parent=panel, id=wx.ID_ANY,
+                         label=" %s " % _("Lat/long projections"),
+                         choices=["DMS", "DEG"],
+                         name="GetStringSelection")
         self.winId['projection:format:ll'] = ll.GetId()
-        if self.settings.Get(group = 'projection', key = 'format', subkey = 'll') == 'DMS':
+        if self.settings.Get(group='projection',
+                             key='format', subkey='ll') == 'DMS':
             ll.SetSelection(0)
         else:
             ll.SetSelection(1)
-        
+
         # precision
-        precision =  wx.SpinCtrl(parent = panel, id = wx.ID_ANY,
-                                 min = 0, max = 12,
-                                 name = "GetValue")
-        precision.SetValue(int(self.settings.Get(group = 'projection', key = 'format', subkey = 'precision')))
+        precision = wx.SpinCtrl(parent=panel, id=wx.ID_ANY,
+                                min=0, max=12,
+                                name="GetValue")
+        precision.SetValue(int(self.settings.Get(
+            group='projection', key='format', subkey='precision')))
         self.winId['projection:format:precision'] = precision.GetId()
-                
-        gridSizer.Add(item = ll,
-                      pos = (row, 0))
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Precision:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
-                      border = 20,
-                      pos = (row, 1))
-        gridSizer.Add(item = precision,
-                      flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 2))
-        
-        
+
+        gridSizer.Add(item=ll,
+                      pos=(row, 0))
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Precision:")),
+                      flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
+                      border=20,
+                      pos=(row, 1))
+        gridSizer.Add(item=precision,
+                      flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(row, 2))
+
         gridSizer.AddGrowableCol(2)
-        sizer.Add(item = gridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
-        
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.LEFT |
+                   wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
+
         panel.SetSizer(border)
 
         # bindings
         epsgLoad.Bind(wx.EVT_BUTTON, self.OnLoadEpsgCodes)
         epsgCode.Bind(wx.EVT_COMBOBOX, self.OnSetEpsgCode)
         epsgCode.Bind(wx.EVT_TEXT_ENTER, self.OnSetEpsgCode)
-        
+
         return panel
 
     def _updateSettings(self):
@@ -1342,7 +1797,8 @@
         #
         # update default window dimension
         #
-        if self.settings.Get(group = 'general', key = 'defWindowPos', subkey = 'enabled') is True:
+        if self.settings.Get(
+                group='general', key='defWindowPos', subkey='enabled') is True:
             dim = ''
             # layer manager
             pos = self.parent.GetPosition()
@@ -1350,56 +1806,68 @@
             dim = '%d,%d,%d,%d' % (pos[0], pos[1], size[0], size[1])
             # opened displays
             for mapdisp in self._giface.GetAllMapDisplays():
-                pos  = mapdisp.GetPosition()
+                pos = mapdisp.GetPosition()
                 size = mapdisp.GetSize()
 
                 # window size must be larger than zero, not minimized
                 if not mapdisp.IsIconized() and (size[0] > 0 and size[1] > 0):
                     dim += ',%d,%d,%d,%d' % (pos[0], pos[1], size[0], size[1])
 
-            self.settings.Set(group = 'general', key = 'defWindowPos', subkey = 'dim', value = dim)
+            self.settings.Set(
+                group='general',
+                key='defWindowPos',
+                subkey='dim',
+                value=dim)
 
         return True
 
     def OnCheckColorTable(self, event):
         """Set/unset default color table"""
-        win = self.FindWindowById(self.winId['rasterLayer:colorTable:selection'])
+        win = self.FindWindowById(
+            self.winId['rasterLayer:colorTable:selection'])
         if event.IsChecked():
             win.Enable()
         else:
             win.Enable(False)
-        
+
     def OnLoadEpsgCodes(self, event):
         """Load EPSG codes from the file"""
         win = self.FindWindowById(self.winId['projection:statusbar:projFile'])
         path = win.GetValue()
-        epsgCombo = self.FindWindowById(self.winId['projection:statusbar:epsg'])
+        epsgCombo = self.FindWindowById(
+            self.winId['projection:statusbar:epsg'])
         wx.BeginBusyCursor()
         try:
             self.epsgCodeDict = ReadEpsgCodes(path)
         except OpenError as e:
             wx.EndBusyCursor()
             epsgCombo.SetItems([])
-            GError(parent = self,
-                   message = _("Unable to read EPGS codes: {}").format(e), showTraceback=False)
+            GError(
+                parent=self,
+                message=_("Unable to read EPGS codes: {}").format(e),
+                showTraceback=False)
             return
 
-        if type(self.epsgCodeDict) == type(''):
-            wx.MessageBox(parent = self,
-                          message = _("Unable to read EPSG codes: %s") % self.epsgCodeDict,
-                          caption = _("Error"),  style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
+        if isinstance(self.epsgCodeDict, type('')):
+            wx.MessageBox(
+                parent=self,
+                message=_("Unable to read EPSG codes: %s") %
+                self.epsgCodeDict,
+                caption=_("Error"),
+                style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
             self.epsgCodeDict = dict()
             epsgCombo.SetItems([])
             epsgCombo.SetValue('')
-            self.FindWindowById(self.winId['projection:statusbar:proj4']).SetValue('')
+            self.FindWindowById(
+                self.winId['projection:statusbar:proj4']).SetValue('')
             wx.EndBusyCursor()
             return
-        
+
         choices = map(str, sorted(self.epsgCodeDict.keys()))
 
         epsgCombo.SetItems(choices)
         wx.EndBusyCursor()
-        code = 4326 # default
+        code = 4326  # default
         win = self.FindWindowById(self.winId['projection:statusbar:proj4'])
         if code in self.epsgCodeDict:
             epsgCombo.SetStringSelection(str(code))
@@ -1408,43 +1876,52 @@
             epsgCombo.SetSelection(0)
             code = int(epsgCombo.GetStringSelection())
             win.SetValue(self.epsgCodeDict[code][1].replace('<>', '').strip())
-    
+
     def OnSetEpsgCode(self, event):
         """EPSG code selected"""
         winCode = self.FindWindowById(event.GetId())
         win = self.FindWindowById(self.winId['projection:statusbar:proj4'])
         if not self.epsgCodeDict:
-            wx.MessageBox(parent = self,
-                          message = _("EPSG code %s not found") % event.GetString(),
-                          caption = _("Error"),  style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
+            wx.MessageBox(
+                parent=self,
+                message=_("EPSG code %s not found") %
+                event.GetString(),
+                caption=_("Error"),
+                style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
             winCode.SetValue('')
             win.SetValue('')
-        
+
         try:
             code = int(event.GetString())
         except ValueError:
-            wx.MessageBox(parent = self,
-                          message = _("EPSG code %s not found") % str(code),
-                          caption = _("Error"),  style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
+            wx.MessageBox(
+                parent=self,
+                message=_("EPSG code %s not found") %
+                str(code),
+                caption=_("Error"),
+                style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
             winCode.SetValue('')
             win.SetValue('')
-        
+
         try:
             win.SetValue(self.epsgCodeDict[code][1].replace('<>', '').strip())
         except KeyError:
-            wx.MessageBox(parent = self,
-                          message = _("EPSG code %s not found") % str(code),
-                          caption = _("Error"),  style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
+            wx.MessageBox(
+                parent=self,
+                message=_("EPSG code %s not found") %
+                str(code),
+                caption=_("Error"),
+                style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
             winCode.SetValue('')
             win.SetValue('')
-        
+
     def OnSetFont(self, event):
         """'Set font' button pressed"""
-        dlg = DefaultFontDialog(parent = self,
-                                title = _('Select default display font'),
-                                style = wx.DEFAULT_DIALOG_STYLE,
-                                type = 'font')
-        
+        dlg = DefaultFontDialog(parent=self,
+                                title=_('Select default display font'),
+                                style=wx.DEFAULT_DIALOG_STYLE,
+                                type='font')
+
         if dlg.ShowModal() == wx.ID_OK:
             # set default font and encoding environmental variables
             if dlg.font:
@@ -1453,52 +1930,66 @@
                     self.settings.Set(group='display', value=dlg.font,
                                       key='font', subkey='type')
                 except UnicodeEncodeError:
-                    GError(parent=self, message=_("Failed to set default display font. "
-                                                  "Try different font."),
-                           showTraceback=True)
+                    GError(
+                        parent=self, message=_(
+                            "Failed to set default display font. "
+                            "Try different font."), showTraceback=True)
                     dlg.Destroy()
                     return
 
             if dlg.encoding and \
                     dlg.encoding != "ISO-8859-1":
                 os.environ["GRASS_ENCODING"] = dlg.encoding
-                self.settings.Set(group = 'display', value = dlg.encoding,
-                                  key = 'font', subkey = 'encoding')
-                
+                self.settings.Set(group='display', value=dlg.encoding,
+                                  key='font', subkey='encoding')
+
         dlg.Destroy()
-        
+
         event.Skip()
 
     def OnSetOutputFont(self, event):
         """'Set output font' button pressed
         """
 
-        type = self.settings.Get(group = 'appearance', key = 'outputfont', subkey = 'type')   
-                           
-        size = self.settings.Get(group = 'appearance', key = 'outputfont', subkey = 'size')
-        if size == None or size == 0: size = 11
+        type = self.settings.Get(
+            group='appearance',
+            key='outputfont',
+            subkey='type')
+
+        size = self.settings.Get(
+            group='appearance',
+            key='outputfont',
+            subkey='size')
+        if size is None or size == 0:
+            size = 11
         size = float(size)
-        if type == None or type == '': type = 'Courier'
+        if type is None or type == '':
+            type = 'Courier'
 
-        outfont = wx.Font(size, wx.FONTFAMILY_MODERN, wx.NORMAL, wx.FONTWEIGHT_NORMAL, faceName=type)
+        outfont = wx.Font(
+            size,
+            wx.FONTFAMILY_MODERN,
+            wx.NORMAL,
+            wx.FONTWEIGHT_NORMAL,
+            faceName=type)
 
         fontdata = wx.FontData()
         fontdata.EnableEffects(True)
         fontdata.SetColour('black')
         fontdata.SetInitialFont(outfont)
-        
+
         dlg = wx.FontDialog(self, fontdata)
-        
+
         'FIXME: native font dialog does not initialize with current font'
 
         if dlg.ShowModal() == wx.ID_OK:
             outdata = dlg.GetFontData()
             font = outdata.GetChosenFont()
 
-            self.settings.Set(group = 'appearance', value = font.GetFaceName(),
-                                  key = 'outputfont', subkey = 'type')
-            self.settings.Set(group = 'appearance', value = font.GetPointSize(),
-                                  key = 'outputfont', subkey = 'size')
+            self.settings.Set(group='appearance', value=font.GetFaceName(),
+                              key='outputfont', subkey='type')
+            self.settings.Set(group='appearance', value=font.GetPointSize(),
+                              key='outputfont', subkey='size')
         dlg.Destroy()
 
         event.Skip()
@@ -1508,8 +1999,8 @@
         winId = self.winId['vectorLayer:point:symbol']
         label = self.FindWindowById(winId)
         bb = self.FindWindowByName('symbolButton')
-        dlg = SymbolDialog(self, symbolPath = globalvar.SYMBDIR,
-                           currentSymbol = label.GetLabel())
+        dlg = SymbolDialog(self, symbolPath=globalvar.SYMBDIR,
+                           currentSymbol=label.GetLabel())
         if dlg.ShowModal() == wx.ID_OK:
             img = dlg.GetSelectedSymbolPath()
             label.SetLabel(dlg.GetSelectedSymbolName())
@@ -1525,121 +2016,130 @@
             enable = True
         scrollId = self.winId['display:scrollDirection:selection']
         self.FindWindowById(scrollId).Enable(enable)
-        
+
+
 class DefaultFontDialog(wx.Dialog):
     """
     Opens a file selection dialog to select default font
     to use in all GRASS displays
     """
-    def __init__(self, parent, title, id = wx.ID_ANY,
-                 style = wx.DEFAULT_DIALOG_STYLE |
+
+    def __init__(self, parent, title, id=wx.ID_ANY,
+                 style=wx.DEFAULT_DIALOG_STYLE |
                  wx.RESIZE_BORDER,
-                 settings = UserSettings,
-                 type = 'font'):
-        
+                 settings=UserSettings,
+                 type='font'):
+
         self.settings = settings
         self.type = type
-        
-        wx.Dialog.__init__(self, parent, id, title, style = style)
 
-        panel = wx.Panel(parent = self, id = wx.ID_ANY)
-        
+        wx.Dialog.__init__(self, parent, id, title, style=style)
+
+        panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
         self.fontlist = self.GetFonts()
-        
+
         border = wx.BoxSizer(wx.VERTICAL)
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Font settings"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Font settings"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
 
-        gridSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
+        gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
 
-        label = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                              label = _("Select font:"))
-        gridSizer.Add(item = label,
-                      flag = wx.ALIGN_TOP,
-                      pos = (0,0))
-        
-        self.fontlb = wx.ListBox(parent = panel, id = wx.ID_ANY, pos = wx.DefaultPosition,
-                                 choices = self.fontlist,
-                                 style = wx.LB_SINGLE|wx.LB_SORT)
+        label = wx.StaticText(parent=panel, id=wx.ID_ANY,
+                              label=_("Select font:"))
+        gridSizer.Add(item=label,
+                      flag=wx.ALIGN_TOP,
+                      pos=(0, 0))
+
+        self.fontlb = wx.ListBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            pos=wx.DefaultPosition,
+            choices=self.fontlist,
+            style=wx.LB_SINGLE | wx.LB_SORT)
         self.Bind(wx.EVT_LISTBOX, self.EvtListBox, self.fontlb)
         self.Bind(wx.EVT_LISTBOX_DCLICK, self.EvtListBoxDClick, self.fontlb)
 
-        gridSizer.Add(item = self.fontlb,
-                flag = wx.EXPAND, pos = (1, 0))
+        gridSizer.Add(item=self.fontlb,
+                      flag=wx.EXPAND, pos=(1, 0))
 
         if self.type == 'font':
             if "GRASS_FONT" in os.environ:
                 self.font = os.environ["GRASS_FONT"]
             else:
-                self.font = self.settings.Get(group = 'display',
-                                              key = 'font', subkey = 'type')
-            self.encoding = self.settings.Get(group = 'display',
-                                          key = 'font', subkey = 'encoding')
+                self.font = self.settings.Get(group='display',
+                                              key='font', subkey='type')
+            self.encoding = self.settings.Get(group='display',
+                                              key='font', subkey='encoding')
 
-            label = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                  label = _("Character encoding:"))
-            gridSizer.Add(item = label,
-                          flag = wx.ALIGN_CENTER_VERTICAL,
-                          pos = (2, 0))
+            label = wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                  label=_("Character encoding:"))
+            gridSizer.Add(item=label,
+                          flag=wx.ALIGN_CENTER_VERTICAL,
+                          pos=(2, 0))
 
-            self.textentry = wx.TextCtrl(parent = panel, id = wx.ID_ANY,
-                                         value = self.encoding)
-            gridSizer.Add(item = self.textentry,
-                    flag = wx.EXPAND, pos = (3, 0))
+            self.textentry = wx.TextCtrl(parent=panel, id=wx.ID_ANY,
+                                         value=self.encoding)
+            gridSizer.Add(item=self.textentry,
+                          flag=wx.EXPAND, pos=(3, 0))
 
             self.textentry.Bind(wx.EVT_TEXT, self.OnEncoding)
 
         elif self.type == 'outputfont':
-            self.font = self.settings.Get(group = 'appearance',
-                                              key = 'outputfont', subkey = 'type')
-            self.fontsize = self.settings.Get(group = 'appearance',
-                                          key = 'outputfont', subkey = 'size')
-            label = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                              label = _("Font size:"))
-            gridSizer.Add(item = label,
-                      flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (2, 0))
-                      
-            self.spin = wx.SpinCtrl(parent = panel, id = wx.ID_ANY)
+            self.font = self.settings.Get(group='appearance',
+                                          key='outputfont', subkey='type')
+            self.fontsize = self.settings.Get(group='appearance',
+                                              key='outputfont', subkey='size')
+            label = wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                  label=_("Font size:"))
+            gridSizer.Add(item=label,
+                          flag=wx.ALIGN_CENTER_VERTICAL,
+                          pos=(2, 0))
+
+            self.spin = wx.SpinCtrl(parent=panel, id=wx.ID_ANY)
             if self.fontsize:
                 self.spin.SetValue(int(self.fontsize))
             self.spin.Bind(wx.EVT_SPINCTRL, self.OnSizeSpin)
             self.spin.Bind(wx.EVT_TEXT, self.OnSizeSpin)
-            gridSizer.Add(item = self.spin,
-                      flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (3, 0))
+            gridSizer.Add(item=self.spin,
+                          flag=wx.ALIGN_CENTER_VERTICAL,
+                          pos=(3, 0))
 
-        else: 
+        else:
             return
 
         if self.font:
             self.fontlb.SetStringSelection(self.font, True)
 
         gridSizer.AddGrowableCol(0)
-        sizer.Add(item = gridSizer, proportion = 1,
-                  flag = wx.EXPAND | wx.ALL,
-                  border = 5)
+        sizer.Add(item=gridSizer, proportion=1,
+                  flag=wx.EXPAND | wx.ALL,
+                  border=5)
 
-        border.Add(item = sizer, proportion = 1,
-                   flag = wx.ALL | wx.EXPAND, border = 3)
-        
+        border.Add(item=sizer, proportion=1,
+                   flag=wx.ALL | wx.EXPAND, border=3)
+
         btnsizer = wx.StdDialogButtonSizer()
 
-        btn = wx.Button(parent = panel, id = wx.ID_OK)
+        btn = wx.Button(parent=panel, id=wx.ID_OK)
         btn.SetDefault()
         btnsizer.AddButton(btn)
 
-        btn = wx.Button(parent = panel, id = wx.ID_CANCEL)
+        btn = wx.Button(parent=panel, id=wx.ID_CANCEL)
         btnsizer.AddButton(btn)
         btnsizer.Realize()
 
-        border.Add(item = btnsizer, proportion = 0,
-                   flag = wx.EXPAND | wx.ALIGN_RIGHT | wx.ALL, border = 5)
-        
+        border.Add(item=btnsizer, proportion=0,
+                   flag=wx.EXPAND | wx.ALIGN_RIGHT | wx.ALL, border=5)
+
         panel.SetAutoLayout(True)
         panel.SetSizer(border)
         border.Fit(self)
-        
+
         self.Layout()
 
     def OnEncoding(self, event):
@@ -1652,11 +2152,11 @@
     def EvtListBoxDClick(self, event):
         self.font = event.GetString()
         event.Skip()
-        
+
     def OnSizeSpin(self, event):
         self.fontsize = self.spin.GetValue()
         event.Skip()
-    
+
     def GetFonts(self):
         """
         parses fonts directory or fretypecap file to get a list of fonts
@@ -1676,48 +2176,52 @@
             return fontlist
 
         dfonts = ret.splitlines()
-        dfonts.sort(lambda x,y: cmp(x.lower(), y.lower()))
+        dfonts.sort(lambda x, y: cmp(x.lower(), y.lower()))
         for item in range(len(dfonts)):
             # ignore duplicate fonts and those starting with #
             if not dfonts[item].startswith('#') and \
-                  dfonts[item] != dfonts[item-1]:
+                    dfonts[item] != dfonts[item - 1]:
                 fontlist.append(dfonts[item])
 
         return fontlist
 
+
 class MapsetAccess(wx.Dialog):
     """Controls setting options and displaying/hiding map overlay
     decorations
     """
-    def __init__(self, parent, id = wx.ID_ANY,
-                 title = _('Manage access to mapsets'),
-                 size  =  (350, 400),
-                 style  =  wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
-        wx.Dialog.__init__(self, parent, id, title, size = size, style = style)
 
-        self.all_mapsets_ordered = ListOfMapsets(get = 'ordered')
-        self.accessible_mapsets  = ListOfMapsets(get = 'accessible')
+    def __init__(self, parent, id=wx.ID_ANY,
+                 title=_('Manage access to mapsets'),
+                 size=(350, 400),
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
+        wx.Dialog.__init__(self, parent, id, title, size=size, style=style)
+
+        self.all_mapsets_ordered = ListOfMapsets(get='ordered')
+        self.accessible_mapsets = ListOfMapsets(get='accessible')
         self.curr_mapset = grass.gisenv()['MAPSET']
 
-        # make a checklistbox from available mapsets and check those that are active
+        # make a checklistbox from available mapsets and check those that are
+        # active
         sizer = wx.BoxSizer(wx.VERTICAL)
 
-        label = wx.StaticText(parent = self, id = wx.ID_ANY,
-                              label = _("Check a mapset to make it accessible, uncheck it to hide it.\n"
-                                        "  Notes:\n"
-                                        "    - The current mapset is always accessible.\n"
-                                        "    - You may only write to the current mapset.\n"
-                                        "    - You may only write to mapsets which you own."))
-        
-        sizer.Add(item = label, proportion = 0,
-                  flag = wx.ALL, border = 5)
+        label = wx.StaticText(
+            parent=self, id=wx.ID_ANY, label=_(
+                "Check a mapset to make it accessible, uncheck it to hide it.\n"
+                "  Notes:\n"
+                "    - The current mapset is always accessible.\n"
+                "    - You may only write to the current mapset.\n"
+                "    - You may only write to mapsets which you own."))
 
-        self.mapsetlb = CheckListMapset(parent = self)
+        sizer.Add(item=label, proportion=0,
+                  flag=wx.ALL, border=5)
+
+        self.mapsetlb = CheckListMapset(parent=self)
         self.mapsetlb.LoadData()
-        
-        sizer.Add(item = self.mapsetlb, proportion = 1,
-                  flag = wx.ALL | wx.EXPAND, border = 5)
 
+        sizer.Add(item=self.mapsetlb, proportion=1,
+                  flag=wx.ALL | wx.EXPAND, border=5)
+
         # check all accessible mapsets
         for mset in self.accessible_mapsets:
             self.mapsetlb.CheckItem(self.all_mapsets_ordered.index(mset), True)
@@ -1726,10 +2230,10 @@
         #self.mapsetlb.Enable(0, False)
 
         # dialog buttons
-        line = wx.StaticLine(parent = self, id = wx.ID_ANY,
-                             style = wx.LI_HORIZONTAL)
-        sizer.Add(item = line, proportion = 0,
-                  flag = wx.EXPAND | wx.ALIGN_CENTRE | wx.ALL, border = 5)
+        line = wx.StaticLine(parent=self, id=wx.ID_ANY,
+                             style=wx.LI_HORIZONTAL)
+        sizer.Add(item=line, proportion=0,
+                  flag=wx.EXPAND | wx.ALIGN_CENTRE | wx.ALL, border=5)
 
         btnsizer = wx.StdDialogButtonSizer()
         okbtn = wx.Button(self, wx.ID_OK)
@@ -1740,8 +2244,8 @@
         btnsizer.AddButton(cancelbtn)
         btnsizer.Realize()
 
-        sizer.Add(item = btnsizer, proportion = 0,
-                  flag = wx.EXPAND | wx.ALIGN_RIGHT | wx.ALL, border = 5)
+        sizer.Add(item=btnsizer, proportion=0,
+                  flag=wx.EXPAND | wx.ALIGN_RIGHT | wx.ALL, border=5)
 
         # do layout
         self.Layout()
@@ -1749,7 +2253,7 @@
         sizer.Fit(self)
 
         self.SetMinSize(size)
-        
+
     def GetMapsets(self):
         """Get list of checked mapsets"""
         ms = []
@@ -1761,13 +2265,16 @@
 
         return ms
 
-class CheckListMapset(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.CheckListCtrlMixin):
+
+class CheckListMapset(
+        wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.CheckListCtrlMixin):
     """List of mapset/owner/group"""
-    def __init__(self, parent, log = None):
+
+    def __init__(self, parent, log=None):
         self.parent = parent
-        
+
         wx.ListCtrl.__init__(self, parent, wx.ID_ANY,
-                             style = wx.LC_REPORT)
+                             style=wx.LC_REPORT)
         listmix.CheckListCtrlMixin.__init__(self)
         self.log = log
 
@@ -1780,28 +2287,33 @@
         self.InsertColumn(1, _('Owner'))
         ### self.InsertColumn(2, _('Group'))
         gisenv = grass.gisenv()
-        locationPath = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'])
+        locationPath = os.path.join(
+            gisenv['GISDBASE'],
+            gisenv['LOCATION_NAME'])
 
         for mapset in self.parent.all_mapsets_ordered:
-            index = self.InsertStringItem(sys.maxint, mapset)
+            index = self.InsertStringItem(sys.maxsize, mapset)
             mapsetPath = os.path.join(locationPath,
                                       mapset)
             stat_info = os.stat(mapsetPath)
             if havePwd:
                 try:
-                    self.SetStringItem(index, 1, "%s" % pwd.getpwuid(stat_info.st_uid)[0])
+                    self.SetStringItem(
+                        index, 1, "%s" %
+                        pwd.getpwuid(
+                            stat_info.st_uid)[0])
                 except KeyError:
                     self.SetStringItem(index, 1, "nobody")
                 # FIXME: get group name
-                ### self.SetStringItem(index, 2, "%-8s" % stat_info.st_gid) 
+                ### self.SetStringItem(index, 2, "%-8s" % stat_info.st_gid)
             else:
                 # FIXME: no pwd under MS Windows (owner: 0, group: 0)
                 self.SetStringItem(index, 1, "%-8s" % stat_info.st_uid)
                 ### self.SetStringItem(index, 2, "%-8s" % stat_info.st_gid)
-                
-        self.SetColumnWidth(col = 0, width = wx.LIST_AUTOSIZE)
+
+        self.SetColumnWidth(col=0, width=wx.LIST_AUTOSIZE)
         ### self.SetColumnWidth(col = 1, width = wx.LIST_AUTOSIZE)
-        
+
     def OnCheckItem(self, index, flag):
         """Mapset checked/unchecked"""
         mapset = self.parent.all_mapsets_ordered[index]

Modified: grass/trunk/gui/wxpython/gui_core/prompt.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/prompt.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gui_core/prompt.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -30,64 +30,69 @@
 
 from grass.pydispatch.signal import Signal
 
-from core          import globalvar
-from core          import utils
-from core.gcmd     import EncodeString, DecodeString
+from core import globalvar
+from core import utils
+from core.gcmd import EncodeString, DecodeString
 from core.utils import _
 
 
 class GPrompt(object):
     """Abstract class for interactive wxGUI prompt
-    
+
     Signal promptRunCmd - emitted to run command from prompt
                         - attribute 'cmd'
 
     See subclass GPromptPopUp and GPromptSTC.
     """
+
     def __init__(self, parent, menuModel):
         self.parent = parent                 # GConsole
-        self.panel  = self.parent.GetPanel()
+        self.panel = self.parent.GetPanel()
 
         self.promptRunCmd = Signal('GPrompt.promptRunCmd')
 
         # probably only subclasses need this
         self._menuModel = menuModel
 
-        self.mapList    = self._getListOfMaps()
+        self.mapList = self._getListOfMaps()
         self.mapsetList = utils.ListOfMapsets()
-        
+
         # auto complete items
-        self.autoCompList   = list()
+        self.autoCompList = list()
         self.autoCompFilter = None
-        
+
         # command description (gtask.grassTask)
-        self.cmdDesc   = None
-        
+        self.cmdDesc = None
+
         self.cmdbuffer = self._readHistory()
-        self.cmdindex  = len(self.cmdbuffer)
-        
+        self.cmdindex = len(self.cmdbuffer)
+
         # list of traced commands
         self.commands = list()
-        
+
     def _readHistory(self):
         """Get list of commands from history file"""
         hist = list()
         env = grass.gisenv()
         try:
-            fileHistory = codecs.open(os.path.join(env['GISDBASE'],
-                                                   env['LOCATION_NAME'],
-                                                   env['MAPSET'],
-                                                   '.bash_history'),
-                                      encoding = 'utf-8', mode = 'r', errors='replace')
+            fileHistory = codecs.open(
+                os.path.join(
+                    env['GISDBASE'],
+                    env['LOCATION_NAME'],
+                    env['MAPSET'],
+                    '.bash_history'),
+                encoding='utf-8',
+                mode='r',
+                errors='replace')
         except IOError:
             return hist
-        
+
         try:
             for line in fileHistory.readlines():
                 hist.append(line.replace('\n', ''))
         finally:
             fileHistory.close()
-        
+
         return hist
 
     def _getListOfMaps(self):
@@ -95,18 +100,18 @@
         result = dict()
         result['raster'] = grass.list_strings('raster')
         result['vector'] = grass.list_strings('vector')
-        
+
         return result
-    
+
     def _runCmd(self, cmdString):
         """Run command
-        
+
         :param str cmdString: command to run
         """
         if not cmdString:
             return
 
-        self.commands.append(cmdString) # trace commands
+        self.commands.append(cmdString)  # trace commands
 
         # parse command into list
         try:
@@ -118,36 +123,37 @@
         self.promptRunCmd.emit(cmd=cmd)
 
         # add command to history & clean prompt
-        ### self.UpdateCmdHistory(cmd)
+        # self.UpdateCmdHistory(cmd)
         self.OnCmdErase(None)
         self.ShowStatusText('')
-        
+
     def GetCommands(self):
         """Get list of launched commands"""
         return self.commands
-    
+
     def ClearCommands(self):
         """Clear list of commands"""
         del self.commands[:]
 
 
 class GPromptSTC(GPrompt, wx.stc.StyledTextCtrl):
-    """Styled wxGUI prompt with autocomplete and calltips"""  
-    def __init__(self, parent, menuModel, margin = False):
-        GPrompt.__init__(self, parent = parent, menuModel = menuModel)
-        wx.stc.StyledTextCtrl.__init__(self, self.panel, id = wx.ID_ANY)
-        
+    """Styled wxGUI prompt with autocomplete and calltips"""
+
+    def __init__(self, parent, menuModel, margin=False):
+        GPrompt.__init__(self, parent=parent, menuModel=menuModel)
+        wx.stc.StyledTextCtrl.__init__(self, self.panel, id=wx.ID_ANY)
+
         #
         # styles
-        #                
+        #
         self.SetWrapMode(True)
-        self.SetUndoCollection(True)        
-        
+        self.SetUndoCollection(True)
+
         #
         # create command and map lists for autocompletion
         #
-        self.AutoCompSetIgnoreCase(False) 
-                
+        self.AutoCompSetIgnoreCase(False)
+
         #
         # line margins
         #
@@ -159,7 +165,7 @@
             self.SetMarginWidth(0, 30)
         else:
             self.SetMarginWidth(0, 0)
-        
+
         #
         # miscellaneous
         #
@@ -168,7 +174,7 @@
         self.UsePopUp(True)
         self.SetSelBackground(True, "#FFFF00")
         self.SetUseHorizontalScrollBar(True)
-        
+
         #
         # bindings
         #
@@ -185,20 +191,21 @@
 
         # signal to notify selected command
         self.commandSelected = Signal('GPromptSTC.commandSelected')
-        
+
     def OnTextSelectionChanged(self, event):
         """Copy selected text to clipboard and skip event.
         The same function is in GStc class (goutput.py).
         """
         wx.CallAfter(self.Copy)
         event.Skip()
-        
+
     def OnItemChanged(self, event):
-        """Change text in statusbar 
+        """Change text in statusbar
         if the item selection in the auto-completion list is changed"""
         # list of commands
         if self.toComplete['entity'] == 'command':
-            item = self.toComplete['cmd'].rpartition('.')[0] + '.' + self.autoCompList[event.GetIndex()] 
+            item = self.toComplete['cmd'].rpartition(
+                '.')[0] + '.' + self.autoCompList[event.GetIndex()]
             try:
                 nodes = self._menuModel.SearchNodes(key='command', value=item)
                 desc = ''
@@ -206,11 +213,13 @@
                     self.commandSelected.emit(command=item)
                     desc = nodes[0].data['description']
             except KeyError:
-                desc = '' 
+                desc = ''
             self.ShowStatusText(desc)
-        # list of flags    
+        # list of flags
         elif self.toComplete['entity'] == 'flags':
-            desc = self.cmdDesc.get_flag(self.autoCompList[event.GetIndex()])['description']
+            desc = self.cmdDesc.get_flag(
+                self.autoCompList[
+                    event.GetIndex()])['description']
             self.ShowStatusText(desc)
         # list of parameters
         elif self.toComplete['entity'] == 'params':
@@ -220,12 +229,15 @@
                 desc = '[' + desc + ']'
             desc += ': ' + item['description']
             self.ShowStatusText(desc)
-        # list of flags and commands       
+        # list of flags and commands
         elif self.toComplete['entity'] == 'params+flags':
             if self.autoCompList[event.GetIndex()][0] == '-':
-                desc = self.cmdDesc.get_flag(self.autoCompList[event.GetIndex()].strip('-'))['description']
+                desc = self.cmdDesc.get_flag(
+                    self.autoCompList[
+                        event.GetIndex()].strip('-'))['description']
             else:
-                item = self.cmdDesc.get_param(self.autoCompList[event.GetIndex()])
+                item = self.cmdDesc.get_param(
+                    self.autoCompList[event.GetIndex()])
                 desc = item['name'] + '=' + item['type']
                 if not item['required']:
                     desc = '[' + desc + ']'
@@ -233,31 +245,33 @@
             self.ShowStatusText(desc)
         else:
             self.ShowStatusText('')
-            
+
     def OnItemSelected(self, event):
         """Item selected from the list"""
         lastWord = self.GetWordLeft()
-        # to insert selection correctly if selected word partly matches written text
+        # to insert selection correctly if selected word partly matches written
+        # text
         match = difflib.SequenceMatcher(None, event.GetText(), lastWord)
-        matchTuple = match.find_longest_match(0, len(event.GetText()), 0, len(lastWord))
-    
+        matchTuple = match.find_longest_match(
+            0, len(event.GetText()), 0, len(lastWord))
+
         compl = event.GetText()[matchTuple[2]:]
         text = self.GetTextLeft() + compl
         # add space or '=' at the end
         end = '='
-        for char in ('.','-','='):
+        for char in ('.', '-', '='):
             if text.split(' ')[-1].find(char) >= 0:
                 end = ' '
-        
+
         compl += end
         text += end
 
         self.AddText(compl)
         pos = len(text)
         self.SetCurrentPos(pos)
-        
+
         cmd = text.strip().split(' ')[0]
-        
+
         if not self.cmdDesc or cmd != self.cmdDesc.get_name():
             try:
                 self.cmdDesc = gtask.parse_interface(cmd)
@@ -281,17 +295,17 @@
 
     def UpdateCmdHistory(self, cmd):
         """Update command history
-        
+
         :param cmd: command given as a string
         """
-        # add command to history    
+        # add command to history
         self.cmdbuffer.append(cmd)
-        
+
         # keep command history to a managable size
         if len(self.cmdbuffer) > 200:
             del self.cmdbuffer[0]
         self.cmdindex = len(self.cmdbuffer)
-        
+
     def EntityToComplete(self):
         """Determines which part of command (flags, parameters) should
         be completed at current cursor position"""
@@ -301,10 +315,10 @@
             cmd = entry.split()[0].strip()
         except IndexError:
             return toComplete
-        
+
         try:
             splitted = utils.split(str(entry))
-        except ValueError: # No closing quotation error
+        except ValueError:  # No closing quotation error
             return toComplete
         if len(splitted) > 0 and cmd in globalvar.grassCmd:
             toComplete['cmd'] = cmd
@@ -316,13 +330,14 @@
                     toComplete['entity'] = 'params+flags'
             else:
                 # get word left from current position
-                word = self.GetWordLeft(withDelimiter = True)
-                
+                word = self.GetWordLeft(withDelimiter=True)
+
                 if word[0] == '=' and word[-1] == '@':
                     toComplete['entity'] = 'mapsets'
                 elif word[0] == '=':
                     # get name of parameter
-                    paramName = self.GetWordLeft(withDelimiter = False, ignoredDelimiter = '=').strip('=')
+                    paramName = self.GetWordLeft(
+                        withDelimiter=False, ignoredDelimiter='=').strip('=')
                     if paramName:
                         try:
                             param = self.cmdDesc.get_param(paramName)
@@ -330,7 +345,7 @@
                             return toComplete
                     else:
                         return toComplete
-                    
+
                     if param['values']:
                         toComplete['entity'] = 'param values'
                     elif param['prompt'] == 'raster' and param['element'] == 'cell':
@@ -344,22 +359,22 @@
         else:
             toComplete['entity'] = 'command'
             toComplete['cmd'] = cmd
-        
+
         return toComplete
-    
-    def GetWordLeft(self, withDelimiter = False, ignoredDelimiter = None):
+
+    def GetWordLeft(self, withDelimiter=False, ignoredDelimiter=None):
         """Get word left from current cursor position. The beginning
-        of the word is given by space or chars: .,-= 
-        
+        of the word is given by space or chars: .,-=
+
         :param withDelimiter: returns the word with the initial delimeter
         :param ignoredDelimiter: finds the word ignoring certain delimeter
         """
         textLeft = self.GetTextLeft()
-        
+
         parts = list()
         if ignoredDelimiter is None:
             ignoredDelimiter = ''
-        
+
         for char in set(' .,-=') - set(ignoredDelimiter):
             if not withDelimiter:
                 delimiter = ''
@@ -367,12 +382,14 @@
                 delimiter = char
             parts.append(delimiter + textLeft.rpartition(char)[2])
         return min(parts, key=lambda x: len(x))
-         
+
     def ShowList(self):
         """Show sorted auto-completion list if it is not empty"""
         if len(self.autoCompList) > 0:
             self.autoCompList.sort()
-            self.AutoCompShow(lenEntered = 0, itemList = ' '.join(self.autoCompList))    
+            self.AutoCompShow(
+                lenEntered=0, itemList=' '.join(
+                    self.autoCompList))
 
     def OnKeyPressed(self, event):
         """Key pressed capture special treatment for tabulator to show help"""
@@ -438,7 +455,7 @@
         .. todo::
             event.ControlDown() for manual autocomplete
         """
-        # keycodes used: "." = 46, "=" = 61, "-" = 45 
+        # keycodes used: "." = 46, "=" = 61, "-" = 45
         pos = self.GetCurrentPos()
         # complete command after pressing '.'
         if event.GetKeyCode() == 46:
@@ -448,15 +465,18 @@
             self.CharRight()
             self.toComplete = self.EntityToComplete()
             try:
-                if self.toComplete['entity'] == 'command': 
+                if self.toComplete['entity'] == 'command':
                     for command in globalvar.grassCmd:
                         try:
                             if command.find(self.toComplete['cmd']) == 0:
-                                dotNumber = list(self.toComplete['cmd']).count('.') 
-                                self.autoCompList.append(command.split('.',dotNumber)[-1])
-                        except UnicodeDecodeError as e: # TODO: fix it
-                            sys.stderr.write(DecodeString(command) + ": " + unicode(e))
-                            
+                                dotNumber = list(
+                                    self.toComplete['cmd']).count('.')
+                                self.autoCompList.append(
+                                    command.split('.', dotNumber)[-1])
+                        except UnicodeDecodeError as e:  # TODO: fix it
+                            sys.stderr.write(
+                                DecodeString(command) + ": " + unicode(e))
+
             except (KeyError, TypeError):
                 return
             self.ShowList()
@@ -471,16 +491,16 @@
             self.CharRight()
             self.toComplete = self.EntityToComplete()
             if self.toComplete['entity'] == 'flags' and self.cmdDesc:
-                if self.GetTextLeft()[-2:] == ' -': # complete e.g. --quite
+                if self.GetTextLeft()[-2:] == ' -':  # complete e.g. --quite
                     for flag in self.cmdDesc.get_options()['flags']:
                         if len(flag['name']) == 1:
                             self.autoCompList.append(flag['name'])
                 else:
                     for flag in self.cmdDesc.get_options()['flags']:
                         if len(flag['name']) > 1:
-                            self.autoCompList.append(flag['name'])            
+                            self.autoCompList.append(flag['name'])
             self.ShowList()
-            
+
         # complete map or values after parameter
         elif event.GetKeyCode() == 61:
             self.autoCompList = list()
@@ -492,56 +512,59 @@
             elif self.toComplete['entity'] == 'vector map':
                 self.autoCompList = self.mapList['vector']
             elif self.toComplete['entity'] == 'param values':
-                param = self.GetWordLeft(withDelimiter = False, ignoredDelimiter='=').strip(' =')
+                param = self.GetWordLeft(
+                    withDelimiter=False,
+                    ignoredDelimiter='=').strip(' =')
                 self.autoCompList = self.cmdDesc.get_param(param)['values']
             self.ShowList()
-        
+
         # complete mapset ('@')
         elif event.GetKeyCode() == 64:
             self.autoCompList = list()
             self.InsertText(pos, '@')
             self.CharRight()
             self.toComplete = self.EntityToComplete()
-            
+
             if self.toComplete['entity'] == 'mapsets':
                 self.autoCompList = self.mapsetList
             self.ShowList()
-            
-        # complete after pressing CTRL + Space          
+
+        # complete after pressing CTRL + Space
         elif event.GetKeyCode() == wx.WXK_SPACE and event.ControlDown():
             self.autoCompList = list()
             self.toComplete = self.EntityToComplete()
 
-            #complete command
+            # complete command
             if self.toComplete['entity'] == 'command':
                 for command in globalvar.grassCmd:
                     if command.find(self.toComplete['cmd']) == 0:
-                        dotNumber = list(self.toComplete['cmd']).count('.') 
-                        self.autoCompList.append(command.split('.',dotNumber)[-1])
-                
-            
+                        dotNumber = list(self.toComplete['cmd']).count('.')
+                        self.autoCompList.append(
+                            command.split('.', dotNumber)[-1])
+
             # complete flags in such situations (| is cursor):
             # r.colors -| ...w, q, l
-            # r.colors -w| ...w, q, l  
+            # r.colors -w| ...w, q, l
             elif self.toComplete['entity'] == 'flags' and self.cmdDesc:
                 for flag in self.cmdDesc.get_options()['flags']:
                     if len(flag['name']) == 1:
                         self.autoCompList.append(flag['name'])
-                    
+
             # complete parameters in such situations (| is cursor):
             # r.colors -w | ...color, map, rast, rules
             # r.colors col| ...color
             elif self.toComplete['entity'] == 'params' and self.cmdDesc:
                 for param in self.cmdDesc.get_options()['params']:
-                    if param['name'].find(self.GetWordLeft(withDelimiter=False)) == 0:
-                        self.autoCompList.append(param['name'])           
-            
+                    if param['name'].find(
+                            self.GetWordLeft(withDelimiter=False)) == 0:
+                        self.autoCompList.append(param['name'])
+
             # complete flags or parameters in such situations (| is cursor):
             # r.colors | ...-w, -q, -l, color, map, rast, rules
             # r.colors color=grey | ...-w, -q, -l, color, map, rast, rules
             elif self.toComplete['entity'] == 'params+flags' and self.cmdDesc:
                 self.autoCompList = list()
-                
+
                 for param in self.cmdDesc.get_options()['params']:
                     self.autoCompList.append(param['name'])
                 for flag in self.cmdDesc.get_options()['flags']:
@@ -549,12 +572,12 @@
                         self.autoCompList.append('-' + flag['name'])
                     else:
                         self.autoCompList.append('--' + flag['name'])
-                    
-                self.ShowList() 
-                   
-            # complete map or values after parameter  
+
+                self.ShowList()
+
+            # complete map or values after parameter
             # r.buffer input=| ...list of raster maps
-            # r.buffer units=| ... feet, kilometers, ...   
+            # r.buffer units=| ... feet, kilometers, ...
             elif self.toComplete['entity'] == 'raster map':
                 self.autoCompList = list()
                 self.autoCompList = self.mapList['raster']
@@ -563,9 +586,11 @@
                 self.autoCompList = self.mapList['vector']
             elif self.toComplete['entity'] == 'param values':
                 self.autoCompList = list()
-                param = self.GetWordLeft(withDelimiter = False, ignoredDelimiter='=').strip(' =')
+                param = self.GetWordLeft(
+                    withDelimiter=False,
+                    ignoredDelimiter='=').strip(' =')
                 self.autoCompList = self.cmdDesc.get_param(param)['values']
-                
+
             self.ShowList()
 
         elif event.GetKeyCode() == wx.WXK_SPACE:
@@ -579,23 +604,23 @@
                     except IOError:
                         self.cmdDesc = None
             event.Skip()
-        
+
         else:
             event.Skip()
 
     def ShowStatusText(self, text):
         """Requests showing of notification, e.g. showing in a statusbar."""
         self.showNotification.emit(message=text)
-        
+
     def GetTextLeft(self):
         """Returns all text left of the caret"""
         pos = self.GetCurrentPos()
         self.HomeExtend()
         entry = self.GetSelectedText()
         self.SetCurrentPos(pos)
-        
+
         return entry
-    
+
     def OnDestroy(self, event):
         """The clipboard contents can be preserved after
         the app has exited"""

Modified: grass/trunk/gui/wxpython/gui_core/pyedit.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/pyedit.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gui_core/pyedit.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -88,11 +88,11 @@
 #
 #%s
 """ % ('#' * 72,
-       EncodeString(properties['name']),
-       EncodeString(properties['author']),
-       EncodeString('\n# '.join(properties['description'].splitlines())),
-       time.asctime(),
-       '#' * 72))
+            EncodeString(properties['name']),
+            EncodeString(properties['author']),
+            EncodeString('\n# '.join(properties['description'].splitlines())),
+            time.asctime(),
+            '#' * 72))
 
     # UI
     output.write(
@@ -323,7 +323,8 @@
         else:
             self.SaveAs()
 
-    # TODO: it should be probably used with replacing, when this gives what we want?
+    # TODO: it should be probably used with replacing, when this gives what we
+    # want?
     def IsModified(self):
         """Check if python script has been modified"""
         return self.body.modified
@@ -432,6 +433,7 @@
     # pylint: disable=too-many-ancestors
     # pylint: disable=too-many-public-methods
     """PyEdit toolbar"""
+
     def __init__(self, parent):
         BaseToolbar.__init__(self, parent)
 
@@ -465,7 +467,7 @@
                                      (None, ),
                                      ("help", BaseIcons['help'],
                                       self.parent.OnHelp),
-                                    ))
+                                     ))
 
 
 class PyEditFrame(wx.Frame):
@@ -473,6 +475,7 @@
     # pylint: disable=missing-docstring
     # pylint: disable=too-many-public-methods
     # pylint: disable=invalid-name
+
     def __init__(self, parent, giface, id=wx.ID_ANY,
                  title=_("GRASS GIS Simple Python Editor"),
                  **kwargs):

Modified: grass/trunk/gui/wxpython/gui_core/pystc.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/pystc.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gui_core/pystc.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -27,60 +27,93 @@
     usage)
 
     Based on StyledTextCtrl_2 from wxPython demo
-    """  
-    def __init__(self, parent, id = wx.ID_ANY, statusbar = None):
+    """
+
+    def __init__(self, parent, id=wx.ID_ANY, statusbar=None):
         stc.StyledTextCtrl.__init__(self, parent, id)
-        
+
         self.parent = parent
         self.statusbar = statusbar
-        
-        self.modified = False # content modified ?
 
+        self.modified = False  # content modified ?
+
         # this is supposed to get monospace
-        font = wx.Font(9, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)
+        font = wx.Font(
+            9,
+            wx.FONTFAMILY_MODERN,
+            wx.FONTSTYLE_NORMAL,
+            wx.FONTWEIGHT_NORMAL)
         face = font.GetFaceName()
         size = font.GetPointSize()
 
         # setting the monospace here to not mess with the rest of the code
         # TODO: review the whole styling
-        self.faces = { 'times': face,
-                       'mono' : face,
-                       'helv' : face,
-                       'other': face,
-                       'size' : 10,
-                       'size2': 8,
-                       }
-        
+        self.faces = {'times': face,
+                      'mono': face,
+                      'helv': face,
+                      'other': face,
+                      'size': 10,
+                      'size2': 8,
+                      }
+
         self.CmdKeyAssign(ord('B'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMIN)
         self.CmdKeyAssign(ord('N'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMOUT)
-        
+
         self.SetLexer(stc.STC_LEX_PYTHON)
         self.SetKeyWords(0, " ".join(keyword.kwlist))
-        
+
         self.SetProperty("fold", "1")
         self.SetProperty("tab.timmy.whinge.level", "1")
         self.SetMargins(0, 0)
         self.SetTabWidth(4)
         self.SetUseTabs(False)
-        
+
         self.SetEdgeMode(stc.STC_EDGE_BACKGROUND)
         self.SetEdgeColumn(78)
-        
+
         # setup a margin to hold fold markers
         self.SetMarginType(2, stc.STC_MARGIN_SYMBOL)
         self.SetMarginMask(2, stc.STC_MASK_FOLDERS)
         self.SetMarginSensitive(2, True)
         self.SetMarginWidth(2, 12)
-        
+
         # like a flattened tree control using square headers
-        self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN,    stc.STC_MARK_BOXMINUS,          "white", "#808080")
-        self.MarkerDefine(stc.STC_MARKNUM_FOLDER,        stc.STC_MARK_BOXPLUS,           "white", "#808080")
-        self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB,     stc.STC_MARK_VLINE,             "white", "#808080")
-        self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL,    stc.STC_MARK_LCORNER,           "white", "#808080")
-        self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND,     stc.STC_MARK_BOXPLUSCONNECTED,  "white", "#808080")
-        self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_BOXMINUSCONNECTED, "white", "#808080")
-        self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_TCORNER,           "white", "#808080")
-        
+        self.MarkerDefine(
+            stc.STC_MARKNUM_FOLDEROPEN,
+            stc.STC_MARK_BOXMINUS,
+            "white",
+            "#808080")
+        self.MarkerDefine(
+            stc.STC_MARKNUM_FOLDER,
+            stc.STC_MARK_BOXPLUS,
+            "white",
+            "#808080")
+        self.MarkerDefine(
+            stc.STC_MARKNUM_FOLDERSUB,
+            stc.STC_MARK_VLINE,
+            "white",
+            "#808080")
+        self.MarkerDefine(
+            stc.STC_MARKNUM_FOLDERTAIL,
+            stc.STC_MARK_LCORNER,
+            "white",
+            "#808080")
+        self.MarkerDefine(
+            stc.STC_MARKNUM_FOLDEREND,
+            stc.STC_MARK_BOXPLUSCONNECTED,
+            "white",
+            "#808080")
+        self.MarkerDefine(
+            stc.STC_MARKNUM_FOLDEROPENMID,
+            stc.STC_MARK_BOXMINUSCONNECTED,
+            "white",
+            "#808080")
+        self.MarkerDefine(
+            stc.STC_MARKNUM_FOLDERMIDTAIL,
+            stc.STC_MARK_TCORNER,
+            "white",
+            "#808080")
+
         self.Bind(stc.EVT_STC_UPDATEUI, self.OnUpdateUI)
         self.Bind(stc.EVT_STC_MARGINCLICK, self.OnMarginClick)
         self.Bind(wx.EVT_KEY_DOWN, self.OnKeyPressed)
@@ -93,94 +126,155 @@
         # Make some styles, the lexer defines what each style is used
         # for, we just have to define what each style looks like.
         # This set is adapted from Scintilla sample property files.
-        
+
         # global default styles for all languages
-        self.StyleSetSpec(stc.STC_STYLE_DEFAULT,     "face:%(helv)s,size:%(size)d" % self.faces)
+        self.StyleSetSpec(
+            stc.STC_STYLE_DEFAULT,
+            "face:%(helv)s,size:%(size)d" %
+            self.faces)
         self.StyleClearAll()  # reset all to be like the default
-        
+
         # global default styles for all languages
-        self.StyleSetSpec(stc.STC_STYLE_DEFAULT,     "face:%(helv)s,size:%(size)d" % self.faces)
-        self.StyleSetSpec(stc.STC_STYLE_LINENUMBER,  "back:#C0C0C0,face:%(helv)s,size:%(size2)d" % self.faces)
-        self.StyleSetSpec(stc.STC_STYLE_CONTROLCHAR, "face:%(other)s" % self.faces)
-        self.StyleSetSpec(stc.STC_STYLE_BRACELIGHT,  "fore:#FFFFFF,back:#0000FF,bold")
-        self.StyleSetSpec(stc.STC_STYLE_BRACEBAD,    "fore:#000000,back:#FF0000,bold")
-        
+        self.StyleSetSpec(
+            stc.STC_STYLE_DEFAULT,
+            "face:%(helv)s,size:%(size)d" %
+            self.faces)
+        self.StyleSetSpec(
+            stc.STC_STYLE_LINENUMBER,
+            "back:#C0C0C0,face:%(helv)s,size:%(size2)d" %
+            self.faces)
+        self.StyleSetSpec(
+            stc.STC_STYLE_CONTROLCHAR,
+            "face:%(other)s" %
+            self.faces)
+        self.StyleSetSpec(
+            stc.STC_STYLE_BRACELIGHT,
+            "fore:#FFFFFF,back:#0000FF,bold")
+        self.StyleSetSpec(
+            stc.STC_STYLE_BRACEBAD,
+            "fore:#000000,back:#FF0000,bold")
+
         # Python styles
-        # Default 
-        self.StyleSetSpec(stc.STC_P_DEFAULT, "fore:#000000,face:%(helv)s,size:%(size)d" % self.faces)
+        # Default
+        self.StyleSetSpec(
+            stc.STC_P_DEFAULT,
+            "fore:#000000,face:%(helv)s,size:%(size)d" %
+            self.faces)
         # Comments
-        self.StyleSetSpec(stc.STC_P_COMMENTLINE, "fore:#007F00,face:%(other)s,size:%(size)d" % self.faces)
+        self.StyleSetSpec(
+            stc.STC_P_COMMENTLINE,
+            "fore:#007F00,face:%(other)s,size:%(size)d" %
+            self.faces)
         # Number
-        self.StyleSetSpec(stc.STC_P_NUMBER, "fore:#007F7F,size:%(size)d" % self.faces)
+        self.StyleSetSpec(
+            stc.STC_P_NUMBER,
+            "fore:#007F7F,size:%(size)d" %
+            self.faces)
         # String
-        self.StyleSetSpec(stc.STC_P_STRING, "fore:#7F007F,face:%(helv)s,size:%(size)d" % self.faces)
+        self.StyleSetSpec(
+            stc.STC_P_STRING,
+            "fore:#7F007F,face:%(helv)s,size:%(size)d" %
+            self.faces)
         # Single quoted string
-        self.StyleSetSpec(stc.STC_P_CHARACTER, "fore:#7F007F,face:%(helv)s,size:%(size)d" % self.faces)
+        self.StyleSetSpec(
+            stc.STC_P_CHARACTER,
+            "fore:#7F007F,face:%(helv)s,size:%(size)d" %
+            self.faces)
         # Keyword
-        self.StyleSetSpec(stc.STC_P_WORD, "fore:#00007F,bold,size:%(size)d" % self.faces)
+        self.StyleSetSpec(
+            stc.STC_P_WORD,
+            "fore:#00007F,bold,size:%(size)d" %
+            self.faces)
         # Triple quotes
-        self.StyleSetSpec(stc.STC_P_TRIPLE, "fore:#7F0000,size:%(size)d" % self.faces)
+        self.StyleSetSpec(
+            stc.STC_P_TRIPLE,
+            "fore:#7F0000,size:%(size)d" %
+            self.faces)
         # Triple double quotes
-        self.StyleSetSpec(stc.STC_P_TRIPLEDOUBLE, "fore:#7F0000,size:%(size)d" % self.faces)
+        self.StyleSetSpec(
+            stc.STC_P_TRIPLEDOUBLE,
+            "fore:#7F0000,size:%(size)d" %
+            self.faces)
         # Class name definition
-        self.StyleSetSpec(stc.STC_P_CLASSNAME, "fore:#0000FF,bold,underline,size:%(size)d" % self.faces)
+        self.StyleSetSpec(
+            stc.STC_P_CLASSNAME,
+            "fore:#0000FF,bold,underline,size:%(size)d" %
+            self.faces)
         # Function or method name definition
-        self.StyleSetSpec(stc.STC_P_DEFNAME, "fore:#007F7F,bold,size:%(size)d" % self.faces)
+        self.StyleSetSpec(
+            stc.STC_P_DEFNAME,
+            "fore:#007F7F,bold,size:%(size)d" %
+            self.faces)
         # Operators
-        self.StyleSetSpec(stc.STC_P_OPERATOR, "bold,size:%(size)d" % self.faces)
+        self.StyleSetSpec(
+            stc.STC_P_OPERATOR,
+            "bold,size:%(size)d" %
+            self.faces)
         # Identifiers
-        self.StyleSetSpec(stc.STC_P_IDENTIFIER, "fore:#000000,face:%(helv)s,size:%(size)d" % self.faces)
+        self.StyleSetSpec(
+            stc.STC_P_IDENTIFIER,
+            "fore:#000000,face:%(helv)s,size:%(size)d" %
+            self.faces)
         # Comment-blocks
-        self.StyleSetSpec(stc.STC_P_COMMENTBLOCK, "fore:#7F7F7F,size:%(size)d" % self.faces)
+        self.StyleSetSpec(
+            stc.STC_P_COMMENTBLOCK,
+            "fore:#7F7F7F,size:%(size)d" %
+            self.faces)
         # End of line where string is not closed
-        self.StyleSetSpec(stc.STC_P_STRINGEOL, "fore:#000000,face:%(mono)s,back:#E0C0E0,eol,size:%(size)d" % self.faces)
-        
+        self.StyleSetSpec(
+            stc.STC_P_STRINGEOL,
+            "fore:#000000,face:%(mono)s,back:#E0C0E0,eol,size:%(size)d" %
+            self.faces)
+
         self.SetCaretForeground("BLUE")
-        
+
     def OnKeyPressed(self, event):
         """Key pressed
-        
+
         .. todo::
             implement code completion (see wxPython demo)
         """
         if not self.modified:
             self.modified = True
             if self.statusbar:
-                self.statusbar.SetStatusText(_('Python script contains local modifications'), 0)
-        
+                self.statusbar.SetStatusText(
+                    _('Python script contains local modifications'), 0)
+
         event.Skip()
-        
+
     def OnUpdateUI(self, evt):
         # check for matching braces
         braceAtCaret = -1
         braceOpposite = -1
         charBefore = None
         caretPos = self.GetCurrentPos()
-        
+
         if caretPos > 0:
-            charBefore  = self.GetCharAt(caretPos - 1)
+            charBefore = self.GetCharAt(caretPos - 1)
             styleBefore = self.GetStyleAt(caretPos - 1)
-        
+
         # check before
-        if charBefore and chr(charBefore) in "[]{}()" and styleBefore == stc.STC_P_OPERATOR:
+        if charBefore and chr(
+                charBefore) in "[]{}()" and styleBefore == stc.STC_P_OPERATOR:
             braceAtCaret = caretPos - 1
-        
+
         # check after
         if braceAtCaret < 0:
             charAfter = self.GetCharAt(caretPos)
             styleAfter = self.GetStyleAt(caretPos)
-            
-            if charAfter and chr(charAfter) in "[]{}()" and styleAfter == stc.STC_P_OPERATOR:
+
+            if charAfter and chr(
+                    charAfter) in "[]{}()" and styleAfter == stc.STC_P_OPERATOR:
                 braceAtCaret = caretPos
-        
+
         if braceAtCaret >= 0:
             braceOpposite = self.BraceMatch(braceAtCaret)
-        
-        if braceAtCaret != -1  and braceOpposite == -1:
+
+        if braceAtCaret != -1 and braceOpposite == -1:
             self.BraceBadLight(braceAtCaret)
         else:
             self.BraceHighlight(braceAtCaret, braceOpposite)
-        
+
     def OnMarginClick(self, evt):
         # fold and unfold as needed
         if evt.GetMargin() == 2:
@@ -188,8 +282,9 @@
                 self.FoldAll()
             else:
                 lineClicked = self.LineFromPosition(evt.GetPosition())
-                
-                if self.GetFoldLevel(lineClicked) & stc.STC_FOLDLEVELHEADERFLAG:
+
+                if self.GetFoldLevel(
+                        lineClicked) & stc.STC_FOLDLEVELHEADERFLAG:
                     if evt.GetShift():
                         self.SetFoldExpanded(lineClicked, True)
                         self.Expand(lineClicked, True, True, 1)
@@ -202,23 +297,23 @@
                             self.Expand(lineClicked, True, True, 100)
                     else:
                         self.ToggleFold(lineClicked)
-        
+
     def FoldAll(self):
         lineCount = self.GetLineCount()
         expanding = True
-        
+
         # find out if we are folding or unfolding
         for lineNum in range(lineCount):
             if self.GetFoldLevel(lineNum) & stc.STC_FOLDLEVELHEADERFLAG:
                 expanding = not self.GetFoldExpanded(lineNum)
                 break
-        
+
         lineNum = 0
         while lineNum < lineCount:
             level = self.GetFoldLevel(lineNum)
             if level & stc.STC_FOLDLEVELHEADERFLAG and \
                (level & stc.STC_FOLDLEVELNUMBERMASK) == stc.STC_FOLDLEVELBASE:
-                
+
                 if expanding:
                     self.SetFoldExpanded(lineNum, True)
                     lineNum = self.Expand(lineNum, True)
@@ -226,16 +321,16 @@
                 else:
                     lastChild = self.GetLastChild(lineNum, -1)
                     self.SetFoldExpanded(lineNum, False)
-                    
+
                     if lastChild > lineNum:
-                        self.HideLines(lineNum+1, lastChild)
-            
+                        self.HideLines(lineNum + 1, lastChild)
+
             lineNum = lineNum + 1
-        
+
     def Expand(self, line, doExpand, force=False, visLevels=0, level=-1):
         lastChild = self.GetLastChild(line, level)
         line = line + 1
-        
+
         while line <= lastChild:
             if force:
                 if visLevels > 0:
@@ -245,24 +340,24 @@
             else:
                 if doExpand:
                     self.ShowLines(line, line)
-            
+
             if level == -1:
                 level = self.GetFoldLevel(line)
-            
+
             if level & stc.STC_FOLDLEVELHEADERFLAG:
                 if force:
                     if visLevels > 1:
                         self.SetFoldExpanded(line, True)
                     else:
                         self.SetFoldExpanded(line, False)
-                    
-                    line = self.Expand(line, doExpand, force, visLevels-1)
+
+                    line = self.Expand(line, doExpand, force, visLevels - 1)
                 else:
                     if doExpand and self.GetFoldExpanded(line):
-                        line = self.Expand(line, True, force, visLevels-1)
+                        line = self.Expand(line, True, force, visLevels - 1)
                     else:
-                        line = self.Expand(line, False, force, visLevels-1)
+                        line = self.Expand(line, False, force, visLevels - 1)
             else:
                 line = line + 1
-        
+
         return line

Modified: grass/trunk/gui/wxpython/gui_core/query.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/query.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gui_core/query.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -23,55 +23,76 @@
 
 from grass.pydispatch.signal import Signal
 
+
 class QueryDialog(wx.Dialog):
-    def __init__(self, parent, data = None):
-        wx.Dialog.__init__(self, parent, id = wx.ID_ANY,
-                           title = _("Query results"),
-                           size = (420, 400),
-                           style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
+
+    def __init__(self, parent, data=None):
+        wx.Dialog.__init__(self, parent, id=wx.ID_ANY,
+                           title=_("Query results"),
+                           size=(420, 400),
+                           style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
         # send query output to console
         self.redirectOutput = Signal('QueryDialog.redirectOutput')
 
         self.data = data
 
-        self.panel = wx.Panel(self, id = wx.ID_ANY)
+        self.panel = wx.Panel(self, id=wx.ID_ANY)
         self.mainSizer = wx.BoxSizer(wx.VERTICAL)
 
-        helpText = wx.StaticText(self.panel, wx.ID_ANY,
-                                 label=_("Right click to copy selected values to clipboard."))
-        helpText.SetForegroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_GRAYTEXT))
+        helpText = wx.StaticText(self.panel, wx.ID_ANY, label=_(
+            "Right click to copy selected values to clipboard."))
+        helpText.SetForegroundColour(
+            wx.SystemSettings_GetColour(
+                wx.SYS_COLOUR_GRAYTEXT))
         self.mainSizer.Add(item=helpText, proportion=0, flag=wx.ALL, border=5)
 
         self._colNames = [_("Feature"), _("Value")]
         self._model = QueryTreeBuilder(self.data, column=self._colNames[1])
         self.tree = TreeListView(model=self._model, parent=self.panel,
                                  columns=self._colNames,
-                                 style=wx.TR_DEFAULT_STYLE | 
+                                 style=wx.TR_DEFAULT_STYLE |
                                  wx.TR_FULL_ROW_HIGHLIGHT | wx.TR_MULTIPLE)
 
         self.tree.SetColumnWidth(0, 220)
         self.tree.SetColumnWidth(1, 1000)
         self.tree.ExpandAll(self._model.root)
         self.tree.contextMenu.connect(self.ShowContextMenu)
-        self.mainSizer.Add(item = self.tree, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
+        self.mainSizer.Add(
+            item=self.tree,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
 
-        
-        close = wx.Button(self.panel, id = wx.ID_CLOSE)
+        close = wx.Button(self.panel, id=wx.ID_CLOSE)
         close.Bind(wx.EVT_BUTTON, lambda event: self.Close())
-        copy = wx.Button(self.panel, id = wx.ID_ANY, label = _("Copy all to clipboard"))
+        copy = wx.Button(
+            self.panel,
+            id=wx.ID_ANY,
+            label=_("Copy all to clipboard"))
         copy.Bind(wx.EVT_BUTTON, self.Copy)
         self.Bind(wx.EVT_CLOSE, self.OnClose)
         self.redirect = wx.CheckBox(self.panel, label=_("Redirect to console"))
         self.redirect.SetValue(False)
-        self.redirect.Bind(wx.EVT_CHECKBOX, lambda evt: self._onRedirect(evt.IsChecked()))
+        self.redirect.Bind(
+            wx.EVT_CHECKBOX,
+            lambda evt: self._onRedirect(
+                evt.IsChecked()))
 
         hbox = wx.BoxSizer(wx.HORIZONTAL)
-        hbox.Add(item=self.redirect, proportion=0, flag=wx.EXPAND | wx.RIGHT, border=5)
+        hbox.Add(
+            item=self.redirect,
+            proportion=0,
+            flag=wx.EXPAND | wx.RIGHT,
+            border=5)
         hbox.AddStretchSpacer(1)
         hbox.Add(item=copy, proportion=0, flag=wx.EXPAND | wx.RIGHT, border=5)
         hbox.Add(item=close, proportion=0, flag=wx.EXPAND | wx.ALL, border=0)
 
-        self.mainSizer.Add(item=hbox, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
+        self.mainSizer.Add(
+            item=hbox,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
         self.panel.SetSizer(self.mainSizer)
         self.mainSizer.Fit(self.panel)
         # for Windows
@@ -93,41 +114,55 @@
 
     def ShowContextMenu(self, node):
         """Show context menu.
-        
+
         Menu for copying distinguishes single and multiple selection.
         """
         nodes = self.tree.GetSelected()
         if not nodes:
             return
-            
+
         menu = wx.Menu()
         texts = []
         if len(nodes) > 1:
             values = []
             for node in nodes:
-                values.append((node.label, node.data[self._colNames[1]] if node.data else ''))
+                values.append(
+                    (node.label, node.data[
+                        self._colNames[1]] if node.data else ''))
             col1 = '\n'.join([val[1] for val in values if val[1]])
             col2 = '\n'.join([val[0] for val in values if val[0]])
             table = '\n'.join([val[0] + ': ' + val[1] for val in values])
-            texts.append((_("Copy from '%s' column") % self._colNames[1], col1))
-            texts.append((_("Copy from '%s' column") % self._colNames[0], col2))
+            texts.append(
+                (_("Copy from '%s' column") %
+                 self._colNames[1], col1))
+            texts.append(
+                (_("Copy from '%s' column") %
+                 self._colNames[0], col2))
             texts.append((_("Copy selected lines"), table))
         else:
             label1 = nodes[0].label
             texts.append((_("Copy '%s'" % self._cutLabel(label1)), label1))
             if nodes[0].data and nodes[0].data[self._colNames[1]]:
                 label2 = nodes[0].data[self._colNames[1]]
-                texts.insert(0, (_("Copy '%s'" % self._cutLabel(label2)), label2))
+                texts.insert(
+                    0, (_(
+                        "Copy '%s'" %
+                        self._cutLabel(label2)), label2))
                 texts.append((_("Copy line"), label1 + ': ' + label2))
 
         ids = []
         for text in texts:
             id = wx.NewId()
             ids.append(id)
-            self.Bind(wx.EVT_MENU, lambda evt, t=text[1], id=id: self._copyText(t), id=id)
- 
+            self.Bind(
+                wx.EVT_MENU,
+                lambda evt,
+                t=text[1],
+                id=id: self._copyText(t),
+                id=id)
+
             menu.Append(id, text[0])
- 
+
         # show the popup menu
         self.PopupMenu(menu)
         menu.Destroy()
@@ -136,8 +171,8 @@
 
     def _onRedirect(self, redirect):
         """Emits instructions to redirect query results.
-        
-        :param redirect: True to start redirecting, False to stop        
+
+        :param redirect: True to start redirecting, False to stop
         """
         if redirect:
             self.redirectOutput.emit(output=_("Query results:"), style='cmd')
@@ -147,14 +182,14 @@
 
     def _textToRedirect(self):
         text = printResults(self._model, self._colNames[1])
-        text += '\n' + "-"* 50 + '\n'
+        text += '\n' + "-" * 50 + '\n'
         return text
 
     def _cutLabel(self, label):
         limit = 15
         if len(label) > limit:
             return label[:limit] + '...'
-            
+
         return label
 
     def _copyText(self, text):
@@ -205,17 +240,22 @@
 
 def printResults(model, valueCol):
     """Print all results to string.
-    
+
     :param model: results tree model
     :param valueCol: column name with value to be printed
     """
     def printTree(node, textList, valueCol, indent=0):
         if node.data.get(valueCol, '') or node.children:
-            textList.append(indent*' ' + node.label + ': ' + node.data.get(valueCol, ''))
+            textList.append(
+                indent * ' ' + node.label + ': ' + node.data.get(valueCol, ''))
         for child in node.children:
-            printTree(node=child, textList=textList, valueCol=valueCol, indent=indent + 2)
-    
-    textList=[]
+            printTree(
+                node=child,
+                textList=textList,
+                valueCol=valueCol,
+                indent=indent + 2)
+
+    textList = []
     for child in model.root.children:
         printTree(node=child, textList=textList, valueCol=valueCol)
     return '\n'.join(textList)
@@ -248,16 +288,23 @@
     app = wx.App()
     from grass.script import vector as gvect
     from grass.script import raster as grast
-    testdata1 = grast.raster_what(map = ('elevation_shade at PERMANENT','landclass96'),
-                                  coord = [(638509.051416,224742.348346)],
-                                  localized=True)
+    testdata1 = grast.raster_what(
+        map=('elevation_shade at PERMANENT', 'landclass96'),
+        coord=[(638509.051416, 224742.348346)],
+        localized=True)
 
-    testdata2 = gvect.vector_what(map=('firestations','bridges'),
-                                  coord=(633177.897487,221352.921257), distance=10)
-    
+    testdata2 = gvect.vector_what(
+        map=(
+            'firestations', 'bridges'), coord=(
+            633177.897487, 221352.921257), distance=10)
+
     testdata = testdata1 + testdata2
-    data = PrepareQueryResults(coordinates = (638509.051416,224742.348346), result = testdata)
-    frame = QueryDialog(parent = None, data = data)
+    data = PrepareQueryResults(
+        coordinates=(
+            638509.051416,
+            224742.348346),
+        result=testdata)
+    frame = QueryDialog(parent=None, data=data)
     frame.ShowModal()
     frame.Destroy()
     app.MainLoop()

Modified: grass/trunk/gui/wxpython/gui_core/simplelmgr.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/simplelmgr.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gui_core/simplelmgr.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -45,9 +45,11 @@
 class SimpleLayerManager(wx.Panel):
     """Simple layer manager class provides similar functionality to
     Layertree, but it's just list, not tree."""
-    def __init__(self, parent, layerList,
-                 lmgrStyle=SIMPLE_LMGR_RASTER | SIMPLE_LMGR_VECTOR | SIMPLE_LMGR_TB_LEFT,
-                 toolbarCls=None, modal=False):
+
+    def __init__(
+            self, parent, layerList, lmgrStyle=SIMPLE_LMGR_RASTER |
+            SIMPLE_LMGR_VECTOR | SIMPLE_LMGR_TB_LEFT, toolbarCls=None,
+            modal=False):
         wx.Panel.__init__(self, parent=parent, name='SimpleLayerManager')
 
         self._style = lmgrStyle
@@ -67,8 +69,12 @@
         # needed in order not to change selection when moving layers
         self._blockSelectionChanged = False
 
-        self._checkList.Bind(wx.EVT_LISTBOX, lambda evt: self._selectionChanged())
-        self._checkList.Bind(wx.EVT_LISTBOX_DCLICK, self.OnLayerChangeProperties)
+        self._checkList.Bind(
+            wx.EVT_LISTBOX,
+            lambda evt: self._selectionChanged())
+        self._checkList.Bind(
+            wx.EVT_LISTBOX_DCLICK,
+            self.OnLayerChangeProperties)
         self._checkList.Bind(wx.EVT_CHECKLISTBOX, self.OnLayerChecked)
         self._checkList.Bind(wx.EVT_CONTEXT_MENU, self.OnContextMenu)
 
@@ -95,9 +101,9 @@
                              CloseButton(False).
                              BestSize((self._checkList.GetBestSize())))
         paneInfo = wx.aui.AuiPaneInfo(). \
-                   Name("toolbar").Caption(_("Toolbar")).ToolbarPane(). \
-                   CloseButton(False).Layer(1).Gripper(False). \
-                   BestSize((self._toolbar.GetBestSize()))
+            Name("toolbar").Caption(_("Toolbar")).ToolbarPane(). \
+            CloseButton(False).Layer(1).Gripper(False). \
+            BestSize((self._toolbar.GetBestSize()))
         if self._style & SIMPLE_LMGR_TB_LEFT:
             paneInfo.Left()
         elif self._style & SIMPLE_LMGR_TB_RIGHT:
@@ -135,7 +141,12 @@
                   _("Copy map names to clipboard (bottom to top)")]
         for label, text in zip(labels, texts):
             id = wx.NewId()
-            self.Bind(wx.EVT_MENU, lambda evt, t=text, id=id: self._copyText(t), id=id)
+            self.Bind(
+                wx.EVT_MENU,
+                lambda evt,
+                t=text,
+                id=id: self._copyText(t),
+                id=id)
 
             menu.Append(id, label)
 
@@ -147,7 +158,7 @@
     def _copyText(self, text):
         """Helper function for copying
 
-        TODO: move to utils?        
+        TODO: move to utils?
         """
         if wx.TheClipboard.Open():
             do = wx.TextDataObject()
@@ -173,8 +184,8 @@
         Dummy layer is added first."""
         cmd = ['d.rast']
         layer = self.AddRaster(name='', cmd=cmd, hidden=True, dialog=None)
-        GUI(parent=self, giface=None, modal=self._modal).ParseCommand(cmd=cmd,
-                                                    completed=(self.GetOptData, layer, ''))
+        GUI(parent=self, giface=None, modal=self._modal).ParseCommand(
+            cmd=cmd, completed=(self.GetOptData, layer, ''))
         event.Skip()
 
     def OnAddVector(self, event):
@@ -183,8 +194,8 @@
         cmd = ['d.vect']
 
         layer = self.AddVector(name='', cmd=cmd, hidden=True, dialog=None)
-        GUI(parent=self, giface=None, modal=self._modal).ParseCommand(cmd=cmd,
-                                                   completed=(self.GetOptData, layer, ''))
+        GUI(parent=self, giface=None, modal=self._modal).ParseCommand(
+            cmd=cmd, completed=(self.GetOptData, layer, ''))
         event.Skip()
 
     def OnAddRast3d(self, event):
@@ -192,8 +203,8 @@
         Dummy layer is added first."""
         cmd = ['d.rast3d']
         layer = self.AddRast3d(name='', cmd=cmd, hidden=True, dialog=None)
-        GUI(parent=self, giface=None, modal=self._modal).ParseCommand(cmd=cmd,
-                                                   completed=(self.GetOptData, layer, ''))
+        GUI(parent=self, giface=None, modal=self._modal).ParseCommand(
+            cmd=cmd, completed=(self.GetOptData, layer, ''))
         event.Skip()
 
     def OnAddRGB(self, event):
@@ -201,15 +212,16 @@
         Dummy layer is added first."""
         cmd = ['d.rgb']
         layer = self.AddRGB(name='', cmd=cmd, hidden=True, dialog=None)
-        GUI(parent=self, giface=None, modal=self._modal).ParseCommand(cmd=cmd,
-                                                    completed=(self.GetOptData, layer, ''))
+        GUI(parent=self, giface=None, modal=self._modal).ParseCommand(
+            cmd=cmd, completed=(self.GetOptData, layer, ''))
         event.Skip()
 
     def OnRemove(self, event):
         """Removes selected layers from list."""
         layers = self._layerList.GetSelectedLayers(activeOnly=False)
         for layer in layers:
-            self.layerRemoved.emit(index=self._layerList.GetLayerIndex(layer), layer=layer)
+            self.layerRemoved.emit(
+                index=self._layerList.GetLayerIndex(layer), layer=layer)
             self._layerList.RemoveLayer(layer)
         self._update()
         self.anyChange.emit()
@@ -240,7 +252,8 @@
         for layer in layers:
             idx = self._layerList.GetLayerIndex(layer)
             if idx < len(self._layerList) - 1:
-                self.layerMovedDown.emit(index=self._layerList.GetLayerIndex(layer), layer=layer)
+                self.layerMovedDown.emit(
+                    index=self._layerList.GetLayerIndex(layer), layer=layer)
                 self._layerList.MoveLayerDown(layer)
         self._update()
         self._blockSelectionChanged = False
@@ -257,9 +270,8 @@
 
     def _layerChangeProperties(self, layer):
         """Opens new module dialog or recycles it."""
-        GUI(parent=self, giface=None,
-            modal=self._modal).ParseCommand(cmd=layer.cmd,
-                                            completed=(self.GetOptData, layer, ''))
+        GUI(parent=self, giface=None, modal=self._modal).ParseCommand(
+            cmd=layer.cmd, completed=(self.GetOptData, layer, ''))
 
     def OnLayerChangeOpacity(self, event):
         """Opacity of a layer is changing."""
@@ -280,9 +292,11 @@
 
     def _setLayerOpacity(self, layer, value):
         """Sets layer's opacity.'"""
-        layer.opacity = value 
+        layer.opacity = value
         self._update()
-        self.opacityChanged.emit(index=self._layerList.GetLayerIndex(layer), layer=layer)
+        self.opacityChanged.emit(
+            index=self._layerList.GetLayerIndex(layer),
+            layer=layer)
         self.anyChange.emit()
 
     def _update(self):
@@ -298,8 +312,10 @@
 
         for layer in self._layerList:
             if layer.opacity < 1:
-                items.append("{name} (opacity {opacity}%)".format(name=layer.name,
-                                                                  opacity=int(layer.opacity * 100)))
+                items.append(
+                    "{name} (opacity {opacity}%)".format(
+                        name=layer.name, opacity=int(
+                            layer.opacity * 100)))
             else:
                 items.append(layer.name)
             active.append(layer.IsActive())
@@ -330,7 +346,9 @@
                         signal = self.cmdChanged
 
                     layer.name = mapName
-                    signal.emit(index=self._layerList.GetLayerIndex(layer), layer=layer)
+                    signal.emit(
+                        index=self._layerList.GetLayerIndex(layer),
+                        layer=layer)
                 except ValueError as e:
                     self._layerList.RemoveLayer(layer)
                     GError(parent=self,
@@ -388,6 +406,7 @@
     Style of the toolbar can be changed (horizontal,
     vertical, which map types to include).
     """
+
     def __init__(self, parent, lmgrStyle):
         """Toolbar constructor
         """
@@ -407,17 +426,17 @@
         """Toolbar data"""
         data = [('edit', icons['edit'],
                  self.parent.OnLayerChangeProperties),
-                 ('remove', icons['remove'],
+                ('remove', icons['remove'],
                  self.parent.OnRemove),
-                 (None, ),
-                 ('up', icons['up'],
+                (None, ),
+                ('up', icons['up'],
                  self.parent.OnLayerUp),
-                 ('down', icons['down'],
+                ('down', icons['down'],
                  self.parent.OnLayerDown),
-                 (None, ),
-                 ('opacity', icons['opacity'],
+                (None, ),
+                ('opacity', icons['opacity'],
                  self.parent.OnLayerChangeOpacity),
-                 ]
+                ]
         if self._style & SIMPLE_LMGR_RASTER3D:
             data.insert(0, ('addRaster3d', icons['addRast3d'],
                             self.parent.OnAddRast3d))
@@ -454,10 +473,11 @@
                           label=_("Add 3D raster map layer"),
                           desc=_("Add 3D raster map layer")),
     'addRGB': MetaIcon(img='layer-rgb-add', label=_('Add RGB map layer'))
-    }
+}
 
 
 class TestFrame(wx.Frame):
+
     def __init__(self, parent):
         wx.Frame.__init__(self, parent=parent)
         SimpleLayerManager(parent=self, layerList=LayerList())

Modified: grass/trunk/gui/wxpython/gui_core/toolbars.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/toolbars.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gui_core/toolbars.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -32,64 +32,65 @@
 
 
 BaseIcons = {
-    'display'    : MetaIcon(img = 'show',
-                            label = _('Display map'),
-                            desc  =  _('Re-render modified map layers only')),
-    'render'     : MetaIcon(img = 'layer-redraw',
-                            label = _('Render map'),
-                            desc = _('Force re-rendering all map layers')),
-    'erase'      : MetaIcon(img = 'erase',
-                            label = _('Erase display'),
-                            desc = _('Erase display canvas with given background color')),
-    'pointer'    : MetaIcon(img = 'pointer',
-                            label = _('Pointer')),
-    'zoomIn'     : MetaIcon(img = 'zoom-in',
-                            label = _('Zoom in'),
-                            desc = _('Drag or click mouse to zoom')),
-    'zoomOut'    : MetaIcon(img = 'zoom-out',
-                            label = _('Zoom out'),
-                            desc = _('Drag or click mouse to unzoom')),
-    'zoomBack'   : MetaIcon(img = 'zoom-last',
-                            label = _('Return to previous zoom')),
-    'zoomMenu'   : MetaIcon(img = 'zoom-more',
-                            label = _('Various zoom options'),
-                            desc = _('Zoom to default or saved region, save to named region, ...')),
-    'zoomExtent' : MetaIcon(img = 'zoom-extent',
-                            label = _('Zoom to selected map layer(s)')),
-    'zoomRegion' : MetaIcon(img = 'zoom-region',
-                            label = _('Zoom to computational region extent')),
-    'pan'        : MetaIcon(img = 'pan',
-                            label = _('Pan'),
-                            desc = _('Drag with mouse to pan')),
-    'saveFile'   : MetaIcon(img = 'map-export',
-                            label = _('Save display to file')),
-    'print'      : MetaIcon(img = 'print',
-                            label = _('Print display')),
-    'font'       : MetaIcon(img = 'font',
-                            label = _('Select font')),
-    'help'       : MetaIcon(img = 'help',
-                            label = _('Show manual')),
-    'quit'       : MetaIcon(img = 'quit',
-                            label = _('Quit')),
-    'addRast'    : MetaIcon(img = 'layer-raster-add',
-                            label = _('Add raster map layer')),
-    'addVect'    : MetaIcon(img = 'layer-vector-add',
-                            label = _('Add vector map layer')),
-    'overlay'    : MetaIcon(img = 'overlay-add',
-                            label = _('Add map elements'),
-                            desc = _('Overlay elements like scale and legend onto map')),
-    'histogramD' : MetaIcon(img = 'layer-raster-histogram',
-                            label = _('Create histogram with d.histogram')),
-    'settings'   : MetaIcon(img = 'settings',
-                            label = _("Settings")),
-    }
-    
+    'display': MetaIcon(img='show',
+                        label=_('Display map'),
+                        desc=_('Re-render modified map layers only')),
+    'render': MetaIcon(img='layer-redraw',
+                       label=_('Render map'),
+                       desc=_('Force re-rendering all map layers')),
+    'erase': MetaIcon(img='erase',
+                      label=_('Erase display'),
+                      desc=_('Erase display canvas with given background color')),
+    'pointer': MetaIcon(img='pointer',
+                        label=_('Pointer')),
+    'zoomIn': MetaIcon(img='zoom-in',
+                       label=_('Zoom in'),
+                       desc=_('Drag or click mouse to zoom')),
+    'zoomOut': MetaIcon(img='zoom-out',
+                        label=_('Zoom out'),
+                        desc=_('Drag or click mouse to unzoom')),
+    'zoomBack': MetaIcon(img='zoom-last',
+                         label=_('Return to previous zoom')),
+    'zoomMenu': MetaIcon(img='zoom-more',
+                         label=_('Various zoom options'),
+                         desc=_('Zoom to default or saved region, save to named region, ...')),
+    'zoomExtent': MetaIcon(img='zoom-extent',
+                           label=_('Zoom to selected map layer(s)')),
+    'zoomRegion': MetaIcon(img='zoom-region',
+                           label=_('Zoom to computational region extent')),
+    'pan': MetaIcon(img='pan',
+                    label=_('Pan'),
+                    desc=_('Drag with mouse to pan')),
+    'saveFile': MetaIcon(img='map-export',
+                         label=_('Save display to file')),
+    'print': MetaIcon(img='print',
+                      label=_('Print display')),
+    'font': MetaIcon(img='font',
+                     label=_('Select font')),
+    'help': MetaIcon(img='help',
+                     label=_('Show manual')),
+    'quit': MetaIcon(img='quit',
+                     label=_('Quit')),
+    'addRast': MetaIcon(img='layer-raster-add',
+                        label=_('Add raster map layer')),
+    'addVect': MetaIcon(img='layer-vector-add',
+                        label=_('Add vector map layer')),
+    'overlay': MetaIcon(img='overlay-add',
+                        label=_('Add map elements'),
+                        desc=_('Overlay elements like scale and legend onto map')),
+    'histogramD': MetaIcon(img='layer-raster-histogram',
+                           label=_('Create histogram with d.histogram')),
+    'settings': MetaIcon(img='settings',
+                         label=_("Settings")),
+}
+
+
 class BaseToolbar(wx.ToolBar):
     """Abstract toolbar class.
-    
+
     Following code shows how to create new basic toolbar:
 
-    
+
         class MyToolbar(BaseToolbar):
             def __init__(self, parent):
                 BaseToolbar.__init__(self, parent)
@@ -100,36 +101,37 @@
                 return self._getToolbarData((("help", Icons["help"],
                                               self.parent.OnHelp),
                                               ))
-    
+
     """
-    def __init__(self, parent, toolSwitcher=None, style=wx.NO_BORDER|wx.TB_HORIZONTAL):
+
+    def __init__(self, parent, toolSwitcher=None,
+                 style=wx.NO_BORDER | wx.TB_HORIZONTAL):
         self.parent = parent
         wx.ToolBar.__init__(self, parent=self.parent, id=wx.ID_ANY,
                             style=style)
-        
 
         self._default = None
         self.SetToolBitmapSize(globalvar.toolbarSize)
-        
+
         self.toolSwitcher = toolSwitcher
         self.handlers = {}
-        
+
     def InitToolbar(self, toolData):
         """Initialize toolbar, add tools to the toolbar
         """
         for tool in toolData:
             self.CreateTool(*tool)
-        
+
         self._data = toolData
-        
+
     def _toolbarData(self):
         """Toolbar data (virtual)"""
         return None
-    
+
     def CreateTool(self, label, bitmap, kind,
-                   shortHelp, longHelp, handler, pos = -1):
+                   shortHelp, longHelp, handler, pos=-1):
         """Add tool to the toolbar
-        
+
         :param pos: if -1 add tool, if > 0 insert at given pos
         :return: id of tool
         """
@@ -137,38 +139,38 @@
         tool = -1
         if label:
             tool = vars(self)[label] = wx.NewId()
-            Debug.msg(3, "CreateTool(): tool=%d, label=%s bitmap=%s" % \
-                          (tool, label, bitmap))
+            Debug.msg(3, "CreateTool(): tool=%d, label=%s bitmap=%s" %
+                      (tool, label, bitmap))
             if pos < 0:
                 toolWin = self.AddLabelTool(tool, label, bitmap,
                                             bmpDisabled, kind,
                                             shortHelp, longHelp)
             else:
                 toolWin = self.InsertLabelTool(pos, tool, label, bitmap,
-                                            bmpDisabled, kind,
-                                            shortHelp, longHelp)
+                                               bmpDisabled, kind,
+                                               shortHelp, longHelp)
             self.handlers[tool] = handler
             self.Bind(wx.EVT_TOOL, handler, toolWin)
             self.Bind(wx.EVT_TOOL, self.OnTool, toolWin)
-        else: # separator
+        else:  # separator
             self.AddSeparator()
 
         return tool
 
-    def EnableLongHelp(self, enable = True):
+    def EnableLongHelp(self, enable=True):
         """Enable/disable long help
-        
+
         :param enable: True for enable otherwise disable
         """
         for tool in self._data:
-            if tool[0] == '': # separator
+            if tool[0] == '':  # separator
                 continue
 
             if enable:
                 self.SetToolLongHelp(vars(self)[tool[0]], tool[4])
             else:
                 self.SetToolLongHelp(vars(self)[tool[0]], "")
-        
+
     def OnTool(self, event):
         """Tool selected
         """
@@ -180,16 +182,16 @@
     def SelectTool(self, id):
         self.ToggleTool(id, True)
         self.toolSwitcher.ToolChanged(id)
-        
+
         self.handlers[id](event=None)
 
     def SelectDefault(self):
         """Select default tool"""
         self.SelectTool(self._default)
-        
+
     def FixSize(self, width):
         """Fix toolbar width on Windows
-            
+
         .. todo::
             Determine why combobox causes problems here
         """
@@ -197,9 +199,9 @@
             size = self.GetBestSize()
             self.SetSize((size[0] + width, size[1]))
 
-    def Enable(self, tool, enable = True):
+    def Enable(self, tool, enable=True):
         """Enable/Disable defined tool
-        
+
         :param tool: name
         :param enable: True to enable otherwise disable tool
         """
@@ -210,19 +212,19 @@
             # this error was ignored for a long time
             raise AttributeError("Toolbar does not have a tool %s." % tool)
             return
-        
+
         self.EnableTool(id, enable)
 
-    def EnableAll(self, enable = True):
+    def EnableAll(self, enable=True):
         """Enable/Disable all tools
-        
+
         :param enable: True to enable otherwise disable tool
         """
         for item in self._toolbarData():
             if not item[0]:
                 continue
             self.Enable(item[0], enable)
-        
+
     def _getToolbarData(self, data):
         """Define tool
         """
@@ -231,73 +233,77 @@
             retData.append(self._defineTool(*args))
         return retData
 
-    def _defineTool(self, name = None, icon = None, handler = None, item = wx.ITEM_NORMAL, pos = -1):
+    def _defineTool(self, name=None, icon=None, handler=None,
+                    item=wx.ITEM_NORMAL, pos=-1):
         """Define tool
         """
         if name:
             return (name, icon.GetBitmap(),
                     item, icon.GetLabel(), icon.GetDesc(),
                     handler, pos)
-        return ("", "", "", "", "", "") # separator
+        return ("", "", "", "", "", "")  # separator
 
     def _onMenu(self, data):
         """Toolbar pop-up menu"""
         menu = wx.Menu()
-        
+
         for icon, handler in data:
             item = wx.MenuItem(menu, wx.ID_ANY, icon.GetLabel())
             item.SetBitmap(icon.GetBitmap(self.parent.iconsize))
             menu.AppendItem(item)
             self.Bind(wx.EVT_MENU, handler, item)
-        
+
         self.PopupMenu(menu)
         menu.Destroy()
 
-    def CreateSelectionButton(self, tooltip = _("Select graphics tool")):
+    def CreateSelectionButton(self, tooltip=_("Select graphics tool")):
         """Add button to toolbar for selection of graphics drawing mode.
 
         Button must be custom (not toolbar tool) to set smaller width.
         """
         arrowPath = os.path.join(IMGDIR, 'small_down_arrow.png')
         if os.path.isfile(arrowPath) and os.path.getsize(arrowPath):
-            bitmap = wx.Bitmap(name = arrowPath)
+            bitmap = wx.Bitmap(name=arrowPath)
         else:
-            bitmap = wx.ArtProvider.GetBitmap(id = wx.ART_MISSING_IMAGE, client = wx.ART_TOOLBAR)
-        button =  wx.BitmapButton(parent=self, id=wx.ID_ANY, size=((-1, self.GetToolSize()[1])),
-                                  bitmap=bitmap, style=wx.NO_BORDER)
+            bitmap = wx.ArtProvider.GetBitmap(
+                id=wx.ART_MISSING_IMAGE, client=wx.ART_TOOLBAR)
+        button = wx.BitmapButton(parent=self, id=wx.ID_ANY, size=(
+            (-1, self.GetToolSize()[1])), bitmap=bitmap, style=wx.NO_BORDER)
         button.SetToolTipString(tooltip)
 
         return button
 
+
 class ToolSwitcher:
     """Class handling switching tools in toolbar and custom toggle buttons."""
+
     def __init__(self):
         self._groups = defaultdict(lambda: defaultdict(list))
         self._toolsGroups = defaultdict(list)
-        
+
         # emitted when tool is changed
         self.toggleToolChanged = Signal('ToolSwitcher.toggleToolChanged')
 
     def AddToolToGroup(self, group, toolbar, tool):
         """Adds tool from toolbar to group of exclusive tools.
-        
+
         :param group: name of group (e.g. 'mouseUse')
         :param toolbar: instance of toolbar
         :param tool: id of a tool from the toolbar
         """
         self._groups[group][toolbar].append(tool)
         self._toolsGroups[tool].append(group)
-        
+
     def AddCustomToolToGroup(self, group, btnId, toggleHandler):
         """Adds custom tool from to group of exclusive tools (some toggle button).
-        
+
         :param group: name of group (e.g. 'mouseUse')
         :param btnId: id of a tool (typically button)
         :param toggleHandler: handler to be called to switch the button
         """
         self._groups[group]['custom'].append((btnId, toggleHandler))
         self._toolsGroups[btnId].append(group)
-       
+
     def RemoveCustomToolFromGroup(self, tool):
         """Removes custom tool from group.
 
@@ -308,14 +314,14 @@
         for group in self._toolsGroups[tool]:
             self._groups[group]['custom'] = \
                 [(bid, hdlr) for (bid, hdlr)
-                in self._groups[group]['custom'] if bid != tool]
-        
+                 in self._groups[group]['custom'] if bid != tool]
+
     def RemoveToolbarFromGroup(self, group, toolbar):
         """Removes toolbar from group.
-        
+
         Before toolbar is destroyed, it must be removed from group, too.
         Otherwise we can expect some DeadObject errors.
-        
+
         :param group: name of group (e.g. 'mouseUse')
         :param toolbar: instance of toolbar
         """
@@ -342,7 +348,7 @@
 
     def ToolChanged(self, tool):
         """When any tool/button is pressed, other tools from group must be unchecked.
-        
+
         :param tool: id of a tool/button
         """
         for group in self._toolsGroups[tool]:

Modified: grass/trunk/gui/wxpython/gui_core/treeview.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/treeview.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gui_core/treeview.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -42,6 +42,7 @@
         itemActivated - attribute 'node'
         contextMenu - attribute 'node'
     """
+
     def __init__(self, model, parent, *args, **kw):
         self._model = model
         super(AbstractTreeViewMixin, self).__init__(parent=parent, *args, **kw)
@@ -51,16 +52,16 @@
         self.contextMenu = Signal('TreeView.contextMenu')
 
         self.Bind(wx.EVT_TREE_SEL_CHANGED, lambda evt:
-                                           self._emitSignal(evt.GetItem(), self.selectionChanged))
+                  self._emitSignal(evt.GetItem(), self.selectionChanged))
         self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, lambda evt:
-                                           self._emitSignal(evt.GetItem(), self.itemActivated))
+                  self._emitSignal(evt.GetItem(), self.itemActivated))
         self.Bind(wx.EVT_TREE_ITEM_MENU, lambda evt:
-                                           self._emitSignal(evt.GetItem(), self.contextMenu))
+                  self._emitSignal(evt.GetItem(), self.contextMenu))
 
     def SetModel(self, model):
         """Set tree model and refresh.
-        
-        :param model: tree model        
+
+        :param model: tree model
         """
         self._model = model
         self.RefreshItems()
@@ -127,7 +128,7 @@
         item = self.GetItemByIndex(index)
 
         return self.IsExpanded(item)
-    
+
     def CollapseNode(self, node, recursive=True):
         """Collapse items.
 
@@ -163,26 +164,31 @@
 
 class TreeView(AbstractTreeViewMixin, wx.TreeCtrl):
     """Tree view class inheriting from wx.TreeCtrl"""
+
     def __init__(self, model, parent, *args, **kw):
         super(TreeView, self).__init__(parent=parent, model=model, *args, **kw)
         self.RefreshItems()
 
+
 class CTreeView(AbstractTreeViewMixin, CT.CustomTreeCtrl):
     """Tree view class inheriting from wx.TreeCtrl"""
+
     def __init__(self, model, parent, **kw):
         if hasAgw:
             style = 'agwStyle'
         else:
             style = 'style'
-        
+
         if style not in kw:
             kw[style] = CT.TR_HIDE_ROOT | CT.TR_FULL_ROW_HIGHLIGHT |\
                 CT.TR_HAS_BUTTONS | CT.TR_LINES_AT_ROOT | CT.TR_SINGLE
         super(CTreeView, self).__init__(parent=parent, model=model, **kw)
         self.SetBackgroundColour("white")
         self.RefreshItems()
-        
+
+
 class TreeListView(AbstractTreeViewMixin, ExpansionState, gizmos.TreeListCtrl):
+
     def __init__(self, model, parent, columns, **kw):
         self._columns = columns
         super(TreeListView, self).__init__(parent=parent, model=model, **kw)
@@ -191,8 +197,8 @@
         self.SetMainColumn(0)
         self.RefreshItems()
         # to solve events inconsitency
-        self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK,  lambda evt:
-                                           self._emitSignal(evt.GetItem(), self.contextMenu))
+        self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, lambda evt:
+                  self._emitSignal(evt.GetItem(), self.contextMenu))
         self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnRightClick)
 
     def OnGetItemText(self, index, column=0):
@@ -211,16 +217,18 @@
 
     def OnRightClick(self, event):
         """Select item on right click.
-        
-        With multiple selection we don't want to deselect all items        
+
+        With multiple selection we don't want to deselect all items
         """
         item = event.GetItem()
         if not self.IsSelected(item):
             self.SelectItem(item)
         event.Skip()
 
+
 class TreeFrame(wx.Frame):
     """Frame for testing purposes only."""
+
     def __init__(self, model=None):
         wx.Frame.__init__(self, None, title='Test tree')
 
@@ -240,7 +248,7 @@
     def OnSelChanged(self):
         print 'selected items: ' + \
               str([node.label for node in self.tree.GetSelected()])
-        
+
     def OnItemActivated(self, node):
         print 'activated: ' + node.label
 
@@ -250,13 +258,18 @@
     root = tree.root
     n1 = tree.AppendNode(parent=root, label='node1')
     n2 = tree.AppendNode(parent=root, label='node2')
-    n3 = tree.AppendNode(parent=root, label='node3') # pylint: disable=W0612
+    n3 = tree.AppendNode(parent=root, label='node3')  # pylint: disable=W0612
     n11 = tree.AppendNode(parent=n1, label='node11', data={'xxx': 'A'})
-    n12 = tree.AppendNode(parent=n1, label='node12', data={'xxx': 'B'}) # pylint: disable=W0612
-    n21 = tree.AppendNode(parent=n2, label='node21', data={'xxx': 'A'}) # pylint: disable=W0612
-    n111 = tree.AppendNode(parent=n11, label='node111', data={'xxx': 'A'}) # pylint: disable=W0612
+    n12 = tree.AppendNode(
+        parent=n1, label='node12', data={
+            'xxx': 'B'})  # pylint: disable=W0612
+    n21 = tree.AppendNode(
+        parent=n2, label='node21', data={
+            'xxx': 'A'})  # pylint: disable=W0612
+    n111 = tree.AppendNode(
+        parent=n11, label='node111', data={
+            'xxx': 'A'})  # pylint: disable=W0612
 
-
     app = wx.App()
     frame = TreeFrame(model=tree)
 #    frame.tree.Select(n111)

Modified: grass/trunk/gui/wxpython/gui_core/vselect.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/vselect.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gui_core/vselect.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -32,13 +32,19 @@
 import grass.script as grass
 from grass.pydispatch.signal import Signal
 
+
 class VectorSelectList(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
     """Widget for managing vector features selected from map display
     """
+
     def __init__(self, parent):
-        wx.ListCtrl.__init__(self, parent=parent, id=wx.ID_ANY, style=wx.LC_REPORT | wx.BORDER_SUNKEN)
+        wx.ListCtrl.__init__(
+            self,
+            parent=parent,
+            id=wx.ID_ANY,
+            style=wx.LC_REPORT | wx.BORDER_SUNKEN)
         listmix.ListCtrlAutoWidthMixin.__init__(self)
-        
+
         self.InsertColumn(col=0, heading=_('category'))
         self.InsertColumn(col=1, heading=_('type'))
         self.SetColumnWidth(0, 100)
@@ -50,7 +56,7 @@
     def AddItem(self, item):
         if 'Category' not in item:
             return
-        
+
         pos = self.InsertStringItem(0, str(item['Category']))
         self.SetStringItem(pos, 1, str(item['Type']))
         self.dictIndex[str(item['Category'])] = pos
@@ -59,12 +65,19 @@
         index = self.dictIndex.get(str(item['Category']), -1)
         if index > -1:
             self.DeleteItem(index)
-        
+
+
 class VectorSelectDialog(wx.Dialog):
     """Dialog for managing vector features selected from map display"""
+
     def __init__(self, parent, title=_("Select features"), size=(200, 300)):
-        wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY,
-                           title=title, size=size, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
+        wx.Dialog.__init__(
+            self,
+            parent=parent,
+            id=wx.ID_ANY,
+            title=title,
+            size=size,
+            style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
 
         self._layout()
 
@@ -78,6 +91,7 @@
 
         self.Show()
 
+
 class VectorSelectBase():
     """@brief Main class of vector selection function
 
@@ -88,6 +102,7 @@
     This class can be initialized with (see CreateDialog()) or without
     (see gselect) dialog (see VectorSelectDialog).
     """
+
     def __init__(self, parent, giface):
         self.parent = parent
         self._giface = giface
@@ -97,13 +112,13 @@
         self.RegisterMapEvtHandler()
 
         self.selectedFeatures = []
-        self.mapName = None # chosen map for selecting features
+        self.mapName = None  # chosen map for selecting features
 
         self._dialog = None
         self.onCloseDialog = None
-        
+
         self.updateLayer = Signal('VectorSelectBase.updateLayer')
-        
+
         self.painter = VectorSelectHighlighter(self.mapDisp, giface)
 
     def CreateDialog(self, createButton=True):
@@ -113,20 +128,21 @@
         """
         if self._dialog:
             return
-        
+
         self._dialog = VectorSelectDialog(parent=self.parent)
-        self._dialog.Bind(wx.EVT_CLOSE,self.OnCloseDialog)
+        self._dialog.Bind(wx.EVT_CLOSE, self.OnCloseDialog)
         if createButton:
-            createMap = wx.Button(self._dialog, wx.ID_ANY, _("Create a new map"))
+            createMap = wx.Button(
+                self._dialog, wx.ID_ANY, _("Create a new map"))
             createMap.Bind(wx.EVT_BUTTON, self.OnExportMap)
             self._dialog.AddWidget(createMap, proportion=0.1)
         self.slist = VectorSelectList(self._dialog)
         self.slist.Bind(wx.EVT_LIST_KEY_DOWN, self.OnDelete)
         self.slist.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.OnDeleteRow)
         self._dialog.AddWidget(self.slist)
-        
+
         self.onCloseDialog = Signal('VectorSelectBase.onCloseDialog')
-        
+
     def OnDeleteRow(self, event=None):
         """Delete row in widget
         """
@@ -151,26 +167,26 @@
             self.mapWin.RegisterMouseEventHandler(wx.EVT_LEFT_DOWN,
                                                   self._onMapClickHandler,
                                                   'cross')
-        self.register=True
+        self.register = True
 
     def UnregisterMapEvtHandler(self):
         """Unregistrates _onMapClickHandler from mapWin"""
         if self.register:
             self.mapWin.UnregisterMouseEventHandler(wx.EVT_LEFT_DOWN,
                                                     self._onMapClickHandler)
-        self.register=False
+        self.register = False
 
     def OnClose(self):
-        self.selectedFeatures=[]
+        self.selectedFeatures = []
         self._draw()
         self.UnregisterMapEvtHandler()
 
-    def OnCloseDialog(self,evt=None):
+    def OnCloseDialog(self, evt=None):
         if not self.onCloseDialog:
             return
-        
+
         self.onCloseDialog.emit()
-        self.selectedFeatures=[]
+        self.selectedFeatures = []
         self.painter.Clear()
         self._dialog.Destroy()
         self.UnregisterMapEvtHandler()
@@ -197,22 +213,23 @@
 
     def AddVecInfo(self, vInfoDictTMP):
         """Update vector in list
-        
+
         Note: click on features add category
               second click on the same vector remove category from list
         """
         if len(self.selectedFeatures) > 0:
             for sel in self.selectedFeatures:
-                if sel['Category'] == vInfoDictTMP['Category']: #features is selected=> remove features
+                if sel['Category'] == vInfoDictTMP[
+                        'Category']:  # features is selected=> remove features
                     self.selectedFeatures.remove(sel)
-                    if self._dialog:#if dialog initilized->update dialog
+                    if self._dialog:  # if dialog initilized->update dialog
                         self.slist.RemoveItem(vInfoDictTMP)
                     return True
 
             self.selectedFeatures.append(vInfoDictTMP)
             if self._dialog:
                 self.slist.AddItem(vInfoDictTMP)
-        else: # only one is selected
+        else:  # only one is selected
             self.selectedFeatures.append(vInfoDictTMP)
             if self._dialog:
                 self.slist.AddItem(vInfoDictTMP)
@@ -252,7 +269,7 @@
         if layerSelected:
             mapName = str(layerSelected)
             if self.mapName is not None:
-                if self.mapName!=mapName:
+                if self.mapName != mapName:
                     self.Reset()
         else:
             mapName = None
@@ -269,7 +286,8 @@
             return {}
 
         mapInfo = self.mapWin.GetMap()
-        threshold = 10.0 * ((mapInfo.region['e'] - mapInfo.region['w']) / mapInfo.width)
+        threshold = 10.0 * (
+            (mapInfo.region['e'] - mapInfo.region['w']) / mapInfo.width)
         try:
             query = grass.vector_what(map=[self.mapName],
                                       coord=self.mapWin.GetLastEN(),
@@ -288,25 +306,27 @@
             strTMP += str(cat['Category']) + ','
         return strTMP[:-1]
 
-    def _id_generator(self, size=6, chars=string.ascii_uppercase + string.digits):
+    def _id_generator(self, size=6,
+                      chars=string.ascii_uppercase + string.digits):
         return ''.join(random.choice(chars) for _ in range(size))
 
     def OnExportMap(self, event):
         """Export selected features to a new map
-        
+
         Add new map layer to layer tree and checked it
 
         @todo: set color of map to higlight color
         """
 
-        if len(self.selectedFeatures)==0:
+        if len(self.selectedFeatures) == 0:
             GMessage(_('No features selected'))
             return
         lst = ''
-        for cat in self.selectedFeatures: # build text string of categories for v.extract input
+        for cat in self.selectedFeatures:  # build text string of categories for v.extract input
             lst += str(cat['Category']) + ','
         lst = lst[:-1]
-        outMap = str(self.selectedFeatures[0]['Map']) + '_selection' + str(self._id_generator(3))
+        outMap = str(self.selectedFeatures[0][
+                     'Map']) + '_selection' + str(self._id_generator(3))
         ret, err = RunCommand('v.extract',
                               input=self.selectedFeatures[0]['Map'],
                               layer=self.selectedFeatures[0]['Layer'],
@@ -320,14 +340,14 @@
                               lcmd=['d.vect', 'map=%s' % outMap],
                               lchecked=True)
 
-                #TODO colorize new map
+                # TODO colorize new map
                 self.Reset()
             else:
                 GMessage(_('Vector map <%s> was created') % outMap)
                 self.Reset()
         else:
             GError(_("Unable to create a new vector map.\n\nReason: %s") % err)
-        
+
     """
     def SetSelectedCat(self, cats):
         # allows setting selected vector categories by list of cats (per line)
@@ -345,12 +365,14 @@
 
         self._draw()
     """
-    
+
+
 class VectorSelectHighlighter():
     """Class for highlighting selected features on display
 
     :param mapdisp: Map display frame
     """
+
     def __init__(self, mapdisp, giface):
         self.qlayer = None
         self.mapdisp = mapdisp
@@ -359,7 +381,7 @@
         self.data = {}
         self.data['Category'] = list()
         self.data['Map'] = None
-        self.data['Layer']= None
+        self.data['Layer'] = None
 
     def SetMap(self, map):
         self.data['Map'] = map
@@ -373,14 +395,14 @@
     def Clear(self):
         self.data['Category'] = list()
         self.data['Map'] = None
-        self.data['Layer']= None
+        self.data['Layer'] = None
         self.mapdisp.RemoveQueryLayer()
-        self.giface.GetMapWindow().UpdateMap(render = False)
+        self.giface.GetMapWindow().UpdateMap(render=False)
 
     def DrawSelected(self):
         """Highlight selected features"""
         self.layerCat[int(self.data['Layer'])] = self.data['Category']
-        
+
         # add map layer with higlighted vector features
         self.AddQueryMapLayer()  # -> self.qlayer
         self.qlayer.SetOpacity(0.7)
@@ -395,13 +417,13 @@
             self.qlayer = None
 
         if self.qlayer:
-            self.qlayer.SetCmd(self.mapdisp.AddTmpVectorMapLayer(self.data['Map'], self.layerCat, addLayer=False))
+            self.qlayer.SetCmd(
+                self.mapdisp.AddTmpVectorMapLayer(
+                    self.data['Map'],
+                    self.layerCat,
+                    addLayer=False))
         else:
-            self.qlayer = self.mapdisp.AddTmpVectorMapLayer(self.data['Map'], self.layerCat)
+            self.qlayer = self.mapdisp.AddTmpVectorMapLayer(
+                self.data['Map'], self.layerCat)
 
         return self.qlayer
-
-
-
-
-

Modified: grass/trunk/gui/wxpython/gui_core/widgets.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/widgets.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gui_core/widgets.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -58,12 +58,12 @@
 from wx.lib.wordwrap import wordwrap
 import wx.combo
 try:
-    import wx.lib.agw.flatnotebook   as FN
+    import wx.lib.agw.flatnotebook as FN
 except ImportError:
-    import wx.lib.flatnotebook   as FN
+    import wx.lib.flatnotebook as FN
 try:
     from wx.lib.buttons import ThemedGenBitmapTextButton as BitmapTextButton
-except ImportError: # not sure about TGBTButton version
+except ImportError:  # not sure about TGBTButton version
     from wx.lib.buttons import GenBitmapTextButton as BitmapTextButton
 try:
     import wx.lib.agw.customtreectrl as CT
@@ -74,10 +74,10 @@
 
 from grass.pydispatch.signal import Signal
 
-from core        import globalvar
+from core import globalvar
 from core.utils import _
-from core.gcmd   import GMessage, GError
-from core.debug  import Debug
+from core.gcmd import GMessage, GError
+from core.debug import Debug
 
 
 class NotebookController:
@@ -89,6 +89,7 @@
     Methods inherited from notebook class must be delegated explicitly
     and other methods can be delegated by @c __getattr__.
     """
+
     def __init__(self, classObject, widget):
         """
         :param classObject: notebook class name (object, i.e. FlatNotebook)
@@ -121,7 +122,7 @@
             del kwargs['name']
         try:
             self.classObject.InsertPage(self.widget, **kwargs)
-        except TypeError, e:  # documentation says 'index', but certain versions of wx require 'n'
+        except TypeError as e:  # documentation says 'index', but certain versions of wx require 'n'
             kwargs['n'] = kwargs['index']
             del kwargs['index']
             self.classObject.InsertPage(self.widget, **kwargs)
@@ -192,7 +193,8 @@
         if page not in self.notebookPages:
             return -1
         for pageIndex in range(self.classObject.GetPageCount(self.widget)):
-            if self.notebookPages[page] == self.classObject.GetPage(self.widget, pageIndex):
+            if self.notebookPages[page] == self.classObject.GetPage(
+                    self.widget, pageIndex):
                 break
         return pageIndex
 
@@ -219,11 +221,14 @@
 
 class FlatNotebookController(NotebookController):
     """Controller specialized for FN.FlatNotebook subclasses"""
+
     def __init__(self, classObject, widget):
         NotebookController.__init__(self, classObject, widget)
 
     def BindPageChanged(self):
-        self.widget.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnRemoveHighlight)
+        self.widget.Bind(
+            FN.EVT_FLATNOTEBOOK_PAGE_CHANGED,
+            self.OnRemoveHighlight)
 
     def GetPageIndexByName(self, page):
         """Get notebook page index
@@ -233,7 +238,8 @@
         if page not in self.notebookPages:
             return -1
 
-        return self.classObject.GetPageIndex(self.widget, self.notebookPages[page])
+        return self.classObject.GetPageIndex(
+            self.widget, self.notebookPages[page])
 
     def InsertPage(self, **kwargs):
         """Insert a new page
@@ -252,6 +258,7 @@
     Enables advanced style settings.
     Problems with hidden tabs and does not respect system colors (native look).
     """
+
     def __init__(self, parent, style, **kwargs):
         if globalvar.hasAgw:
             FN.FlatNotebook.__init__(self, parent, id=wx.ID_ANY,
@@ -292,6 +299,7 @@
 
     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,
@@ -326,6 +334,7 @@
 
     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,
@@ -357,6 +366,7 @@
 
 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)
@@ -367,8 +377,9 @@
 
 class NumTextCtrl(wx.TextCtrl):
     """Class derived from wx.TextCtrl for numerical values only"""
-    def __init__(self, parent,  **kwargs):
-##        self.precision = kwargs.pop('prec')
+
+    def __init__(self, parent, **kwargs):
+        ##        self.precision = kwargs.pop('prec')
         wx.TextCtrl.__init__(self, parent=parent,
                              validator=NTCValidator(flag='DIGIT_ONLY'),
                              **kwargs)
@@ -392,11 +403,12 @@
 
 class FloatSlider(wx.Slider):
     """Class derived from wx.Slider for floats"""
+
     def __init__(self, **kwargs):
         Debug.msg(1, "FloatSlider.__init__()")
         wx.Slider.__init__(self, **kwargs)
         self.coef = 1.
-        #init range
+        # init range
         self.minValueOrig = 0
         self.maxValueOrig = 1
 
@@ -417,22 +429,32 @@
         self.minValueOrig = minValue
         self.maxValueOrig = maxValue
         if abs(minValue) < 1 or abs(maxValue) < 1:
-            while (abs(minValue) < 1 and minValue != 0) or (abs(maxValue) < 1 and maxValue != 0):
+            while (abs(minValue) < 1 and minValue != 0) or (
+                    abs(maxValue) < 1 and maxValue != 0):
                 minValue *= 100
                 maxValue *= 100
                 self.coef *= 100
-            super(FloatSlider, self).SetValue(super(FloatSlider, self).GetValue() * self.coef)
+            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))
+        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
+        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
 
@@ -468,7 +490,7 @@
     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)
+        dc.DrawCircle(size[0] / 2, size[1] / 2, size[0] / 2)
 
     def DrawStop(self, dc, size):
         """Draw stop symbol"""
@@ -479,7 +501,7 @@
         """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))
+                                                                 size[1] / 2))
         dc.DrawPolygon(points)
 
     def DrawPause(self, dc, size):
@@ -493,7 +515,8 @@
     """A Static Text widget that wraps its text to fit parents width,
     enlarging its height if necessary."""
 
-    def __init__(self, parent, id=wx.ID_ANY, label='', margin=0, *args, **kwds):
+    def __init__(self, parent, id=wx.ID_ANY,
+                 label='', margin=0, *args, **kwds):
         self._margin = margin
         self._initialLabel = label
         self.init = False
@@ -507,7 +530,8 @@
             self.init = True
         parent = self.GetParent()
         newExtent = wx.ClientDC(parent).GetMultiLineTextExtent(self.GetLabel())
-        # when starting, width is very small and height is big which creates very high windows
+        # when starting, width is very small and height is big which creates
+        # very high windows
         if newExtent[0] < newExtent[1]:
             return (0, 0)
         return newExtent[:2]
@@ -530,6 +554,7 @@
 
 
 class BaseValidator(wx.PyValidator):
+
     def __init__(self):
         wx.PyValidator.__init__(self)
 
@@ -573,10 +598,10 @@
         return True
 
     def TransferToWindow(self):
-        return True # Prevent wxDialog from complaining.
+        return True  # Prevent wxDialog from complaining.
 
     def TransferFromWindow(self):
-        return True # Prevent wxDialog from complaining.
+        return True  # Prevent wxDialog from complaining.
 
 
 class CoordinatesValidator(BaseValidator):
@@ -614,6 +639,7 @@
 
 class IntegerValidator(BaseValidator):
     """Validator for floating-point input"""
+
     def __init__(self):
         BaseValidator.__init__(self)
         self.type = int
@@ -625,6 +651,7 @@
 
 class FloatValidator(BaseValidator):
     """Validator for floating-point input"""
+
     def __init__(self):
         BaseValidator.__init__(self)
         self.type = float
@@ -636,6 +663,7 @@
 
 class EmailValidator(BaseValidator):
     """Validator for email input"""
+
     def __init__(self):
         BaseValidator.__init__(self)
 
@@ -658,6 +686,7 @@
 
 class TimeISOValidator(BaseValidator):
     """Validator for time ISO format (YYYY-MM-DD) input"""
+
     def __init__(self):
         BaseValidator.__init__(self)
 
@@ -679,8 +708,10 @@
         """Clone validator"""
         return TimeISOValidator()
 
+
 class NTCValidator(wx.PyValidator):
     """validates input in textctrls, taken from wxpython demo"""
+
     def __init__(self, flag=None):
         wx.PyValidator.__init__(self)
         self.flag = flag
@@ -708,6 +739,7 @@
     """This validator is used to ensure that the user has entered something
         into the text object editor dialog's text field.
     """
+
     def __init__(self, callback):
         """Standard constructor.
         """
@@ -739,7 +771,7 @@
         error occurred.  We simply return True, as we don't do any data
         transfer.
         """
-        return True # Prevent wxDialog from complaining.
+        return True  # Prevent wxDialog from complaining.
 
     def TransferFromWindow(self):
         """Transfer data from window to validator.
@@ -748,13 +780,14 @@
         error occurred.  We simply return True, as we don't do any data
         transfer.
         """
-        return True # Prevent wxDialog from complaining.
+        return True  # Prevent wxDialog from complaining.
 
 
 class GenericValidator(wx.PyValidator):
     """This validator checks condition and calls callback
     in case the condition is not fulfilled.
     """
+
     def __init__(self, condition, callback):
         """Standard constructor.
 
@@ -786,35 +819,42 @@
     def TransferToWindow(self):
         """Transfer data from validator to window.
         """
-        return True # Prevent wxDialog from complaining.
+        return True  # Prevent wxDialog from complaining.
 
     def TransferFromWindow(self):
         """Transfer data from window to validator.
         """
-        return True # Prevent wxDialog from complaining.
+        return True  # Prevent wxDialog from complaining.
 
+
 class MapValidator(GenericValidator):
     """Validator for map name input
 
     See G_legal_filename()
     """
+
     def __init__(self):
         def _mapNameValidationFailed(ctrl):
-            message = _("Name <%(name)s> is not a valid name for GRASS map. "
-                        "Please use only ASCII characters excluding %(chars)s "
-                        "and space.") % {'name': ctrl.GetValue(), 'chars': '/"\'@,=*~'}
+            message = _(
+                "Name <%(name)s> is not a valid name for GRASS map. "
+                "Please use only ASCII characters excluding %(chars)s "
+                "and space.") % {
+                'name': ctrl.GetValue(),
+                'chars': '/"\'@,=*~'}
             GError(message, caption=_("Invalid name"))
-        
+
         GenericValidator.__init__(self,
                                   grass.legal_name,
                                   _mapNameValidationFailed)
-       
+
+
 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
 
@@ -825,7 +865,8 @@
         :param parent: parent (gui_core::dialog::SymbolDialog)
         :param symbolPath: absolute path to symbol
         """
-        self.symbolSelectionChanged = Signal('SingleSymbolPanel.symbolSelectionChanged')
+        self.symbolSelectionChanged = Signal(
+            'SingleSymbolPanel.symbolSelectionChanged')
 
         wx.Panel.__init__(self, parent, id=wx.ID_ANY, style=wx.BORDER_RAISED)
         self.SetName(os.path.splitext(os.path.basename(symbolPath))[0])
@@ -836,7 +877,11 @@
         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)
@@ -854,7 +899,8 @@
         self.Refresh()
         event.Skip()
 
-        self.symbolSelectionChanged.emit(name=self.GetName(), doubleClick=False)
+        self.symbolSelectionChanged.emit(
+            name=self.GetName(), doubleClick=False)
 
     def OnDoubleClick(self, event):
         self.symbolSelectionChanged.emit(name=self.GetName(), doubleClick=True)
@@ -872,9 +918,11 @@
         self.Refresh()
 
 
-class GListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.CheckListCtrlMixin):
+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
 
@@ -885,8 +933,8 @@
         # 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
+        self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnPopupMenu)  # wxMSW
+        self.Bind(wx.EVT_RIGHT_UP, self.OnPopupMenu)  # wxGTK
 
     def LoadData(self):
         """Load data into list"""
@@ -901,7 +949,7 @@
             self.popupDataID1 = wx.NewId()
             self.popupDataID2 = wx.NewId()
 
-            self.Bind(wx.EVT_MENU, self.OnSelectAll,  id=self.popupDataID1)
+            self.Bind(wx.EVT_MENU, self.OnSelectAll, id=self.popupDataID1)
             self.Bind(wx.EVT_MENU, self.OnSelectNone, id=self.popupDataID2)
 
         # generate popup-menu
@@ -940,24 +988,24 @@
         """Get list data"""
         data = []
         checkedList = []
-        
+
         item = -1
         while True:
-            
+
             row = []
             item = self.GetNextItem(item)
             if item == -1:
                 break
 
             isChecked = self.IsChecked(item)
-            if checked is not None and  checked != isChecked:
+            if checked is not None and checked != isChecked:
                 continue
 
             checkedList.append(isChecked)
 
             for i in range(self.GetColumnCount()):
                 row.append(self.GetItem(item, i).GetText())
-            
+
             row.append(item)
             data.append(tuple(row))
 
@@ -971,16 +1019,17 @@
         self.DeleteAllItems()
         if data is None:
             return
-        
+
         for item in data:
-            index = self.InsertStringItem(sys.maxint, str(item[0]))
+            index = self.InsertStringItem(sys.maxsize, str(item[0]))
             for i in range(1, self.GetColumnCount()):
                 self.SetStringItem(index, i, item[i])
-        
+
         # check by default only on one item
         if len(data) == 1 and selectOne:
             self.CheckItem(index, True)
 
+
 class SearchModuleWidget(wx.Panel):
     """Search module widget (used e.g. in SearchModuleWindow)
 
@@ -989,12 +1038,13 @@
         showSearchResult - attribute 'result' is a node (representing module)
         showNotification - attribute 'message'
     """
+
     def __init__(self, parent, model,
                  showChoice=True, showTip=False, **kwargs):
         self._showTip = showTip
         self._showChoice = showChoice
         self._model = model
-        self._results = [] # list of found nodes
+        self._results = []  # list of found nodes
         self._resultIndex = -1
         self._searchKeys = ['description', 'keywords', 'command']
         self._oldValue = ''
@@ -1006,27 +1056,32 @@
         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)"))
+# label = " %s " % _("Find module - (press Enter for next match)"))
 
         if sys.platform == 'win32':
-            self._search = wx.TextCtrl(parent = self, id = wx.ID_ANY,
-                                       size = (-1, 25), style = wx.TE_PROCESS_ENTER)
+            self._search = wx.TextCtrl(
+                parent=self, id=wx.ID_ANY, size=(-1, 25),
+                style=wx.TE_PROCESS_ENTER)
         else:
-            self._search = wx.SearchCtrl(parent = self, id = wx.ID_ANY,
-                                         size = (-1, 25), style = wx.TE_PROCESS_ENTER)
+            self._search = wx.SearchCtrl(
+                parent=self, id=wx.ID_ANY, size=(-1, 25),
+                style=wx.TE_PROCESS_ENTER)
             self._search.SetDescriptiveText(_('Fulltext search'))
-            self._search.SetToolTipString(_("Type to search in all modules. Press Enter for next match."))
+            self._search.SetToolTipString(
+                _("Type to search in all modules. Press Enter for next match."))
 
         self._search.Bind(wx.EVT_TEXT, self.OnSearchModule)
         self._search.Bind(wx.EVT_TEXT_ENTER, self.OnEnter)
 
         if self._showTip:
-            self._searchTip = StaticWrapText(parent = self, id = wx.ID_ANY,
-                                             size = (-1, 35))
+            self._searchTip = StaticWrapText(parent=self, id=wx.ID_ANY,
+                                             size=(-1, 35))
 
         if self._showChoice:
             self._searchChoice = wx.Choice(parent=self, id=wx.ID_ANY)
-            self._searchChoice.SetItems(self._searchModule(keys=['command'], value=''))
+            self._searchChoice.SetItems(
+                self._searchModule(
+                    keys=['command'], value=''))
             self._searchChoice.Bind(wx.EVT_CHOICE, self.OnSelectModule)
 
         self._layout()
@@ -1048,7 +1103,7 @@
             boxSizer.Add(item=hSizer, flag=wx.EXPAND)
         if self._showTip:
             boxSizer.Add(item=self._searchTip,
-                          flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
+                         flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
 
         sizer.Add(item=boxSizer, proportion=1)
 
@@ -1076,10 +1131,11 @@
         self._oldValue = value
 
         if len(value) <= 2:
-            if len(value) == 0: # reset
+            if len(value) == 0:  # reset
                 commands = self._searchModule(keys=['command'], value='')
             else:
-                self.showNotification.emit(message=_("Searching, please type more characters."))
+                self.showNotification.emit(
+                    message=_("Searching, please type more characters."))
                 return
         else:
             commands = self._searchModule(keys=self._searchKeys, value=value)
@@ -1110,14 +1166,14 @@
         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)
+        commands = sorted([node.data['command']
+                           for node in nodes if node.data['command']])
 
         return commands
 
     def OnSelectModule(self, event):
         """Module selected from choice, update command prompt"""
-        cmd  = self._searchChoice.GetStringSelection()
+        cmd = self._searchChoice.GetStringSelection()
         self.moduleSelected.emit(name=cmd)
 
         if self._showTip:
@@ -1135,6 +1191,7 @@
 
 class ManageSettingsWidget(wx.Panel):
     """Widget which allows loading and saving settings into file."""
+
     def __init__(self, parent, settingsFile):
         """
         Signals:
@@ -1166,13 +1223,14 @@
         self.btnSettingsSave.SetToolTipString(_("Save current settings"))
         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"))
+        self.btnSettingsSave.SetToolTipString(
+            _("Delete currently selected settings"))
 
         # escaping with '$' character - index in self.esc_chars
         self.e_char_i = 0
         self.esc_chars = ['$', ';']
 
-        self._settings = self._loadSettings() # -> self.settingsChoice.SetItems()
+        self._settings = self._loadSettings()  # -> self.settingsChoice.SetItems()
         self.settingsLoaded.emit(settings=self._settings)
 
         self.data_to_save = []
@@ -1185,12 +1243,18 @@
     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:")),
-                               flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT | wx.LEFT,
-                               border=5)
-        self.settingsSizer.Add(item=self.settingsChoice,
-                               proportion=1, flag=wx.EXPAND | wx.BOTTOM, border=3)
+        self.settingsSizer.Add(
+            item=wx.StaticText(
+                parent=self,
+                id=wx.ID_ANY,
+                label=_("Load:")),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT | wx.LEFT,
+            border=5)
+        self.settingsSizer.Add(
+            item=self.settingsChoice,
+            proportion=1,
+            flag=wx.EXPAND | wx.BOTTOM,
+            border=3)
         self.settingsSizer.Add(item=self.btnSettingsSave,
                                flag=wx.LEFT | wx.RIGHT | wx.BOTTOM, border=3)
         self.settingsSizer.Add(item=self.btnSettingsDel,
@@ -1200,8 +1264,8 @@
         """Load named settings"""
         name = event.GetString()
         if name not in self._settings:
-            GError(parent = self,
-                   message = _("Settings <%s> not found") % name)
+            GError(parent=self,
+                   message=_("Settings <%s> not found") % name)
             return
 
         data = self._settings[name]
@@ -1229,10 +1293,14 @@
     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
@@ -1278,8 +1346,8 @@
         """
         name = self.settingsChoice.GetStringSelection()
         if not name:
-            GMessage(parent = self,
-                     message = _("No settings is defined. Operation canceled."))
+            GMessage(parent=self,
+                     message=_("No settings is defined. Operation canceled."))
             return
 
         self._settings.pop(name)
@@ -1300,11 +1368,15 @@
                 for v in values:
                     # escaping characters
                     for e_ch in self.esc_chars:
-                        v = v.replace(e_ch, self.esc_chars[self.e_char_i] + e_ch)
+                        v = v.replace(
+                            e_ch, self.esc_chars[
+                                self.e_char_i] + e_ch)
                     if first:
                         # escaping characters
                         for e_ch in self.esc_chars:
-                            key = key.replace(e_ch, self.esc_chars[self.e_char_i] + e_ch)
+                            key = key.replace(
+                                e_ch, self.esc_chars[
+                                    self.e_char_i] + e_ch)
                         fd.write('%s;%s;' % (key, v))
                         first = False
                     else:
@@ -1312,8 +1384,8 @@
                 fd.write('\n')
 
         except IOError:
-            GError(parent = self,
-                   message = _("Unable to save settings"))
+            GError(parent=self,
+                   message=_("Unable to save settings"))
             return -1
         fd.close()
 
@@ -1382,18 +1454,20 @@
                         # $$$$$; - it is not separator
                         i_esc_chars = 0
                         while True:
-                            if line[idx - (i_esc_chars + 1)] == self.esc_chars[self.e_char_i]:
+                            if line[idx - (i_esc_chars + 1)
+                                    ] == self.esc_chars[self.e_char_i]:
                                 i_esc_chars += 1
                             else:
                                 break
-                        if i_esc_chars%2 != 0:
+                        if i_esc_chars % 2 != 0:
                             i_last = idx + 1
                             continue
 
-                    lineItem = line[i_last_found : idx]
+                    lineItem = line[i_last_found: idx]
                     # unescape characters
                     for e_ch in self.esc_chars:
-                        lineItem = lineItem.replace(self.esc_chars[self.e_char_i] + e_ch, e_ch)
+                        lineItem = lineItem.replace(
+                            self.esc_chars[self.e_char_i] + e_ch, e_ch)
                     if i_last_found == 0:
                         key = lineItem
                     else:
@@ -1421,19 +1495,31 @@
                 lineData = line.rstrip('\n').split(';')
                 if len(lineData) > 4:
                     # type, dsn, format, options
-                    data[lineData[0]] = (lineData[1], lineData[2], lineData[3], lineData[4])
+                    data[
+                        lineData[0]] = (
+                        lineData[1],
+                        lineData[2],
+                        lineData[3],
+                        lineData[4])
                 else:
-                    data[lineData[0]] = (lineData[1], lineData[2], lineData[3], '')
+                    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.
 
@@ -1449,7 +1535,8 @@
         # for painting the items in the popup
         bitmap = self.GetPictureBitmap(self.GetString(item))
         if bitmap:
-            dc.DrawBitmap(bitmap, r.x, r.y + (r.height - bitmap.GetHeight()) / 2)
+            dc.DrawBitmap(
+                bitmap, r.x, r.y + (r.height - bitmap.GetHeight()) / 2)
             width = bitmap.GetWidth() + 10
         else:
             width = 0
@@ -1487,18 +1574,25 @@
     """ComboBox with drawn color tables (created by thumbnails.py).
 
     Used in r(3).colors dialog."""
+
     def _getPath(self, name):
-        return os.path.join(os.getenv("GISBASE"), "docs", "html", "colortables", "%s.png" % name)
+        return os.path.join(
+            os.getenv("GISBASE"),
+            "docs", "html", "colortables", "%s.png" % name)
 
 
 class BarscalesComboBox(PictureComboBox):
     """ComboBox with barscales for d.barscale."""
+
     def _getPath(self, name):
-        return os.path.join(os.getenv("GISBASE"), "docs", "html", "barscales", name + '.png')
+        return os.path.join(
+            os.getenv("GISBASE"),
+            "docs", "html", "barscales", name + '.png')
 
 
 class NArrowsComboBox(PictureComboBox):
     """ComboBox with north arrows for d.barscale."""
+
     def _getPath(self, name):
         path = os.path.join(os.getenv("GISBASE"), "gui", "images",
                             'symbols', 'n_arrows')
@@ -1511,52 +1605,54 @@
     def OnMeasureItem(self, item):
         return 32
 
+
 class LayersList(GListCtrl, listmix.TextEditMixin):
     """List of layers to be imported (dxf, shp...)"""
-    def __init__(self, parent, columns, log = None):
+
+    def __init__(self, parent, columns, log=None):
         GListCtrl.__init__(self, parent)
-        
+
         self.log = log
-        
+
         # setup mixins
         listmix.TextEditMixin.__init__(self)
-        
+
         for i in range(len(columns)):
             self.InsertColumn(i, columns[i])
-        
+
         if len(columns) == 4:
             width = (65, 200, 90)
         else:
             width = (65, 180, 90, 70)
-        
+
         for i in range(len(width)):
-            self.SetColumnWidth(col = i, width = width[i])
-                
+            self.SetColumnWidth(col=i, width=width[i])
+
     def OnLeftDown(self, event):
         """Allow editing only output name
-        
+
         Code taken from TextEditMixin class.
         """
         x, y = event.GetPosition()
-        
+
         colLocs = [0]
         loc = 0
         for n in range(self.GetColumnCount()):
             loc = loc + self.GetColumnWidth(n)
             colLocs.append(loc)
-        
+
         col = bisect(colLocs, x + self.GetScrollPos(wx.HORIZONTAL)) - 1
-        
+
         if col == self.GetColumnCount() - 1:
             listmix.TextEditMixin.OnLeftDown(self, event)
         else:
             event.Skip()
-        
+
     def GetLayers(self):
         """Get list of layers (layer name, output name, list id)"""
         layers = []
 
-        data = self.GetData(checked=True);
+        data = self.GetData(checked=True)
 
         for itm in data:
 
@@ -1568,4 +1664,3 @@
             layers.append((layer, output, itm[-1]))
 
         return layers
-

Modified: grass/trunk/gui/wxpython/iclass/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/iclass/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/iclass/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -6,4 +6,4 @@
     'toolbars',
     'statistics',
     'frame',
-    ]
+]

Modified: grass/trunk/gui/wxpython/iclass/dialogs.py
===================================================================
--- grass/trunk/gui/wxpython/iclass/dialogs.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/iclass/dialogs.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -25,41 +25,47 @@
 import wx.lib.mixins.listctrl as listmix
 import wx.lib.scrolledpanel as scrolled
 
-from core               import globalvar
+from core import globalvar
 from core.utils import _
-from core.settings      import UserSettings
-from core.gcmd          import GError, RunCommand, GMessage
-from gui_core.dialogs   import SimpleDialog, GroupDialog
-from gui_core           import gselect
-from gui_core.widgets   import SimpleValidator
-from iclass.statistics  import Statistics, BandStatistics
+from core.settings import UserSettings
+from core.gcmd import GError, RunCommand, GMessage
+from gui_core.dialogs import SimpleDialog, GroupDialog
+from gui_core import gselect
+from gui_core.widgets import SimpleValidator
+from iclass.statistics import Statistics, BandStatistics
 
 import grass.script as grass
 
+
 class IClassGroupDialog(SimpleDialog):
     """Dialog for imagery group selection"""
-    def __init__(self, parent, group = None, subgroup = None, 
-                 title = _("Select imagery group"), id = wx.ID_ANY):
+
+    def __init__(self, parent, group=None, subgroup=None,
+                 title=_("Select imagery group"), id=wx.ID_ANY):
         """
         Does post init and layout.
-        
+
         :param parent: gui parent
         :param title: dialog window title
         :param id: wx id
         """
         SimpleDialog.__init__(self, parent, title)
-        
+
         self.use_subg = True
 
-        self.groupSelect = gselect.Select(parent = self.panel, type = 'group',
-                                      mapsets = [grass.gisenv()['MAPSET']],
-                                      size = globalvar.DIALOG_GSELECT_SIZE,
-                                      validator = SimpleValidator(callback = self.ValidatorCallback))
+        self.groupSelect = gselect.Select(
+            parent=self.panel,
+            type='group',
+            mapsets=[
+                grass.gisenv()['MAPSET']],
+            size=globalvar.DIALOG_GSELECT_SIZE,
+            validator=SimpleValidator(
+                callback=self.ValidatorCallback))
 
         # TODO use when subgroup will be optional
-        #self.subg_chbox = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
+        # self.subg_chbox = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
         #                              label = _("Use subgroup"))
-        self.subGroupSelect = gselect.SubGroupSelect(parent = self.panel)
+        self.subGroupSelect = gselect.SubGroupSelect(parent=self.panel)
 
         self.groupSelect.SetFocus()
         if group:
@@ -68,12 +74,13 @@
         if subgroup:
             self.subGroupSelect.SetValue(subgroup)
 
-        self.editGroup = wx.Button(parent = self.panel, id = wx.ID_ANY,
-                                   label = _("Create/edit group..."))
+        self.editGroup = wx.Button(parent=self.panel, id=wx.ID_ANY,
+                                   label=_("Create/edit group..."))
 
         self.editGroup.Bind(wx.EVT_BUTTON, self.OnEditGroup)
-        self.groupSelect.GetTextCtrl().Bind(wx.EVT_TEXT, 
-                                           lambda event : wx.CallAfter(self.GroupSelected))
+        self.groupSelect.GetTextCtrl().Bind(
+            wx.EVT_TEXT, lambda event: wx.CallAfter(
+                self.GroupSelected))
 
         self.warning = _("Name of imagery group is missing.")
         self._layout()
@@ -81,33 +88,37 @@
 
     def _layout(self):
         """Do layout"""
-        self.dataSizer.Add(wx.StaticText(self.panel, id = wx.ID_ANY,
-                                         label = _("Name of imagery group:")),
-                                         proportion = 0, 
-                                         flag = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
-                                         border = 5)
-        self.dataSizer.Add(self.groupSelect, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL, border = 5)
-        
+        self.dataSizer.Add(wx.StaticText(self.panel, id=wx.ID_ANY,
+                                         label=_("Name of imagery group:")),
+                           proportion=0,
+                           flag=wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
+                           border=5)
+        self.dataSizer.Add(self.groupSelect, proportion=0,
+                           flag=wx.EXPAND | wx.ALL, border=5)
+
         # TODO use when subgroup will be optional
-        #self.dataSizer.Add(self.subg_chbox, proportion = 0,
-        #              flag = wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border = 5)
+        # self.dataSizer.Add(self.subg_chbox, proportion = 0,
+        # flag = wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border = 5)
 
-        self.dataSizer.Add(wx.StaticText(self.panel, id = wx.ID_ANY,
-                                         label = _("Name of imagery subgroup:")),
-                           proportion = 0, flag = wx.EXPAND | wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
-                           border = 5)
-        self.dataSizer.Add(self.subGroupSelect, proportion = 0,
-                       flag = wx.EXPAND | wx.ALL, border = 5)
+        self.dataSizer.Add(
+            wx.StaticText(
+                self.panel,
+                id=wx.ID_ANY,
+                label=_("Name of imagery subgroup:")),
+            proportion=0,
+            flag=wx.EXPAND | wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
+            border=5)
+        self.dataSizer.Add(self.subGroupSelect, proportion=0,
+                           flag=wx.EXPAND | wx.ALL, border=5)
 
-        self.dataSizer.Add(self.editGroup, proportion = 0,
-                      flag = wx.ALL, border = 5)
+        self.dataSizer.Add(self.editGroup, proportion=0,
+                           flag=wx.ALL, border=5)
 
         self.panel.SetSizer(self.sizer)
         self.sizer.Fit(self)
 
-        #TODO use when subgroup will be optional
-        #self.subg_panel.Show(False)
+        # TODO use when subgroup will be optional
+        # self.subg_panel.Show(False)
         #self.subg_chbox.Bind(wx.EVT_CHECKBOX, self.OnSubgChbox)
 
     def OnSubgChbox(self, event):
@@ -115,10 +126,10 @@
 
         if self.use_subg:
             self.subg_panel.Show()
-            #self.SubGroupSelected()
+            # self.SubGroupSelected()
         else:
             self.subg_panel.Hide()
-            #self.GroupSelected()
+            # self.GroupSelected()
         self.SetMinSize(self.GetBestSize())
         self.Layout()
 
@@ -131,7 +142,7 @@
             ret = (self.groupSelect.GetValue(), None)
 
         return ret
-        
+
     def OnEditGroup(self, event):
         """Launch edit group dialog"""
         g, s = self.GetData()
@@ -155,36 +166,38 @@
 
     def GetGroupBandsErr(self, parent):
         """Get list of raster bands which are in the soubgroup of group with both having same name.
-           If the group does not exists or it does not contain any bands in subgoup with same name, 
+           If the group does not exists or it does not contain any bands in subgoup with same name,
            error dialog is shown.
         """
         gr, s = self.GetData()
 
         group = grass.find_file(name=gr, element='group')
-    
+
         bands = []
         g = group['name']
-    
+
         if g:
             if self.use_subg:
                 if s == '':
                     GError(_("Please choose a subgroup."), parent=parent)
                     return bands
                 if s not in self.GetSubgroups(g):
-                    GError(_("Subgroup <%s> not found in group <%s>") % (s, g), parent=parent)
+                    GError(
+                        _("Subgroup <%s> not found in group <%s>") %
+                        (s, g), parent=parent)
                     return bands
 
             bands = self.GetGroupBands(g, s)
             if not bands:
                 if self.use_subg:
-                    GError(_("No data found in subgroup <%s> of group <%s>.\n" \
-                             ".") \
-                               % (s, g), parent=parent)
-        
+                    GError(_("No data found in subgroup <%s> of group <%s>.\n"
+                             ".")
+                           % (s, g), parent=parent)
+
                 else:
-                    GError(_("No data found in group <%s>.\n" \
-                             ".") \
-                               % g, parent=parent)
+                    GError(_("No data found in group <%s>.\n"
+                             ".")
+                           % g, parent=parent)
         else:
             GError(_("Group <%s> not found") % gr, parent=parent)
 
@@ -200,33 +213,38 @@
         res = RunCommand('i.group',
                          flags='g',
                          group=group,
-                         read = True, **kwargs).strip()
+                         read=True, **kwargs).strip()
         bands = None
         if res.split('\n')[0]:
             bands = res.split('\n')
-            
+
         return bands
 
     def GetSubgroups(self, group):
         return RunCommand('i.group', group=group,
-                           read=True, flags='sg').splitlines()
+                          read=True, flags='sg').splitlines()
 
+
 class IClassMapDialog(SimpleDialog):
     """Dialog for adding raster/vector map"""
+
     def __init__(self, parent, title, element):
         """
-        
+
         :param parent: gui parent
         :param title: dialog title
         :param element: element type ('raster', 'vector')
         """
-        
-        SimpleDialog.__init__(self, parent, title = title)
-        
+
+        SimpleDialog.__init__(self, parent, title=title)
+
         self.elementType = element
-        self.element = gselect.Select(parent = self.panel, type = element,
-                                      size = globalvar.DIALOG_GSELECT_SIZE,
-                                      validator = SimpleValidator(callback = self.ValidatorCallback))
+        self.element = gselect.Select(
+            parent=self.panel,
+            type=element,
+            size=globalvar.DIALOG_GSELECT_SIZE,
+            validator=SimpleValidator(
+                callback=self.ValidatorCallback))
         self.element.SetFocus()
 
         self.warning = _("Name of map is missing.")
@@ -239,12 +257,12 @@
             label = _("Name of raster map:")
         elif self.elementType == 'vector':
             label = _("Name of vector map:")
-        self.dataSizer.Add(wx.StaticText(self.panel, id = wx.ID_ANY,
-                                         label = label),
-                           proportion = 0, flag = wx.EXPAND | wx.ALL, border = 5)
-        self.dataSizer.Add(self.element, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL, border = 5)
-        
+        self.dataSizer.Add(wx.StaticText(self.panel, id=wx.ID_ANY,
+                                         label=label),
+                           proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
+        self.dataSizer.Add(self.element, proportion=0,
+                           flag=wx.EXPAND | wx.ALL, border=5)
+
         self.panel.SetSizer(self.sizer)
         self.sizer.Fit(self)
 
@@ -255,52 +273,68 @@
 
 class IClassCategoryManagerDialog(wx.Dialog):
     """Dialog for managing categories (classes).
-    
+
     Alows adding, deleting class and changing its name and color.
     """
-    def __init__(self, parent, title = _("Class manager"), id = wx.ID_ANY):
+
+    def __init__(self, parent, title=_("Class manager"), id=wx.ID_ANY):
         """
         Does post init and layout.
-        
+
         :param parent: gui parent
         :param title: dialog window title
         :param id: wx id
         """
-        wx.Dialog.__init__(self, parent = parent, title = title, id = id)
-        
+        wx.Dialog.__init__(self, parent=parent, title=title, id=id)
+
         self.parent = parent
-        panel = wx.Panel(parent = self, id = wx.ID_ANY)
-        
+        panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
         mainSizer = wx.BoxSizer(wx.VERTICAL)
-        box = wx.StaticBox(panel, id = wx.ID_ANY,
-                           label = " %s " % _("Classes"))
+        box = wx.StaticBox(panel, id=wx.ID_ANY,
+                           label=" %s " % _("Classes"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
-        self.catList = CategoryListCtrl(panel, mapwindow = parent, 
-                                               stats_data = parent.stats_data)
-        addButton = wx.Button(panel, id = wx.ID_ADD)
-        deleteButton = wx.Button(panel, id = wx.ID_DELETE)
-        
-        gridSizer.Add(item = self.catList, pos = (0, 0), span = (3, 1), flag = wx.EXPAND)
-        gridSizer.Add(item = addButton, pos = (0, 1), flag = wx.EXPAND)
-        gridSizer.Add(item = deleteButton, pos = (1, 1), flag = wx.EXPAND)
-                
+        gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
+        self.catList = CategoryListCtrl(panel, mapwindow=parent,
+                                        stats_data=parent.stats_data)
+        addButton = wx.Button(panel, id=wx.ID_ADD)
+        deleteButton = wx.Button(panel, id=wx.ID_DELETE)
+
+        gridSizer.Add(
+            item=self.catList, pos=(
+                0, 0), span=(
+                3, 1), flag=wx.EXPAND)
+        gridSizer.Add(item=addButton, pos=(0, 1), flag=wx.EXPAND)
+        gridSizer.Add(item=deleteButton, pos=(1, 1), flag=wx.EXPAND)
+
         gridSizer.AddGrowableCol(0)
         gridSizer.AddGrowableRow(2)
-        sizer.Add(item = gridSizer, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
-        mainSizer.Add(item = sizer, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
-        
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        mainSizer.Add(
+            item=sizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+
         btnSizer = wx.BoxSizer(wx.HORIZONTAL)
-        closeButton = wx.Button(panel, id = wx.ID_CLOSE)
-        btnSizer.Add(item = wx.Size(-1, -1), proportion = 1, flag = wx.EXPAND)
-        btnSizer.Add(item = closeButton, proportion = 0, flag = wx.ALIGN_RIGHT)
-        mainSizer.Add(item = btnSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = 5)
-        
+        closeButton = wx.Button(panel, id=wx.ID_CLOSE)
+        btnSizer.Add(item=wx.Size(-1, -1), proportion=1, flag=wx.EXPAND)
+        btnSizer.Add(item=closeButton, proportion=0, flag=wx.ALIGN_RIGHT)
+        mainSizer.Add(
+            item=btnSizer,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+
         addButton.Bind(wx.EVT_BUTTON, self.OnAddCategory)
         deleteButton.Bind(wx.EVT_BUTTON, self.OnDeleteCategory)
         closeButton.Bind(wx.EVT_BUTTON, self.OnClose)
         self.Bind(wx.EVT_CLOSE, self.OnClose)
-        
+
         panel.SetSizer(mainSizer)
         mainSizer.Fit(self)
 
@@ -313,66 +347,70 @@
             cat = max(self.parent.stats_data.GetCategories()) + 1
         else:
             cat = 1
-        defaultName = 'class' + '_' + str(cat) # intentionally not translatable
+        # intentionally not translatable
+        defaultName = 'class' + '_' + str(cat)
         defaultColor = '0:0:0'
-        self.catList.AddCategory(cat = cat, name = defaultName, color = defaultColor)
-        
+        self.catList.AddCategory(cat=cat, name=defaultName, color=defaultColor)
+
     def OnDeleteCategory(self, event):
         self.catList.DeleteCategory()
-        
+
     def OnClose(self, event):
         self.catList.DeselectAll()
-        
+
         self.Hide()
-        #if not isinstance(event, wx.CloseEvent):
-            #self.Destroy()
-            
-        #event.Skip()
-        
+        # if not isinstance(event, wx.CloseEvent):
+        # self.Destroy()
+
+        # event.Skip()
+
     def GetListCtrl(self):
         """Returns list widget"""
         return self.catList
-        
+
+
 class CategoryListCtrl(wx.ListCtrl,
                        listmix.ListCtrlAutoWidthMixin,
                        listmix.TextEditMixin):
     """Widget for controling list of classes (categories).
-    
+
     CategoryListCtrl updates choice in mapwindow and removes raster map
     when deleting class (category).
     It uses virtual data in the terms of @c wx.ListCtrl.
-    
+
     .. todo::
         delete vector features after deleting class
     """
-    def __init__(self, parent, mapwindow, stats_data, id = wx.ID_ANY):
+
+    def __init__(self, parent, mapwindow, stats_data, id=wx.ID_ANY):
         """
         :param parent: gui parent
         :param mapwindow: mapwindow instance with iclass toolbar and remove raster method
         :param stats_data: StatisticsData instance (defined in statistics.py)
         :param id: wx id
         """
-        wx.ListCtrl.__init__(self, parent, id,
-                             style = wx.LC_REPORT|wx.LC_VIRTUAL|wx.LC_HRULES|wx.LC_VRULES)
+        wx.ListCtrl.__init__(
+            self, parent, id, style=wx.LC_REPORT | wx.LC_VIRTUAL | wx.LC_HRULES |
+            wx.LC_VRULES)
         self.columns = ((_('Class name'), 'name'),
                         (_('Color'), 'color'))
-        self.Populate(columns = self.columns)
+        self.Populate(columns=self.columns)
         self.mapWindow = mapwindow
         self.stats_data = stats_data
         self.SetItemCount(len(self.stats_data.GetCategories()))
-        
+
         self.rightClickedItemIdx = wx.NOT_FOUND
-        
+
         listmix.ListCtrlAutoWidthMixin.__init__(self)
 
         listmix.TextEditMixin.__init__(self)
-        
+
         self.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT, self.OnEdit)
         self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnCategorySelected)
-        
-        self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnClassRightUp) #wxMSW
-        self.Bind(wx.EVT_RIGHT_UP,            self.OnClassRightUp) #wxGTK
-    
+
+        self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnClassRightUp)  # wxMSW
+        self.Bind(wx.EVT_RIGHT_UP, self.OnClassRightUp)  # wxGTK
+
         self.stats_data.statisticsAdded.connect(self.Update)
         self.stats_data.statisticsDeleted.connect(self.Update)
         self.stats_data.allStatisticsDeleted.connect(self.Update)
@@ -387,38 +425,40 @@
             try:
                 text.encode('ascii')
             except UnicodeEncodeError:
-                GMessage(parent = self, message = _("Please use only ASCII characters."))
+                GMessage(parent=self, message=_(
+                    "Please use only ASCII characters."))
                 return
 
         cat = self.stats_data.GetCategories()[row]
-        self.stats_data.GetStatistics(cat).SetStatistics(stats = {attr : text})
-        
+        self.stats_data.GetStatistics(cat).SetStatistics(stats={attr: text})
+
         toolbar = self.mapWindow.toolbars['iClass']
         toolbar.choice.SetSelection(row)
         self.Select(row)
-        
+
         if attr == 'name':
-            self.mapWindow.UpdateRasterName(text, toolbar.GetSelectedCategoryIdx())
-            
-        self.mapWindow.UpdateChangeState(changes = True)
-        
+            self.mapWindow.UpdateRasterName(
+                text, toolbar.GetSelectedCategoryIdx())
+
+        self.mapWindow.UpdateChangeState(changes=True)
+
     def Populate(self, columns):
         for i, col in enumerate(columns):
-            self.InsertColumn(i, col[0])#wx.LIST_FORMAT_RIGHT
+            self.InsertColumn(i, col[0])  # wx.LIST_FORMAT_RIGHT
 
         self.SetColumnWidth(0, 100)
         self.SetColumnWidth(1, 100)
-        
+
     def AddCategory(self, cat, name, color):
         """Add category record (used when importing areas)"""
 
         self.stats_data.AddStatistics(cat, name, color)
         self.SetItemCount(len(self.stats_data.GetCategories()))
-        
-        self.mapWindow.UpdateChangeState(changes = True)
-                
+
+        self.mapWindow.UpdateChangeState(changes=True)
+
     def DeleteCategory(self):
-        indexList = sorted(self.GetSelectedIndices(), reverse = True)
+        indexList = sorted(self.GetSelectedIndices(), reverse=True)
         del_cats = []
         cats = self.stats_data.GetCategories()
 
@@ -429,17 +469,17 @@
 
             name = stat.rasterName
             self.mapWindow.RemoveTempRaster(name)
-            
+
             del_cats.append(cat)
             self.stats_data.DeleteStatistics(cat)
-            
+
         self.SetItemCount(len(self.stats_data.GetCategories()))
-        
-        self.mapWindow.UpdateChangeState(changes = True)
-        
-        self.mapWindow.DeleteAreas(cats = del_cats)
-            
-    def GetSelectedIndices(self, state =  wx.LIST_STATE_SELECTED):
+
+        self.mapWindow.UpdateChangeState(changes=True)
+
+        self.mapWindow.DeleteAreas(cats=del_cats)
+
+    def GetSelectedIndices(self, state=wx.LIST_STATE_SELECTED):
         indices = []
         lastFound = -1
         while True:
@@ -450,7 +490,7 @@
                 lastFound = index
                 indices.append(index)
         return indices
-        
+
     def OnEdit(self, event):
         currentItem = event.m_itemIndex
         currentCol = event.m_col
@@ -458,7 +498,7 @@
             col = self.OnGetItemText(currentItem, currentCol)
             col = map(int, col.split(':'))
 
-            col_data =  wx.ColourData()
+            col_data = wx.ColourData()
             col_data.SetColour(wx.Colour(*col))
 
             dlg = wx.ColourDialog(self, col_data)
@@ -470,9 +510,9 @@
                 self.SetVirtualData(currentItem, currentCol, color)
             dlg.Destroy()
             wx.CallAfter(self.SetFocus)
-        
+
         event.Skip()
-        
+
     def OnCategorySelected(self, event):
         """Highlight selected areas"""
         indexList = self.GetSelectedIndices()
@@ -480,46 +520,51 @@
         cats = self.stats_data.GetCategories()
         for i in indexList:
             sel_cats.append(cats[i])
-        
+
         self.mapWindow.HighlightCategory(sel_cats)
         if event:
             event.Skip()
-        
+
     def OnClassRightUp(self, event):
         """Show context menu on right click"""
         item, flags = self.HitTest((event.GetX(), event.GetY()))
         if item != wx.NOT_FOUND and flags & wx.LIST_HITTEST_ONITEM:
             self.rightClickedItemIdx = item
-           
+
         if not hasattr(self, "popupZoomtoAreas"):
             self.popupZoomtoAreas = wx.NewId()
-            self.Bind(wx.EVT_MENU, self.OnZoomToAreasByCat, id = self.popupZoomtoAreas)
+            self.Bind(
+                wx.EVT_MENU,
+                self.OnZoomToAreasByCat,
+                id=self.popupZoomtoAreas)
 
         # generate popup-menu
         menu = wx.Menu()
-        menu.Append(self.popupZoomtoAreas, _("Zoom to training areas of selected class"))
-        
+        menu.Append(
+            self.popupZoomtoAreas,
+            _("Zoom to training areas of selected class"))
+
         self.PopupMenu(menu)
         menu.Destroy()
-    
+
     def OnZoomToAreasByCat(self, event):
         """Zoom to areas of given category"""
         cat = self.stats_data.GetCategories()[self.rightClickedItemIdx]
         self.mapWindow.ZoomToAreasByCat(cat)
-        
+
     def DeselectAll(self):
         """Deselect all items"""
         indexList = self.GetSelectedIndices()
         for i in indexList:
-            self.Select(i, on = 0)
-         
+            self.Select(i, on=0)
+
         # no highlight
         self.OnCategorySelected(None)
-        
+
     def OnGetItemText(self, item, col):
         cat = self.stats_data.GetCategories()[item]
         stat = self.stats_data.GetStatistics(cat)
-        return getattr(stat, self.columns[col][1]) 
+        return getattr(stat, self.columns[col][1])
 
     def OnGetItemImage(self, item):
         return -1
@@ -532,65 +577,70 @@
         back_c = wx.Colour(*map(int, self.OnGetItemText(item, 1).split(':')))
         text_c = wx.Colour(*ContrastColor(back_c))
 
-        # if it is in scope of the method, gui falls, using self solved it 
-        self.l = wx.ListItemAttr(colText = text_c, colBack =  back_c)
+        # if it is in scope of the method, gui falls, using self solved it
+        self.l = wx.ListItemAttr(colText=text_c, colBack=back_c)
         return self.l
-    
+
+
 def ContrastColor(color):
-    """Decides which value shoud have text to be contrast with backgroud color 
+    """Decides which value shoud have text to be contrast with backgroud color
         (bright bg -> black, dark bg -> white)
 
     .. todo::
-        could be useful by other apps, consider moving it into gui_core 
+        could be useful by other apps, consider moving it into gui_core
     """
-    #gacek, http://stackoverflow.com/questions/1855884/determine-font-color-based-on-background-color
-    a = 1 - ( 0.299 * color[0] + 0.587 * color[1] + 0.114 * color[2])/255;
+    # gacek,
+    # http://stackoverflow.com/questions/1855884/determine-font-color-based-on-background-color
+    a = 1 - (0.299 * color[0] + 0.587 * color[1] + 0.114 * color[2]) / 255
 
     if a < 0.5:
         d = 0
     else:
-        d = 255 
-    # maybe return just bool if text shoud be dark or bright 
+        d = 255
+    # maybe return just bool if text shoud be dark or bright
     return (d, d, d)
 
+
 class IClassSignatureFileDialog(wx.Dialog):
-    def __init__(self, parent, group, subgroup, 
-                 file = None, title = _("Save signature file"), id = wx.ID_ANY,
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
+
+    def __init__(self, parent, group, subgroup,
+                 file=None, title=_("Save signature file"), id=wx.ID_ANY,
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
                  **kwargs):
         """Dialog for saving signature file
-        
+
         :param parent: window
         :param group: group name
         :param file: signature file name
         :param title: window title
         """
-        wx.Dialog.__init__(self, parent, id, title, style = style, **kwargs)
-        
+        wx.Dialog.__init__(self, parent, id, title, style=style, **kwargs)
+
         self.fileName = file
-        
+
         env = grass.gisenv()
-        
+
         # inconsistent group and subgroup name
-        # path: grassdata/nc_spm_08/landsat/group/test_group/subgroup/test_group/sig/sigFile
+        # path:
+        # grassdata/nc_spm_08/landsat/group/test_group/subgroup/test_group/sig/sigFile
         self.baseFilePath = os.path.join(env['GISDBASE'],
                                          env['LOCATION_NAME'],
                                          env['MAPSET'],
                                          'group', group,
                                          'subgroup', subgroup,
                                          'sig')
-        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
-        
-        self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
-        self.btnOK     = wx.Button(parent = self.panel, id = wx.ID_OK)
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
+        self.btnCancel = wx.Button(parent=self.panel, id=wx.ID_CANCEL)
+        self.btnOK = wx.Button(parent=self.panel, id=wx.ID_OK)
         self.btnOK.SetDefault()
         self.btnOK.Enable(False)
-        
+
         self.__layout()
-        
+
         self.fileNameCtrl.Bind(wx.EVT_TEXT, self.OnTextChanged)
         self.OnTextChanged(None)
-        
+
     def OnTextChanged(self, event):
         """Name for signature file given"""
         file = self.fileNameCtrl.GetValue()
@@ -598,100 +648,114 @@
             self.btnOK.Enable(True)
         else:
             self.btnOK.Enable(False)
-            
+
         path = os.path.join(self.baseFilePath, file)
         self.filePathText.SetLabel(path)
-        bestSize = self.pathPanel.GetBestVirtualSize() 
+        bestSize = self.pathPanel.GetBestVirtualSize()
         self.pathPanel.SetVirtualSize(bestSize)
         self.pathPanel.Scroll(*bestSize)
-        
+
     def __layout(self):
         """Do layout"""
         sizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         dataSizer = wx.BoxSizer(wx.VERTICAL)
-        
-        dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                           label = _("Enter name of signature file:")),
-                      proportion = 0, flag = wx.ALL, border = 3)
-        self.fileNameCtrl = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY, size = (400, -1))
+
+        dataSizer.Add(
+            item=wx.StaticText(
+                parent=self.panel,
+                id=wx.ID_ANY,
+                label=_("Enter name of signature file:")),
+            proportion=0,
+            flag=wx.ALL,
+            border=3)
+        self.fileNameCtrl = wx.TextCtrl(
+            parent=self.panel, id=wx.ID_ANY, size=(400, -1))
         if self.fileName:
             self.fileNameCtrl.SetValue(self.fileName)
-        dataSizer.Add(item = self.fileNameCtrl,
-                      proportion = 0, flag = wx.ALL | wx.EXPAND, border = 3)
-    
-        dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                                label = _("Signature file path:")),
-                           proportion = 0, flag = wx.ALL, border = 3)
-        
-        self.pathPanel = scrolled.ScrolledPanel(self.panel, size = (-1, 40))
+        dataSizer.Add(item=self.fileNameCtrl,
+                      proportion=0, flag=wx.ALL | wx.EXPAND, border=3)
+
+        dataSizer.Add(item=wx.StaticText(parent=self.panel, id=wx.ID_ANY,
+                                         label=_("Signature file path:")),
+                      proportion=0, flag=wx.ALL, border=3)
+
+        self.pathPanel = scrolled.ScrolledPanel(self.panel, size=(-1, 40))
         pathSizer = wx.BoxSizer()
-        self.filePathText = wx.StaticText(parent = self.pathPanel, id = wx.ID_ANY,
-                                                label = self.baseFilePath)
-        pathSizer.Add(self.filePathText, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
-        self.pathPanel.SetupScrolling(scroll_x = True, scroll_y = False)
+        self.filePathText = wx.StaticText(parent=self.pathPanel, id=wx.ID_ANY,
+                                          label=self.baseFilePath)
+        pathSizer.Add(
+            self.filePathText,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=1)
+        self.pathPanel.SetupScrolling(scroll_x=True, scroll_y=False)
         self.pathPanel.SetSizer(pathSizer)
 
-        dataSizer.Add(item = self.pathPanel,
-                      proportion = 0, flag = wx.ALL | wx.EXPAND, border = 3)
-                      
+        dataSizer.Add(item=self.pathPanel,
+                      proportion=0, flag=wx.ALL | wx.EXPAND, border=3)
+
         # buttons
         btnSizer = wx.StdDialogButtonSizer()
         btnSizer.AddButton(self.btnCancel)
         btnSizer.AddButton(self.btnOK)
         btnSizer.Realize()
-        
-        sizer.Add(item = dataSizer, proportion = 1,
-                       flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
-        
-        sizer.Add(item = btnSizer, proportion = 0,
-                       flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
-        
+
+        sizer.Add(item=dataSizer, proportion=1,
+                  flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
+
+        sizer.Add(item=btnSizer, proportion=0,
+                  flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
+
         self.panel.SetSizer(sizer)
         sizer.Fit(self)
-        
+
         self.SetMinSize(self.GetSize())
-        
-    def GetFileName(self, fullPath = False):
+
+    def GetFileName(self, fullPath=False):
         """Returns signature file name
-        
+
         :param fullPath: return full path of sig. file
         """
         if fullPath:
-            return os.path.join(self.baseFilePath, self.fileNameCtrl.GetValue())
-            
+            return os.path.join(self.baseFilePath,
+                                self.fileNameCtrl.GetValue())
+
         return self.fileNameCtrl.GetValue()
-        
+
+
 class IClassExportAreasDialog(wx.Dialog):
-    def __init__(self, parent, vectorName = None, title = _("Export training areas"), id = wx.ID_ANY,
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
+
+    def __init__(self, parent, vectorName=None,
+                 title=_("Export training areas"),
+                 id=wx.ID_ANY, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
                  **kwargs):
         """Dialog for export of training areas to vector layer
-        
+
         :param parent: window
         :param vectorName: name of vector layer for export
         :param title: window title
         """
-        wx.Dialog.__init__(self, parent, id, title, style = style, **kwargs)
-        
+        wx.Dialog.__init__(self, parent, id, title, style=style, **kwargs)
+
         self.vectorName = vectorName
-        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
-        
-        self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
-        self.btnOK     = wx.Button(parent = self.panel, id = wx.ID_OK)
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
+        self.btnCancel = wx.Button(parent=self.panel, id=wx.ID_CANCEL)
+        self.btnOK = wx.Button(parent=self.panel, id=wx.ID_OK)
         self.btnOK.SetDefault()
         self.btnOK.Enable(False)
         self.btnOK.Bind(wx.EVT_BUTTON, self.OnOK)
-        
+
         self.__layout()
-        
+
         self.vectorNameCtrl.Bind(wx.EVT_TEXT, self.OnTextChanged)
         self.OnTextChanged(None)
         wx.CallAfter(self.vectorNameCtrl.SetFocus)
 
     def OnTextChanged(self, event):
         """Name of new vector map given.
-        
+
         Enable/diable OK button.
         """
         file = self.vectorNameCtrl.GetValue()
@@ -699,71 +763,79 @@
             self.btnOK.Enable(True)
         else:
             self.btnOK.Enable(False)
-        
+
     def __layout(self):
         """Do layout"""
         sizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         dataSizer = wx.BoxSizer(wx.VERTICAL)
-        
-        dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                           label = _("Enter name of new vector map:")),
-                      proportion = 0, flag = wx.ALL, border = 3)
-        self.vectorNameCtrl = gselect.Select(parent = self.panel, type = 'vector',
-                                             mapsets = [grass.gisenv()['MAPSET']],
-                                             size = globalvar.DIALOG_GSELECT_SIZE)
+
+        dataSizer.Add(
+            item=wx.StaticText(
+                parent=self.panel,
+                id=wx.ID_ANY,
+                label=_("Enter name of new vector map:")),
+            proportion=0,
+            flag=wx.ALL,
+            border=3)
+        self.vectorNameCtrl = gselect.Select(
+            parent=self.panel, type='vector',
+            mapsets=[grass.gisenv()['MAPSET']],
+            size=globalvar.DIALOG_GSELECT_SIZE)
         if self.vectorName:
             self.vectorNameCtrl.SetValue(self.vectorName)
-        dataSizer.Add(item = self.vectorNameCtrl,
-                      proportion = 0, flag = wx.ALL | wx.EXPAND, border = 3)
-        self.withTableCtrl = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
-                                       label = _("Export attribute table"))
+        dataSizer.Add(item=self.vectorNameCtrl,
+                      proportion=0, flag=wx.ALL | wx.EXPAND, border=3)
+        self.withTableCtrl = wx.CheckBox(parent=self.panel, id=wx.ID_ANY,
+                                         label=_("Export attribute table"))
         self.withTableCtrl.SetValue(True)
-        self.withTableCtrl.SetToolTipString(_("Export attribute table containing" 
-                                              " computed statistical data"))
-        
-        dataSizer.Add(item = self.withTableCtrl,
-                      proportion = 0, flag = wx.ALL, border = 3)
-                      
+        self.withTableCtrl.SetToolTipString(
+            _("Export attribute table containing" " computed statistical data"))
+
+        dataSizer.Add(item=self.withTableCtrl,
+                      proportion=0, flag=wx.ALL, border=3)
+
         # buttons
         btnSizer = wx.StdDialogButtonSizer()
         btnSizer.AddButton(self.btnCancel)
         btnSizer.AddButton(self.btnOK)
         btnSizer.Realize()
-        
-        sizer.Add(item = dataSizer, proportion = 1,
-                       flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
-        
-        sizer.Add(item = btnSizer, proportion = 0,
-                       flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
-        
+
+        sizer.Add(item=dataSizer, proportion=1,
+                  flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
+
+        sizer.Add(item=btnSizer, proportion=0,
+                  flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
+
         self.panel.SetSizer(sizer)
         sizer.Fit(self)
-        
+
         self.SetMinSize(self.GetSize())
-        
+
     def GetVectorName(self):
         """Returns vector name"""
         return self.vectorNameCtrl.GetValue()
-        
+
     def WithTable(self):
         """Returns true if attribute table should be exported too"""
         return self.withTableCtrl.IsChecked()
-        
+
     def OnOK(self, event):
         """Checks if map exists and can be overwritten."""
-        overwrite = UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled')
+        overwrite = UserSettings.Get(
+            group='cmd', key='overwrite', subkey='enabled')
         vName = self.GetVectorName()
-        res = grass.find_file(vName, element = 'vector')
+        res = grass.find_file(vName, element='vector')
         if res['fullname'] and overwrite is False:
-            qdlg = wx.MessageDialog(parent = self,
-                                        message = _("Vector map <%s> already exists."
-                                                    " Do you want to overwrite it?" % vName) ,
-                                        caption = _("Vector <%s> exists" % vName),
-                                        style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
+            qdlg = wx.MessageDialog(
+                parent=self, message=_(
+                    "Vector map <%s> already exists."
+                    " Do you want to overwrite it?" %
+                    vName), caption=_(
+                    "Vector <%s> exists" %
+                    vName), style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
             if qdlg.ShowModal() == wx.ID_YES:
                 event.Skip()
             qdlg.Destroy()
         else:
             event.Skip()
-            

Modified: grass/trunk/gui/wxpython/iclass/digit.py
===================================================================
--- grass/trunk/gui/wxpython/iclass/digit.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/iclass/digit.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -19,26 +19,28 @@
 import wx
 
 from vdigit.mapwindow import VDigitWindow
-from vdigit.wxdigit   import IVDigit
+from vdigit.wxdigit import IVDigit
 from vdigit.wxdisplay import DisplayDriver, TYPE_AREA
-from core.gcmd        import GWarning
+from core.gcmd import GWarning
 from core.utils import _
 try:
-    from grass.lib.gis    import G_verbose, G_set_verbose
+    from grass.lib.gis import G_verbose, G_set_verbose
     from grass.lib.vector import *
-    from grass.lib.vedit  import *
+    from grass.lib.vedit import *
 except ImportError:
     pass
 
 import grass.script as grass
 
+
 class IClassVDigitWindow(VDigitWindow):
     """Class similar to VDigitWindow but specialized for wxIClass."""
+
     def __init__(self, parent, giface, map, properties):
         """
-        
+
         @a parent should has toolbar providing current class (category).
-        
+
         :param parent: gui parent
         :param map: map renderer instance
         """
@@ -52,45 +54,49 @@
 
         region = grass.region()
         e, n = self.Pixel2Cell(event.GetPositionTuple())
-        if not ((region['s'] <= n <= region['n']) and (region['w'] <= e <= region['e'])):
-            GWarning(parent = self.parent, 
-                     message = _("You are trying to create a training area "
-                                 "outside the computational region. "
-                                 "Please, use g.region to set the appropriate region first."))
+        if not((region['s'] <= n <= region['n'])
+               and(region['w'] <= e <= region['e'])):
+            GWarning(
+                parent=self.parent, message=_(
+                    "You are trying to create a training area "
+                    "outside the computational region. "
+                    "Please, use g.region to set the appropriate region first."))
             return
 
         cat = self.GetCurrentCategory()
-        
+
         if cat is None and action == "addLine":
-            dlg = wx.MessageDialog(parent = self.parent,
-                      message = _("In order to create a training area, "
-                                  "you have to select class first.\n\n"
-                                  "There is no class yet, "
-                                  "do you want to create one?"),
-                      caption = _("No class selected"),
-                      style = wx.YES_NO)
+            dlg = wx.MessageDialog(
+                parent=self.parent,
+                message=_(
+                    "In order to create a training area, "
+                    "you have to select class first.\n\n"
+                    "There is no class yet, "
+                    "do you want to create one?"),
+                caption=_("No class selected"),
+                style=wx.YES_NO)
             if dlg.ShowModal() == wx.ID_YES:
                 self.parent.OnCategoryManager(None)
-                
+
             dlg.Destroy()
             event.Skip()
             return
-        
+
         super(IClassVDigitWindow, self)._onLeftDown(event)
-        
+
     def _addRecord(self):
         return False
-        
+
     def _updateATM(self):
         pass
-        
+
     def _onRightUp(self, event):
         super(IClassVDigitWindow, self)._onRightUp(event)
-        self.parent.UpdateChangeState(changes = True)
-        
+        self.parent.UpdateChangeState(changes=True)
+
     def GetCurrentCategory(self):
         """Returns current category (class).
-        
+
         Category should be assigned to new features (areas).
         It is taken from parent's toolbar.
         """
@@ -100,20 +106,22 @@
         """Get color associated with given category"""
         r, g, b = map(int, self.parent.GetClassColor(cat).split(':'))
         return wx.Colour(r, g, b)
-        
+
+
 class IClassVDigit(IVDigit):
     """Class similar to IVDigit but specialized for wxIClass."""
+
     def __init__(self, mapwindow):
-        IVDigit.__init__(self, mapwindow, driver = IClassDisplayDriver)
-        self._settings['closeBoundary'] = True # snap to the first node
-        
+        IVDigit.__init__(self, mapwindow, driver=IClassDisplayDriver)
+        self._settings['closeBoundary'] = True  # snap to the first node
+
     def _getNewFeaturesLayer(self):
         return 1
-        
+
     def _getNewFeaturesCat(self):
         cat = self.mapWindow.GetCurrentCategory()
         return cat
-        
+
     def DeleteAreasByCat(self, cats):
         """Delete areas (centroid+boundaries) by categories
 
@@ -121,12 +129,12 @@
         """
         for cat in cats:
             Vedit_delete_areas_cat(self.poMapInfo, 1, cat)
-       
-    def CopyMap(self, name, tmp = False):
+
+    def CopyMap(self, name, tmp=False):
         """Make a copy of open vector map
 
         Note: Attributes are not copied
-        
+
         :param name: name for a copy
         :param tmp: True for temporary map
 
@@ -136,9 +144,9 @@
         if not self.poMapInfo:
             # nothing to copy
             return -1
-        
+
         poMapInfoNew = pointer(Map_info())
-        
+
         if not tmp:
             open_fn = Vect_open_new
         else:
@@ -150,33 +158,42 @@
 
         verbose = G_verbose()
         G_set_verbose(-1)      # be silent
-        
+
         if Vect_copy_map_lines(self.poMapInfo, poMapInfoNew) == 1:
             G_set_verbose(verbose)
             return -1
-        
+
         Vect_build(poMapInfoNew)
         G_set_verbose(verbose)
-        
+
         ret = Vect_get_num_lines(poMapInfoNew)
         Vect_close(poMapInfoNew)
-        
+
         return ret
 
     def GetMapInfo(self):
         """Returns Map_info() struct of open vector map"""
         return self.poMapInfo
 
+
 class IClassDisplayDriver(DisplayDriver):
     """Class similar to DisplayDriver but specialized for wxIClass
 
     .. todo::
         needs refactoring (glog, gprogress)
     """
+
     def __init__(self, device, deviceTmp, mapObj, window, glog, gprogress):
-        DisplayDriver.__init__(self, device, deviceTmp, mapObj, window, glog, gprogress)
+        DisplayDriver.__init__(
+            self,
+            device,
+            deviceTmp,
+            mapObj,
+            window,
+            glog,
+            gprogress)
         self._cat = -1
-        
+
     def _drawObject(self, robj):
         """Draw given object to the device
 
@@ -185,9 +202,9 @@
         if robj.type == TYPE_AREA:
             self._cat = Vect_get_area_cat(self.poMapInfo, robj.fid, 1)
         elif robj.type == TYPE_CENTROIDIN:
-            return # skip centroids
+            return  # skip centroids
         DisplayDriver._drawObject(self, robj)
-        
+
     def _definePen(self, rtype):
         """Define pen/brush based on rendered object)
 
@@ -198,7 +215,7 @@
         pen, brush = DisplayDriver._definePen(self, rtype)
         if self._cat > 0 and rtype == TYPE_AREA:
             brush = wx.Brush(self.window.GetCategoryColor(self._cat), wx.SOLID)
-        
+
         return pen, brush
 
     def CloseMap(self):

Modified: grass/trunk/gui/wxpython/iclass/frame.py
===================================================================
--- grass/trunk/gui/wxpython/iclass/frame.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/iclass/frame.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -40,50 +40,55 @@
 
 import grass.script as grass
 
-from mapdisp            import statusbar as sb
+from mapdisp import statusbar as sb
 from mapwin.buffered import BufferedMapWindow
-from vdigit.toolbars    import VDigitToolbar
-from gui_core.mapdisp   import DoubleMapFrame
-from core.render        import Map, MapLayer
-from core.gcmd          import RunCommand, GMessage, GError, GWarning
-from gui_core.dialogs   import SetOpacityDialog
+from vdigit.toolbars import VDigitToolbar
+from gui_core.mapdisp import DoubleMapFrame
+from core.render import Map, MapLayer
+from core.gcmd import RunCommand, GMessage, GError, GWarning
+from gui_core.dialogs import SetOpacityDialog
 from mapwin.base import MapWindowProperties
-from dbmgr.vinfo        import VectorDBInfo
+from dbmgr.vinfo import VectorDBInfo
 import grass.script as grass
 
-from iclass.digit       import IClassVDigitWindow, IClassVDigit
+from iclass.digit import IClassVDigitWindow, IClassVDigit
 from iclass.toolbars    import IClassMapToolbar, IClassMiscToolbar,\
-                               IClassToolbar, IClassMapManagerToolbar
-from iclass.statistics  import StatisticsData, Statistics, BandStatistics
+    IClassToolbar, IClassMapManagerToolbar
+from iclass.statistics import StatisticsData, Statistics, BandStatistics
 from iclass.dialogs     import CategoryListCtrl, IClassCategoryManagerDialog,\
-                               IClassGroupDialog, IClassSignatureFileDialog,\
-                               IClassExportAreasDialog, IClassMapDialog
-from iclass.plots       import PlotPanel
+    IClassGroupDialog, IClassSignatureFileDialog,\
+    IClassExportAreasDialog, IClassMapDialog
+from iclass.plots import PlotPanel
 
 from grass.pydispatch.signal import Signal
 
+
 class IClassMapFrame(DoubleMapFrame):
     """wxIClass main frame
-    
+
     It has two map windows one for digitizing training areas and one for
     result preview.
     It generates histograms, raster maps and signature files using
     @c I_iclass_* functions from C imagery library.
-    
+
     It is wxGUI counterpart of old i.class module.
     """
-    def __init__(self, parent = None, giface = None, title = _("GRASS GIS Supervised Classification Tool"),
-                 toolbars = ["iClassMisc", "iClassMap", "vdigit", "iClass"],
-                 size = (875, 600), name = 'IClassWindow', **kwargs):
+
+    def __init__(
+            self, parent=None, giface=None,
+            title=_("GRASS GIS Supervised Classification Tool"),
+            toolbars=["iClassMisc", "iClassMap", "vdigit", "iClass"],
+            size=(875, 600),
+            name='IClassWindow', **kwargs):
         """
         :param parent: (no parent is expected)
         :param title: window title
         :param toolbars: dictionary of active toolbars (defalult value represents all toolbars)
         :param size: default size
         """
-        DoubleMapFrame.__init__(self, parent = parent, title = title,
-                                name = name,
-                                firstMap = Map(), secondMap = Map(),
+        DoubleMapFrame.__init__(self, parent=parent, title=title,
+                                name=name,
+                                firstMap=Map(), secondMap=Map(),
                                 **kwargs)
         self._giface = giface
         self.tree = None
@@ -92,20 +97,21 @@
         # show computation region by defaut
         self.mapWindowProperties.showRegion = True
 
-        self.firstMapWindow = IClassVDigitWindow(parent = self, giface = self._giface,
-                                                 properties=self.mapWindowProperties,
-                                                 map = self.firstMap)
-        self.secondMapWindow = BufferedMapWindow(parent=self, giface=self._giface,
-                                                 properties=self.mapWindowProperties,
-                                                 Map=self.secondMap)
-        self.MapWindow = self.firstMapWindow # current by default
-        
+        self.firstMapWindow = IClassVDigitWindow(
+            parent=self, giface=self._giface,
+            properties=self.mapWindowProperties, map=self.firstMap)
+        self.secondMapWindow = BufferedMapWindow(
+            parent=self, giface=self._giface,
+            properties=self.mapWindowProperties, Map=self.secondMap)
+        self.MapWindow = self.firstMapWindow  # current by default
+
         self._bindWindowsActivation()
         self._setUpMapWindow(self.firstMapWindow)
         self._setUpMapWindow(self.secondMapWindow)
         self.firstMapWindow.InitZoomHistory()
         self.secondMapWindow.InitZoomHistory()
-        # TODO: for vdigit: it does nothing here because areas do not produce this info
+        # TODO: for vdigit: it does nothing here because areas do not produce
+        # this info
         self.firstMapWindow.digitizingInfo.connect(
             lambda text:
             self.statusbarManager.statusbarItems['coordinates'].SetAdditionalInfo(text))
@@ -115,7 +121,7 @@
         self.SetSize(size)
 
         #
-        #Signals
+        # Signals
         #
 
         self.groupSet = Signal("IClassMapFrame.groupSet")
@@ -126,7 +132,7 @@
         #
         # Add toolbars
         #
-        
+
         toolbarsCopy = toolbars[:]
         if sys.platform == 'win32':
             self.AddToolbar(toolbarsCopy.pop(1))
@@ -136,13 +142,13 @@
         for toolb in toolbarsCopy:
             self.AddToolbar(toolb)
         self.firstMapWindow.SetToolbar(self.toolbars['vdigit'])
-        
+
         self.GetMapToolbar().GetActiveMapTool().Bind(wx.EVT_CHOICE, self.OnUpdateActive)
-        
+
         #
         # Add statusbar
         #
-        
+
         # items for choice
         self.statusbarItems = [sb.SbCoordinates,
                                sb.SbRegionExtent,
@@ -154,54 +160,65 @@
                                sb.SbMapScale,
                                sb.SbGoTo,
                                sb.SbProjection]
-        
+
         # create statusbar and its manager
-        statusbar = self.CreateStatusBar(number = 4, style = 0)
+        statusbar = self.CreateStatusBar(number=4, style=0)
         statusbar.SetStatusWidths([-5, -2, -1, -1])
-        self.statusbarManager = sb.SbManager(mapframe = self, statusbar = statusbar)
-        
+        self.statusbarManager = sb.SbManager(
+            mapframe=self, statusbar=statusbar)
+
         # fill statusbar manager
-        self.statusbarManager.AddStatusbarItemsByClass(self.statusbarItems, mapframe = self, statusbar = statusbar)
-        self.statusbarManager.AddStatusbarItem(sb.SbMask(self, statusbar = statusbar, position = 2))
-        self.statusbarManager.AddStatusbarItem(sb.SbRender(self, statusbar = statusbar, position = 3))
-        
+        self.statusbarManager.AddStatusbarItemsByClass(
+            self.statusbarItems, mapframe=self, statusbar=statusbar)
+        self.statusbarManager.AddStatusbarItem(
+            sb.SbMask(self, statusbar=statusbar, position=2))
+        self.statusbarManager.AddStatusbarItem(
+            sb.SbRender(self, statusbar=statusbar, position=3))
+
         self.statusbarManager.Update()
 
-        self.trainingMapManager = MapManager(self, mapWindow = self.GetFirstWindow(),
-                                             Map = self.GetFirstMap())
-        self.previewMapManager = MapManager(self, mapWindow = self.GetSecondWindow(),
-                                            Map = self.GetSecondMap())
-                                                   
+        self.trainingMapManager = MapManager(
+            self, mapWindow=self.GetFirstWindow(),
+            Map=self.GetFirstMap())
+        self.previewMapManager = MapManager(
+            self, mapWindow=self.GetSecondWindow(),
+            Map=self.GetSecondMap())
+
         self.changes = False
         self.exportVector = None
-        
+
         # dialogs
         self.dialogs = dict()
         self.dialogs['classManager'] = None
         self.dialogs['scatt_plot'] = None
         # just to make digitizer happy
         self.dialogs['attributes'] = None
-        self.dialogs['category']   = None
-        
+        self.dialogs['category'] = None
+
         # PyPlot init
-        self.plotPanel = PlotPanel(self, giface = self._giface, stats_data = self.stats_data)
-                                   
+        self.plotPanel = PlotPanel(
+            self,
+            giface=self._giface,
+            stats_data=self.stats_data)
+
         self._addPanes()
         self._mgr.Update()
-        
-        self.trainingMapManager.SetToolbar(self.toolbars['iClassTrainingMapManager'])
-        self.previewMapManager.SetToolbar(self.toolbars['iClassPreviewMapManager'])
-        
+
+        self.trainingMapManager.SetToolbar(
+            self.toolbars['iClassTrainingMapManager'])
+        self.previewMapManager.SetToolbar(
+            self.toolbars['iClassPreviewMapManager'])
+
         # default action
         self.GetMapToolbar().SelectDefault()
-        
+
         wx.CallAfter(self.AddTrainingAreaMap)
-        
+
         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
         self.Bind(wx.EVT_SIZE, self.OnSize)
 
         self.SendSizeEvent()
-        
+
     def OnCloseWindow(self, event):
         self.GetFirstWindow().GetDigit().CloseMap()
         self.plotPanel.CloseWindow()
@@ -215,81 +232,81 @@
         I_free_group_ref(self.refer)
         for st in self.cStatisticsDict.values():
             I_iclass_free_statistics(st)
-            
+
         self.RemoveTempVector()
         for i in self.stats_data.GetCategories():
             self.RemoveTempRaster(self.stats_data.GetStatistics(i).rasterName)
-            
+
     def OnHelp(self, event):
         """Show help page"""
-        self._giface.Help(entry = 'wxGUI.iclass')
-        
+        self._giface.Help(entry='wxGUI.iclass')
+
     def _getTempVectorName(self):
         """Return new name for temporary vector map (training areas)"""
-        vectorPath = grass.tempfile(create = False)
-        
-        return 'trAreas' + os.path.basename(vectorPath).replace('.','')
+        vectorPath = grass.tempfile(create=False)
 
+        return 'trAreas' + os.path.basename(vectorPath).replace('.', '')
+
     def SetGroup(self, group, subgroup):
         """Set group and subgroup manually"""
-        self.g = {'group' : group, 'subgroup' : subgroup}
+        self.g = {'group': group, 'subgroup': subgroup}
 
     def CreateTempVector(self):
         """Create temporary vector map for training areas"""
         vectorName = self._getTempVectorName()
-        
+
         env = os.environ.copy()
-        env['GRASS_VECTOR_TEMPORARY'] = '1' # create temporary map
+        env['GRASS_VECTOR_TEMPORARY'] = '1'  # create temporary map
         cmd = ('v.edit', {'tool': 'create',
                           'map': vectorName})
-        
-        ret = RunCommand(prog = cmd[0],
-                         parent = self, env = env,
+
+        ret = RunCommand(prog=cmd[0],
+                         parent=self, env=env,
                          **cmd[1])
-        
+
         if ret != 0:
             return False
-        
+
         return vectorName
-    
+
     def RemoveTempVector(self):
         """Removes temporary vector map with training areas"""
-        ret = RunCommand(prog = 'g.remove',
-                         parent = self,
-                         flags = 'f',
-                         type = 'vector',
-                         name = self.trainingAreaVector)
+        ret = RunCommand(prog='g.remove',
+                         parent=self,
+                         flags='f',
+                         type='vector',
+                         name=self.trainingAreaVector)
         if ret != 0:
             return False
         return True
-        
+
     def RemoveTempRaster(self, raster):
         """Removes temporary raster maps"""
         self.GetFirstMap().Clean()
         self.GetSecondMap().Clean()
-        ret = RunCommand(prog = 'g.remove',
-                         parent = self,
-                         flags = 'f',
-                         type = 'raster',
-                         name = raster)
+        ret = RunCommand(prog='g.remove',
+                         parent=self,
+                         flags='f',
+                         type='raster',
+                         name=raster)
         if ret != 0:
             return False
         return True
 
     def AddToolbar(self, name):
         """Add defined toolbar to the window
-        
+
         Currently known toolbars are:
          - 'iClassMap'          - basic map toolbar
          - 'iClass'             - iclass tools
          - 'iClassMisc'         - miscellaneous (help)
          - 'vdigit'             - digitizer toolbar (areas)
-         
+
          Toolbars 'iClassPreviewMapManager' are added in _addPanes().
         """
         if name == "iClassMap":
             self.toolbars[name] = IClassMapToolbar(self, self._toolSwitcher)
-            
+
             self._mgr.AddPane(self.toolbars[name],
                               wx.aui.AuiPaneInfo().
                               Name(name).Caption(_("Map Toolbar")).
@@ -298,10 +315,11 @@
                               BottomDockable(False).TopDockable(True).
                               CloseButton(False).Layer(2).Row(1).
                               BestSize((self.toolbars[name].GetBestSize())))
-                              
+
         if name == "iClass":
-            self.toolbars[name] = IClassToolbar(self, stats_data=self.stats_data)
-            
+            self.toolbars[name] = IClassToolbar(
+                self, stats_data=self.stats_data)
+
             self._mgr.AddPane(self.toolbars[name],
                               wx.aui.AuiPaneInfo().
                               Name(name).Caption(_("IClass Toolbar")).
@@ -310,10 +328,10 @@
                               BottomDockable(False).TopDockable(True).
                               CloseButton(False).Layer(2).Row(2).
                               BestSize((self.toolbars[name].GetBestSize())))
-                              
+
         if name == "iClassMisc":
             self.toolbars[name] = IClassMiscToolbar(self)
-            
+
             self._mgr.AddPane(self.toolbars[name],
                               wx.aui.AuiPaneInfo().
                               Name(name).Caption(_("IClass Misc Toolbar")).
@@ -324,13 +342,23 @@
                               BestSize((self.toolbars[name].GetBestSize())))
 
         if name == "vdigit":
-            self.toolbars[name] = VDigitToolbar(parent=self, toolSwitcher=self._toolSwitcher,
-                                                MapWindow=self.GetFirstWindow(),
-                                                digitClass=IClassVDigit, giface=self._giface,
-                                                tools = ['addArea', 'moveVertex', 'addVertex',
-                                                         'removeVertex', 'editLine', 'moveLine',
-                                                         'deleteArea',
-                                                         'undo', 'redo', 'settings'])
+            self.toolbars[name] = VDigitToolbar(
+                parent=self,
+                toolSwitcher=self._toolSwitcher,
+                MapWindow=self.GetFirstWindow(),
+                digitClass=IClassVDigit,
+                giface=self._giface,
+                tools=[
+                    'addArea',
+                    'moveVertex',
+                    'addVertex',
+                    'removeVertex',
+                    'editLine',
+                    'moveLine',
+                    'deleteArea',
+                    'undo',
+                    'redo',
+                    'settings'])
             self._mgr.AddPane(self.toolbars[name],
                               wx.aui.AuiPaneInfo().
                               Name(name).Caption(_("Digitization Toolbar")).
@@ -339,41 +367,41 @@
                               BottomDockable(False).TopDockable(True).
                               CloseButton(False).Layer(2).Row(2).
                               BestSize((self.toolbars[name].GetBestSize())))
-                              
+
     def _addPanes(self):
         """Add mapwindows and toolbars to aui manager"""
         if sys.platform == 'win32':
-            self._addPaneMapWindow(name = 'training')
-            self._addPaneToolbar(name = 'iClassTrainingMapManager')
-            self._addPaneMapWindow(name = 'preview')
-            self._addPaneToolbar(name = 'iClassPreviewMapManager')
+            self._addPaneMapWindow(name='training')
+            self._addPaneToolbar(name='iClassTrainingMapManager')
+            self._addPaneMapWindow(name='preview')
+            self._addPaneToolbar(name='iClassPreviewMapManager')
         else:
-            self._addPaneToolbar(name = 'iClassPreviewMapManager')
-            self._addPaneMapWindow(name = 'preview')
-            self._addPaneToolbar(name = 'iClassTrainingMapManager')
-            self._addPaneMapWindow(name = 'training')
+            self._addPaneToolbar(name='iClassPreviewMapManager')
+            self._addPaneMapWindow(name='preview')
+            self._addPaneToolbar(name='iClassTrainingMapManager')
+            self._addPaneMapWindow(name='training')
 
         # otherwise best size was ignored
-        self._mgr.SetDockSizeConstraint(0.5, 0.5) 
+        self._mgr.SetDockSizeConstraint(0.5, 0.5)
 
         self._mgr.AddPane(self.plotPanel, wx.aui.AuiPaneInfo().
-                  Name("plots").Caption(_("Plots")).
-                  Dockable(False).Floatable(False).CloseButton(False).
-                  Left().Layer(1).BestSize((335, -1)))
-        
+                          Name("plots").Caption(_("Plots")).
+                          Dockable(False).Floatable(False).CloseButton(False).
+                          Left().Layer(1).BestSize((335, -1)))
+
     def _addPaneToolbar(self, name):
         if name == 'iClassPreviewMapManager':
             parent = self.previewMapManager
         else:
             parent = self.trainingMapManager
-        
+
         self.toolbars[name] = IClassMapManagerToolbar(self, parent)
         self._mgr.AddPane(self.toolbars[name],
                           wx.aui.AuiPaneInfo().ToolbarPane().Movable().
                           Name(name).
                           CloseButton(False).Center().Layer(0).
                           BestSize((self.toolbars[name].GetBestSize())))
-        
+
     def _addPaneMapWindow(self, name):
         if name == 'preview':
             window = self.GetSecondWindow()
@@ -381,12 +409,12 @@
         else:
             window = self.GetFirstWindow()
             caption = _("Training Areas Display")
-        
+
         self._mgr.AddPane(window, wx.aui.AuiPaneInfo().
                           Name(name).Caption(caption).
                           Dockable(False).Floatable(False).CloseButton(False).
                           Center().Layer(0))
-        
+
     def IsStandalone(self):
         """Check if Map display is standalone"""
         return True
@@ -415,49 +443,57 @@
         """
         mapTb = self.GetMapToolbar()
         # optionally disable tool zoomback tool
-        mapTb.Enable('zoomBack', enable = (len(self.MapWindow.zoomhistory) > 1))
+        mapTb.Enable('zoomBack', enable=(len(self.MapWindow.zoomhistory) > 1))
 
         if mapTb.GetActiveMap() != (win == self.secondMapWindow):
             mapTb.SetActiveMap((win == self.secondMapWindow))
-        self.StatusbarUpdate() 
+        self.StatusbarUpdate()
 
     def ActivateFirstMap(self, event=None):
         DoubleMapFrame.ActivateFirstMap(self, event)
-        self.GetMapToolbar().Enable('zoomBack', enable=(len(self.MapWindow.zoomhistory) > 1))
+        self.GetMapToolbar().Enable('zoomBack',
+                                    enable=(len(self.MapWindow.zoomhistory) > 1))
 
     def ActivateSecondMap(self, event=None):
         DoubleMapFrame.ActivateSecondMap(self, event)
-        self.GetMapToolbar().Enable('zoomBack', enable=(len(self.MapWindow.zoomhistory) > 1))
+        self.GetMapToolbar().Enable('zoomBack',
+                                    enable=(len(self.MapWindow.zoomhistory) > 1))
 
     def GetMapToolbar(self):
         """Returns toolbar with zooming tools"""
-        return self.toolbars['iClassMap'] if 'iClassMap' in self.toolbars else None
+        return self.toolbars[
+            'iClassMap'] if 'iClassMap' in self.toolbars else None
 
     def GetClassColor(self, cat):
         """Get class color as string
 
         :param cat: class category
-        
+
         :return: 'R:G:B'
         """
         if cat in self.stats_data.GetCategories():
             return self.stats_data.GetStatistics(cat).color
         return '0:0:0'
-        
+
     def OnZoomMenu(self, event):
         """Popup Zoom menu """
         zoommenu = wx.Menu()
         # Add items to the menu
 
         i = 0
-        for label, handler in ((_('Adjust Training Area Display to Preview Display'), self.OnZoomToPreview),
-                               (_('Adjust Preview display to Training Area Display'), self.OnZoomToTraining),
-                               (_("Display synchronization ON"), lambda event: self.SetBindRegions(True)),
-                               (_("Display synchronization OFF"), lambda event: self.SetBindRegions(False))):
+        for label, handler in (
+            (_('Adjust Training Area Display to Preview Display'),
+             self.OnZoomToPreview),
+            (_('Adjust Preview display to Training Area Display'),
+             self.OnZoomToTraining),
+            (_("Display synchronization ON"),
+             lambda event: self.SetBindRegions(True)),
+            (_("Display synchronization OFF"),
+             lambda event: self.SetBindRegions(False))):
             if label is None:
                 zoommenu.AppendSeparator()
                 continue
-            
+
             item = wx.MenuItem(zoommenu, wx.ID_ANY, label)
             zoommenu.AppendItem(item)
             self.Bind(wx.EVT_MENU, handler, item)
@@ -466,12 +502,12 @@
             elif i == 4:
                 item.Enable(self._bindRegions)
             i += 1
-        
+
         # Popup the menu. If an item is selected then its handler
         # will be called before PopupMenu returns.
         self.PopupMenu(zoommenu)
         zoommenu.Destroy()
-        
+
     def OnZoomToTraining(self, event):
         """Set preview display to match extents of training display """
 
@@ -482,9 +518,9 @@
 
         newreg = self.firstMap.GetCurrentRegion()
         self.GetSecondMap().region = copy.copy(newreg)
-        
+
         self.Render(self.GetSecondWindow())
-        
+
     def OnZoomToPreview(self, event):
         """Set preview display to match extents of training display """
 
@@ -495,16 +531,16 @@
 
         newreg = self.GetSecondMap().GetCurrentRegion()
         self.GetFirstMap().region = copy.copy(newreg)
-        
+
         self.Render(self.GetFirstWindow())
-        
+
     def AddBands(self):
         """Add imagery group"""
         dlg = IClassGroupDialog(self, group=self.g['group'])
-        
+
         while True:
             if dlg.ShowModal() == wx.ID_OK:
-                
+
                 if dlg.GetGroupBandsErr(parent=self):
                     g, s = dlg.GetData()
                     group = grass.find_file(name=g, element='group')
@@ -513,235 +549,257 @@
                     self.groupSet.emit(group=self.g['group'],
                                        subgroup=self.g['subgroup'])
                     break
-            else: 
+            else:
                 break
-        
+
         dlg.Destroy()
 
     def OnImportAreas(self, event):
         """Import training areas"""
         # check if we have any changes
         if self.GetAreasCount() or self.stats_data.GetCategories():
-            qdlg = wx.MessageDialog(parent = self,
-                                    message = _("All changes will be lost. "
-                                                "Do you want to continue?") ,
-                                    style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
+            qdlg = wx.MessageDialog(
+                parent=self,
+                message=_(
+                    "All changes will be lost. "
+                    "Do you want to continue?"),
+                style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
             if qdlg.ShowModal() == wx.ID_NO:
                 qdlg.Destroy()
                 return
             qdlg.Destroy()
-            
-        dlg = IClassMapDialog(self, title = _("Import vector map"), element = 'vector')
+
+        dlg = IClassMapDialog(
+            self, title=_("Import vector map"),
+            element='vector')
         if dlg.ShowModal() == wx.ID_OK:
             vName = dlg.GetMap()
-            
+
             self.ImportAreas(vName)
-            
+
         dlg.Destroy()
-        
+
     def _checkImportedTopo(self, vector):
         """Check if imported vector map has areas
-        
+
         :param str vector: vector map name
-        
+
         :return: warning message (empty if topology is ok)
         """
-        topo = grass.vector_info_topo(map = vector)
-        
+        topo = grass.vector_info_topo(map=vector)
+
         warning = ''
         if topo['areas'] == 0:
             warning = _("No areas in vector map <%s>.\n" % vector)
         if topo['points'] or topo['lines']:
-            warning +=_("Vector map <%s> contains points or lines, "
-                        "these features are ignored." % vector)
-            
+            warning += _("Vector map <%s> contains points or lines, "
+                         "these features are ignored." % vector)
+
         return warning
-            
+
     def ImportAreas(self, vector):
         """Import training areas.
-        
+
         If table connected, try load certain columns to class manager
-        
+
         :param str vector: vector map name
         """
         warning = self._checkImportedTopo(vector)
         if warning:
-             GMessage(parent = self, message = warning)
-             return
-        
+            GMessage(parent=self, message=warning)
+            return
+
         wx.BeginBusyCursor()
         wx.Yield()
-        
+
         # close, build, copy and open again the temporary vector
         digitClass = self.GetFirstWindow().GetDigit()
-        
+
         # open vector map to be imported
         if digitClass.OpenMap(vector, update=False) is None:
-            GError(parent = self, message = _("Unable to open vector map <%s>") % vector)
+            GError(
+                parent=self,
+                message=_("Unable to open vector map <%s>") %
+                vector)
             return
-        
+
         # copy features to the temporary map
         vname = self._getTempVectorName()
-        os.environ['GRASS_VECTOR_TEMPORARY'] = '1' # avoid deleting temporary map
-        if digitClass.CopyMap(vname, tmp = True) == -1:
-            GError(parent = self, message = _("Unable to copy vector features from <%s>") % vector)
+        # avoid deleting temporary map
+        os.environ['GRASS_VECTOR_TEMPORARY'] = '1'
+        if digitClass.CopyMap(vname, tmp=True) == -1:
+            GError(
+                parent=self,
+                message=_("Unable to copy vector features from <%s>") %
+                vector)
             return
         del os.environ['GRASS_VECTOR_TEMPORARY']
-        
+
         # close map
         digitClass.CloseMap()
-        
+
         # open temporary map (copy of imported map)
-        self.poMapInfo = digitClass.OpenMap(vname, tmp = True)
+        self.poMapInfo = digitClass.OpenMap(vname, tmp=True)
         if self.poMapInfo is None:
-            GError(parent = self, message = _("Unable to open temporary vector map"))
+            GError(parent=self, message=_(
+                "Unable to open temporary vector map"))
             return
 
         # remove temporary rasters
         for cat in self.stats_data.GetCategories():
-            self.RemoveTempRaster(self.stats_data.GetStatistics(cat).rasterName)
-        
+            self.RemoveTempRaster(
+                self.stats_data.GetStatistics(cat).rasterName)
+
         # clear current statistics
         self.stats_data.DeleteAllStatistics()
-        
+
         # reset plots
         self.plotPanel.Reset()
-        
-        self.GetFirstWindow().UpdateMap(render = False, renderVector = True)
-        
+
+        self.GetFirstWindow().UpdateMap(render=False, renderVector=True)
+
         self.ImportClasses(vector)
-        
+
         # should be saved in attribute table?
         self.toolbars['iClass'].UpdateStddev(1.5)
-        
+
         wx.EndBusyCursor()
-        
+
         return True
-        
+
     def ImportClasses(self, vector):
         """If imported map has table, try to import certain columns to class manager"""
         # check connection
         dbInfo = VectorDBInfo(vector)
         connected = (len(dbInfo.layers.keys()) > 0)
-        
+
         # remove attribute table of temporary vector, we don't need it
         if connected:
             RunCommand('v.db.droptable',
-                       flags = 'f',
-                       map = self.trainingAreaVector)
-        
+                       flags='f',
+                       map=self.trainingAreaVector)
+
         # we use first layer with table, TODO: user should choose
         layer = None
         for key in dbInfo.layers.keys():
             if dbInfo.GetTable(key):
                 layer = key
-        
+
         # get columns to check if we can use them
         # TODO: let user choose which columns mean what
-        if layer is not None: 
-            columns = dbInfo.GetColumns(table = dbInfo.GetTable(layer))
+        if layer is not None:
+            columns = dbInfo.GetColumns(table=dbInfo.GetTable(layer))
         else:
             columns = []
-        
+
         # get class manager
         if self.dialogs['classManager'] is None:
             self.dialogs['classManager'] = IClassCategoryManagerDialog(self)
-                
+
         listCtrl = self.dialogs['classManager'].GetListCtrl()
-        
+
         # unable to load data (no connection, table, right columns)
         if not connected or layer is None or \
-                   'class' not in columns or \
-                   'color' not in columns:
+                'class' not in columns or \
+                'color' not in columns:
             # no table connected
             cats = RunCommand('v.category',
-                       input = vector,
-                       layer = 1, # set layer?
-                       # type = ['centroid', 'area'] ?
-                       option = "print",
-                       read = True)
+                              input=vector,
+                              layer=1,  # set layer?
+                              # type = ['centroid', 'area'] ?
+                              option="print",
+                              read=True)
             cats = map(int, cats.strip().split())
             cats = sorted(list(set(cats)))
 
             for cat in cats:
-                listCtrl.AddCategory(cat = cat, name = 'class_%d' % cat, color = "0:0:0")
+                listCtrl.AddCategory(
+                    cat=cat, name='class_%d' %
+                    cat, color="0:0:0")
         # connection, table and columns exists
         else:
             columns = ['cat', 'class', 'color']
             ret = RunCommand('v.db.select',
-                                 quiet = True,
-                                 parent = self,
-                                 flags = 'c',
-                                 map = vector,
-                                 layer = 1,
-                                 columns = ','.join(columns),
-                                 read = True)
+                             quiet=True,
+                             parent=self,
+                             flags='c',
+                             map=vector,
+                             layer=1,
+                             columns=','.join(columns),
+                             read=True)
             records = ret.strip().splitlines()
             for record in records:
                 record = record.split('|')
-                listCtrl.AddCategory(cat = int(record[0]), name = record[1], color = record[2])
-            
+                listCtrl.AddCategory(
+                    cat=int(record[0]),
+                    name=record[1],
+                    color=record[2])
+
     def OnExportAreas(self, event):
         """Export training areas"""
         if self.GetAreasCount() == 0:
-            GMessage(parent = self, message = _("No training areas to export."))
+            GMessage(parent=self, message=_("No training areas to export."))
             return
-            
-        dlg = IClassExportAreasDialog(self, vectorName = self.exportVector)
-        
+
+        dlg = IClassExportAreasDialog(self, vectorName=self.exportVector)
+
         if dlg.ShowModal() == wx.ID_OK:
             vName = dlg.GetVectorName()
             self.exportVector = vName
             withTable = dlg.WithTable()
             dlg.Destroy()
-            
-            if self.ExportAreas(vectorName = vName, withTable = withTable):
-                GMessage(_("%d training areas (%d classes) exported to vector map <%s>.") % \
-                             (self.GetAreasCount(), len(self.stats_data.GetCategories()),
-                              self.exportVector), parent = self)
-                    
+
+            if self.ExportAreas(vectorName=vName, withTable=withTable):
+                GMessage(
+                    _("%d training areas (%d classes) exported to vector map <%s>.") %
+                    (self.GetAreasCount(), len(
+                        self.stats_data.GetCategories()), self.exportVector), parent=self)
+
     def ExportAreas(self, vectorName, withTable):
         """Export training areas to new vector map (with attribute table).
-        
+
         :param str vectorName: name of exported vector map
         :param bool withTable: true if attribute table is required
         """
         wx.BeginBusyCursor()
         wx.Yield()
-        
+
         # close, build, copy and open again the temporary vector
         digitClass = self.GetFirstWindow().GetDigit()
         if '@' in vectorName:
             vectorName = vectorName.split('@')[0]
         if digitClass.CopyMap(vectorName) < 0:
             return False
-        
+
         if not withTable:
             wx.EndBusyCursor()
             return False
-            
+
         # add new table
         columns = ["class varchar(30)",
                    "color varchar(11)",
-                   "n_cells integer",]
-                   
+                   "n_cells integer", ]
+
         nbands = len(self.GetGroupLayers(self.g['group'], self.g['subgroup']))
-        for statistic, format in (("min", "integer"), ("mean", "double precision"), ("max", "integer")):
+        for statistic, format in (
+                ("min", "integer"),
+                ("mean", "double precision"),
+                ("max", "integer")):
             for i in range(nbands):
                 # 10 characters limit?
-                columns.append("band%(band)d_%(stat)s %(format)s" % {'band' : i + 1,
-                                                                    'stat' : statistic,
-                                                                    'format' : format})
-        
+                columns.append(
+                    "band%(band)d_%(stat)s %(format)s" %
+                    {'band': i + 1, 'stat': statistic, 'format': format})
+
         if 0 != RunCommand('v.db.addtable',
-                           map = vectorName,
-                           columns = columns,
-                           parent = self):
+                           map=vectorName,
+                           columns=columns,
+                           parent=self):
             wx.EndBusyCursor()
             return False
-        
+
         try:
-            dbInfo =  grass.vector_db(vectorName)[1]
+            dbInfo = grass.vector_db(vectorName)[1]
         except KeyError:
             wx.EndBusyCursor()
             return False
@@ -752,25 +810,50 @@
         # populate table
         for cat in self.stats_data.GetCategories():
             stat = self.stats_data.GetStatistics(cat)
-            
-            self._runDBUpdate(dbFile, table = dbInfo['table'], column = "class", value = stat.name, cat = cat)
-            self._runDBUpdate(dbFile, table = dbInfo['table'], column = "color", value = stat.color, cat = cat)
-            
+
+            self._runDBUpdate(
+                dbFile,
+                table=dbInfo['table'],
+                column="class",
+                value=stat.name,
+                cat=cat)
+            self._runDBUpdate(
+                dbFile,
+                table=dbInfo['table'],
+                column="color",
+                value=stat.color,
+                cat=cat)
+
             if not stat.IsReady():
                 continue
-                
-            self._runDBUpdate(dbFile, table = dbInfo['table'], column = "n_cells",value = stat.ncells, cat = cat)
-            
+
+            self._runDBUpdate(
+                dbFile,
+                table=dbInfo['table'],
+                column="n_cells",
+                value=stat.ncells,
+                cat=cat)
+
             for i in range(nbands):
-                self._runDBUpdate(dbFile, table = dbInfo['table'], column = "band%d_min" % (i + 1), value = stat.bands[i].min, cat = cat)
-                self._runDBUpdate(dbFile, table = dbInfo['table'], column = "band%d_mean" % (i + 1), value = stat.bands[i].mean, cat = cat)
-                self._runDBUpdate(dbFile, table = dbInfo['table'], column = "band%d_max" % (i + 1), value = stat.bands[i].max, cat = cat)
-                
+                self._runDBUpdate(
+                    dbFile, table=dbInfo['table'], column="band%d_min" %
+                    (i + 1), value=stat.bands[i].min, cat=cat)
+                self._runDBUpdate(
+                    dbFile, table=dbInfo['table'], column="band%d_mean" %
+                    (i + 1), value=stat.bands[i].mean, cat=cat)
+                self._runDBUpdate(
+                    dbFile, table=dbInfo['table'], column="band%d_max" %
+                    (i + 1), value=stat.bands[i].max, cat=cat)
+
         if dbInfo['driver'] != 'dbf':
             dbFile.write("COMMIT\n")
         dbFile.file.close()
 
-        ret = RunCommand('db.execute', input=dbFile.name, driver=dbInfo['driver'], database=dbInfo['database'])
+        ret = RunCommand(
+            'db.execute',
+            input=dbFile.name,
+            driver=dbInfo['driver'],
+            database=dbInfo['database'])
         wx.EndBusyCursor()
         os.remove(dbFile.name)
         if ret != 0:
@@ -779,20 +862,20 @@
 
     def _runDBUpdate(self, tmpFile, table, column, value, cat):
         """Helper function for UPDATE statement
-        
+
         :param tmpFile: file where to write UPDATE statements
         :param table: table name
         :param column: name of updated column
         :param value: new value
         :param cat: which category to update
         """
-        if type(value) == (types.IntType, types.FloatType):
+        if isinstance(value, (types.IntType, types.FloatType)):
             tmpFile.write("UPDATE %s SET %s = %d WHERE cat = %d\n" %
                           (table, column, value, cat))
         else:
             tmpFile.write("UPDATE %s SET %s = '%s' WHERE cat = %d\n" %
                           (table, column, value, cat))
-        
+
     def OnCategoryManager(self, event):
         """Show category management dialog"""
         if self.dialogs['classManager'] is None:
@@ -803,91 +886,103 @@
         else:
             if not self.dialogs['classManager'].IsShown():
                 self.dialogs['classManager'].Show()
-        
+
     def CategoryChanged(self, currentCat):
         """Updates everything which depends on current category.
-        
-        Updates number of stddev, histograms, layer in preview display. 
+
+        Updates number of stddev, histograms, layer in preview display.
         """
         if currentCat:
-          stat = self.stats_data.GetStatistics(currentCat)
-          nstd = stat.nstd
-          self.toolbars['iClass'].UpdateStddev(nstd)
-          
-          self.plotPanel.UpdateCategory(currentCat)
-          self.plotPanel.OnPlotTypeSelected(None)
-                                   
-          name = stat.rasterName
-          name = self.previewMapManager.GetAlias(name)
-          if name:
-              self.previewMapManager.SelectLayer(name)
+            stat = self.stats_data.GetStatistics(currentCat)
+            nstd = stat.nstd
+            self.toolbars['iClass'].UpdateStddev(nstd)
 
-        self.categoryChanged.emit(cat = currentCat)
-        
+            self.plotPanel.UpdateCategory(currentCat)
+            self.plotPanel.OnPlotTypeSelected(None)
+
+            name = stat.rasterName
+            name = self.previewMapManager.GetAlias(name)
+            if name:
+                self.previewMapManager.SelectLayer(name)
+
+        self.categoryChanged.emit(cat=currentCat)
+
     def DeleteAreas(self, cats):
         """Removes all training areas of given categories
-        
+
         :param cats: list of categories to be deleted
         """
         self.firstMapWindow.GetDigit().DeleteAreasByCat(cats)
         self.firstMapWindow.UpdateMap(render=False, renderVector=True)
-        
+
     def HighlightCategory(self, cats):
         """Highlight araes given by category"""
-        self.firstMapWindow.GetDigit().GetDisplay().SetSelected(cats, layer = 1)
+        self.firstMapWindow.GetDigit().GetDisplay().SetSelected(cats, layer=1)
         self.firstMapWindow.UpdateMap(render=False, renderVector=True)
-        
+
     def ZoomToAreasByCat(self, cat):
         """Zoom to areas given by category"""
         n, s, w, e = self.GetFirstWindow().GetDigit().GetDisplay().GetRegionSelected()
-        self.GetFirstMap().GetRegion(n = n, s = s, w = w, e = e, update = True)
+        self.GetFirstMap().GetRegion(n=n, s=s, w=w, e=e, update=True)
         self.GetFirstMap().AdjustRegion()
         self.GetFirstMap().AlignExtentFromDisplay()
-        
-        self.GetFirstWindow().UpdateMap(render = True, renderVector = True)
-        
+
+        self.GetFirstWindow().UpdateMap(render=True, renderVector=True)
+
     def UpdateRasterName(self, newName, cat):
         """Update alias of raster map when category name is changed"""
         origName = self.stats_data.GetStatistics(cat).rasterName
         self.previewMapManager.SetAlias(origName, self._addSuffix(newName))
-        
+
     def StddevChanged(self, cat, nstd):
         """Standard deviation multiplier changed, rerender map, histograms"""
         stat = self.stats_data.GetStatistics(cat)
-        stat.SetStatistics({"nstd" : nstd})
-        
+        stat.SetStatistics({"nstd": nstd})
+
         if not stat.IsReady():
             return
-            
+
         raster = stat.rasterName
-        
+
         cstat = self.cStatisticsDict[cat]
         I_iclass_statistics_set_nstd(cstat, nstd)
-        
+
         I_iclass_create_raster(cstat, self.refer, raster)
         self.Render(self.GetSecondWindow())
-    
+
         stat.SetBandStatistics(cstat)
         self.plotPanel.StddevChanged()
-        
+
     def UpdateChangeState(self, changes):
         """Informs if any important changes happened
         since last analysis computation.
         """
         self.changes = changes
-        
-    def AddRasterMap(self, name, firstMap = True, secondMap = True):
+
+    def AddRasterMap(self, name, firstMap=True, secondMap=True):
         """Add raster map to Map"""
         cmdlist = ['d.rast', 'map=%s' % name]
         if firstMap:
-            self.GetFirstMap().AddLayer(ltype='raster', command=cmdlist, active=True,
-                                        name=name, hidden=False, opacity=1.0, render=False)
+            self.GetFirstMap().AddLayer(
+                ltype='raster',
+                command=cmdlist,
+                active=True,
+                name=name,
+                hidden=False,
+                opacity=1.0,
+                render=False)
             self.Render(self.GetFirstWindow())
         if secondMap:
-            self.GetSecondMap().AddLayer(ltype='raster', command=cmdlist, active=True,
-                                        name=name, hidden=False, opacity=1.0, render=False)
+            self.GetSecondMap().AddLayer(
+                ltype='raster',
+                command=cmdlist,
+                active=True,
+                name=name,
+                hidden=False,
+                opacity=1.0,
+                render=False)
             self.Render(self.GetSecondWindow())
-           
+
     def AddTrainingAreaMap(self):
         """Add vector map with training areas to Map (training
         sub-display)"""
@@ -895,89 +990,111 @@
         if vname:
             self.trainingAreaVector = vname
         else:
-            GMessage(parent = self, message = _("Failed to create temporary vector map."))
+            GMessage(parent=self, message=_(
+                "Failed to create temporary vector map."))
             return
-        
+
         # use 'hidden' for temporary maps (TODO: do it better)
-        mapLayer = self.GetFirstMap().AddLayer(ltype = 'vector',
-                                               command = ['d.vect', 'map=%s' % vname],
-                                               name = vname, active = False, hidden = True)
-        
+        mapLayer = self.GetFirstMap().AddLayer(
+            ltype='vector',
+            command=[
+                'd.vect',
+                'map=%s' %
+                vname],
+            name=vname,
+            active=False,
+            hidden=True)
+
         self.toolbars['vdigit'].StartEditing(mapLayer)
         self.poMapInfo = self.GetFirstWindow().GetDigit().GetMapInfo()
         self.Render(self.GetFirstWindow())
-        
+
     def OnRunAnalysis(self, event):
         """Run analysis and update plots"""
         if self.RunAnalysis():
             currentCat = self.GetCurrentCategoryIdx()
-            self.plotPanel.UpdatePlots(group = self.g['group'], subgroup = self.g['subgroup'], 
-                                       currentCat = currentCat, stats_data = self.stats_data)
-        
+            self.plotPanel.UpdatePlots(
+                group=self.g['group'],
+                subgroup=self.g['subgroup'],
+                currentCat=currentCat,
+                stats_data=self.stats_data)
+
     def RunAnalysis(self):
         """Run analysis
-        
+
         Calls C functions to compute all statistics and creates raster maps.
         Signatures are created but signature file is not.
         """
-        if not self.CheckInput(group = self.g['group'], vector = self.trainingAreaVector):
+        if not self.CheckInput(
+                group=self.g['group'],
+                vector=self.trainingAreaVector):
             return
-            
+
         for statistic in self.cStatisticsDict.values():
             I_iclass_free_statistics(statistic)
         self.cStatisticsDict = {}
-        
+
         # init Ref struct with the files in group */
         I_free_group_ref(self.refer)
 
-        if (not I_iclass_init_group(self.g['group'], self.g["subgroup"], self.refer)):
+        if (not I_iclass_init_group(
+                self.g['group'], self.g["subgroup"], self.refer)):
             return False
-        
+
         I_free_signatures(self.signatures)
         I_iclass_init_signatures(self.signatures, self.refer)
-        
+
         # why create copy
         #cats = self.statisticsList[:]
-        
+
         cats = self.stats_data.GetCategories()
         for i in cats:
             stats = self.stats_data.GetStatistics(i)
-            
+
             statistics_obj = IClass_statistics()
             statistics = pointer(statistics_obj)
-            
-            I_iclass_init_statistics(statistics, 
+
+            I_iclass_init_statistics(statistics,
                                      stats.category,
                                      stats.name,
                                      stats.color,
                                      stats.nstd)
-            
-            ret = I_iclass_analysis(statistics, self.refer, self.poMapInfo, "1",
-                                 self.g['group'], stats.rasterName)
+
+            ret = I_iclass_analysis(
+                statistics,
+                self.refer,
+                self.poMapInfo,
+                "1",
+                self.g['group'],
+                stats.rasterName)
             if ret > 0:
                 # tests
                 self.cStatisticsDict[i] = statistics
-                
+
                 stats.SetFromcStatistics(statistics)
                 stats.SetReady()
-                
+
                 # stat is already part of stats_data?
                 #self.statisticsDict[stats.category] = stats
-                
-                self.ConvertToNull(name = stats.rasterName)
-                self.previewMapManager.AddLayer(name = stats.rasterName,
-                                                alias = self._addSuffix(stats.name), resultsLayer = True)
+
+                self.ConvertToNull(name=stats.rasterName)
+                self.previewMapManager.AddLayer(
+                    name=stats.rasterName, alias=self._addSuffix(
+                        stats.name), resultsLayer=True)
                 # write statistics
                 I_iclass_add_signature(self.signatures, statistics)
-                
+
             elif ret == 0:
-                GMessage(parent = self, message = _("No area in category %s. Category skipped.") % stats.category)
+                GMessage(
+                    parent=self,
+                    message=_("No area in category %s. Category skipped.") %
+                    stats.category)
                 I_iclass_free_statistics(statistics)
             else:
-                GMessage(parent = self, message = _("Analysis failed."))
+                GMessage(parent=self, message=_("Analysis failed."))
                 I_iclass_free_statistics(statistics)
-        
-        self.UpdateChangeState(changes = False)
+
+        self.UpdateChangeState(changes=False)
         return True
 
     def _addSuffix(self, name):
@@ -987,117 +1104,127 @@
     def OnSaveSigFile(self, event):
         """Asks for signature file name and saves it."""
         if not self.g['group']:
-            GMessage(parent = self, message = _("No imagery group selected."))
+            GMessage(parent=self, message=_("No imagery group selected."))
             return
-            
+
         if self.changes:
-            qdlg = wx.MessageDialog(parent = self,
-                                    message = _("Due to recent changes in classes, "
-                                                "signatures can be outdated and should be recalculated. "
-                                                "Do you still want to continue?") ,
-                                   caption = _("Outdated signatures"),
-                                   style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
+            qdlg = wx.MessageDialog(
+                parent=self,
+                message=_(
+                    "Due to recent changes in classes, "
+                    "signatures can be outdated and should be recalculated. "
+                    "Do you still want to continue?"),
+                caption=_("Outdated signatures"),
+                style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
             if qdlg.ShowModal() == wx.ID_YES:
                 qdlg.Destroy()
             else:
                 qdlg.Destroy()
                 return
-                    
-        dlg = IClassSignatureFileDialog(self, 
-                                        group = self.g['group'], 
-                                        subgroup = self.g['subgroup'], 
-                                        file = self.sigFile)
-        
+
+        dlg = IClassSignatureFileDialog(self,
+                                        group=self.g['group'],
+                                        subgroup=self.g['subgroup'],
+                                        file=self.sigFile)
+
         if dlg.ShowModal() == wx.ID_OK:
-            if os.path.exists(dlg.GetFileName(fullPath = True)):
-                qdlg = wx.MessageDialog(parent = self,
-                                        message = _("A signature file named %s already exists.\n"
-                                                    "Do you want to replace it?") % dlg.GetFileName(),
-                                        caption = _("File already exists"),
-                                        style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
+            if os.path.exists(dlg.GetFileName(fullPath=True)):
+                qdlg = wx.MessageDialog(
+                    parent=self,
+                    message=_(
+                        "A signature file named %s already exists.\n"
+                        "Do you want to replace it?") %
+                    dlg.GetFileName(),
+                    caption=_("File already exists"),
+                    style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
                 if qdlg.ShowModal() == wx.ID_YES:
                     qdlg.Destroy()
                 else:
                     qdlg.Destroy()
                     return
             self.sigFile = dlg.GetFileName()
-            self.WriteSignatures(self.signatures, self.g['group'], self.g['subgroup'], self.sigFile)
-            
+            self.WriteSignatures(
+                self.signatures,
+                self.g['group'],
+                self.g['subgroup'],
+                self.sigFile)
+
         dlg.Destroy()
-        
+
     def InitStatistics(self):
         """Initialize variables and c structures neccessary for
         computing statistics.
         """
-        self.g = {'group' : None, 'subgroup' : None}
+        self.g = {'group': None, 'subgroup': None}
         self.sigFile = None
-        
+
         self.stats_data = StatisticsData()
-        
+
         self.cStatisticsDict = {}
-        
+
         self.signatures_obj = Signature()
         self.signatures = pointer(self.signatures_obj)
-        I_init_signatures(self.signatures, 0) # must be freed on exit
-        
+        I_init_signatures(self.signatures, 0)  # must be freed on exit
+
         refer_obj = Ref()
         self.refer = pointer(refer_obj)
-        I_init_group_ref(self.refer) # must be freed on exit
-        
+        I_init_group_ref(self.refer)  # must be freed on exit
+
     def WriteSignatures(self, signatures, group, subgroup, filename):
         """Writes current signatures to signature file
-        
+
         :param signatures: signature (c structure)
         :param group: imagery group
         :param filename: signature file name
         """
         I_iclass_write_signatures(signatures, group, subgroup, filename)
-                                        
+
     def CheckInput(self, group, vector):
         """Check if input is valid"""
         # check if group is ok
-        #TODO check subgroup
+        # TODO check subgroup
         if not group:
-            GMessage(parent = self,
-                     message = _("No imagery group selected. "
-                                 "Operation canceled."))
+            GMessage(parent=self,
+                     message=_("No imagery group selected. "
+                               "Operation canceled."))
             return False
-            
+
         groupLayers = self.GetGroupLayers(self.g['group'], self.g['subgroup'])
-            
+
         nLayers = len(groupLayers)
         if nLayers <= 1:
-            GMessage(parent = self,
-                     message = _("Group <%(group)s> does not have enough files "
-                                 "(it has %(files)d files). Operation canceled.") % \
-                         { 'group' : group,
-                           'files' : nLayers })
+            GMessage(
+                parent=self,
+                message=_(
+                    "Group <%(group)s> does not have enough files "
+                    "(it has %(files)d files). Operation canceled.") %
+                {'group': group, 'files': nLayers})
             return False
-        
-        #check if vector has any areas
+
+        # check if vector has any areas
         if self.GetAreasCount() == 0:
-            GMessage(parent = self,
-            message = _("No areas given. "
-                        "Operation canceled."))
+            GMessage(parent=self,
+                     message=_("No areas given. "
+                               "Operation canceled."))
             return False
-            
+
         # check if vector is inside raster
         regionBox = bound_box()
         Vect_get_map_box(self.poMapInfo, byref(regionBox))
-        
+
         rasterInfo = grass.raster_info(groupLayers[0])
-        
+
         if regionBox.N > rasterInfo['north'] or \
            regionBox.S < rasterInfo['south'] or \
            regionBox.E > rasterInfo['east'] or \
            regionBox.W < rasterInfo['west']:
-           GMessage(parent = self,
-                    message = _("Vector features are outside raster layers. "
-                                "Operation canceled."))
-           return False
-            
+            GMessage(parent=self,
+                     message=_("Vector features are outside raster layers. "
+                               "Operation canceled."))
+            return False
+
         return True
-        
+
     def GetAreasCount(self):
         """Returns number of not dead areas"""
         count = 0
@@ -1106,10 +1233,10 @@
             if Vect_area_alive(self.poMapInfo, i + 1):
                 count += 1
         return count
-        
+
     def GetGroupLayers(self, group, subgroup=None):
         """Get layers in subgroup (expecting same name for group and subgroup)
-    
+
         .. todo::
             consider moving this function to core module for convenient
         """
@@ -1118,42 +1245,42 @@
             kwargs['subgroup'] = subgroup
 
         res = RunCommand('i.group',
-                         flags = 'g',
-                         group = group,
-                         read = True, **kwargs).strip()
+                         flags='g',
+                         group=group,
+                         read=True, **kwargs).strip()
         if res.splitlines()[0]:
             return sorted(res.splitlines())
-        
+
         return []
-    
+
     def ConvertToNull(self, name):
         """Sets value which represents null values for given raster map.
-        
+
         :param name: raster map name
         """
         RunCommand('r.null',
-                   map = name,
-                   setnull = 0)
-                     
+                   map=name,
+                   setnull=0)
+
     def GetCurrentCategoryIdx(self):
         """Returns current category number"""
         return self.toolbars['iClass'].GetSelectedCategoryIdx()
-        
+
     def OnZoomIn(self, event):
         """Enable zooming for plots"""
         super(IClassMapFrame, self).OnZoomIn(event)
-        self.plotPanel.EnableZoom(type = 1)
-        
+        self.plotPanel.EnableZoom(type=1)
+
     def OnZoomOut(self, event):
         """Enable zooming for plots"""
         super(IClassMapFrame, self).OnZoomOut(event)
-        self.plotPanel.EnableZoom(type = -1)
-        
+        self.plotPanel.EnableZoom(type=-1)
+
     def OnPan(self, event):
         """Enable panning for plots"""
         super(IClassMapFrame, self).OnPan(event)
         self.plotPanel.EnablePan()
-        
+
     def OnPointer(self, event):
         """Set pointer mode.
 
@@ -1166,20 +1293,22 @@
     def GetMapManagers(self):
         """Get map managers of wxIClass
 
-        :return: trainingMapManager, previewMapManager 
+        :return: trainingMapManager, previewMapManager
         """
         return self.trainingMapManager, self.previewMapManager
 
+
 class MapManager:
     """Class for managing map renderer.
-    
+
     It is connected with iClassMapManagerToolbar.
     """
+
     def __init__(self, frame, mapWindow, Map):
         """
-        
+
         It is expected that \a mapWindow is conected with \a Map.
-        
+
         :param frame: application main window
         :param mapWindow: map window instance
         :param map: map renderer instance
@@ -1188,38 +1317,37 @@
         self.frame = frame
         self.mapWindow = mapWindow
         self.toolbar = None
-        
+
         self.layerName = {}
-        
-        
+
     def SetToolbar(self, toolbar):
         self.toolbar = toolbar
-        
-    def AddLayer(self, name, alias = None, resultsLayer = False):
-        """Adds layer to Map and update toolbar 
-        
+
+    def AddLayer(self, name, alias=None, resultsLayer=False):
+        """Adds layer to Map and update toolbar
+
         :param str name: layer (raster) name
         :param str resultsLayer: True if layer is temp. raster showing the results of computation
         """
-        if (resultsLayer and
-            name in [l.GetName() for l in self.map.GetListOfLayers(name = name)]):
+        if (resultsLayer and name in [l.GetName()
+                                      for l in self.map.GetListOfLayers(name=name)]):
             self.frame.Render(self.mapWindow)
             return
-            
+
         cmdlist = ['d.rast', 'map=%s' % name]
-        self.map.AddLayer(ltype = 'raster', command = cmdlist, active = True,
-                          name = name, hidden = False, opacity = 1.0, render = True)
+        self.map.AddLayer(ltype='raster', command=cmdlist, active=True,
+                          name=name, hidden=False, opacity=1.0, render=True)
         self.frame.Render(self.mapWindow)
-        
+
         if alias is not None:
             self.layerName[alias] = name
             name = alias
         else:
             self.layerName[name] = name
-            
+
         self.toolbar.choice.Insert(name, 0)
         self.toolbar.choice.SetSelection(0)
-        
+
     def AddLayerRGB(self, cmd):
         """Adds RGB layer and update toolbar.
 
@@ -1230,8 +1358,8 @@
             if '=' in param:
                 name.append(param.split('=')[1])
         name = ','.join(name)
-        self.map.AddLayer(ltype = 'rgb', command = cmd, active = True,
-                          name = name, hidden = False, opacity = 1.0, render = True)
+        self.map.AddLayer(ltype='rgb', command=cmd, active=True,
+                          name=name, hidden=False, opacity=1.0, render=True)
         self.frame.Render(self.mapWindow)
         self.layerName[name] = name
         self.toolbar.choice.Insert(name, 0)
@@ -1239,11 +1367,11 @@
 
     def RemoveTemporaryLayer(self, name):
         """Removes temporary layer (if exists) from Map and and updates toolbar.
-        
+
         :param name: real name of layer
         """
         # check if layer is loaded
-        layers = self.map.GetListOfLayers(ltype = 'raster')
+        layers = self.map.GetListOfLayers(ltype='raster')
         idx = None
         for i, layer in enumerate(layers):
             if name == layer.GetName():
@@ -1252,13 +1380,13 @@
         if idx is None:
             return
         # remove it from Map
-        self.map.RemoveLayer(name = name)
-        
+        self.map.RemoveLayer(name=name)
+
         # update inner list of layers
         alias = self.GetAlias(name)
         if alias not in self.layerName:
             return
-            
+
         del self.layerName[alias]
         # update choice
         idx = self.toolbar.choice.FindString(alias)
@@ -1266,9 +1394,9 @@
             self.toolbar.choice.Delete(idx)
             if not self.toolbar.choice.IsEmpty():
                 self.toolbar.choice.SetSelection(0)
-        
+
         self.frame.Render(self.mapWindow)
-    
+
     def Render(self):
         """
         .. todo::
@@ -1278,66 +1406,67 @@
     def RemoveLayer(self, name, idx):
         """Removes layer from Map and update toolbar"""
         name = self.layerName[name]
-        self.map.RemoveLayer(name = name)
+        self.map.RemoveLayer(name=name)
         del self.layerName[name]
         self.toolbar.choice.Delete(idx)
         if not self.toolbar.choice.IsEmpty():
             self.toolbar.choice.SetSelection(0)
-            
+
         self.frame.Render(self.mapWindow)
-            
+
     def SelectLayer(self, name):
         """Moves selected layer to top"""
-        layers = self.map.GetListOfLayers(ltype = 'rgb') + \
-                 self.map.GetListOfLayers(ltype = 'raster')
+        layers = self.map.GetListOfLayers(ltype='rgb') + \
+            self.map.GetListOfLayers(ltype='raster')
         idx = None
         for i, layer in enumerate(layers):
             if self.layerName[name] == layer.GetName():
                 idx = i
                 break
-                
-        if idx is not None: # should not happen
+
+        if idx is not None:  # should not happen
             layers.append(layers.pop(idx))
-            
+
             choice = self.toolbar.choice
             idx = choice.FindString(name)
             choice.Delete(idx)
             choice.Insert(name, 0)
             choice.SetSelection(0)
-            
-            #layers.reverse()
+
+            # layers.reverse()
             self.map.SetLayers(layers)
             self.frame.Render(self.mapWindow)
-        
+
     def SetOpacity(self, name):
         """Sets opacity of layers."""
         name = self.layerName[name]
-        layers = self.map.GetListOfLayers(name = name)
+        layers = self.map.GetListOfLayers(name=name)
         if not layers:
             return
-            
+
         # works for first layer only
         oldOpacity = layers[0].GetOpacity()
-        dlg = SetOpacityDialog(self.frame, opacity = oldOpacity)
-        dlg.applyOpacity.connect(lambda value:
-                                 self._changeOpacity(layer=layers[0], opacity=value))
-        
+        dlg = SetOpacityDialog(self.frame, opacity=oldOpacity)
+        dlg.applyOpacity.connect(
+            lambda value: self._changeOpacity(
+                layer=layers[0], opacity=value))
+
         if dlg.ShowModal() == wx.ID_OK:
             self._changeOpacity(layer=layers[0], opacity=dlg.GetOpacity())
-            
+
         dlg.Destroy()
 
     def _changeOpacity(self, layer, opacity):
         self.map.ChangeOpacity(layer=layer, opacity=opacity)
         self.frame.Render(self.mapWindow)
-                
+
     def GetAlias(self, name):
         """Returns alias for layer"""
-        name =  [k for k, v in self.layerName.iteritems() if v == name]
+        name = [k for k, v in self.layerName.iteritems() if v == name]
         if name:
             return name[0]
         return None
-        
+
     def SetAlias(self, original, alias):
         name = self.GetAlias(original)
         if name:
@@ -1347,16 +1476,16 @@
             if idx != wx.NOT_FOUND:
                 self.toolbar.choice.SetString(idx, alias)
 
+
 def test():
     import core.render as render
 
     app = wx.App()
     wx.InitAllImageHandlers()
-    
+
     frame = IClassMapFrame()
     frame.Show()
     app.MainLoop()
 
 if __name__ == "__main__":
     test()
-    

Modified: grass/trunk/gui/wxpython/iclass/g.gui.iclass.py
===================================================================
--- grass/trunk/gui/wxpython/iclass/g.gui.iclass.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/iclass/g.gui.iclass.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -61,7 +61,7 @@
 
     from grass.script.setup import set_gui_path
     set_gui_path()
-    
+
     from core.settings import UserSettings
     from core.globalvar import CheckWxVersion
     from core.giface import StandaloneGrassInterface
@@ -94,7 +94,9 @@
         trainingmap_name = gscript.find_file(name=options['trainingmap'],
                                              element='vector')['fullname']
         if not trainingmap_name:
-            gscript.fatal(_("Vector map <%s> not found") % options['trainingmap'])
+            gscript.fatal(
+                _("Vector map <%s> not found") %
+                options['trainingmap'])
 
     # define display driver
     driver = UserSettings.Get(group='display', key='driver', subkey='type')

Modified: grass/trunk/gui/wxpython/iclass/plots.py
===================================================================
--- grass/trunk/gui/wxpython/iclass/plots.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/iclass/plots.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -21,25 +21,27 @@
 from core.utils import _
 from core.gcmd import GError
 
+
 class PlotPanel(scrolled.ScrolledPanel):
     """Panel for drawing multiple plots.
-    
+
     There are three types of plots: histograms, coincidence plots and scatter plots.
     Histograms show frequency of cell category values in training areas
     for each band and for one category. Coincidence plots show min max range
     of classes for each band.
     """
+
     def __init__(self, parent, giface, stats_data):
         scrolled.ScrolledPanel.__init__(self, parent)
-        
-        self.SetupScrolling(scroll_x = False, scroll_y = True)
+
+        self.SetupScrolling(scroll_x=False, scroll_y=True)
         self._giface = giface
         self.parent = parent
         self.canvasList = []
         self.bandList = []
         self.stats_data = stats_data
         self.currentCat = None
-        
+
         self.mainSizer = wx.BoxSizer(wx.VERTICAL)
 
         self._createControlPanel()
@@ -57,46 +59,64 @@
     def _createPlotPanel(self):
 
         self.canvasPanel = wx.Panel(parent=self)
-        self.mainSizer.Add(item = self.canvasPanel, proportion = 1, flag = wx.EXPAND, border = 0)
+        self.mainSizer.Add(
+            item=self.canvasPanel,
+            proportion=1,
+            flag=wx.EXPAND,
+            border=0)
         self.canvasSizer = wx.BoxSizer(wx.VERTICAL)
         self.canvasPanel.SetSizer(self.canvasSizer)
 
     def _createControlPanel(self):
-        self.plotSwitch = wx.Choice(self, id = wx.ID_ANY,
-                                     choices = [_("Histograms"),
-                                                _("Coincident plots"),
-                                                _("Scatter plots")])
-        self.mainSizer.Add(self.plotSwitch, proportion = 0, flag = wx.EXPAND|wx.ALL, border = 5)
+        self.plotSwitch = wx.Choice(self, id=wx.ID_ANY,
+                                    choices=[_("Histograms"),
+                                             _("Coincident plots"),
+                                             _("Scatter plots")])
+        self.mainSizer.Add(
+            self.plotSwitch,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
         self.plotSwitch.Bind(wx.EVT_CHOICE, self.OnPlotTypeSelected)
-    
+
     def _createScatterPlotPanel(self):
         """Init interactive scatter plot tool
         """
         try:
             from iscatt.frame import IClassIScattPanel
-            self.iscatt_panel = IClassIScattPanel(parent=self, 
-                                                  giface=self._giface, 
-                                                  iclass_mapwin = self.parent.GetFirstWindow())
-            self.mainSizer.Add(self.iscatt_panel, proportion = 1, flag = wx.EXPAND, border = 0)
+            self.iscatt_panel = IClassIScattPanel(
+                parent=self, giface=self._giface,
+                iclass_mapwin=self.parent.GetFirstWindow())
+            self.mainSizer.Add(
+                self.iscatt_panel,
+                proportion=1,
+                flag=wx.EXPAND,
+                border=0)
             self.iscatt_panel.Hide()
         except ImportError as e:
-            self.scatt_error = _("Scatter plot functionality is disabled.\n\nReason: " \
-                                 "Unable to import packages needed for scatter plot.\n%s" % e)
-            wx.CallAfter(GError, self.scatt_error, showTraceback=False, parent=self)
+            self.scatt_error = _(
+                "Scatter plot functionality is disabled.\n\nReason: "
+                "Unable to import packages needed for scatter plot.\n%s" %
+                e)
+            wx.CallAfter(
+                GError,
+                self.scatt_error,
+                showTraceback=False,
+                parent=self)
             self.iscatt_panel = None
 
     def OnPlotTypeSelected(self, event):
         """Plot type selected"""
 
         if self.plotSwitch.GetSelection() in [0, 1]:
-            self.SetupScrolling(scroll_x = False, scroll_y = True)
+            self.SetupScrolling(scroll_x=False, scroll_y=True)
             if self.iscatt_panel:
                 self.iscatt_panel.Hide()
             self.canvasPanel.Show()
             self.Layout()
 
         elif self.plotSwitch.GetSelection() == 2:
-            self.SetupScrolling(scroll_x = False, scroll_y = False)
+            self.SetupScrolling(scroll_x=False, scroll_y=False)
             if self.iscatt_panel:
                 self.iscatt_panel.Show()
             else:
@@ -123,35 +143,35 @@
         if self.plotSwitch.GetSelection() == 0:
             stat = self.stats_data.GetStatistics(self.currentCat)
             self.UpdateRanges(stat)
-        
-    def EnableZoom(self, type, enable = True):
+
+    def EnableZoom(self, type, enable=True):
         for canvas in self.canvasList:
             canvas.SetEnableZoom(enable)
-            
+
         #canvas.zoom = type
-        
-    def EnablePan(self, enable = True):
+
+    def EnablePan(self, enable=True):
         for canvas in self.canvasList:
             canvas.SetEnableDrag(enable)
-            
+
     def DestroyPlots(self):
         """Destroy all plot canvases"""
         for panel in self.canvasList:
             panel.Destroy()
-            
+
         self.canvasList = []
 
     def ClearPlots(self):
         """Clears plot canvases"""
         for bandIdx in range(len(self.bandList)):
             self.canvasList[bandIdx].Clear()
-            
+
     def Reset(self):
         """Reset plots (when new map imported)"""
         self.currentCat = None
         self.ClearPlots()
         # bands are still the same
-        
+
     def CreatePlotCanvases(self):
         """Create plot canvases according to the number of bands"""
         for band in self.bandList:
@@ -160,15 +180,19 @@
             canvas.SetFontSizeTitle(10)
             canvas.SetFontSizeAxis(8)
             self.canvasList.append(canvas)
-            
-            self.canvasSizer.Add(item = canvas, proportion = 1, flag = wx.EXPAND, border = 0)
-        
+
+            self.canvasSizer.Add(
+                item=canvas,
+                proportion=1,
+                flag=wx.EXPAND,
+                border=0)
+
         self.SetVirtualSize(self.GetBestVirtualSize())
         self.Layout()
-        
+
     def UpdatePlots(self, group, subgroup, currentCat, stats_data):
         """Update plots after new analysis
-        
+
         :param group: imagery group
         :param subgroup: imagery group
         :param currentCat: currently selected category (class)
@@ -177,24 +201,24 @@
         self.stats_data = stats_data
         self.currentCat = currentCat
         self.bandList = self.parent.GetGroupLayers(group, subgroup)
-        
+
         graphType = self.plotSwitch.GetSelection()
 
         stat = self.stats_data.GetStatistics(currentCat)
         if not stat.IsReady() and graphType == 0:
             return
-            
+
         self.DestroyPlots()
         self.CreatePlotCanvases()
         self.OnPlotTypeSelected(None)
-        
+
     def UpdateCategory(self, cat):
         self.currentCat = cat
-    
+
     def DrawCoincidencePlots(self):
         """Draw coincidence plots"""
         for bandIdx in range(len(self.bandList)):
-            self.canvasList[bandIdx].SetYSpec(type = 'none')
+            self.canvasList[bandIdx].SetYSpec(type='none')
             lines = []
             level = 0.5
             lines.append(self.DrawInvisibleLine(level))
@@ -206,19 +230,20 @@
                     continue
                 color = stat.color
                 level = i + 1
-                line = self.DrawCoincidenceLine(level, color, stat.bands[bandIdx])
+                line = self.DrawCoincidenceLine(
+                    level, color, stat.bands[bandIdx])
                 lines.append(line)
-            
-            # invisible 
+
+            # invisible
             level += 0.5
             lines.append(self.DrawInvisibleLine(level))
-            
-            plotGraph = plot.PlotGraphics(lines, title = self.bandList[bandIdx])
+
+            plotGraph = plot.PlotGraphics(lines, title=self.bandList[bandIdx])
             self.canvasList[bandIdx].Draw(plotGraph)
-        
+
     def DrawCoincidenceLine(self, level, color, bandValues):
         """Draw line between band min and max values
-        
+
         :param level: y coordinate of line
         :param color: class color
         :param bandValues: BandStatistics instance
@@ -227,75 +252,80 @@
         maxim = bandValues.max
         points = [(minim, level), (maxim, level)]
         color = wx.Colour(*map(int, color.split(':')))
-        return plot.PolyLine(points, colour = color, width = 4)
-        
+        return plot.PolyLine(points, colour=color, width=4)
+
     def DrawInvisibleLine(self, level):
         """Draw white line to achieve better margins"""
         points = [(100, level), (101, level)]
-        return plot.PolyLine(points, colour = wx.WHITE, width = 1)
-        
+        return plot.PolyLine(points, colour=wx.WHITE, width=1)
+
     def DrawHistograms(self, statistics):
         """Draw histograms for one class
-        
+
         :param statistics: statistics for one class
         """
         self.histogramLines = []
         for bandIdx in range(len(self.bandList)):
             self.canvasList[bandIdx].Clear()
-            self.canvasList[bandIdx].SetYSpec(type = 'auto')
-            histgramLine = self.CreateHistogramLine(bandValues = statistics.bands[bandIdx])
-                                                
-            meanLine = self.CreateMean(bandValues = statistics.bands[bandIdx])
-            
-            minLine = self.CreateMin(bandValues = statistics.bands[bandIdx])
-            
-            maxLine = self.CreateMax(bandValues = statistics.bands[bandIdx])
-            
-            self.histogramLines.append([histgramLine, meanLine, minLine, maxLine])
-            
-            maxRangeLine = self.CreateMaxRange(bandValues = statistics.bands[bandIdx])
-            minRangeLine = self.CreateMinRange(bandValues = statistics.bands[bandIdx])
-            
-            plotGraph = plot.PlotGraphics(self.histogramLines[bandIdx] + [minRangeLine, maxRangeLine],
-                                          title = self.bandList[bandIdx])
+            self.canvasList[bandIdx].SetYSpec(type='auto')
+            histgramLine = self.CreateHistogramLine(
+                bandValues=statistics.bands[bandIdx])
+
+            meanLine = self.CreateMean(bandValues=statistics.bands[bandIdx])
+
+            minLine = self.CreateMin(bandValues=statistics.bands[bandIdx])
+
+            maxLine = self.CreateMax(bandValues=statistics.bands[bandIdx])
+
+            self.histogramLines.append(
+                [histgramLine, meanLine, minLine, maxLine])
+
+            maxRangeLine = self.CreateMaxRange(
+                bandValues=statistics.bands[bandIdx])
+            minRangeLine = self.CreateMinRange(
+                bandValues=statistics.bands[bandIdx])
+
+            plotGraph = plot.PlotGraphics(
+                self.histogramLines[bandIdx] + [minRangeLine, maxRangeLine],
+                title=self.bandList[bandIdx])
             self.canvasList[bandIdx].Draw(plotGraph)
-                            
+
     def CreateMinRange(self, bandValues):
         maxVal = max(bandValues.histo)
         rMin = bandValues.rangeMin
-        
+
         points = [(rMin, 0), (rMin, maxVal)]
-        
-        return plot.PolyLine(points, colour = wx.RED, width = 1)
-        
+
+        return plot.PolyLine(points, colour=wx.RED, width=1)
+
     def CreateMaxRange(self, bandValues):
         maxVal = max(bandValues.histo)
         rMax = bandValues.rangeMax
         points = [(rMax, 0), (rMax, maxVal)]
-        
-        return plot.PolyLine(points, colour = wx.RED, width = 1)
-        
+
+        return plot.PolyLine(points, colour=wx.RED, width=1)
+
     def CreateMean(self, bandValues):
         maxVal = max(bandValues.histo)
         mean = bandValues.mean
         points = [(mean, 0), (mean, maxVal)]
-        
-        return plot.PolyLine(points, colour = wx.BLUE, width = 1)
-        
+
+        return plot.PolyLine(points, colour=wx.BLUE, width=1)
+
     def CreateMin(self, bandValues):
         maxVal = max(bandValues.histo)
         minim = bandValues.min
         points = [(minim, 0), (minim, maxVal)]
-        
-        return plot.PolyLine(points, colour = wx.Colour(200, 200, 200), width = 1)
-        
+
+        return plot.PolyLine(points, colour=wx.Colour(200, 200, 200), width=1)
+
     def CreateMax(self, bandValues):
         maxVal = max(bandValues.histo)
         maxim = bandValues.max
         points = [(maxim, 0), (maxim, maxVal)]
-        
-        return plot.PolyLine(points, colour = wx.Colour(200, 200, 200), width = 1)
-        
+
+        return plot.PolyLine(points, colour=wx.Colour(200, 200, 200), width=1)
+
     def CreateHistogramLine(self, bandValues):
         points = []
         for cellCat, count in enumerate(bandValues.histo):
@@ -304,20 +334,22 @@
             if cellCat > bandValues.max + 5:
                 break
             points.append((cellCat, count))
-            
-        return plot.PolyLine(points, colour = wx.BLACK, width = 1)
-         
+
+        return plot.PolyLine(points, colour=wx.BLACK, width=1)
+
     def UpdateRanges(self, statistics):
         """Redraw ranges lines in histograms when std dev multiplier changes
-        
+
         :param statistics: python Statistics instance
         """
         for bandIdx in range(len(self.bandList)):
             self.canvasList[bandIdx].Clear()
-            maxRangeLine = self.CreateMaxRange(bandValues = statistics.bands[bandIdx])
-            minRangeLine = self.CreateMinRange(bandValues = statistics.bands[bandIdx])
-            
-            plotGraph = plot.PlotGraphics(self.histogramLines[bandIdx] + [minRangeLine, maxRangeLine],
-                                          title = self.bandList[bandIdx])
+            maxRangeLine = self.CreateMaxRange(
+                bandValues=statistics.bands[bandIdx])
+            minRangeLine = self.CreateMinRange(
+                bandValues=statistics.bands[bandIdx])
+
+            plotGraph = plot.PlotGraphics(
+                self.histogramLines[bandIdx] + [minRangeLine, maxRangeLine],
+                title=self.bandList[bandIdx])
             self.canvasList[bandIdx].Draw(plotGraph)
-        

Modified: grass/trunk/gui/wxpython/iclass/statistics.py
===================================================================
--- grass/trunk/gui/wxpython/iclass/statistics.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/iclass/statistics.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -30,38 +30,42 @@
 
 from grass.pydispatch.signal import Signal
 
+
 class StatisticsData:
     """Stores all statistics.
     """
+
     def __init__(self):
         self.statisticsDict = {}
         self.statisticsList = []
 
-        self.statisticsAdded = Signal("StatisticsData.statisticsAdded") 
-        self.statisticsDeleted = Signal("StatisticsData.statisticsDeleted") 
-        self.allStatisticsDeleted = Signal("StatisticsData.allStatisticsDeleted") 
+        self.statisticsAdded = Signal("StatisticsData.statisticsAdded")
+        self.statisticsDeleted = Signal("StatisticsData.statisticsDeleted")
+        self.allStatisticsDeleted = Signal(
+            "StatisticsData.allStatisticsDeleted")
 
-        self.statisticsSet = Signal("StatisticsData.statisticsSet") 
+        self.statisticsSet = Signal("StatisticsData.statisticsSet")
 
     def GetStatistics(self, cat):
         return self.statisticsDict[cat]
 
     def AddStatistics(self, cat, name, color):
         st = Statistics()
-        st.SetBaseStatistics(cat = cat, name = name, color = color)
-        st.statisticsSet.connect(lambda stats : self.statisticsSet.emit(cat = cat, 
-                                                                        stats = stats))
+        st.SetBaseStatistics(cat=cat, name=name, color=color)
+        st.statisticsSet.connect(
+            lambda stats: self.statisticsSet.emit(
+                cat=cat, stats=stats))
 
         self.statisticsDict[cat] = st
         self.statisticsList.append(cat)
 
-        self.statisticsAdded.emit(cat = cat, name = name, color = color)
+        self.statisticsAdded.emit(cat=cat, name=name, color=color)
 
     def DeleteStatistics(self, cat):
         del self.statisticsDict[cat]
         self.statisticsList.remove(cat)
 
-        self.statisticsDeleted.emit(cat = cat)
+        self.statisticsDeleted.emit(cat=cat)
 
     def GetCategories(self):
         return self.statisticsList[:]
@@ -72,13 +76,15 @@
 
         self.allStatisticsDeleted.emit()
 
+
 class Statistics:
     """Statistis conected to one class (category).
-    
+
     It is Python counterpart of similar C structure.
     But it adds some attributes or features used in wxIClass.
     It is not interface to C structure (it copies values).
     """
+
     def __init__(self):
         self.category = -1
         self.name = ""
@@ -90,19 +96,19 @@
         self.bands = []
         self.ready = False
 
-        self.statisticsSet = Signal("Statistics.statisticsSet") 
+        self.statisticsSet = Signal("Statistics.statisticsSet")
 
-    def SetReady(self, ready = True):
+    def SetReady(self, ready=True):
         self.ready = ready
-        
+
     def IsReady(self):
         return self.ready
-        
+
     def SetBaseStatistics(self, cat, name, color):
         """Sets basic (non-statistical) values.
-        
+
         .. todo::
-            Later self.name is changed but self.rasterName is not. 
+            Later self.name is changed but self.rasterName is not.
             self.rasterName should not be set by user. It can remains
             the same. But it should be done more explicitly. Currently
             it looks like unintentional feature or bug.
@@ -110,16 +116,16 @@
         self.category = cat
         self.name = name
         self.color = color
-        
-        rasterPath = grass.tempfile(create = False)
+
+        rasterPath = grass.tempfile(create=False)
         name = name.replace(' ', '_')
         self.rasterName = name + '_' + os.path.basename(rasterPath)
-        
+
     def SetFromcStatistics(self, cStatistics):
         """Sets all statistical values.
-        
+
         Copies all statistic values from \a cStattistics.
-        
+
         :param cStatistics: pointer to C statistics structure
         """
         cat = c_int()
@@ -138,12 +144,12 @@
         I_iclass_statistics_get_color(cStatistics, byref(color))
         if self.color != color.value:
             set_stats["color"] = color.value
-        
+
         nbands = c_int()
         I_iclass_statistics_get_nbands(cStatistics, byref(nbands))
         if self.nbands != nbands.value:
             set_stats["nbands"] = nbands.value
-        
+
         ncells = c_int()
         I_iclass_statistics_get_ncells(cStatistics, byref(ncells))
         if self.ncells != ncells.value:
@@ -153,19 +159,19 @@
         I_iclass_statistics_get_nstd(cStatistics, byref(nstd))
         if self.nstd != nstd.value:
             set_stats["nstd"] = nstd.value
-                
+
         self.SetStatistics(set_stats)
         self.SetBandStatistics(cStatistics)
 
     def SetBandStatistics(self, cStatistics):
         """Sets all band statistics.
-        
+
         :param cStatistics: pointer to C statistics structure
         """
         self.bands = []
         for i in range(self.nbands):
             band = BandStatistics()
-            band.SetFromcStatistics(cStatistics, index = i)
+            band.SetFromcStatistics(cStatistics, index=i)
             self.bands.append(band)
 
     def SetStatistics(self, stats):
@@ -173,24 +179,25 @@
         for st, val in stats.iteritems():
             setattr(self, st, val)
 
-        self.statisticsSet.emit(stats = stats)
+        self.statisticsSet.emit(stats=stats)
 
+
 class BandStatistics:
     """Statistis conected to one band within class (category).
-    
+
     :class:`Statistics`
     """
+
     def __init__(self):
         self.min = self.max = None
         self.rangeMin = self.rangeMax = None
         self.mean = None
         self.stddev = None
-        self.histo = [0] * 256 # max categories
-        
-        
+        self.histo = [0] * 256  # max categories
+
     def SetFromcStatistics(self, cStatistics, index):
         """Sets statistics for one band by given index.
-        
+
         :param cStatistics: pointer to C statistics structure
         :param index: index of band in C statistics structure
         """
@@ -198,19 +205,18 @@
         I_iclass_statistics_get_min(cStatistics, index, byref(min))
         I_iclass_statistics_get_max(cStatistics, index, byref(max))
         self.min, self.max = min.value, max.value
-        
+
         rangeMin, rangeMax = c_int(), c_int()
         I_iclass_statistics_get_range_min(cStatistics, index, byref(rangeMin))
         I_iclass_statistics_get_range_max(cStatistics, index, byref(rangeMax))
         self.rangeMin, self.rangeMax = rangeMin.value, rangeMax.value
-        
+
         mean, stddev = c_float(), c_float()
         I_iclass_statistics_get_mean(cStatistics, index, byref(mean))
         I_iclass_statistics_get_stddev(cStatistics, index, byref(stddev))
         self.mean, self.stddev = mean.value, stddev.value
-        
+
         histo = c_int()
         for i in range(len(self.histo)):
             I_iclass_statistics_get_histo(cStatistics, index, i, byref(histo))
             self.histo[i] = histo.value
-        

Modified: grass/trunk/gui/wxpython/iclass/toolbars.py
===================================================================
--- grass/trunk/gui/wxpython/iclass/toolbars.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/iclass/toolbars.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -29,67 +29,80 @@
 import grass.script as grass
 
 iClassIcons = {
-        'opacity' : MetaIcon(img = 'layer-opacity',
-                             label = _('Set opacity level')),
-        'classManager' : MetaIcon(img = 'table-manager',
-                                  label = _('Class manager')),
-        'selectGroup' : MetaIcon(img = 'layer-group-add',
-                                 label = _('Select imagery group')),
-        'run' : MetaIcon(img = 'execute',
-                         label = _('Run analysis, update histogram and coincidence plots')),
-        'sigFile' : MetaIcon(img = 'script-save',
-                             label = _('Save signature file for i.maxlik')),
-        'delCmd' : MetaIcon(img = 'layer-remove',
-                            label = _('Remove selected map layer')),
-        'exportAreas' : MetaIcon(img = 'layer-export',
-                            label = _('Export training areas to vector map')),
-        'importAreas' : MetaIcon(img = 'layer-import',
-                            label = _('Import training areas from vector map')),
-        'addRgb' : MetaIcon(img = 'layer-rgb-add',
-                            label = _('Add RGB map layer'))
-        }
-        
+    'opacity': MetaIcon(
+        img='layer-opacity',
+        label=_('Set opacity level')),
+    'classManager': MetaIcon(
+        img='table-manager',
+        label=_('Class manager')),
+    'selectGroup': MetaIcon(
+        img='layer-group-add',
+        label=_('Select imagery group')),
+    'run': MetaIcon(
+        img='execute',
+        label=_('Run analysis, update histogram and coincidence plots')),
+    'sigFile': MetaIcon(
+        img='script-save',
+        label=_('Save signature file for i.maxlik')),
+    'delCmd': MetaIcon(
+        img='layer-remove',
+        label=_('Remove selected map layer')),
+    'exportAreas': MetaIcon(
+        img='layer-export',
+        label=_('Export training areas to vector map')),
+    'importAreas': MetaIcon(
+        img='layer-import',
+        label=_('Import training areas from vector map')),
+    'addRgb': MetaIcon(
+        img='layer-rgb-add',
+        label=_('Add RGB map layer'))}
+
+
 class IClassMapToolbar(BaseToolbar):
     """IClass Map toolbar
     """
+
     def __init__(self, parent, toolSwitcher):
         """IClass Map toolbar constructor
         """
         BaseToolbar.__init__(self, parent, toolSwitcher)
-        
+
         self.InitToolbar(self._toolbarData())
         self._default = self.pan
-        
+
         # add tool to toggle active map window
         self.togglemapid = wx.NewId()
-        self.togglemap = wx.Choice(parent = self, id = self.togglemapid,
-                                   choices = [_('Training'), _('Preview')])
-        
+        self.togglemap = wx.Choice(parent=self, id=self.togglemapid,
+                                   choices=[_('Training'), _('Preview')])
+
         self.InsertControl(9, self.togglemap)
 
-        self.SetToolShortHelp(self.togglemapid, '%s %s %s' % (_('Set map canvas for '),
-                                                              BaseIcons["zoomBack"].GetLabel(),
-                                                              _('/ Zoom to map')))
+        self.SetToolShortHelp(
+            self.togglemapid, '%s %s %s' %
+            (_('Set map canvas for '),
+             BaseIcons["zoomBack"].GetLabel(),
+             _('/ Zoom to map')))
 
         for tool in (self.pan, self.zoomIn, self.zoomOut):
-            self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=tool)
+            self.toolSwitcher.AddToolToGroup(
+                group='mouseUse', toolbar=self, tool=tool)
         # realize the toolbar
         self.Realize()
-        
+
         self.EnableTool(self.zoomBack, False)
-        
+
     def GetActiveMapTool(self):
         """Return widget for selecting active maps"""
         return self.togglemap
-        
+
     def GetActiveMap(self):
         """Get currently selected map"""
         return self.togglemap.GetSelection()
-        
+
     def SetActiveMap(self, index):
         """Set currently selected map"""
         return self.togglemap.SetSelection(index)
-        
+
     def _toolbarData(self):
         """Toolbar data"""
         icons = BaseIcons
@@ -118,10 +131,13 @@
                                       self.parent.OnZoomBack),
                                      ("zoomToMap", icons["zoomExtent"],
                                       self.parent.OnZoomToMap)
-                                    ))
+                                     ))
+
+
 class IClassToolbar(BaseToolbar):
     """IClass toolbar
     """
+
     def __init__(self, parent, stats_data):
         """IClass toolbar constructor
         """
@@ -129,25 +145,25 @@
 
         BaseToolbar.__init__(self, parent)
         self.InitToolbar(self._toolbarData())
-        
-        self.choice = wx.Choice(parent = self, id = wx.ID_ANY, size = (110, -1))
+
+        self.choice = wx.Choice(parent=self, id=wx.ID_ANY, size=(110, -1))
         choiceid = self.InsertControl(3, self.choice)
-        
+
         self.choice.Bind(wx.EVT_CHOICE, self.OnSelectCategory)
-        
+
         # stupid workaround to insert small space between controls
-        self.InsertControl(4, wx.StaticText(self, id = wx.ID_ANY, label = ' '))
-        
-        self.combo = wx.ComboBox(self, id = wx.ID_ANY, size = (130, -1), 
-                                 style = wx.TE_PROCESS_ENTER)
+        self.InsertControl(4, wx.StaticText(self, id=wx.ID_ANY, label=' '))
+
+        self.combo = wx.ComboBox(self, id=wx.ID_ANY, size=(130, -1),
+                                 style=wx.TE_PROCESS_ENTER)
         self.InitStddev()
         comboid = self.InsertControl(5, self.combo)
-        
+
         self.EnableControls(False)
-        
+
         self.combo.Bind(wx.EVT_COMBOBOX, self.OnStdChangeSelection)
         self.combo.Bind(wx.EVT_TEXT_ENTER, self.OnStdChangeText)
-    
+
         self.stats_data.statisticsAdded.connect(self.Update)
         self.stats_data.statisticsDeleted.connect(self.Update)
         self.stats_data.allStatisticsDeleted.connect(self.Update)
@@ -155,37 +171,37 @@
 
         # realize the toolbar
         self.Realize()
-        
+
     def _toolbarData(self):
         """Toolbar data"""
         icons = iClassIcons
         return self._getToolbarData((("selectGroup", icons['selectGroup'],
-                                      lambda event : self.parent.AddBands()),
-                                      (None, ),
-                                      ("classManager", icons['classManager'],
+                                      lambda event: self.parent.AddBands()),
+                                     (None, ),
+                                     ("classManager", icons['classManager'],
                                       self.parent.OnCategoryManager),
-                                      (None, ),
-                                      ("runAnalysis", icons['run'],
+                                     (None, ),
+                                     ("runAnalysis", icons['run'],
                                       self.parent.OnRunAnalysis),
-                                      (None, ),
-                                      ("importAreas", icons['importAreas'],
+                                     (None, ),
+                                     ("importAreas", icons['importAreas'],
                                       self.parent.OnImportAreas),
-                                      ("exportAreas", icons['exportAreas'],
+                                     ("exportAreas", icons['exportAreas'],
                                       self.parent.OnExportAreas),
-                                      ("sigFile", icons['sigFile'],
+                                     ("sigFile", icons['sigFile'],
                                       self.parent.OnSaveSigFile),
-                                    ))
+                                     ))
 
     def OnMotion(self, event):
         print self.choice.GetStringSelection()
-                                
+
     def OnSelectCategory(self, event):
         idx = self.choice.GetSelection()
         cat = self.choice.GetClientData(idx)
 
         self._updateColor(cat)
-        self.parent.CategoryChanged(currentCat = cat)
-        
+        self.parent.CategoryChanged(currentCat=cat)
+
     def _updateColor(self, cat):
 
         if cat:
@@ -203,23 +219,23 @@
         self.choice.Clear()
         for name, idx in zip(catNames, catIdx):
             self.choice.Append(name, idx)
-        
+
     def GetSelectedCategoryName(self):
         return self.choice.GetStringSelection()
-        
+
     def GetSelectedCategoryIdx(self):
         idx = self.choice.GetSelection()
         if idx != wx.NOT_FOUND:
             return self.choice.GetClientData(idx)
-        
+
         return None
-        
+
     def OnStdChangeSelection(self, event):
         idx = self.combo.GetSelection()
         nstd = self.combo.GetClientData(idx)
-        
+
         self.StddevChanged(nstd)
-        
+
     def OnStdChangeText(self, event):
         val = self.combo.GetValue().strip()
         try:
@@ -229,27 +245,32 @@
                 nstd = float(val.split()[0])
             except ValueError:
                 nstd = None
-                
+
         if nstd is not None:
             self.StddevChanged(nstd)
-            
+
     def StddevChanged(self, nstd):
         idx = self.GetSelectedCategoryIdx()
         if not idx:
             return
-            
-        self.parent.StddevChanged(cat = idx, nstd = nstd)
-        
+
+        self.parent.StddevChanged(cat=idx, nstd=nstd)
+
     def UpdateStddev(self, nstd):
         self.combo.SetValue(' '.join(("%.2f" % nstd, _('std dev'))))
-        
+
     def InitStddev(self):
         for nstd in range(50, 250, 25):
             nstd /= 100.
-            self.combo.Append(item = ' '.join(("%.2f" % nstd, _('std dev'))), clientData = nstd)
-        self.combo.SetSelection(4) # 1.5
-        
-    def EnableControls(self, enable = True):
+            self.combo.Append(
+                item=' '.join(
+                    ("%.2f" %
+                     nstd,
+                     _('std dev'))),
+                clientData=nstd)
+        self.combo.SetSelection(4)  # 1.5
+
+    def EnableControls(self, enable=True):
         self.combo.Enable(enable)
         self.choice.Enable(enable)
 
@@ -261,7 +282,7 @@
         for cat in cats:
             stat = self.stats_data.GetStatistics(cat)
             catNames.append(stat.name)
-        self.SetCategories(catNames = catNames, catIdx = cats)
+        self.SetCategories(catNames=catNames, catIdx=cats)
         if name in catNames:
             self.choice.SetStringSelection(name)
             cat = self.GetSelectedCategoryIdx()
@@ -279,26 +300,28 @@
         self._updateColor(cat)
         self.parent.CategoryChanged(cat)
         # don't forget to update maps, histo, ...
-        
+
+
 class IClassMapManagerToolbar(BaseToolbar):
     """IClass toolbar
     """
+
     def __init__(self, parent, mapManager):
         """IClass toolbar constructor
         """
         BaseToolbar.__init__(self, parent)
-        
+
         self.InitToolbar(self._toolbarData())
-        self.choice = wx.Choice(parent = self, id = wx.ID_ANY, size = (300, -1))
-        
+        self.choice = wx.Choice(parent=self, id=wx.ID_ANY, size=(300, -1))
+
         self.choiceid = self.AddControl(self.choice)
-        
+
         self.choice.Bind(wx.EVT_CHOICE, self.OnSelectLayer)
-        
+
         self.mapManager = mapManager
         # realize the toolbar
         self.Realize()
-        
+
     def _toolbarData(self):
         """Toolbar data"""
         return self._getToolbarData((("addRast", BaseIcons['addRast'],
@@ -306,58 +329,63 @@
                                      ('addRgb', iClassIcons['addRgb'],
                                       self.OnAddRGB),
                                      ("delRast", iClassIcons['delCmd'],
-                                     self.OnDelRast),
+                                      self.OnDelRast),
                                      ("setOpacity", iClassIcons['opacity'],
-                                     self.OnSetOpacity),
-                                    ))
-                                    
+                                      self.OnSetOpacity),
+                                     ))
+
     def OnSelectLayer(self, event):
         layer = self.choice.GetStringSelection()
-        self.mapManager.SelectLayer(name = layer)
-        
+        self.mapManager.SelectLayer(name=layer)
+
     def OnAddRast(self, event):
-        dlg = IClassMapDialog(self, title = _("Add raster map"), element = 'raster')
+        dlg = IClassMapDialog(
+            self, title=_("Add raster map"),
+            element='raster')
         if dlg.ShowModal() == wx.ID_OK:
-            raster = grass.find_file(name = dlg.GetMap(), element = 'cell')
+            raster = grass.find_file(name=dlg.GetMap(), element='cell')
             if raster['fullname']:
-                self.mapManager.AddLayer(name = raster['fullname'])
-                
+                self.mapManager.AddLayer(name=raster['fullname'])
+
         dlg.Destroy()
-        
+
     def OnAddRGB(self, event):
         cmd = ['d.rgb']
-        GUI(parent = self.parent).ParseCommand(cmd, completed = (self.GetOptData, '', ''))
+        GUI(parent=self.parent).ParseCommand(
+            cmd, completed=(self.GetOptData, '', ''))
 
     def GetOptData(self, dcmd, layer, params, propwin):
         if dcmd:
-            self.mapManager.AddLayerRGB(cmd = dcmd)
+            self.mapManager.AddLayerRGB(cmd=dcmd)
 
     def OnDelRast(self, event):
         layer = self.choice.GetStringSelection()
         idx = self.choice.GetSelection()
         if layer:
-            self.mapManager.RemoveLayer(name = layer, idx = idx)
-            
+            self.mapManager.RemoveLayer(name=layer, idx=idx)
+
     def OnSetOpacity(self, event):
         layer = self.choice.GetStringSelection()
         idx = self.choice.GetSelection()
         if idx == wx.NOT_FOUND:
             return
-            
-        self.mapManager.SetOpacity(name = layer)
 
+        self.mapManager.SetOpacity(name=layer)
+
+
 class IClassMiscToolbar(BaseToolbar):
     """IClass toolbar
     """
+
     def __init__(self, parent):
         """IClass toolbar constructor
         """
         BaseToolbar.__init__(self, parent)
-        
+
         self.InitToolbar(self._toolbarData())
         # realize the toolbar
         self.Realize()
-        
+
     def _toolbarData(self):
         """Toolbar data"""
         icons = BaseIcons
@@ -366,4 +394,3 @@
                                      ("quit", icons['quit'],
                                       self.parent.OnCloseWindow),
                                      ))
-    

Modified: grass/trunk/gui/wxpython/icons/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/icons/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/icons/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -1 +1 @@
-all = [ "grass" ]
+all = ["grass"]

Modified: grass/trunk/gui/wxpython/icons/icon.py
===================================================================
--- grass/trunk/gui/wxpython/icons/icon.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/icons/icon.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -26,84 +26,95 @@
 
 # default icon set
 import grass_icons
-iconSetDefault  = grass_icons.iconSet
+iconSetDefault = grass_icons.iconSet
 iconPathDefault = grass_icons.iconPath
 
-iconTheme = UserSettings.Get(group = 'appearance', key = 'iconTheme', subkey = 'type')
+iconTheme = UserSettings.Get(
+    group='appearance',
+    key='iconTheme',
+    subkey='type')
 if iconTheme != 'grass':
-    sys.stderr.write(_("Unknown iconset '%s', using default 'grass'...\n") % (iconTheme))
+    sys.stderr.write(
+        _("Unknown iconset '%s', using default 'grass'...\n") %
+        (iconTheme))
 
-iconSet  = iconSetDefault
+iconSet = iconSetDefault
 iconPath = iconPathDefault
 
 # join paths
 try:
     if iconPath and not os.path.exists(iconPath):
         raise OSError
-    
+
     for key, img in iconSet.iteritems():
         if key not in iconSet or \
-                iconSet[key] is None: # add key
+                iconSet[key] is None:  # add key
             iconSet[key] = img
-        
+
         iconSet[key] = os.path.join(iconPath, iconSet[key])
-except StandardError as e:
+except Exception as e:
     sys.exit(_("Unable to load icon theme. Reason: %s. Quiting wxGUI...") % e)
-    
+
+
 class MetaIcon:
     """Handle icon metadata (image path, tooltip, ...)
     """
-    def __init__(self, img, label = None, desc = None):
+
+    def __init__(self, img, label=None, desc=None):
         self.imagepath = iconSet.get(img, wx.ART_MISSING_IMAGE)
         if not self.imagepath:
             self.type = 'unknown'
         else:
-            if self.imagepath.find ('wxART_') > -1:
+            if self.imagepath.find('wxART_') > -1:
                 self.type = 'wx'
             else:
                 self.type = 'img'
-        
+
         self.label = label
-        
+
         if desc:
             self.description = desc
         else:
             self.description = ''
-        
+
     def __str__(self):
-        return "label=%s, img=%s, type=%s" % (self.label, self.imagepath, self.type)
+        return "label=%s, img=%s, type=%s" % (
+            self.label, self.imagepath, self.type)
 
-    def GetBitmap(self, size = None):
+    def GetBitmap(self, size=None):
         bmp = None
-        
+
         if self.type == 'wx':
-            bmp = wx.ArtProvider.GetBitmap(id = self.imagepath, client = wx.ART_TOOLBAR, size = size)
+            bmp = wx.ArtProvider.GetBitmap(
+                id=self.imagepath, client=wx.ART_TOOLBAR, size=size)
         elif self.type == 'img':
-            if os.path.isfile(self.imagepath) and os.path.getsize(self.imagepath):
+            if os.path.isfile(
+                    self.imagepath) and os.path.getsize(
+                    self.imagepath):
                 if size and len(size) == 2:
-                    image = wx.Image(name = self.imagepath)
+                    image = wx.Image(name=self.imagepath)
                     image.Rescale(size[0], size[1])
                     bmp = image.ConvertToBitmap()
                 elif self.imagepath:
-                    bmp = wx.Bitmap(name = self.imagepath)
-        
+                    bmp = wx.Bitmap(name=self.imagepath)
+
         return bmp
-    
+
     def GetLabel(self):
         return self.label
 
     def GetDesc(self):
         return self.description
-    
+
     def GetImageName(self):
         return os.path.basename(self.imagepath)
 
-    def SetLabel(self, label = None, desc = None):
+    def SetLabel(self, label=None, desc=None):
         """Set label/description for icon
 
         :param label: icon label (None for no change)
         :param desc: icon description (None for no change)
-        
+
         :return: copy of original object
         """
         cobj = copy.copy(self)
@@ -111,5 +122,5 @@
             cobj.label = label
         if desc:
             cobj.description = desc
-        
+
         return cobj

Modified: grass/trunk/gui/wxpython/iscatt/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/iscatt/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/iscatt/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -6,4 +6,4 @@
     'iscatt_core',
     'toolbars',
     'core_c',
-    ]
+]

Modified: grass/trunk/gui/wxpython/iscatt/controllers.py
===================================================================
--- grass/trunk/gui/wxpython/iscatt/controllers.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/iscatt/controllers.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -25,12 +25,11 @@
 import wx
 
 
-
 from core.gcmd import GException, GError, GMessage, RunCommand, GWarning
 from core.settings import UserSettings
 from core.gthread import gThread
 from iscatt.iscatt_core import Core, idBandsToidScatt, GetRasterInfo, GetRegion, \
-MAX_SCATT_SIZE, WARN_SCATT_SIZE, MAX_NCELLS, WARN_NCELLS
+    MAX_SCATT_SIZE, WARN_SCATT_SIZE, MAX_NCELLS, WARN_NCELLS
 from iscatt.dialogs import AddScattPlotDialog, ExportCategoryRaster
 from iclass.dialogs import IClassGroupDialog
 
@@ -38,12 +37,14 @@
 
 from grass.pydispatch.signal import Signal
 
+
 class ScattsManager:
     """Main controller
     """
-    def __init__(self, guiparent, giface, iclass_mapwin = None):
+
+    def __init__(self, guiparent, giface, iclass_mapwin=None):
         self.giface = giface
-        self.mapDisp  = giface.GetMapDisplay()
+        self.mapDisp = giface.GetMapDisplay()
 
         if iclass_mapwin:
             self.mapWin = iclass_mapwin
@@ -57,15 +58,15 @@
         self.core = Core()
 
         self.cats_mgr = CategoriesManager(self, self.core)
-        self.render_mgr = PlotsRenderingManager(scatt_mgr=self, 
-                                                cats_mgr=self.cats_mgr, 
+        self.render_mgr = PlotsRenderingManager(scatt_mgr=self,
+                                                cats_mgr=self.cats_mgr,
                                                 core=self.core)
 
         self.thread = gThread()
-        
+
         self.plots = {}
 
-        self.plot_mode =  None
+        self.plot_mode = None
         self.pol_sel_mode = [False, None]
 
         self.data_set = False
@@ -77,17 +78,17 @@
 
         self.computingStarted = Signal("ScattsManager.computingStarted")
 
-        if iclass_mapwin: 
-            self.digit_conn = IClassDigitConnection(self, 
-                                                    self.mapWin, 
+        if iclass_mapwin:
+            self.digit_conn = IClassDigitConnection(self,
+                                                    self.mapWin,
                                                     self.core.CatRastUpdater())
-            self.iclass_conn = IClassConnection(self, 
-                                                iclass_mapwin.parent, 
+            self.iclass_conn = IClassConnection(self,
+                                                iclass_mapwin.parent,
                                                 self.cats_mgr)
         else:
             self.digit_conn = IMapWinDigitConnection()
-            self.iclass_conn = IMapDispConnection(scatt_mgr=self, 
-                                                  cats_mgr=self.cats_mgr, 
+            self.iclass_conn = IMapDispConnection(scatt_mgr=self,
+                                                  cats_mgr=self.cats_mgr,
                                                   giface=self.giface)
 
         self._initSettings()
@@ -95,7 +96,7 @@
         self.modeSet = Signal("ScattsManager.mondeSet")
 
     def CleanUp(self):
-        self.thread.Terminate() 
+        self.thread.Terminate()
         # there should be better way hot to clean up the thread
         # than calling the clean up function outside the thread,
         # which still may running
@@ -107,28 +108,28 @@
                 scatt['scatt'].CleanUp()
 
         self.plots.clear()
-    
+
     def _initSettings(self):
         """Initialization of settings (if not already defined)
         """
         # initializes default settings
         initSettings = [
-                        ['selection', 'sel_pol', (255,255,0)],
-                        ['selection', 'sel_pol_vertex', (255,0,0)],
-                        ['selection', 'sel_area', (0,255,19)],
-                        ['selection', "snap_tresh", 10],
-                        ['selection', 'sel_area_opacty', 50],
-                        ['ellipses', 'show_ellips', True],
-                       ]
+            ['selection', 'sel_pol', (255, 255, 0)],
+            ['selection', 'sel_pol_vertex', (255, 0, 0)],
+            ['selection', 'sel_area', (0, 255, 19)],
+            ['selection', "snap_tresh", 10],
+            ['selection', 'sel_area_opacty', 50],
+            ['ellipses', 'show_ellips', True],
+        ]
 
-        for init in initSettings: 
+        for init in initSettings:
             UserSettings.ReadSettingsFile()
-            UserSettings.Append(dict = UserSettings.userSettings, 
-                                group ='scatt',
-                                key = init[0],
-                                subkey =init[1],
-                                value = init[2],
-                                overwrite = False)
+            UserSettings.Append(dict=UserSettings.userSettings,
+                                group='scatt',
+                                key=init[0],
+                                subkey=init[1],
+                                value=init[2],
+                                overwrite=False)
 
     def SetData(self):
         self.iclass_conn.SetData()
@@ -137,13 +138,13 @@
     def SetBands(self, bands):
         self.busy = wx.BusyInfo(_("Loading data..."))
         self.data_set = False
-        self.thread.Run(callable=self.core.CleanUp, 
-                        ondone=lambda event : self.CleanUpDone())
+        self.thread.Run(callable=self.core.CleanUp,
+                        ondone=lambda event: self.CleanUpDone())
 
         if self.show_add_scatt_plot:
-            show_add=True
+            show_add = True
         else:
-            show_add=False
+            show_add = False
 
         self.all_bands_to_bands = dict(zip(bands, [-1] * len(bands)))
         self.all_bands = bands
@@ -159,7 +160,7 @@
         self.bands = bands[:]
         self.bands_info = {}
         valid_bands = []
-    
+
         for b in self.bands[:]:
             i = GetRasterInfo(b)
 
@@ -168,14 +169,14 @@
                 valid_bands.append(b)
 
         for i, b in enumerate(valid_bands):
-            # name : index in core bands - 
-            # if not in core bands (not CELL type) -> index = -1 
+            # name : index in core bands -
+            # if not in core bands (not CELL type) -> index = -1
             self.all_bands_to_bands[b] = i
 
-        self.thread.Run(callable=self.core.SetData, 
-                        bands=valid_bands, 
-                        ondone=self.SetDataDone, 
-                        userdata={"show_add" : show_add})
+        self.thread.Run(callable=self.core.SetData,
+                        bands=valid_bands,
+                        ondone=self.SetDataDone,
+                        userdata={"show_add": show_add})
 
     def SetDataDone(self, event):
         del self.busy
@@ -188,7 +189,7 @@
         self.bad_rasts = event.ret
         self.cats_mgr.SetData()
         if event.userdata['show_add']:
-          self.AddScattPlot()
+            self.AddScattPlot()
 
     def GetBands(self):
         return self.core.GetBands()
@@ -208,37 +209,39 @@
         bands = self.core.GetBands()
 
         #added_bands_ids = []
-        #for scatt_id in self.plots):
+        # for scatt_id in self.plots):
         #    added_bands_ids.append[idBandsToidScatt(scatt_id)]
 
         self.digit_conn.Update()
 
         ncells = self.region["rows"] * self.region["cols"]
         if ncells > MAX_NCELLS:
-            GError(_(parent=self.guiparent,
-                     mmessage=_("Interactive Scatter Plot Tool can not be used.\n"
-                                "Number of cells (rows*cols) <%d> in current region" 
-                                "is higher than maximum limit <%d>.\n\n"
-                                "You can reduce number of cells in current region using <g.region> command."
-                       % (ncells, MAX_NCELLS))))
+            GError(
+                _(
+                    parent=self.guiparent, mmessage=_(
+                        "Interactive Scatter Plot Tool can not be used.\n"
+                        "Number of cells (rows*cols) <%d> in current region"
+                        "is higher than maximum limit <%d>.\n\n"
+                        "You can reduce number of cells in current region using <g.region> command." %
+                        (ncells, MAX_NCELLS))))
             return
         elif ncells > WARN_NCELLS:
             dlg = wx.MessageDialog(
-                     parent=self.guiparent, 
-                     message=_("Number of cells (rows*cols) <%d> in current region is "
-                               "higher than recommended threshold <%d>.\n"
-                               "It is strongly advised to reduce number of cells "
-                               "in current region below recommend threshold.\n "
-                               "It can be done by <g.region> command.\n\n" 
-                               "Do you want to continue using "
-                               "Interactive Scatter Plot Tool with this region?" 
-                     % (ncells, WARN_NCELLS)), 
-                     style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_WARNING)
+                parent=self.guiparent,
+                message=_("Number of cells (rows*cols) <%d> in current region is "
+                          "higher than recommended threshold <%d>.\n"
+                          "It is strongly advised to reduce number of cells "
+                          "in current region below recommend threshold.\n "
+                          "It can be done by <g.region> command.\n\n"
+                          "Do you want to continue using "
+                          "Interactive Scatter Plot Tool with this region?"
+                          % (ncells, WARN_NCELLS)),
+                style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_WARNING)
             ret = dlg.ShowModal()
             if ret != wx.ID_YES:
                 return
-                
-        dlg = AddScattPlotDialog(parent=self.guiparent, 
+
+        dlg = AddScattPlotDialog(parent=self.guiparent,
                                  bands=self.all_bands,
                                  check_bands_callback=self.CheckBands)
 
@@ -259,17 +262,17 @@
                 b_2_id = self.all_bands_to_bands[self.all_bands[b_2]]
 
                 scatt_id = idBandsToidScatt(b_1_id, b_2_id, len(bands))
-                if self.plots.has_key(scatt_id):
+                if scatt_id in self.plots:
                     continue
 
-                self.plots[scatt_id] = {'transpose' : transpose,
-                                        'scatt' : None}
+                self.plots[scatt_id] = {'transpose': transpose,
+                                        'scatt': None}
                 scatt_ids.append(scatt_id)
-            
+
             self._addScattPlot(scatt_ids)
-            
+
         dlg.Destroy()
-     
+
     def CheckBands(self, b_1, b_2):
         bands = self.core.GetBands()
         added_scatts_ids = self.plots.keys()
@@ -278,15 +281,16 @@
         b_2_id = self.all_bands_to_bands[self.all_bands[b_1]]
 
         scatt_id = idBandsToidScatt(b_1_id, b_2_id, len(bands))
-        
+
         if scatt_id in added_scatts_ids:
-            GWarning(parent=self.guiparent, 
-                     message=_("Scatter plot with same band combination (regardless x y order) " 
-                               "is already displayed."))
+            GWarning(
+                parent=self.guiparent, message=_(
+                    "Scatter plot with same band combination (regardless x y order) "
+                    "is already displayed."))
             return False
 
-        b_1_name =  self.all_bands[b_1]
-        b_2_name =  self.all_bands[b_2]
+        b_1_name = self.all_bands[b_1]
+        b_2_name = self.all_bands[b_2]
 
         b_1_i = self.bands_info[b_1_name]
         b_2_i = self.bands_info[b_2_name]
@@ -296,7 +300,7 @@
             if self.bands_info[b] is None:
                 err += _("Band <%s> is not CELL (integer) type.\n" % b)
         if err:
-            GMessage(parent=self.guiparent, 
+            GMessage(parent=self.guiparent,
                      message=_("Scatter plot cannot be added.\n" + err))
             return False
 
@@ -304,27 +308,30 @@
         if mrange > MAX_SCATT_SIZE:
             GWarning(parent=self.guiparent,
                      message=_("Scatter plot cannot be added.\n"
-                               "Multiple of bands ranges <%s:%d * %s:%d = %d> " 
-                               "is higher than maximum limit <%d>.\n" 
-                                  % (b_1_name, b_1_i['range'], b_1_name, b_2_i['range'], 
+                               "Multiple of bands ranges <%s:%d * %s:%d = %d> "
+                               "is higher than maximum limit <%d>.\n"
+                               % (b_1_name, b_1_i['range'], b_1_name, b_2_i['range'],
                                   mrange, MAX_SCATT_SIZE)))
             return False
         elif mrange > WARN_SCATT_SIZE:
-            dlg = wx.MessageDialog(parent = self.guiparent,
-                     message=_("Multiple of bands ranges <%s:%d * %s:%d = %d> " 
-                               "is higher than recommended limit <%d>.\n" 
-                               "It is strongly advised to reduce range extend of bands" 
-                               "(e. g. using r.rescale) below recommended threshold.\n\n"
-                               "Do you really want to add this scatter plot?" 
-                                % (b_1_name, b_1_i['range'], b_1_name, b_2_i['range'], 
-                                   mrange, WARN_SCATT_SIZE)), 
-                     style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_WARNING)
+            dlg = wx.MessageDialog(
+                parent=self.guiparent,
+                message=_(
+                    "Multiple of bands ranges <%s:%d * %s:%d = %d> "
+                    "is higher than recommended limit <%d>.\n"
+                    "It is strongly advised to reduce range extend of bands"
+                    "(e. g. using r.rescale) below recommended threshold.\n\n"
+                    "Do you really want to add this scatter plot?" %
+                    (b_1_name, b_1_i['range'],
+                     b_1_name, b_2_i['range'],
+                     mrange, WARN_SCATT_SIZE)),
+                style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_WARNING)
             ret = dlg.ShowModal()
             if ret != wx.ID_YES:
-                return False  
+                return False
 
         return True
-        
+
     def _addScattPlot(self, scatt_ids):
         self.render_mgr.NewRunningProcess()
         self.thread.Run(callable=self.core.AddScattPlots,
@@ -338,14 +345,14 @@
         for s_id in scatt_ids:
             trans = self.plots[s_id]['transpose']
 
-            self.plots[s_id]['scatt'] = self.guiparent.NewScatterPlot(scatt_id=s_id, 
-                                                                      transpose=trans)
+            self.plots[s_id]['scatt'] = self.guiparent.NewScatterPlot(
+                scatt_id=s_id, transpose=trans)
 
             self.plots[s_id]['scatt'].plotClosed.connect(self.PlotClosed)
             self.plots[s_id]['scatt'].cursorMove.connect(
-                                        lambda x, y, scatt_id: 
-                                        self.cursorPlotMove.emit(x=x, y=y, 
-                                                                 scatt_id=scatt_id))
+                lambda x, y, scatt_id:
+                self.cursorPlotMove.emit(x=x, y=y,
+                                         scatt_id=scatt_id))
 
             if self.plot_mode:
                 self.plots[s_id]['scatt'].SetMode(self.plot_mode)
@@ -363,7 +370,7 @@
             if scatt['scatt']:
                 scatt['scatt'].SetMode(mode)
 
-        self.modeSet.emit(mode = mode)
+        self.modeSet.emit(mode=mode)
 
     def ActivateSelectionPolygonMode(self, activate):
         self.pol_sel_mode[0] = activate
@@ -371,14 +378,15 @@
             if not scatt['scatt']:
                 continue
             scatt['scatt'].SetSelectionPolygonMode(activate)
-            if not activate and self.plot_mode not in ['zoom', 'pan', 'zoom_extend']:
+            if not activate and self.plot_mode not in [
+                    'zoom', 'pan', 'zoom_extend']:
                 self.SetPlotsMode(None)
 
         self.render_mgr.RunningProcessDone()
         return activate
 
-    def ProcessSelectionPolygons(self, process_mode):        
-        scatts_polygons = {}        
+    def ProcessSelectionPolygons(self, process_mode):
+        scatts_polygons = {}
         for scatt_id, scatt in self.plots.iteritems():
             if not scatt['scatt']:
                 continue
@@ -395,13 +403,15 @@
 
         sel_cat_id = self.cats_mgr.GetSelectedCat()
         if not sel_cat_id:
-            dlg = wx.MessageDialog(parent = self.guiparent,
-                      message=_("In order to select arrea in scatter plot, "
-                                  "you have to select class first.\n\n"
-                                  "There is no class yet, "
-                                  "do you want to create one?"),
-                      caption=_("No class selected"),
-                      style = wx.YES_NO)
+            dlg = wx.MessageDialog(
+                parent=self.guiparent,
+                message=_(
+                    "In order to select arrea in scatter plot, "
+                    "you have to select class first.\n\n"
+                    "There is no class yet, "
+                    "do you want to create one?"),
+                caption=_("No class selected"),
+                style=wx.YES_NO)
             if dlg.ShowModal() == wx.ID_YES:
                 self.iclass_conn.EmptyCategories()
 
@@ -419,10 +429,10 @@
         self.render_mgr.CategoryChanged(cat_ids=[sel_cat_id])
         self.render_mgr.CategoryCondsChanged(cat_ids=[sel_cat_id])
 
-        self.thread.Run(callable = self.core.UpdateCategoryWithPolygons, 
-                        cat_id = sel_cat_id,
-                        scatts_pols = scatts_polygons,
-                        value = value, ondone=self.SetEditCatDataDone)
+        self.thread.Run(callable=self.core.UpdateCategoryWithPolygons,
+                        cat_id=sel_cat_id,
+                        scatts_pols=scatts_polygons,
+                        value=value, ondone=self.SetEditCatDataDone)
 
     def SetEditCatDataDone(self, event):
         if not self.data_set:
@@ -430,12 +440,14 @@
 
         self.render_mgr.RunningProcessDone()
         if event.exception:
-            GError(_("Error occurred during computation of scatter plot category:\n%s"), 
-                      parent = self.guiparent, showTraceback = False)
+            GError(
+                _("Error occurred during computation of scatter plot category:\n%s"),
+                parent=self.guiparent,
+                showTraceback=False)
 
         cat_id = event.ret
         self.iclass_conn.RenderCatRast(cat_id)
-            
+
     def SettingsUpdated(self, chanaged_setts):
         self.render_mgr.RenderRequest()
 
@@ -443,12 +455,14 @@
     def GetCategoriesManager(self):
         return self.cats_mgr
 
+
 class PlotsRenderingManager:
     """Manages rendering of scatter plot.
 
     .. todo::
         still space for optimalization
     """
+
     def __init__(self, scatt_mgr, cats_mgr, core):
         self.scatt_mgr = scatt_mgr
         self.cats_mgr = cats_mgr
@@ -473,10 +487,10 @@
             else:
                 for c in cat_ids:
                     if c not in self.data_to_render[scatt_id]:
-                         self.data_to_render[scatt_id].append(c) 
+                        self.data_to_render[scatt_id].append(c)
 
     def NewRunningProcess(self):
-        self.runningProcesses += 1 
+        self.runningProcesses += 1
 
     def RunningProcessDone(self):
         self.runningProcesses -= 1
@@ -497,18 +511,21 @@
             if c not in self.cat_cond_ids:
                 self.cat_cond_ids.append(c)
 
-    def RenderScattPlts(self, scatt_ids = None):
+    def RenderScattPlts(self, scatt_ids=None):
         if len(self.render_queue) > 1:
-            return 
-        
+            return
+
         self.renderingStarted.emit()
         self.render_queue.append(self.scatt_mgr.thread.GetId())
 
         cats_attrs = deepcopy(self.cats_mgr.GetCategoriesAttrs())
         cats = self.cats_mgr.GetCategories()[:]
-        self.scatt_mgr.thread.Run(callable=self._renderscattplts, scatt_ids=scatt_ids,
-                                  cats=cats, cats_attrs=cats_attrs,
-                                  ondone=self.RenderingDone)
+        self.scatt_mgr.thread.Run(
+            callable=self._renderscattplts,
+            scatt_ids=scatt_ids,
+            cats=cats,
+            cats_attrs=cats_attrs,
+            ondone=self.RenderingDone)
 
     def _renderscattplts(self, scatt_ids, cats, cats_attrs):
         cats.reverse()
@@ -522,28 +539,29 @@
 
             scatt_dt = self.scatts_dt.GetScatt(i_scatt_id)
             if self._showConfEllipses():
-                ellipses_dt = self.scatts_dt.GetEllipses(i_scatt_id, cats_attrs)
+                ellipses_dt = self.scatts_dt.GetEllipses(
+                    i_scatt_id, cats_attrs)
             else:
                 ellipses_dt = {}
 
             for c in scatt_dt.iterkeys():
                 try:
                     self.cat_ids.remove(c)
-                    scatt_dt[c]['render']=True
+                    scatt_dt[c]['render'] = True
                 except:
-                    scatt_dt[c]['render']=False
+                    scatt_dt[c]['render'] = False
 
             if self.scatt_mgr.pol_sel_mode[0]:
                 self._getSelectedAreas(cats, i_scatt_id, scatt_dt, cats_attrs)
 
             scatt['scatt'].Plot(cats_order=cats,
-                                scatts=scatt_dt, 
-                                ellipses=ellipses_dt, 
+                                scatts=scatt_dt,
+                                ellipses=ellipses_dt,
                                 styles=cats_attrs)
 
     def RenderingDone(self, event):
         self.render_queue.remove(event.pid)
-        if not self.render_queue:    
+        if not self.render_queue:
             self.renderingFinished.emit()
 
     def _getSelectedAreas(self, cats_order, scatt_id, scatt_dt, cats_attrs):
@@ -552,7 +570,7 @@
         if not cat_id:
             return
 
-        sel_a_cat_id = -1        
+        sel_a_cat_id = -1
 
         s = self.scatt_conds_dt.GetScatt(scatt_id, [cat_id])
         if not s:
@@ -560,34 +578,36 @@
 
         cats_order.append(sel_a_cat_id)
 
-        col = UserSettings.Get(group='scatt', 
-                                 key='selection', 
-                                 subkey='sel_area')
+        col = UserSettings.Get(group='scatt',
+                               key='selection',
+                               subkey='sel_area')
 
         col = ":".join(map(str, col))
-        opac = UserSettings.Get(group='scatt', 
-                                key='selection', 
+        opac = UserSettings.Get(group='scatt',
+                                key='selection',
                                 subkey='sel_area_opacty') / 100.0
 
-        cats_attrs[sel_a_cat_id] = {'color' : col,
-                                    'opacity' : opac,
-                                    'show' : True}
+        cats_attrs[sel_a_cat_id] = {'color': col,
+                                    'opacity': opac,
+                                    'show': True}
 
         scatt_dt[sel_a_cat_id] = s[cat_id]
-        
+
         scatt_dt[sel_a_cat_id]['render'] = False
         if cat_id in self.cat_cond_ids:
             scatt_dt[sel_a_cat_id]['render'] = True
             self.cat_cond_ids.remove(cat_id)
 
     def _showConfEllipses(self):
-        return UserSettings.Get(group='scatt', 
-                                key="ellipses", 
+        return UserSettings.Get(group='scatt',
+                                key="ellipses",
                                 subkey="show_ellips")
 
+
 class CategoriesManager:
     """Manages categories list of scatter plot.
     """
+
     def __init__(self, scatt_mgr, core):
 
         self.core = core
@@ -603,7 +623,7 @@
         self.initialized = Signal('CategoriesManager.initialized')
         self.setCategoryAttrs = Signal('CategoriesManager.setCategoryAttrs')
         self.deletedCategory = Signal('CategoriesManager.deletedCategory')
-        self.addedCategory = Signal('CategoriesManager.addedCategory')  
+        self.addedCategory = Signal('CategoriesManager.addedCategory')
 
     def ChangePosition(self, cat_id, new_pos):
         if new_pos >= len(self.cats_ids):
@@ -625,7 +645,7 @@
         return True
 
     def _addCategory(self, cat_id):
-        self.scatt_mgr.thread.Run(callable=self.core.AddCategory, 
+        self.scatt_mgr.thread.Run(callable=self.core.AddCategory,
                                   cat_id=cat_id)
 
     def SetData(self):
@@ -634,10 +654,10 @@
             return
 
         for cat_id in self.cats_ids:
-            self.scatt_mgr.thread.Run(callable=self.core.AddCategory, 
+            self.scatt_mgr.thread.Run(callable=self.core.AddCategory,
                                       cat_id=cat_id)
 
-    def AddCategory(self, cat_id = None, name = None, color = None, nstd = None):
+    def AddCategory(self, cat_id=None, name=None, color=None, nstd=None):
 
         if cat_id is None:
             if self.cats_ids:
@@ -646,34 +666,34 @@
                 cat_id = 1
 
         if self.scatt_mgr.data_set:
-            self.scatt_mgr.thread.Run(callable = self.core.AddCategory, 
-                                      cat_id = cat_id)
-            #TODO check number of cats
-            #if ret < 0: #TODO
+            self.scatt_mgr.thread.Run(callable=self.core.AddCategory,
+                                      cat_id=cat_id)
+            # TODO check number of cats
+            # if ret < 0: #TODO
             #    return -1;
 
         self.cats[cat_id] = {
-                                'name' : 'class_%d' % cat_id,
-                                'color' : "0:0:0",
-                                'opacity' : 1.0,
-                                'show' : True,
-                                'nstd' : 1.0,
-                            }
+            'name': 'class_%d' % cat_id,
+            'color': "0:0:0",
+            'opacity': 1.0,
+            'show': True,
+            'nstd': 1.0,
+        }
 
         self.cats_ids.insert(0, cat_id)
 
         if name is not None:
             self.cats[cat_id]["name"] = name
-   
+
         if color is not None:
             self.cats[cat_id]["color"] = color
 
         if nstd is not None:
             self.cats[cat_id]["nstd"] = nstd
 
-        self.addedCategory.emit(cat_id = cat_id,
-                                name = self.cats[cat_id]["name"], 
-                                color = self.cats[cat_id]["color"] )
+        self.addedCategory.emit(cat_id=cat_id,
+                                name=self.cats[cat_id]["name"],
+                                color=self.cats[cat_id]["color"])
         return cat_id
 
     def SetCategoryAttrs(self, cat_id, attrs_dict):
@@ -691,23 +711,24 @@
         if render:
             self.scatt_mgr.render_mgr.CategoryChanged(cat_ids=[cat_id])
             self.scatt_mgr.render_mgr.RenderRequest()
-        
+
         if update_cat_rast:
-            self.scatt_mgr.iclass_conn.UpdateCategoryRaster(cat_id, update_cat_rast)
+            self.scatt_mgr.iclass_conn.UpdateCategoryRaster(
+                cat_id, update_cat_rast)
 
-        self.setCategoryAttrs.emit(cat_id = cat_id, attrs_dict = attrs_dict)
+        self.setCategoryAttrs.emit(cat_id=cat_id, attrs_dict=attrs_dict)
 
     def DeleteCategory(self, cat_id):
 
         if self.scatt_mgr.data_set:
-            self.scatt_mgr.thread.Run(callable = self.core.DeleteCategory, 
-                                      cat_id = cat_id)
+            self.scatt_mgr.thread.Run(callable=self.core.DeleteCategory,
+                                      cat_id=cat_id)
         del self.cats[cat_id]
         self.cats_ids.remove(cat_id)
 
-        self.deletedCategory.emit(cat_id = cat_id)
+        self.deletedCategory.emit(cat_id=cat_id)
 
-    #TODO emit event?
+    # TODO emit event?
     def SetSelectedCat(self, cat_id):
         self.sel_cat_id = cat_id
         if self.scatt_mgr.pol_sel_mode[0]:
@@ -723,60 +744,66 @@
     def GetCategoriesAttrs(self):
         #TODO is mutable
         return self.cats
-     
+
     def GetCategories(self):
         return self.cats_ids[:]
 
     def SetCategoryPosition(self):
         if newindex > oldindex:
             newindex -= 1
-        
+
         self.cats_ids.insert(newindex, self.cats_ids.pop(oldindex))
 
     def ExportCatRast(self, cat_id):
 
         cat_attrs = self.GetCategoryAttrs(cat_id)
 
-        dlg = ExportCategoryRaster(parent=self.scatt_mgr.guiparent, 
-                                   rasterName=self.exportRaster, 
-                                   title=_("Export scatter plot raster of class <%s>")
-                                            % cat_attrs['name'])
-        
+        dlg = ExportCategoryRaster(
+            parent=self.scatt_mgr.guiparent,
+            rasterName=self.exportRaster,
+            title=_("Export scatter plot raster of class <%s>") %
+            cat_attrs['name'])
+
         if dlg.ShowModal() == wx.ID_OK:
             self.exportCatRast = dlg.GetRasterName()
             dlg.Destroy()
 
             self.scatt_mgr.thread.Run(callable=self.core.ExportCatRast,
-                                      userdata={'name' : cat_attrs['name']},
+                                      userdata={'name': cat_attrs['name']},
                                       cat_id=cat_id,
-                                      rast_name=self.exportCatRast, 
+                                      rast_name=self.exportCatRast,
                                       ondone=self.OnExportCatRastDone)
 
     def OnExportCatRastDone(self, event):
         ret, err = event.ret
         if ret == 0:
             cat_attrs = self.GetCategoryAttrs(event.kwds['cat_id'])
-            GMessage(_("Scatter plot raster of class <%s> exported to raster map <%s>.") % 
-                      (event.userdata['name'], event.kwds['rast_name']))
+            GMessage(
+                _("Scatter plot raster of class <%s> exported to raster map <%s>.") %
+                (event.userdata['name'], event.kwds['rast_name']))
         else:
-            GMessage(_("Export of scatter plot raster of class <%s> to map <%s> failed.\n%s") % 
-                      (event.userdata['name'], event.kwds['rast_name'], err))
+            GMessage(
+                _("Export of scatter plot raster of class <%s> to map <%s> failed.\n%s") %
+                (event.userdata['name'], event.kwds['rast_name'], err))
 
 
 class IMapWinDigitConnection:
     """Manage communication of the scatter plot with digitizer in
     mapwindow (does not work).
     """
+
     def Update(self):
         pass
 
     def SetData(self):
         pass
 
+
 class IClassDigitConnection:
     """Manages communication of the scatter plot with digitizer in
     wx.iclass.
     """
+
     def __init__(self, scatt_mgr, mapWin, scatt_rast_updater):
         self.mapWin = mapWin
         self.vectMap = None
@@ -785,19 +812,20 @@
         self.cats_mgr = scatt_mgr.cats_mgr
 
         self.cats_to_update = []
-        self.pids = {'mapwin_conn' : []}
+        self.pids = {'mapwin_conn': []}
 
         self.thread = self.scatt_mgr.thread
 
-        #TODO
-        self.mapWin.parent.toolbars["vdigit"].editingStarted.connect(self.DigitDataChanged)
+        # TODO
+        self.mapWin.parent.toolbars[
+            "vdigit"].editingStarted.connect(self.DigitDataChanged)
 
     def Update(self):
         self.thread.Run(callable=self.scatt_rast_updater.SyncWithMap)
 
     def SetData(self):
         self.cats_to_update = []
-        self.pids = {'mapwin_conn' : []}
+        self.pids = {'mapwin_conn': []}
 
     def _connectSignals(self):
         self.digit.featureAdded.connect(self.AddFeature)
@@ -814,11 +842,11 @@
         self.scatt_mgr.computingStarted.emit()
 
         self.pids['mapwin_conn'].append(self.thread.GetId())
-        self.thread.Run(callable = self.scatt_rast_updater.EditedFeature, 
-                        new_bboxs = new_bboxs, 
-                        old_bboxs = [], 
-                        old_areas_cats = [],
-                        new_areas_cats = new_areas_cats,
+        self.thread.Run(callable=self.scatt_rast_updater.EditedFeature,
+                        new_bboxs=new_bboxs,
+                        old_bboxs=[],
+                        old_areas_cats=[],
+                        new_areas_cats=new_areas_cats,
                         ondone=self.OnDone)
 
     def DeleteAreas(self, old_bboxs, old_areas_cats):
@@ -827,24 +855,25 @@
         self.scatt_mgr.computingStarted.emit()
 
         self.pids['mapwin_conn'].append(self.thread.GetId())
-        self.thread.Run(callable = self.scatt_rast_updater.EditedFeature, 
-                        new_bboxs = [], 
-                        old_bboxs = old_bboxs, 
-                        old_areas_cats = old_areas_cats,
-                        new_areas_cats = [],
+        self.thread.Run(callable=self.scatt_rast_updater.EditedFeature,
+                        new_bboxs=[],
+                        old_bboxs=old_bboxs,
+                        old_areas_cats=old_areas_cats,
+                        new_areas_cats=[],
                         ondone=self.OnDone)
 
-    def EditedFeature(self, new_bboxs, new_areas_cats, old_bboxs, old_areas_cats):
+    def EditedFeature(self, new_bboxs, new_areas_cats,
+                      old_bboxs, old_areas_cats):
         if not self.scatt_mgr.data_set:
             return
         self.scatt_mgr.computingStarted.emit()
 
         self.pids['mapwin_conn'].append(self.thread.GetId())
-        self.thread.Run(callable = self.scatt_rast_updater.EditedFeature, 
-                        new_bboxs = new_bboxs, 
-                        old_bboxs = old_bboxs, 
-                        old_areas_cats = old_areas_cats,
-                        new_areas_cats = new_areas_cats,
+        self.thread.Run(callable=self.scatt_rast_updater.EditedFeature,
+                        new_bboxs=new_bboxs,
+                        old_bboxs=old_bboxs,
+                        old_areas_cats=old_areas_cats,
+                        new_areas_cats=new_areas_cats,
                         ondone=self.OnDone)
 
     def DigitDataChanged(self, vectMap, digit):
@@ -852,7 +881,7 @@
         self.digit = digit
         self.vectMap = vectMap
 
-        self.digit.EmitSignals(emit = True)
+        self.digit.EmitSignals(emit=True)
 
         self.scatt_rast_updater.SetVectMap(vectMap)
 
@@ -864,48 +893,52 @@
         self.pids['mapwin_conn'].remove(event.pid)
         updated_cats = event.ret
         for cat in updated_cats:
-            if cat not in  self.cats_to_update:
+            if cat not in self.cats_to_update:
                 self.cats_to_update.append(cat)
 
         if not self.pids['mapwin_conn']:
-            self.thread.Run(callable = self.scatt_mgr.core.ComputeCatsScatts, 
-                            cats_ids = self.cats_to_update[:], ondone=self.Render)
+            self.thread.Run(
+                callable=self.scatt_mgr.core.ComputeCatsScatts,
+                cats_ids=self.cats_to_update[:],
+                ondone=self.Render)
             del self.cats_to_update[:]
 
     def Render(self, event):
         self.scatt_mgr.render_mgr.RenderScattPlts()
 
+
 class IMapDispConnection:
     """Manage comunication of the scatter plot with mapdisplay in mapwindow.
     """
+
     def __init__(self, scatt_mgr, cats_mgr, giface):
         self.scatt_mgr = scatt_mgr
         self.cats_mgr = cats_mgr
-        self.set_g = {'group' :  None, 'subg' :  None}
+        self.set_g = {'group': None, 'subg': None}
         self.giface = giface
         self.added_cats_rasts = {}
 
     def SetData(self):
 
-        dlg = IClassGroupDialog(self.scatt_mgr.guiparent, 
+        dlg = IClassGroupDialog(self.scatt_mgr.guiparent,
                                 group=self.set_g['group'],
                                 subgroup=self.set_g['subg'])
-        
+
         bands = []
         while True:
             if dlg.ShowModal() == wx.ID_OK:
-                
+
                 bands = dlg.GetGroupBandsErr(parent=self.scatt_mgr.guiparent)
                 if bands:
                     name, s = dlg.GetData()
-                    group = grass.find_file(name = name, element = 'group')
+                    group = grass.find_file(name=name, element='group')
                     self.set_g['group'] = group['name']
                     self.set_g['subg'] = s
 
                     break
-            else: 
+            else:
                 break
-        
+
         dlg.Destroy()
         self.added_cats_rasts = {}
 
@@ -915,10 +948,10 @@
     def EmptyCategories(self):
         return None
 
-    def UpdateCategoryRaster(self, cat_id, attrs, render = True):
+    def UpdateCategoryRaster(self, cat_id, attrs, render=True):
 
         cat_rast = self.scatt_mgr.core.GetCatRast(cat_id)
-        if not grass.find_file(cat_rast, element = 'cell', mapset = '.')['file']:
+        if not grass.find_file(cat_rast, element='cell', mapset='.')['file']:
             return
         cats_attrs = self.cats_mgr.GetCategoryAttrs(cat_id)
 
@@ -935,9 +968,9 @@
                 self.giface.updateMap.emit()
 
         if "name" in attrs:
-            #TODO hack
-            self.giface.GetLayerList()._tree.SetItemText(self.added_cats_rasts[cat_id], 
-                                                         cats_attrs['name'])
+            # TODO hack
+            self.giface.GetLayerList()._tree.SetItemText(
+                self.added_cats_rasts[cat_id], cats_attrs['name'])
             cats_attrs["name"]
 
     def RenderCatRast(self, cat_id):
@@ -946,26 +979,28 @@
             cat_rast = self.scatt_mgr.core.GetCatRast(cat_id)
 
             cat_name = self.cats_mgr.GetCategoryAttrs(cat_id)['name']
-            self.UpdateCategoryRaster(cat_id, ['color'], render = False)
+            self.UpdateCategoryRaster(cat_id, ['color'], render=False)
 
             cmd = ['d.rast', 'map=%s' % cat_rast]
-            #TODO HACK
+            # TODO HACK
             layer = self.giface.GetLayerList()._tree.AddLayer(ltype="raster",
-                                                         lname=cat_name,
-                                                         lcmd=cmd,
-                                                         lchecked=True)
+                                                              lname=cat_name,
+                                                              lcmd=cmd,
+                                                              lchecked=True)
             self.added_cats_rasts[cat_id] = layer
-        else: #TODO settings
+        else:  # TODO settings
             self.giface.updateMap.emit()
 
+
 class IClassConnection:
     """Manage comunication of the scatter plot with mapdisplay in wx.iclass.
     """
+
     def __init__(self, scatt_mgr, iclass_frame, cats_mgr):
         self.iclass_frame = iclass_frame
         self.stats_data = self.iclass_frame.stats_data
         self.cats_mgr = cats_mgr
-        self.scatt_mgr= scatt_mgr
+        self.scatt_mgr = scatt_mgr
         self.added_cats_rasts = []
 
         self.stats_data.statisticsAdded.connect(self.AddCategory)
@@ -983,7 +1018,7 @@
 
         self.SyncCats()
 
-    def UpdateCategoryRaster(self, cat_id, attrs, render = True):
+    def UpdateCategoryRaster(self, cat_id, attrs, render=True):
         if not self.scatt_mgr.data_set:
             return
 
@@ -991,7 +1026,7 @@
         if not cat_rast:
             return
 
-        if not grass.find_file(cat_rast, element = 'cell', mapset = '.')['file']:
+        if not grass.find_file(cat_rast, element='cell', mapset='.')['file']:
             return
         cats_attrs = self.cats_mgr.GetCategoryAttrs(cat_id)
         train_mgr, preview_mgr = self.iclass_frame.GetMapManagers()
@@ -1021,11 +1056,11 @@
             cat_rast = self.scatt_mgr.core.GetCatRast(cat_id)
 
             cat_name = self.cats_mgr.GetCategoryAttrs(cat_id)['name']
-            self.UpdateCategoryRaster(cat_id, ['color'], render = False)
-            train_mgr.AddLayer(cat_rast, alias = cat_name)
+            self.UpdateCategoryRaster(cat_id, ['color'], render=False)
+            train_mgr.AddLayer(cat_rast, alias=cat_name)
 
             self.added_cats_rasts.append(cat_id)
-        else: #TODO settings
+        else:  # TODO settings
             train_mgr.Render()
 
     def SetData(self):
@@ -1035,7 +1070,7 @@
     def EmptyCategories(self):
         self.iclass_frame.OnCategoryManager(None)
 
-    def SyncCats(self, cats_ids = None):
+    def SyncCats(self, cats_ids=None):
         self.cats_mgr.addedCategory.disconnect(self.AddStatistics)
         cats = self.stats_data.GetCategories()
         for c in cats:
@@ -1046,12 +1081,16 @@
         self.cats_mgr.addedCategory.connect(self.AddStatistics)
 
     def CategoryChanged(self, cat):
-        self.cats_mgr.SetSelectedCat(cat) 
+        self.cats_mgr.SetSelectedCat(cat)
 
     def AddCategory(self, cat, name, color):
         self.cats_mgr.addedCategory.disconnect(self.AddStatistics)
         stats = self.stats_data.GetStatistics(cat)
-        self.cats_mgr.AddCategory(cat_id = cat, name = name, color = color, nstd = stats.nstd)
+        self.cats_mgr.AddCategory(
+            cat_id=cat,
+            name=name,
+            color=color,
+            nstd=stats.nstd)
         self.cats_mgr.addedCategory.connect(self.AddStatistics)
 
     def DeleteCategory(self, cat):
@@ -1073,14 +1112,13 @@
         cats_attr = {}
 
         for attr in ['name', 'color', 'nstd']:
-            if stats.has_key(attr):
+            if attr in stats:
                 cats_attr[attr] = stats[attr]
 
         if cats_attr:
             self.cats_mgr.SetCategoryAttrs(cat, cats_attr)
         self.cats_mgr.setCategoryAttrs.connect(self.SetStatistics)
 
-
     def SetStatistics(self, cat_id, attrs_dict):
         self.stats_data.statisticsSet.disconnect(self.SetCategory)
         self.stats_data.GetStatistics(cat_id).SetStatistics(attrs_dict)
@@ -1102,9 +1140,9 @@
             kwargs['subgroup'] = subgroup
 
         res = RunCommand('i.group',
-                         flags = 'g',
-                         group = group,
-                         read = True, **kwargs).strip()
+                         flags='g',
+                         group=group,
+                         read=True, **kwargs).strip()
 
         if res.splitlines()[0]:
             bands = res.splitlines()

Modified: grass/trunk/gui/wxpython/iscatt/core_c.py
===================================================================
--- grass/trunk/gui/wxpython/iscatt/core_c.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/iscatt/core_c.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -24,10 +24,11 @@
 
 from core.gcmd import GException
 
+
 def Rasterize(polygon, rast, region, value):
-    rows, cols = rast.shape 
+    rows, cols = rast.shape
 
-    #TODO creating of region is on many places
+    # TODO creating of region is on many places
     region['rows'] = rows
     region['cols'] = cols
 
@@ -42,16 +43,16 @@
 
     return rast
 
+
 def ApplyColormap(vals, vals_mask, colmap, out_vals):
-    
+
     c_uint8_p = POINTER(c_uint8)
 
     vals_p = vals.ctypes.data_as(c_uint8_p)
 
-
     if hasattr(vals_mask, "ctypes"):
         vals_mask_p = vals_mask.ctypes.data_as(c_uint8_p)
-    else: #vals mask is empty (all data are selected)
+    else:  # vals mask is empty (all data are selected)
         vals_mask_p = None
     colmap_p = colmap.ctypes.data_as(c_uint8_p)
     out_vals_p = out_vals.ctypes.data_as(c_uint8_p)
@@ -59,6 +60,7 @@
     vals_size = vals.reshape((-1)).shape[0]
     I_apply_colormap(vals_p, vals_mask_p, vals_size, colmap_p, out_vals_p)
 
+
 def MergeArrays(merged_arr, overlay_arr, alpha):
     if merged_arr.shape != overlay_arr.shape:
         GException("MergeArrays: merged_arr.shape != overlay_arr.shape")
@@ -67,61 +69,89 @@
     merged_p = merged_arr.ctypes.data_as(c_uint8_p)
     overlay_p = overlay_arr.ctypes.data_as(c_uint8_p)
 
-    I_merge_arrays(merged_p, overlay_p, merged_arr.shape[0], merged_arr.shape[1], alpha)
+    I_merge_arrays(
+        merged_p,
+        overlay_p,
+        merged_arr.shape[0],
+        merged_arr.shape[1],
+        alpha)
 
-def ComputeScatts(region, scatt_conds, bands, n_bands, scatts, cats_rasts_conds, cats_rasts):
+
+def ComputeScatts(region, scatt_conds, bands, n_bands,
+                  scatts, cats_rasts_conds, cats_rasts):
     _memmapToFileNames(scatts)
     _memmapToFileNames(scatt_conds)
 
     q = Queue()
-    p = Process(target=_computeScattsProcess, args=(region, scatt_conds, bands, 
-                                                    n_bands, scatts, cats_rasts_conds, cats_rasts, q))
+    p = Process(
+        target=_computeScattsProcess,
+        args=(
+            region,
+            scatt_conds,
+            bands,
+            n_bands,
+            scatts,
+            cats_rasts_conds,
+            cats_rasts,
+            q))
     p.start()
     ret = q.get()
     p.join()
-    
+
     return ret[0], ret[1]
 
-#_memmapToFileNames and _fileNamesToMemmap are  workaround for older numpy version, 
+#_memmapToFileNames and _fileNamesToMemmap are  workaround for older numpy version,
 # where memmap objects are not pickable,
 # and therefore cannot be passed to process spawned by multiprocessing module
+
+
 def _memmapToFileNames(data):
 
-    for k, v in data.iteritems(): 
-        if v.has_key('np_vals'):
+    for k, v in data.iteritems():
+        if 'np_vals' in v:
             data[k]['np_vals'] = v['np_vals'].filename()
 
+
 def _fileNamesToMemmap(data):
-    for k, v in data.iteritems(): 
-        if v.has_key('np_vals'):
+    for k, v in data.iteritems():
+        if 'np_vals' in v:
             data[k]['np_vals'] = np.memmap(filename=v['np_vals'])
 
+
 def UpdateCatRast(patch_rast, region, cat_rast):
     q = Queue()
-    p = Process(target=_updateCatRastProcess, args=(patch_rast, region, cat_rast, q))
+    p = Process(
+        target=_updateCatRastProcess,
+        args=(
+            patch_rast,
+            region,
+            cat_rast,
+            q))
     p.start()
     ret = q.get()
     p.join()
 
     return ret
 
+
 def CreateCatRast(region, cat_rast):
     cell_head = _regionToCellHead(region)
-    I_create_cat_rast(pointer(cell_head), cat_rast)   
+    I_create_cat_rast(pointer(cell_head), cat_rast)
 
-def _computeScattsProcess(region, scatt_conds, bands, n_bands, scatts, 
+
+def _computeScattsProcess(region, scatt_conds, bands, n_bands, scatts,
                           cats_rasts_conds, cats_rasts, output_queue):
 
     _fileNamesToMemmap(scatts)
     _fileNamesToMemmap(scatt_conds)
 
-    sccats_c, cats_rasts_c, refs = _getComputationStruct(scatts, cats_rasts, 
-                                                         SC_SCATT_DATA, n_bands)
-    scatt_conds_c, cats_rasts_conds_c, refs2 = _getComputationStruct(scatt_conds, cats_rasts_conds, 
-                                                                     SC_SCATT_CONDITIONS, n_bands)
+    sccats_c, cats_rasts_c, refs = _getComputationStruct(
+        scatts, cats_rasts, SC_SCATT_DATA, n_bands)
+    scatt_conds_c, cats_rasts_conds_c, refs2 = _getComputationStruct(
+        scatt_conds, cats_rasts_conds, SC_SCATT_CONDITIONS, n_bands)
 
     char_bands = _stringListToCharArr(bands)
-   
+
     cell_head = _regionToCellHead(region)
 
     ret = I_compute_scatts(pointer(cell_head),
@@ -137,7 +167,8 @@
 
     output_queue.put((ret, scatts))
 
-def _getBandcRange( band_info):
+
+def _getBandcRange(band_info):
     band_c_range = struct_Range()
 
     band_c_range.max = band_info['max']
@@ -145,14 +176,15 @@
 
     return band_c_range
 
+
 def _regionToCellHead(region):
     cell_head = struct_Cell_head()
     G_get_window(pointer(cell_head))
 
-    convert_dict = {'n' : 'north', 'e' : 'east', 
-                    'w' : 'west',  's' : 'south', 
-                    'nsres' : 'ns_res',
-                    'ewres' : 'ew_res'}
+    convert_dict = {'n': 'north', 'e': 'east',
+                    'w': 'west', 's': 'south',
+                    'nsres': 'ns_res',
+                    'ewres': 'ew_res'}
 
     for k, v in region.iteritems():
         if k in ["rows", "cols", "cells", "zone"]:  # zone added in r65224
@@ -160,13 +192,14 @@
         else:
             v = float(v)
 
-        if convert_dict.has_key(k):
+        if k in convert_dict:
             k = convert_dict[k]
-           
+
         setattr(cell_head, k, v)
 
     return cell_head
 
+
 def _stringListToCharArr(str_list):
 
     arr = c_char_p * len(str_list)
@@ -179,56 +212,62 @@
 
     return char_arr
 
+
 def _getComputationStruct(cats, cats_rasts, cats_type, n_bands):
 
     sccats = struct_scCats()
-    I_sc_init_cats(pointer(sccats), c_int(n_bands), c_int(cats_type));
+    I_sc_init_cats(pointer(sccats), c_int(n_bands), c_int(cats_type))
 
-    refs = []        
+    refs = []
     cats_rasts_core = []
-    
+
     for cat_id, scatt_ids in cats.iteritems():
         cat_c_id = I_sc_add_cat(pointer(sccats))
         cats_rasts_core.append(cats_rasts[cat_id])
 
         for scatt_id, dt in scatt_ids.iteritems():
-            # if key is missing condition is always True (full scatter plor is computed)
-                vals = dt['np_vals']
+            # if key is missing condition is always True (full scatter plor is
+            # computed)
+            vals = dt['np_vals']
 
-                scatt_vals = scdScattData()
+            scatt_vals = scdScattData()
 
-                c_void_p = ctypes.POINTER(ctypes.c_void_p)
+            c_void_p = ctypes.POINTER(ctypes.c_void_p)
 
-                if cats_type == SC_SCATT_DATA:
-                    vals[:] = 0
-                elif cats_type == SC_SCATT_CONDITIONS:
-                    pass
-                else:
-                    return None
-                data_p = vals.ctypes.data_as(c_void_p)
-                I_scd_init_scatt_data(pointer(scatt_vals), cats_type, len(vals), data_p)
+            if cats_type == SC_SCATT_DATA:
+                vals[:] = 0
+            elif cats_type == SC_SCATT_CONDITIONS:
+                pass
+            else:
+                return None
+            data_p = vals.ctypes.data_as(c_void_p)
+            I_scd_init_scatt_data(
+                pointer(scatt_vals),
+                cats_type, len(vals),
+                data_p)
 
-                refs.append(scatt_vals)
+            refs.append(scatt_vals)
 
-                I_sc_insert_scatt_data(pointer(sccats),  
-                                       pointer(scatt_vals),
-                                       cat_c_id, scatt_id)
+            I_sc_insert_scatt_data(pointer(sccats),
+                                   pointer(scatt_vals),
+                                   cat_c_id, scatt_id)
 
     cats_rasts_c = _stringListToCharArr(cats_rasts_core)
 
     return sccats, cats_rasts_c, refs
 
+
 def _updateCatRastProcess(patch_rast, region, cat_rast, output_queue):
     cell_head = _regionToCellHead(region)
-    
-    
-    ret = I_insert_patch_to_cat_rast(patch_rast, 
-                                     pointer(cell_head), 
+
+    ret = I_insert_patch_to_cat_rast(patch_rast,
+                                     pointer(cell_head),
                                      cat_rast)
 
     output_queue.put(ret)
 
-def _rasterize(polygon, rast, region, value, output_queue):    
+
+def _rasterize(polygon, rast, region, value, output_queue):
     pol_size = len(polygon) * 2
     pol = np.array(polygon, dtype=float)
 
@@ -239,9 +278,9 @@
     rast_p = rast.ctypes.data_as(c_uint8_p)
 
     cell_h = _regionToCellHead(region)
-    I_rasterize(pol_p, 
-                len(polygon), 
-                value, 
+    I_rasterize(pol_p,
+                len(polygon),
+                value,
                 pointer(cell_h), rast_p)
 
     output_queue.put(rast)

Modified: grass/trunk/gui/wxpython/iscatt/dialogs.py
===================================================================
--- grass/trunk/gui/wxpython/iscatt/dialogs.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/iscatt/dialogs.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -32,10 +32,11 @@
 from core.settings import UserSettings
 from gui_core.dialogs import SimpleDialog
 
+
 class AddScattPlotDialog(wx.Dialog):
 
-    def __init__(self, parent, bands, check_bands_callback, id  = wx.ID_ANY):
-        wx.Dialog.__init__(self, parent, title = _("Add scatter plots"), id = id)
+    def __init__(self, parent, bands, check_bands_callback, id=wx.ID_ANY):
+        wx.Dialog.__init__(self, parent, title=_("Add scatter plots"), id=id)
 
         self.bands = bands
 
@@ -53,72 +54,90 @@
         self.labels = {}
         self.params = {}
 
-        self.band_1_label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("x axis:"))
+        self.band_1_label = wx.StaticText(
+            parent=self, id=wx.ID_ANY, label=_("x axis:"))
 
-        self.band_1_ch = wx.ComboBox(parent = self, id = wx.ID_ANY,
-                                     choices = self.bands,
-                                     style = wx.CB_READONLY, size = (350, 30))
+        self.band_1_ch = wx.ComboBox(parent=self, id=wx.ID_ANY,
+                                     choices=self.bands,
+                                     style=wx.CB_READONLY, size=(350, 30))
 
-        self.band_2_label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("y axis:"))
+        self.band_2_label = wx.StaticText(
+            parent=self, id=wx.ID_ANY, label=_("y axis:"))
 
-        self.band_2_ch = wx.ComboBox(parent = self, id = wx.ID_ANY,
-                                     choices = self.bands,
-                                     style = wx.CB_READONLY, size = (350, 30))
+        self.band_2_ch = wx.ComboBox(parent=self, id=wx.ID_ANY,
+                                     choices=self.bands,
+                                     style=wx.CB_READONLY, size=(350, 30))
 
-        self.scattsBox = wx.ListBox(parent = self,  id = wx.ID_ANY, size = (-1, 150),
-                                    style = wx.LB_MULTIPLE | wx.LB_NEEDED_SB)
+        self.scattsBox = wx.ListBox(parent=self, id=wx.ID_ANY, size=(-1, 150),
+                                    style=wx.LB_MULTIPLE | wx.LB_NEEDED_SB)
 
         # buttons
         self.btn_add = wx.Button(parent=self, id=wx.ID_ADD)
         self.btn_remove = wx.Button(parent=self, id=wx.ID_REMOVE)
-        
-        self.btn_close = wx.Button(parent=self, id=wx.ID_CANCEL)        
+
+        self.btn_close = wx.Button(parent=self, id=wx.ID_CANCEL)
         self.btn_ok = wx.Button(parent=self, id=wx.ID_OK)
 
         self._layout()
 
     def _layout(self):
 
-        border = wx.BoxSizer(wx.VERTICAL) 
+        border = wx.BoxSizer(wx.VERTICAL)
         dialogSizer = wx.BoxSizer(wx.VERTICAL)
 
         regionSizer = wx.BoxSizer(wx.HORIZONTAL)
 
-        dialogSizer.Add(item = self._addSelectSizer(title = self.band_1_label, 
-                                                    sel = self.band_1_ch))
+        dialogSizer.Add(item=self._addSelectSizer(title=self.band_1_label,
+                                                  sel=self.band_1_ch))
 
-        dialogSizer.Add(item = self._addSelectSizer(title = self.band_2_label, 
-                                                    sel = self.band_2_ch))
+        dialogSizer.Add(item=self._addSelectSizer(title=self.band_2_label,
+                                                  sel=self.band_2_ch))
 
+        dialogSizer.Add(
+            item=self.btn_add,
+            proportion=0,
+            flag=wx.TOP | wx.ALIGN_RIGHT,
+            border=5)
 
-        dialogSizer.Add(item=self.btn_add, proportion=0,  flag = wx.TOP | wx.ALIGN_RIGHT, border = 5)
-
-        box = wx.StaticBox(self, id = wx.ID_ANY,
-                           label = " %s " % _("Bands of scatter plots to be added (x y):"))
+        box = wx.StaticBox(
+            self, id=wx.ID_ANY, label=" %s " %
+            _("Bands of scatter plots to be added (x y):"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
 
-        sizer.Add(item=self.scattsBox, proportion=1, flag=wx.EXPAND | wx.TOP, border=5)
-        sizer.Add(item=self.btn_remove, proportion=0, flag=wx.TOP | wx.ALIGN_RIGHT, border = 5)
+        sizer.Add(
+            item=self.scattsBox,
+            proportion=1,
+            flag=wx.EXPAND | wx.TOP,
+            border=5)
+        sizer.Add(
+            item=self.btn_remove,
+            proportion=0,
+            flag=wx.TOP | wx.ALIGN_RIGHT,
+            border=5)
 
-        dialogSizer.Add(item=sizer, proportion=1,  flag = wx.EXPAND | wx.TOP, border = 5)
+        dialogSizer.Add(
+            item=sizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.TOP,
+            border=5)
 
         # buttons
-        self.btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
+        self.btnsizer = wx.BoxSizer(orient=wx.HORIZONTAL)
 
-        self.btnsizer.Add(item = self.btn_close, proportion = 0,
-                          flag = wx.RIGHT | wx.LEFT | wx.ALIGN_CENTER,
-                          border = 10)
-        
-        self.btnsizer.Add(item = self.btn_ok, proportion = 0,
-                          flag = wx.RIGHT | wx.LEFT | wx.ALIGN_CENTER,
-                          border = 10)
+        self.btnsizer.Add(item=self.btn_close, proportion=0,
+                          flag=wx.RIGHT | wx.LEFT | wx.ALIGN_CENTER,
+                          border=10)
 
-        dialogSizer.Add(item = self.btnsizer, proportion = 0,
-                        flag = wx.ALIGN_CENTER | wx.TOP, border = 5)
+        self.btnsizer.Add(item=self.btn_ok, proportion=0,
+                          flag=wx.RIGHT | wx.LEFT | wx.ALIGN_CENTER,
+                          border=10)
 
-        border.Add(item = dialogSizer, proportion = 0,
-                   flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 10)
+        dialogSizer.Add(item=self.btnsizer, proportion=0,
+                        flag=wx.ALIGN_CENTER | wx.TOP, border=5)
 
+        border.Add(item=dialogSizer, proportion=0,
+                   flag=wx.LEFT | wx.RIGHT | wx.BOTTOM, border=10)
+
         self.SetSizer(border)
         self.Layout()
         self.Fit()
@@ -130,28 +149,28 @@
         self.btn_remove.Bind(wx.EVT_BUTTON, self.OnRemoveLayer)
 
     def OnOk(self, event):
-        
+
         if not self.GetBands():
             GMessage(parent=self, message=_("No scatter plots selected."))
             return
 
         event.Skip()
 
-    def _addSelectSizer(self, title, sel): 
+    def _addSelectSizer(self, title, sel):
         """Helper layout function.
         """
-        selSizer = wx.BoxSizer(orient = wx.VERTICAL)
+        selSizer = wx.BoxSizer(orient=wx.VERTICAL)
 
         selTitleSizer = wx.BoxSizer(wx.HORIZONTAL)
-        selTitleSizer.Add(item = title, proportion = 1,
-                          flag = wx.TOP | wx.EXPAND, border = 5)
+        selTitleSizer.Add(item=title, proportion=1,
+                          flag=wx.TOP | wx.EXPAND, border=5)
 
-        selSizer.Add(item = selTitleSizer, proportion = 0,
-                     flag = wx.EXPAND)
+        selSizer.Add(item=selTitleSizer, proportion=0,
+                     flag=wx.EXPAND)
 
-        selSizer.Add(item = sel, proportion = 1,
-                     flag = wx.EXPAND | wx.TOP| wx.ALIGN_CENTER_VERTICAL,
-                     border = 5)
+        selSizer.Add(item=sel, proportion=1,
+                     flag=wx.EXPAND | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
+                     border=5)
 
         return selSizer
 
@@ -183,13 +202,16 @@
             GMessage(parent=self, message=_("Select both x and y bands."))
             return
         if b_y == b_x:
-            GMessage(parent=self, message=_("Selected bands must be different."))
+            GMessage(parent=self, message=_(
+                "Selected bands must be different."))
             return
 
-        if [b_x, b_y] in self.sel_bands_ids or [b_y, b_x] in self.sel_bands_ids:
-            GMessage(parent=self, 
-                     message=_("Scatter plot with same bands combination (regardless x y order) " 
-                               "has been already added into the list."))
+        if [b_x, b_y] in self.sel_bands_ids or [
+                b_y, b_x] in self.sel_bands_ids:
+            GMessage(
+                parent=self, message=_(
+                    "Scatter plot with same bands combination (regardless x y order) "
+                    "has been already added into the list."))
             return
 
         if not self.chb_callback(b_x, b_y):
@@ -205,36 +227,38 @@
         self.scattsBox.Append(text)
         event.Skip()
 
+
 class ExportCategoryRaster(wx.Dialog):
-    def __init__(self, parent, title, rasterName = None, id = wx.ID_ANY,
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
+
+    def __init__(self, parent, title, rasterName=None, id=wx.ID_ANY,
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
                  **kwargs):
         """Dialog for export of category raster.
-        
+
         :param parent: window
         :param str rasterName name of vector layer for export
         :param title: window title
         """
-        wx.Dialog.__init__(self, parent, id, title, style = style, **kwargs)
-        
+        wx.Dialog.__init__(self, parent, id, title, style=style, **kwargs)
+
         self.rasterName = rasterName
-        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
-        
-        self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
-        self.btnOK     = wx.Button(parent = self.panel, id = wx.ID_OK)
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
+        self.btnCancel = wx.Button(parent=self.panel, id=wx.ID_CANCEL)
+        self.btnOK = wx.Button(parent=self.panel, id=wx.ID_OK)
         self.btnOK.SetDefault()
         self.btnOK.Enable(False)
         self.btnOK.Bind(wx.EVT_BUTTON, self.OnOK)
-        
+
         self.__layout()
-        
+
         self.vectorNameCtrl.Bind(wx.EVT_TEXT, self.OnTextChanged)
         self.OnTextChanged(None)
         wx.CallAfter(self.vectorNameCtrl.SetFocus)
 
     def OnTextChanged(self, event):
         """Name of new vector map given.
-        
+
         Enable/diable OK button.
         """
         file = self.vectorNameCtrl.GetValue()
@@ -242,66 +266,76 @@
             self.btnOK.Enable(True)
         else:
             self.btnOK.Enable(False)
-        
+
     def __layout(self):
         """Do layout"""
         sizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         dataSizer = wx.BoxSizer(wx.VERTICAL)
-        
-        dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                           label = _("Enter name of new vector map:")),
-                      proportion = 0, flag = wx.ALL, border = 3)
-        self.vectorNameCtrl = Select(parent = self.panel, type = 'raster',
-                                     mapsets = [grass.gisenv()['MAPSET']],
-                                     size = globalvar.DIALOG_GSELECT_SIZE)
+
+        dataSizer.Add(
+            item=wx.StaticText(
+                parent=self.panel,
+                id=wx.ID_ANY,
+                label=_("Enter name of new vector map:")),
+            proportion=0,
+            flag=wx.ALL,
+            border=3)
+        self.vectorNameCtrl = Select(parent=self.panel, type='raster',
+                                     mapsets=[grass.gisenv()['MAPSET']],
+                                     size=globalvar.DIALOG_GSELECT_SIZE)
         if self.rasterName:
             self.vectorNameCtrl.SetValue(self.rasterName)
-        dataSizer.Add(item = self.vectorNameCtrl,
-                      proportion = 0, flag = wx.ALL | wx.EXPAND, border = 3)
-        
-                      
+        dataSizer.Add(item=self.vectorNameCtrl,
+                      proportion=0, flag=wx.ALL | wx.EXPAND, border=3)
+
         # buttons
         btnSizer = wx.StdDialogButtonSizer()
         btnSizer.AddButton(self.btnCancel)
         btnSizer.AddButton(self.btnOK)
         btnSizer.Realize()
-        
-        sizer.Add(item = dataSizer, proportion = 1,
-                       flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
-        
-        sizer.Add(item = btnSizer, proportion = 0,
-                       flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
-        
+
+        sizer.Add(item=dataSizer, proportion=1,
+                  flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
+
+        sizer.Add(item=btnSizer, proportion=0,
+                  flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
+
         self.panel.SetSizer(sizer)
         sizer.Fit(self)
-        
+
         self.SetMinSize(self.GetSize())
-        
+
     def GetRasterName(self):
         """Returns vector name"""
         return self.vectorNameCtrl.GetValue()
 
     def OnOK(self, event):
         """Checks if map exists and can be overwritten."""
-        overwrite = UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled')
+        overwrite = UserSettings.Get(
+            group='cmd', key='overwrite', subkey='enabled')
         rast_name = self.GetRasterName()
-        res = grass.find_file(rast_name, element = 'cell')
+        res = grass.find_file(rast_name, element='cell')
         if res['fullname'] and overwrite is False:
-            qdlg = wx.MessageDialog(parent = self,
-                                        message = _("Raster map <%s> already exists."
-                                                    " Do you want to overwrite it?" % rast_name) ,
-                                        caption = _("Raster <%s> exists" % rast_name),
-                                        style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
+            qdlg = wx.MessageDialog(
+                parent=self, message=_(
+                    "Raster map <%s> already exists."
+                    " Do you want to overwrite it?" %
+                    rast_name), caption=_(
+                    "Raster <%s> exists" %
+                    rast_name), style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
             if qdlg.ShowModal() == wx.ID_YES:
                 event.Skip()
             qdlg.Destroy()
         else:
             event.Skip()
 
+
 class SettingsDialog(wx.Dialog):
-    def __init__(self, parent, id, title, scatt_mgr, pos=wx.DefaultPosition, size=wx.DefaultSize,
-                 style=wx.DEFAULT_DIALOG_STYLE):
+
+    def __init__(
+            self, parent, id, title, scatt_mgr, pos=wx.DefaultPosition,
+            size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE):
         """Settings dialog"""
         wx.Dialog.__init__(self, parent, id, title, pos, size, style)
 
@@ -311,41 +345,45 @@
         self.parent = parent
         self.settings = {}
 
-        settsLabels = {} 
+        settsLabels = {}
 
-        self.settings["show_ellips"] = wx.CheckBox(parent = self, id=wx.ID_ANY,
-                                                   label = _('Show confidence ellipses'))
-        show_ellips = UserSettings.Get(group ='scatt', key = "ellipses", subkey = "show_ellips")
+        self.settings["show_ellips"] = wx.CheckBox(
+            parent=self, id=wx.ID_ANY, label=_('Show confidence ellipses'))
+        show_ellips = UserSettings.Get(
+            group='scatt', key="ellipses", subkey="show_ellips")
         self.settings["show_ellips"].SetValue(show_ellips)
 
-
         self.colorsSetts = {
-                            "sel_pol" : ["selection", _("Selection polygon color:")],
-                            "sel_pol_vertex" : ["selection", _("Color of selection polygon vertex:")], 
-                            "sel_area" : ["selection", _("Selected area color:")]
-                           }
+            "sel_pol": [
+                "selection", _("Selection polygon color:")], "sel_pol_vertex": [
+                "selection", _("Color of selection polygon vertex:")], "sel_area": [
+                "selection", _("Selected area color:")]}
 
         for settKey, sett in self.colorsSetts.iteritems():
-            settsLabels[settKey] = wx.StaticText(parent = self, id = wx.ID_ANY, label = sett[1])
-            col = UserSettings.Get(group ='scatt', key = sett[0], subkey = settKey)
-            self.settings[settKey] = csel.ColourSelect(parent = self, id = wx.ID_ANY,
-                                            colour = wx.Colour(col[0],
-                                                               col[1],
-                                                               col[2], 
-                                                               255))
+            settsLabels[settKey] = wx.StaticText(
+                parent=self, id=wx.ID_ANY, label=sett[1])
+            col = UserSettings.Get(group='scatt', key=sett[0], subkey=settKey)
+            self.settings[settKey] = csel.ColourSelect(
+                parent=self, id=wx.ID_ANY, colour=wx.Colour(
+                    col[0], col[1], col[2], 255))
 
         self.sizeSetts = {
-                          "snap_tresh" : ["selection", _("Snapping treshold in pixels:")],
-                          "sel_area_opacty" : ["selection", _("Selected area opacity:")]
-                         }
+            "snap_tresh": ["selection", _("Snapping treshold in pixels:")],
+            "sel_area_opacty": ["selection", _("Selected area opacity:")]
+        }
 
         for settKey, sett in self.sizeSetts.iteritems():
-            settsLabels[settKey] = wx.StaticText(parent = self, id = wx.ID_ANY, label = sett[1])
-            self.settings[settKey] = wx.SpinCtrl(parent = self, id = wx.ID_ANY, min=0, max = 100)
-            size = int(UserSettings.Get(group = 'scatt', key = sett[0], subkey = settKey))
+            settsLabels[settKey] = wx.StaticText(
+                parent=self, id=wx.ID_ANY, label=sett[1])
+            self.settings[settKey] = wx.SpinCtrl(
+                parent=self, id=wx.ID_ANY, min=0, max=100)
+            size = int(
+                UserSettings.Get(
+                    group='scatt',
+                    key=sett[0],
+                    subkey=settKey))
             self.settings[settKey].SetValue(size)
 
-
         # buttons
         self.btnSave = wx.Button(self, wx.ID_SAVE)
         self.btnApply = wx.Button(self, wx.ID_APPLY)
@@ -354,24 +392,26 @@
 
         # bindings
         self.btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
-        self.btnApply.SetToolTipString(_("Apply changes for the current session"))
+        self.btnApply.SetToolTipString(
+            _("Apply changes for the current session"))
         self.btnSave.Bind(wx.EVT_BUTTON, self.OnSave)
-        self.btnSave.SetToolTipString(_("Apply and save changes to user settings file (default for next sessions)"))
+        self.btnSave.SetToolTipString(
+            _("Apply and save changes to user settings file (default for next sessions)"))
         self.btnClose.Bind(wx.EVT_BUTTON, self.OnClose)
         self.btnClose.SetToolTipString(_("Close dialog"))
 
-        #Layout
+        # Layout
 
         # Analysis result style layout
         self.SetMinSize(self.GetBestSize())
 
         sizer = wx.BoxSizer(wx.VERTICAL)
 
-        sel_pol_box = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                                   label =" %s " % _("Selection style:"))
+        sel_pol_box = wx.StaticBox(parent=self, id=wx.ID_ANY,
+                                   label=" %s " % _("Selection style:"))
         selPolBoxSizer = wx.StaticBoxSizer(sel_pol_box, wx.VERTICAL)
 
-        gridSizer = wx.GridBagSizer(vgap = 1, hgap = 1)
+        gridSizer = wx.GridBagSizer(vgap=1, hgap=1)
 
         row = 0
         setts = dict(self.colorsSetts.items() + self.sizeSetts.items())
@@ -380,25 +420,30 @@
                       "sel_area_opacty", "snap_tresh"]
         for settKey in settsOrder:
             sett = setts[settKey]
-            gridSizer.Add(item = settsLabels[settKey], flag = wx.ALIGN_CENTER_VERTICAL, pos =(row, 0))
-            gridSizer.Add(item = self.settings[settKey],
-                          flag = wx.ALIGN_RIGHT | wx.ALL, border = 5,
-                          pos =(row, 1))  
+            gridSizer.Add(
+                item=settsLabels[settKey],
+                flag=wx.ALIGN_CENTER_VERTICAL,
+                pos=(
+                    row,
+                    0))
+            gridSizer.Add(item=self.settings[settKey],
+                          flag=wx.ALIGN_RIGHT | wx.ALL, border=5,
+                          pos=(row, 1))
             row += 1
 
         gridSizer.AddGrowableCol(1)
-        selPolBoxSizer.Add(item = gridSizer, flag = wx.EXPAND)
+        selPolBoxSizer.Add(item=gridSizer, flag=wx.EXPAND)
 
-        ell_box = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                               label =" %s " % _("Ellipses settings:"))
+        ell_box = wx.StaticBox(parent=self, id=wx.ID_ANY,
+                               label=" %s " % _("Ellipses settings:"))
         ellPolBoxSizer = wx.StaticBoxSizer(ell_box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 1, hgap = 1)
+        gridSizer = wx.GridBagSizer(vgap=1, hgap=1)
 
         sett = setts[settKey]
 
         row = 0
-        gridSizer.Add(item=self.settings["show_ellips"], 
-                      flag=wx.ALIGN_CENTER_VERTICAL, 
+        gridSizer.Add(item=self.settings["show_ellips"],
+                      flag=wx.ALIGN_CENTER_VERTICAL,
                       pos=(row, 0))
 
         gridSizer.AddGrowableCol(1)
@@ -411,11 +456,15 @@
 
         sizer.Add(item=selPolBoxSizer, flag=wx.EXPAND | wx.ALL, border=5)
         sizer.Add(item=ellPolBoxSizer, flag=wx.EXPAND | wx.ALL, border=5)
-        sizer.Add(item=btnSizer, flag=wx.EXPAND | wx.ALL, border=5, proportion=0)    
+        sizer.Add(
+            item=btnSizer,
+            flag=wx.EXPAND | wx.ALL,
+            border=5,
+            proportion=0)
 
         self.SetSizer(sizer)
         sizer.Fit(self)
-     
+
     def OnSave(self, event):
         """Button 'Save' pressed"""
         self.UpdateSettings()
@@ -429,47 +478,57 @@
 
     def UpdateSettings(self):
 
-        chanaged_setts = [];
+        chanaged_setts = []
         for settKey, sett in self.colorsSetts.iteritems():
             col = tuple(self.settings[settKey].GetColour())
-            col_s = UserSettings.Get(group='scatt', key=sett[0], subkey=settKey)
+            col_s = UserSettings.Get(
+                group='scatt', key=sett[0], subkey=settKey)
             if col_s != col:
-                UserSettings.Set(group='scatt', 
-                                 key=sett[0], 
+                UserSettings.Set(group='scatt',
+                                 key=sett[0],
                                  subkey=settKey,
                                  value=col)
                 chanaged_setts.append([settKey, sett[0]])
 
         for settKey, sett in self.sizeSetts.iteritems():
             val = self.settings[settKey].GetValue()
-            val_s = UserSettings.Get(group ='scatt', key = sett[0], subkey = settKey)
+            val_s = UserSettings.Get(
+                group='scatt', key=sett[0], subkey=settKey)
 
             if val_s != val:
-                UserSettings.Set(group = 'scatt', key = sett[0], subkey = settKey, 
-                                 value = val)
+                UserSettings.Set(group='scatt', key=sett[0], subkey=settKey,
+                                 value=val)
                 chanaged_setts.append([settKey, sett[0]])
 
         val = self.settings['show_ellips'].IsChecked()
-        val_s = UserSettings.Get(group ='scatt', key='ellipses', subkey='show_ellips')
+        val_s = UserSettings.Get(
+            group='scatt',
+            key='ellipses',
+            subkey='show_ellips')
 
         if val != val_s:
-            UserSettings.Set(group='scatt', key='ellipses', subkey='show_ellips', 
-                             value=val)
+            UserSettings.Set(
+                group='scatt',
+                key='ellipses',
+                subkey='show_ellips',
+                value=val)
             chanaged_setts.append(['ellipses', 'show_ellips'])
 
-        if chanaged_setts: 
+        if chanaged_setts:
             self.scatt_mgr.SettingsUpdated(chanaged_setts)
 
     def OnApply(self, event):
         """Button 'Apply' pressed"""
         self.UpdateSettings()
-        #self.Close()
+        # self.Close()
 
     def OnClose(self, event):
         """Button 'Cancel' pressed"""
         self.Close()
 
+
 class ManageBusyCursorMixin:
+
     def __init__(self, window):
         self.win = window
 
@@ -479,8 +538,8 @@
         self.win.Bind(wx.EVT_ENTER_WINDOW, self.OnEnter)
         self.win.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave)
 
-    def OnLeave(self, event):   
-        self.cur_inside = False     
+    def OnLeave(self, event):
+        self.cur_inside = False
         self.busy_cur = None
 
     def OnEnter(self, event):
@@ -496,15 +555,17 @@
 
         self.busy_cur = None
 
+
 class RenameClassDialog(SimpleDialog):
+
     def __init__(self, parent, old_name, title=("Change class name")):
         SimpleDialog.__init__(self, parent, title)
 
-        self.name = wx.TextCtrl(self.panel, id = wx.ID_ANY) 
+        self.name = wx.TextCtrl(self.panel, id=wx.ID_ANY)
         self.name.SetValue(old_name)
 
-        self.dataSizer.Add(self.name, proportion = 0,
-                           flag = wx.EXPAND | wx.ALL, border = 1)
+        self.dataSizer.Add(self.name, proportion=0,
+                           flag=wx.EXPAND | wx.ALL, border=1)
 
         self.panel.SetSizer(self.sizer)
         self.name.SetMinSize((200, -1))

Modified: grass/trunk/gui/wxpython/iscatt/frame.py
===================================================================
--- grass/trunk/gui/wxpython/iscatt/frame.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/iscatt/frame.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -41,44 +41,54 @@
 except ImportError:
     import wx.lib.agw.aui as aui
 
+
 class IClassIScattPanel(wx.Panel, ManageBusyCursorMixin):
-    def __init__(self, parent, giface, iclass_mapwin = None,
-                 id = wx.ID_ANY):
 
-        #wx.SplitterWindow.__init__(self, parent = parent, id = id,
+    def __init__(self, parent, giface, iclass_mapwin=None,
+                 id=wx.ID_ANY):
+
+        # wx.SplitterWindow.__init__(self, parent = parent, id = id,
         #                           style = wx.SP_LIVE_UPDATE)
-        wx.Panel.__init__(self, parent = parent, id = wx.ID_ANY)
+        wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)
         ManageBusyCursorMixin.__init__(self, window=self)
 
-        self.scatt_mgr = self._createScattMgr(guiparent=parent, giface=giface, 
+        self.scatt_mgr = self._createScattMgr(guiparent=parent, giface=giface,
                                               iclass_mapwin=iclass_mapwin)
 
         # toobars
         self.toolbars = {}
         self.toolbars['mainToolbar'] = self._createMainToolbar()
-        self.toolbars['editingToolbar'] = EditingToolbar(parent = self, scatt_mgr = self.scatt_mgr)
-        
+        self.toolbars['editingToolbar'] = EditingToolbar(
+            parent=self, scatt_mgr=self.scatt_mgr)
+
         self._createCategoryPanel(self)
 
         self.plot_panel = ScatterPlotsPanel(self, self.scatt_mgr)
 
         self.mainsizer = wx.BoxSizer(wx.VERTICAL)
-        self.mainsizer.Add(item = self.toolbars['mainToolbar'], proportion = 0, flag = wx.EXPAND)
-        self.mainsizer.Add(item = self.toolbars['editingToolbar'], proportion = 0, flag = wx.EXPAND)
-        self.mainsizer.Add(item = self.catsPanel, proportion = 0, 
-                           flag = wx.EXPAND | wx.LEFT | wx.RIGHT , border = 5)
-        self.mainsizer.Add(item = self.plot_panel, proportion = 1, flag = wx.EXPAND)
+        self.mainsizer.Add(
+            item=self.toolbars['mainToolbar'],
+            proportion=0, flag=wx.EXPAND)
+        self.mainsizer.Add(
+            item=self.toolbars['editingToolbar'],
+            proportion=0, flag=wx.EXPAND)
+        self.mainsizer.Add(item=self.catsPanel, proportion=0,
+                           flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5)
+        self.mainsizer.Add(item=self.plot_panel, proportion=1, flag=wx.EXPAND)
 
         self.catsPanel.Hide()
         self.toolbars['editingToolbar'].Hide()
 
         self.SetSizer(self.mainsizer)
-        
-        self.scatt_mgr.computingStarted.connect(lambda : self.UpdateCur(busy=True))
-        self.scatt_mgr.renderingStarted.connect(lambda : self.UpdateCur(busy=True))
-        self.scatt_mgr.renderingFinished.connect(lambda : self.UpdateCur(busy=False))
 
-        #self.SetSashGravity(0.5)
+        self.scatt_mgr.computingStarted.connect(
+            lambda: self.UpdateCur(busy=True))
+        self.scatt_mgr.renderingStarted.connect(
+            lambda: self.UpdateCur(busy=True))
+        self.scatt_mgr.renderingFinished.connect(
+            lambda: self.UpdateCur(busy=False))
+
+        # self.SetSashGravity(0.5)
         #self.SplitHorizontally(self.head_panel, self.plot_panel, -50)
         self.Layout()
 
@@ -90,15 +100,15 @@
         ManageBusyCursorMixin.UpdateCur(self, busy)
 
     def _selCatInIScatt(self):
-         return False
+        return False
 
     def _createMainToolbar(self):
-         return MainToolbar(parent = self, scatt_mgr = self.scatt_mgr)
+        return MainToolbar(parent=self, scatt_mgr=self.scatt_mgr)
 
     def _createScattMgr(self, guiparent, giface, iclass_mapwin):
-        return ScattsManager(guiparent=self, giface=giface, iclass_mapwin=iclass_mapwin)
+        return ScattsManager(guiparent=self, giface=giface,
+                             iclass_mapwin=iclass_mapwin)
 
-
     def NewScatterPlot(self, scatt_id, transpose):
         return self.plot_panel.NewScatterPlot(scatt_id, transpose)
 
@@ -108,46 +118,67 @@
 
     def ShowCategoryPanel(self, show):
         self.catsPanel.Show(show)
-        
-        #if show:
-        #    self.SetSashSize(5) 
-        #else:
+
+        # if show:
+        #    self.SetSashSize(5)
+        # else:
         #    self.SetSashSize(0)
         self.plot_panel.SetVirtualSize(self.plot_panel.GetBestVirtualSize())
         self.Layout()
 
     def _createCategoryPanel(self, parent):
         self.catsPanel = wx.Panel(parent=parent)
-        self.cats_list = CategoryListCtrl(parent=self.catsPanel, 
-                                          cats_mgr=self.scatt_mgr.GetCategoriesManager(),
-                                          sel_cats_in_iscatt=self._selCatInIScatt())
+        self.cats_list = CategoryListCtrl(
+            parent=self.catsPanel,
+            cats_mgr=self.scatt_mgr.GetCategoriesManager(),
+            sel_cats_in_iscatt=self._selCatInIScatt())
 
         self.catsPanel.SetMinSize((-1, 100))
         self.catsPanel.SetInitialSize((-1, 150))
 
         box_capt = wx.StaticBox(parent=self.catsPanel, id=wx.ID_ANY,
-                             label=' %s ' % _("Classes"),)
+                                label=' %s ' % _("Classes"),)
         catsSizer = wx.StaticBoxSizer(box_capt, wx.VERTICAL)
 
-        self.toolbars['categoryToolbar'] = self._createCategoryToolbar(self.catsPanel)
+        self.toolbars['categoryToolbar'] = self._createCategoryToolbar(
+            self.catsPanel)
 
-        catsSizer.Add(item=self.cats_list, proportion=1,  flag=wx.EXPAND | wx.TOP, border = 5)
+        catsSizer.Add(
+            item=self.cats_list,
+            proportion=1,
+            flag=wx.EXPAND | wx.TOP,
+            border=5)
         if self.toolbars['categoryToolbar']:
             catsSizer.Add(item=self.toolbars['categoryToolbar'], proportion=0)
 
         self.catsPanel.SetSizer(catsSizer)
-    
+
     def _createCategoryToolbar(self, parent):
         return CategoryToolbar(parent=parent,
-                               scatt_mgr=self.scatt_mgr, 
+                               scatt_mgr=self.scatt_mgr,
                                cats_list=self.cats_list)
 
+
 class IScattDialog(wx.Dialog):
-    def __init__(self, parent, giface, title=_("GRASS GIS Interactive Scatter Plot Tool"),
-                 id=wx.ID_ANY, style=wx.DEFAULT_FRAME_STYLE, **kwargs):
-        wx.Dialog.__init__(self, parent, id, style=style, title = title, **kwargs)
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
 
+    def __init__(
+            self, parent, giface,
+            title=_("GRASS GIS Interactive Scatter Plot Tool"),
+            id=wx.ID_ANY, style=wx.DEFAULT_FRAME_STYLE, **kwargs):
+        wx.Dialog.__init__(
+            self,
+            parent,
+            id,
+            style=style,
+            title=title,
+            **kwargs)
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass.ico'),
+                wx.BITMAP_TYPE_ICO))
+
         self.iscatt_panel = MapDispIScattPanel(self, giface)
 
         mainsizer = wx.BoxSizer(wx.VERTICAL)
@@ -161,26 +192,31 @@
 
     def OnCloseWindow(self, event):
         event.Skip()
-        #self.
+        # self.
 
+
 class MapDispIScattPanel(IClassIScattPanel):
+
     def __init__(self, parent, giface,
                  id=wx.ID_ANY, **kwargs):
         IClassIScattPanel.__init__(self, parent=parent, giface=giface,
-                                         id=id, **kwargs)
+                                   id=id, **kwargs)
 
     def _createScattMgr(self, guiparent, giface, iclass_mapwin):
-        return ScattsManager(guiparent = self, giface = giface)
+        return ScattsManager(guiparent=self, giface=giface)
 
     def _createMainToolbar(self):
-         return MainToolbar(parent = self, scatt_mgr = self.scatt_mgr, opt_tools=['add_group'])
+        return MainToolbar(
+            parent=self, scatt_mgr=self.scatt_mgr, opt_tools=['add_group'])
 
     def _selCatInIScatt(self):
-         return True
+        return True
 
+
 class ScatterPlotsPanel(scrolled.ScrolledPanel):
+
     def __init__(self, parent, scatt_mgr, id=wx.ID_ANY):
-    
+
         scrolled.ScrolledPanel.__init__(self, parent)
         self.SetupScrolling(scroll_x=False, scroll_y=True, scrollToTop=False)
 
@@ -188,10 +224,10 @@
 
         self.mainPanel = wx.Panel(parent=self, id=wx.ID_ANY)
 
-        #self._createCategoryPanel()
+        # self._createCategoryPanel()
         # Fancy gui
         self._mgr = aui.AuiManager(self.mainPanel)
-        #self._mgr.SetManagedWindow(self)
+        # self._mgr.SetManagedWindow(self)
 
         self._mgr.Update()
 
@@ -202,11 +238,11 @@
         self.Bind(aui.EVT_AUI_PANE_CLOSE, self.OnPlotPaneClosed)
 
         dlgSize = (-1, 400)
-        #self.SetBestSize(dlgSize)
-        #self.SetInitialSize(dlgSize)
+        # self.SetBestSize(dlgSize)
+        # self.SetInitialSize(dlgSize)
         self.SetAutoLayout(1)
-        #fix goutput's pane size (required for Mac OSX)
-        #if self.gwindow:         
+        # fix goutput's pane size (required for Mac OSX)
+        # if self.gwindow:
         #    self.gwindow.SetSashPosition(int(self.GetSize()[1] * .75))
         self.ignore_scroll = 0
         self.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel)
@@ -217,7 +253,7 @@
         self.scatts = {}
 
         self.Bind(wx.EVT_CLOSE, self.OnClose)
-        
+
         self.scatt_mgr.cursorPlotMove.connect(self.CursorPlotMove)
 
     def SetBusy(self, busy):
@@ -256,17 +292,18 @@
         del self.scatt_id_scatt_i[scatt_id]
         del self.scatts[scatt_id]
 
-        if pane.IsOk(): 
-          self._mgr.ClosePane(pane) 
-        self._mgr.Update() 
+        if pane.IsOk():
+            self._mgr.ClosePane(pane)
+        self._mgr.Update()
 
     def OnMouseWheel(self, event):
-        #TODO very ugly find some better solution        
+        # TODO very ugly find some better solution
         self.ignore_scroll = 3
         event.Skip()
 
     def ScrollChildIntoView(self, child):
-        #For aui manager it does not work and returns position always to the top -> deactivated.
+        # For aui manager it does not work and returns position always to the
+        # top -> deactivated.
         pass
 
     def OnPlotPaneClosed(self, event):
@@ -282,13 +319,13 @@
         else:
             event.Skip()
 
-        #wx.CallAfter(self._mgr.Update)
-        #wx.CallAfter(self.Layout)
+        # wx.CallAfter(self._mgr.Update)
+        # wx.CallAfter(self.Layout)
 
     def _doLayout(self):
 
         mainsizer = wx.BoxSizer(wx.VERTICAL)
-        mainsizer.Add(item = self.mainPanel, proportion = 1, flag = wx.EXPAND)
+        mainsizer.Add(item=self.mainPanel, proportion=1, flag=wx.EXPAND)
         self.SetSizer(mainsizer)
 
         self.Layout()
@@ -296,7 +333,7 @@
 
     def OnClose(self, event):
         """Close dialog"""
-        #TODO
+        # TODO
         print "closed"
         self.scatt_mgr.CleanUp()
         self.Destroy()
@@ -305,7 +342,7 @@
         pass
 
     def _newScatterPlotName(self, scatt_id):
-        name = self._getScatterPlotName(self.scatt_i) 
+        name = self._getScatterPlotName(self.scatt_i)
         self.scatt_id_scatt_i[scatt_id] = self.scatt_i
         self.scatt_i += 1
         return name
@@ -315,26 +352,26 @@
         return name
 
     def NewScatterPlot(self, scatt_id, transpose):
-        #TODO needs to be resolved (should be in this class)
+        # TODO needs to be resolved (should be in this class)
 
-        scatt = ScatterPlotWidget(parent = self.mainPanel, 
-                                  scatt_mgr = self.scatt_mgr, 
-                                  scatt_id = scatt_id, 
-                                  transpose = transpose)
+        scatt = ScatterPlotWidget(parent=self.mainPanel,
+                                  scatt_mgr=self.scatt_mgr,
+                                  scatt_id=scatt_id,
+                                  transpose=transpose)
         scatt.plotClosed.connect(self.ScatterPlotClosed)
         self.transpose[scatt_id] = transpose
-        
+
         caption = self._creteCaption(scatt_id)
         self._mgr.AddPane(scatt,
-                           aui.AuiPaneInfo().Dockable(True).Floatable(True).
-                           Name(self._newScatterPlotName(scatt_id)).MinSize((-1, 300)).
-                           Caption(caption).
-                           Center().Position(1).MaximizeButton(True).
-                           MinimizeButton(True).CaptionVisible(True).
-                           CloseButton(True).Layer(0))
+                          aui.AuiPaneInfo().Dockable(True).Floatable(True).
+                          Name(self._newScatterPlotName(scatt_id)).MinSize((-1, 300)).
+                          Caption(caption).
+                          Center().Position(1).MaximizeButton(True).
+                          MinimizeButton(True).CaptionVisible(True).
+                          CloseButton(True).Layer(0))
 
         self._mgr.Update()
-  
+
         self.SetVirtualSize(self.GetBestVirtualSize())
         self.Layout()
 
@@ -347,10 +384,10 @@
         transpose = self.transpose[scatt_id]
         bands = self.scatt_mgr.GetBands()
 
-        #TODO too low level
+        # TODO too low level
         b1_id, b2_id = idScattToidBands(scatt_id, len(bands))
 
-        x_b =  bands[b1_id].split('@')[0]
+        x_b = bands[b1_id].split('@')[0]
         y_b = bands[b2_id].split('@')[0]
 
         if transpose:
@@ -361,39 +398,40 @@
         return "%s x: %s y: %s" % (_("scatter plot"), x_b, y_b)
 
     def GetScattMgr(self):
-        return  self.scatt_mgr
+        return self.scatt_mgr
 
+
 class CategoryListCtrl(wx.ListCtrl,
                        listmix.ListCtrlAutoWidthMixin):
-                       #listmix.TextEditMixin):
+                       # listmix.TextEditMixin):
 
-    def __init__(self, parent, cats_mgr, sel_cats_in_iscatt, id = wx.ID_ANY):
+    def __init__(self, parent, cats_mgr, sel_cats_in_iscatt, id=wx.ID_ANY):
 
-        wx.ListCtrl.__init__(self, parent, id,
-                             style = wx.LC_REPORT|wx.LC_VIRTUAL|wx.LC_HRULES|
-                                     wx.LC_VRULES|wx.LC_SINGLE_SEL|wx.LC_NO_HEADER)
+        wx.ListCtrl.__init__(
+            self, parent, id, style=wx.LC_REPORT | wx.LC_VIRTUAL | wx.LC_HRULES |
+            wx.LC_VRULES | wx.LC_SINGLE_SEL | wx.LC_NO_HEADER)
         self.columns = ((_('Class name'), 'name'), )
-                        #(_('Color'), 'color'))
+        #(_('Color'), 'color'))
 
         self.sel_cats_in_iscatt = sel_cats_in_iscatt
 
-        self.Populate(columns = self.columns)
-        
+        self.Populate(columns=self.columns)
+
         self.cats_mgr = cats_mgr
         self.SetItemCount(len(self.cats_mgr.GetCategories()))
 
         self.rightClickedItemIdx = wx.NOT_FOUND
-        
+
         listmix.ListCtrlAutoWidthMixin.__init__(self)
 
-        #listmix.TextEditMixin.__init__(self)
-      
-        self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnCategoryRightUp) #wxMSW
-        self.Bind(wx.EVT_RIGHT_UP,            self.OnCategoryRightUp) #wxGTK
+        # listmix.TextEditMixin.__init__(self)
 
+        self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnCategoryRightUp)  # wxMSW
+        self.Bind(wx.EVT_RIGHT_UP, self.OnCategoryRightUp)  # wxGTK
+
         #self.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT, self.OnEdit)
         self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSel)
-             
+
         self.cats_mgr.setCategoryAttrs.connect(self.Update)
         self.cats_mgr.deletedCategory.connect(self.Update)
         self.cats_mgr.addedCategory.connect(self.Update)
@@ -409,24 +447,25 @@
             try:
                 text.encode('ascii')
             except UnicodeEncodeError:
-                GMessage(parent = self, message = _("Please use only ASCII characters."))
+                GMessage(parent=self, message=_(
+                    "Please use only ASCII characters."))
                 return
 
         cat_id = self.cats_mgr.GetCategories()[row]
 
         self.cats_mgr.setCategoryAttrs.disconnect(self.Update)
-        self.cats_mgr.SetCategoryAttrs(cat_id, {attr : text})
+        self.cats_mgr.SetCategoryAttrs(cat_id, {attr: text})
         self.cats_mgr.setCategoryAttrs.connect(self.Update)
-        
+
         self.Select(row)
-        
+
     def Populate(self, columns):
         for i, col in enumerate(columns):
-            self.InsertColumn(i, col[0])#wx.LIST_FORMAT_RIGHT
+            self.InsertColumn(i, col[0])  # wx.LIST_FORMAT_RIGHT
 
         #self.SetColumnWidth(0, 100)
         #self.SetColumnWidth(1, 100)
-        
+
     def AddCategory(self):
 
         self.cats_mgr.addedCategory.disconnect(self.Update)
@@ -437,35 +476,35 @@
             GError(_("Maximum limit of categories number was reached."))
             return
         self.SetItemCount(len(self.cats_mgr.GetCategories()))
-                        
+
     def DeleteCategory(self):
-        indexList = sorted(self.GetSelectedIndices(), reverse = True)
+        indexList = sorted(self.GetSelectedIndices(), reverse=True)
         cats = []
         for i in indexList:
             # remove temporary raster
             cat_id = self.cats_mgr.GetCategories()[i]
-            
+
             cats.append(cat_id)
 
             self.cats_mgr.deletedCategory.disconnect(self.Update)
             self.cats_mgr.DeleteCategory(cat_id)
             self.cats_mgr.deletedCategory.connect(self.Update)
-            
+
         self.SetItemCount(len(self.cats_mgr.GetCategories()))
-        
+
     def OnSel(self, event):
         if self.sel_cats_in_iscatt:
             indexList = self.GetSelectedIndices()
             sel_cats = []
             cats = self.cats_mgr.GetCategories()
             for i in indexList:
-                sel_cats.append(cats[i])       
+                sel_cats.append(cats[i])
 
             if sel_cats:
                 self.cats_mgr.SetSelectedCat(sel_cats[0])
         event.Skip()
 
-    def GetSelectedIndices(self, state =  wx.LIST_STATE_SELECTED):
+    def GetSelectedIndices(self, state=wx.LIST_STATE_SELECTED):
         indices = []
         lastFound = -1
         while True:
@@ -475,17 +514,17 @@
             else:
                 lastFound = index
                 indices.append(index)
-        return indices        
+        return indices
 
     def DeselectAll(self):
         """Deselect all items"""
         indexList = self.GetSelectedIndices()
         for i in indexList:
-            self.Select(i, on = 0)
-         
+            self.Select(i, on=0)
+
         # no highlight
         self.OnCategorySelected(None)
-        
+
     def OnGetItemText(self, item, col):
         attr = self.columns[col][1]
         cat_id = self.cats_mgr.GetCategories()[item]
@@ -499,17 +538,18 @@
         cat_id = self.cats_mgr.GetCategories()[item]
 
         cattr = self.cats_mgr.GetCategoryAttrs(cat_id)
-        
+
         if cattr['show']:
             c = cattr['color']
-            
+
             back_c = wx.Colour(*map(int, c.split(':')))
             text_c = wx.Colour(*ContrastColor(back_c))
         else:
             back_c = wx.SystemSettings.GetColour(wx.SYS_COLOUR_INACTIVECAPTION)
-            text_c = wx.SystemSettings.GetColour(wx.SYS_COLOUR_INACTIVECAPTIONTEXT)
+            text_c = wx.SystemSettings.GetColour(
+                wx.SYS_COLOUR_INACTIVECAPTIONTEXT)
 
-        # if it is in scope of the method, gui falls, using self solved it 
+        # if it is in scope of the method, gui falls, using self solved it
         self.l = wx.ListItemAttr(colText=text_c, colBack=back_c)
         return self.l
 
@@ -525,7 +565,7 @@
         cats = self.cats_mgr.GetCategories()
         cat_id = cats[cat_idx]
         showed = self.cats_mgr.GetCategoryAttrs(cat_id)['show']
-        
+
         menu = wx.Menu()
 
         item_id = wx.NewId()
@@ -546,13 +586,17 @@
             text = _("Show")
 
         item_id = wx.NewId()
-        menu.Append(item_id, text = text)
-        self.Bind(wx.EVT_MENU, lambda event : self._setCatAttrs(cat_id=cat_id,
-                                                                attrs={'show' : not showed}), 
-                                                                id=item_id) 
-        
+        menu.Append(item_id, text=text)
+        self.Bind(
+            wx.EVT_MENU,
+            lambda event: self._setCatAttrs(
+                cat_id=cat_id,
+                attrs={
+                    'show': not showed}),
+            id=item_id)
+
         menu.AppendSeparator()
-        
+
         item_id = wx.NewId()
         menu.Append(item_id, text=_("Move to top"))
         self.Bind(wx.EVT_MENU, self.OnMoveTop, id=item_id)
@@ -590,7 +634,7 @@
 
     def OnExportCatRast(self, event):
         """Export training areas"""
-        #TODO
+        # TODO
         #   GMessage(parent=self, message=_("No class raster to export."))
         #    return
 
@@ -632,7 +676,7 @@
         col = self.cats_mgr.GetCategoryAttrs(cat_id)['color']
         col = map(int, col.split(':'))
 
-        col_data =  wx.ColourData()
+        col_data = wx.ColourData()
         col_data.SetColour(wx.Colour(*col))
 
         dlg = wx.ColourDialog(self, col_data)
@@ -641,7 +685,7 @@
         if dlg.ShowModal() == wx.ID_OK:
             color = dlg.GetColourData().GetColour().Get()
             color = ':'.join(map(str, color))
-            self.cats_mgr.SetCategoryAttrs(cat_id, {"color" : color})
+            self.cats_mgr.SetCategoryAttrs(cat_id, {"color": color})
 
         dlg.Destroy()
 
@@ -653,16 +697,18 @@
         value = cat_attrs['opacity'] * 100
         name = cat_attrs['name']
 
-        dlg = SetOpacityDialog(self, opacity = value,
-                               title = _("Change opacity of class <%s>" % name))
+        dlg = SetOpacityDialog(self, opacity=value,
+                               title=_("Change opacity of class <%s>" % name))
 
-        dlg.applyOpacity.connect(lambda value:
-                                 self._setCatAttrs(cat_id=cat_id, attrs={'opacity' : value}))
+        dlg.applyOpacity.connect(
+            lambda value: self._setCatAttrs(
+                cat_id=cat_id, attrs={
+                    'opacity': value}))
         dlg.CentreOnParent()
 
         if dlg.ShowModal() == wx.ID_OK:
-            self._setCatAttrs(cat_id=cat_id, attrs={'opacity' : value})
-        
+            self._setCatAttrs(cat_id=cat_id, attrs={'opacity': value})
+
         dlg.Destroy()
 
     def OnRename(self, event):
@@ -676,9 +722,10 @@
             if dlg.ShowModal() == wx.ID_OK:
                 name = dlg.GetNewName().strip()
                 if not name:
-                    GMessage(parent=self, message=_("Empty name was inserted."))
+                    GMessage(parent=self, message=_(
+                        "Empty name was inserted."))
                 else:
-                    self.cats_mgr.SetCategoryAttrs(cat_id, {"name" : name})
+                    self.cats_mgr.SetCategoryAttrs(cat_id, {"name": name})
                     break
             else:
                 break

Modified: grass/trunk/gui/wxpython/iscatt/iscatt_core.py
===================================================================
--- grass/trunk/gui/wxpython/iscatt/iscatt_core.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/iscatt/iscatt_core.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -25,7 +25,7 @@
 import numpy as np
 
 # used iclass perimeters algorithm instead of convolve2d
-#from matplotlib.path import Path 
+#from matplotlib.path import Path
 #from scipy.signal import convolve2d
 
 from math import sqrt, ceil, floor
@@ -36,24 +36,27 @@
 import grass.script as grass
 
 from core_c import CreateCatRast, ComputeScatts, UpdateCatRast, \
-                   Rasterize, SC_SCATT_DATA, SC_SCATT_CONDITIONS
+    Rasterize, SC_SCATT_DATA, SC_SCATT_CONDITIONS
 
 MAX_SCATT_SIZE = 4100 * 4100
 WARN_SCATT_SIZE = 2000 * 2000
 MAX_NCELLS = 65536 * 65536
 WARN_NCELLS = 12000 * 12000
 
+
 class Core:
     """Represents scatter plot backend.
     """
+
     def __init__(self):
-        
+
         self.an_data = AnalyzedData()
 
         self.scatts_dt = ScattPlotsData(self.an_data)
         self.scatt_conds_dt = ScattPlotsCondsData(self.an_data)
 
-        self.cat_rast_updater = CatRastUpdater(self.scatts_dt, self.an_data, self)
+        self.cat_rast_updater = CatRastUpdater(
+            self.scatts_dt, self.an_data, self)
 
     def SetData(self, bands):
         """Set bands for analysis.
@@ -85,7 +88,7 @@
         return self.an_data.GetBands()
 
     def GetScattsData(self):
-        return self.scatts_dt, self.scatt_conds_dt;
+        return self.scatts_dt, self.scatt_conds_dt
 
     def GetRegion(self):
         return self.an_data.GetRegion()
@@ -94,9 +97,9 @@
         return self.scatts_dt.GetCatRast(cat_id)
 
     def AddScattPlots(self, scatt_ids):
-    
+
         for s_id in scatt_ids:
-            self.scatts_dt.AddScattPlot(scatt_id = s_id)
+            self.scatts_dt.AddScattPlot(scatt_id=s_id)
 
         cats_ids = self.scatts_dt.GetCategories()
         self.ComputeCatsScatts(cats_ids)
@@ -114,7 +117,7 @@
         for k, v in bbox.iteritems():
             bbox[k] = self._validExtend(v)
 
-        arr[bbox['btm_y'] : bbox['up_y'], bbox['btm_x'] : bbox['up_x']] = value
+        arr[bbox['btm_y']: bbox['up_y'], bbox['btm_x']: bbox['up_x']] = value
 
         self.ComputeCatsScatts([cat_id])
         return cat_id
@@ -136,12 +139,12 @@
         cats_rasts = self.scatts_dt.GetCatsRasts()
         cats_rasts_conds = self.scatts_dt.GetCatsRastsConds()
 
-        returncode, scatts = ComputeScatts(self.an_data.GetRegion(), 
-                                           scatt_conds, 
+        returncode, scatts = ComputeScatts(self.an_data.GetRegion(),
+                                           scatt_conds,
                                            bands,
-                                           len(self.GetBands()), 
-                                           scatts, 
-                                           cats_rasts_conds, 
+                                           len(self.GetBands()),
+                                           scatts,
+                                           cats_rasts_conds,
                                            cats_rasts)
 
         if returncode < 0:
@@ -149,7 +152,7 @@
 
     def CatRastUpdater(self):
         return self.cat_rast_updater
-    
+
     def UpdateCategoryWithPolygons(self, cat_id, scatts_pols, value):
         start_time = time.clock()
 
@@ -161,7 +164,7 @@
             if self.scatt_conds_dt.AddScattPlot(cat_id, scatt_id) < 0:
                 return False
 
-            b1, b2 = idScattToidBands(scatt_id, len(self.an_data.GetBands()))    
+            b1, b2 = idScattToidBands(scatt_id, len(self.an_data.GetBands()))
             b = self.scatts_dt.GetBandsInfo(scatt_id)
 
             region = {}
@@ -172,50 +175,52 @@
             region['e'] = b['b1']['max'] + 0.5
 
             arr = self.scatt_conds_dt.GetValuesArr(cat_id, scatt_id)
-            arr = Rasterize(polygon=coords, 
-                            rast=arr, 
-                            region=region, 
+            arr = Rasterize(polygon=coords,
+                            rast=arr,
+                            region=region,
                             value=value)
 
             # previous way of rasterization / used scipy
-            #raster_pol = RasterizePolygon(coords, b['b1']['range'], b['b1']['min'], 
-            #                                      b['b2']['range'], b['b2']['min'])
+            # raster_pol = RasterizePolygon(coords, b['b1']['range'], b['b1']['min'],
+            # b['b2']['range'], b['b2']['min'])
 
-            #raster_ind = np.where(raster_pol > 0) 
+            #raster_ind = np.where(raster_pol > 0)
             #arr = self.scatt_conds_dt.GetValuesArr(cat_id, scatt_id)
 
             #arr[raster_ind] = value
-            #arr.flush()
-        
+            # arr.flush()
+
         self.ComputeCatsScatts([cat_id])
         return cat_id
 
     def ExportCatRast(self, cat_id, rast_name):
 
-        cat_rast = self.scatts_dt.GetCatRast(cat_id);
+        cat_rast = self.scatts_dt.GetCatRast(cat_id)
         if not cat_rast:
             return 1
-        
-        return RunCommand("g.copy", 
+
+        return RunCommand("g.copy",
                           raster=cat_rast + ',' + rast_name,
                           getErrorMsg=True,
                           overwrite=True)
 
     def _validExtend(self, val):
-        #TODO do it general
-        if  val > 255:
+        # TODO do it general
+        if val > 255:
             val = 255
         elif val < 0:
             val = 0
 
         return val
 
+
 class CatRastUpdater:
     """Update backend data structures according to selected areas in mapwindow.
     """
+
     def __init__(self, scatts_dt, an_data, core):
         self.scatts_dt = scatts_dt
-        self.an_data = an_data # TODO may be confusing
+        self.an_data = an_data  # TODO may be confusing
         self.core = core
         self.vectMap = None
 
@@ -223,7 +228,8 @@
         self.vectMap = vectMap
 
     def SyncWithMap(self):
-        #TODO possible optimization - bbox only of vertex and its two neighbours
+        # TODO possible optimization - bbox only of vertex and its two
+        # neighbours
 
         region = self.an_data.GetRegion()
 
@@ -238,23 +244,25 @@
         for cat_id in self.scatts_dt.GetCategories():
             if cat_id == 0:
                 continue
-            
-            cat = [{1 : [cat_id]}]
+
+            cat = [{1: [cat_id]}]
             self._updateCatRast(bbox, cat, updated_cats)
 
         return updated_cats
 
-    def EditedFeature(self, new_bboxs, new_areas_cats, old_bboxs, old_areas_cats):
-        #TODO possible optimization - bbox only of vertex and its two neighbours
+    def EditedFeature(self, new_bboxs, new_areas_cats,
+                      old_bboxs, old_areas_cats):
+        # TODO possible optimization - bbox only of vertex and its two
+        # neighbours
 
         bboxs = old_bboxs + new_bboxs
-        areas_cats = old_areas_cats + new_areas_cats 
+        areas_cats = old_areas_cats + new_areas_cats
 
         updated_cats = []
 
         for i in range(len(areas_cats)):
             self._updateCatRast(bboxs[i], areas_cats[i], updated_cats)
-        
+
         return updated_cats
 
     def _updateCatRast(self, bbox, areas_cats, updated_cats):
@@ -266,7 +274,7 @@
                 continue
 
             layer = areas_cats[c].keys()[0]
-            cat =  areas_cats[c][layer][0]
+            cat = areas_cats[c][layer][0]
 
             if cat in rasterized_cats:
                 continue
@@ -276,34 +284,38 @@
 
             grass_region = self._create_grass_region_env(bbox)
 
-            #TODO hack check if raster exists?
+            # TODO hack check if raster exists?
             patch_rast = "temp_scatt_patch_%d" % (os.getpid())
             self._rasterize(grass_region, layer, cat, patch_rast)
 
             region = self.an_data.GetRegion()
-            ret = UpdateCatRast(patch_rast, region, self.scatts_dt.GetCatRastCond(cat))
+            ret = UpdateCatRast(
+                patch_rast,
+                region,
+                self.scatts_dt.GetCatRastCond(cat))
             if ret < 0:
-                GException(_("Patching category raster conditions file failed."))            
+                GException(
+                    _("Patching category raster conditions file failed."))
             RunCommand("g.remove", flags='f', type='raster', name=patch_rast)
 
     def _rasterize(self, grass_region, layer, cat, out_rast):
 
-        #TODO different thread may be problem when user edits map
+        # TODO different thread may be problem when user edits map
         environs = os.environ.copy()
         environs['GRASS_VECTOR_TEMPORARY'] = '1'
 
         ret, text, msg = RunCommand("v.category",
                                     input=self.vectMap,
-                                    getErrorMsg = True,
+                                    getErrorMsg=True,
                                     option='report',
                                     read=True,
                                     env=environs)
 
         ret, text, msg = RunCommand("v.build",
-                                    map = self.vectMap,
-                                    getErrorMsg = True,
-                                    read = True,
-                                    env = environs)
+                                    map=self.vectMap,
+                                    getErrorMsg=True,
+                                    read=True,
+                                    env=environs)
 
         if ret != 0:
             GException(_("v.build failed:\n%s" % msg))
@@ -313,15 +325,15 @@
         environs['GRASS_VECTOR_TEMPORARY'] = '1'
 
         ret, text, msg = RunCommand("v.to.rast",
-                                    input = self.vectMap,
-                                    use = "cat",
-                                    layer = str(layer),
-                                    cat = str(cat),
-                                    output = out_rast,
-                                    getErrorMsg = True,
-                                    read = True,
-                                    overwrite = True,
-                                    env = environs)
+                                    input=self.vectMap,
+                                    use="cat",
+                                    layer=str(layer),
+                                    cat=str(cat),
+                                    output=out_rast,
+                                    getErrorMsg=True,
+                                    read=True,
+                                    overwrite=True,
+                                    env=environs)
 
         if ret != 0:
             GException(_("v.to.rast failed:\n%s" % msg))
@@ -336,40 +348,46 @@
         elif bbox["maxy"] >= r["n"]:
             new_r["n"] = bbox["maxy"]
         else:
-            new_r["n"] = ceil((bbox["maxy"] - r["s"]) / r["nsres"]) * r["nsres"] + r["s"]
+            new_r["n"] = ceil(
+                (bbox["maxy"] - r["s"]) / r["nsres"]) * r["nsres"] + r["s"]
 
         if bbox["miny"] >= r["n"]:
             return 0
         elif bbox["miny"] <= r["s"]:
             new_r["s"] = bbox["miny"]
         else:
-            new_r["s"] = floor((bbox["miny"] - r["s"]) / r["nsres"]) * r["nsres"] + r["s"]
+            new_r["s"] = floor(
+                (bbox["miny"] - r["s"]) / r["nsres"]) * r["nsres"] + r["s"]
 
         if bbox["maxx"] <= r["w"]:
             return 0
         elif bbox["maxx"] >= r["e"]:
             new_r["e"] = bbox["maxx"]
         else:
-            new_r["e"] = ceil((bbox["maxx"] - r["w"]) / r["ewres"]) * r["ewres"] + r["w"]
+            new_r["e"] = ceil(
+                (bbox["maxx"] - r["w"]) / r["ewres"]) * r["ewres"] + r["w"]
 
         if bbox["minx"] >= r["e"]:
             return 0
         elif bbox["minx"] <= r["w"]:
             new_r["w"] = bbox["minx"]
         else:
-            new_r["w"] = floor((bbox["minx"] - r["w"]) / r["ewres"]) * r["ewres"] + r["w"]
+            new_r["w"] = floor(
+                (bbox["minx"] - r["w"]) / r["ewres"]) * r["ewres"] + r["w"]
 
-        #TODO check regions resolution
+        # TODO check regions resolution
         new_r["nsres"] = r["nsres"]
         new_r["ewres"] = r["ewres"]
 
-        return {"GRASS_REGION" :  grass.region_env(**new_r)}
+        return {"GRASS_REGION": grass.region_env(**new_r)}
 
+
 class AnalyzedData:
     """Represents analyzed data (bands, region).
     """
+
     def __init__(self):
-        
+
         self.bands = []
         self.bands_info = {}
 
@@ -393,9 +411,9 @@
 
             if i is None:
                 GException("raster %s is not CELL type" % (b))
-    
+
             self.bands_info[b] = i
-            #TODO check size of raster
+            # TODO check size of raster
 
         return True
 
@@ -406,22 +424,24 @@
         band = self.bands[band_id]
         return self.bands_info[band]
 
+
 class ScattPlotsCondsData:
     """Data structure for selected areas in scatter plot(condtions).
     """
+
     def __init__(self, an_data):
 
         self.an_data = an_data
 
-        #TODO
+        # TODO
         self.max_n_cats = 10
-    
+
         self.dtype = 'uint8'
-        self.type = 1;
+        self.type = 1
         self.CleanUp()
 
     def CleanUp(self):
-    
+
         self.cats = {}
 
         self.n_scatts = -1
@@ -434,10 +454,10 @@
 
         self.CleanUp()
 
-        self.n_scatts =  (n_bands - 1) * n_bands / 2;
+        self.n_scatts = (n_bands - 1) * n_bands / 2
         self.n_bands = n_bands
 
-        self.AddCategory(cat_id = 0)
+        self.AddCategory(cat_id=0)
 
     def AddCategory(self, cat_id):
 
@@ -464,27 +484,36 @@
 
     def GetCatScatts(self, cat_id):
 
-        if not self.cats.has_key(cat_id):
+        if cat_id not in self.cats:
             return False
 
         return self.cats[cat_id].keys()
 
-
     def AddScattPlot(self, cat_id, scatt_id):
 
-        if not self.cats.has_key(cat_id):
+        if cat_id not in self.cats:
             return -1
 
-        if self.cats[cat_id].has_key(scatt_id):
+        if scatt_id in self.cats[cat_id]:
             return 0
 
         b_i = self.GetBandsInfo(scatt_id)
 
-        shape = (b_i['b2']['max'] - b_i['b2']['min'] + 1, b_i['b1']['max'] - b_i['b1']['min'] + 1)
+        shape = (
+            b_i['b2']['max'] -
+            b_i['b2']['min'] +
+            1,
+            b_i['b1']['max'] -
+            b_i['b1']['min'] +
+            1)
 
-        np_vals = np.memmap(grass.tempfile(), dtype=self.dtype, mode='w+', shape=shape)
+        np_vals = np.memmap(
+            grass.tempfile(),
+            dtype=self.dtype,
+            mode='w+',
+            shape=shape)
 
-        self.cats[cat_id][scatt_id] = {'np_vals' : np_vals}
+        self.cats[cat_id][scatt_id] = {'np_vals': np_vals}
 
         return 1
 
@@ -494,17 +523,17 @@
         b1_info = self.an_data.GetBandInfo(b1)
         b2_info = self.an_data.GetBandInfo(b2)
 
-        bands_info = {'b1' : b1_info,
-                      'b2' : b2_info}
+        bands_info = {'b1': b1_info,
+                      'b2': b2_info}
 
         return bands_info
 
     def DeleScattPlot(self, cat_id, scatt_id):
 
-        if not self.cats.has_key(cat_id):
+        if cat_id not in self.cats:
             return False
 
-        if not self.cats[cat_id].has_key(scatt_id):
+        if scatt_id not in self.cats[cat_id]:
             return False
 
         del self.cats[cat_id][scatt_id]
@@ -512,63 +541,68 @@
 
     def GetValuesArr(self, cat_id, scatt_id):
 
-        if not self.cats.has_key(cat_id):
+        if cat_id not in self.cats:
             return None
 
-        if not self.cats[cat_id].has_key(scatt_id):
+        if scatt_id not in self.cats[cat_id]:
             return None
 
         return self.cats[cat_id][scatt_id]['np_vals']
 
     def GetData(self, requested_dt):
-        
+
         cats = {}
         for cat_id, scatt_ids in requested_dt.iteritems():
-            if not cats.has_key(cat_id):
+            if cat_id not in cats:
                 cats[cat_id] = {}
             for scatt_id in scatt_ids:
-                # if key is missing condition is always True (full scatter plor is computed)
-                if self.cats[cat_id].has_key(scatt_id):
-                    cats[cat_id][scatt_id] = {'np_vals' : self.cats[cat_id][scatt_id]['np_vals'],
-                                              'bands_info' : self.GetBandsInfo(scatt_id)}
-                        
+                # if key is missing condition is always True (full scatter plor
+                # is computed)
+                if scatt_id in self.cats[cat_id]:
+                    cats[cat_id][scatt_id] = {
+                        'np_vals': self.cats[cat_id][scatt_id]['np_vals'],
+                        'bands_info': self.GetBandsInfo(scatt_id)}
+
         return cats
 
     def SetData(self, cats):
-        
-        for cat_id, scatt_ids in cats.iteritems():            
+
+        for cat_id, scatt_ids in cats.iteritems():
             for scatt_id in scatt_ids:
-                # if key is missing condition is always True (full scatter plor is computed)
-                if self.cats[cat_id].has_key(scatt_id):
-                    self.cats[cat_id][scatt_id]['np_vals'] = cats[cat_id][scatt_id]['np_vals']
+                # if key is missing condition is always True (full scatter plor
+                # is computed)
+                if scatt_id in self.cats[cat_id]:
+                    self.cats[cat_id][scatt_id]['np_vals'] = cats[
+                        cat_id][scatt_id]['np_vals']
 
-    def GetScatt(self, scatt_id, cats_ids = None):
+    def GetScatt(self, scatt_id, cats_ids=None):
         scatts = {}
         for cat_id in self.cats.iterkeys():
             if cats_ids and cat_id not in cats_ids:
                 continue
-            if not self.cats[cat_id].has_key(scatt_id):
+            if scatt_id not in self.cats[cat_id]:
                 continue
 
-            scatts[cat_id] = {'np_vals' : self.cats[cat_id][scatt_id]['np_vals'],
-                              'bands_info' : self.GetBandsInfo(scatt_id)}
+            scatts[cat_id] = {'np_vals': self.cats[cat_id][scatt_id][
+                'np_vals'], 'bands_info': self.GetBandsInfo(scatt_id)}
         return scatts
 
-                   
+
 class ScattPlotsData(ScattPlotsCondsData):
     """Data structure for computed points (classes) in scatter plots.\
     """
+
     def __init__(self, an_data):
 
         self.cats_rasts = {}
-        self.cats_rasts_conds = {}    
-        self.scatts_ids = []    
+        self.cats_rasts_conds = {}
+        self.scatts_ids = []
 
         ScattPlotsCondsData.__init__(self, an_data)
 
         self.dtype = 'uint32'
 
-        #TODO
+        # TODO
         self.type = 0
 
     def AddCategory(self, cat_id):
@@ -584,7 +618,8 @@
             self.cats_rasts[cat_id] = None
         else:
             self.cats_rasts_conds[cat_id] = grass.tempfile()
-            self.cats_rasts[cat_id] = "temp_cat_rast_%d_%d" % (cat_id, os.getpid())
+            self.cats_rasts[cat_id] = "temp_cat_rast_%d_%d" % (
+                cat_id, os.getpid())
             region = self.an_data.GetRegion()
             CreateCatRast(region, self.cats_rasts_conds[cat_id])
 
@@ -593,7 +628,7 @@
     def DeleteCategory(self, cat_id):
 
         ScattPlotsCondsData.DeleteCategory(self, cat_id)
-        
+
         grass.try_remove(self.cats_rasts_conds[cat_id])
         del self.cats_rasts_conds[cat_id]
 
@@ -604,26 +639,26 @@
         return True
 
     def AddScattPlot(self, scatt_id):
-        
+
         if scatt_id in self.scatts_ids:
             return False
 
         self.scatts_ids.append(scatt_id)
         for cat_id in self.cats.iterkeys():
-                ScattPlotsCondsData.AddScattPlot(self, cat_id, scatt_id)
-                self.cats[cat_id][scatt_id]['ellipse'] = None
+            ScattPlotsCondsData.AddScattPlot(self, cat_id, scatt_id)
+            self.cats[cat_id][scatt_id]['ellipse'] = None
 
         return True
 
     def DeleteScatterPlot(self, scatt_id):
-        
+
         if scatt_id not in self.scatts_ids:
             return False
 
         self.scatts_ids.remove(scatt_id)
 
         for cat_id in self.cats.iterkeys():
-                ScattPlotsCondsData.DeleteScattPlot(self, cat_id, scatt_id)
+            ScattPlotsCondsData.DeleteScattPlot(self, cat_id, scatt_id)
 
         return True
 
@@ -664,36 +699,36 @@
 
         x_diff = (x - x_avg)
         y_diff = (y - y_avg)
-        
-        x_diff = (x - x_avg) 
-        y_diff = (y - y_avg) 
 
+        x_diff = (x - x_avg)
+        y_diff = (y - y_avg)
+
         diffs = x_diff * y_diff.T
         cov = np.dot(diffs, weights) / (np.sum(weights) - 1)
 
         diffs = x_diff * x_diff.T
-        var_x = np.dot(diffs, weights) /  (np.sum(weights) - 1)
-        
+        var_x = np.dot(diffs, weights) / (np.sum(weights) - 1)
+
         diffs = y_diff * y_diff.T
-        var_y = np.dot(diffs, weights) /  (np.sum(weights) - 1)
+        var_y = np.dot(diffs, weights) / (np.sum(weights) - 1)
 
-        cov = np.array([[var_x, cov],[cov, var_y]])
+        cov = np.array([[var_x, cov], [cov, var_y]])
 
         def eigsorted(cov):
             vals, vecs = np.linalg.eigh(cov)
             order = vals.argsort()[::-1]
-            return vals[order], vecs[:,order]
+            return vals[order], vecs[:, order]
 
         vals, vecs = eigsorted(cov)
-        theta = np.degrees(np.arctan2(*vecs[:,0][::-1]))
+        theta = np.degrees(np.arctan2(*vecs[:, 0][::-1]))
 
         # Width and height are "full" widths, not radius
         width, height = 2 * nstd * np.sqrt(vals)
 
-        ellipse = {'pos' : pos, 
-                   'width' : width,
-                   'height' : height,
-                   'theta' : theta}
+        ellipse = {'pos': pos,
+                   'width': width,
+                   'height': height,
+                   'theta': theta}
 
         del data
         del flatten_data
@@ -704,9 +739,9 @@
 
     def CleanUp(self):
 
-        ScattPlotsCondsData.CleanUp(self)        
+        ScattPlotsCondsData.CleanUp(self)
         for tmp in self.cats_rasts_conds.itervalues():
-            grass.try_remove(tmp) 
+            grass.try_remove(tmp)
         for tmp in self.cats_rasts.itervalues():
             RunCommand("g.remove", flags='f',
                        type='raster', name=tmp,
@@ -716,7 +751,7 @@
         self.cats_rasts_conds = {}
 
     def GetCatRast(self, cat_id):
-        if self.cats_rasts.has_key(cat_id):
+        if cat_id in self.cats_rasts:
             return self.cats_rasts[cat_id]
         return None
 
@@ -754,7 +789,7 @@
     nx = width
     ny = height
 
-    x, y =  np.meshgrid(np.arange(-0.5 + min_w, nx + 0.5 + min_w, dtype=float), 
+    x, y =  np.meshgrid(np.arange(-0.5 + min_w, nx + 0.5 + min_w, dtype=float),
                         np.arange(-0.5 + min_h, ny + 0.5 + min_h, dtype=float))
     x, y = x.flatten(), y.flatten()
 
@@ -772,40 +807,46 @@
     return raster
 """
 
+
 def idScattToidBands(scatt_id, n_bands):
     """Get bands ids from scatter plot id."""
     n_b1 = n_bands - 1
 
-    band_1 = (int) ((2 * n_b1 + 1 - sqrt(((2 * n_b1 + 1) * (2 * n_b1 + 1) - 8 * scatt_id))) / 2)
+    band_1 = (int)(
+        (2 * n_b1 + 1 - sqrt(((2 * n_b1 + 1) * (2 * n_b1 + 1) - 8 * scatt_id))) / 2)
 
     band_2 = scatt_id - (band_1 * (2 * n_b1 + 1) - band_1 * band_1) / 2 + band_1 + 1
 
     return band_1, band_2
 
+
 def idBandsToidScatt(band_1_id, band_2_id, n_bands):
     """Get scatter plot id from band ids."""
-    if band_2_id <  band_1_id:
+    if band_2_id < band_1_id:
         tmp = band_1_id
         band_1_id = band_2_id
         band_2_id = tmp
 
     n_b1 = n_bands - 1
 
-    scatt_id = (band_1_id * (2 * n_b1 + 1) - band_1_id * band_1_id) / 2 + band_2_id - band_1_id - 1
+    scatt_id = (
+        band_1_id * (2 * n_b1 + 1) - band_1_id * band_1_id) / 2 + band_2_id - band_1_id - 1
 
     return scatt_id
 
+
 def GetRegion():
     ret, region, msg = RunCommand("g.region",
-                                  flags = "gp",
-                                  getErrorMsg = True,
-                                  read = True)
+                                  flags="gp",
+                                  getErrorMsg=True,
+                                  read=True)
 
     if ret != 0:
         raise GException("g.region failed:\n%s" % msg)
 
     return _parseRegion(region)
 
+
 def _parseRegion(region_str):
 
     region = {}
@@ -821,18 +862,19 @@
 
     return region
 
+
 def GetRasterInfo(rast):
     ret, out, msg = RunCommand("r.info",
-                                map = rast,
-                                flags = "rg",
-                                getErrorMsg = True,
-                                read = True)
+                               map=rast,
+                               flags="rg",
+                               getErrorMsg=True,
+                               read=True)
 
-    if  ret != 0:
+    if ret != 0:
         raise GException("r.info failed:\n%s" % msg)
 
     out = out.splitlines()
-    raster_info = {} 
+    raster_info = {}
 
     for b in out:
         if not b.strip():

Modified: grass/trunk/gui/wxpython/iscatt/plots.py
===================================================================
--- grass/trunk/gui/wxpython/iscatt/plots.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/iscatt/plots.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -30,7 +30,7 @@
     matplotlib.use('WXAgg')
     from matplotlib.figure import Figure
     from matplotlib.backends.backend_wxagg import \
-    FigureCanvasWxAgg as FigCanvas
+        FigureCanvasWxAgg as FigCanvas
     from matplotlib.lines import Line2D
     from matplotlib.artist import Artist
     from matplotlib.mlab import dist_point_to_segment
@@ -45,12 +45,14 @@
 import grass.script as grass
 from grass.pydispatch.signal import Signal
 
+
 class ScatterPlotWidget(wx.Panel, ManageBusyCursorMixin):
+
     def __init__(self, parent, scatt_id, scatt_mgr, transpose,
-                 id = wx.ID_ANY):
-        #TODO should not be transpose and scatt_id but x, y
+                 id=wx.ID_ANY):
+        # TODO should not be transpose and scatt_id but x, y
         wx.Panel.__init__(self, parent, id)
-        # bacause of aui (if floatable it can not take cursor from parent)        
+        # bacause of aui (if floatable it can not take cursor from parent)
         ManageBusyCursorMixin.__init__(self, window=self)
 
         self.parent = parent
@@ -75,12 +77,12 @@
         self.Layout()
 
         self.base_scale = 1.2
-        self.Bind(wx.EVT_CLOSE,lambda event : self.CleanUp())
+        self.Bind(wx.EVT_CLOSE, lambda event: self.CleanUp())
 
         self.plotClosed = Signal("ScatterPlotWidget.plotClosed")
         self.cursorMove = Signal("ScatterPlotWidget.cursorMove")
 
-        self.contex_menu = ScatterPlotContextMenu(plot = self)
+        self.contex_menu = ScatterPlotContextMenu(plot=self)
 
         self.ciddscroll = None
 
@@ -96,7 +98,7 @@
 
     def _createWidgets(self):
 
-        # Create the mpl Figure and FigCanvas objects. 
+        # Create the mpl Figure and FigCanvas objects.
         # 5x4 inches, 100 dots-per-inch
         #
         self.dpi = 100
@@ -104,16 +106,16 @@
         self.fig.autolayout = True
 
         self.canvas = FigCanvas(self, -1, self.fig)
-        
-        self.axes = self.fig.add_axes([0.0,0.0,1,1])
 
+        self.axes = self.fig.add_axes([0.0, 0.0, 1, 1])
+
         pol = Polygon(list(zip([0], [0])), animated=True)
         self.axes.add_patch(pol)
-        self.polygon_drawer = PolygonDrawer(self.axes, pol = pol, empty_pol = True)
+        self.polygon_drawer = PolygonDrawer(self.axes, pol=pol, empty_pol=True)
 
         self.zoom_wheel_coords = None
         self.zoom_rect_coords = None
-        self.zoom_rect = Polygon(list(zip([0], [0])), facecolor = 'none')
+        self.zoom_rect = Polygon(list(zip([0], [0])), facecolor='none')
         self.zoom_rect.set_visible(False)
         self.axes.add_patch(self.zoom_rect)
 
@@ -125,7 +127,8 @@
     def SetMode(self, mode):
         self._deactivateMode()
         if mode == 'zoom':
-            self.ciddscroll = self.canvas.mpl_connect('scroll_event', self.ZoomWheel)
+            self.ciddscroll = self.canvas.mpl_connect(
+                'scroll_event', self.ZoomWheel)
             self.mode = 'zoom'
         elif mode == 'zoom_extend':
             self.mode = 'zoom_extend'
@@ -138,7 +141,7 @@
         self.polygon_drawer.SetSelectionPolygonMode(activate)
 
     def _deactivateMode(self):
-        self.mode  = None
+        self.mode = None
         self.polygon_drawer.SetMode(None)
 
         if self.ciddscroll:
@@ -165,11 +168,12 @@
         return self.polygon_drawer.SetEmpty()
 
     def OnRelease(self, event):
-        if not self.mode == "zoom": return
+        if not self.mode == "zoom":
+            return
         self.zoom_rect.set_visible(False)
         self.ZoomRectangle(event)
         self.canvas.draw()
-    
+
     def OnPress(self, event):
         'on button press we will see if the mouse is over us and store some data'
         if not event.inaxes:
@@ -178,8 +182,8 @@
             self.ZoomToExtend()
 
         if event.xdata and event.ydata:
-            self.zoom_wheel_coords = { 'x' : event.xdata, 'y' : event.ydata}
-            self.zoom_rect_coords = { 'x' : event.xdata, 'y' : event.ydata}
+            self.zoom_wheel_coords = {'x': event.xdata, 'y': event.ydata}
+            self.zoom_rect_coords = {'x': event.xdata, 'y': event.ydata}
         else:
             self.zoom_wheel_coords = None
             self.zoom_rect_coords = None
@@ -191,15 +195,15 @@
             self.canvas.mpl_disconnect(self.cidpress)
         if self.cidrelease:
             self.canvas.mpl_disconnect(self.cidrelease)
-        #self.canvas.mpl_disconnect(self.cidmotion)
+        # self.canvas.mpl_disconnect(self.cidmotion)
 
     def _doLayout(self):
-        
+
         self.main_sizer = wx.BoxSizer(wx.VERTICAL)
         self.main_sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
         self.SetSizer(self.main_sizer)
         self.main_sizer.Fit(self)
-    
+
     def Plot(self, cats_order, scatts, ellipses, styles):
         """Redraws the figure
         """
@@ -215,15 +219,16 @@
 
         q = Queue()
         _rendDtMemmapsToFiles(self.rend_dt)
-        p = Process(target=MergeImg, args=(cats_order, scatts, styles, 
+        p = Process(target=MergeImg, args=(cats_order, scatts, styles,
                                            self.rend_dt, q))
         p.start()
         merged_img, self.full_extend, self.rend_dt = q.get()
         p.join()
-        
 
         _rendDtFilesToMemmaps(self.rend_dt)
-        merged_img = np.memmap(filename=merged_img['dt'], shape=merged_img['sh'])
+        merged_img = np.memmap(
+            filename=merged_img['dt'],
+            shape=merged_img['sh'])
 
         #merged_img, self.full_extend = MergeImg(cats_order, scatts, styles, None)
         self.axes.clear()
@@ -233,7 +238,7 @@
             merged_img = np.transpose(merged_img, (1, 0, 2))
 
         img = imshow(self.axes, merged_img,
-                     extent= [int(ceil(x)) for x in self.full_extend],
+                     extent=[int(ceil(x)) for x in self.full_extend],
                      origin='lower',
                      interpolation='nearest',
                      aspect="equal")
@@ -244,9 +249,9 @@
         for cat_id in cats_order:
             if cat_id == 0:
                 continue
-            if not ellipses.has_key(cat_id):
+            if cat_id not in ellipses:
                 continue
-                
+
             e = ellipses[cat_id]
             if not e:
                 continue
@@ -255,37 +260,39 @@
             if self.transpose:
                 e['theta'] = 360 - e['theta'] + 90
                 if e['theta'] >= 360:
-                    e['theta'] = abs(360 - e['theta']) 
-                
+                    e['theta'] = abs(360 - e['theta'])
+
                 e['pos'] = [e['pos'][1], e['pos'][0]]
 
-            ellip = Ellipse(xy=e['pos'], 
-                            width=e['width'], 
-                            height=e['height'], 
-                            angle=e['theta'], 
+            ellip = Ellipse(xy=e['pos'],
+                            width=e['width'],
+                            height=e['height'],
+                            angle=e['theta'],
                             edgecolor="w",
-                            linewidth=1.5, 
+                            linewidth=1.5,
                             facecolor='None')
             self.axes.add_artist(ellip)
             callafter_list.append([self.axes.draw_artist, [ellip]])
 
-            color = map(lambda v : int(v)/255.0, styles[cat_id]['color'].split(":"))
+            color = map(
+                lambda v: int(v) / 255.0,
+                styles[cat_id]['color'].split(":"))
 
-            ellip = Ellipse(xy=e['pos'], 
-                            width=e['width'], 
-                            height=e['height'], 
-                            angle=e['theta'], 
+            ellip = Ellipse(xy=e['pos'],
+                            width=e['width'],
+                            height=e['height'],
+                            angle=e['theta'],
                             edgecolor=color,
-                            linewidth=1, 
+                            linewidth=1,
                             facecolor='None')
 
             self.axes.add_artist(ellip)
             callafter_list.append([self.axes.draw_artist, [ellip]])
-            
-            center = Line2D([e['pos'][0]], [e['pos'][1]], 
+
+            center = Line2D([e['pos'][0]], [e['pos'][1]],
                             marker='x',
                             markeredgecolor='w',
-                            #markerfacecolor=color,
+                            # markerfacecolor=color,
                             markersize=2)
             self.axes.add_artist(center)
             callafter_list.append([self.axes.draw_artist, [center]])
@@ -294,17 +301,17 @@
 
         if c:
             self.axes.axis(c)
-        wx.CallAfter(lambda : self.CallAfter(callafter_list))
-    
+        wx.CallAfter(lambda: self.CallAfter(callafter_list))
+
     def CallAfter(self, funcs_list):
-        while funcs_list: 
-            fcn, args = funcs_list.pop(0) 
-            fcn(*args) 
+        while funcs_list:
+            fcn, args = funcs_list.pop(0)
+            fcn(*args)
 
         self.canvas.draw()
 
     def CleanUp(self):
-        self.plotClosed.emit(scatt_id = self.scatt_id)
+        self.plotClosed.emit(scatt_id=self.scatt_id)
         self.Destroy()
 
     def ZoomWheel(self, event):
@@ -315,34 +322,37 @@
         # http://stackoverflow.com/questions/11551049/matplotlib-plot-zooming-with-scroll-wheel
         cur_xlim = self.axes.get_xlim()
         cur_ylim = self.axes.get_ylim()
-        
+
         xdata = event.xdata
-        ydata = event.ydata 
+        ydata = event.ydata
         if event.button == 'up':
-            scale_factor = 1/self.base_scale
+            scale_factor = 1 / self.base_scale
         elif event.button == 'down':
             scale_factor = self.base_scale
         else:
             scale_factor = 1
 
         extend = (xdata - (xdata - cur_xlim[0]) * scale_factor,
-                  xdata + (cur_xlim[1] - xdata) * scale_factor, 
+                  xdata + (cur_xlim[1] - xdata) * scale_factor,
                   ydata - (ydata - cur_ylim[0]) * scale_factor,
                   ydata + (cur_ylim[1] - ydata) * scale_factor)
 
         self.axes.axis(extend)
-        
+
         self.canvas.draw()
 
     def ZoomRectangle(self, event):
         # get the current x and y limits
-        if not self.mode == "zoom": return
-        if event.inaxes is None: return
-        if event.button != 1: return
+        if not self.mode == "zoom":
+            return
+        if event.inaxes is None:
+            return
+        if event.button != 1:
+            return
 
         cur_xlim = self.axes.get_xlim()
         cur_ylim = self.axes.get_ylim()
-        
+
         x1, y1 = event.xdata, event.ydata
         x2 = deepcopy(self.zoom_rect_coords['x'])
         y2 = deepcopy(self.zoom_rect_coords['y'])
@@ -351,64 +361,74 @@
             return
 
         if x1 > x2:
-            tmp = x1 
+            tmp = x1
             x1 = x2
             x2 = tmp
 
         if y1 > y2:
-            tmp = y1 
+            tmp = y1
             y1 = y2
             y2 = tmp
 
         self.axes.axis((x1, x2, y1, y2))
-        #self.axes.set_xlim(x1, x2)#, auto = True)
-        #self.axes.set_ylim(y1, y2)#, auto = True)
+        # self.axes.set_xlim(x1, x2)#, auto = True)
+        # self.axes.set_ylim(y1, y2)#, auto = True)
         self.canvas.draw()
 
     def Motion(self, event):
         self.PanMotion(event)
         self.ZoomRectMotion(event)
-        
-        if event.inaxes is None: 
+
+        if event.inaxes is None:
             return
-        
-        self.cursorMove.emit(x=event.xdata, y=event.ydata, scatt_id=self.scatt_id)
 
+        self.cursorMove.emit(
+            x=event.xdata,
+            y=event.ydata,
+            scatt_id=self.scatt_id)
+
     def OnCanvasLeave(self, event):
         self.cursorMove.emit(x=None, y=None, scatt_id=self.scatt_id)
 
     def PanMotion(self, event):
         'on mouse movement'
-        if not self.mode == "pan": 
+        if not self.mode == "pan":
             return
-        if event.inaxes is None: 
+        if event.inaxes is None:
             return
-        if event.button != 1: 
+        if event.button != 1:
             return
 
         cur_xlim = self.axes.get_xlim()
         cur_ylim = self.axes.get_ylim()
 
-        x,y = event.xdata, event.ydata
-        
+        x, y = event.xdata, event.ydata
+
         mx = (x - self.zoom_wheel_coords['x']) * 0.6
         my = (y - self.zoom_wheel_coords['y']) * 0.6
 
-        extend = (cur_xlim[0] - mx, cur_xlim[1] - mx, cur_ylim[0] - my, cur_ylim[1] - my)
+        extend = (
+            cur_xlim[0] - mx,
+            cur_xlim[1] - mx,
+            cur_ylim[0] - my,
+            cur_ylim[1] - my)
 
         self.zoom_wheel_coords['x'] = x
         self.zoom_wheel_coords['y'] = y
 
         self.axes.axis(extend)
 
-        #self.canvas.copy_from_bbox(self.axes.bbox)
-        #self.canvas.restore_region(self.background)
+        # self.canvas.copy_from_bbox(self.axes.bbox)
+        # self.canvas.restore_region(self.background)
         self.canvas.draw()
-        
+
     def ZoomRectMotion(self, event):
-        if not self.mode == "zoom": return
-        if event.inaxes is None: return
-        if event.button != 1: return
+        if not self.mode == "zoom":
+            return
+        if event.inaxes is None:
+            return
+        if event.button != 1:
+            return
 
         x1, y1 = event.xdata, event.ydata
         self.zoom_rect.set_visible(True)
@@ -417,115 +437,137 @@
 
         self.zoom_rect.xy = ((x1, y1), (x1, y2), (x2, y2), (x2, y1), (x1, y1))
 
-        #self.axes.draw_artist(self.zoom_rect)
+        # self.axes.draw_artist(self.zoom_rect)
         self.canvas.draw()
 
+
 def MergeImg(cats_order, scatts, styles, rend_dt, output_queue):
 
-        _rendDtFilesToMemmaps(rend_dt)
+    _rendDtFilesToMemmaps(rend_dt)
 
-        init = True
-        merged_img = None
-        merge_tmp = grass.tempfile()
-        for cat_id in cats_order:
-            if not scatts.has_key(cat_id):
+    init = True
+    merged_img = None
+    merge_tmp = grass.tempfile()
+    for cat_id in cats_order:
+        if cat_id not in scatts:
+            continue
+        scatt = scatts[cat_id]
+        # print "color map %d" % cat_id
+        # TODO make more general
+        if cat_id != 0 and (styles[cat_id]['opacity'] == 0.0 or
+                            not styles[cat_id]['show']):
+            if cat_id in rend_dt and not rend_dt[cat_id]:
+                del rend_dt[cat_id]
+            continue
+        if init:
+
+            b2_i = scatt['bands_info']['b1']
+            b1_i = scatt['bands_info']['b2']
+
+            full_extend = (
+                b1_i['min'] - 0.5,
+                b1_i['max'] + 0.5,
+                b2_i['min'] - 0.5,
+                b2_i['max'] + 0.5)
+
+        # if it does not need to be updated and was already rendered
+        if not _renderCat(cat_id, rend_dt, scatt, styles):
+            # is empty - has only zeros
+            if rend_dt[cat_id] is None:
                 continue
-            scatt = scatts[cat_id]
-            #print "color map %d" % cat_id
-            #TODO make more general
-            if cat_id != 0 and (styles[cat_id]['opacity'] == 0.0 or \
-               not styles[cat_id]['show']):
-                if rend_dt.has_key(cat_id) and not rend_dt[cat_id]:
-                    del rend_dt[cat_id]
+        else:
+            masked_cat = np.ma.masked_less_equal(scatt['np_vals'], 0)
+            vmax = np.amax(masked_cat)
+            # totally empty -> no need to render
+            if vmax == 0:
+                render_cat_ids[cat_id] = None
                 continue
-            if init:
 
-                b2_i = scatt['bands_info']['b1']
-                b1_i = scatt['bands_info']['b2']
+            cmap = _getColorMap(cat_id, styles)
+            masked_cat = np.uint8(masked_cat * (255.0 / float(vmax)))
 
-                full_extend = (b1_i['min'] - 0.5, b1_i['max'] + 0.5, b2_i['min'] - 0.5, b2_i['max'] + 0.5) 
-            
-            # if it does not need to be updated and was already rendered 
-            if not _renderCat(cat_id, rend_dt, scatt, styles):
-                # is empty - has only zeros
-                if rend_dt[cat_id] is None:
-                    continue
-            else:
-                masked_cat = np.ma.masked_less_equal(scatt['np_vals'], 0)
-                vmax = np.amax(masked_cat)
-                # totally empty -> no need to render
-                if vmax == 0:
-                    render_cat_ids[cat_id] = None
-                    continue
+            cmap = np.uint8(cmap._lut * 255)
+            sh = masked_cat.shape
 
-                cmap = _getColorMap(cat_id, styles)
-                masked_cat = np.uint8(masked_cat * (255.0 / float(vmax)))
+            rend_dt[cat_id] = {}
+            if cat_id != 0:
+                rend_dt[cat_id]['color'] = styles[cat_id]['color']
 
-                cmap = np.uint8(cmap._lut * 255)
-                sh =masked_cat.shape
+            rend_dt[cat_id]['dt'] = np.memmap(
+                grass.tempfile(),
+                dtype='uint8',
+                mode='w+',
+                shape=(
+                    sh[0],
+                    sh[1],
+                    4))
 
-                rend_dt[cat_id] = {}
-                if cat_id != 0:
-                    rend_dt[cat_id]['color'] = styles[cat_id]['color']
-                
-                rend_dt[cat_id]['dt'] = np.memmap(grass.tempfile(), dtype='uint8', mode='w+', 
-                                                                    shape=(sh[0], sh[1], 4))
+            #colored_cat = np.zeros(dtype='uint8', )
+            ApplyColormap(
+                masked_cat,
+                masked_cat.mask,
+                cmap,
+                rend_dt[cat_id]['dt'])
 
-                #colored_cat = np.zeros(dtype='uint8', )
-                ApplyColormap(masked_cat, masked_cat.mask, cmap, rend_dt[cat_id]['dt'])
+            #colored_cat = np.uint8(cmap(masked_cat) * 255)
+            del masked_cat
+            del cmap
 
-                #colored_cat = np.uint8(cmap(masked_cat) * 255)
-                del masked_cat
-                del cmap
-            
-            #colored_cat[...,3] = np.choose(masked_cat.mask, (255, 0))
-            if init:
-                merged_img = np.memmap(merge_tmp, dtype='uint8', mode='w+', 
-                                       shape=rend_dt[cat_id]['dt'].shape)
-                merged_img[:] = rend_dt[cat_id]['dt']
-                init = False
-            else:
-                MergeArrays(merged_img, rend_dt[cat_id]['dt'], styles[cat_id]['opacity'])
+        #colored_cat[...,3] = np.choose(masked_cat.mask, (255, 0))
+        if init:
+            merged_img = np.memmap(merge_tmp, dtype='uint8', mode='w+',
+                                   shape=rend_dt[cat_id]['dt'].shape)
+            merged_img[:] = rend_dt[cat_id]['dt']
+            init = False
+        else:
+            MergeArrays(
+                merged_img,
+                rend_dt[cat_id]['dt'],
+                styles[cat_id]['opacity'])
 
-            """
-                #c_img_a = np.memmap(grass.tempfile(), dtype="uint16", mode='w+', shape = shape) 
+        """
+                #c_img_a = np.memmap(grass.tempfile(), dtype="uint16", mode='w+', shape = shape)
                 c_img_a = colored_cat.astype('uint16')[:,:,3] * styles[cat_id]['opacity']
 
                 #TODO apply strides and there will be no need for loop
                 #b = as_strided(a, strides=(0, a.strides[3], a.strides[3], a.strides[3]), shape=(3, a.shape[0], a.shape[1]))
-                
+
                 for i in range(3):
                     merged_img[:,:,i] = (merged_img[:,:,i] * (255 - c_img_a) + colored_cat[:,:,i] * c_img_a) / 255;
                 merged_img[:,:,3] = (merged_img[:,:,3] * (255 - c_img_a) + 255 * c_img_a) / 255;
-                
+
                 del c_img_a
             """
 
-        _rendDtMemmapsToFiles(rend_dt)
+    _rendDtMemmapsToFiles(rend_dt)
 
-        merged_img = {'dt' : merged_img.filename, 'sh' : merged_img.shape} 
-        output_queue.put((merged_img, full_extend, rend_dt))
+    merged_img = {'dt': merged_img.filename, 'sh': merged_img.shape}
+    output_queue.put((merged_img, full_extend, rend_dt))
 
 #_rendDtMemmapsToFiles and _rendDtFilesToMemmaps are workarounds for older numpy versions,
-# where memmap objects are not pickable  
+# where memmap objects are not pickable
+
+
 def _rendDtMemmapsToFiles(rend_dt):
 
     for k, v in rend_dt.iteritems():
-        if v.has_key('dt'):
+        if 'dt' in v:
             rend_dt[k]['sh'] = v['dt'].shape
             rend_dt[k]['dt'] = v['dt'].filename
 
+
 def _rendDtFilesToMemmaps(rend_dt):
 
     for k, v in rend_dt.iteritems():
-        if v.has_key('dt'):
+        if 'dt' in v:
             rend_dt[k]['dt'] = np.memmap(filename=v['dt'], shape=v['sh'])
             del rend_dt[k]['sh']
 
+
 def _renderCat(cat_id, rend_dt, scatt, styles):
     return True
 
-    if not rend_dt.has_key(cat_id):
+    if cat_id not in rend_dt:
         return True
     if not rend_dt[cat_id]:
         return False
@@ -533,64 +575,70 @@
         return True
     if cat_id != 0 and \
        rend_dt[cat_id]['color'] != styles[cat_id]['color']:
-       return True
-    
+        return True
+
     return False
 
+
 def _getColorMap(cat_id, styles):
     cmap = matplotlib.cm.jet
     if cat_id == 0:
-        cmap.set_bad('w',1.)
+        cmap.set_bad('w', 1.)
         cmap._init()
         cmap._lut[len(cmap._lut) - 1, -1] = 0
     else:
         colors = styles[cat_id]['color'].split(":")
 
-        cmap.set_bad('w',1.)
+        cmap.set_bad('w', 1.)
         cmap._init()
         cmap._lut[len(cmap._lut) - 1, -1] = 0
-        cmap._lut[:, 0] = int(colors[0])/255.0
-        cmap._lut[:, 1] = int(colors[1])/255.0
-        cmap._lut[:, 2] = int(colors[2])/255.0
+        cmap._lut[:, 0] = int(colors[0]) / 255.0
+        cmap._lut[:, 1] = int(colors[1]) / 255.0
+        cmap._lut[:, 2] = int(colors[2]) / 255.0
 
     return cmap
 
+
 class ScatterPlotContextMenu:
+
     def __init__(self, plot):
 
         self.plot = plot
         self.canvas = plot.canvas
         self.cidpress = self.canvas.mpl_connect(
             'button_press_event', self.ContexMenu)
-   
+
     def ContexMenu(self, event):
         if not event.inaxes:
             return
 
         if event.button == 3:
-            menu = wx.Menu()       
-            menu_items = [["zoom_to_extend", _("Zoom to scatter plot extend"), 
-                            lambda event : self.plot.ZoomToExtend()]]
+            menu = wx.Menu()
+            menu_items = [["zoom_to_extend", _("Zoom to scatter plot extend"),
+                           lambda event: self.plot.ZoomToExtend()]]
 
             for item in menu_items:
                 item_id = wx.ID_ANY
-                menu.Append(item_id, text = item[1])
-                menu.Bind(wx.EVT_MENU, item[2], id = item_id)
+                menu.Append(item_id, text=item[1])
+                menu.Bind(wx.EVT_MENU, item[2], id=item_id)
 
-            wx.CallAfter(self.ShowMenu, menu) 
-   
+            wx.CallAfter(self.ShowMenu, menu)
+
     def ShowMenu(self, menu):
         self.plot.PopupMenu(menu)
         menu.Destroy()
-        self.plot.ReleaseMouse() 
+        self.plot.ReleaseMouse()
 
+
 class PolygonDrawer:
     """
     An polygon editor.
     """
+
     def __init__(self, ax, pol, empty_pol):
         if pol.figure is None:
-            raise RuntimeError('You must first add the polygon to a figure or canvas before defining the interactor')
+            raise RuntimeError(
+                'You must first add the polygon to a figure or canvas before defining the interactor')
         self.ax = ax
         self.canvas = pol.figure.canvas
 
@@ -603,12 +651,17 @@
 
         style = self._getPolygonStyle()
 
-        self.line = Line2D(x, y, marker='o', markerfacecolor='r', animated=True)
+        self.line = Line2D(
+            x,
+            y,
+            marker='o',
+            markerfacecolor='r',
+            animated=True)
         self.ax.add_line(self.line)
-        #self._update_line(pol)
+        # self._update_line(pol)
 
         cid = self.pol.add_callback(self.poly_changed)
-        self.moving_ver_idx = None # the active vert
+        self.moving_ver_idx = None  # the active vert
 
         self.mode = None
 
@@ -617,38 +670,42 @@
 
         #self.canvas.mpl_connect('draw_event', self.DrawCallback)
         self.canvas.mpl_connect('button_press_event', self.OnButtonPressed)
-        self.canvas.mpl_connect('button_release_event', self.ButtonReleaseCallback)
-        self.canvas.mpl_connect('motion_notify_event', self.motion_notify_callback)
-    
+        self.canvas.mpl_connect(
+            'button_release_event',
+            self.ButtonReleaseCallback)
+        self.canvas.mpl_connect(
+            'motion_notify_event',
+            self.motion_notify_callback)
+
         self.it = 0
 
     def _getPolygonStyle(self):
         style = {}
-        style['sel_pol'] = UserSettings.Get(group='scatt', 
-                                            key='selection', 
+        style['sel_pol'] = UserSettings.Get(group='scatt',
+                                            key='selection',
                                             subkey='sel_pol')
-        style['sel_pol_vertex'] = UserSettings.Get(group='scatt', 
-                                                   key='selection', 
+        style['sel_pol_vertex'] = UserSettings.Get(group='scatt',
+                                                   key='selection',
                                                    subkey='sel_pol_vertex')
 
-        style['sel_pol'] = [i / 255.0 for i in style['sel_pol']] 
-        style['sel_pol_vertex'] = [i / 255.0 for i in style['sel_pol_vertex']] 
+        style['sel_pol'] = [i / 255.0 for i in style['sel_pol']]
+        style['sel_pol_vertex'] = [i / 255.0 for i in style['sel_pol_vertex']]
 
         return style
 
     def _getSnapTresh(self):
-        return UserSettings.Get(group='scatt', 
-                                key='selection', 
+        return UserSettings.Get(group='scatt',
+                                key='selection',
                                 subkey='snap_tresh')
 
     def SetMode(self, mode):
         self.mode = mode
 
     def SetSelectionPolygonMode(self, activate):
-        
+
         self.Show(activate)
         if not activate and self.mode:
-            self.SetMode(None) 
+            self.SetMode(None)
 
     def Show(self, show):
         if show:
@@ -670,7 +727,7 @@
     def _setEmptyPol(self, empty_pol):
         self.empty_pol = empty_pol
         if self.empty_pol:
-            #TODO
+            # TODO
             self.pol.xy = np.array([[0, 0]])
         self._show(not empty_pol)
 
@@ -692,14 +749,14 @@
 
     def DrawCallback(self, event):
 
-        style=self._getPolygonStyle()
+        style = self._getPolygonStyle()
         self.pol.set_facecolor(style['sel_pol'])
         self.line.set_markerfacecolor(style['sel_pol_vertex'])
 
         self.background = self.canvas.copy_from_bbox(self.ax.bbox)
         self.ax.draw_artist(self.pol)
         self.ax.draw_artist(self.line)
-    
+
     def poly_changed(self, pol):
         'this method is called whenever the polygon object is called'
         # only copy the artist props to the line (except visibility)
@@ -714,11 +771,11 @@
         xy = np.asarray(self.pol.xy)
         xyt = self.pol.get_transform().transform(xy)
         xt, yt = xyt[:, 0], xyt[:, 1]
-        d = np.sqrt((xt-event.x)**2 + (yt-event.y)**2)
+        d = np.sqrt((xt - event.x)**2 + (yt - event.y)**2)
         indseq = np.nonzero(np.equal(d, np.amin(d)))[0]
         ind = indseq[0]
 
-        if d[ind]>=self._getSnapTresh():
+        if d[ind] >= self._getSnapTresh():
             ind = None
 
         return ind
@@ -727,7 +784,7 @@
         if not event.inaxes:
             return
 
-        if event.button in [2, 3]: 
+        if event.button in [2, 3]:
             return
 
         if self.mode == "delete_vertex":
@@ -742,19 +799,22 @@
 
     def ButtonReleaseCallback(self, event):
         'whenever a mouse button is released'
-        if not self.showverts: return
-        if event.button != 1: return
+        if not self.showverts:
+            return
+        if event.button != 1:
+            return
         self.moving_ver_idx = None
 
     def ShowVertices(self, show):
         self.showverts = show
         self.line.set_visible(self.showverts)
-        if not self.showverts: self.moving_ver_idx = None
+        if not self.showverts:
+            self.moving_ver_idx = None
 
     def _deleteVertex(self, event):
         ind = self.get_ind_under_point(event)
 
-        if ind  is None or self.empty_pol:
+        if ind is None or self.empty_pol:
             return
 
         if len(self.pol.xy) <= 2:
@@ -763,12 +823,12 @@
             return
 
         coords = []
-        for i,tup in enumerate(self.pol.xy): 
+        for i, tup in enumerate(self.pol.xy):
             if i == ind:
                 continue
             elif i == 0 and ind == len(self.pol.xy) - 1:
                 continue
-            elif i == len(self.pol.xy) - 1 and ind == 0: 
+            elif i == len(self.pol.xy) - 1 and ind == 0:
                 continue
 
             coords.append(tup)
@@ -783,13 +843,13 @@
             return
 
         xys = self.pol.get_transform().transform(self.pol.xy)
-        p = event.x, event.y # display coords
-        for i in range(len(xys)-1):
+        p = event.x, event.y  # display coords
+        for i in range(len(xys) - 1):
             s0 = xys[i]
-            s1 = xys[i+1]
+            s1 = xys[i + 1]
             d = dist_point_to_segment(p, s0, s1)
 
-            if d<=self._getSnapTresh():
+            if d <= self._getSnapTresh():
                 self.pol.xy = np.array(
                     list(self.pol.xy[:i + 1]) +
                     [(event.xdata, event.ydata)] +
@@ -808,32 +868,38 @@
             self.empty_pol = False
         else:
             self.pol.xy = np.array(
-                        [(event.xdata, event.ydata)] +
-                        list(self.pol.xy[1:]) +
-                        [(event.xdata, event.ydata)])
+                [(event.xdata, event.ydata)] +
+                list(self.pol.xy[1:]) +
+                [(event.xdata, event.ydata)])
 
         self.line.set_data(zip(*self.pol.xy))
-        
+
         self.Redraw()
 
     def motion_notify_callback(self, event):
         'on mouse movement'
-        if not self.mode == "move_vertex": return
-        if not self.showverts: return
-        if self.empty_pol: return
-        if self.moving_ver_idx is None: return
-        if event.inaxes is None: return
-        if event.button != 1: return
+        if not self.mode == "move_vertex":
+            return
+        if not self.showverts:
+            return
+        if self.empty_pol:
+            return
+        if self.moving_ver_idx is None:
+            return
+        if event.inaxes is None:
+            return
+        if event.button != 1:
+            return
 
         self.it += 1
 
-        x,y = event.xdata, event.ydata
+        x, y = event.xdata, event.ydata
 
-        self.pol.xy[self.moving_ver_idx] = x,y
+        self.pol.xy[self.moving_ver_idx] = x, y
         if self.moving_ver_idx == 0:
-            self.pol.xy[len(self.pol.xy) - 1] = x,y
+            self.pol.xy[len(self.pol.xy) - 1] = x, y
         elif self.moving_ver_idx == len(self.pol.xy) - 1:
-            self.pol.xy[0] = x,y
+            self.pol.xy[0] = x, y
 
         self.line.set_data(zip(*self.pol.xy))
 
@@ -841,6 +907,7 @@
 
         self.Redraw()
 
+
 class ModestImage(mi.AxesImage):
     """
     Computationally modest image class.
@@ -860,6 +927,7 @@
 
     Author: Chris Beaumont <beaumont at hawaii.edu>
     """
+
     def __init__(self, minx=0.0, miny=0.0, *args, **kwargs):
         if 'extent' in kwargs and kwargs['extent'] is not None:
             raise NotImplementedError("ModestImage does not support extents")
@@ -886,10 +954,10 @@
             raise TypeError("Image data can not convert to float")
 
         if (self._A.ndim not in (2, 3) or
-            (self._A.ndim == 3 and self._A.shape[-1] not in (3, 4))):
+                (self._A.ndim == 3 and self._A.shape[-1] not in (3, 4))):
             raise TypeError("Invalid dimensions for image data")
 
-        self._imcache =None
+        self._imcache = None
         self._rgbacache = None
         self._oldxslice = None
         self._oldyslice = None
@@ -919,11 +987,11 @@
 
         # have we already calculated what we need?
         if sx == self._sx and sy == self._sy and \
-            x0 == self._bounds[0] and x1 == self._bounds[1] and \
-            y0 == self._bounds[2] and y1 == self._bounds[3]:
+                x0 == self._bounds[0] and x1 == self._bounds[1] and \
+                y0 == self._bounds[2] and y1 == self._bounds[3]:
             return
 
-        self._A = self._full_res[y0 - self.miny:y1 - self.miny:sy, 
+        self._A = self._full_res[y0 - self.miny:y1 - self.miny:sy,
                                  x0 - self.minx:x1 - self.minx:sx]
 
         x1 = x0 + self._A.shape[1] * sx
@@ -939,6 +1007,7 @@
         self._scale_to_res()
         super(ModestImage, self).draw(renderer, *args, **kwargs)
 
+
 def imshow(axes, X, cmap=None, norm=None, aspect=None,
            interpolation=None, alpha=None, vmin=None, vmax=None,
            origin=None, extent=None, shape=None, filternorm=1,
@@ -958,15 +1027,25 @@
     axes.set_aspect(aspect)
 
     if extent:
-        minx=extent[0]
-        miny=extent[2]
+        minx = extent[0]
+        miny = extent[2]
     else:
-        minx=0.0
-        miny=0.0
+        minx = 0.0
+        miny = 0.0
 
-    im = ModestImage(minx, miny, axes, cmap, norm, interpolation, origin, extent,
-                     filternorm=filternorm,
-                     filterrad=filterrad, resample=resample, **kwargs)
+    im = ModestImage(
+        minx,
+        miny,
+        axes,
+        cmap,
+        norm,
+        interpolation,
+        origin,
+        extent,
+        filternorm=filternorm,
+        filterrad=filterrad,
+        resample=resample,
+        **kwargs)
 
     im.set_data(X)
     im.set_alpha(alpha)
@@ -976,7 +1055,7 @@
         # image does not already have clipping set, clip to axes patch
         im.set_clip_path(axes.patch)
 
-    #if norm is None and shape is None:
+    # if norm is None and shape is None:
     #    im.set_clim(vmin, vmax)
     if vmin is not None or vmax is not None:
         im.set_clim(vmin, vmax)

Modified: grass/trunk/gui/wxpython/iscatt/toolbars.py
===================================================================
--- grass/trunk/gui/wxpython/iscatt/toolbars.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/iscatt/toolbars.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -22,16 +22,18 @@
 from iscatt.iscatt_core import idBandsToidScatt
 from iscatt.dialogs import SettingsDialog
 
+
 class MainToolbar(BaseToolbar):
     """Main toolbar
     """
+
     def __init__(self, parent, scatt_mgr, opt_tools=None):
         BaseToolbar.__init__(self, parent)
         self.scatt_mgr = scatt_mgr
         self.opt_tools = opt_tools
 
         self.InitToolbar(self._toolbarData())
-        
+
         # realize the toolbar
         self.Realize()
         self.scatt_mgr.modeSet.connect(self.ModeSet)
@@ -39,81 +41,90 @@
     def _toolbarData(self):
 
         icons = {
-                'selectGroup' : MetaIcon(img = 'layer-group-add',
-                                 label = _('Select imagery group')),
-                'settings'   : BaseIcons['settings'].SetLabel( _('Settings')),
-                'help'       : MetaIcon(img = 'help',
-                                         label = _('Show manual')),
-                'add_scatt_pl'  : MetaIcon(img = 'layer-raster-analyze',
-                                            label = _('Add scatter plot')),
-                'selCatPol'  : MetaIcon(img = 'polygon',
-                                      label = _('Select area with polygon')),
-                'pan'        : MetaIcon(img = 'pan',
-                                         label = _('Pan mode for scatter plots')),
-                'zoomIn'     : MetaIcon(img = 'zoom-in',
-                                        label = _('Zoom mode for scatter plots (left mouse button, wheel)')),
-                'zoomExtent' : MetaIcon(img = 'zoom-extent',
-                                       label = _('Zoom to scatter plot data extend mode (click on scatter plot for zooming to extend)')),
-                'cats_mgr' : MetaIcon(img = 'table-manager',
-                                          label = _('Show/hide class manager'))
-                }
-            
+            'selectGroup': MetaIcon(
+                img='layer-group-add',
+                label=_('Select imagery group')),
+            'settings': BaseIcons['settings'].SetLabel(
+                _('Settings')),
+            'help': MetaIcon(
+                img='help',
+                label=_('Show manual')),
+            'add_scatt_pl': MetaIcon(
+                img='layer-raster-analyze',
+                label=_('Add scatter plot')),
+            'selCatPol': MetaIcon(
+                img='polygon',
+                label=_('Select area with polygon')),
+            'pan': MetaIcon(
+                img='pan',
+                label=_('Pan mode for scatter plots')),
+            'zoomIn': MetaIcon(
+                img='zoom-in',
+                label=_('Zoom mode for scatter plots (left mouse button, wheel)')),
+            'zoomExtent': MetaIcon(
+                img='zoom-extent',
+                label=_('Zoom to scatter plot data extend mode (click on scatter plot for zooming to extend)')),
+            'cats_mgr': MetaIcon(
+                img='table-manager',
+                label=_('Show/hide class manager'))}
+
         tools = [
-                    ('add_scatt', icons["add_scatt_pl"],
-                    lambda event : self.scatt_mgr.AddScattPlot()),
-                    (None, ),
-                    ("cats_mgr", icons['cats_mgr'],
-                    lambda event: self.parent.ShowCategoryPanel(event.Checked()), wx.ITEM_CHECK),
-                    (None, ),
-                    ("pan", icons["pan"],
-                    lambda event: self.SetPloltsMode(event, 'pan'),
-                    wx.ITEM_CHECK),
-                    ("zoom", icons["zoomIn"],
-                    lambda event: self.SetPloltsMode(event, 'zoom'),
-                    wx.ITEM_CHECK),
-                    ("zoom_extend", icons["zoomExtent"],
-                    lambda event: self.SetPloltsMode(event, 'zoom_extend'),
-                    wx.ITEM_CHECK),
-                    (None, ),
-                    ('sel_pol_mode', icons['selCatPol'],
-                    self.ActivateSelectionPolygonMode,
-                    wx.ITEM_CHECK),
-                    (None, ),
-                    ('settings', icons["settings"],
-                    self.OnSettings),
-                    ('help', icons["help"],
-                     self.OnHelp)                    
-                ]
+            ('add_scatt', icons["add_scatt_pl"],
+             lambda event: self.scatt_mgr.AddScattPlot()),
+            (None,),
+            ("cats_mgr", icons['cats_mgr'],
+             lambda event: self.parent.ShowCategoryPanel(event.Checked()),
+             wx.ITEM_CHECK),
+            (None,),
+            ("pan", icons["pan"],
+             lambda event: self.SetPloltsMode(event, 'pan'),
+             wx.ITEM_CHECK),
+            ("zoom", icons["zoomIn"],
+             lambda event: self.SetPloltsMode(event, 'zoom'),
+             wx.ITEM_CHECK),
+            ("zoom_extend", icons["zoomExtent"],
+             lambda event: self.SetPloltsMode(event, 'zoom_extend'),
+             wx.ITEM_CHECK),
+            (None,),
+            ('sel_pol_mode', icons['selCatPol'],
+             self.ActivateSelectionPolygonMode, wx.ITEM_CHECK),
+            (None,),
+            ('settings', icons["settings"],
+             self.OnSettings),
+            ('help', icons["help"],
+             self.OnHelp)]
 
         if self.opt_tools and "add_group" in self.opt_tools:
             tools.insert(0, ("selectGroup", icons['selectGroup'],
-                             lambda event : self.scatt_mgr.SetData()))
+                             lambda event: self.scatt_mgr.SetData()))
 
         return self._getToolbarData(tools)
 
-    def GetToolId(self, toolName): #TODO can be useful in base
-        return vars(self)[toolName]            
+    def GetToolId(self, toolName):  # TODO can be useful in base
+        return vars(self)[toolName]
 
     def SetPloltsMode(self, event, tool_name):
         self.scatt_mgr.modeSet.disconnect(self.ModeSet)
-        if event.Checked()  == True:
-            for i_tool_data in  self._data:
+        if event.Checked() == True:
+            for i_tool_data in self._data:
                 i_tool_name = i_tool_data[0]
-                if not i_tool_name or i_tool_name in ["cats_mgr", "sel_pol_mode"]:
+                if not i_tool_name or i_tool_name in [
+                        "cats_mgr", "sel_pol_mode"]:
                     continue
                 if i_tool_name == tool_name:
                     continue
                 i_tool_id = vars(self)[i_tool_name]
                 self.ToggleTool(i_tool_id, False)
 
-            self.scatt_mgr.SetPlotsMode(mode = tool_name)
+            self.scatt_mgr.SetPlotsMode(mode=tool_name)
         else:
-            self.scatt_mgr.SetPlotsMode(mode = None)
+            self.scatt_mgr.SetPlotsMode(mode=None)
         self.scatt_mgr.modeSet.connect(self.ModeSet)
 
     def ActivateSelectionPolygonMode(self, event):
 
-        activated = self.scatt_mgr.ActivateSelectionPolygonMode(event.Checked())
+        activated = self.scatt_mgr.ActivateSelectionPolygonMode(
+            event.Checked())
         self.parent.ShowPlotEditingToolbar(activated)
 
         i_tool_id = vars(self)['sel_pol_mode']
@@ -123,33 +134,35 @@
         self.UnsetMode()
 
     def UnsetMode(self):
-        for i_tool_data in  self._data:
-                i_tool_name = i_tool_data[0]
-                if not i_tool_name or i_tool_name in ["cats_mgr", "sel_pol_mode"]:
-                    continue
-                i_tool_id = vars(self)[i_tool_name]
-                self.ToggleTool(i_tool_id, False)
+        for i_tool_data in self._data:
+            i_tool_name = i_tool_data[0]
+            if not i_tool_name or i_tool_name in ["cats_mgr", "sel_pol_mode"]:
+                continue
+            i_tool_id = vars(self)[i_tool_name]
+            self.ToggleTool(i_tool_id, False)
 
     def OnSettings(self, event):
-        dlg = SettingsDialog(parent=self, id=wx.ID_ANY, 
-                             title=_('Settings'), scatt_mgr = self.scatt_mgr)
-        
+        dlg = SettingsDialog(parent=self, id=wx.ID_ANY,
+                             title=_('Settings'), scatt_mgr=self.scatt_mgr)
+
         dlg.ShowModal()
         dlg.Destroy()
 
-    def OnHelp(self, event) :
-            RunCommand('g.manual',
-                       entry = 'wxGUI.iscatt')
+    def OnHelp(self, event):
+        RunCommand('g.manual',
+                   entry='wxGUI.iscatt')
 
+
 class EditingToolbar(BaseToolbar):
     """Main toolbar
     """
+
     def __init__(self, parent, scatt_mgr):
         BaseToolbar.__init__(self, parent)
         self.scatt_mgr = scatt_mgr
 
         self.InitToolbar(self._toolbarData())
-        
+
         # realize the toolbar
         self.Realize()
         self.scatt_mgr.modeSet.connect(self.ModeSet)
@@ -158,55 +171,54 @@
         """Toolbar data
         """
         self.icons = {
-            'sel_add'         : MetaIcon(img = 'layer-add',
-                                         label = _('Include selected area to class'),
-                                         desc = _('Include selected area to class')),
-            'sel_remove'      : MetaIcon(img = 'layer-remove',
-                                         label = _('Exclude selected area from class'),
-                                         desc = _('Exclude selected area from class')),
-            'addVertex'       : MetaIcon(img = 'vertex-create',
-                                         label = _('Add new vertex'),
-                                         desc = _('Add new vertex to polygon boundary scatter plot')),
-            'editLine'        : MetaIcon(img = 'polygon-create',
-                                         label = _('Create selection polygon'),
-                                         desc = _('Add new vertex between last and first points of the boundary')),
-            'moveVertex'      : MetaIcon(img = 'vertex-move',
-                                         label = _('Move vertex'),
-                                         desc = _('Move boundary vertex')),
-            'removeVertex'    : MetaIcon(img = 'vertex-delete',
-                                         label = _('Remove vertex'),
-                                         desc = _('Remove boundary vertex')),
-            'delete'        : MetaIcon(img = 'polygon-delete',
-                                       label = _("Remove polygon (click on scatter plot for removing it's polygon)")),
-            }
+            'sel_add': MetaIcon(img='layer-add',
+                                label=_('Include selected area to class'),
+                                desc=_('Include selected area to class')),
+            'sel_remove': MetaIcon(img='layer-remove',
+                                   label=_('Exclude selected area from class'),
+                                   desc=_('Exclude selected area from class')),
+            'addVertex': MetaIcon(img='vertex-create',
+                                  label=_('Add new vertex'),
+                                  desc=_('Add new vertex to polygon boundary scatter plot')),
+            'editLine': MetaIcon(img='polygon-create',
+                                 label=_('Create selection polygon'),
+                                 desc=_('Add new vertex between last and first points of the boundary')),
+            'moveVertex': MetaIcon(img='vertex-move',
+                                   label=_('Move vertex'),
+                                   desc=_('Move boundary vertex')),
+            'removeVertex': MetaIcon(img='vertex-delete',
+                                     label=_('Remove vertex'),
+                                     desc=_('Remove boundary vertex')),
+            'delete': MetaIcon(img='polygon-delete',
+                               label=_("Remove polygon (click on scatter plot for removing it's polygon)")),
+        }
 
-        return self._getToolbarData((
-                                    ("sel_add", self.icons["sel_add"],
-                                     lambda event: self.scatt_mgr.ProcessSelectionPolygons('add')),
-                                     ("sel_remove", self.icons['sel_remove'],
-                                     lambda event: self.scatt_mgr.ProcessSelectionPolygons('remove')),
-                                     (None, ),
-                                     ("add_vertex", self.icons["editLine"],
-                                     lambda event: self.SetMode(event, 'add_vertex'),
-                                     wx.ITEM_CHECK),
-                                     ("add_boundary_vertex", self.icons['addVertex'],
-                                     lambda event: self.SetMode(event, 'add_boundary_vertex'),
-                                     wx.ITEM_CHECK),
-                                     ("move_vertex", self.icons["moveVertex"],
-                                     lambda event: self.SetMode(event, 'move_vertex'),
-                                     wx.ITEM_CHECK),
-                                     ('delete_vertex', self.icons['removeVertex'],
-                                     lambda event: self.SetMode(event, 'delete_vertex'),
-                                     wx.ITEM_CHECK),
-                                     ('remove_polygon', self.icons['delete'],
-                                     lambda event: self.SetMode(event, 'remove_polygon'),
-                                     wx.ITEM_CHECK)
-                                    ))
+        return self._getToolbarData(
+            (("sel_add", self.icons["sel_add"],
+              lambda event: self.scatt_mgr.ProcessSelectionPolygons('add')),
+             ("sel_remove", self.icons['sel_remove'],
+              lambda event: self.scatt_mgr.ProcessSelectionPolygons('remove')),
+             (None,),
+             ("add_vertex", self.icons["editLine"],
+              lambda event: self.SetMode(event, 'add_vertex'),
+              wx.ITEM_CHECK),
+             ("add_boundary_vertex", self.icons['addVertex'],
+              lambda event: self.SetMode(event, 'add_boundary_vertex'),
+              wx.ITEM_CHECK),
+             ("move_vertex", self.icons["moveVertex"],
+              lambda event: self.SetMode(event, 'move_vertex'),
+              wx.ITEM_CHECK),
+             ('delete_vertex', self.icons['removeVertex'],
+              lambda event: self.SetMode(event, 'delete_vertex'),
+              wx.ITEM_CHECK),
+             ('remove_polygon', self.icons['delete'],
+              lambda event: self.SetMode(event, 'remove_polygon'),
+              wx.ITEM_CHECK)))
 
     def SetMode(self, event, tool_name):
         self.scatt_mgr.modeSet.disconnect(self.ModeSet)
         if event.Checked() == True:
-            for i_tool_data in  self._data:
+            for i_tool_data in self._data:
                 i_tool_name = i_tool_data[0]
                 if not i_tool_name:
                     continue
@@ -225,19 +237,21 @@
             self.UnsetMode()
 
     def UnsetMode(self):
-        for i_tool_data in  self._data:
-                i_tool_name = i_tool_data[0]
-                if not i_tool_name:
-                    continue
-                i_tool_id = vars(self)[i_tool_name]
-                self.ToggleTool(i_tool_id, False)
+        for i_tool_data in self._data:
+            i_tool_name = i_tool_data[0]
+            if not i_tool_name:
+                continue
+            i_tool_id = vars(self)[i_tool_name]
+            self.ToggleTool(i_tool_id, False)
 
     def GetToolId(self, toolName):
         return vars(self)[toolName]
 
+
 class CategoryToolbar(BaseToolbar):
     """Main toolbar
     """
+
     def __init__(self, parent, scatt_mgr, cats_list):
         BaseToolbar.__init__(self, parent)
         self.scatt_mgr = scatt_mgr
@@ -245,7 +259,7 @@
         self.cats_list = cats_list
 
         self.InitToolbar(self._toolbarData())
-        
+
         # realize the toolbar
         self.Realize()
 
@@ -253,15 +267,14 @@
         """Toolbar data
         """
         self.icons = {
-            'add_class'     : MetaIcon(img = 'layer-add',
-                                       label = _('Add class')),
-            'remove_class'  : MetaIcon(img = 'layer-remove',
-                                       label = _('Remove selected class'))
-            }
+            'add_class': MetaIcon(img='layer-add',
+                                  label=_('Add class')),
+            'remove_class': MetaIcon(img='layer-remove',
+                                     label=_('Remove selected class'))
+        }
 
-        return self._getToolbarData((
-                                    ("add_class", self.icons["add_class"],
-                                     lambda event: self.cats_mgr.AddCategory()),
-                                     ("remove_class", self.icons['remove_class'],
-                                     lambda event: self.cats_list.DeleteCategory()),
-                                    ))
+        return self._getToolbarData(
+            (("add_class", self.icons["add_class"],
+              lambda event: self.cats_mgr.AddCategory()),
+             ("remove_class", self.icons['remove_class'],
+              lambda event: self.cats_list.DeleteCategory()),))

Modified: grass/trunk/gui/wxpython/lmgr/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/lmgr/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/lmgr/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -6,4 +6,4 @@
     'frame',
     'giface',
     'datacatalog'
-    ]
+]

Modified: grass/trunk/gui/wxpython/lmgr/frame.py
===================================================================
--- grass/trunk/gui/wxpython/lmgr/frame.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/lmgr/frame.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -28,65 +28,68 @@
 try:
     import xml.etree.ElementTree as etree
 except ImportError:
-    import elementtree.ElementTree as etree # Python <= 2.4
+    import elementtree.ElementTree as etree  # Python <= 2.4
 
 from core import globalvar
 import wx
 import wx.aui
 try:
-    import wx.lib.agw.flatnotebook   as FN
+    import wx.lib.agw.flatnotebook as FN
 except ImportError:
-    import wx.lib.flatnotebook   as FN
+    import wx.lib.flatnotebook as FN
 
 if os.path.join(globalvar.ETCDIR, "python") not in sys.path:
     sys.path.append(os.path.join(globalvar.ETCDIR, "python"))
 
-from grass.script          import core as grass
+from grass.script import core as grass
 
-from core.gcmd             import RunCommand, GError, GMessage, EncodeString
-from core.settings         import UserSettings, GetDisplayVectSettings
-from core.utils            import SetAddOnPath, GetLayerNameFromCmd, command2ltype, _
-from gui_core.preferences  import MapsetAccess, PreferencesDialog
-from lmgr.layertree        import LayerTree, LMIcons
-from lmgr.menudata         import LayerManagerMenuData, LayerManagerModuleTree
-from gui_core.widgets      import GNotebook, FormNotebook
+from core.gcmd import RunCommand, GError, GMessage, EncodeString
+from core.settings import UserSettings, GetDisplayVectSettings
+from core.utils import SetAddOnPath, GetLayerNameFromCmd, command2ltype, _
+from gui_core.preferences import MapsetAccess, PreferencesDialog
+from lmgr.layertree import LayerTree, LMIcons
+from lmgr.menudata import LayerManagerMenuData, LayerManagerModuleTree
+from gui_core.widgets import GNotebook, FormNotebook
 from modules.mcalc_builder import MapCalcFrame
-from dbmgr.manager         import AttributeManager
-from core.workspace        import ProcessWorkspaceFile, ProcessGrcFile, WriteWorkspaceFile
-from core.gconsole         import GConsole, EVT_IGNORED_CMD_RUN
-from core.giface           import Notification
-from gui_core.goutput      import GConsoleWindow, GC_SEARCH, GC_PROMPT
+from dbmgr.manager import AttributeManager
+from core.workspace import ProcessWorkspaceFile, ProcessGrcFile, WriteWorkspaceFile
+from core.gconsole import GConsole, EVT_IGNORED_CMD_RUN
+from core.giface import Notification
+from gui_core.goutput import GConsoleWindow, GC_SEARCH, GC_PROMPT
 from modules.import_export import GdalOutputDialog, DxfImportDialog, GdalImportDialog, OgrImportDialog
-from gui_core.dialogs      import LocationDialog, MapsetDialog, CreateNewVector, GroupDialog, MapLayersDialog, QuitDialog
-from modules.colorrules    import RasterColorTable, VectorColorTable
-from gui_core.menu         import Menu, SearchModuleWindow
-from gmodeler.model        import Model
-from gmodeler.frame        import ModelFrame
-from psmap.frame           import PsMapFrame
-from core.debug            import Debug
-from gui_core.ghelp        import AboutWindow
-from modules.extensions    import InstallExtensionWindow, ManageExtensionWindow
-from lmgr.toolbars         import LMWorkspaceToolbar, LMDataToolbar, LMToolsToolbar
-from lmgr.toolbars         import LMMiscToolbar, LMVectorToolbar, LMNvizToolbar
-from lmgr.pyshell          import PyShellWindow
-from lmgr.giface           import LayerManagerGrassInterface
-from datacatalog.catalog   import DataCatalog
-from gui_core.forms        import GUI
-from gcp.manager           import GCPWizard
-from nviz.main             import haveNviz
-from nviz.preferences      import NvizPreferencesDialog
-from mapswipe.frame        import SwipeMapFrame
-from rlisetup.frame        import RLiSetupFrame
+from gui_core.dialogs import LocationDialog, MapsetDialog, CreateNewVector, GroupDialog, MapLayersDialog, QuitDialog
+from modules.colorrules import RasterColorTable, VectorColorTable
+from gui_core.menu import Menu, SearchModuleWindow
+from gmodeler.model import Model
+from gmodeler.frame import ModelFrame
+from psmap.frame import PsMapFrame
+from core.debug import Debug
+from gui_core.ghelp import AboutWindow
+from modules.extensions import InstallExtensionWindow, ManageExtensionWindow
+from lmgr.toolbars import LMWorkspaceToolbar, LMDataToolbar, LMToolsToolbar
+from lmgr.toolbars import LMMiscToolbar, LMVectorToolbar, LMNvizToolbar
+from lmgr.pyshell import PyShellWindow
+from lmgr.giface import LayerManagerGrassInterface
+from datacatalog.catalog import DataCatalog
+from gui_core.forms import GUI
+from gcp.manager import GCPWizard
+from nviz.main import haveNviz
+from nviz.preferences import NvizPreferencesDialog
+from mapswipe.frame import SwipeMapFrame
+from rlisetup.frame import RLiSetupFrame
 
+
 class GMFrame(wx.Frame):
     """Layer Manager frame with notebook widget for controlling GRASS
     GIS. Includes command console page for typing GRASS (and other)
     commands, tree widget page for managing map layers.
     """
-    def __init__(self, parent, id = wx.ID_ANY, title = None,
-                 workspace = None,
-                 size = globalvar.GM_WINDOW_SIZE, style = wx.DEFAULT_FRAME_STYLE, **kwargs):
-        self.parent    = parent
+
+    def __init__(
+            self, parent, id=wx.ID_ANY, title=None, workspace=None,
+            size=globalvar.GM_WINDOW_SIZE, style=wx.DEFAULT_FRAME_STYLE, **
+            kwargs):
+        self.parent = parent
         if title:
             self.baseTitle = title
         else:
@@ -97,67 +100,72 @@
                 grassVersion = "?"
             self.baseTitle = _("GRASS GIS %s Layer Manager") % grassVersion
 
-        self.iconsize  = (16, 16)
+        self.iconsize = (16, 16)
 
-        self.displayIndex    = 0          # index value for map displays and layer trees
-        self.currentPage     = None       # currently selected page for layer tree notebook
-        self.currentPageNum  = None       # currently selected page number for layer tree notebook
+        self.displayIndex = 0          # index value for map displays and layer trees
+        self.currentPage = None       # currently selected page for layer tree notebook
+        self.currentPageNum = None       # currently selected page number for layer tree notebook
         self.workspaceFile = workspace    # workspace file
         self.workspaceChanged = False     # track changes in workspace
-        self.loadingWorkspace = False     # if we are currently loading workspace to ignore some events
+        # if we are currently loading workspace to ignore some events
+        self.loadingWorkspace = False
         self.cwdPath = None               # current working directory
 
-        wx.Frame.__init__(self, parent = parent, id = id, size = size,
-                          style = style, **kwargs)
+        wx.Frame.__init__(self, parent=parent, id=id, size=size,
+                          style=style, **kwargs)
         self._setTitle()
         self.SetName("LayerManager")
-        
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
-        
+
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass.ico'),
+                wx.BITMAP_TYPE_ICO))
+
         self._giface = LayerManagerGrassInterface(self)
-        
+
         # the main menu bar
         self._menuTreeBuilder = LayerManagerMenuData()
         # the search tree and command console
         self._moduleTreeBuilder = LayerManagerModuleTree()
         self._auimgr = wx.aui.AuiManager(self)
-        
-        
+
         # list of open dialogs
-        self.dialogs        = dict()
+        self.dialogs = dict()
         self.dialogs['preferences'] = None
         self.dialogs['nvizPreferences'] = None
         self.dialogs['atm'] = list()
-        
+
         # create widgets
         self._createMenuBar()
-        self.statusbar = self.CreateStatusBar(number = 1)
-        self.notebook  = self._createNoteBook()
-        self.toolbars  = { 'workspace' : LMWorkspaceToolbar(parent = self),
-                           'data'      : LMDataToolbar(parent = self),
-                           'tools'     : LMToolsToolbar(parent = self),
-                           'misc'      : LMMiscToolbar(parent = self),
-                           'vector'    : LMVectorToolbar(parent = self),
-                           'nviz'      : LMNvizToolbar(parent = self)}
-        self._toolbarsData = { 'workspace' : ("toolbarWorkspace",     # name
-                                              _("Workspace Toolbar"), # caption
-                                              1),                     # row
-                               'data'      : ("toolbarData",
-                                              _("Data Toolbar"),
-                                              1),
-                               'misc'      : ("toolbarMisc",
-                                              _("Misc Toolbar"),
-                                              2),
-                               'tools'     : ("toolbarTools",
-                                              _("Tools Toolbar"),
-                                              2),
-                               'vector'    : ("toolbarVector",
-                                              _("Vector Toolbar"),
-                                              2),
-                               'nviz'      : ("toolbarNviz",
-                                              _("3D view Toolbar"),
-                                              2),                                            
-                               }
+        self.statusbar = self.CreateStatusBar(number=1)
+        self.notebook = self._createNoteBook()
+        self.toolbars = {'workspace': LMWorkspaceToolbar(parent=self),
+                         'data': LMDataToolbar(parent=self),
+                         'tools': LMToolsToolbar(parent=self),
+                         'misc': LMMiscToolbar(parent=self),
+                         'vector': LMVectorToolbar(parent=self),
+                         'nviz': LMNvizToolbar(parent=self)}
+        self._toolbarsData = {'workspace': ("toolbarWorkspace",     # name
+                                            _("Workspace Toolbar"),  # caption
+                                            1),                     # row
+                              'data': ("toolbarData",
+                                       _("Data Toolbar"),
+                                       1),
+                              'misc': ("toolbarMisc",
+                                       _("Misc Toolbar"),
+                                       2),
+                              'tools': ("toolbarTools",
+                                        _("Tools Toolbar"),
+                                        2),
+                              'vector': ("toolbarVector",
+                                         _("Vector Toolbar"),
+                                         2),
+                              'nviz': ("toolbarNviz",
+                                       _("3D view Toolbar"),
+                                       2),
+                              }
         if sys.platform == 'win32':
             self._toolbarsList = ('workspace', 'data',
                                   'vector', 'tools', 'misc', 'nviz')
@@ -174,10 +182,10 @@
                                  BottomDockable(False).TopDockable(True).
                                  CloseButton(False).Layer(2).
                                  BestSize((self.toolbars[toolbar].GetBestSize())))
-            
+
         self._auimgr.GetPane('toolbarNviz').Hide()
         # bindings
-        self.Bind(wx.EVT_CLOSE,    self.OnCloseWindowOrExit)
+        self.Bind(wx.EVT_CLOSE, self.OnCloseWindowOrExit)
         self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
 
         self._giface.mapCreated.connect(self.OnMapCreated)
@@ -188,30 +196,34 @@
 
         # AUI stuff
         self._auimgr.AddPane(self.notebook, wx.aui.AuiPaneInfo().
-                             Left().CentrePane().BestSize((-1,-1)).Dockable(False).
+                             Left().CentrePane().BestSize((-1, -1)).Dockable(False).
                              CloseButton(False).DestroyOnClose(True).Row(1).Layer(0))
 
         self._auimgr.Update()
 
         wx.CallAfter(self.notebook.SetSelectionByName, 'layers')
-        
+
         # use default window layout ?
-        if UserSettings.Get(group = 'general', key = 'defWindowPos', subkey = 'enabled'):
-            dim = UserSettings.Get(group = 'general', key = 'defWindowPos', subkey = 'dim')
+        if UserSettings.Get(
+                group='general', key='defWindowPos', subkey='enabled'):
+            dim = UserSettings.Get(
+                group='general',
+                key='defWindowPos',
+                subkey='dim')
             try:
-               x, y = map(int, dim.split(',')[0:2])
-               w, h = map(int, dim.split(',')[2:4])
-               self.SetPosition((x, y))
-               self.SetSize((w, h))
+                x, y = map(int, dim.split(',')[0:2])
+                w, h = map(int, dim.split(',')[2:4])
+                self.SetPosition((x, y))
+                self.SetSize((w, h))
             except:
                 pass
         else:
             # does center (of screen) make sense for lmgr?
             self.Centre()
-        
+
         self.Layout()
         self.Show()
-        
+
         # load workspace file if requested
         if self.workspaceFile:
             # load given workspace file
@@ -221,21 +233,21 @@
                 self.workspaceFile = None
         else:
             # start default initial display
-            self.NewDisplay(show = False)
+            self.NewDisplay(show=False)
 
         # show map display widnow
         # -> OnSize() -> UpdateMap()
-        for mapdisp in self.GetMapDisplay(onlyCurrent = False):
+        for mapdisp in self.GetMapDisplay(onlyCurrent=False):
             mapdisp.Show()
-        
+
         # redirect stderr to log area
         self._gconsole.Redirect()
-        
+
         # fix goutput's pane size (required for Mac OSX)`
         self.goutput.SetSashPosition(int(self.GetSize()[1] * .8))
-        
+
         self.workspaceChanged = False
-        
+
         # start with layer manager on top
         if self.currentPage:
             self.GetMapDisplay().Raise()
@@ -244,67 +256,91 @@
     def _setTitle(self):
         """Set frame title"""
         if self.workspaceFile:
-            self.SetTitle(self.baseTitle + " - " +  os.path.splitext(os.path.basename(self.workspaceFile))[0])
+            self.SetTitle(
+                self.baseTitle +
+                " - " +
+                os.path.splitext(
+                    os.path.basename(
+                        self.workspaceFile))[0])
         else:
             self.SetTitle(self.baseTitle)
-        
+
     def _createMenuBar(self):
         """Creates menu bar"""
-        self.menubar = Menu(parent=self, model=self._menuTreeBuilder.GetModel(separators=True))
+        self.menubar = Menu(
+            parent=self,
+            model=self._menuTreeBuilder.GetModel(
+                separators=True))
         self.SetMenuBar(self.menubar)
         self.menucmd = self.menubar.GetCmd()
-        
+
     def _createTabMenu(self):
         """Creates context menu for display tabs.
-        
+
         Used to rename display.
         """
         menu = wx.Menu()
-        item = wx.MenuItem(menu, id = wx.ID_ANY, text = _("Rename Map Display"))
+        item = wx.MenuItem(menu, id=wx.ID_ANY, text=_("Rename Map Display"))
         menu.AppendItem(item)
         self.Bind(wx.EVT_MENU, self.OnRenameDisplay, item)
-        
+
         return menu
-        
+
     def _setCopyingOfSelectedText(self):
-        copy = UserSettings.Get(group = 'manager', key = 'copySelectedTextToClipboard', subkey = 'enabled')
+        copy = UserSettings.Get(
+            group='manager',
+            key='copySelectedTextToClipboard',
+            subkey='enabled')
         self.goutput.SetCopyingOfSelectedText(copy)
-    
+
     def IsPaneShown(self, name):
         """Check if pane (toolbar, ...) of given name is currently shown"""
         if self._auimgr.GetPane(name).IsOk():
             return self._auimgr.GetPane(name).IsShown()
         return False
-    
+
     def _createNoteBook(self):
         """Creates notebook widgets"""
         if sys.platform == 'win32':
-            self.notebook = GNotebook(parent=self, style=globalvar.FNPageDStyle)
+            self.notebook = GNotebook(
+                parent=self, style=globalvar.FNPageDStyle)
         else:
             self.notebook = FormNotebook(parent=self, style=wx.NB_BOTTOM)
         # create displays notebook widget and add it to main notebook page
         cbStyle = globalvar.FNPageStyle
         if globalvar.hasAgw:
-            self.notebookLayers = FN.FlatNotebook(self.notebook, id=wx.ID_ANY, agwStyle=cbStyle)
+            self.notebookLayers = FN.FlatNotebook(
+                self.notebook, id=wx.ID_ANY, agwStyle=cbStyle)
         else:
-            self.notebookLayers = FN.FlatNotebook(self.notebook, id=wx.ID_ANY, style=cbStyle)
+            self.notebookLayers = FN.FlatNotebook(
+                self.notebook, id=wx.ID_ANY, style=cbStyle)
         self.notebookLayers.SetTabAreaColour(globalvar.FNPageColor)
         menu = self._createTabMenu()
         self.notebookLayers.SetRightClickMenu(menu)
-        self.notebook.AddPage(page = self.notebookLayers, text = _("Layers"), name = 'layers')
-        
+        self.notebook.AddPage(
+            page=self.notebookLayers,
+            text=_("Layers"),
+            name='layers')
+
         # create 'command output' text area
-        self._gconsole = GConsole(guiparent = self, giface = self._giface,
-                                  ignoredCmdPattern = '^d\..*|^r[3]?\.mapcalc$|^i.group$|^r.in.gdal$|'
-                                                      '^r.external$|^r.external.out$|'
-                                                      '^v.in.ogr$|^v.external$|^v.external.out$|'
-                                                      '^cd$|^cd .*')
-        self.goutput = GConsoleWindow(parent=self.notebook, gconsole=self._gconsole,
-                                      menuModel=self._moduleTreeBuilder.GetModel(),
-                                      gcstyle = GC_PROMPT)
-        self.notebook.AddPage(page = self.goutput, text = _("Console"), name = 'output')
+        self._gconsole = GConsole(
+            guiparent=self, giface=self._giface,
+            ignoredCmdPattern='^d\..*|^r[3]?\.mapcalc$|^i.group$|^r.in.gdal$|'
+            '^r.external$|^r.external.out$|'
+            '^v.in.ogr$|^v.external$|^v.external.out$|'
+            '^cd$|^cd .*')
+        self.goutput = GConsoleWindow(
+            parent=self.notebook,
+            gconsole=self._gconsole,
+            menuModel=self._moduleTreeBuilder.GetModel(),
+            gcstyle=GC_PROMPT)
+        self.notebook.AddPage(
+            page=self.goutput,
+            text=_("Console"),
+            name='output')
 
-        self.goutput.showNotification.connect(lambda message: self.SetStatusText(message))
+        self.goutput.showNotification.connect(
+            lambda message: self.SetStatusText(message))
 
         self._gconsole.mapCreated.connect(self.OnMapCreated)
         self.goutput.contentChanged.connect(
@@ -314,38 +350,62 @@
                             lambda event: self.RunSpecialCmd(event.cmd))
 
         self._setCopyingOfSelectedText()
-        
+
         # create 'search module' notebook page
-        if not UserSettings.Get(group = 'manager', key = 'hideTabs', subkey = 'search'):
-            self.search = SearchModuleWindow(parent=self.notebook, handlerObj=self,
-                                             model=self._moduleTreeBuilder.GetModel())
-            self.search.showNotification.connect(lambda message: self.SetStatusText(message))
-            self.notebook.AddPage(page = self.search, text = _("Modules"), name = 'search')
+        if not UserSettings.Get(
+                group='manager', key='hideTabs', subkey='search'):
+            self.search = SearchModuleWindow(
+                parent=self.notebook, handlerObj=self,
+                model=self._moduleTreeBuilder.GetModel())
+            self.search.showNotification.connect(
+                lambda message: self.SetStatusText(message))
+            self.notebook.AddPage(
+                page=self.search,
+                text=_("Modules"),
+                name='search')
         else:
             self.search = None
-        
+
         # create 'data catalog' notebook page
-        self.datacatalog = DataCatalog(parent=self.notebook, giface=self._giface)
-        self.datacatalog.showNotification.connect(lambda message: self.SetStatusText(message))
-        self.notebook.AddPage(page = self.datacatalog, text = _("Data"), name = 'catalog')
-        
+        self.datacatalog = DataCatalog(
+            parent=self.notebook, giface=self._giface)
+        self.datacatalog.showNotification.connect(
+            lambda message: self.SetStatusText(message))
+        self.notebook.AddPage(
+            page=self.datacatalog,
+            text=_("Data"),
+            name='catalog')
+
         # create 'python shell' notebook page
-        if not UserSettings.Get(group = 'manager', key = 'hideTabs', subkey = 'pyshell'):
-            self.pyshell = PyShellWindow(parent=self.notebook, giface=self._giface)
-            self.notebook.AddPage(page = self.pyshell, text = _("Python"), name = 'pyshell')
+        if not UserSettings.Get(
+                group='manager', key='hideTabs', subkey='pyshell'):
+            self.pyshell = PyShellWindow(
+                parent=self.notebook, giface=self._giface)
+            self.notebook.AddPage(
+                page=self.pyshell,
+                text=_("Python"),
+                name='pyshell')
         else:
             self.pyshell = None
-        
+
         # bindings
         if sys.platform == 'win32':
-            self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
+            self.notebook.Bind(
+                FN.EVT_FLATNOTEBOOK_PAGE_CHANGED,
+                self.OnPageChanged)
         else:
-            self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
-        self.notebookLayers.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED,    self.OnCBPageChanged)
-        self.notebookLayers.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CLOSING,    self.OnCBPageClosed)
-        
+            self.notebook.Bind(
+                wx.EVT_NOTEBOOK_PAGE_CHANGED,
+                self.OnPageChanged)
+        self.notebookLayers.Bind(
+            FN.EVT_FLATNOTEBOOK_PAGE_CHANGED,
+            self.OnCBPageChanged)
+        self.notebookLayers.Bind(
+            FN.EVT_FLATNOTEBOOK_PAGE_CLOSING,
+            self.OnCBPageClosed)
+
         return self.notebook
-            
+
     def AddNvizTools(self, firstTime):
         """Add nviz notebook page
 
@@ -355,106 +415,119 @@
         Debug.msg(5, "GMFrame.AddNvizTools()")
         if not haveNviz:
             return
-        
+
         from nviz.main import NvizToolWindow
-        
+
         # show toolbar
         self._auimgr.GetPane('toolbarNviz').Show()
         # reorder other toolbars
-        for pos, toolbar in enumerate(('toolbarVector', 'toolbarTools', 'toolbarMisc','toolbarNviz')):
+        for pos, toolbar in enumerate(
+                ('toolbarVector', 'toolbarTools', 'toolbarMisc', 'toolbarNviz')):
             self._auimgr.GetPane(toolbar).Row(2).Position(pos)
         self._auimgr.Update()
-        
+
         # create nviz tools tab
-        self.nviz = NvizToolWindow(parent=self.notebook, tree=self.GetLayerTree(),
-                                   display=self.GetMapDisplay())
+        self.nviz = NvizToolWindow(
+            parent=self.notebook,
+            tree=self.GetLayerTree(),
+            display=self.GetMapDisplay())
         idx = self.notebook.GetPageIndexByName('layers')
-        self.notebook.InsertPage(index=idx + 1, page=self.nviz, text=_("3D view"), name='nviz')
+        self.notebook.InsertPage(
+            index=idx + 1,
+            page=self.nviz,
+            text=_("3D view"),
+            name='nviz')
         self.notebook.SetSelectionByName('nviz')
 
         # this is a bit strange here since a new window is created everytime
         if not firstTime:
-            for page in ('view', 'light', 'fringe', 'constant', 'cplane', 'animation'):
+            for page in ('view', 'light', 'fringe',
+                         'constant', 'cplane', 'animation'):
                 self.nviz.UpdatePage(page)
 
     def RemoveNvizTools(self):
         """Remove nviz notebook page"""
-        # if more mapwindow3D were possible, check here if nb page should be removed
+        # if more mapwindow3D were possible, check here if nb page should be
+        # removed
         self.notebook.SetSelectionByName('layers')
         self.notebook.DeletePage('nviz')
 
         # hide toolbar
         self._auimgr.GetPane('toolbarNviz').Hide()
-        for pos, toolbar in enumerate(('toolbarVector', 'toolbarTools', 'toolbarMisc')):
+        for pos, toolbar in enumerate(
+                ('toolbarVector', 'toolbarTools', 'toolbarMisc')):
             self._auimgr.GetPane(toolbar).Row(2).Position(pos)
         self._auimgr.Update()
-    
+
     def WorkspaceChanged(self):
         """Update window title"""
         if not self.workspaceChanged:
             self.workspaceChanged = True
-        
+
         if self.workspaceFile:
             self._setTitle()
-        
+
     def OnLocationWizard(self, event):
         """Launch location wizard"""
         from location_wizard.wizard import LocationWizard
         from location_wizard.dialogs import RegionDef
-        
-        gWizard = LocationWizard(parent = self,
-                                 grassdatabase = grass.gisenv()['GISDBASE'])
+
+        gWizard = LocationWizard(parent=self,
+                                 grassdatabase=grass.gisenv()['GISDBASE'])
         location = gWizard.location
-        
-        if location !=  None:
-            dlg = wx.MessageDialog(parent = self,
-                                   message = _('Location <%s> created.\n\n'
-                                               'Do you want to switch to the '
-                                               'new location?') % location,
+
+        if location is not None:
+            dlg = wx.MessageDialog(parent=self,
+                                   message=_('Location <%s> created.\n\n'
+                                             'Do you want to switch to the '
+                                             'new location?') % location,
                                    caption=_("Switch to new location?"),
-                                   style = wx.YES_NO | wx.NO_DEFAULT |
+                                   style=wx.YES_NO | wx.NO_DEFAULT |
                                    wx.ICON_QUESTION | wx.CENTRE)
-            
+
             ret = dlg.ShowModal()
             dlg.Destroy()
             if ret == wx.ID_YES:
-                if RunCommand('g.mapset', parent = self,
-                              location = location,
-                              mapset = 'PERMANENT') != 0:
+                if RunCommand('g.mapset', parent=self,
+                              location=location,
+                              mapset='PERMANENT') != 0:
                     return
 
                 # close current workspace and create new one
                 self.OnWorkspaceClose()
                 self.OnWorkspaceNew()
-                GMessage(parent = self,
-                         message = _("Current location is <%(loc)s>.\n"
-                                     "Current mapset is <%(mapset)s>.") % \
-                             { 'loc' : location, 'mapset' : 'PERMANENT' })
+                GMessage(parent=self,
+                         message=_("Current location is <%(loc)s>.\n"
+                                   "Current mapset is <%(mapset)s>.") %
+                         {'loc': location, 'mapset': 'PERMANENT'})
 
                 # code duplication with gis_set.py
-                dlg = wx.MessageDialog(parent = self,
-                               message = _("Do you want to set the default "
-                                           "region extents and resolution now?"),
-                               caption = _("Location <%s> created") % location,
-                               style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
+                dlg = wx.MessageDialog(
+                    parent=self,
+                    message=_(
+                        "Do you want to set the default "
+                        "region extents and resolution now?"),
+                    caption=_("Location <%s> created") %
+                    location,
+                    style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
                 dlg.CenterOnScreen()
                 if dlg.ShowModal() == wx.ID_YES:
                     dlg.Destroy()
-                    defineRegion = RegionDef(self, location = location)
+                    defineRegion = RegionDef(self, location=location)
                     defineRegion.CenterOnScreen()
                     defineRegion.ShowModal()
                     defineRegion.Destroy()
                 else:
                     dlg.Destroy()
-        
+
     def OnSettingsChanged(self):
         """Here can be functions which have to be called
-        after receiving settingsChanged signal. 
+        after receiving settingsChanged signal.
         Now only set copying of selected text to clipboard (in goutput).
         """
-        ### self._createMenuBar() # bug when menu is re-created on the fly
+        # self._createMenuBar() # bug when menu is re-created on the fly
         self._setCopyingOfSelectedText()
-        
+
     def OnGCPManager(self, event=None, cmd=None):
         """Launch georectifier module. See OnIClass documentation.
         """
@@ -462,17 +535,17 @@
 
     def OnGModeler(self, event=None, cmd=None):
         """Launch Graphical Modeler. See OnIClass documentation."""
-        win = ModelFrame(parent = self, giface = self._giface)
+        win = ModelFrame(parent=self, giface=self._giface)
         win.CentreOnScreen()
-        
+
         win.Show()
-        
+
     def OnPsMap(self, event=None, cmd=None):
         """Launch Cartographic Composer. See OnIClass documentation.
         """
-        win = PsMapFrame(parent = self)
+        win = PsMapFrame(parent=self)
         win.CentreOnScreen()
-        
+
         win.Show()
 
     def OnMapSwipe(self, event=None, cmd=None):
@@ -483,9 +556,12 @@
         tree = self.GetLayerTree()
         if tree:
             for layer in tree.GetSelections():
-                if tree.GetLayerInfo(layer, key = 'maplayer').GetType() != 'raster':
+                if tree.GetLayerInfo(
+                        layer, key='maplayer').GetType() != 'raster':
                     continue
-                rasters.append(tree.GetLayerInfo(layer, key = 'maplayer').GetName())
+                rasters.append(
+                    tree.GetLayerInfo(
+                        layer, key='maplayer').GetName())
 
         if len(rasters) >= 1:
             win.SetFirstRaster(rasters[0])
@@ -498,60 +574,63 @@
 
     def OnRLiSetup(self, event=None, cmd=None):
         """Launch r.li Setup. See OnIClass documentation."""
-        win = RLiSetupFrame(parent = self)
+        win = RLiSetupFrame(parent=self)
         win.CentreOnScreen()
-        
+
         win.Show()
 
     def OnDone(self, event):
         """Command execution finished"""
         if hasattr(self, "model"):
-            self.model.DeleteIntermediateData(log = self._gconsole)
+            self.model.DeleteIntermediateData(log=self._gconsole)
             del self.model
         self.SetStatusText('')
-        
+
     def OnRunModel(self, event):
         """Run model"""
         filename = ''
-        dlg = wx.FileDialog(parent = self, message =_("Choose model to run"),
-                            defaultDir = os.getcwd(),
-                            wildcard = _("GRASS Model File (*.gxm)|*.gxm"))
+        dlg = wx.FileDialog(parent=self, message=_("Choose model to run"),
+                            defaultDir=os.getcwd(),
+                            wildcard=_("GRASS Model File (*.gxm)|*.gxm"))
         if dlg.ShowModal() == wx.ID_OK:
             filename = dlg.GetPath()
-        
+
         if not filename:
             dlg.Destroy()
             return
-        
+
         self.model = Model()
         self.model.LoadModel(filename)
-        self.model.Run(log = self.GetLogWindow(), onDone = self.OnDone, parent = self)
-        
+        self.model.Run(
+            log=self.GetLogWindow(),
+            onDone=self.OnDone,
+            parent=self)
+
         dlg.Destroy()
-        
+
     def OnMapsets(self, event):
         """Launch mapset access dialog
         """
-        dlg = MapsetAccess(parent = self, id = wx.ID_ANY)
+        dlg = MapsetAccess(parent=self, id=wx.ID_ANY)
         dlg.CenterOnScreen()
-        
+
         if dlg.ShowModal() == wx.ID_OK:
             ms = dlg.GetMapsets()
             RunCommand('g.mapsets',
-                       parent = self,
-                       mapset = '%s' % ','.join(ms),
-                       operation = 'set')
-        
+                       parent=self,
+                       mapset='%s' % ','.join(ms),
+                       operation='set')
+
     def OnCBPageChanged(self, event):
         """Page in notebook (display) changed"""
-        self.currentPage    = self.notebookLayers.GetCurrentPage()
+        self.currentPage = self.notebookLayers.GetCurrentPage()
         self.currentPageNum = self.notebookLayers.GetSelection()
         try:
             self.GetMapDisplay().SetFocus()
             self.GetMapDisplay().Raise()
         except:
             pass
-        
+
         event.Skip()
 
     def OnPageChanged(self, event):
@@ -562,29 +641,30 @@
         elif page == self.notebook.GetPageIndexByName('catalog'):
             wx.CallAfter(self.datacatalog.LoadItems)
         self.SetStatusText('', 0)
-        
+
         event.Skip()
 
     def OnCBPageClosed(self, event):
         """Page of notebook closed
         Also close associated map display
         """
-        if UserSettings.Get(group = 'manager', key = 'askOnQuit', subkey = 'enabled'):
+        if UserSettings.Get(group='manager', key='askOnQuit',
+                            subkey='enabled'):
             maptree = self.GetLayerTree()
-            
+
             if self.workspaceFile:
                 message = _("Do you want to save changes in the workspace?")
             else:
                 message = _("Do you want to store current settings "
                             "to workspace file?")
-            
+
             # ask user to save current settings
             if maptree.GetCount() > 0:
                 name = self.notebookLayers.GetPageText(self.currentPageNum)
                 dlg = wx.MessageDialog(self,
-                                       message = message,
-                                       caption = _("Close Map Display %s") % name,
-                                       style = wx.YES_NO | wx.YES_DEFAULT |
+                                       message=message,
+                                       caption=_("Close Map Display %s") % name,
+                                       style=wx.YES_NO | wx.YES_DEFAULT |
                                        wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
                 ret = dlg.ShowModal()
                 if ret == wx.ID_YES:
@@ -625,23 +705,23 @@
         if re.compile('^d\..*').search(command[0]):
             self.RunDisplayCmd(command)
         elif re.compile('r[3]?\.mapcalc').search(command[0]):
-            self.OnMapCalculator(event = None, cmd = command)
+            self.OnMapCalculator(event=None, cmd=command)
         elif command[0] == 'i.group':
-            self.OnEditImageryGroups(event = None, cmd = command)
+            self.OnEditImageryGroups(event=None, cmd=command)
         elif command[0] == 'r.in.gdal':
-            self.OnImportGdalLayers(event = None, cmd = command)
+            self.OnImportGdalLayers(event=None, cmd=command)
         elif command[0] == 'r.external':
-            self.OnLinkGdalLayers(event = None, cmd = command)
+            self.OnLinkGdalLayers(event=None, cmd=command)
         elif command[0] == 'r.external.out':
-             self.OnRasterOutputFormat(event = None)
+            self.OnRasterOutputFormat(event=None)
         elif command[0] == 'v.in.ogr':
-            self.OnImportOgrLayers(event = None, cmd = command)
+            self.OnImportOgrLayers(event=None, cmd=command)
         elif command[0] == 'v.external':
-            self.OnLinkOgrLayers(event = None, cmd = command)
+            self.OnLinkOgrLayers(event=None, cmd=command)
         elif command[0] == 'v.external.out':
-             self.OnVectorOutputFormat(event = None)
+            self.OnVectorOutputFormat(event=None)
         elif command[0] == 'cd':
-             self.OnChangeCWD(event=None, cmd=command)
+            self.OnChangeCWD(event=None, cmd=command)
         else:
             raise ValueError('Layer Manager special command (%s)'
                              ' not supported.' % ' '.join(command))
@@ -652,54 +732,57 @@
         :param command: command in a list
         """
         if not self.currentPage:
-            self.NewDisplay(show = True)
+            self.NewDisplay(show=True)
         try:
             # display GRASS commands
             layertype = command2ltype[command[0]]
         except KeyError:
-            GMessage(parent = self,
-                     message = _("Command '%s' not yet implemented in the WxGUI. "
-                                 "Try adding it as a command layer instead.") % command[0])
+            GMessage(
+                parent=self, message=_(
+                    "Command '%s' not yet implemented in the WxGUI. "
+                    "Try adding it as a command layer instead.") %
+                command[0])
             return
-        
+
         if layertype == 'barscale':
             if len(command) > 1:
-                self.GetMapDisplay().AddBarscale(cmd = command, showDialog = False)
+                self.GetMapDisplay().AddBarscale(cmd=command, showDialog=False)
             else:
-                self.GetMapDisplay().AddBarscale(showDialog = True)
+                self.GetMapDisplay().AddBarscale(showDialog=True)
         elif layertype == 'rastleg':
             if len(command) > 1:
-                self.GetMapDisplay().AddLegend(cmd = command, showDialog = False)
+                self.GetMapDisplay().AddLegend(cmd=command, showDialog=False)
             else:
-                self.GetMapDisplay().AddLegend(showDialog = True)
+                self.GetMapDisplay().AddLegend(showDialog=True)
         elif layertype == 'redraw':
             self.GetMapDisplay().OnRender(None)
         elif layertype == 'export':
-            GUI(parent=self, show=False).ParseCommand(command,
-                                                      completed=(self.GetMapDisplay().DOutFileOptData,
-                                                                 '', ''))
+            GUI(parent=self, show=False).ParseCommand(
+                command, completed=(self.GetMapDisplay().DOutFileOptData, '', ''))
         elif layertype == 'torast':
             if len(command) <= 1:
-                task = GUI(parent=self, show=True).ParseCommand(command,
-                                                                completed=(self.GetMapDisplay().DToRastOptData,
-                                                                '', ''))
+                task = GUI(
+                    parent=self, show=True).ParseCommand(
+                    command, completed=(
+                        self.GetMapDisplay().DToRastOptData, '', ''))
             else:
-                task = GUI(parent=self, show=None).ParseCommand(command,
-                                                                completed=(self.GetMapDisplay().DToRastOptData,
-                                                                '', ''))
+                task = GUI(
+                    parent=self, show=None).ParseCommand(
+                    command, completed=(
+                        self.GetMapDisplay().DToRastOptData, '', ''))
                 self.GetMapDisplay().DToRast(command=task.get_cmd())
         else:
             # add layer into layer tree
-            lname, found = GetLayerNameFromCmd(command, fullyQualified = True,
-                                               layerType = layertype)
-            self.GetLayerTree().AddLayer(ltype = layertype, lchecked = True,
-                                         lname = lname,
-                                         lcmd = command)
+            lname, found = GetLayerNameFromCmd(command, fullyQualified=True,
+                                               layerType=layertype)
+            self.GetLayerTree().AddLayer(ltype=layertype, lchecked=True,
+                                         lname=lname,
+                                         lcmd=command)
 
     def GetLayerNotebook(self):
         """Get Layers Notebook"""
         return self.notebookLayers
-    
+
     def GetLayerTree(self):
         """Get current layer tree
 
@@ -709,8 +792,8 @@
         if self.currentPage:
             return self.currentPage.maptree
         return None
-    
-    def GetMapDisplay(self, onlyCurrent = True):
+
+    def GetMapDisplay(self, onlyCurrent=True):
         """Get current map display
 
         :param bool onlyCurrent: True to return only active mapdisplay
@@ -724,24 +807,25 @@
                 return self.GetLayerTree().GetMapDisplay()
             else:
                 return None
-        else: # -> return list of all mapdisplays
+        else:  # -> return list of all mapdisplays
             mlist = list()
             for idx in range(0, self.notebookLayers.GetPageCount()):
-                mlist.append(self.notebookLayers.GetPage(idx).maptree.GetMapDisplay())
-            
+                mlist.append(self.notebookLayers.GetPage(
+                    idx).maptree.GetMapDisplay())
+
             return mlist
 
     def GetLogWindow(self):
         """Gets console for command output and messages"""
         return self._gconsole
-    
+
     def GetToolbar(self, name):
         """Returns toolbar if exists else None"""
         if name in self.toolbars:
             return self.toolbars[name]
-        
+
         return None
-        
+
     def GetMenuCmd(self, event):
         """Get GRASS command from menu item
 
@@ -754,135 +838,141 @@
 
         try:
             cmdlist = cmd.split(' ')
-        except: # already list?
+        except:  # already list?
             cmdlist = cmd
-        
+
         # check list of dummy commands for GUI modules that do not have GRASS
-        # bin modules or scripts. 
+        # bin modules or scripts.
         if cmd in ['vcolors', 'r.mapcalc', 'r3.mapcalc', 'v.krige']:
             return cmdlist
 
         try:
             layer = self.GetLayerTree().layer_selected
-            name = self.GetLayerTree().GetLayerInfo(layer, key = 'maplayer').name
-            type = self.GetLayerTree().GetLayerInfo(layer, key = 'type')
+            name = self.GetLayerTree().GetLayerInfo(layer, key='maplayer').name
+            type = self.GetLayerTree().GetLayerInfo(layer, key='type')
         except:
             layer = None
 
-        if layer and len(cmdlist) == 1: # only if no parameters given
-            if (type == 'raster' and cmdlist[0][0] == 'r' and cmdlist[0][1] != '3') or \
-                    (type == 'vector' and cmdlist[0][0] == 'v'):
+        if layer and len(cmdlist) == 1:  # only if no parameters given
+            if (type == 'raster' and cmdlist[0][0] == 'r' and cmdlist[0][
+                    1] != '3') or (type == 'vector' and cmdlist[0][0] == 'v'):
                 input = GUI().GetCommandInputMapParamKey(cmdlist[0])
                 if input:
                     cmdlist.append("%s=%s" % (input, name))
-        
+
         return cmdlist
 
-    def RunMenuCmd(self, event = None, cmd = []):
+    def RunMenuCmd(self, event=None, cmd=[]):
         """Run command selected from menu"""
-        if event:       
+        if event:
             cmd = self.GetMenuCmd(event)
         self._gconsole.RunCmd(cmd)
 
-    def OnMenuCmd(self, event = None, cmd = []):
+    def OnMenuCmd(self, event=None, cmd=[]):
         """Parse command selected from menu"""
-        if event:       
+        if event:
             cmd = self.GetMenuCmd(event)
         GUI(parent=self, giface=self._giface).ParseCommand(cmd)
-        
+
     def OnVNet(self, event):
         """Vector network analysis tool"""
         if self.GetMapDisplay():
             self.GetMapDisplay().OnVNet(event)
         else:
-            self.NewDisplay(show = True).OnVNet(event)
-        
+            self.NewDisplay(show=True).OnVNet(event)
+
     def OnVDigit(self, event):
         """Start vector digitizer
         """
         if not self.currentPage:
             self.MsgNoLayerSelected()
             return
-        
+
         tree = self.GetLayerTree()
         layer = tree.layer_selected
         # no map layer selected
         if not layer:
             self.MsgNoLayerSelected()
             return
-        
+
         # available only for vector map layers
         try:
-            mapLayer = tree.GetLayerInfo(layer, key = 'maplayer')
+            mapLayer = tree.GetLayerInfo(layer, key='maplayer')
         except:
             mapLayer = None
-        
+
         if not mapLayer or mapLayer.GetType() != 'vector':
-            GMessage(parent = self,
-                     message = _("Selected map layer is not vector."))
+            GMessage(parent=self,
+                     message=_("Selected map layer is not vector."))
             return
-        
+
         if mapLayer.GetMapset() != grass.gisenv()['MAPSET']:
-            GMessage(parent = self,
-                     message = _("Editing is allowed only for vector maps from the "
-                                 "current mapset."))
+            GMessage(
+                parent=self, message=_(
+                    "Editing is allowed only for vector maps from the "
+                    "current mapset."))
             return
-        
+
         if not tree.GetLayerInfo(layer):
             return
-        dcmd = tree.GetLayerInfo(layer, key = 'cmd')
+        dcmd = tree.GetLayerInfo(layer, key='cmd')
         if not dcmd:
             return
-        
+
         digitToolbar = self.GetMapDisplay().GetToolbar('vdigit')
         if digitToolbar:
             stopOnly = False
             if mapLayer is digitToolbar.GetLayer():
                 stopOnly = True
-            tree.OnStopEditing(None) # TODO: change to signal
+            tree.OnStopEditing(None)  # TODO: change to signal
             if stopOnly:
                 return
-        
-        tree.OnStartEditing(None) # TODO: change to signal
-        
+
+        tree.OnStartEditing(None)  # TODO: change to signal
+
     def OnRunScript(self, event):
         """Run user-defined script"""
         # open dialog and choose script file
-        dlg = wx.FileDialog(parent = self, message = _("Choose script file to run"),
-                            defaultDir = os.getcwd(),
-                            wildcard = _("Python script (*.py)|*.py|Bash script (*.sh)|*.sh"))
-        
+        dlg = wx.FileDialog(
+            parent=self,
+            message=_("Choose script file to run"),
+            defaultDir=os.getcwd(),
+            wildcard=_("Python script (*.py)|*.py|Bash script (*.sh)|*.sh"))
+
         filename = None
         if dlg.ShowModal() == wx.ID_OK:
             filename = dlg.GetPath()
-        
+
         if not filename:
             return False
         try:
             filename_encoded = EncodeString(filename)
         except UnicodeEncodeError:
-            GError(parent=self,
-                   message = _("Due to the limitations of your operating system, "
-                               "the script path cannot contain certain non-ascii characters. "
-                               "Please rename the script or move it to a different location."))
+            GError(
+                parent=self, message=_(
+                    "Due to the limitations of your operating system, "
+                    "the script path cannot contain certain non-ascii characters. "
+                    "Please rename the script or move it to a different location."))
             return
-        
+
         if not os.path.exists(filename):
-            GError(parent = self,
-                   message = _("Script file '%s' doesn't exist. "
-                               "Operation canceled.") % filename)
+            GError(parent=self,
+                   message=_("Script file '%s' doesn't exist. "
+                             "Operation canceled.") % filename)
             return
 
         # check permission
         if not os.access(filename, os.X_OK):
-            dlg = wx.MessageDialog(self,
-                                   message = _("Script <%s> is not executable. "
-                                               "Do you want to set the permissions "
-                                               "that allows you to run this script "
-                                               "(note that you must be the owner of the file)?" % \
-                                                   os.path.basename(filename)),
-                                   caption = _("Set permission?"),
-                                   style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+            dlg = wx.MessageDialog(
+                self,
+                message=_(
+                    "Script <%s> is not executable. "
+                    "Do you want to set the permissions "
+                    "that allows you to run this script "
+                    "(note that you must be the owner of the file)?" %
+                    os.path.basename(filename)),
+                caption=_("Set permission?"),
+                style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
             if dlg.ShowModal() != wx.ID_YES:
                 return
             dlg.Destroy()
@@ -890,9 +980,11 @@
                 mode = stat.S_IMODE(os.lstat(filename)[stat.ST_MODE])
                 os.chmod(filename, mode | stat.S_IXUSR)
             except OSError:
-                GError(_("Unable to set permission. Operation canceled."), parent = self)
+                GError(
+                    _("Unable to set permission. Operation canceled."),
+                    parent=self)
                 return
-        
+
         # check GRASS_ADDON_PATH
         addonPath = os.getenv('GRASS_ADDON_PATH', [])
         if addonPath:
@@ -900,89 +992,92 @@
         dirName = os.path.dirname(filename_encoded)
         if dirName not in addonPath:
             addonPath.append(dirName)
-            dlg = wx.MessageDialog(self,
-                                   message = _("Directory '%s' is not defined in GRASS_ADDON_PATH. "
-                                               "Do you want add this directory to GRASS_ADDON_PATH?") % \
-                                       dirName,
-                                   caption = _("Update Addons path?"),
-                                   style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+            dlg = wx.MessageDialog(
+                self,
+                message=_(
+                    "Directory '%s' is not defined in GRASS_ADDON_PATH. "
+                    "Do you want add this directory to GRASS_ADDON_PATH?") %
+                dirName, caption=_("Update Addons path?"),
+                style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
             if dlg.ShowModal() == wx.ID_YES:
-                SetAddOnPath(os.pathsep.join(addonPath), key = 'PATH')
+                SetAddOnPath(os.pathsep.join(addonPath), key='PATH')
             dlg.Destroy()
-        
+
         self._gconsole.WriteCmdLog(_("Launching script '%s'...") % filename)
         self._gconsole.RunCmd([filename])
-        
+
     def OnChangeLocation(self, event):
         """Change current location"""
-        dlg = LocationDialog(parent = self)
+        dlg = LocationDialog(parent=self)
         if dlg.ShowModal() == wx.ID_OK:
             location, mapset = dlg.GetValues()
             dlg.Destroy()
-            
+
             if not location or not mapset:
-                GError(parent = self,
-                       message = _("No location/mapset provided. Operation canceled."))
-                return # this should not happen
-            
-            if RunCommand('g.mapset', parent = self,
-                          location = location,
-                          mapset = mapset) != 0:
-                return # error reported
-            
+                GError(
+                    parent=self,
+                    message=_(
+                        "No location/mapset provided. Operation canceled."))
+                return  # this should not happen
+
+            if RunCommand('g.mapset', parent=self,
+                          location=location,
+                          mapset=mapset) != 0:
+                return  # error reported
+
             # close current workspace and create new one
             self.OnWorkspaceClose()
             self.OnWorkspaceNew()
-            GMessage(parent = self,
-                     message = _("Current location is <%(loc)s>.\n"
-                                 "Current mapset is <%(mapset)s>.") % \
-                         { 'loc' : location, 'mapset' : mapset })
-        
+            GMessage(parent=self,
+                     message=_("Current location is <%(loc)s>.\n"
+                               "Current mapset is <%(mapset)s>.") %
+                     {'loc': location, 'mapset': mapset})
+
     def OnCreateMapset(self, event):
         """Create new mapset"""
-        dlg = wx.TextEntryDialog(parent = self,
-                                 message = _('Enter name for new mapset:'),
-                                 caption = _('Create new mapset'))
-        
-        if dlg.ShowModal() ==  wx.ID_OK:
+        dlg = wx.TextEntryDialog(parent=self,
+                                 message=_('Enter name for new mapset:'),
+                                 caption=_('Create new mapset'))
+
+        if dlg.ShowModal() == wx.ID_OK:
             mapset = dlg.GetValue()
             if not mapset:
-                GError(parent = self,
-                       message = _("No mapset provided. Operation canceled."))
+                GError(parent=self,
+                       message=_("No mapset provided. Operation canceled."))
                 return
-            
+
             ret = RunCommand('g.mapset',
-                             parent = self,
-                             flags = 'c',
-                             mapset = mapset)
+                             parent=self,
+                             flags='c',
+                             mapset=mapset)
             if ret == 0:
-                GMessage(parent = self,
-                         message = _("Current mapset is <%s>.") % mapset)
-                
+                GMessage(parent=self,
+                         message=_("Current mapset is <%s>.") % mapset)
+
     def OnChangeMapset(self, event):
         """Change current mapset"""
-        dlg = MapsetDialog(parent = self)
-        
+        dlg = MapsetDialog(parent=self)
+
         if dlg.ShowModal() == wx.ID_OK:
             mapset = dlg.GetMapset()
             dlg.Destroy()
-            
+
             if not mapset:
-                GError(parent = self,
-                       message = _("No mapset provided. Operation canceled."))
+                GError(parent=self,
+                       message=_("No mapset provided. Operation canceled."))
                 return
-            
+
             if RunCommand('g.mapset',
-                          parent = self,
-                          mapset = mapset) == 0:
-                GMessage(parent = self,
-                         message = _("Current mapset is <%s>.") % mapset)
-        
+                          parent=self,
+                          mapset=mapset) == 0:
+                GMessage(parent=self,
+                         message=_("Current mapset is <%s>.") % mapset)
+
                 dispId = 1
-                for display in self.GetMapDisplay(onlyCurrent = False):
-                    display.SetTitleNumber(dispId) # TODO: signal ?
-                    dispId += 1 
-        
+                for display in self.GetMapDisplay(onlyCurrent=False):
+                    display.SetTitleNumber(dispId)  # TODO: signal ?
+                    dispId += 1
+
     def OnChangeCWD(self, event=None, cmd=None):
         """Change current working directory
 
@@ -1013,8 +1108,8 @@
             # but this should be solved by the function not caller
             # also because of translations
             self._giface.WriteLog(_("If ~ (tilde) is present as the first"
-                " directory on the path, it is replaced"
-                " by user's home directory."))
+                                    " directory on the path, it is replaced"
+                                    " by user's home directory."))
 
         # check correctness of cmd
         if cmd and cmd[0] != 'cd':
@@ -1059,25 +1154,25 @@
     def GetCwdPath(self):
         """Get current working directory or None"""
         return self.cwdPath
-    
+
     def OnNewVector(self, event):
         """Create new vector map layer"""
         dlg = CreateNewVector(self, giface=self._giface,
                               cmd=(('v.edit',
                                     {'tool': 'create'},
                                     'map')))
-        
+
         if not dlg:
             return
-        
-        name = dlg.GetName(full = True)
+
+        name = dlg.GetName(full=True)
         if name and dlg.IsChecked('add'):
             # add layer to map layer tree
-            self.GetLayerTree().AddLayer(ltype = 'vector',
-                                         lname = name, lchecked=True,
-                                         lcmd = ['d.vect', 'map=%s' % name])
+            self.GetLayerTree().AddLayer(ltype='vector',
+                                         lname=name, lchecked=True,
+                                         lcmd=['d.vect', 'map=%s' % name])
         dlg.Destroy()
-        
+
     def OnSystemInfo(self, event):
         """Print system information"""
         vInfo = grass.version()
@@ -1085,12 +1180,12 @@
             sys.stderr.write(_("Unable to get GRASS version\n"))
 
         # check also OSGeo4W on MS Windows
-        if sys.platform == 'win32' and \
-                not os.path.exists(os.path.join(os.getenv("GISBASE"), "WinGRASS-README.url")):
+        if sys.platform == 'win32' and not os.path.exists(
+                os.path.join(os.getenv("GISBASE"), "WinGRASS-README.url")):
             osgeo4w = ' (OSGeo4W)'
         else:
             osgeo4w = ''
-        
+
         self._gconsole.WriteCmdLog(_("System Info"))
         # platform from UTF-8 conversion was added because of the Fedora 19 release
         # which has the name "Schrödinger’s cat" (umlaut and special ' character)
@@ -1106,29 +1201,39 @@
                                 "SQLite: %s\n"
                                 "Python: %s\n"
                                 "wxPython: %s\n"
-                                "%s: %s%s\n"% (_("GRASS version"), vInfo.get('version', _('unknown version')),
-                                               _("GRASS SVN revision"), vInfo.get('revision', '?'),
-                                               _("Build date"), vInfo.get('build_date', '?'),
-                                               _("Build platform"), vInfo.get('build_platform', '?'),
-                                               # _("GIS Library Revision"), vInfo.get('libgis_revision'], vInfo.get('libgis_date'].split(' ', 1)[0],
-                                               vInfo.get('gdal', '?'), vInfo.get('proj4', '?'), vInfo.get('geos', '?'), vInfo.get('sqlite', '?'),
-                                               platform.python_version(),
-                                               wx.__version__,
-                                               _("Platform"), platform.platform().decode('utf8', 'replace'), osgeo4w),
+                                "%s: %s%s\n" % (_("GRASS version"), vInfo.get('version', _('unknown version')),
+                                                _("GRASS SVN revision"), vInfo.get(
+                                                    'revision', '?'),
+                                                _("Build date"), vInfo.get(
+                                                    'build_date', '?'),
+                                                _("Build platform"), vInfo.get(
+                                                    'build_platform', '?'),
+                                                # _("GIS Library Revision"),
+                                                # vInfo.get('libgis_revision'],
+                                                # vInfo.get('libgis_date'].split('
+                                                # ', 1)[0],
+                                                vInfo.get(
+                                                    'gdal', '?'), vInfo.get(
+                                                    'proj4', '?'), vInfo.get(
+                                                    'geos', '?'), vInfo.get(
+                                                    'sqlite', '?'),
+                                                platform.python_version(),
+                                                wx.__version__,
+                                                _("Platform"), platform.platform().decode('utf8', 'replace'), osgeo4w),
                                 notification=Notification.MAKE_VISIBLE)
         self._gconsole.WriteCmdLog(' ')
-    
+
     def OnAboutGRASS(self, event):
         """Display 'About GRASS' dialog"""
         win = AboutWindow(self)
         win.CentreOnScreen()
-        win.Show(True)  
+        win.Show(True)
 
     def _popupMenu(self, data):
         """Create popup menu
         """
         menu = wx.Menu()
-        
+
         for key, handler in data:
             if key is None:
                 menu.AppendSeparator()
@@ -1137,7 +1242,7 @@
             item.SetBitmap(LMIcons[key].GetBitmap(self.iconsize))
             menu.AppendItem(item)
             self.Bind(wx.EVT_MENU, handler, item)
-        
+
         # create menu
         self.PopupMenu(menu)
         menu.Destroy()
@@ -1145,64 +1250,69 @@
     def OnImportMenu(self, event):
         """Import maps menu (import, link)
         """
-        self._popupMenu((('rastImport',    self.OnImportGdalLayers),
-                         ('rastLink',      self.OnLinkGdalLayers),
-                         ('rastUnpack',    self.OnUnpackRaster),
-                         ('rastOut',       self.OnRasterOutputFormat),
+        self._popupMenu((('rastImport', self.OnImportGdalLayers),
+                         ('rastLink', self.OnLinkGdalLayers),
+                         ('rastUnpack', self.OnUnpackRaster),
+                         ('rastOut', self.OnRasterOutputFormat),
                          (None, None),
-                         ('vectImport',    self.OnImportOgrLayers),
-                         ('vectLink',      self.OnLinkOgrLayers),
-                         ('vectUnpack',    self.OnUnpackVector),
-                         ('vectOut',       self.OnVectorOutputFormat)))
-        
-    def OnWorkspaceNew(self, event = None):
+                         ('vectImport', self.OnImportOgrLayers),
+                         ('vectLink', self.OnLinkOgrLayers),
+                         ('vectUnpack', self.OnUnpackVector),
+                         ('vectOut', self.OnVectorOutputFormat)))
+
+    def OnWorkspaceNew(self, event=None):
         """Create new workspace file
 
         Erase current workspace settings first
         """
         Debug.msg(4, "GMFrame.OnWorkspaceNew():")
-        
+
         # start new map display if no display is available
         if not self.currentPage:
             self.NewDisplay()
-        
+
         maptree = self.GetLayerTree()
-        
+
         # ask user to save current settings
         if self.workspaceFile and self.workspaceChanged:
             self.OnWorkspaceSave()
         elif self.workspaceFile is None and maptree.GetCount() > 0:
-             dlg = wx.MessageDialog(self, message = _("Current workspace is not empty. "
-                                                    "Do you want to store current settings "
-                                                    "to workspace file?"),
-                                    caption = _("Create new workspace?"),
-                                    style = wx.YES_NO | wx.YES_DEFAULT | \
-                                        wx.CANCEL | wx.ICON_QUESTION)
-             ret = dlg.ShowModal()
-             if ret == wx.ID_YES:
-                 self.OnWorkspaceSaveAs()
-             elif ret == wx.ID_CANCEL:
-                 dlg.Destroy()
-                 return
-             
-             dlg.Destroy()
-        
+            dlg = wx.MessageDialog(
+                self,
+                message=_(
+                    "Current workspace is not empty. "
+                    "Do you want to store current settings "
+                    "to workspace file?"),
+                caption=_("Create new workspace?"),
+                style=wx.YES_NO | wx.YES_DEFAULT | wx.CANCEL | wx.ICON_QUESTION)
+            ret = dlg.ShowModal()
+            if ret == wx.ID_YES:
+                self.OnWorkspaceSaveAs()
+            elif ret == wx.ID_CANCEL:
+                dlg.Destroy()
+                return
+
+            dlg.Destroy()
+
         # delete all items
         maptree.DeleteAllItems()
-        
+
         # add new root element
         maptree.root = maptree.AddRoot("Map Layers")
-        self.GetLayerTree().SetPyData(maptree.root, (None,None))
-        
+        self.GetLayerTree().SetPyData(maptree.root, (None, None))
+
         # no workspace file loaded
         self.workspaceFile = None
         self.workspaceChanged = False
         self._setTitle()
-        
-    def OnWorkspaceOpen(self, event = None):
+
+    def OnWorkspaceOpen(self, event=None):
         """Open file with workspace definition"""
-        dlg = wx.FileDialog(parent = self, message = _("Choose workspace file"),
-                            defaultDir = os.getcwd(), wildcard = _("GRASS Workspace File (*.gxw)|*.gxw"))
+        dlg = wx.FileDialog(
+            parent=self,
+            message=_("Choose workspace file"),
+            defaultDir=os.getcwd(),
+            wildcard=_("GRASS Workspace File (*.gxw)|*.gxw"))
 
         filename = ''
         if dlg.ShowModal() == wx.ID_OK:
@@ -1212,7 +1322,7 @@
             return
 
         Debug.msg(4, "GMFrame.OnWorkspaceOpen(): filename=%s" % filename)
-        
+
         # delete current layer tree content
         self.OnWorkspaceClose()
         self.loadingWorkspace = True
@@ -1227,7 +1337,7 @@
 
         .. todo::
             Validate against DTD
-        
+
         :return: True on success
         :return: False on error
         """
@@ -1235,19 +1345,22 @@
         try:
             gxwXml = ProcessWorkspaceFile(etree.parse(filename))
         except Exception as e:
-            GError(parent = self,
-                   message = _("Reading workspace file <%s> failed.\n"
-                               "Invalid file, unable to parse XML document.") % filename)
+            GError(
+                parent=self, message=_(
+                    "Reading workspace file <%s> failed.\n"
+                    "Invalid file, unable to parse XML document.") %
+                filename)
             return
-        
-        busy = wx.BusyInfo(message = _("Please wait, loading workspace..."),
-                           parent = self)
+
+        busy = wx.BusyInfo(message=_("Please wait, loading workspace..."),
+                           parent=self)
         wx.Yield()
 
         #
         # load layer manager window properties
         #
-        if UserSettings.Get(group = 'general', key = 'workspace', subkey = ['posManager', 'enabled']) is False:
+        if UserSettings.Get(group='general', key='workspace', subkey=[
+                            'posManager', 'enabled']) is False:
             if gxwXml.layerManager['pos']:
                 self.SetPosition(gxwXml.layerManager['pos'])
             if gxwXml.layerManager['size']:
@@ -1256,72 +1369,81 @@
                 self.cwdPath = gxwXml.layerManager['cwd']
                 if os.path.isdir(self.cwdPath):
                     os.chdir(self.cwdPath)
-        
+
         #
         # start map displays first (list of layers can be empty)
         #
         displayId = 0
         mapdisplay = list()
         for display in gxwXml.displays:
-            mapdisp = self.NewDisplay(name = display['name'], show = False)
+            mapdisp = self.NewDisplay(name=display['name'], show=False)
             mapdisplay.append(mapdisp)
             maptree = self.notebookLayers.GetPage(displayId).maptree
-            
+
             # set windows properties
-            mapdisp.SetProperties(render = display['render'],
-                                  mode = display['mode'],
-                                  showCompExtent = display['showCompExtent'],
-                                  alignExtent = display['alignExtent'],
-                                  constrainRes = display['constrainRes'],
-                                  projection = display['projection']['enabled'])
+            mapdisp.SetProperties(render=display['render'],
+                                  mode=display['mode'],
+                                  showCompExtent=display['showCompExtent'],
+                                  alignExtent=display['alignExtent'],
+                                  constrainRes=display['constrainRes'],
+                                  projection=display['projection']['enabled'])
 
             if display['projection']['enabled']:
                 if display['projection']['epsg']:
-                    UserSettings.Set(group = 'display', key = 'projection', subkey = 'epsg',
-                                     value = display['projection']['epsg'])
+                    UserSettings.Set(
+                        group='display',
+                        key='projection',
+                        subkey='epsg',
+                        value=display['projection']['epsg'])
                     if display['projection']['proj']:
-                        UserSettings.Set(group = 'display', key = 'projection', subkey = 'proj4',
-                                         value = display['projection']['proj'])
-            
+                        UserSettings.Set(
+                            group='display',
+                            key='projection',
+                            subkey='proj4',
+                            value=display['projection']['proj'])
+
             # set position and size of map display
-            if not UserSettings.Get(group = 'general', key = 'workspace', subkey = ['posDisplay', 'enabled']):
+            if not UserSettings.Get(
+                    group='general', key='workspace',
+                    subkey=['posDisplay', 'enabled']):
                 if display['pos']:
                     mapdisp.SetPosition(display['pos'])
                 if display['size']:
                     mapdisp.SetSize(display['size'])
-            
+
             # set extent if defined
             if display['extent']:
                 w, s, e, n, b, t = display['extent']
-                region = maptree.Map.region = maptree.Map.GetRegion(w = w, s = s, e = e, n = n)
+                region = maptree.Map.region = maptree.Map.GetRegion(
+                    w=w, s=s, e=e, n=n)
                 mapdisp.GetWindow().ResetZoomHistory()
                 mapdisp.GetWindow().ZoomHistory(region['n'],
                                                 region['s'],
                                                 region['e'],
                                                 region['w'])
-            
+
             displayId += 1
-            mapdisp.Show() # show mapdisplay
+            mapdisp.Show()  # show mapdisplay
             # set render property to False to speed up loading layers
             mapdisp.mapWindowProperties.autoRender = False
 
         maptree = None
         selectList = []  # list of selected layers
-        # 
+        #
         # load list of map layers
         #
         for layer in gxwXml.layers:
             display = layer['display']
             maptree = self.notebookLayers.GetPage(display).maptree
 
-            newItem = maptree.AddLayer(ltype = layer['type'],
-                                       lname = layer['name'],
-                                       lchecked = layer['checked'],
-                                       lopacity = layer['opacity'],
-                                       lcmd = layer['cmd'],
-                                       lgroup = layer['group'],
-                                       lnviz = layer['nviz'],
-                                       lvdigit = layer['vdigit'])
+            newItem = maptree.AddLayer(ltype=layer['type'],
+                                       lname=layer['name'],
+                                       lchecked=layer['checked'],
+                                       lopacity=layer['opacity'],
+                                       lcmd=layer['cmd'],
+                                       lgroup=layer['group'],
+                                       lnviz=layer['nviz'],
+                                       lvdigit=layer['vdigit'])
 
             if 'selected' in layer:
                 selectList.append((maptree, newItem, layer['selected']))
@@ -1338,16 +1460,16 @@
         # set render property again when all layers are loaded
         for i, display in enumerate(gxwXml.displays):
             mapdisplay[i].mapWindowProperties.autoRender = display['render']
-            
+
         for idx, mdisp in enumerate(mapdisplay):
-            ### avoid double-rendering when loading workspace
-            ### mdisp.MapWindow2D.UpdateMap()
+            # avoid double-rendering when loading workspace
+            # mdisp.MapWindow2D.UpdateMap()
             # nviz
             if gxwXml.displays[idx]['viewMode'] == '3d':
                 mdisp.AddNviz()
-                self.nviz.UpdateState(view = gxwXml.nviz_state['view'],
-                                              iview = gxwXml.nviz_state['iview'],
-                                              light = gxwXml.nviz_state['light'])
+                self.nviz.UpdateState(view=gxwXml.nviz_state['view'],
+                                      iview=gxwXml.nviz_state['iview'],
+                                      light=gxwXml.nviz_state['light'])
                 mdisp.MapWindow3D.constants = gxwXml.nviz_state['constants']
                 for idx, constant in enumerate(mdisp.MapWindow3D.constants):
                     mdisp.MapWindow3D.AddConstant(constant, idx + 1)
@@ -1355,13 +1477,16 @@
                     self.nviz.UpdatePage(page)
                 self.nviz.UpdateSettings()
                 mdisp.toolbars['map'].combo.SetSelection(1)
-            
+
         return True
-    
+
     def OnWorkspaceLoadGrcFile(self, event):
         """Load map layers from GRC file (Tcl/Tk GUI) into map layer tree"""
-        dlg = wx.FileDialog(parent = self, message = _("Choose GRC file to load"),
-                            defaultDir = os.getcwd(), wildcard = _("Old GRASS Workspace File (*.grc)|*.grc"))
+        dlg = wx.FileDialog(
+            parent=self,
+            message=_("Choose GRC file to load"),
+            defaultDir=os.getcwd(),
+            wildcard=_("Old GRASS Workspace File (*.grc)|*.grc"))
 
         filename = ''
         if dlg.ShowModal() == wx.ID_OK:
@@ -1370,36 +1495,43 @@
         if filename == '':
             return
 
-        Debug.msg(4, "GMFrame.OnWorkspaceLoadGrcFile(): filename=%s" % filename)
+        Debug.msg(
+            4,
+            "GMFrame.OnWorkspaceLoadGrcFile(): filename=%s" %
+            filename)
 
         # start new map display if no display is available
         if not self.currentPage:
             self.NewDisplay()
 
-        busy = wx.BusyInfo(message = _("Please wait, loading workspace..."),
-                           parent = self)
+        busy = wx.BusyInfo(message=_("Please wait, loading workspace..."),
+                           parent=self)
         wx.Yield()
 
         maptree = None
         for layer in ProcessGrcFile(filename).read(self):
             maptree = self.notebookLayers.GetPage(layer['display']).maptree
-            newItem = maptree.AddLayer(ltype = layer['type'],
-                                       lname = layer['name'],
-                                       lchecked = layer['checked'],
-                                       lopacity = layer['opacity'],
-                                       lcmd = layer['cmd'],
-                                       lgroup = layer['group'])
+            newItem = maptree.AddLayer(ltype=layer['type'],
+                                       lname=layer['name'],
+                                       lchecked=layer['checked'],
+                                       lopacity=layer['opacity'],
+                                       lcmd=layer['cmd'],
+                                       lgroup=layer['group'])
 
             busy.Destroy()
-            
+
         if maptree:
             # reverse list of map layers
             maptree.Map.ReverseListOfLayers()
 
-    def OnWorkspaceSaveAs(self, event = None):
+    def OnWorkspaceSaveAs(self, event=None):
         """Save workspace definition to selected file"""
-        dlg = wx.FileDialog(parent = self, message = _("Choose file to save current workspace"),
-                            defaultDir = os.getcwd(), wildcard = _("GRASS Workspace File (*.gxw)|*.gxw"), style = wx.FD_SAVE)
+        dlg = wx.FileDialog(
+            parent=self,
+            message=_("Choose file to save current workspace"),
+            defaultDir=os.getcwd(),
+            wildcard=_("GRASS Workspace File (*.gxw)|*.gxw"),
+            style=wx.FD_SAVE)
 
         filename = ''
         if dlg.ShowModal() == wx.ID_OK:
@@ -1413,9 +1545,14 @@
             filename += ".gxw"
 
         if os.path.exists(filename):
-            dlg = wx.MessageDialog(self, message = _("Workspace file <%s> already exists. "
-                                                     "Do you want to overwrite this file?") % filename,
-                                   caption = _("Save workspace"), style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+            dlg = wx.MessageDialog(
+                self,
+                message=_(
+                    "Workspace file <%s> already exists. "
+                    "Do you want to overwrite this file?") %
+                filename,
+                caption=_("Save workspace"),
+                style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
             if dlg.ShowModal() != wx.ID_YES:
                 dlg.Destroy()
                 return False
@@ -1426,17 +1563,23 @@
         self.workspaceFile = filename
         self._setTitle()
 
-    def OnWorkspaceSave(self, event = None):
+    def OnWorkspaceSave(self, event=None):
         """Save file with workspace definition"""
         if self.workspaceFile:
-            dlg = wx.MessageDialog(self, message = _("Workspace file <%s> already exists. "
-                                                   "Do you want to overwrite this file?") % \
-                                       self.workspaceFile,
-                                   caption = _("Save workspace"), style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+            dlg = wx.MessageDialog(
+                self,
+                message=_(
+                    "Workspace file <%s> already exists. "
+                    "Do you want to overwrite this file?") %
+                self.workspaceFile,
+                caption=_("Save workspace"),
+                style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
             if dlg.ShowModal() == wx.ID_NO:
                 dlg.Destroy()
             else:
-                Debug.msg(4, "GMFrame.OnWorkspaceSave(): filename=%s" % self.workspaceFile)
+                Debug.msg(
+                    4, "GMFrame.OnWorkspaceSave(): filename=%s" %
+                    self.workspaceFile)
                 self.SaveToWorkspaceFile(self.workspaceFile)
                 self._setTitle()
                 self.workspaceChanged = False
@@ -1445,103 +1588,113 @@
 
     def SaveToWorkspaceFile(self, filename):
         """Save layer tree layout to workspace file
-        
+
         :return: True on success, False on error
         """
-        tmpfile = tempfile.TemporaryFile(mode = 'w+b')
+        tmpfile = tempfile.TemporaryFile(mode='w+b')
         try:
-            WriteWorkspaceFile(lmgr = self, file = tmpfile)
-        except StandardError as e:
-            GError(parent = self,
-                   message = _("Writing current settings to workspace file "
-                               "failed."))
+            WriteWorkspaceFile(lmgr=self, file=tmpfile)
+        except Exception as e:
+            GError(parent=self,
+                   message=_("Writing current settings to workspace file "
+                             "failed."))
             return False
-        
+
         try:
             mfile = open(filename, "w")
             tmpfile.seek(0)
             for line in tmpfile.readlines():
                 mfile.write(line)
         except IOError:
-            GError(parent = self,
-                   message = _("Unable to open file <%s> for writing.") % filename)
+            GError(
+                parent=self,
+                message=_("Unable to open file <%s> for writing.") %
+                filename)
             return False
-        
+
         mfile.close()
-        
+
         return True
-    
-    def OnWorkspaceClose(self, event = None):
+
+    def OnWorkspaceClose(self, event=None):
         """Close file with workspace definition
-        
+
         If workspace has been modified ask user to save the changes.
         """
-        Debug.msg(4, "GMFrame.OnWorkspaceClose(): file=%s" % self.workspaceFile)
-        
+        Debug.msg(
+            4, "GMFrame.OnWorkspaceClose(): file=%s" %
+            self.workspaceFile)
+
         self.OnDisplayCloseAll()
         self.workspaceFile = None
         self.workspaceChanged = False
         self._setTitle()
         self.displayIndex = 0
         self.currentPage = None
-        
-    def OnDisplayClose(self, event = None):
+
+    def OnDisplayClose(self, event=None):
         """Close current map display window
         """
         if self.currentPage and self.GetMapDisplay():
             self.GetMapDisplay().OnCloseWindow(event)
-        
-    def OnDisplayCloseAll(self, event = None):
+
+    def OnDisplayCloseAll(self, event=None):
         """Close all open map display windows
         """
-        for display in self.GetMapDisplay(onlyCurrent = False):
+        for display in self.GetMapDisplay(onlyCurrent=False):
             display.OnCloseWindow(event)
-        
+
     def OnRenameDisplay(self, event):
         """Change Map Display name"""
         name = self.notebookLayers.GetPageText(self.currentPageNum)
-        dlg = wx.TextEntryDialog(self, message = _("Enter new name:"),
-                                 caption = _("Rename Map Display"), defaultValue = name)
+        dlg = wx.TextEntryDialog(
+            self, message=_("Enter new name:"),
+            caption=_("Rename Map Display"),
+            defaultValue=name)
         if dlg.ShowModal() == wx.ID_OK:
             name = dlg.GetValue()
-            self.notebookLayers.SetPageText(page = self.currentPageNum, text = name)
+            self.notebookLayers.SetPageText(
+                page=self.currentPageNum, text=name)
             mapdisplay = self.GetMapDisplay()
-            mapdisplay.SetTitle(_("GRASS GIS {version} Map Display: {name} - Location: {loc}").format(
-                                 version=grass.version()['version'], name=name,
-                                 loc=grass.gisenv()["LOCATION_NAME"]))
+            mapdisplay.SetTitle(
+                _("GRASS GIS {version} Map Display: {name} - Location: {loc}").format(
+                    version=grass.version()['version'],
+                    name=name,
+                    loc=grass.gisenv()["LOCATION_NAME"]))
         dlg.Destroy()
-        
+
     def OnRasterRules(self, event):
         """Launches dialog for raster color rules
         """
-        ctable = RasterColorTable(self, layerTree = self.GetLayerTree())
+        ctable = RasterColorTable(self, layerTree=self.GetLayerTree())
         ctable.Show()
         ctable.CentreOnScreen()
 
     def OnVectorRules(self, event):
         """Launches dialog for vector color rules
         """
-        ctable = VectorColorTable(self, layerTree = self.GetLayerTree(),
-                                  attributeType = 'color')
+        ctable = VectorColorTable(self, layerTree=self.GetLayerTree(),
+                                  attributeType='color')
         ctable.Show()
         ctable.CentreOnScreen()
-        
-    def OnEditImageryGroups(self, event, cmd = None):
+
+    def OnEditImageryGroups(self, event, cmd=None):
         """Show dialog for creating and editing groups.
         """
         dlg = GroupDialog(self)
         dlg.CentreOnScreen()
         dlg.Show()
-        
+
     def OnInstallExtension(self, event):
         """Install extension from GRASS Addons SVN repository"""
-        win = InstallExtensionWindow(self, giface=self._giface, size = (650, 550))
+        win = InstallExtensionWindow(
+            self, giface=self._giface, size=(650, 550))
         win.CentreOnScreen()
         win.Show()
-        
+
     def OnManageExtension(self, event):
         """Uninstall extension"""
-        win = ManageExtensionWindow(self, size = (650, 300))
+        win = ManageExtensionWindow(self, size=(650, 300))
         win.CentreOnScreen()
         win.Show()
 
@@ -1554,14 +1707,18 @@
             self.dialogs['preferences'].CenterOnParent()
 
             dlg.settingsChanged.connect(self.OnSettingsChanged)
-            self.Bind(wx.EVT_CLOSE, lambda evt: self.dialogs.update(preferences=None), dlg)
+            self.Bind(
+                wx.EVT_CLOSE,
+                lambda evt: self.dialogs.update(
+                    preferences=None),
+                dlg)
 
         self.dialogs['preferences'].Show()
-        
+
     def OnNvizPreferences(self, event):
         """Show nviz preferences"""
         if not self.dialogs['nvizPreferences']:
-            dlg = NvizPreferencesDialog(parent = self, giface = self._giface)
+            dlg = NvizPreferencesDialog(parent=self, giface=self._giface)
             self.dialogs['nvizPreferences'] = dlg
             self.dialogs['nvizPreferences'].CenterOnScreen()
 
@@ -1570,8 +1727,8 @@
     def OnHelp(self, event):
         """Show help
         """
-        self._gconsole.RunCmd(['g.manual','-i'])
-        
+        self._gconsole.RunCmd(['g.manual', '-i'])
+
     def OnIClass(self, event=None, cmd=None):
         """Start wxIClass tool
 
@@ -1579,7 +1736,7 @@
         and contained in menu/toolboxes must be event and cmd.
         When called from menu event is always None and cmd is the
         associated command (list containing a module name and parameters).
-        
+
         .. todo::
             This documentation is actually documentation of some
             component related to gui_core/menu.py file.
@@ -1589,10 +1746,10 @@
             GError(_('Unable to launch "Supervised Classification Tool".\n\n'
                      'Reason: %s') % errMsg)
             return
-        
-        win = IClassMapFrame(parent = self, giface = self._giface)
+
+        win = IClassMapFrame(parent=self, giface=self._giface)
         win.CentreOnScreen()
-        
+
         win.Show()
 
     def OnAnimationTool(self, event=None, cmd=None):
@@ -1607,9 +1764,11 @@
         tree = self.GetLayerTree()
         if tree:
             rasters = []
-            for layer in tree.GetSelectedLayers(checkedOnly = False):
-                if tree.GetLayerInfo(layer, key = 'type') == 'raster':
-                    rasters.append(tree.GetLayerInfo(layer, key = 'maplayer').GetName())
+            for layer in tree.GetSelectedLayers(checkedOnly=False):
+                if tree.GetLayerInfo(layer, key='type') == 'raster':
+                    rasters.append(
+                        tree.GetLayerInfo(
+                            layer, key='maplayer').GetName())
             if len(rasters) >= 2:
                 from core.layerlist import LayerList
                 from animation.data import AnimLayer
@@ -1636,23 +1795,24 @@
         try:
             from tplot.frame import TplotFrame
         except ImportError:
-            GError(parent=self, message=_("Unable to start Temporal Plot Tool."))
+            GError(parent=self, message=_(
+                "Unable to start Temporal Plot Tool."))
             return
         frame = TplotFrame(parent=self, giface=self._giface)
         frame.Show()
-          
+
     def OnHistogram(self, event):
         """Init histogram display canvas and tools
         """
         from modules.histogram import HistogramFrame
         win = HistogramFrame(self, giface=self._giface)
-        
+
         win.CentreOnScreen()
         win.Show()
         win.Refresh()
         win.Update()
 
-    def OnMapCalculator(self, event, cmd = ''):
+    def OnMapCalculator(self, event, cmd=''):
         """Init map calculator for interactive creation of mapcalc statements
         """
         if event:
@@ -1660,125 +1820,125 @@
                 cmd = self.GetMenuCmd(event)
             except KeyError:
                 cmd = ['r.mapcalc']
-        
-        win = MapCalcFrame(parent = self,
-                           giface = self._giface,
-                           cmd = cmd[0])
+
+        win = MapCalcFrame(parent=self,
+                           giface=self._giface,
+                           cmd=cmd[0])
         win.CentreOnScreen()
         win.Show()
-    
-    def OnVectorCleaning(self, event, cmd = ''):
+
+    def OnVectorCleaning(self, event, cmd=''):
         """Init interactive vector cleaning
         """
         from modules.vclean import VectorCleaningFrame
-        win = VectorCleaningFrame(parent = self)
+        win = VectorCleaningFrame(parent=self)
         win.CentreOnScreen()
         win.Show()
 
     def OnRasterOutputFormat(self, event):
         """Set raster output format handler"""
-        self.OnMenuCmd(cmd = ['r.external.out'])
+        self.OnMenuCmd(cmd=['r.external.out'])
 
     def OnVectorOutputFormat(self, event):
         """Set vector output format handler"""
-        dlg = GdalOutputDialog(parent = self, ogr = True)
+        dlg = GdalOutputDialog(parent=self, ogr=True)
         dlg.CentreOnScreen()
         dlg.Show()
 
     def OnUnpackRaster(self, event):
         """Unpack raster map handler"""
-        self.OnMenuCmd(cmd = ['r.unpack'])
+        self.OnMenuCmd(cmd=['r.unpack'])
 
     def OnUnpackVector(self, event):
         """Unpack vector map handler"""
-        self.OnMenuCmd(cmd = ['v.unpack'])
+        self.OnMenuCmd(cmd=['v.unpack'])
 
-    def OnImportDxfFile(self, event, cmd = None):
+    def OnImportDxfFile(self, event, cmd=None):
         """Convert multiple DXF layers to GRASS vector map layers"""
-        dlg = DxfImportDialog(parent = self, giface = self._giface)
+        dlg = DxfImportDialog(parent=self, giface=self._giface)
         dlg.CentreOnScreen()
         dlg.Show()
 
-    def OnImportGdalLayers(self, event, cmd = None):
+    def OnImportGdalLayers(self, event, cmd=None):
         """Convert multiple GDAL layers to GRASS raster map layers"""
-        dlg = GdalImportDialog(parent = self, giface = self._giface)
+        dlg = GdalImportDialog(parent=self, giface=self._giface)
         dlg.CentreOnScreen()
         dlg.Show()
 
-    def OnLinkGdalLayers(self, event, cmd = None):
+    def OnLinkGdalLayers(self, event, cmd=None):
         """Link multiple GDAL layers to GRASS raster map layers"""
-        dlg = GdalImportDialog(parent = self, giface = self._giface, link = True)
+        dlg = GdalImportDialog(parent=self, giface=self._giface, link=True)
         dlg.CentreOnScreen()
         dlg.Show()
-        
-    def OnImportOgrLayers(self, event, cmd = None):
+
+    def OnImportOgrLayers(self, event, cmd=None):
         """Convert multiple OGR layers to GRASS vector map layers"""
-        dlg = OgrImportDialog(parent = self, giface = self._giface)
+        dlg = OgrImportDialog(parent=self, giface=self._giface)
         dlg.CentreOnScreen()
         dlg.Show()
-        
-    def OnLinkOgrLayers(self, event, cmd = None):
+
+    def OnLinkOgrLayers(self, event, cmd=None):
         """Links multiple OGR layers to GRASS vector map layers"""
-        dlg = OgrImportDialog(parent = self, giface = self._giface, link = True)
+        dlg = OgrImportDialog(parent=self, giface=self._giface, link=True)
         dlg.CentreOnScreen()
         dlg.Show()
-        
-    def OnAddWS(self, event, cmd = None):
+
+    def OnAddWS(self, event, cmd=None):
         """Add web services layer"""
         from web_services.dialogs import AddWSDialog
-        dlg = AddWSDialog(parent = self, giface = self._giface)
+        dlg = AddWSDialog(parent=self, giface=self._giface)
         dlg.CentreOnScreen()
         x, y = dlg.GetPosition()
         dlg.SetPosition((x, y - 200))
         dlg.Show()
 
-    def OnShowAttributeTable(self, event, selection = None):
+    def OnShowAttributeTable(self, event, selection=None):
         """Show attribute table of the given vector map layer
         """
         if not self.currentPage:
             self.MsgNoLayerSelected()
             return
-        
+
         tree = self.GetLayerTree()
         layer = tree.layer_selected
         # no map layer selected
         if not layer:
             self.MsgNoLayerSelected()
             return
-        
+
         # available only for vector map layers
         try:
-            maptype = tree.GetLayerInfo(layer, key = 'maplayer').type
+            maptype = tree.GetLayerInfo(layer, key='maplayer').type
         except:
             maptype = None
-        
+
         if not maptype or maptype != 'vector':
-            GMessage(parent = self,
-                     message = _("Selected map layer is not vector."))
+            GMessage(parent=self,
+                     message=_("Selected map layer is not vector."))
             return
-        
+
         if not tree.GetLayerInfo(layer):
             return
-        dcmd = tree.GetLayerInfo(layer, key = 'cmd')
+        dcmd = tree.GetLayerInfo(layer, key='cmd')
         if not dcmd:
             return
 
-        dbmanager = AttributeManager(parent = self, id = wx.ID_ANY,
-                                     size = wx.Size(500, 300),
-                                     item = layer, log = self._gconsole,
-                                     selection = selection)
+        dbmanager = AttributeManager(parent=self, id=wx.ID_ANY,
+                                     size=wx.Size(500, 300),
+                                     item=layer, log=self._gconsole,
+                                     selection=selection)
 
         # register ATM dialog
         self.dialogs['atm'].append(dbmanager)
-        
+
         # show ATM window
         dbmanager.Show()
-        
-    def OnNewDisplay(self, event = None):
+
+    def OnNewDisplay(self, event=None):
         """Create new layer tree and map display instance"""
         self.NewDisplay()
 
-    def NewDisplay(self, name = None, show = True):
+    def NewDisplay(self, name=None, show=True):
         """Create new layer tree, which will
         create an associated map display frame
 
@@ -1788,28 +1948,37 @@
         :return: reference to mapdisplay intance
         """
         Debug.msg(1, "GMFrame.NewDisplay(): idx=%d" % self.displayIndex)
-        
-        # make a new page in the bookcontrol for the layer tree (on page 0 of the notebook)
-        self.pg_panel = wx.Panel(self.notebookLayers, id = wx.ID_ANY, style = wx.EXPAND)
+
+        # make a new page in the bookcontrol for the layer tree (on page 0 of
+        # the notebook)
+        self.pg_panel = wx.Panel(
+            self.notebookLayers,
+            id=wx.ID_ANY,
+            style=wx.EXPAND)
         if name:
             dispName = name
         else:
             dispName = "Display " + str(self.displayIndex + 1)
-        self.notebookLayers.AddPage(self.pg_panel, text = dispName, select = True)
+        self.notebookLayers.AddPage(self.pg_panel, text=dispName, select=True)
         self.currentPage = self.notebookLayers.GetCurrentPage()
-        
-        # create layer tree (tree control for managing GIS layers)  and put on new notebook page
-        self.currentPage.maptree = LayerTree(self.currentPage, giface = self._giface,
-                                             id = wx.ID_ANY, pos = wx.DefaultPosition,
-                                             size = wx.DefaultSize, style = wx.TR_HAS_BUTTONS |
-                                             wx.TR_LINES_AT_ROOT| wx.TR_HIDE_ROOT |
-                                             wx.TR_DEFAULT_STYLE| wx.NO_BORDER | wx.FULL_REPAINT_ON_RESIZE,
-                                             idx = self.displayIndex, lmgr = self, notebook = self.notebookLayers,
-                                             showMapDisplay = show)
-        
+
+        # create layer tree (tree control for managing GIS layers)  and put on
+        # new notebook page
+        self.currentPage.maptree = LayerTree(
+            self.currentPage, giface=self._giface, id=wx.ID_ANY,
+            pos=wx.DefaultPosition, size=wx.DefaultSize,
+            style=wx.TR_HAS_BUTTONS | wx.TR_LINES_AT_ROOT | wx.TR_HIDE_ROOT | wx.
+            TR_DEFAULT_STYLE | wx.NO_BORDER | wx.FULL_REPAINT_ON_RESIZE,
+            idx=self.displayIndex, lmgr=self, notebook=self.notebookLayers,
+            showMapDisplay=show)
+
         # layout for controls
         cb_boxsizer = wx.BoxSizer(wx.VERTICAL)
-        cb_boxsizer.Add(self.GetLayerTree(), proportion = 1, flag = wx.EXPAND, border = 1)
+        cb_boxsizer.Add(
+            self.GetLayerTree(),
+            proportion=1,
+            flag=wx.EXPAND,
+            border=1)
         self.currentPage.SetSizer(cb_boxsizer)
         cb_boxsizer.Fit(self.GetLayerTree())
         self.currentPage.Layout()
@@ -1826,8 +1995,12 @@
         mapdisplay.ending3dMode.connect(self.RemoveNvizTools)
 
         # use default window layout
-        if UserSettings.Get(group = 'general', key = 'defWindowPos', subkey = 'enabled'):
-            dim = UserSettings.Get(group = 'general', key = 'defWindowPos', subkey = 'dim')
+        if UserSettings.Get(
+                group='general', key='defWindowPos', subkey='enabled'):
+            dim = UserSettings.Get(
+                group='general',
+                key='defWindowPos',
+                subkey='dim')
             idx = 4 + self.displayIndex * 4
             try:
                 x, y = map(int, dim.split(',')[idx:idx + 2])
@@ -1836,9 +2009,9 @@
                 self.GetMapDisplay().SetSize((w, h))
             except:
                 pass
-        
+
         self.displayIndex += 1
-        
+
         return self.GetMapDisplay()
 
     def _onMapDisplayFocus(self, notebookLayerPage):
@@ -1862,17 +2035,18 @@
             if self.GetLayerNotebook().GetPage(page) != mapDisplayPage:
                 mapdisp.Disable3dMode()
 
-    def OnAddMaps(self, event = None):
+    def OnAddMaps(self, event=None):
         """Add selected map layers into layer tree"""
-        dialog = MapLayersDialog(parent = self, title = _("Add selected map layers into layer tree"))
+        dialog = MapLayersDialog(parent=self, title=_(
+            "Add selected map layers into layer tree"))
         dialog.applyAddingMapLayers.connect(self.AddMaps)
         val = dialog.ShowModal()
-        
+
         if val == wx.ID_OK:
-            self.AddMaps(dialog.GetMapLayers(), dialog.GetLayerType(cmd = True))
+            self.AddMaps(dialog.GetMapLayers(), dialog.GetLayerType(cmd=True))
         dialog.Destroy()
 
-    def AddMaps(self, mapLayers, ltype, check = False):
+    def AddMaps(self, mapLayers, ltype, check=False):
         """Add map layers to layer tree.
 
         :param list mapLayers: list of map names
@@ -1883,31 +2057,33 @@
         # start new map display if no display is available
         if not self.currentPage:
             self.NewDisplay()
-            
+
         maptree = self.GetLayerTree()
-        
+
         for layerName in mapLayers:
             if ltype == 'raster':
                 cmd = ['d.rast', 'map=%s' % layerName]
             elif ltype == 'raster_3d':
                 cmd = ['d.rast3d', 'map=%s' % layerName]
             elif ltype == 'vector':
-                cmd = ['d.vect', 'map=%s' % layerName] + GetDisplayVectSettings()
+                cmd = [
+                    'd.vect', 'map=%s' %
+                    layerName] + GetDisplayVectSettings()
             else:
-                GError(parent = self,
-                       message = _("Unsupported map layer type <%s>.") % ltype)
+                GError(parent=self,
+                       message=_("Unsupported map layer type <%s>.") % ltype)
                 return
-            
-            newItem = maptree.AddLayer(ltype = ltype,
-                                       lname = layerName,
-                                       lchecked = check,
-                                       lopacity = 1.0,
-                                       lcmd = cmd,
-                                       lgroup = None)
 
+            newItem = maptree.AddLayer(ltype=ltype,
+                                       lname=layerName,
+                                       lchecked=check,
+                                       lopacity=1.0,
+                                       lcmd=cmd,
+                                       lgroup=None)
+
     def _updateCurrentMap(self, **kwargs):
         """Updates map of the current map window."""
-        if kwargs.has_key('delay'):
+        if 'delay' in kwargs:
             self.GetMapDisplay().GetWindow().UpdateMap(delay=kwargs['delay'])
         else:
             self.GetMapDisplay().GetWindow().UpdateMap()
@@ -1916,8 +2092,8 @@
         """Decides wheter the map should be added to layer tree."""
         if add is None:
             # add new map into layer if globally enabled
-            if UserSettings.Get(group = 'cmd',
-                                key = 'addNewLayer', subkey = 'enabled'):
+            if UserSettings.Get(group='cmd',
+                                key='addNewLayer', subkey='enabled'):
                 self.AddOrUpdateMap(name, ltype)
         elif add:
             # add new map into layer tree
@@ -1925,14 +2101,14 @@
         else:
             # update the map
             display = self.GetMapDisplay()
-            display.GetWindow().UpdateMap(render = True)
+            display.GetWindow().UpdateMap(render=True)
 
     def AddOrUpdateMap(self, mapName, ltype):
         """Add map layer or update"""
         # start new map display if no display is available
         if ltype not in ['raster', 'raster_3d', 'vector']:
-            GError(parent = self,
-                   message = _("Unsupported map layer type <%s>.") % ltype)
+            GError(parent=self,
+                   message=_("Unsupported map layer type <%s>.") % ltype)
             return
 
         if not self.currentPage:
@@ -1940,9 +2116,9 @@
         else:
             display = self.GetMapDisplay()
             mapLayers = map(lambda x: x.GetName(),
-                            display.GetMap().GetListOfLayers(ltype = ltype))
+                            display.GetMap().GetListOfLayers(ltype=ltype))
             if mapName in mapLayers:
-                display.GetWindow().UpdateMap(render = True)
+                display.GetWindow().UpdateMap(render=True)
             else:
                 self.AddMaps([mapName], ltype, check=True)
 
@@ -1950,36 +2126,36 @@
         """Add raster map layer"""
         # start new map display if no display is available
         if not self.currentPage:
-            self.NewDisplay(show = True)
-        
+            self.NewDisplay(show=True)
+
         self.notebook.SetSelectionByName('layers')
         self.GetLayerTree().AddLayer('raster')
-        
+
     def OnAddRasterMisc(self, event):
         """Create misc raster popup-menu"""
         # start new map display if no display is available
         if not self.currentPage:
-            self.NewDisplay(show = True)
-        
+            self.NewDisplay(show=True)
+
         self._popupMenu((('layerRaster_3d', self.OnAddRaster3D),
                          (None, None),
-                         ('layerRgb',    self.OnAddRasterRGB),
-                         ('layerHis',    self.OnAddRasterHIS),
+                         ('layerRgb', self.OnAddRasterRGB),
+                         ('layerHis', self.OnAddRasterHIS),
                          (None, None),
                          ('layerShaded', self.OnAddRasterShaded),
                          (None, None),
                          ('layerRastarrow', self.OnAddRasterArrow),
-                         ('layerRastnum',   self.OnAddRasterNum)))
-        
+                         ('layerRastnum', self.OnAddRasterNum)))
+
         # show map display
         self.GetMapDisplay().Show()
-        
+
     def OnAddVector(self, event):
         """Add vector map to the current layer tree"""
         # start new map display if no display is available
         if not self.currentPage:
-            self.NewDisplay(show = True)
-        
+            self.NewDisplay(show=True)
+
         self.notebook.SetSelectionByName('layers')
         self.GetLayerTree().AddLayer('vector')
 
@@ -1987,11 +2163,11 @@
         """Create misc vector popup-menu"""
         # start new map display if no display is available
         if not self.currentPage:
-            self.NewDisplay(show = True)
+            self.NewDisplay(show=True)
 
         self._popupMenu((('layerThememap', self.OnAddVectorTheme),
-                         ('layerThemechart',    self.OnAddVectorChart)))
-        
+                         ('layerThemechart', self.OnAddVectorChart)))
+
         # show map display
         self.GetMapDisplay().Show()
 
@@ -2009,18 +2185,18 @@
         """Create decoration overlay menu"""
         # start new map display if no display is available
         if not self.currentPage:
-            self.NewDisplay(show = True)
+            self.NewDisplay(show=True)
 
-        self._popupMenu((('layerGrid',     self.OnAddGrid),
-                         ('layerLabels',   self.OnAddLabels),
+        self._popupMenu((('layerGrid', self.OnAddGrid),
+                         ('layerLabels', self.OnAddLabels),
                          ('layerGeodesic', self.OnAddGeodesic),
-                         ('layerRhumb',    self.OnAddRhumb),
+                         ('layerRhumb', self.OnAddRhumb),
                          (None, None),
-                         ('layerCmd',      self.OnAddCommand)))
-        
+                         ('layerCmd', self.OnAddCommand)))
+
         # show map display
         self.GetMapDisplay().Show()
-        
+
     def OnAddRaster3D(self, event):
         """Add 3D raster map to the current layer tree"""
         self.notebook.SetSelectionByName('layers')
@@ -2077,7 +2253,7 @@
         """Add command line map layer to the current layer tree"""
         # start new map display if no display is available
         if not self.currentPage:
-            self.NewDisplay(show = True)
+            self.NewDisplay(show=True)
 
         self.notebook.SetSelectionByName('layers')
         self.GetLayerTree().AddLayer('command')
@@ -2089,7 +2265,7 @@
         """Add layer group"""
         # start new map display if no display is available
         if not self.currentPage:
-            self.NewDisplay(show = True)
+            self.NewDisplay(show=True)
 
         self.notebook.SetSelectionByName('layers')
         self.GetLayerTree().AddLayer('group')
@@ -2116,7 +2292,7 @@
         """Add vector labels map layer to the current layer tree"""
         # start new map display if no display is available
         if not self.currentPage:
-            self.NewDisplay(show = True)
+            self.NewDisplay(show=True)
 
         self.notebook.SetSelectionByName('layers')
         self.GetLayerTree().AddLayer('labels')
@@ -2131,7 +2307,8 @@
             self.MsgNoLayerSelected()
             return
 
-        if UserSettings.Get(group = 'manager', key = 'askOnRemoveLayer', subkey = 'enabled'):
+        if UserSettings.Get(
+                group='manager', key='askOnRemoveLayer', subkey='enabled'):
             layerName = ''
             for item in self.GetLayerTree().GetSelections():
                 name = self.GetLayerTree().GetItemText(item)
@@ -2141,33 +2318,35 @@
                 else:
                     layerName += '<' + name + '>,\n'
             layerName = layerName.rstrip(',\n')
-            
-            if len(layerName) > 2: # <>
+
+            if len(layerName) > 2:  # <>
                 message = _("Do you want to remove map layer(s)\n%s\n"
                             "from layer tree?") % layerName
             else:
                 message = _("Do you want to remove selected map layer(s) "
                             "from layer tree?")
 
-            dlg = wx.MessageDialog (parent = self, message = message,
-                                    caption = _("Remove map layer"),
-                                    style  =  wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+            dlg = wx.MessageDialog(
+                parent=self,
+                message=message,
+                caption=_("Remove map layer"),
+                style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
 
             if dlg.ShowModal() != wx.ID_YES:
                 dlg.Destroy()
                 return
-            
+
             dlg.Destroy()
 
         for layer in self.GetLayerTree().GetSelections():
-            if self.GetLayerTree().GetLayerInfo(layer, key = 'type') == 'group':
+            if self.GetLayerTree().GetLayerInfo(layer, key='type') == 'group':
                 self.GetLayerTree().DeleteChildren(layer)
             self.GetLayerTree().Delete(layer)
-        
+
     def OnKeyDown(self, event):
         """Key pressed"""
         kc = event.GetKeyCode()
-        
+
         if event.ControlDown():
             if kc == wx.WXK_TAB:
                 # switch layer list / command output
@@ -2175,19 +2354,19 @@
                     self.notebook.SetSelectionByName('output')
                 else:
                     self.notebook.SetSelectionByName('layers')
-        
+
         try:
             ckc = chr(kc)
         except ValueError:
             event.Skip()
             return
-        
+
         if event.CtrlDown():
             if kc == 'R':
                 self.OnAddRaster(None)
             elif kc == 'V':
                 self.OnAddVector(None)
-        
+
         event.Skip()
 
     def OnCloseWindow(self, event):
@@ -2206,34 +2385,34 @@
             self._closeWindow(event)
             if ret == wx.ID_YES:
                 self._quitGRASS()
-        
+
     def _closeWindow(self, event):
         """Close wxGUI"""
         # save command protocol if actived
         if self.goutput.btnCmdProtocol.GetValue():
             self.goutput.CmdProtocolSave()
-        
+
         if not self.currentPage:
             self._auimgr.UnInit()
             self.Destroy()
             return
-        
+
         # save changes in the workspace
         maptree = self.GetLayerTree()
-        if self.workspaceChanged and \
-                UserSettings.Get(group = 'manager', key = 'askOnQuit', subkey = 'enabled'):
+        if self.workspaceChanged and UserSettings.Get(
+                group='manager', key='askOnQuit', subkey='enabled'):
             if self.workspaceFile:
                 message = _("Do you want to save changes in the workspace?")
             else:
                 message = _("Do you want to store current settings "
                             "to workspace file?")
-            
+
             # ask user to save current settings
             if maptree.GetCount() > 0:
                 dlg = wx.MessageDialog(self,
-                                       message = message,
-                                       caption = _("Quit GRASS GUI"),
-                                       style = wx.YES_NO | wx.YES_DEFAULT |
+                                       message=message,
+                                       caption=_("Quit GRASS GUI"),
+                                       style=wx.YES_NO | wx.YES_DEFAULT |
                                        wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
                 ret = dlg.ShowModal()
                 dlg.Destroy()
@@ -2243,21 +2422,22 @@
                     else:
                         self.SaveToWorkspaceFile(self.workspaceFile)
                 elif ret == wx.ID_CANCEL:
-                    # when called from menu, it gets CommandEvent and not CloseEvent
+                    # when called from menu, it gets CommandEvent and not
+                    # CloseEvent
                     if hasattr(event, 'Veto'):
                         event.Veto()
                     return
-        
+
         # don't ask any more...
-        UserSettings.Set(group = 'manager', key = 'askOnQuit', subkey = 'enabled',
-                         value = False)
-        
+        UserSettings.Set(group='manager', key='askOnQuit', subkey='enabled',
+                         value=False)
+
         self.OnDisplayCloseAll()
-        
+
         self.notebookLayers.DeleteAllPages()
         self._auimgr.UnInit()
         self.Destroy()
-        
+
     def _quitGRASS(self):
         """Quit GRASS terminal"""
         try:
@@ -2269,18 +2449,18 @@
         Debug.msg(1, "Exiting shell with pid={}".format(shellPid))
         import signal
         os.kill(shellPid, signal.SIGTERM)
-        
+
     def MsgNoLayerSelected(self):
         """Show dialog message 'No layer selected'"""
-        wx.MessageBox(parent = self,
-                      message = _("No map layer selected. Operation canceled."),
-                      caption = _("Message"),
-                      style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
-                      
-    def MsgDisplayResolution(self, limitText = None):
+        wx.MessageBox(parent=self,
+                      message=_("No map layer selected. Operation canceled."),
+                      caption=_("Message"),
+                      style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
+
+    def MsgDisplayResolution(self, limitText=None):
         """Returns dialog for d.rast.num, d.rast.arrow
             when display resolution is not constrained
-            
+
         :param limitText: adds a note about cell limit
         """
         message = _("Display resolution is currently not constrained to "
@@ -2290,8 +2470,8 @@
                     "the resolution?")
         if limitText:
             message += "\n\n%s" % _(limitText)
-        dlg = wx.MessageDialog(parent = self,
-                               message = message,
-                               caption = _("Constrain map to region geometry?"),
-                               style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
+        dlg = wx.MessageDialog(
+            parent=self, message=message,
+            caption=_("Constrain map to region geometry?"),
+            style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
         return dlg

Modified: grass/trunk/gui/wxpython/lmgr/giface.py
===================================================================
--- grass/trunk/gui/wxpython/lmgr/giface.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/lmgr/giface.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -29,6 +29,7 @@
         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
 
@@ -44,19 +45,20 @@
 
 class LayerList(object):
     """@implements core.giface.Layer"""
+
     def __init__(self, tree):
         self._tree = tree
 
     def __len__(self):
         return len([layer for layer in self])
-        
+
     def __iter__(self):
         """Iterates over the contents of the list."""
         item = self._tree.GetFirstChild(self._tree.root)[0]
         while item and item.IsOk():
             yield Layer(self._tree.GetPyData(item))
             item = self._tree.GetNextItem(item)
-        
+
     def __getitem__(self, index):
         """Select a layer from the LayerList using the index."""
         return [l for l in self][index]
@@ -133,6 +135,7 @@
 
 class LayerManagerGrassInterface(object):
     """@implements core::giface::GrassInterface"""
+
     def __init__(self, lmgr):
         """Costructor is specific to the current implementation.
 
@@ -199,7 +202,7 @@
 
     def UpdateCmdHistory(self, cmd):
         self.lmgr.goutput.GetPrompt().UpdateCmdHistory(cmd)
-        
+
     def ShowStatusbar(self, show=True):
         self.lmgr.GetMapDisplay().statusbarManager.Show(show)
 
@@ -207,22 +210,24 @@
         return self.lmgr.GetMapDisplay().statusbarManager.IsShown()
 
     def ShowAllToolbars(self, show=True):
-        if not show: # hide
+        if not show:  # hide
             action = self.lmgr.GetMapDisplay().RemoveToolbar
         else:
             action = self.lmgr.GetMapDisplay().AddToolbar
         for toolbar in self.lmgr.GetMapDisplay().GetToolbarNames():
             action(toolbar)
-            
+
     def AreAllToolbarsShown(self):
         return self.lmgr.GetMapDisplay().GetMapToolbar().IsShown()
 
+
 class LayerManagerGrassInterfaceForMapDisplay(object):
     """Provides reference only to the given layer list (according to tree),
         not to the current.
 
         @implements core::giface::GrassInterface
     """
+
     def __init__(self, giface, tree):
         """
         :param giface: original grass interface
@@ -232,7 +237,8 @@
         self.tree = tree
 
         # Signal emitted to request updating of map
-        self.updateMap = Signal('LayerManagerGrassInterfaceForMapDisplay.updateMap')
+        self.updateMap = Signal(
+            'LayerManagerGrassInterfaceForMapDisplay.updateMap')
 
     def GetLayerTree(self):
         return self.tree

Modified: grass/trunk/gui/wxpython/lmgr/layertree.py
===================================================================
--- grass/trunk/gui/wxpython/lmgr/layertree.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/lmgr/layertree.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -10,7 +10,7 @@
 
 This program is free software under the GNU General Public License
 (>=v2). Read the file COPYING that comes with GRASS for details.
- 
+
 @author Michael Barton (Arizona State University)
 @author Jachym Cepicky (Mendel University of Agriculture)
 @author Martin Landa <landa.martin gmail.com>
@@ -22,28 +22,28 @@
     import wx.lib.agw.customtreectrl as CT
 except ImportError:
     import wx.lib.customtreectrl as CT
-import wx.lib.buttons  as buttons
+import wx.lib.buttons as buttons
 try:
-    import treemixin 
+    import treemixin
 except ImportError:
     from wx.lib.mixins import treemixin
 
 from grass.script import core as grass
 from grass.script import vector as gvector
 
-from core                 import globalvar
-from gui_core.dialogs     import SqlQueryFrame, SetOpacityDialog, TextEntryDialog
-from gui_core.forms       import GUI
-from mapdisp.frame        import MapFrame
-from core.render          import Map
-from wxplot.histogram     import HistogramPlotFrame
-from core.utils           import GetLayerNameFromCmd, ltype2command, _
-from wxplot.profile       import ProfileFrame
-from core.debug           import Debug
-from core.settings        import UserSettings, GetDisplayVectSettings
-from vdigit.main          import haveVDigit
-from core.gcmd            import GWarning, GError, RunCommand
-from icons.icon           import MetaIcon
+from core import globalvar
+from gui_core.dialogs import SqlQueryFrame, SetOpacityDialog, TextEntryDialog
+from gui_core.forms import GUI
+from mapdisp.frame import MapFrame
+from core.render import Map
+from wxplot.histogram import HistogramPlotFrame
+from core.utils import GetLayerNameFromCmd, ltype2command, _
+from wxplot.profile import ProfileFrame
+from core.debug import Debug
+from core.settings import UserSettings, GetDisplayVectSettings
+from vdigit.main import haveVDigit
+from core.gcmd import GWarning, GError, RunCommand
+from icons.icon import MetaIcon
 from web_services.dialogs import SaveWMSLayerDialog
 from gui_core.widgets import MapValidator
 from lmgr.giface import LayerManagerGrassInterfaceForMapDisplay
@@ -52,76 +52,78 @@
 TREE_ITEM_HEIGHT = 25
 
 LMIcons = {
-    'rastImport' : MetaIcon(img = 'layer-import',
-                            label = _('Import raster data')),
-    'rastLink'   : MetaIcon(img = 'layer-import',
-                            label = _('Link external raster data')),
-    'rastUnpack' : MetaIcon(img = 'layer-import',
-                            label = _('Unpack raster map')),
-    'rastOut'    : MetaIcon(img = 'layer-export',
-                            label = _('Set raster output format')),
-    'vectImport' : MetaIcon(img = 'layer-import',
-                            label = _('Import vector data')),
-    'vectLink'   : MetaIcon(img = 'layer-import',
-                                    label = _('Link external vector data')),
-    'vectUnpack' : MetaIcon(img = 'layer-import',
-                            label = _('Unpack vector map')),
-    'vectOut'    : MetaIcon(img = 'layer-export',
-                            label = _('Set vector output format')),
-    'wmsImport'  : MetaIcon(img = 'layer-wms-add',
-                            label = _('Import data from WMS server')),
-    'layerCmd'     : MetaIcon(img = 'layer-command-add',
-                            label = _('Add command layer')),
-    'quit'       : MetaIcon(img = 'quit',
-                            label = _('Quit')),
-    'layerRaster'    : MetaIcon(img = 'raster',
-                            label = _('Add raster map layer')),
-    'layerRgb'     : MetaIcon(img = 'rgb',
-                            label = _('Add RGB map layer')),
-    'layerHis'     : MetaIcon(img = 'his',
-                                    label = _('Add HIS map layer')),
-    'layerShaded'  : MetaIcon(img = 'shaded-relief',
-                              label = _('Add shaded relief map layer')),
-    'layerRastarrow'  : MetaIcon(img = 'aspect-arrow',
-                            label = _('Add raster flow arrows')),
-    'layerRastnum'    : MetaIcon(img = 'cell-cats',
-                            label = _('Add raster cell numbers')),
-    'layerVector'    : MetaIcon(img = 'vector',
-                            label = _('Add vector map layer')),
-    'layerThememap': MetaIcon(img = 'vector-thematic',
-                            label = _('Add thematic area (choropleth) map layer')),
-    'layerThemechart'   : MetaIcon(img = 'vector-chart',
-                            label = _('Add thematic chart layer')),
-    'layerGrid'    : MetaIcon(img = 'layer-grid-add',
-                            label = _('Add grid layer')),
-    'layerGeodesic': MetaIcon(img = 'shortest-distance',
-                            label = _('Add geodesic line layer')),
-    'layerRhumb'   : MetaIcon(img = 'shortest-distance',
-                            label = _('Add rhumbline layer')),
-    'layerLabels'  : MetaIcon(img = 'label',
-                            label = _('Add labels')),
-    'layerRaster_3d'  : MetaIcon(img = 'raster3d',
-                            label = _('Add 3D raster map layer'),
-                            desc  =  _('Note that 3D raster data are rendered only in 3D view mode')),
-    'layerWms'      :  MetaIcon(img = 'wms',
-                            label = _('Add WMS layer.')),
-    'layerOptions'  : MetaIcon(img = 'options',
-                               label = _('Set options')),
-    'layerEdited'     : MetaIcon(img = 'layer-edit',
-                               label = _("Editing mode")),
-    'layerBgmap'     : MetaIcon(img = 'layer-bottom',
-                               label = _("Background vector map"))
-    }
+    'rastImport': MetaIcon(img='layer-import',
+                           label=_('Import raster data')),
+    'rastLink': MetaIcon(img='layer-import',
+                         label=_('Link external raster data')),
+    'rastUnpack': MetaIcon(img='layer-import',
+                           label=_('Unpack raster map')),
+    'rastOut': MetaIcon(img='layer-export',
+                        label=_('Set raster output format')),
+    'vectImport': MetaIcon(img='layer-import',
+                           label=_('Import vector data')),
+    'vectLink': MetaIcon(img='layer-import',
+                         label=_('Link external vector data')),
+    'vectUnpack': MetaIcon(img='layer-import',
+                           label=_('Unpack vector map')),
+    'vectOut': MetaIcon(img='layer-export',
+                        label=_('Set vector output format')),
+    'wmsImport': MetaIcon(img='layer-wms-add',
+                          label=_('Import data from WMS server')),
+    'layerCmd': MetaIcon(img='layer-command-add',
+                         label=_('Add command layer')),
+    'quit': MetaIcon(img='quit',
+                     label=_('Quit')),
+    'layerRaster': MetaIcon(img='raster',
+                            label=_('Add raster map layer')),
+    'layerRgb': MetaIcon(img='rgb',
+                         label=_('Add RGB map layer')),
+    'layerHis': MetaIcon(img='his',
+                         label=_('Add HIS map layer')),
+    'layerShaded': MetaIcon(img='shaded-relief',
+                            label=_('Add shaded relief map layer')),
+    'layerRastarrow': MetaIcon(img='aspect-arrow',
+                               label=_('Add raster flow arrows')),
+    'layerRastnum': MetaIcon(img='cell-cats',
+                             label=_('Add raster cell numbers')),
+    'layerVector': MetaIcon(img='vector',
+                            label=_('Add vector map layer')),
+    'layerThememap': MetaIcon(img='vector-thematic',
+                              label=_('Add thematic area (choropleth) map layer')),
+    'layerThemechart': MetaIcon(img='vector-chart',
+                                label=_('Add thematic chart layer')),
+    'layerGrid': MetaIcon(img='layer-grid-add',
+                          label=_('Add grid layer')),
+    'layerGeodesic': MetaIcon(img='shortest-distance',
+                              label=_('Add geodesic line layer')),
+    'layerRhumb': MetaIcon(img='shortest-distance',
+                           label=_('Add rhumbline layer')),
+    'layerLabels': MetaIcon(img='label',
+                            label=_('Add labels')),
+    'layerRaster_3d': MetaIcon(img='raster3d',
+                               label=_('Add 3D raster map layer'),
+                               desc=_('Note that 3D raster data are rendered only in 3D view mode')),
+    'layerWms': MetaIcon(img='wms',
+                         label=_('Add WMS layer.')),
+    'layerOptions': MetaIcon(img='options',
+                             label=_('Set options')),
+    'layerEdited': MetaIcon(img='layer-edit',
+                            label=_("Editing mode")),
+    'layerBgmap': MetaIcon(img='layer-bottom',
+                           label=_("Background vector map"))
+}
 
+
 class LayerTree(treemixin.DragAndDrop, CT.CustomTreeCtrl):
     """Creates layer tree structure
     """
+
     def __init__(self, parent, giface,
-                 id = wx.ID_ANY, style = wx.SUNKEN_BORDER,
-                 ctstyle = CT.TR_HAS_BUTTONS | CT.TR_HAS_VARIABLE_ROW_HEIGHT |
+                 id=wx.ID_ANY, style=wx.SUNKEN_BORDER,
+                 ctstyle=CT.TR_HAS_BUTTONS | CT.TR_HAS_VARIABLE_ROW_HEIGHT |
                  CT.TR_HIDE_ROOT | CT.TR_ROW_LINES | CT.TR_FULL_ROW_HIGHLIGHT |
                  CT.TR_MULTIPLE, **kwargs):
-        
+
         if 'style' in kwargs:
             ctstyle |= kwargs['style']
             del kwargs['style']
@@ -129,7 +131,8 @@
         del kwargs['idx']
         self.lmgr = kwargs['lmgr']
         del kwargs['lmgr']
-        self.notebook = kwargs['notebook']   # GIS Manager notebook for layer tree
+        # GIS Manager notebook for layer tree
+        self.notebook = kwargs['notebook']
         del kwargs['notebook']
         showMapDisplay = kwargs['showMapDisplay']
         del kwargs['showMapDisplay']
@@ -146,74 +149,90 @@
         # layer change requires a rerendering
         # (used to request rendering only when layer changes are finished)
         self.rerender = False
-        self.hitCheckbox = False             # if cursor points at layer checkbox (to cancel selection changes)
+        # if cursor points at layer checkbox (to cancel selection changes)
+        self.hitCheckbox = False
         self.forceCheck = False              # force check layer if CheckItem is called
-        
+
         try:
             ctstyle |= CT.TR_ALIGN_WINDOWS
         except AttributeError:
             pass
-        
+
         if globalvar.hasAgw:
-            super(LayerTree, self).__init__(parent, id, agwStyle = ctstyle, **kwargs)
+            super(
+                LayerTree,
+                self).__init__(
+                parent,
+                id,
+                agwStyle=ctstyle,
+                **kwargs)
         else:
-            super(LayerTree, self).__init__(parent, id, style = ctstyle, **kwargs)
+            super(
+                LayerTree,
+                self).__init__(
+                parent,
+                id,
+                style=ctstyle,
+                **kwargs)
         self.SetName("LayerTree")
         self.SetBackgroundColour("white")
-        
-        ### SetAutoLayout() causes that no vertical scrollbar is displayed
-        ### when some layers are not visible in layer tree
+
+        # SetAutoLayout() causes that no vertical scrollbar is displayed
+        # when some layers are not visible in layer tree
         # self.SetAutoLayout(True)
         self.SetGradientStyle(1)
         self.EnableSelectionGradient(True)
         self._setGradient()
-        
+
         # init associated map display
-        pos = wx.Point((self.displayIndex + 1) * 25, (self.displayIndex + 1) * 25)
-        self._gifaceForDisplay = LayerManagerGrassInterfaceForMapDisplay(self._giface,
-                                                                         self)
+        pos = wx.Point(
+            (self.displayIndex + 1) * 25,
+            (self.displayIndex + 1) * 25)
+        self._gifaceForDisplay = LayerManagerGrassInterfaceForMapDisplay(
+            self._giface, self)
         self.mapdisplay = MapFrame(self, giface=self._gifaceForDisplay,
-                                   id = wx.ID_ANY, pos = pos,
-                                   size = globalvar.MAP_WINDOW_SIZE,
-                                   style = wx.DEFAULT_FRAME_STYLE,
+                                   id=wx.ID_ANY, pos=pos,
+                                   size=globalvar.MAP_WINDOW_SIZE,
+                                   style=wx.DEFAULT_FRAME_STYLE,
                                    tree=self, notebook=self.notebook,
-                                   lmgr = self.lmgr, page = self.treepg,
-                                   Map = self.Map)
-        
+                                   lmgr=self.lmgr, page=self.treepg,
+                                   Map=self.Map)
+
         self.mapdisplay.SetTitleNumber(self.displayIndex + 1)
-        
+
         # show new display
         if showMapDisplay is True:
             self.mapdisplay.Show()
             self.mapdisplay.Refresh()
             self.mapdisplay.Update()
-        
+
         self.root = self.AddRoot(_("Map Layers"))
         self.SetPyData(self.root, (None, None))
-        
+
         # create image list to use with layer tree
         self.bmpsize = (16, 16)
-        il = wx.ImageList(16, 16, mask = False)
-        trart = wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_OTHER, (16, 16))
+        il = wx.ImageList(16, 16, mask=False)
+        trart = wx.ArtProvider.GetBitmap(
+            wx.ART_FILE_OPEN, wx.ART_OTHER, (16, 16))
         self.folder_open = il.Add(trart)
         trart = wx.ArtProvider.GetBitmap(wx.ART_FOLDER, wx.ART_OTHER, (16, 16))
         self.folder = il.Add(trart)
         self._setIcons(il)
         self.AssignImageList(il)
 
-        self.Bind(wx.EVT_TREE_ITEM_ACTIVATED,   self.OnActivateLayer)
-        self.Bind(wx.EVT_TREE_SEL_CHANGED,      self.OnChangeSel)
-        self.Bind(wx.EVT_TREE_SEL_CHANGING,     self.OnChangingSel)
-        self.Bind(CT.EVT_TREE_ITEM_CHECKED,     self.OnLayerChecked)
-        self.Bind(CT.EVT_TREE_ITEM_CHECKING,    self.OnLayerChecking)
-        self.Bind(wx.EVT_TREE_DELETE_ITEM,      self.OnDeleteLayer)
+        self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivateLayer)
+        self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnChangeSel)
+        self.Bind(wx.EVT_TREE_SEL_CHANGING, self.OnChangingSel)
+        self.Bind(CT.EVT_TREE_ITEM_CHECKED, self.OnLayerChecked)
+        self.Bind(CT.EVT_TREE_ITEM_CHECKING, self.OnLayerChecking)
+        self.Bind(wx.EVT_TREE_DELETE_ITEM, self.OnDeleteLayer)
         self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnLayerContextMenu)
-        self.Bind(wx.EVT_TREE_END_DRAG,         self.OnEndDrag)
-        self.Bind(wx.EVT_TREE_END_LABEL_EDIT,   self.OnRenamed)
-        self.Bind(wx.EVT_KEY_UP,                self.OnKeyUp)
-        self.Bind(wx.EVT_KEY_DOWN,                self.OnKeyDown)
-        self.Bind(wx.EVT_IDLE,                  self.OnIdle)
-        self.Bind(wx.EVT_MOTION,                self.OnMotion)
+        self.Bind(wx.EVT_TREE_END_DRAG, self.OnEndDrag)
+        self.Bind(wx.EVT_TREE_END_LABEL_EDIT, self.OnRenamed)
+        self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
+        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
+        self.Bind(wx.EVT_IDLE, self.OnIdle)
+        self.Bind(wx.EVT_MOTION, self.OnMotion)
 
     def _setIcons(self, il):
         self._icon = {}
@@ -226,33 +245,33 @@
             iconKey = iconName[len("layer"):].lower()
             icon = LMIcons[iconName].GetBitmap(self.bmpsize)
             self._icon[iconKey] = il.Add(icon)
-            
+
     def _getSelectedLayer(self):
         """Get selected layer.
 
         :return: None if no layer selected
         :return: first layer (GenericTreeItem instance) of all selected
         """
-        return self.GetSelectedLayer(multi = False, checkedOnly = False)
+        return self.GetSelectedLayer(multi=False, checkedOnly=False)
 
     # for compatibility
-    layer_selected = property(fget = _getSelectedLayer)
+    layer_selected = property(fget=_getSelectedLayer)
 
-    def GetSelectedLayers(self, checkedOnly = False):
+    def GetSelectedLayers(self, checkedOnly=False):
         """Get selected layers as a list.
 
         .. todo::
             somewhere we have checkedOnly default True and elsewhere False
         """
-        return self.GetSelectedLayer(multi = True, checkedOnly = checkedOnly)
+        return self.GetSelectedLayer(multi=True, checkedOnly=checkedOnly)
 
-    def GetSelectedLayer(self, multi = False, checkedOnly = False):
+    def GetSelectedLayer(self, multi=False, checkedOnly=False):
         """Get selected layer from layer tree.
-        
+
         :param bool multi: return multiple selection as a list
         :param bool checkedOnly: return only the checked layers
 
-        :return: None or [] for multi == True if no layer selected 
+        :return: None or [] for multi == True if no layer selected
         :return: first layer (GenericTreeItem instance) of all selected or a list
         """
         ret = []
@@ -273,7 +292,7 @@
         """!Returns next item from tree (flattened expanded tree)"""
         # this is a not empty group
         if self.GetChildrenCount(item):
-                return self.GetFirstChild(item)[0]
+            return self.GetFirstChild(item)[0]
         # this is a layer outside group
         if self.GetItemParent(item) == self.root:
             return self.GetNextSibling(item)
@@ -288,10 +307,10 @@
 
     def SetItemIcon(self, item, iconName=None):
         if not iconName:
-            iconName = self.GetLayerInfo(item, key = 'maplayer').GetType()
+            iconName = self.GetLayerInfo(item, key='maplayer').GetType()
         self.SetItemImage(item, self._icon[iconName])
-        
-    def _setGradient(self, iType = None):
+
+    def _setGradient(self, iType=None):
         """Set gradient for items
 
         :param iType: bgmap, vdigit or None
@@ -305,32 +324,32 @@
         else:
             self.SetFirstGradientColour(wx.Colour(100, 100, 100))
             self.SetSecondGradientColour(wx.Colour(150, 150, 150))
-        
+
     def GetSelections(self):
         """Returns a list of selected items.
 
         This method is copied from customtreecontrol and overriden because
-        with some version wx (?) multiple selection doesn't work. 
+        with some version wx (?) multiple selection doesn't work.
         Probably it is caused by another GetSelections method in treemixin.DragAndDrop?
         """
         array = []
         idRoot = self.GetRootItem()
         if idRoot:
             array = self.FillArray(idRoot, array)
-        
-        #else: the tree is empty, so no selections
 
+        # else: the tree is empty, so no selections
+
         return array
 
     def GetMap(self):
         """Get map instace"""
         return self.Map
-    
+
     def GetMapDisplay(self):
         """Get associated MapFrame"""
         return self.mapdisplay
 
-    def GetLayerInfo(self, layer, key = None):
+    def GetLayerInfo(self, layer, key=None):
         """Get layer info.
 
         :param layer: GenericTreeItem instance
@@ -371,59 +390,69 @@
             self.rerender = False
             if self.mapdisplay.IsAutoRendered():
                 self.mapdisplay.GetMapWindow().UpdateMap(render=False)
-        
+
         event.Skip()
-        
+
     def OnKeyUp(self, event):
         """Key pressed"""
         key = event.GetKeyCode()
-        
+
         if key == wx.WXK_DELETE and self.lmgr and \
                 not self.GetEditControl():
             self.lmgr.OnDeleteLayer(None)
-        
+
         event.Skip()
 
     def OnKeyDown(self, event):
         """Skip event, otherwise causing error when layertree is empty"""
         event.Skip()
 
-    def OnLayerContextMenu (self, event):
+    def OnLayerContextMenu(self, event):
         """Contextual menu for item/layer"""
         if not self.layer_selected:
             event.Skip()
             return
 
-        ltype = self.GetLayerInfo(self.layer_selected, key = 'type')
-        mapLayer = self.GetLayerInfo(self.layer_selected, key = 'maplayer')
-        
-        Debug.msg (4, "LayerTree.OnContextMenu: layertype=%s" % \
-                       ltype)
+        ltype = self.GetLayerInfo(self.layer_selected, key='type')
+        mapLayer = self.GetLayerInfo(self.layer_selected, key='maplayer')
 
-        if not hasattr (self, "popupID"):
+        Debug.msg(4, "LayerTree.OnContextMenu: layertype=%s" %
+                  ltype)
+
+        if not hasattr(self, "popupID"):
             self.popupID = dict()
-            for key in ('remove', 'rename', 'opacity', 'nviz', 'zoom',
-                        'region', 'export', 'attr', 'edit', 'save_ws',
-                        'bgmap', 'topo', 'meta', 'null', 'zoom1',
-                        'color', 'colori', 'hist', 'univar', 'prof', 'properties', 'sql', 'copy',
-                        'report', 'export-pg', 'export-attr', 'pack'):
+            for key in (
+                    'remove', 'rename', 'opacity', 'nviz', 'zoom', 'region',
+                    'export', 'attr', 'edit', 'save_ws', 'bgmap', 'topo', 'meta',
+                    'null', 'zoom1', 'color', 'colori', 'hist', 'univar', 'prof',
+                    'properties', 'sql', 'copy', 'report', 'export-pg',
+                    'export-attr', 'pack'):
                 self.popupID[key] = wx.NewId()
-        
+
         # get current mapset
         currentMapset = grass.gisenv()['MAPSET']
 
         self.popupMenu = wx.Menu()
 
         numSelected = len(self.GetSelections())
-        
-        item = wx.MenuItem(self.popupMenu, id = self.popupID['remove'], text = _("Remove"))
-        item.SetBitmap(MetaIcon(img = 'layer-remove').GetBitmap(self.bmpsize))
+
+        item = wx.MenuItem(
+            self.popupMenu,
+            id=self.popupID['remove'],
+            text=_("Remove"))
+        item.SetBitmap(MetaIcon(img='layer-remove').GetBitmap(self.bmpsize))
         self.popupMenu.AppendItem(item)
-        self.Bind(wx.EVT_MENU, self.lmgr.OnDeleteLayer, id = self.popupID['remove'])
-        
+        self.Bind(
+            wx.EVT_MENU,
+            self.lmgr.OnDeleteLayer,
+            id=self.popupID['remove'])
+
         if ltype != "command" and numSelected == 1:
-            self.popupMenu.Append(self.popupID['rename'], text = _("Rename"))
-            self.Bind(wx.EVT_MENU, self.OnRenameLayer, id = self.popupID['rename'])
+            self.popupMenu.Append(self.popupID['rename'], text=_("Rename"))
+            self.Bind(
+                wx.EVT_MENU,
+                self.OnRenameLayer,
+                id=self.popupID['rename'])
 
         # when multiple maps are selected of different types
         # we cannot zoom or change region
@@ -434,119 +463,208 @@
             if self.GetLayerInfo(layer, key='type') != ltype:
                 same = False
                 break
-        
+
         # map layer items
         if ltype not in ("group", "command"):
             if numSelected == 1:
                 self.popupMenu.AppendSeparator()
                 if ltype != 'raster_3d':
-                    item = wx.MenuItem(self.popupMenu, id = self.popupID['opacity'], text=_("Change opacity level"))
-                    item.SetBitmap(MetaIcon(img = 'layer-opacity').GetBitmap(self.bmpsize))
+                    item = wx.MenuItem(
+                        self.popupMenu,
+                        id=self.popupID['opacity'],
+                        text=_("Change opacity level"))
+                    item.SetBitmap(
+                        MetaIcon(img='layer-opacity').GetBitmap(self.bmpsize))
                     self.popupMenu.AppendItem(item)
-                    self.Bind(wx.EVT_MENU, self.OnPopupOpacityLevel, id=self.popupID['opacity'])
-                item = wx.MenuItem(self.popupMenu, id = self.popupID['properties'], text = _("Properties"))
-                item.SetBitmap(MetaIcon(img = 'options').GetBitmap(self.bmpsize))
+                    self.Bind(
+                        wx.EVT_MENU,
+                        self.OnPopupOpacityLevel,
+                        id=self.popupID['opacity'])
+                item = wx.MenuItem(
+                    self.popupMenu,
+                    id=self.popupID['properties'],
+                    text=_("Properties"))
+                item.SetBitmap(MetaIcon(img='options').GetBitmap(self.bmpsize))
                 self.popupMenu.AppendItem(item)
-                self.Bind(wx.EVT_MENU, self.OnPopupProperties, id = self.popupID['properties'])
-            
-                if ltype in ('raster', 'vector', 'raster_3d') and self.mapdisplay.IsPaneShown('3d'):
-                    self.popupMenu.Append(self.popupID['nviz'], _("3D view properties"))
-                    self.Bind (wx.EVT_MENU, self.OnNvizProperties, id = self.popupID['nviz'])
+                self.Bind(
+                    wx.EVT_MENU,
+                    self.OnPopupProperties,
+                    id=self.popupID['properties'])
 
+                if ltype in ('raster', 'vector',
+                             'raster_3d') and self.mapdisplay.IsPaneShown('3d'):
+                    self.popupMenu.Append(
+                        self.popupID['nviz'],
+                        _("3D view properties"))
+                    self.Bind(
+                        wx.EVT_MENU,
+                        self.OnNvizProperties,
+                        id=self.popupID['nviz'])
+
             if same and ltype in ('raster', 'vector', 'rgb', 'raster_3d'):
                 self.popupMenu.AppendSeparator()
-                item = wx.MenuItem(self.popupMenu, id = self.popupID['zoom'], text = _("Zoom to selected map(s)"))
-                item.SetBitmap(MetaIcon(img = 'zoom-layer').GetBitmap(self.bmpsize))
+                item = wx.MenuItem(
+                    self.popupMenu,
+                    id=self.popupID['zoom'],
+                    text=_("Zoom to selected map(s)"))
+                item.SetBitmap(
+                    MetaIcon(img='zoom-layer').GetBitmap(self.bmpsize))
                 self.popupMenu.AppendItem(item)
-                self.Bind(wx.EVT_MENU, self.mapdisplay.OnZoomToMap, id = self.popupID['zoom'])
-                
-                item = wx.MenuItem(self.popupMenu, id = self.popupID['region'], text = _("Set computational region from selected map(s)"))
-                item.SetBitmap(MetaIcon(img = 'region').GetBitmap(self.bmpsize))
+                self.Bind(
+                    wx.EVT_MENU,
+                    self.mapdisplay.OnZoomToMap,
+                    id=self.popupID['zoom'])
+
+                item = wx.MenuItem(
+                    self.popupMenu,
+                    id=self.popupID['region'],
+                    text=_("Set computational region from selected map(s)"))
+                item.SetBitmap(MetaIcon(img='region').GetBitmap(self.bmpsize))
                 self.popupMenu.AppendItem(item)
-                self.Bind(wx.EVT_MENU, self.OnSetCompRegFromMap, id = self.popupID['region'])
-        
+                self.Bind(
+                    wx.EVT_MENU,
+                    self.OnSetCompRegFromMap,
+                    id=self.popupID['region'])
+
         # specific items
         try:
-            mltype = self.GetLayerInfo(self.layer_selected, key = 'type')
+            mltype = self.GetLayerInfo(self.layer_selected, key='type')
         except:
             mltype = None
-        
+
         # vector layers (specific items)
         if mltype and mltype == "vector" and numSelected == 1:
             self.popupMenu.AppendSeparator()
-            item = wx.MenuItem(self.popupMenu, id = self.popupID['export'], text = _("Export common formats"))
-            item.SetBitmap(MetaIcon(img = 'layer-export').GetBitmap(self.bmpsize))
+            item = wx.MenuItem(
+                self.popupMenu,
+                id=self.popupID['export'],
+                text=_("Export common formats"))
+            item.SetBitmap(
+                MetaIcon(img='layer-export').GetBitmap(self.bmpsize))
             self.popupMenu.AppendItem(item)
-            self.Bind(wx.EVT_MENU, lambda x: self.lmgr.OnMenuCmd(cmd = ['v.out.ogr',
-                                                                        'input=%s' % mapLayer.GetName()]),
-                      id = self.popupID['export'])
+            self.Bind(
+                wx.EVT_MENU,
+                lambda x: self.lmgr.OnMenuCmd(
+                    cmd=[
+                        'v.out.ogr',
+                        'input=%s' %
+                        mapLayer.GetName()]),
+                id=self.popupID['export'])
             if 'v.out.ogr' not in globalvar.grassCmd:
                 self.popupMenu.Enable(self.popupID['export'], False)
 
-            self.popupMenu.Append(self.popupID['export-pg'], text = _("Export PostGIS"))
-            self.Bind(wx.EVT_MENU, lambda x: self.lmgr.OnMenuCmd(cmd = ['v.out.postgis',
-                                                                        'input=%s' % mapLayer.GetName()]),
-                      id = self.popupID['export-pg'])
+            self.popupMenu.Append(
+                self.popupID['export-pg'],
+                text=_("Export PostGIS"))
+            self.Bind(
+                wx.EVT_MENU,
+                lambda x: self.lmgr.OnMenuCmd(
+                    cmd=[
+                        'v.out.postgis',
+                        'input=%s' %
+                        mapLayer.GetName()]),
+                id=self.popupID['export-pg'])
             if 'v.out.postgis' not in globalvar.grassCmd:
                 self.popupMenu.Enable(self.popupID['export-pg'], False)
 
-            self.popupMenu.Append(self.popupID['export-attr'], text = _("Export attribute table"))
-            self.Bind(wx.EVT_MENU, lambda x: self.lmgr.OnMenuCmd(cmd = ['v.db.select',
-                                                                        'map=%s' % mapLayer.GetName()]),
-                      id = self.popupID['export-attr'])
+            self.popupMenu.Append(
+                self.popupID['export-attr'],
+                text=_("Export attribute table"))
+            self.Bind(
+                wx.EVT_MENU,
+                lambda x: self.lmgr.OnMenuCmd(
+                    cmd=[
+                        'v.db.select',
+                        'map=%s' %
+                        mapLayer.GetName()]),
+                id=self.popupID['export-attr'])
             if 'v.db.select' not in globalvar.grassCmd:
                 self.popupMenu.Enable(self.popupID['export-attr'], False)
 
-            item = wx.MenuItem(self.popupMenu, id = self.popupID['pack'], text = _("Create pack"))
+            item = wx.MenuItem(
+                self.popupMenu,
+                id=self.popupID['pack'],
+                text=_("Create pack"))
             self.popupMenu.AppendItem(item)
-            self.Bind(wx.EVT_MENU, lambda x: self.lmgr.OnMenuCmd(cmd = ['v.pack',
-                                                                        'input=%s' % mapLayer.GetName()]),
-                      id = self.popupID['pack'])
-            
-            lmapset = self.GetLayerInfo(self.layer_selected, key = 'maplayer').GetMapset()
+            self.Bind(
+                wx.EVT_MENU,
+                lambda x: self.lmgr.OnMenuCmd(
+                    cmd=[
+                        'v.pack',
+                        'input=%s' %
+                        mapLayer.GetName()]),
+                id=self.popupID['pack'])
+
+            lmapset = self.GetLayerInfo(
+                self.layer_selected, key='maplayer').GetMapset()
             if lmapset != currentMapset:
-                self.popupMenu.Append(self.popupID['copy'], text = _("Make a copy in the current mapset"))
-                self.Bind(wx.EVT_MENU, self.OnCopyMap, id = self.popupID['copy'])
-            
+                self.popupMenu.Append(
+                    self.popupID['copy'],
+                    text=_("Make a copy in the current mapset"))
+                self.Bind(wx.EVT_MENU, self.OnCopyMap, id=self.popupID['copy'])
+
             self.popupMenu.AppendSeparator()
 
             self.popupMenu.Append(self.popupID['color'], _("Set color table"))
-            self.Bind (wx.EVT_MENU, self.OnVectorColorTable, id = self.popupID['color'])
+            self.Bind(
+                wx.EVT_MENU,
+                self.OnVectorColorTable,
+                id=self.popupID['color'])
 
-            item = wx.MenuItem(self.popupMenu, id = self.popupID['attr'], text = _("Show attribute data"))
-            item.SetBitmap(MetaIcon(img = 'table').GetBitmap(self.bmpsize))
+            item = wx.MenuItem(
+                self.popupMenu,
+                id=self.popupID['attr'],
+                text=_("Show attribute data"))
+            item.SetBitmap(MetaIcon(img='table').GetBitmap(self.bmpsize))
             self.popupMenu.AppendItem(item)
-            self.Bind(wx.EVT_MENU, self.lmgr.OnShowAttributeTable, id = self.popupID['attr'])
+            self.Bind(
+                wx.EVT_MENU,
+                self.lmgr.OnShowAttributeTable,
+                id=self.popupID['attr'])
 
             digitToolbar = self.mapdisplay.GetToolbar('vdigit')
             if digitToolbar:
                 vdigitLayer = digitToolbar.GetLayer()
             else:
                 vdigitLayer = None
-            layer = self.GetLayerInfo(self.layer_selected, key = 'maplayer')
+            layer = self.GetLayerInfo(self.layer_selected, key='maplayer')
             if vdigitLayer is not layer:
-                item = wx.MenuItem(self.popupMenu, id = self.popupID['edit'], text = _("Start editing"))
-                self.Bind (wx.EVT_MENU, self.OnStartEditing, id = self.popupID['edit'])
+                item = wx.MenuItem(
+                    self.popupMenu,
+                    id=self.popupID['edit'],
+                    text=_("Start editing"))
+                self.Bind(
+                    wx.EVT_MENU,
+                    self.OnStartEditing,
+                    id=self.popupID['edit'])
             else:
-                item = wx.MenuItem(self.popupMenu, id = self.popupID['edit'], text = _("Stop editing"))
-                self.Bind (wx.EVT_MENU, self.OnStopEditing,  id = self.popupID['edit'])
-            item.SetBitmap(MetaIcon(img = 'edit').GetBitmap(self.bmpsize))
+                item = wx.MenuItem(
+                    self.popupMenu,
+                    id=self.popupID['edit'],
+                    text=_("Stop editing"))
+                self.Bind(
+                    wx.EVT_MENU,
+                    self.OnStopEditing,
+                    id=self.popupID['edit'])
+            item.SetBitmap(MetaIcon(img='edit').GetBitmap(self.bmpsize))
             self.popupMenu.AppendItem(item)
-            
-            ### removed from layer tree
+
+            # removed from layer tree
             #  if digitToolbar:
-                # background vector map
-                # self.popupMenu.Append(self.popupID['bgmap'],
-                #                       text = _("Use as background vector map for digitizer"),
-                #                       kind = wx.ITEM_CHECK)
-                # self.Bind(wx.EVT_MENU, self.OnSetBgMap, id = self.popupID['bgmap'])
-                # if UserSettings.Get(group = 'vdigit', key = 'bgmap', subkey = 'value',
-                #                     internal = True) == layer.GetName():
-                #     self.popupMenu.Check(self.popupID['bgmap'], True)
-            
-            self.popupMenu.Append(self.popupID['topo'], text = _("Rebuild topology"))
-            self.Bind(wx.EVT_MENU, self.OnTopology, id = self.popupID['topo'])
+            # background vector map
+            # self.popupMenu.Append(self.popupID['bgmap'],
+            #                       text = _("Use as background vector map for digitizer"),
+            #                       kind = wx.ITEM_CHECK)
+            # self.Bind(wx.EVT_MENU, self.OnSetBgMap, id = self.popupID['bgmap'])
+            # if UserSettings.Get(group = 'vdigit', key = 'bgmap', subkey = 'value',
+            #                     internal = True) == layer.GetName():
+            #     self.popupMenu.Check(self.popupID['bgmap'], True)
 
+            self.popupMenu.Append(
+                self.popupID['topo'],
+                text=_("Rebuild topology"))
+            self.Bind(wx.EVT_MENU, self.OnTopology, id=self.popupID['topo'])
+
             # determine format
             # if layer and layer.GetType() == 'vector':
             #     if 'info' not in self.GetLayerInfo(self.layer_selected):
@@ -559,113 +677,200 @@
             #             info['format'].split(',')[1] == 'PostgreSQL':
             #         self.popupMenu.Append(self.popupID['sql'], text = _("SQL Spatial Query"))
             #         self.Bind(wx.EVT_MENU, self.OnSqlQuery, id = self.popupID['sql'])
-            
+
             if layer.GetMapset() != currentMapset:
                 # only vector map in current mapset can be edited
-                self.popupMenu.Enable (self.popupID['edit'], False)
-                self.popupMenu.Enable (self.popupID['topo'], False)
+                self.popupMenu.Enable(self.popupID['edit'], False)
+                self.popupMenu.Enable(self.popupID['topo'], False)
             elif digitToolbar and digitToolbar.GetLayer():
                 # vector map already edited
                 vdigitLayer = digitToolbar.GetLayer()
                 if vdigitLayer is layer:
                     self.popupMenu.Enable(self.popupID['remove'], False)
                     # self.popupMenu.Enable(self.popupID['bgmap'],  False)
-                    self.popupMenu.Enable(self.popupID['topo'],   False)
+                    self.popupMenu.Enable(self.popupID['topo'], False)
                 # else:
                 ###    self.popupMenu.Enable(self.popupID['bgmap'], True)
-            
-            item = wx.MenuItem(self.popupMenu, id = self.popupID['meta'], text = _("Metadata"))
-            item.SetBitmap(MetaIcon(img = 'layer-info').GetBitmap(self.bmpsize))
+
+            item = wx.MenuItem(
+                self.popupMenu,
+                id=self.popupID['meta'],
+                text=_("Metadata"))
+            item.SetBitmap(MetaIcon(img='layer-info').GetBitmap(self.bmpsize))
             self.popupMenu.AppendItem(item)
-            self.Bind (wx.EVT_MENU, self.OnMetadata, id = self.popupID['meta'])
-        
+            self.Bind(wx.EVT_MENU, self.OnMetadata, id=self.popupID['meta'])
+
         # raster layers (specific items)
         elif mltype and mltype == "raster":
             if same:
-                self.popupMenu.Append(self.popupID['zoom1'], text=_("Zoom to selected map(s) (ignore NULLs)"))
-                self.Bind(wx.EVT_MENU, self.mapdisplay.OnZoomToRaster, id=self.popupID['zoom1'])
-            
+                self.popupMenu.Append(
+                    self.popupID['zoom1'],
+                    text=_("Zoom to selected map(s) (ignore NULLs)"))
+                self.Bind(
+                    wx.EVT_MENU,
+                    self.mapdisplay.OnZoomToRaster,
+                    id=self.popupID['zoom1'])
+
             self.popupMenu.AppendSeparator()
-            
+
             if numSelected == 1:
-                item = wx.MenuItem(self.popupMenu, id = self.popupID['export'], text = _("Export"))
-                item.SetBitmap(MetaIcon(img = 'layer-export').GetBitmap(self.bmpsize))
+                item = wx.MenuItem(
+                    self.popupMenu,
+                    id=self.popupID['export'],
+                    text=_("Export"))
+                item.SetBitmap(
+                    MetaIcon(img='layer-export').GetBitmap(self.bmpsize))
                 self.popupMenu.AppendItem(item)
-                self.Bind(wx.EVT_MENU, lambda x: self.lmgr.OnMenuCmd(cmd = ['r.out.gdal',
-                                                                            'input=%s' % mapLayer.GetName()]),
-                          id = self.popupID['export'])
+                self.Bind(
+                    wx.EVT_MENU,
+                    lambda x: self.lmgr.OnMenuCmd(
+                        cmd=[
+                            'r.out.gdal',
+                            'input=%s' %
+                            mapLayer.GetName()]),
+                    id=self.popupID['export'])
 
-                item = wx.MenuItem(self.popupMenu, id = self.popupID['pack'], text = _("Create pack"))
+                item = wx.MenuItem(
+                    self.popupMenu,
+                    id=self.popupID['pack'],
+                    text=_("Create pack"))
                 self.popupMenu.AppendItem(item)
-                self.Bind(wx.EVT_MENU, lambda x: self.lmgr.OnMenuCmd(cmd = ['r.pack',
-                                                                            'input=%s' % mapLayer.GetName()]),
-                          id = self.popupID['pack'])
-                
-                lmapset = self.GetLayerInfo(self.layer_selected, key = 'maplayer').GetMapset()
+                self.Bind(
+                    wx.EVT_MENU,
+                    lambda x: self.lmgr.OnMenuCmd(
+                        cmd=[
+                            'r.pack',
+                            'input=%s' %
+                            mapLayer.GetName()]),
+                    id=self.popupID['pack'])
+
+                lmapset = self.GetLayerInfo(
+                    self.layer_selected, key='maplayer').GetMapset()
                 if lmapset != currentMapset:
-                    self.popupMenu.Append(self.popupID['copy'], text = _("Make a copy in the current mapset"))
-                    self.Bind(wx.EVT_MENU, self.OnCopyMap, id = self.popupID['copy'])
-                
+                    self.popupMenu.Append(
+                        self.popupID['copy'],
+                        text=_("Make a copy in the current mapset"))
+                    self.Bind(
+                        wx.EVT_MENU,
+                        self.OnCopyMap,
+                        id=self.popupID['copy'])
+
                 self.popupMenu.AppendSeparator()
-                
+
             self.popupMenu.Append(self.popupID['color'], _("Set color table"))
-            self.Bind (wx.EVT_MENU, self.OnRasterColorTable, id = self.popupID['color'])
-            self.popupMenu.Append(self.popupID['colori'], _("Set color table interactively"))
-            self.Bind (wx.EVT_MENU, self.lmgr.OnRasterRules, id = self.popupID['colori'])
+            self.Bind(
+                wx.EVT_MENU,
+                self.OnRasterColorTable,
+                id=self.popupID['color'])
+            self.popupMenu.Append(
+                self.popupID['colori'],
+                _("Set color table interactively"))
+            self.Bind(
+                wx.EVT_MENU,
+                self.lmgr.OnRasterRules,
+                id=self.popupID['colori'])
 
-            item = wx.MenuItem(self.popupMenu, id = self.popupID['hist'], text = _("Histogram"))
-            item.SetBitmap(MetaIcon(img = 'layer-raster-histogram').GetBitmap(self.bmpsize))
+            item = wx.MenuItem(
+                self.popupMenu,
+                id=self.popupID['hist'],
+                text=_("Histogram"))
+            item.SetBitmap(
+                MetaIcon(img='layer-raster-histogram').GetBitmap(self.bmpsize))
             self.popupMenu.AppendItem(item)
-            self.Bind (wx.EVT_MENU, self.OnHistogram, id = self.popupID['hist'])
+            self.Bind(wx.EVT_MENU, self.OnHistogram, id=self.popupID['hist'])
 
-            item = wx.MenuItem(self.popupMenu, id = self.popupID['univar'], text = _("Univariate raster statistics"))
-            item.SetBitmap(MetaIcon(img = 'raster-stats').GetBitmap(self.bmpsize))
+            item = wx.MenuItem(
+                self.popupMenu,
+                id=self.popupID['univar'],
+                text=_("Univariate raster statistics"))
+            item.SetBitmap(
+                MetaIcon(img='raster-stats').GetBitmap(self.bmpsize))
             self.popupMenu.AppendItem(item)
-            self.Bind (wx.EVT_MENU, self.OnUnivariateStats, id = self.popupID['univar'])
+            self.Bind(
+                wx.EVT_MENU,
+                self.OnUnivariateStats,
+                id=self.popupID['univar'])
 
-            item = wx.MenuItem(self.popupMenu, id = self.popupID['report'], text = _("Report raster statistics"))
-            item.SetBitmap(MetaIcon(img = 'stats').GetBitmap(self.bmpsize))
+            item = wx.MenuItem(
+                self.popupMenu,
+                id=self.popupID['report'],
+                text=_("Report raster statistics"))
+            item.SetBitmap(MetaIcon(img='stats').GetBitmap(self.bmpsize))
             self.popupMenu.AppendItem(item)
-            self.Bind(wx.EVT_MENU, self.OnReportStats, id = self.popupID['report'])
-            
+            self.Bind(
+                wx.EVT_MENU,
+                self.OnReportStats,
+                id=self.popupID['report'])
+
             if numSelected == 1:
-                item = wx.MenuItem(self.popupMenu, id = self.popupID['prof'], text = _("Profile"))
-                item.SetBitmap(MetaIcon(img = 'layer-raster-profile').GetBitmap(self.bmpsize))
+                item = wx.MenuItem(
+                    self.popupMenu,
+                    id=self.popupID['prof'],
+                    text=_("Profile"))
+                item.SetBitmap(
+                    MetaIcon(img='layer-raster-profile').GetBitmap(self.bmpsize))
                 self.popupMenu.AppendItem(item)
-                self.Bind (wx.EVT_MENU, self.OnProfile, id = self.popupID['prof'])
+                self.Bind(wx.EVT_MENU, self.OnProfile, id=self.popupID['prof'])
 
-                item = wx.MenuItem(self.popupMenu, id = self.popupID['meta'], text = _("Metadata"))
-                item.SetBitmap(MetaIcon(img = 'layer-info').GetBitmap(self.bmpsize))
+                item = wx.MenuItem(
+                    self.popupMenu,
+                    id=self.popupID['meta'],
+                    text=_("Metadata"))
+                item.SetBitmap(
+                    MetaIcon(img='layer-info').GetBitmap(self.bmpsize))
                 self.popupMenu.AppendItem(item)
-                self.Bind (wx.EVT_MENU, self.OnMetadata, id = self.popupID['meta'])
-            
+                self.Bind(
+                    wx.EVT_MENU,
+                    self.OnMetadata,
+                    id=self.popupID['meta'])
+
         elif mltype and mltype == 'raster_3d':
             if numSelected == 1:
                 self.popupMenu.AppendSeparator()
-                self.popupMenu.Append(self.popupID['color'], _("Set color table"))
-                self.Bind(wx.EVT_MENU, self.OnRasterColorTable, id=self.popupID['color'])
-                
-                item = wx.MenuItem(self.popupMenu, id = self.popupID['univar'], text = _("Univariate raster statistics"))
-                item.SetBitmap(MetaIcon(img = 'stats').GetBitmap(self.bmpsize))
+                self.popupMenu.Append(
+                    self.popupID['color'],
+                    _("Set color table"))
+                self.Bind(
+                    wx.EVT_MENU,
+                    self.OnRasterColorTable,
+                    id=self.popupID['color'])
+
+                item = wx.MenuItem(
+                    self.popupMenu,
+                    id=self.popupID['univar'],
+                    text=_("Univariate raster statistics"))
+                item.SetBitmap(MetaIcon(img='stats').GetBitmap(self.bmpsize))
                 self.popupMenu.AppendItem(item)
-                self.Bind (wx.EVT_MENU, self.OnUnivariateStats, id = self.popupID['univar'])
-                 
-                item = wx.MenuItem(self.popupMenu, id = self.popupID['meta'], text = _("Metadata"))
-                item.SetBitmap(MetaIcon(img = 'layer-info').GetBitmap(self.bmpsize))
+                self.Bind(
+                    wx.EVT_MENU,
+                    self.OnUnivariateStats,
+                    id=self.popupID['univar'])
+
+                item = wx.MenuItem(
+                    self.popupMenu,
+                    id=self.popupID['meta'],
+                    text=_("Metadata"))
+                item.SetBitmap(
+                    MetaIcon(img='layer-info').GetBitmap(self.bmpsize))
                 self.popupMenu.AppendItem(item)
-                self.Bind (wx.EVT_MENU, self.OnMetadata, id = self.popupID['meta'])
-        
+                self.Bind(
+                    wx.EVT_MENU,
+                    self.OnMetadata,
+                    id=self.popupID['meta'])
+
         # web service layers (specific item)
         elif mltype and mltype == "wms":
-            self.popupMenu.Append(self.popupID['save_ws'], text = _("Save web service layer"))
-            self.Bind(wx.EVT_MENU, self.OnSaveWs, id = self.popupID['save_ws'])
+            self.popupMenu.Append(
+                self.popupID['save_ws'],
+                text=_("Save web service layer"))
+            self.Bind(wx.EVT_MENU, self.OnSaveWs, id=self.popupID['save_ws'])
 
         self.PopupMenu(self.popupMenu)
         self.popupMenu.Destroy()
 
     def OnSaveWs(self, event):
         """Show dialog for saving web service layer into GRASS vector/raster layer"""
-        mapLayer = self.GetLayerInfo(self.layer_selected, key = 'maplayer')
+        mapLayer = self.GetLayerInfo(self.layer_selected, key='maplayer')
         dlg = SaveWMSLayerDialog(parent=self, layer=mapLayer,
                                  giface=self._gifaceForDisplay)
         dlg.CentreOnScreen()
@@ -673,7 +878,7 @@
 
     def OnTopology(self, event):
         """Rebuild topology of selected vector map"""
-        mapLayer = self.GetLayerInfo(self.layer_selected, key = 'maplayer')
+        mapLayer = self.GetLayerInfo(self.layer_selected, key='maplayer')
         cmd = ['v.build',
                'map=%s' % mapLayer.GetName()]
         self._giface.RunCmd(cmd)
@@ -681,18 +886,18 @@
     def OnSqlQuery(self, event):
         """Show SQL query window for PostGIS layers
         """
-        dlg = SqlQueryFrame(parent = self)
+        dlg = SqlQueryFrame(parent=self)
         dlg.CentreOnScreen()
         dlg.Show()
-        
+
     def OnMetadata(self, event):
         """Print metadata of raster/vector map layer
-        
+
         .. todo::
             Dialog to modify metadata
         """
-        mapLayer = self.GetLayerInfo(self.layer_selected, key = 'maplayer')
-        mltype = self.GetLayerInfo(self.layer_selected,key = 'type')
+        mapLayer = self.GetLayerInfo(self.layer_selected, key='maplayer')
+        mltype = self.GetLayerInfo(self.layer_selected, key='type')
 
         if mltype == 'raster':
             cmd = ['r.info']
@@ -708,14 +913,14 @@
     def OnSetCompRegFromRaster(self, event):
         """Set computational region from selected raster map (ignore NULLs).
         Unused, removed item from layer context menu"""
-        mapLayer = self.GetLayerInfo(self.layer_selected, key = 'maplayer')
+        mapLayer = self.GetLayerInfo(self.layer_selected, key='maplayer')
 
         cmd = ['g.region', 'raster=%s' % mapLayer.GetName(),
                'zoom=%s' % mapLayer.GetName()]
 
         # print output to command log area
         self._giface.RunCmd(cmd, notification=Notification.NO_NOTIFICATION)
-        
+
         # re-render map display
         self._giface.GetMapWindow().UpdateMap(render=True)
 
@@ -726,9 +931,9 @@
         vect = []
         rast3d = []
         for layer in self.GetSelections():
-            mapLayer = self.GetLayerInfo(layer, key = 'maplayer')
-            mltype = self.GetLayerInfo(layer, key = 'type')
-                
+            mapLayer = self.GetLayerInfo(layer, key='maplayer')
+            mltype = self.GetLayerInfo(layer, key='type')
+
             if mltype == 'raster':
                 rast.append(mapLayer.GetName())
             elif mltype == 'vector':
@@ -738,7 +943,7 @@
             elif mltype == 'rgb':
                 for rname in mapLayer.GetName().splitlines():
                     rast.append(rname)
-        
+
         cmd = ['g.region']
         if rast:
             cmd.append('raster=%s' % ','.join(rast))
@@ -746,25 +951,28 @@
             cmd.append('vector=%s' % ','.join(vect))
         if rast3d:
             cmd.append('raster_3d=%s' % ','.join(rast3d))
-        
+
         # print output to command log area
         if len(cmd) > 1:
             if mltype == 'raster_3d':
                 cmd.append('-3')
-            self._giface.RunCmd(cmd, compReg = False,
+            self._giface.RunCmd(cmd, compReg=False,
                                 notification=Notification.NO_NOTIFICATION)
-        
+
         # re-render map display
         self._giface.GetMapWindow().UpdateMap(render=True)
-            
+
     def OnProfile(self, event):
         """Plot profile of given raster map layer"""
-        mapLayer = self.GetLayerInfo(self.layer_selected, key = 'maplayer')
+        mapLayer = self.GetLayerInfo(self.layer_selected, key='maplayer')
         if not mapLayer.GetName():
-            wx.MessageBox(parent = self,
-                          message = _("Unable to create profile of "
-                                    "raster map."),
-                          caption = _("Error"), style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
+            wx.MessageBox(
+                parent=self,
+                message=_(
+                    "Unable to create profile of "
+                    "raster map."),
+                caption=_("Error"),
+                style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
             return
         self.mapdisplay.Profile(rasters=[mapLayer.GetName()])
 
@@ -774,29 +982,33 @@
         raster3d = []
         for layer in self.GetSelectedLayers():
             if self.GetLayerInfo(layer, key='type') == 'raster_3d':
-                raster3d.append(self.GetLayerInfo(layer, key = 'maplayer').GetName())
+                raster3d.append(
+                    self.GetLayerInfo(
+                        layer, key='maplayer').GetName())
             else:
-                raster2d.append(self.GetLayerInfo(layer, key = 'maplayer').GetName())
-        
+                raster2d.append(
+                    self.GetLayerInfo(
+                        layer, key='maplayer').GetName())
+
         if raster2d:
-            GUI(parent = self, giface = self._giface).ParseCommand(['r.colors',
-                                                                    'map=%s' % ','.join(raster2d)])
+            GUI(parent=self, giface=self._giface).ParseCommand(
+                ['r.colors', 'map=%s' % ','.join(raster2d)])
         if raster3d:
-            GUI(parent = self, giface = self._giface).ParseCommand(['r3.colors',
-                                                                    'map=%s' % ','.join(raster3d)])
-            
+            GUI(parent=self, giface=self._giface).ParseCommand(
+                ['r3.colors', 'map=%s' % ','.join(raster3d)])
+
     def OnVectorColorTable(self, event):
         """Set color table for vector map"""
-        name = self.GetLayerInfo(self.layer_selected, key = 'maplayer').GetName()
-        GUI(parent = self, centreOnParent = False).ParseCommand(['v.colors',
-                                                                 'map=%s' % name])
-        
+        name = self.GetLayerInfo(self.layer_selected, key='maplayer').GetName()
+        GUI(parent=self, centreOnParent=False).ParseCommand(['v.colors',
+                                                             'map=%s' % name])
+
     def OnCopyMap(self, event):
         """Copy selected map into current mapset"""
         layer = self.GetSelectedLayer()
         ltype = self.GetLayerInfo(layer, key='type')
-        lnameSrc = self.GetLayerInfo(layer, key = 'maplayer').GetName()
-        
+        lnameSrc = self.GetLayerInfo(layer, key='maplayer').GetName()
+
         if ltype == 'raster':
             key = 'raster'
             module = 'rast'
@@ -810,81 +1022,103 @@
             module = 'rast3d'
             label = _('3D raster map')
         else:
-            GError(_("Unsupported map type <%s>") % ltype, parent = self)
+            GError(_("Unsupported map type <%s>") % ltype, parent=self)
             return
-        
+
         # TODO: replace by New[Raster|Vector]Dialog
-        dlg = TextEntryDialog(parent = self,
-                              message = _('Enter name for the new %s in the current mapset:') % label.lower(),
-                              caption = _('Make a copy of %s <%s>') % (label.lower(), lnameSrc),
-                              defaultValue = lnameSrc.split('@')[0],
-                              validator = MapValidator(),
-                              size = (700, -1))
+        dlg = TextEntryDialog(
+            parent=self,
+            message=_('Enter name for the new %s in the current mapset:') %
+            label.lower(),
+            caption=_('Make a copy of %s <%s>') % (label.lower(),
+                                                   lnameSrc),
+            defaultValue=lnameSrc.split('@')[0],
+            validator=MapValidator(),
+            size=(700, -1))
         if dlg.ShowModal() == wx.ID_OK:
             lnameDst = dlg.GetValue()
             dlg.Destroy()
         else:
             dlg.Destroy()
             return
-        
+
         currentMapset = grass.gisenv()['MAPSET']
         # check if map already exists
         if lnameDst in grass.list_grouped(key)[currentMapset]:
-            dlgOw = wx.MessageDialog(parent = self, message = _("%s <%s> already exists "
-                                                                "in the current mapset. "
-                                                                "Do you want to overwrite it?") % (label, lnameDst),
-                                     caption = _("Overwrite?"),
-                                     style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+            dlgOw = wx.MessageDialog(
+                parent=self,
+                message=_(
+                    "%s <%s> already exists "
+                    "in the current mapset. "
+                    "Do you want to overwrite it?") %
+                (label,
+                 lnameDst),
+                caption=_("Overwrite?"),
+                style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
             if dlgOw.ShowModal() != wx.ID_YES:
                 return
-        
-        kwargs = {key : '%s,%s' % (lnameSrc, lnameDst)}
-        if 0 != RunCommand('g.copy', overwrite = True, **kwargs):
+
+        kwargs = {key: '%s,%s' % (lnameSrc, lnameDst)}
+        if 0 != RunCommand('g.copy', overwrite=True, **kwargs):
             GError(_("Unable to make copy of <%s>") % lnameSrc,
                    parent=self)
             return
-        
+
         if '@' in lnameDst:
             mapsetDst = lnameDst.split('@')[1]
             if mapsetDst != currentMapset:
-                GError(_("Unable to make copy of <%s>. Mapset <%s> is not current mapset.") % \
-                           (lnameSrc, mapsetDst))
+                GError(
+                    _("Unable to make copy of <%s>. Mapset <%s> is not current mapset.") %
+                    (lnameSrc, mapsetDst))
                 return
-            
+
         lnameDst += '@' + currentMapset
         # add copied map to the layer tree
-        self.AddLayer(ltype, lname = lnameDst, lcmd = ['d.%s' % module, 'map=%s' % lnameDst])
+        self.AddLayer(
+            ltype,
+            lname=lnameDst,
+            lcmd=[
+                'd.%s' %
+                module,
+                'map=%s' %
+                lnameDst])
 
     def OnHistogram(self, event):
         """Plot histogram for given raster map layer
         """
         rasterList = []
         for layer in self.GetSelectedLayers():
-            rasterList.append(self.GetLayerInfo(layer, key = 'maplayer').GetName())
+            rasterList.append(
+                self.GetLayerInfo(
+                    layer, key='maplayer').GetName())
 
         if not rasterList:
-            GError(parent = self,
-                   message = _("Unable to display histogram of "
-                               "raster map. No map name defined."))
+            GError(parent=self,
+                   message=_("Unable to display histogram of "
+                             "raster map. No map name defined."))
             return
-        
-        win = HistogramPlotFrame(parent = self, rasterList = rasterList)
+
+        win = HistogramPlotFrame(parent=self, rasterList=rasterList)
         win.CentreOnScreen()
         win.Show()
-                
+
     def OnUnivariateStats(self, event):
         """Univariate 2D/3D raster statistics"""
         raster2d = []
         raster3d = []
         for layer in self.GetSelectedLayers():
             if self.GetLayerInfo(layer, key='type') == 'raster_3d':
-                raster3d.append(self.GetLayerInfo(layer, key = 'maplayer').GetName())
+                raster3d.append(
+                    self.GetLayerInfo(
+                        layer, key='maplayer').GetName())
             else:
-                raster2d.append(self.GetLayerInfo(layer, key = 'maplayer').GetName())
-        
+                raster2d.append(
+                    self.GetLayerInfo(
+                        layer, key='maplayer').GetName())
+
         if raster2d:
             self._giface.RunCmd(['r.univar', 'map=%s' % ','.join(raster2d)])
-        
+
         if raster3d:
             self._giface.RunCmd(['r3.univar', 'map=%s' % ','.join(raster3d)])
 
@@ -894,39 +1128,42 @@
         # TODO: Implement self.GetSelectedLayers(ltype='raster')
         for layer in self.GetSelectedLayers():
             if self.GetLayerInfo(layer, key='type') == 'raster':
-                rasters.append(self.GetLayerInfo(layer, key = 'maplayer').GetName())
-        
+                rasters.append(
+                    self.GetLayerInfo(
+                        layer, key='maplayer').GetName())
+
         if rasters:
-            self._giface.RunCmd(['r.report', 'map=%s' % ','.join(rasters), 'units=h,c,p'])
-        
+            self._giface.RunCmd(['r.report', 'map=%s' %
+                                 ','.join(rasters), 'units=h,c,p'])
+
     def OnStartEditing(self, event):
         """Start editing vector map layer requested by the user
         """
-        mapLayer = self.GetLayerInfo(self.layer_selected, key = 'maplayer')
+        mapLayer = self.GetLayerInfo(self.layer_selected, key='maplayer')
         if not haveVDigit:
             from vdigit import errorMsg
-            
-            self.mapdisplay.toolbars['map'].combo.SetValue (_("2D view"))
-            
+
+            self.mapdisplay.toolbars['map'].combo.SetValue(_("2D view"))
+
             GError(_("Unable to start wxGUI vector digitizer.\n"
-                     "Details: %s") % errorMsg, parent = self)
+                     "Details: %s") % errorMsg, parent=self)
             return
-        
-        if not self.mapdisplay.GetToolbar('vdigit'): # enable tool
+
+        if not self.mapdisplay.GetToolbar('vdigit'):  # enable tool
             self.mapdisplay.AddToolbar('vdigit')
 
-        else: # tool already enabled
+        else:  # tool already enabled
             pass
-        
+
         # mark layer as 'edited'
         self.mapdisplay.toolbars['vdigit'].StartEditing(mapLayer)
-        
+
     def StartEditing(self, layerItem):
         self._setGradient('vdigit')
         if layerItem:
             self.SetItemIcon(layerItem, 'edited')
             self.RefreshLine(layerItem)
-        
+
     def OnStopEditing(self, event):
         """Stop editing the current vector map layer
         """
@@ -941,37 +1178,43 @@
         try:
             layerItem = self.FindItemByData('name', mapName)[0]
         except IndexError:
-             return
-        
+            return
+
         if not unset:
             self._setGradient('bgmap')
             self.SetItemIcon(layerItem, 'bgmap')
         else:
             self._setGradient()
             self.SetItemIcon(layerItem)
-        
+
         self.RefreshLine(layerItem)
 
-    def OnPopupProperties (self, event):
+    def OnPopupProperties(self, event):
         """Popup properties dialog"""
         self.PropertiesDialog(self.layer_selected)
 
     def OnPopupOpacityLevel(self, event):
         """Popup opacity level indicator"""
-        if not self.GetLayerInfo(self.layer_selected, key = 'ctrl'):
+        if not self.GetLayerInfo(self.layer_selected, key='ctrl'):
             return
-        
-        maplayer = self.GetLayerInfo(self.layer_selected, key = 'maplayer')
+
+        maplayer = self.GetLayerInfo(self.layer_selected, key='maplayer')
         current_opacity = maplayer.GetOpacity()
-        
-        dlg = SetOpacityDialog(self, opacity = current_opacity,
-                               title = _("Set opacity of <%s>") % maplayer.GetName())
-        dlg.applyOpacity.connect(lambda value:
-                                 self.ChangeLayerOpacity(layer=self.layer_selected, value=value))
+
+        dlg = SetOpacityDialog(
+            self,
+            opacity=current_opacity,
+            title=_("Set opacity of <%s>") %
+            maplayer.GetName())
+        dlg.applyOpacity.connect(
+            lambda value: self.ChangeLayerOpacity(
+                layer=self.layer_selected, value=value))
         dlg.CentreOnParent()
 
         if dlg.ShowModal() == wx.ID_OK:
-            self.ChangeLayerOpacity(layer = self.layer_selected, value = dlg.GetOpacity())
+            self.ChangeLayerOpacity(
+                layer=self.layer_selected,
+                value=dlg.GetOpacity())
         dlg.Destroy()
 
     def ChangeLayerOpacity(self, layer, value):
@@ -980,23 +1223,24 @@
         :param layer: layer for which to change (item in layertree)
         :param value: opacity value (float between 0 and 1)
         """
-        maplayer = self.GetLayerInfo(layer, key = 'maplayer')
+        maplayer = self.GetLayerInfo(layer, key='maplayer')
         self.Map.ChangeOpacity(maplayer, value)
         maplayer.SetOpacity(value)
         self.SetItemText(layer,
                          self._getLayerName(layer))
-        
+
         # vector layer currently edited
-        if self.GetMapDisplay().GetToolbar('vdigit') and \
-                self.GetMapDisplay().GetToolbar('vdigit').GetLayer() == maplayer:
+        if self.GetMapDisplay().GetToolbar('vdigit') and self.GetMapDisplay(
+        ).GetToolbar('vdigit').GetLayer() == maplayer:
             alpha = int(value * 255)
-            self.GetMapDisplay().GetWindow().digit.GetDisplay().UpdateSettings(alpha = alpha)
-            
+            self.GetMapDisplay().GetWindow().digit.GetDisplay().UpdateSettings(alpha=alpha)
+
         # redraw map if auto-rendering is enabled
         renderVector = False
         if self.GetMapDisplay().GetToolbar('vdigit'):
             renderVector = True
-        self.GetMapDisplay().GetWindow().UpdateMap(render = False, renderVector = renderVector)
+        self.GetMapDisplay().GetWindow().UpdateMap(
+            render=False, renderVector=renderVector)
 
     def OnNvizProperties(self, event):
         """Nviz-related properties (raster/vector/volume)
@@ -1005,33 +1249,33 @@
             vector/volume
         """
         self.lmgr.notebook.SetSelectionByName('nviz')
-        ltype = self.GetLayerInfo(self.layer_selected, key = 'type')
+        ltype = self.GetLayerInfo(self.layer_selected, key='type')
         if ltype == 'raster':
             self.lmgr.nviz.SetPage('surface')
         elif ltype == 'vector':
             self.lmgr.nviz.SetPage('vector')
         elif ltype == 'raster_3d':
             self.lmgr.nviz.SetPage('volume')
-        
-    def OnRenameLayer (self, event):
+
+    def OnRenameLayer(self, event):
         """Rename layer"""
         self.EditLabel(self.layer_selected)
         self.GetEditControl().SetSelection(-1, -1)
-        
+
     def OnRenamed(self, event):
         """Layer renamed"""
         if not event.GetLabel():
             event.Skip()
             return
-        
+
         item = self.layer_selected
-        self.SetLayerInfo(item, key = 'label', value = event.GetLabel())
+        self.SetLayerInfo(item, key='label', value=event.GetLabel())
         self.SetItemText(item, self._getLayerName(item))
-        
+
         event.Skip()
 
-    def AddLayer(self, ltype, lname = None, lchecked = None,
-                 lopacity = 1.0, lcmd = None, lgroup = None, lvdigit = None, lnviz = None, multiple = True):
+    def AddLayer(self, ltype, lname=None, lchecked=None, lopacity=1.0,
+                 lcmd=None, lgroup=None, lvdigit=None, lnviz=None, multiple=True):
         """Add new item to the layer tree, create corresponding MapLayer instance.
         Launch property dialog if needed (raster, vector, etc.)
 
@@ -1049,19 +1293,19 @@
             # check for duplicates
             item = self.GetFirstChild(self.root)[0]
             while item and item.IsOk():
-                if self.GetLayerInfo(item, key = 'type') == 'vector':
-                    name = self.GetLayerInfo(item, key = 'maplayer').GetName()
+                if self.GetLayerInfo(item, key='type') == 'vector':
+                    name = self.GetLayerInfo(item, key='maplayer').GetName()
                     if name == lname:
                         return
                 item = self.GetNextItem(item)
-        
+
         selectedLayer = self.GetSelectedLayer()
         # deselect active item
         if lchecked != False and selectedLayer:
             self.SelectItem(selectedLayer, select=False)
-        
-        Debug.msg (3, "LayerTree().AddLayer(): ltype=%s" % (ltype))
-        
+
+        Debug.msg(3, "LayerTree().AddLayer(): ltype=%s" % (ltype))
+
         if ltype == 'command':
             # generic command item
             ctrl = self._createCommandCtrl()
@@ -1073,39 +1317,43 @@
             grouptext = _('Layer group:') + str(self.groupnode)
             self.groupnode += 1
         else:
-            btnbmp = LMIcons["layerOptions"].GetBitmap((16,16))
-            ctrl = buttons.GenBitmapButton(self, id = wx.ID_ANY, bitmap = btnbmp, size = (24,24))
+            btnbmp = LMIcons["layerOptions"].GetBitmap((16, 16))
+            ctrl = buttons.GenBitmapButton(
+                self, id=wx.ID_ANY, bitmap=btnbmp, size=(24, 24))
             ctrl.SetToolTipString(_("Click to edit layer settings"))
             self.Bind(wx.EVT_BUTTON, self.OnLayerContextMenu, ctrl)
         # add layer to the layer tree
         if selectedLayer and selectedLayer != self.GetRootItem():
-            if self.GetLayerInfo(selectedLayer, key = 'type') == 'group' \
-                and self.IsExpanded(selectedLayer):
-                # add to group (first child of self.layer_selected) if group expanded
-                layer = self.PrependItem(parent = selectedLayer,
-                                         text = '', ct_type = 1, wnd = ctrl)
+            if self.GetLayerInfo(selectedLayer, key='type') == 'group' \
+                    and self.IsExpanded(selectedLayer):
+                # add to group (first child of self.layer_selected) if group
+                # expanded
+                layer = self.PrependItem(parent=selectedLayer,
+                                         text='', ct_type=1, wnd=ctrl)
             else:
                 # prepend to individual layer or non-expanded group
                 if lgroup == -1:
                     # -> last child of root (loading from workspace)
-                    layer = self.AppendItem(parentId = self.root,
-                                            text = '', ct_type = 1, wnd = ctrl)
+                    layer = self.AppendItem(parentId=self.root,
+                                            text='', ct_type=1, wnd=ctrl)
                 elif lgroup > -1:
                     # -> last child of group (loading from workspace)
-                    parent = self.FindItemByIndex(index = lgroup)
+                    parent = self.FindItemByIndex(index=lgroup)
                     if not parent:
                         parent = self.root
-                    layer = self.AppendItem(parentId = parent,
-                                            text = '', ct_type = 1, wnd = ctrl)
+                    layer = self.AppendItem(parentId=parent,
+                                            text='', ct_type=1, wnd=ctrl)
                 elif lgroup is None:
                     # -> previous sibling of selected layer
                     parent = self.GetItemParent(selectedLayer)
-                    layer = self.InsertItem(parentId = parent,
-                                            input = self.GetPrevSibling(selectedLayer),
-                                            text = '', ct_type = 1, wnd = ctrl)
-        else: # add first layer to the layer tree (first child of root)
-            layer = self.PrependItem(parent = self.root, text = '', ct_type = 1, wnd = ctrl)
-        
+                    layer = self.InsertItem(
+                        parentId=parent, input=self.GetPrevSibling(
+                            selectedLayer),
+                        text='', ct_type=1, wnd=ctrl)
+        else:  # add first layer to the layer tree (first child of root)
+            layer = self.PrependItem(
+                parent=self.root, text='', ct_type=1, wnd=ctrl)
+
         # layer is initially unchecked as inactive (beside 'command')
         # use predefined value if given
         if lchecked is not None:
@@ -1114,22 +1362,34 @@
         else:
             checked = False
             render = False
-        
+
         self.forceCheck = True
-        
+
         # add text and icons for each layer ltype
         if ltype == 'command':
             self.SetItemImage(layer, self._icon['cmd'])
         elif ltype == 'group':
             self.SetItemImage(layer, self.folder, CT.TreeItemIcon_Normal)
-            self.SetItemImage(layer, self.folder_open, CT.TreeItemIcon_Expanded)
+            self.SetItemImage(
+                layer,
+                self.folder_open,
+                CT.TreeItemIcon_Expanded)
             self.SetItemText(layer, grouptext)
         else:
             if ltype in self._icon:
                 self.SetItemImage(layer, self._icon[ltype])
                 # do not use title() - will not work with ltype == 'raster_3d'
-                self.SetItemText(layer, '%s %s' % (LMIcons["layer"+ltype[0].upper()+ltype[1:]].GetLabel(),
-                                                   _('(double click to set properties)') + ' ' * 15))
+                self.SetItemText(
+                    layer,
+                    '%s %s' %
+                    (LMIcons[
+                        "layer" +
+                        ltype[0].upper() +
+                        ltype[
+                            1:]].GetLabel(),
+                        _('(double click to set properties)') +
+                        ' ' *
+                        15))
             else:
                 self.SetItemImage(layer, self._icon['cmd'])
                 self.SetItemText(layer, ltype)
@@ -1143,68 +1403,75 @@
                 if ltype == 'command' and lname:
                     for c in lname.split(';'):
                         cmd.append(c.split(' '))
-                
+
                 name = None
-            
+
             if ctrl:
                 ctrlId = ctrl.GetId()
             else:
                 ctrlId = None
-            
+
             # add a data object to hold the layer's command (does not
             # apply to generic command layers)
-            self.SetPyData(layer, ({'cmd'      : cmd,
-                                    'type'     : ltype,
-                                    'ctrl'     : ctrlId,
-                                    'label'    : None,
-                                    'maplayer' : None,
-                                    'vdigit'   : lvdigit,
-                                    'nviz'     : lnviz,
-                                    'propwin'  : None}, 
+            self.SetPyData(layer, ({'cmd': cmd,
+                                    'type': ltype,
+                                    'ctrl': ctrlId,
+                                    'label': None,
+                                    'maplayer': None,
+                                    'vdigit': lvdigit,
+                                    'nviz': lnviz,
+                                    'propwin': None},
                                    None))
-            
+
             # must be after SetPyData because it calls OnLayerChecked
             # which calls GetVisibleLayers which requires already set PyData
             self.CheckItem(layer, checked=checked)
-            
-            # find previous map layer instance 
+
+            # find previous map layer instance
             prevItem = self.GetFirstChild(self.root)[0]
-            prevMapLayer = None 
+            prevMapLayer = None
             pos = -1
-            while prevItem and prevItem.IsOk() and prevItem != layer: 
-                if self.GetLayerInfo(prevItem, key = 'maplayer'): 
-                    prevMapLayer = self.GetLayerInfo(prevItem, key = 'maplayer')
-                
-                prevItem = self.GetNextItem(prevItem) 
-                
-                if prevMapLayer: 
+            while prevItem and prevItem.IsOk() and prevItem != layer:
+                if self.GetLayerInfo(prevItem, key='maplayer'):
+                    prevMapLayer = self.GetLayerInfo(prevItem, key='maplayer')
+
+                prevItem = self.GetNextItem(prevItem)
+
+                if prevMapLayer:
                     pos = self.Map.GetLayerIndex(prevMapLayer)
-                else: 
+                else:
                     pos = -1
-            
-            maplayer = self.Map.AddLayer(pos = pos,
-                                         ltype = ltype, command = self.GetLayerInfo(prevItem, key = 'cmd'), name = name,
-                                         active = checked, hidden = False,
-                                         opacity = lopacity, render = render)
-            self.SetLayerInfo(layer, key = 'maplayer', value = maplayer)
-            
+
+            maplayer = self.Map.AddLayer(
+                pos=pos,
+                ltype=ltype,
+                command=self.GetLayerInfo(
+                    prevItem,
+                    key='cmd'),
+                name=name,
+                active=checked,
+                hidden=False,
+                opacity=lopacity,
+                render=render)
+            self.SetLayerInfo(layer, key='maplayer', value=maplayer)
+
             # run properties dialog if no properties given
             if len(cmd) == 0:
-                self.PropertiesDialog(layer, show = True)
+                self.PropertiesDialog(layer, show=True)
             else:
                 self.first = False
-        else: # group
-            self.SetPyData(layer, ({'cmd'      : None,
-                                    'type'     : ltype,
-                                    'ctrl'     : None,
-                                    'label'    : None,
-                                    'maplayer' : None,
-                                    'propwin'  : None}, 
+        else:  # group
+            self.SetPyData(layer, ({'cmd': None,
+                                    'type': ltype,
+                                    'ctrl': None,
+                                    'label': None,
+                                    'maplayer': None,
+                                    'propwin': None},
                                    None))
-        
+
         # select new item
         if lchecked != False:
-            self.SelectItem(layer, select = True)
+            self.SelectItem(layer, select=True)
 
         # use predefined layer name if given
         if lname:
@@ -1220,43 +1487,44 @@
 
         return layer
 
-    def PropertiesDialog(self, layer, show = True):
+    def PropertiesDialog(self, layer, show=True):
         """Launch the properties dialog"""
-        ltype  = self.GetLayerInfo(layer, key = 'type')
+        ltype = self.GetLayerInfo(layer, key='type')
         if 'propwin' in self.GetLayerInfo(layer) and \
-                self.GetLayerInfo(layer, key = 'propwin') is not None:
+                self.GetLayerInfo(layer, key='propwin') is not None:
             # recycle GUI dialogs
-            win = self.GetLayerInfo(layer, key = 'propwin')
+            win = self.GetLayerInfo(layer, key='propwin')
             if win.IsShown():
                 win.SetFocus()
             else:
                 win.Show()
             return
-        
+
         params = self.GetLayerParams(layer)
-                
-        Debug.msg (3, "LayerTree.PropertiesDialog(): ltype=%s" % \
-                   ltype)
-        
+
+        Debug.msg(3, "LayerTree.PropertiesDialog(): ltype=%s" %
+                  ltype)
+
         cmd = None
-        if self.GetLayerInfo(layer, key = 'cmd'):
-            module = GUI(parent = self, show = show, centreOnParent = False)
-            module.ParseCommand(self.GetLayerInfo(layer, key = 'cmd'),
-                                completed = (self.GetOptData, layer, params))
-            self.SetLayerInfo(layer, key = 'cmd', value = module.GetCmd())
-        elif self.GetLayerInfo(layer, key = 'type') != 'command':
+        if self.GetLayerInfo(layer, key='cmd'):
+            module = GUI(parent=self, show=show, centreOnParent=False)
+            module.ParseCommand(self.GetLayerInfo(layer, key='cmd'),
+                                completed=(self.GetOptData, layer, params))
+            self.SetLayerInfo(layer, key='cmd', value=module.GetCmd())
+        elif self.GetLayerInfo(layer, key='type') != 'command':
             cmd = [ltype2command[ltype]]
             if ltype in ('raster', 'rgb'):
-                if UserSettings.Get(group = 'rasterLayer', key = 'opaque', subkey = 'enabled'):
+                if UserSettings.Get(group='rasterLayer',
+                                    key='opaque', subkey='enabled'):
                     cmd.append('-n')
             elif ltype == 'vector':
                 cmd += GetDisplayVectSettings()
-        
+
         if cmd:
-            module = GUI(parent = self, centreOnParent = False)
+            module = GUI(parent=self, centreOnParent=False)
             module.ParseCommand(cmd,
-                                completed = (self.GetOptData,layer,params))
-            
+                                completed=(self.GetOptData, layer, params))
+
     def OnActivateLayer(self, event):
         """Double click on the layer item.
         Launch property dialog, or expand/collapse group of items, etc.
@@ -1272,21 +1540,20 @@
             return
 
         self.PropertiesDialog(layer)
-        
-        
+
     def OnDeleteLayer(self, event):
         """Remove selected layer item from the layer tree"""
         self.lmgr.WorkspaceChanged()
         item = event.GetItem()
-        
+
         try:
             item.properties.Close(True)
         except:
             pass
 
         if item != self.root:
-            Debug.msg (3, "LayerTree.OnDeleteLayer(): name=%s" % \
-                           (self.GetItemText(item)))
+            Debug.msg(3, "LayerTree.OnDeleteLayer(): name=%s" %
+                      (self.GetItemText(item)))
         else:
             self.root = None
 
@@ -1294,8 +1561,8 @@
         self.Unselect()
 
         try:
-            if self.GetLayerInfo(item, key = 'type') != 'group':
-                self.Map.DeleteLayer(self.GetLayerInfo(item, key = 'maplayer'))
+            if self.GetLayerInfo(item, key='type') != 'group':
+                self.Map.DeleteLayer(self.GetLayerInfo(item, key='maplayer'))
         except:
             pass
 
@@ -1303,11 +1570,12 @@
         self.rerender = True
         nlayers = self.GetVisibleLayers()
         if not nlayers:
-            self.first = True # layer tree is empty
+            self.first = True  # layer tree is empty
         self.Map.SetLayers(nlayers)
-        
+
         if self.mapdisplay.GetToolbar('vdigit'):
-            self.mapdisplay.toolbars['vdigit'].UpdateListOfLayers (updateTool = True)
+            self.mapdisplay.toolbars[
+                'vdigit'].UpdateListOfLayers(updateTool=True)
 
         # here was some dead code related to layer and nviz
         # however, in condition was rerender = False
@@ -1331,42 +1599,45 @@
     def OnLayerChecked(self, event):
         """Enable/disable data layer"""
         self.lmgr.WorkspaceChanged()
-        
-        item    = event.GetItem()
+
+        item = event.GetItem()
         checked = item.IsChecked()
-        
+
         digitToolbar = self.mapdisplay.GetToolbar('vdigit')
         if not self.first:
             # change active parameter for item in layers list in render.Map
-            if self.GetLayerInfo(item, key = 'type') == 'group':
+            if self.GetLayerInfo(item, key='type') == 'group':
                 child, cookie = self.GetFirstChild(item)
                 while child:
                     self.forceCheck = True
                     self.CheckItem(child, checked)
-                    mapLayer = self.GetLayerInfo(child, key = 'maplayer')
-                    if not digitToolbar or \
-                           (digitToolbar and digitToolbar.GetLayer() != mapLayer):
+                    mapLayer = self.GetLayerInfo(child, key='maplayer')
+                    if not digitToolbar or(
+                            digitToolbar
+                            and digitToolbar.GetLayer() !=
+                            mapLayer):
                         # ignore when map layer is edited
                         self.Map.ChangeLayerActive(mapLayer, checked)
                     child = self.GetNextSibling(child)
             else:
-                mapLayer = self.GetLayerInfo(item, key = 'maplayer')
-                if mapLayer and (not digitToolbar or \
-                       (digitToolbar and digitToolbar.GetLayer() != mapLayer)):
+                mapLayer = self.GetLayerInfo(item, key='maplayer')
+                if mapLayer and (not digitToolbar or (
+                        digitToolbar and digitToolbar.GetLayer() != mapLayer)):
                     # ignore when map layer is edited
                     self.Map.ChangeLayerActive(mapLayer, checked)
-        
+
         # nviz
         if self.mapdisplay.IsPaneShown('3d') and \
                 self.GetPyData(item) is not None:
             # nviz - load/unload data layer
-            mapLayer = self.GetLayerInfo(item, key = 'maplayer')
+            mapLayer = self.GetLayerInfo(item, key='maplayer')
             if mapLayer is None:
                 return
 
-            self.mapdisplay.SetStatusText(_("Please wait, updating data..."), 0)
+            self.mapdisplay.SetStatusText(
+                _("Please wait, updating data..."), 0)
 
-            if checked: # enable
+            if checked:  # enable
                 if mapLayer.type == 'raster':
                     self.mapdisplay.MapWindow.LoadRaster(item)
                 elif mapLayer.type == 'raster_3d':
@@ -1374,20 +1645,21 @@
                 elif mapLayer.type == 'vector':
                     vInfo = gvector.vector_info_topo(mapLayer.GetName())
                     if (vInfo['points'] + vInfo['centroids']) > 0:
-                        self.mapdisplay.MapWindow.LoadVector(item, points = True)
+                        self.mapdisplay.MapWindow.LoadVector(item, points=True)
                     if (vInfo['lines'] + vInfo['boundaries']) > 0:
-                        self.mapdisplay.MapWindow.LoadVector(item, points = False)
+                        self.mapdisplay.MapWindow.LoadVector(
+                            item, points=False)
 
-            else: # disable
+            else:  # disable
                 if mapLayer.type == 'raster':
                     self.mapdisplay.MapWindow.UnloadRaster(item)
                 elif mapLayer.type == 'raster_3d':
                     self.mapdisplay.MapWindow.UnloadRaster3d(item)
                 elif mapLayer.type == 'vector':
                     self.mapdisplay.MapWindow.UnloadVector(item)
-            
+
             self.mapdisplay.SetStatusText("", 0)
-        
+
         # redraw map if auto-rendering is enabled
         self.rerender = True
         self.Map.SetLayers(self.GetVisibleLayers())
@@ -1400,17 +1672,17 @@
     def OnCmdChanged(self, event):
         """Change command string"""
         ctrl = event.GetEventObject().GetId()
-        
+
         # find layer tree item by ctrl
         layer = self.GetFirstChild(self.root)[0]
         while layer and layer.IsOk():
-            if self.GetLayerInfo(layer, key = 'ctrl') == ctrl:
+            if self.GetLayerInfo(layer, key='ctrl') == ctrl:
                 break
             layer = self.GetNextItem(layer)
-        
+
         # change parameters for item in layers list in render.Map
         self.ChangeLayer(layer)
-        
+
         event.Skip()
 
     def OnMotion(self, event):
@@ -1422,12 +1694,13 @@
         # workaround: in order not to check checkox when clicking outside
         # we need flag TREE_HITTEST_ONITEMCHECKICON but not TREE_HITTEST_ONITEMLABEL
         # this applies only for TR_FULL_ROW_HIGHLIGHT style
-        if (flags & CT.TREE_HITTEST_ONITEMCHECKICON) and not (flags & CT.TREE_HITTEST_ONITEMLABEL):
+        if (flags & CT.TREE_HITTEST_ONITEMCHECKICON) and not (
+                flags & CT.TREE_HITTEST_ONITEMLABEL):
             self.hitCheckbox = True
         else:
             self.hitCheckbox = False
         event.Skip()
-        
+
     def OnChangingSel(self, event):
         """Selection is changing.
 
@@ -1451,10 +1724,13 @@
         layer = event.GetItem()
         digitToolbar = self.mapdisplay.GetToolbar('vdigit')
         if digitToolbar:
-            mapLayer = self.GetLayerInfo(layer, key = 'maplayer')
-            bgmap = UserSettings.Get(group = 'vdigit', key = 'bgmap', subkey = 'value',
-                                     settings_type='internal')
-            
+            mapLayer = self.GetLayerInfo(layer, key='maplayer')
+            bgmap = UserSettings.Get(
+                group='vdigit',
+                key='bgmap',
+                subkey='value',
+                settings_type='internal')
+
             if digitToolbar.GetLayer() == mapLayer:
                 self._setGradient('vdigit')
             elif bgmap == mapLayer.GetName():
@@ -1465,28 +1741,29 @@
             self._setGradient()
 
         self.RefreshLine(layer)
-        
+
         # update statusbar -> show command string
-        if self.GetLayerInfo(layer, key = 'maplayer'):
-            cmd = self.GetLayerInfo(layer, key = 'maplayer').GetCmd(string = True)
+        if self.GetLayerInfo(layer, key='maplayer'):
+            cmd = self.GetLayerInfo(layer, key='maplayer').GetCmd(string=True)
             if len(cmd) > 0:
                 self.lmgr.SetStatusText(cmd)
-        
+
         # set region if auto-zooming is enabled
-        if self.GetLayerInfo(layer, key = 'cmd') and \
-               UserSettings.Get(group = 'display', key = 'autoZooming', subkey = 'enabled'):
-            mapLayer = self.GetLayerInfo(layer, key = 'maplayer')
+        if self.GetLayerInfo(layer, key='cmd') and UserSettings.Get(
+                group='display', key='autoZooming', subkey='enabled'):
+            mapLayer = self.GetLayerInfo(layer, key='maplayer')
             if mapLayer.GetType() in ('raster', 'vector'):
                 render = self.mapdisplay.IsAutoRendered()
-                self.mapdisplay.MapWindow.ZoomToMap(layers = [mapLayer,],
-                                                    render = render)
-        
+                self.mapdisplay.MapWindow.ZoomToMap(layers=[mapLayer, ],
+                                                    render=render)
+
         # update nviz tools
         if self.mapdisplay.IsPaneShown('3d'):
             if self.layer_selected.IsChecked():
                 # update Nviz tool window
-                type = self.GetLayerInfo(self.layer_selected, key = 'maplayer').type
-                
+                type = self.GetLayerInfo(
+                    self.layer_selected, key='maplayer').type
+
                 if type == 'raster':
                     self.lmgr.nviz.UpdatePage('surface')
                     self.lmgr.nviz.SetPage('surface')
@@ -1510,12 +1787,12 @@
             self.mapdisplay.MapWindow.UnloadDataLayers(True)
         if self.IsValidDropTarget(dropTarget):
             self.UnselectAll()
-            if dropTarget != None:
+            if dropTarget is not None:
                 self.SelectItem(dropTarget)
             self.OnDrop(dropTarget, self._dragItem)
-        elif dropTarget == None:
+        elif dropTarget is None:
             self.OnDrop(dropTarget, self._dragItem)
-            
+
     def OnDrop(self, dropTarget, dragItem):
         # save everthing associated with item to drag
         try:
@@ -1523,69 +1800,76 @@
         except:
             return
 
-        Debug.msg (4, "LayerTree.OnDrop(): layer=%s" % \
-                   (self.GetItemText(dragItem)))
-        
-        # recreate data layer, insert copy of layer in new position, and delete original at old position
-        newItem  = self.RecreateItem (dragItem, dropTarget)
+        Debug.msg(4, "LayerTree.OnDrop(): layer=%s" %
+                  (self.GetItemText(dragItem)))
 
+        # recreate data layer, insert copy of layer in new position, and delete
+        # original at old position
+        newItem = self.RecreateItem(dragItem, dropTarget)
+
         # if recreated layer is a group, also recreate its children
-        if  self.GetLayerInfo(newItem, key = 'type') == 'group':
+        if self.GetLayerInfo(newItem, key='type') == 'group':
             (child, cookie) = self.GetFirstChild(dragItem)
             if child:
                 while child:
-                    self.RecreateItem(child, dropTarget, parent = newItem)
+                    self.RecreateItem(child, dropTarget, parent=newItem)
                     child, cookie = self.GetNextChild(old, cookie)
-        
+
         # delete layer at original position
         try:
-            self.Delete(old) # entry in render.Map layers list automatically deleted by OnDeleteLayer handler
+            # entry in render.Map layers list automatically deleted by
+            # OnDeleteLayer handler
+            self.Delete(old)
         except AttributeError:
             pass
 
         # redraw map if auto-rendering is enabled
         self.rerender = True
         self.Map.SetLayers(self.GetVisibleLayers())
-        
+
         # select new item
         self.SelectItem(newItem)
-        
-    def RecreateItem (self, dragItem, dropTarget, parent = None):
+
+    def RecreateItem(self, dragItem, dropTarget, parent=None):
         """Recreate item (needed for OnEndDrag())
         """
-        Debug.msg (4, "LayerTree.RecreateItem(): layer=%s" % \
-                   self.GetItemText(dragItem))
+        Debug.msg(4, "LayerTree.RecreateItem(): layer=%s" %
+                  self.GetItemText(dragItem))
 
         # fetch data (dragItem)
         checked = self.IsItemChecked(dragItem)
-        image   = self.GetItemImage(dragItem, 0)
-        text    = self.GetItemText(dragItem)
-        if self.GetLayerInfo(dragItem, key = 'type') == 'command':
+        image = self.GetItemImage(dragItem, 0)
+        text = self.GetItemText(dragItem)
+        if self.GetLayerInfo(dragItem, key='type') == 'command':
             # recreate command layer
             newctrl = self._createCommandCtrl()
             try:
-                newctrl.SetValue(self.GetLayerInfo(dragItem, key = 'maplayer').GetCmd(string = True))
+                newctrl.SetValue(
+                    self.GetLayerInfo(
+                        dragItem,
+                        key='maplayer').GetCmd(
+                        string=True))
             except:
                 pass
             newctrl.Bind(wx.EVT_TEXT_ENTER, self.OnCmdChanged)
             data = self.GetPyData(dragItem)
 
-        elif self.GetLayerInfo(dragItem, key = 'ctrl'):
+        elif self.GetLayerInfo(dragItem, key='ctrl'):
             # recreate data layer
-            btnbmp = LMIcons["layerOptions"].GetBitmap((16,16))
-            newctrl = buttons.GenBitmapButton(self, id = wx.ID_ANY, bitmap = btnbmp, size = (24, 24))
+            btnbmp = LMIcons["layerOptions"].GetBitmap((16, 16))
+            newctrl = buttons.GenBitmapButton(
+                self, id=wx.ID_ANY, bitmap=btnbmp, size=(24, 24))
             newctrl.SetToolTipString(_("Click to edit layer settings"))
             self.Bind(wx.EVT_BUTTON, self.OnLayerContextMenu, newctrl)
             data = self.GetPyData(dragItem)
-        
 
-        elif self.GetLayerInfo(dragItem, key = 'type') == 'group':
+        elif self.GetLayerInfo(dragItem, key='type') == 'group':
             # recreate group
             newctrl = None
-            data    = None
-            
+            data = None
+
         # decide where to put recreated item
-        if dropTarget != None and dropTarget != self.GetRootItem():
+        if dropTarget is not None and dropTarget != self.GetRootItem():
             if parent:
                 # new item is a group
                 afteritem = parent
@@ -1594,92 +1878,98 @@
                 afteritem = dropTarget
 
             # dragItem dropped on group
-            if  self.GetLayerInfo(afteritem, key = 'type') == 'group':
-                newItem = self.PrependItem(afteritem, text = text, \
-                                      ct_type = 1, wnd = newctrl, image = image, \
-                                      data = data)
+            if self.GetLayerInfo(afteritem, key='type') == 'group':
+                newItem = self.PrependItem(afteritem, text=text,
+                                           ct_type=1, wnd=newctrl, image=image,
+                                           data=data)
                 self.Expand(afteritem)
             else:
-                #dragItem dropped on single layer
+                # dragItem dropped on single layer
                 newparent = self.GetItemParent(afteritem)
-                newItem = self.InsertItem(newparent, self.GetPrevSibling(afteritem), \
-                                       text = text, ct_type = 1, wnd = newctrl, \
-                                       image = image, data = data)
+                newItem = self.InsertItem(
+                    newparent,
+                    self.GetPrevSibling(afteritem),
+                    text=text,
+                    ct_type=1,
+                    wnd=newctrl,
+                    image=image,
+                    data=data)
         else:
-            # if dragItem not dropped on a layer or group, append or prepend it to the layer tree
+            # if dragItem not dropped on a layer or group, append or prepend it
+            # to the layer tree
             if self.flag & wx.TREE_HITTEST_ABOVE:
-                newItem = self.PrependItem(self.root, text = text, \
-                                      ct_type = 1, wnd = newctrl, image = image, \
-                                      data = data)
+                newItem = self.PrependItem(self.root, text=text,
+                                           ct_type=1, wnd=newctrl, image=image,
+                                           data=data)
             elif (self.flag &  wx.TREE_HITTEST_BELOW) or (self.flag & wx.TREE_HITTEST_NOWHERE) \
-                     or (self.flag & wx.TREE_HITTEST_TOLEFT) or (self.flag & wx.TREE_HITTEST_TORIGHT):
-                newItem = self.AppendItem(self.root, text = text, \
-                                      ct_type = 1, wnd = newctrl, image = image, \
-                                      data = data)
+                    or (self.flag & wx.TREE_HITTEST_TOLEFT) or (self.flag & wx.TREE_HITTEST_TORIGHT):
+                newItem = self.AppendItem(self.root, text=text,
+                                          ct_type=1, wnd=newctrl, image=image,
+                                          data=data)
 
-        #update new layer 
+        # update new layer
         self.SetPyData(newItem, self.GetPyData(dragItem))
         if newctrl:
-            self.SetLayerInfo(newItem, key = 'ctrl', value = newctrl.GetId())
+            self.SetLayerInfo(newItem, key='ctrl', value=newctrl.GetId())
         else:
-            self.SetLayerInfo(newItem, key = 'ctrl', value = None)
-            
+            self.SetLayerInfo(newItem, key='ctrl', value=None)
+
         self.forceCheck = True
-        self.CheckItem(newItem, checked = checked) # causes a new render
-        
+        self.CheckItem(newItem, checked=checked)  # causes a new render
+
         return newItem
 
-    def _getLayerName(self, item, lname = ''):
+    def _getLayerName(self, item, lname=''):
         """Get layer name string
 
         :param lname: optional layer name
         """
-        mapLayer = self.GetLayerInfo(item, key = 'maplayer')
+        mapLayer = self.GetLayerInfo(item, key='maplayer')
         if not mapLayer:
             return lname
-        
+
         if not lname:
-            lname  = self.GetLayerInfo(item, key = 'label')
-        opacity  = int(mapLayer.GetOpacity() * 100)
+            lname = self.GetLayerInfo(item, key='label')
+        opacity = int(mapLayer.GetOpacity() * 100)
         if not lname:
-            dcmd    = self.GetLayerInfo(item, key = 'cmd')
-            lname, found = GetLayerNameFromCmd(dcmd, layerType = mapLayer.GetType(),
-                                               fullyQualified = True)
+            dcmd = self.GetLayerInfo(item, key='cmd')
+            lname, found = GetLayerNameFromCmd(
+                dcmd, layerType=mapLayer.GetType(), fullyQualified=True)
             if not found:
                 return None
-        
+
         if opacity < 100:
             return lname + ' (%s %d' % (_('opacity:'), opacity) + '%)'
-        
+
         return lname
-                
+
     def GetOptData(self, dcmd, layer, params, propwin):
         """Process layer data (when changes in properties dialog are applied)
         """
         # set layer text to map name
         if dcmd:
-            self.SetLayerInfo(layer, key = 'cmd', value = dcmd)
-            mapText  = self._getLayerName(layer)
+            self.SetLayerInfo(layer, key='cmd', value=dcmd)
+            mapText = self._getLayerName(layer)
             mapName, found = GetLayerNameFromCmd(dcmd)
-            mapLayer = self.GetLayerInfo(layer, key = 'maplayer')
+            mapLayer = self.GetLayerInfo(layer, key='maplayer')
             self.SetItemText(layer, mapName)
-            
+
             if not mapText or not found:
                 propwin.Hide()
-                GWarning(parent = self,
-                         message = _("Map <%s> not found.") % mapName)
+                GWarning(parent=self,
+                         message=_("Map <%s> not found.") % mapName)
                 return
 
             if not mapLayer.IsActive():
                 self.forceCheck = True
                 self.CheckItem(layer, True)
                 mapLayer.SetActive(True)
-                
+
         # update layer data
         if params:
             self.SetPyData(layer, (self.GetLayerInfo(layer), params))
-        self.SetLayerInfo(layer, key = 'propwin', value = propwin)
-        
+        self.SetLayerInfo(layer, key='propwin', value=propwin)
+
         # change parameters for item in layers list in render.Map
         if params:
             self.ChangeLayer(layer)
@@ -1687,46 +1977,51 @@
         # set region if auto-zooming is enabled or layer tree contains
         # only one map layer
         if dcmd:
-            if not self.mapdisplay.IsPaneShown('3d') and \
-               (self.first or \
-                UserSettings.Get(group = 'display', key = 'autoZooming', subkey = 'enabled')):
-                mapLayer = self.GetLayerInfo(layer, key = 'maplayer')
+            if not self.mapdisplay.IsPaneShown('3d') and(
+                self.first or UserSettings.Get(
+                    group='display', key='autoZooming', subkey='enabled')):
+                mapLayer = self.GetLayerInfo(layer, key='maplayer')
                 if mapLayer.GetType() in ('raster', 'vector'):
-                    self.mapdisplay.MapWindow.ZoomToMap(layers = [mapLayer,],
-                                                        render = False)
-                    
-            self.first = False # first layer has been already added to
-                               # the layer tree
-        
-        # update nviz session        
+                    self.mapdisplay.MapWindow.ZoomToMap(layers=[mapLayer, ],
+                                                        render=False)
+
+            self.first = False  # first layer has been already added to
+            # the layer tree
+
+        # update nviz session
         if self.mapdisplay.IsPaneShown('3d') and dcmd:
-            mapLayer = self.GetLayerInfo(layer, key = 'maplayer')
+            mapLayer = self.GetLayerInfo(layer, key='maplayer')
             mapWin = self.mapdisplay.MapWindow
             if len(mapLayer.GetCmd()) > 0:
                 if mapLayer.type == 'raster':
                     if mapWin.IsLoaded(layer):
                         mapWin.UnloadRaster(layer)
-                    
+
                     mapWin.LoadRaster(layer)
-                    
+
                 elif mapLayer.type == 'raster_3d':
                     if mapWin.IsLoaded(layer):
                         mapWin.UnloadRaster3d(layer)
-                    
+
                     mapWin.LoadRaster3d(layer)
-                    
+
                 elif mapLayer.type == 'vector':
                     if mapWin.IsLoaded(layer):
                         mapWin.UnloadVector(layer)
-                    
+
                     mapWin.LoadVector(layer)
 
                 # reset view when first layer loaded
-                nlayers = len(mapWin.Map.GetListOfLayers(ltype = ('raster', 'raster_3d', 'vector'),
-                                                         active = True))
+                nlayers = len(
+                    mapWin.Map.GetListOfLayers(
+                        ltype=(
+                            'raster',
+                            'raster_3d',
+                            'vector'),
+                        active=True))
                 if nlayers < 2:
                     mapWin.ResetView()
-        
+
     def GetVisibleLayers(self, skipDigitized=False):
         # make a list of visible layers
         layers = []
@@ -1762,12 +2057,12 @@
 
     def ChangeLayer(self, item):
         """Change layer"""
-        type = self.GetLayerInfo(item, key = 'type')
+        type = self.GetLayerInfo(item, key='type')
         layerName = None
-        
+
         if type == 'command':
-            win = self.FindWindowById(self.GetLayerInfo(item, key = 'ctrl'))
-            if win.GetValue() != None:
+            win = self.FindWindowById(self.GetLayerInfo(item, key='ctrl'))
+            if win.GetValue() is not None:
                 cmd = win.GetValue().split(';')
                 cmdlist = []
                 for c in cmd:
@@ -1777,27 +2072,37 @@
                 hidden = not self.IsVisible(item)
         elif type != 'group':
             if self.GetPyData(item) is not None:
-                cmdlist = self.GetLayerInfo(item, key = 'cmd')
-                opac = self.GetLayerInfo(item, key = 'maplayer').GetOpacity()
+                cmdlist = self.GetLayerInfo(item, key='cmd')
+                opac = self.GetLayerInfo(item, key='maplayer').GetOpacity()
                 chk = self.IsItemChecked(item)
                 hidden = not self.IsVisible(item)
                 # determine layer name
-                layerName, found = GetLayerNameFromCmd(cmdlist, fullyQualified = True)
+                layerName, found = GetLayerNameFromCmd(
+                    cmdlist, fullyQualified=True)
                 if not found:
                     layerName = self.GetItemText(item)
 
-        maplayer = self.Map.ChangeLayer(layer = self.GetLayerInfo(item, key = 'maplayer'),
-                                        type = type, command = cmdlist, name = layerName,
-                                        active = chk, hidden = hidden, opacity = opac)
-        
-        self.SetLayerInfo(item, key = 'maplayer', value = maplayer)
-        
-        # if digitization tool enabled -> update list of available vector map layers
+        maplayer = self.Map.ChangeLayer(
+            layer=self.GetLayerInfo(
+                item,
+                key='maplayer'),
+            type=type,
+            command=cmdlist,
+            name=layerName,
+            active=chk,
+            hidden=hidden,
+            opacity=opac)
+
+        self.SetLayerInfo(item, key='maplayer', value=maplayer)
+
+        # if digitization tool enabled -> update list of available vector map
+        # layers
         if self.mapdisplay.GetToolbar('vdigit'):
-            self.mapdisplay.GetToolbar('vdigit').UpdateListOfLayers(updateTool = True)
-        
+            self.mapdisplay.GetToolbar(
+                'vdigit').UpdateListOfLayers(updateTool=True)
+
         self.Map.SetLayers(self.GetVisibleLayers())
-        
+
         # redraw map if auto-rendering is enabled
         self.rerender = True
 
@@ -1807,9 +2112,9 @@
 
     def FindItemByData(self, key, value):
         """Find item based on key and value (see PyData[0]).
-        
+
         If key is 'name', finds item(s) of given maplayer name.
-        
+
         :return: item instance
         :return: None not found
         """
@@ -1830,30 +2135,30 @@
         while item and item.IsOk():
             if i == index:
                 return item
-            
+
             item = self.GetNextItem(item)
             i += 1
-        
+
         return None
-    
-    def EnableItemType(self, type, enable = True):
+
+    def EnableItemType(self, type, enable=True):
         """Enable/disable items in layer tree"""
         item = self.GetFirstChild(self.root)[0]
         while item and item.IsOk():
-            mapLayer = self.GetLayerInfo(item, key = 'maplayer')
+            mapLayer = self.GetLayerInfo(item, key='maplayer')
             if mapLayer and type == mapLayer.type:
                 self.EnableItem(item, enable)
-            
+
             item = self.GetNextSibling(item)
-        
+
     def __FindSubItemByData(self, item, key, value):
         """Support method for FindItemByData"""
         while item and item.IsOk():
-            itemValue = self.GetLayerInfo(item, key = key)
-            
+            itemValue = self.GetLayerInfo(item, key=key)
+
             if value == itemValue:
                 return item
-            if self.GetLayerInfo(item, key = 'type') == 'group':
+            if self.GetLayerInfo(item, key='type') == 'group':
                 subItem = self.GetFirstChild(item)[0]
                 found = self.__FindSubItemByData(subItem, key, value)
                 if found:
@@ -1867,19 +2172,19 @@
         items = []
         while item and item.IsOk():
             try:
-                itemLayer = self.GetLayerInfo(item, key = 'maplayer')
+                itemLayer = self.GetLayerInfo(item, key='maplayer')
             except KeyError:
                 return None
-            
+
             if itemLayer and value == itemLayer.GetName():
                 items.append(item)
-            if self.GetLayerInfo(item, key = 'type') == 'group':
+            if self.GetLayerInfo(item, key='type') == 'group':
                 subItem = self.GetFirstChild(item)[0]
                 found = self.__FindSubItemByName(subItem, value)
                 if found:
                     items.extend(found)
             item = self.GetNextSibling(item)
-        
+
         if items:
             return items
         return None
@@ -1889,7 +2194,6 @@
         height = 25
         if sys.platform in ('win32', 'darwin'):
             height = 40
-        ctrl = wx.TextCtrl(self, id = wx.ID_ANY, value = '',
-                               pos = wx.DefaultPosition, size = (self.GetSize()[0]-100, height),
-                               style = wx.TE_PROCESS_ENTER | wx.TE_DONTWRAP)
+        ctrl = wx.TextCtrl(self, id=wx.ID_ANY, value='', pos=wx.DefaultPosition, size=(
+            self.GetSize()[0] - 100, height), style=wx.TE_PROCESS_ENTER | wx.TE_DONTWRAP)
         return ctrl

Modified: grass/trunk/gui/wxpython/lmgr/menudata.py
===================================================================
--- grass/trunk/gui/wxpython/lmgr/menudata.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/lmgr/menudata.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -17,7 +17,7 @@
 
 import os
 
-from core.menutree  import MenuTreeModelBuilder
+from core.menutree import MenuTreeModelBuilder
 from core.toolboxes import getMenudataFile
 from core.globalvar import WXGUIDIR
 from core.gcmd import GError
@@ -25,6 +25,7 @@
 
 
 class LayerManagerMenuData(MenuTreeModelBuilder):
+
     def __init__(self, filename=None):
         if filename:
             expandAddons = False
@@ -37,7 +38,8 @@
                                        newFile='menudata.xml',
                                        fallback=fallback)
         try:
-            MenuTreeModelBuilder.__init__(self, filename, expandAddons=expandAddons)
+            MenuTreeModelBuilder.__init__(
+                self, filename, expandAddons=expandAddons)
         except (ValueError, AttributeError, TypeError):
             GError(_("Unable to parse user toolboxes XML files. "
                      "Default main menu will be loaded."))
@@ -46,6 +48,7 @@
 
 
 class LayerManagerModuleTree(MenuTreeModelBuilder):
+
     def __init__(self, filename=None):
         if filename:
             expandAddons = False
@@ -59,7 +62,8 @@
                                        fallback=fallback)
         # TODO: try-except useless?
         try:
-            MenuTreeModelBuilder.__init__(self, filename, expandAddons=expandAddons)
+            MenuTreeModelBuilder.__init__(
+                self, filename, expandAddons=expandAddons)
         except (ValueError, AttributeError, TypeError):
             GError(_("Unable to parse user toolboxes XML files. "
                      "Default module tree will be loaded."))

Modified: grass/trunk/gui/wxpython/lmgr/pyshell.py
===================================================================
--- grass/trunk/gui/wxpython/lmgr/pyshell.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/lmgr/pyshell.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -21,7 +21,7 @@
 import sys
 
 import wx
-from wx.py.shell   import Shell as PyShell
+from wx.py.shell import Shell as PyShell
 from wx.py.version import VERSION
 
 import grass.script as grass
@@ -29,62 +29,66 @@
 
 from core.utils import _
 
+
 class PyShellWindow(wx.Panel):
     """Python Shell Window"""
-    def __init__(self, parent, giface, id = wx.ID_ANY, **kwargs):
+
+    def __init__(self, parent, giface, id=wx.ID_ANY, **kwargs):
         self.parent = parent
         self.giface = giface
-        
-        wx.Panel.__init__(self, parent = parent, id = id, **kwargs)
-        
+
+        wx.Panel.__init__(self, parent=parent, id=id, **kwargs)
+
         self.intro = _("Welcome to wxGUI Interactive Python Shell %s") % VERSION + "\n\n" + \
             _("Type %s for more GRASS scripting related information.") % "\"help(grass)\"" + "\n" + \
             _("Type %s to add raster or vector to the layer tree.") % "\"AddLayer()\"" + "\n\n"
-        self.shell = PyShell(parent = self, id = wx.ID_ANY,
-                             introText = self.intro,
+        self.shell = PyShell(parent=self, id=wx.ID_ANY,
+                             introText=self.intro,
                              locals={'grass': grass,
                                      'AddLayer': self.AddLayer})
-        
+
         sys.displayhook = self._displayhook
-        
+
         self.btnClear = wx.Button(self, wx.ID_CLEAR)
         self.btnClear.Bind(wx.EVT_BUTTON, self.OnClear)
         self.btnClear.SetToolTipString(_("Delete all text from the shell"))
 
-        self.btnSimpleEditor = wx.Button(self, id=wx.ID_ANY, label=_("Simple &editor"))
+        self.btnSimpleEditor = wx.Button(
+            self, id=wx.ID_ANY, label=_("Simple &editor"))
         self.btnSimpleEditor.Bind(wx.EVT_BUTTON, self.OnSimpleEditor)
-        self.btnSimpleEditor.SetToolTipString(_("Open a simple Python code editor"))
+        self.btnSimpleEditor.SetToolTipString(
+            _("Open a simple Python code editor"))
 
         self._layout()
-        
+
     def _displayhook(self, value):
-        print value # do not modify __builtin__._
-        
+        print value  # do not modify __builtin__._
+
     def _layout(self):
         sizer = wx.BoxSizer(wx.VERTICAL)
-        
-        sizer.Add(item = self.shell, proportion = 1,
-                  flag = wx.EXPAND)
-        
+
+        sizer.Add(item=self.shell, proportion=1,
+                  flag=wx.EXPAND)
+
         btnSizer = wx.BoxSizer(wx.HORIZONTAL)
         btnSizer.Add(item=self.btnSimpleEditor, proportion=0,
                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5)
         btnSizer.AddStretchSpacer()
-        btnSizer.Add(item = self.btnClear, proportion = 0,
-                     flag = wx.EXPAND | wx.ALIGN_RIGHT, border = 5)
-        sizer.Add(item = btnSizer, proportion = 0,
-                  flag = wx.ALIGN_RIGHT | wx.ALL | wx.EXPAND, border = 5)
-        
+        btnSizer.Add(item=self.btnClear, proportion=0,
+                     flag=wx.EXPAND | wx.ALIGN_RIGHT, border=5)
+        sizer.Add(item=btnSizer, proportion=0,
+                  flag=wx.ALIGN_RIGHT | wx.ALL | wx.EXPAND, border=5)
+
         sizer.Fit(self)
         sizer.SetSizeHints(self)
-        
+
         self.SetSizer(sizer)
-        
+
         self.Fit()
-        self.SetAutoLayout(True)        
+        self.SetAutoLayout(True)
         self.Layout()
 
-    def AddLayer(self, name, ltype = 'auto'):
+    def AddLayer(self, name, ltype='auto'):
         """Add selected map to the layer tree
 
         :param name: name of raster/vector map to be added
@@ -93,30 +97,30 @@
         fname = None
         if ltype == 'raster' or ltype != 'vector':
             # check for raster
-            fname = grass.find_file(name, element = 'cell')['fullname']
+            fname = grass.find_file(name, element='cell')['fullname']
             if fname:
                 ltype = 'raster'
                 lcmd = 'd.rast'
-        
+
         if not fname and (ltype == 'vector' or ltype != 'raster'):
             # if not found check for vector
-            fname = grass.find_file(name, element = 'vector')['fullname']
+            fname = grass.find_file(name, element='vector')['fullname']
             if fname:
                 ltype = 'vector'
                 lcmd = 'd.vect'
-        
+
         if not fname:
             return _("Raster or vector map <%s> not found") % (name)
-        
-        self.giface.GetLayerTree().AddLayer(ltype = ltype,
-                                            lname = fname,
-                                            lchecked = True,
-                                            lcmd = [lcmd, 'map=%s' % fname])
+
+        self.giface.GetLayerTree().AddLayer(ltype=ltype,
+                                            lname=fname,
+                                            lchecked=True,
+                                            lcmd=[lcmd, 'map=%s' % fname])
         if ltype == 'raster':
             return _('Raster map <%s> added') % fname
-        
+
         return _('Vector map <%s> added') % fname
-    
+
     def OnClear(self, event):
         """Delete all text from the shell
         """

Modified: grass/trunk/gui/wxpython/lmgr/toolbars.py
===================================================================
--- grass/trunk/gui/wxpython/lmgr/toolbars.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/lmgr/toolbars.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -22,19 +22,21 @@
 @author Anna Kratochvilova <kratochanna gmail.com>
 """
 
-from core.gcmd          import RunCommand
-from gui_core.toolbars  import BaseToolbar, BaseIcons
-from icons.icon         import MetaIcon
+from core.gcmd import RunCommand
+from gui_core.toolbars import BaseToolbar, BaseIcons
+from icons.icon import MetaIcon
 from core.utils import _
 
+
 class LMWorkspaceToolbar(BaseToolbar):
     """Layer Manager `workspace` toolbar
     """
+
     def __init__(self, parent):
         BaseToolbar.__init__(self, parent)
-        
+
         self.InitToolbar(self._toolbarData())
-        
+
         # realize the toolbar
         self.Realize()
 
@@ -42,15 +44,19 @@
         """Toolbar data
         """
         icons = {
-            'newdisplay'    : MetaIcon(img = 'monitor-create',
-                                       label = _('Start new map display')),
-            'workspaceNew'  : MetaIcon(img = 'create',
-                                       label = _('Create new workspace (Ctrl+N)')),
-            'workspaceOpen' : MetaIcon(img = 'open',
-                                       label = _('Open existing workspace file (Ctrl+O)')),
-            'workspaceSave' : MetaIcon(img = 'save',
-                                       label = _('Save current workspace to file (Ctrl+S)')),
-            }
+            'newdisplay': MetaIcon(
+                img='monitor-create',
+                label=_('Start new map display')),
+            'workspaceNew': MetaIcon(
+                img='create',
+                label=_('Create new workspace (Ctrl+N)')),
+            'workspaceOpen': MetaIcon(
+                img='open',
+                label=_('Open existing workspace file (Ctrl+O)')),
+            'workspaceSave': MetaIcon(
+                img='save',
+                label=_('Save current workspace to file (Ctrl+S)')),
+        }
         return self._getToolbarData((('newdisplay', icons["newdisplay"],
                                       self.parent.OnNewDisplay),
                                      ('workspaceNew', icons["workspaceNew"],
@@ -61,14 +67,16 @@
                                       self.parent.OnWorkspaceSave),
                                      ))
 
+
 class LMDataToolbar(BaseToolbar):
     """Layer Manager `data` toolbar
     """
+
     def __init__(self, parent):
         BaseToolbar.__init__(self, parent)
-        
+
         self.InitToolbar(self._toolbarData())
-        
+
         # realize the toolbar
         self.Realize()
 
@@ -76,24 +84,33 @@
         """Toolbar data
         """
         icons = {
-            'addMulti'   : MetaIcon(img = 'layer-open',
-                                    label = _('Add multiple raster or vector map layers (Ctrl+Shift+L)')),
-            'addRast'    : BaseIcons['addRast'].SetLabel(_("Add raster map layer (Ctrl+Shift+R)")),
-            'rastMisc'   : MetaIcon(img = 'layer-raster-more',
-                                    label = _('Add various raster map layers (RGB, HIS, shaded relief...)')),
-            'addVect'    : BaseIcons['addVect'].SetLabel(_("Add vector map layer (Ctrl+Shift+V)")),
-            'vectMisc'   : MetaIcon(img = 'layer-vector-more',
-                                    label = _('Add various vector map layers (thematic, chart...)')),
-            'addWS'       : MetaIcon(img = 'layer-wms-add',
-                                     label = _('Add web service layer (WMS, WMTS, NASA OnEarth)')),
-            'addGroup'   : MetaIcon(img = 'layer-group-add',
-                                    label = _('Add group')),
-            'addOverlay' : MetaIcon(img = 'layer-more',
-                                    label = _('Add various overlays')),
-            'delCmd'     : MetaIcon(img = 'layer-remove',
-                                    label = _('Remove selected map layer(s) from layer tree')),
-            }
-        
+            'addMulti': MetaIcon(
+                img='layer-open',
+                label=_('Add multiple raster or vector map layers (Ctrl+Shift+L)')),
+            'addRast': BaseIcons['addRast'].SetLabel(
+                _("Add raster map layer (Ctrl+Shift+R)")),
+            'rastMisc': MetaIcon(
+                img='layer-raster-more',
+                label=_('Add various raster map layers (RGB, HIS, shaded relief...)')),
+            'addVect': BaseIcons['addVect'].SetLabel(
+                _("Add vector map layer (Ctrl+Shift+V)")),
+            'vectMisc': MetaIcon(
+                img='layer-vector-more',
+                label=_('Add various vector map layers (thematic, chart...)')),
+            'addWS': MetaIcon(
+                img='layer-wms-add',
+                label=_('Add web service layer (WMS, WMTS, NASA OnEarth)')),
+            'addGroup': MetaIcon(
+                img='layer-group-add',
+                label=_('Add group')),
+            'addOverlay': MetaIcon(
+                img='layer-more',
+                label=_('Add various overlays')),
+            'delCmd': MetaIcon(
+                img='layer-remove',
+                label=_('Remove selected map layer(s) from layer tree')),
+        }
+
         return self._getToolbarData((('addMulti', icons["addMulti"],
                                       self.parent.OnAddMaps),
                                      ('addrast', icons["addRast"],
@@ -104,25 +121,27 @@
                                       self.parent.OnAddVector),
                                      ('vectmisc', icons["vectMisc"],
                                       self.parent.OnAddVectorMisc),
-                                     ('addovl',  icons["addOverlay"],
+                                     ('addovl', icons["addOverlay"],
                                       self.parent.OnAddOverlay),
-                                     ('addWS',  icons["addWS"],
+                                     ('addWS', icons["addWS"],
                                       self.parent.OnAddWS),
                                      (None, ),
-                                     ('addgrp',  icons["addGroup"],
+                                     ('addgrp', icons["addGroup"],
                                       self.parent.OnAddGroup),
-                                     ('delcmd',  icons["delCmd"],
+                                     ('delcmd', icons["delCmd"],
                                       self.parent.OnDeleteLayer),
                                      ))
 
+
 class LMToolsToolbar(BaseToolbar):
     """Layer Manager `tools` toolbar
     """
+
     def __init__(self, parent):
         BaseToolbar.__init__(self, parent)
-        
+
         self.InitToolbar(self._toolbarData())
-        
+
         # realize the toolbar
         self.Realize()
 
@@ -130,22 +149,22 @@
         """Toolbar data
         """
         icons = {
-            'import'  : MetaIcon(img = 'layer-import',
-                                 label = _('Import/link raster or vector data')),
-            'mapcalc' : MetaIcon(img = 'raster-calculator',
-                                 label = _('Raster Map Calculator')),
-            'modeler' : MetaIcon(img = 'modeler-main',
-                                 label = _('Graphical Modeler')),
-            'georectify' : MetaIcon(img = 'georectify',
-                                 label = _('Georectifier')),
-            'composer': MetaIcon(img = 'print-compose',
-                                 label = _('Cartographic Composer')),
-            'script-load': MetaIcon(img = 'script-load',
-                                 label = _('Launch user-defined script')),
-            'python': MetaIcon(img = 'python',
-                               label = _('Open a simple Python code editor')),
-            }
-        
+            'import': MetaIcon(img='layer-import',
+                               label=_('Import/link raster or vector data')),
+            'mapcalc': MetaIcon(img='raster-calculator',
+                                label=_('Raster Map Calculator')),
+            'modeler': MetaIcon(img='modeler-main',
+                                label=_('Graphical Modeler')),
+            'georectify': MetaIcon(img='georectify',
+                                   label=_('Georectifier')),
+            'composer': MetaIcon(img='print-compose',
+                                 label=_('Cartographic Composer')),
+            'script-load': MetaIcon(img='script-load',
+                                    label=_('Launch user-defined script')),
+            'python': MetaIcon(img='python',
+                               label=_('Open a simple Python code editor')),
+        }
+
         return self._getToolbarData((('importMap', icons["import"],
                                       self.parent.OnImportMenu),
                                      (None, ),
@@ -164,14 +183,16 @@
                                       self.parent.pyshell.OnSimpleEditor),
                                      ))
 
+
 class LMMiscToolbar(BaseToolbar):
     """Layer Manager `misc` toolbar
     """
+
     def __init__(self, parent):
         BaseToolbar.__init__(self, parent)
-        
+
         self.InitToolbar(self._toolbarData())
-        
+
         # realize the toolbar
         self.Realize()
 
@@ -179,24 +200,26 @@
         """Toolbar data
         """
         icons = {
-            'settings'   : BaseIcons['settings'].SetLabel(_('GUI settings')),
-            'help'       : BaseIcons['help'].SetLabel(_('GRASS manual')),
-            }
-        
+            'settings': BaseIcons['settings'].SetLabel(_('GUI settings')),
+            'help': BaseIcons['help'].SetLabel(_('GRASS manual')),
+        }
+
         return self._getToolbarData((('settings', icons["settings"],
                                       self.parent.OnPreferences),
                                      ('help', icons["help"],
                                       self.parent.OnHelp),
                                      ))
 
+
 class LMVectorToolbar(BaseToolbar):
     """Layer Manager `vector` toolbar
     """
+
     def __init__(self, parent):
         BaseToolbar.__init__(self, parent)
-        
+
         self.InitToolbar(self._toolbarData())
-        
+
         # realize the toolbar
         self.Realize()
 
@@ -204,47 +227,54 @@
         """Toolbar data
         """
         icons = {
-            'vdigit'     : MetaIcon(img = 'edit',
-                                    label = _('Edit selected vector map')),
-            'attrTable'  : MetaIcon(img = 'table',
-                                    label = _('Show attribute data for selected vector map')),
-            }
-        
+            'vdigit': MetaIcon(
+                img='edit',
+                label=_('Edit selected vector map')),
+            'attrTable': MetaIcon(
+                img='table',
+                label=_('Show attribute data for selected vector map')),
+        }
+
         return self._getToolbarData((('vdigit', icons["vdigit"],
                                       self.parent.OnVDigit),
                                      ('attribute', icons["attrTable"],
                                       self.parent.OnShowAttributeTable),
                                      ))
 
+
 class LMNvizToolbar(BaseToolbar):
     """Nviz toolbar
     """
+
     def __init__(self, parent):
         self.lmgr = parent
-        
+
         BaseToolbar.__init__(self, parent)
-        
+
         # only one dialog can be open
-        self.settingsDialog   = None
-        
+        self.settingsDialog = None
+
         self.InitToolbar(self._toolbarData())
-        
+
         # realize the toolbar
         self.Realize()
-        
+
     def _toolbarData(self):
         """Toolbar data"""
         icons = {
-            'cmd'    : MetaIcon(img = 'script-save',
-                                label = _('Generate command for m.nviz.image'),
-                                desc = _('Generate command for m.nviz.image based on current state')),
-            'settings' : MetaIcon(img = '3d-settings',
-                                  label = _('3D view mode settings'),
-                                  desc = _('Show 3D view mode settings dialog')),
-            'help'   : MetaIcon(img = '3d-help',
-                                label = _('Show 3D view mode manual')),
-            }
-        
+            'cmd': MetaIcon(
+                img='script-save',
+                label=_('Generate command for m.nviz.image'),
+                desc=_('Generate command for m.nviz.image based on current state')),
+            'settings': MetaIcon(
+                img='3d-settings',
+                label=_('3D view mode settings'),
+                desc=_('Show 3D view mode settings dialog')),
+            'help': MetaIcon(
+                img='3d-help',
+                label=_('Show 3D view mode manual')),
+        }
+
         return self._getToolbarData((("nvizCmd", icons['cmd'],
                                       self.OnNvizCmd),
                                      (None, ),
@@ -253,11 +283,11 @@
                                      ("help", icons["help"],
                                       self.OnHelp))
                                     )
-        
+
     def OnNvizCmd(self, event):
         """Show m.nviz.image command"""
         self.lmgr.GetLayerTree().GetMapDisplay().GetWindow().OnNvizCmd()
-        
+
     def OnHelp(self, event):
         """Show 3D view mode help"""
         if not self.lmgr:

Modified: grass/trunk/gui/wxpython/location_wizard/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/location_wizard/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/location_wizard/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -2,4 +2,4 @@
     'wizard',
     'base',
     'dialogs',
-    ]
+]

Modified: grass/trunk/gui/wxpython/location_wizard/base.py
===================================================================
--- grass/trunk/gui/wxpython/location_wizard/base.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/location_wizard/base.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -13,42 +13,49 @@
 
 @author Michael Barton
 @author Jachym Cepicky
- at author Martin Landa <landa.martin gmail.com>   
+ at author Martin Landa <landa.martin gmail.com>
 """
 
 import wx
 
+
 class BaseClass(wx.Object):
     """Base class providing basic methods"""
+
     def __init__(self):
         pass
 
-    def MakeLabel(self, text = "", style = wx.ALIGN_LEFT, parent = None, tooltip = None):
+    def MakeLabel(self, text="", style=wx.ALIGN_LEFT,
+                  parent=None, tooltip=None):
         """Make aligned label"""
         if not parent:
             parent = self
-        label =  wx.StaticText(parent = parent, id = wx.ID_ANY, label = text,
-                              style = style)
+        label = wx.StaticText(parent=parent, id=wx.ID_ANY, label=text,
+                              style=style)
         if tooltip:
             label.SetToolTipString(tooltip)
         return label
 
-    def MakeTextCtrl(self, text = '', size = (100,-1), style = 0, parent = None, tooltip = None):
+    def MakeTextCtrl(
+            self, text='', size=(100, -1),
+            style=0, parent=None, tooltip=None):
         """Generic text control"""
         if not parent:
             parent = self
-        textCtrl = wx.TextCtrl(parent = parent, id = wx.ID_ANY, value = text,
-                               size = size, style = style)
+        textCtrl = wx.TextCtrl(parent=parent, id=wx.ID_ANY, value=text,
+                               size=size, style=style)
         if tooltip:
             textCtrl.SetToolTipString(tooltip)
         return textCtrl
 
-    def MakeButton(self, text, id = wx.ID_ANY, size = (-1,-1), parent = None, tooltip = None):
+    def MakeButton(
+            self, text, id=wx.ID_ANY, size=(-1, -1),
+            parent=None, tooltip=None):
         """Generic button"""
         if not parent:
             parent = self
-        button = wx.Button(parent = parent, id = id, label = text,
-                           size = size)
+        button = wx.Button(parent=parent, id=id, label=text,
+                           size=size)
         if tooltip:
             button.SetToolTipString(tooltip)
         return button

Modified: grass/trunk/gui/wxpython/location_wizard/dialogs.py
===================================================================
--- grass/trunk/gui/wxpython/location_wizard/dialogs.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/location_wizard/dialogs.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -15,33 +15,40 @@
 
 @author Michael Barton
 @author Jachym Cepicky
- at author Martin Landa <landa.martin gmail.com>   
+ at author Martin Landa <landa.martin gmail.com>
 """
 import os
 
 import wx
 import wx.lib.scrolledpanel as scrolled
 
-from core                 import globalvar
-from core.gcmd            import RunCommand
+from core import globalvar
+from core.gcmd import RunCommand
 from core.utils import _
 from location_wizard.base import BaseClass
 
 from grass.script import core as grass
 
+
 class RegionDef(BaseClass, wx.Dialog):
     """Page for setting default region extents and resolution
     """
-    def __init__(self, parent, id = wx.ID_ANY, size = (800, 600),
-                 title = _("Set default region extent and resolution"), location = None):
-        wx.Dialog.__init__(self, parent, id, title, size = size)
-        panel = wx.Panel(self, id = wx.ID_ANY)
-        
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
-        
+
+    def __init__(self, parent, id=wx.ID_ANY, size=(800, 600), title=_(
+            "Set default region extent and resolution"), location=None):
+        wx.Dialog.__init__(self, parent, id, title, size=size)
+        panel = wx.Panel(self, id=wx.ID_ANY)
+
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass.ico'),
+                wx.BITMAP_TYPE_ICO))
+
         self.parent = parent
         self.location = location
-        
+
         #
         # default values
         #
@@ -57,46 +64,66 @@
         self.bottom = 0.0
         #         self.nsres3 = 1.0
         #         self.ewres3 = 1.0
-        self.tbres  = 1.0
-        
+        self.tbres = 1.0
+
         #
         # inputs
         #
         # 2D
-        self.tnorth = self.MakeTextCtrl(text = str(self.north), size = (150, -1), parent = panel)
-        self.tsouth = self.MakeTextCtrl(str(self.south), size = (150, -1), parent = panel)
-        self.twest = self.MakeTextCtrl(str(self.west), size = (150, -1), parent = panel)
-        self.teast = self.MakeTextCtrl(str(self.east), size = (150, -1), parent = panel)
-        self.tnsres = self.MakeTextCtrl(str(self.nsres), size = (150, -1), parent = panel)
-        self.tewres = self.MakeTextCtrl(str(self.ewres), size = (150, -1), parent = panel)
-        
+        self.tnorth = self.MakeTextCtrl(
+            text=str(
+                self.north), size=(
+                150, -1), parent=panel)
+        self.tsouth = self.MakeTextCtrl(
+            str(self.south),
+            size=(150, -1),
+            parent=panel)
+        self.twest = self.MakeTextCtrl(
+            str(self.west),
+            size=(150, -1),
+            parent=panel)
+        self.teast = self.MakeTextCtrl(
+            str(self.east),
+            size=(150, -1),
+            parent=panel)
+        self.tnsres = self.MakeTextCtrl(
+            str(self.nsres),
+            size=(150, -1),
+            parent=panel)
+        self.tewres = self.MakeTextCtrl(
+            str(self.ewres),
+            size=(150, -1),
+            parent=panel)
+
         #
         # labels
         #
-        self.lrows  = self.MakeLabel(parent = panel)
-        self.lcols  = self.MakeLabel(parent = panel)
-        self.lcells = self.MakeLabel(parent = panel)
-        
+        self.lrows = self.MakeLabel(parent=panel)
+        self.lcols = self.MakeLabel(parent=panel)
+        self.lcells = self.MakeLabel(parent=panel)
+
         #
         # buttons
         #
-        self.bset = self.MakeButton(text = _("&Set region"), id = wx.ID_OK, parent = panel)
-        self.bcancel = wx.Button(panel, id = wx.ID_CANCEL)
+        self.bset = self.MakeButton(
+            text=_("&Set region"),
+            id=wx.ID_OK, parent=panel)
+        self.bcancel = wx.Button(panel, id=wx.ID_CANCEL)
         self.bset.SetDefault()
-        
+
         #
         # image
         #
         self.img = wx.Image(os.path.join(globalvar.IMGDIR, "qgis_world.png"),
                             wx.BITMAP_TYPE_PNG).ConvertToBitmap()
-        
+
         #
         # set current working environment to PERMANENT mapset
         # in selected location in order to set default region (WIND)
         #
         envval = {}
         ret = RunCommand('g.gisenv',
-                         read = True)
+                         read=True)
         if ret:
             for line in ret.splitlines():
                 key, val = line.split('=')
@@ -105,34 +132,38 @@
             self.currmapset = envval['MAPSET'].strip("';")
             if self.currlocation != self.location or self.currmapset != 'PERMANENT':
                 RunCommand('g.gisenv',
-                           set = 'LOCATION_NAME=%s' % self.location)
+                           set='LOCATION_NAME=%s' % self.location)
                 RunCommand('g.gisenv',
-                           set = 'MAPSET=PERMANENT')
+                           set='MAPSET=PERMANENT')
         else:
-            dlg = wx.MessageBox(parent = self,
-                                message = _('Invalid location selected.'),
-                                caption = _("Error"), style = wx.ID_OK | wx.ICON_ERROR)
+            dlg = wx.MessageBox(
+                parent=self,
+                message=_('Invalid location selected.'),
+                caption=_("Error"),
+                style=wx.ID_OK | wx.ICON_ERROR)
             return
-        
+
         #
         # get current region settings
         #
         region = {}
         ret = RunCommand('g.region',
-                         read = True,
-                         flags = 'gp3')
+                         read=True,
+                         flags='gp3')
         if ret:
             for line in ret.splitlines():
                 key, val = line.split('=')
                 region[key] = float(val)
         else:
-            dlg = wx.MessageBox(parent = self,
-                                message = _("Invalid region"),
-                                caption = _("Error"), style = wx.ID_OK | wx.ICON_ERROR)
+            dlg = wx.MessageBox(
+                parent=self,
+                message=_("Invalid region"),
+                caption=_("Error"),
+                style=wx.ID_OK | wx.ICON_ERROR)
             dlg.ShowModal()
             dlg.Destroy()
             return
-        
+
         #
         # update values
         # 2D
@@ -153,20 +184,23 @@
         self.tbres = float(region['tbres'])
         self.depth = int(region['depths'])
         self.cells3 = int(region['cells3'])
-        
+
         #
         # 3D box collapsable
         #
         self.infoCollapseLabelExp = _("Click here to show 3D settings")
         self.infoCollapseLabelCol = _("Click here to hide 3D settings")
-        self.settings3D = wx.CollapsiblePane(parent = panel,
-                                             label = self.infoCollapseLabelExp,
-                                             style = wx.CP_DEFAULT_STYLE |
+        self.settings3D = wx.CollapsiblePane(parent=panel,
+                                             label=self.infoCollapseLabelExp,
+                                             style=wx.CP_DEFAULT_STYLE |
                                              wx.CP_NO_TLW_RESIZE | wx.EXPAND)
         self.MakeSettings3DPaneContent(self.settings3D.GetPane())
-        self.settings3D.Collapse(False) # FIXME
-        self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnSettings3DPaneChanged, self.settings3D)
-        
+        self.settings3D.Collapse(False)  # FIXME
+        self.Bind(
+            wx.EVT_COLLAPSIBLEPANE_CHANGED,
+            self.OnSettings3DPaneChanged,
+            self.settings3D)
+
         #
         # set current region settings
         #
@@ -184,74 +218,89 @@
         self.lrows.SetLabel(_("Rows: %d") % self.rows)
         self.lcols.SetLabel(_("Cols: %d") % self.cols)
         self.lcells.SetLabel(_("Cells: %d") % self.cells)
-        
+
         #
         # bindings
         #
         self.Bind(wx.EVT_BUTTON, self.OnSetButton, self.bset)
         self.Bind(wx.EVT_BUTTON, self.OnCancel, self.bcancel)
-        self.tnorth.Bind(wx.EVT_TEXT,   self.OnValue)
-        self.tsouth.Bind(wx.EVT_TEXT,   self.OnValue)
-        self.teast.Bind(wx.EVT_TEXT,    self.OnValue)
-        self.twest.Bind(wx.EVT_TEXT,    self.OnValue)
-        self.tnsres.Bind(wx.EVT_TEXT,   self.OnValue)
-        self.tewres.Bind(wx.EVT_TEXT,   self.OnValue)
-        self.ttop.Bind(wx.EVT_TEXT,     self.OnValue)
-        self.tbottom.Bind(wx.EVT_TEXT,  self.OnValue)
+        self.tnorth.Bind(wx.EVT_TEXT, self.OnValue)
+        self.tsouth.Bind(wx.EVT_TEXT, self.OnValue)
+        self.teast.Bind(wx.EVT_TEXT, self.OnValue)
+        self.twest.Bind(wx.EVT_TEXT, self.OnValue)
+        self.tnsres.Bind(wx.EVT_TEXT, self.OnValue)
+        self.tewres.Bind(wx.EVT_TEXT, self.OnValue)
+        self.ttop.Bind(wx.EVT_TEXT, self.OnValue)
+        self.tbottom.Bind(wx.EVT_TEXT, self.OnValue)
         #         self.tnsres3.Bind(wx.EVT_TEXT,  self.OnValue)
         #         self.tewres3.Bind(wx.EVT_TEXT,  self.OnValue)
-        self.ttbres.Bind(wx.EVT_TEXT,   self.OnValue)
-        
+        self.ttbres.Bind(wx.EVT_TEXT, self.OnValue)
+
         self.__DoLayout(panel)
         self.SetMinSize(self.GetBestSize())
         self.minWindowSize = self.GetMinSize()
         wx.CallAfter(self.settings3D.Collapse, True)
-    
+
     def MakeSettings3DPaneContent(self, pane):
         """Create 3D region settings pane"""
         border = wx.BoxSizer(wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 0, hgap = 0)
+        gridSizer = wx.GridBagSizer(vgap=0, hgap=0)
 
         # inputs
-        self.ttop = wx.TextCtrl(parent = pane, id = wx.ID_ANY, value = str(self.top),
-                                size = (150, -1))
-        self.tbottom = wx.TextCtrl(parent = pane, id = wx.ID_ANY, value = str(self.bottom),
-                                size = (150, -1))
-        self.ttbres = wx.TextCtrl(parent = pane, id = wx.ID_ANY, value = str(self.tbres),
-                                size = (150, -1))
+        self.ttop = wx.TextCtrl(parent=pane, id=wx.ID_ANY, value=str(self.top),
+                                size=(150, -1))
+        self.tbottom = wx.TextCtrl(
+            parent=pane, id=wx.ID_ANY, value=str(
+                self.bottom), size=(
+                150, -1))
+        self.ttbres = wx.TextCtrl(
+            parent=pane, id=wx.ID_ANY, value=str(
+                self.tbres), size=(
+                150, -1))
         #         self.tnsres3 = wx.TextCtrl(parent = pane, id = wx.ID_ANY, value = str(self.nsres3),
         #                                    size = (150, -1))
         #         self.tewres3  =  wx.TextCtrl(parent = pane, id = wx.ID_ANY, value = str(self.ewres3),
         #                                    size = (150, -1))
 
-        #labels
-        self.ldepth = wx.StaticText(parent = pane, label = _("Depth: %d") % self.depth)
-        self.lcells3  =  wx.StaticText(parent = pane, label = _("3D Cells: %d") % self.cells3)
+        # labels
+        self.ldepth = wx.StaticText(
+            parent=pane,
+            label=_("Depth: %d") %
+            self.depth)
+        self.lcells3 = wx.StaticText(
+            parent=pane,
+            label=_("3D Cells: %d") %
+            self.cells3)
 
         # top
-        gridSizer.Add(item = wx.StaticText(parent = pane, label = _("Top")),
-                      flag = wx.ALIGN_CENTER |
-                      wx.LEFT | wx.RIGHT | wx.TOP, border = 5,
-                      pos = (0, 1))
-        gridSizer.Add(item = self.ttop,
-                      flag = wx.ALIGN_CENTER_HORIZONTAL |
-                      wx.ALL, border = 5, pos = (1, 1))
+        gridSizer.Add(item=wx.StaticText(parent=pane, label=_("Top")),
+                      flag=wx.ALIGN_CENTER |
+                      wx.LEFT | wx.RIGHT | wx.TOP, border=5,
+                      pos=(0, 1))
+        gridSizer.Add(item=self.ttop,
+                      flag=wx.ALIGN_CENTER_HORIZONTAL |
+                      wx.ALL, border=5, pos=(1, 1))
         # bottom
-        gridSizer.Add(item = wx.StaticText(parent = pane, label = _("Bottom")),
-                      flag = wx.ALIGN_CENTER |
-                      wx.LEFT | wx.RIGHT | wx.TOP, border = 5,
-                      pos = (0, 2))
-        gridSizer.Add(item = self.tbottom,
-                      flag = wx.ALIGN_CENTER_HORIZONTAL |
-                      wx.ALL, border = 5, pos = (1, 2))
+        gridSizer.Add(item=wx.StaticText(parent=pane, label=_("Bottom")),
+                      flag=wx.ALIGN_CENTER |
+                      wx.LEFT | wx.RIGHT | wx.TOP, border=5,
+                      pos=(0, 2))
+        gridSizer.Add(item=self.tbottom,
+                      flag=wx.ALIGN_CENTER_HORIZONTAL |
+                      wx.ALL, border=5, pos=(1, 2))
         # tbres
-        gridSizer.Add(item = wx.StaticText(parent = pane, label = _("T-B resolution")),
-                      flag = wx.ALIGN_CENTER | 
-                      wx.LEFT | wx.RIGHT | wx.TOP, border = 5,
-                      pos = (0, 3))
-        gridSizer.Add(item = self.ttbres,
-                      flag = wx.ALIGN_CENTER_HORIZONTAL |
-                      wx.ALL, border = 5, pos = (1, 3))
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=pane,
+                label=_("T-B resolution")),
+            flag=wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT | wx.TOP,
+            border=5,
+            pos=(
+                0,
+                3))
+        gridSizer.Add(item=self.ttbres,
+                      flag=wx.ALIGN_CENTER_HORIZONTAL |
+                      wx.ALL, border=5, pos=(1, 3))
 
         # res
         #         gridSizer.Add(item = wx.StaticText(parent = pane, label = _("3D N-S resolution")),
@@ -270,16 +319,16 @@
         #                       wx.ALL, border = 5, pos = (3, 3))
 
         # rows/cols/cells
-        gridSizer.Add(item = self.ldepth,
-                      flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER |
-                      wx.ALL, border = 5, pos = (2, 1))
+        gridSizer.Add(item=self.ldepth,
+                      flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER |
+                      wx.ALL, border=5, pos=(2, 1))
 
-        gridSizer.Add(item = self.lcells3,
-                      flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER |
-                      wx.ALL, border = 5, pos = (2, 2))
+        gridSizer.Add(item=self.lcells3,
+                      flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER |
+                      wx.ALL, border=5, pos=(2, 2))
 
-        border.Add(item = gridSizer, proportion = 1,
-                   flag = wx.ALL | wx.ALIGN_CENTER | wx.EXPAND, border = 5)
+        border.Add(item=gridSizer, proportion=1,
+                   flag=wx.ALL | wx.ALIGN_CENTER | wx.EXPAND, border=5)
 
         pane.SetSizer(border)
         border.Fit(pane)
@@ -303,101 +352,103 @@
     def __DoLayout(self, panel):
         """Window layout"""
         frameSizer = wx.BoxSizer(wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 0, hgap = 0)
+        gridSizer = wx.GridBagSizer(vgap=0, hgap=0)
         settings3DSizer = wx.BoxSizer(wx.VERTICAL)
         buttonSizer = wx.BoxSizer(wx.HORIZONTAL)
 
         # north
-        gridSizer.Add(item = self.MakeLabel(text = _("North"), parent = panel),
-                      flag = wx.ALIGN_BOTTOM | wx.ALIGN_CENTER_HORIZONTAL |
-                      wx.TOP | wx.LEFT | wx.RIGHT, border = 5, pos = (0, 2))
-        gridSizer.Add(item = self.tnorth,
-                      flag = wx.ALIGN_CENTER_HORIZONTAL |
+        gridSizer.Add(item=self.MakeLabel(text=_("North"), parent=panel),
+                      flag=wx.ALIGN_BOTTOM | wx.ALIGN_CENTER_HORIZONTAL |
+                      wx.TOP | wx.LEFT | wx.RIGHT, border=5, pos=(0, 2))
+        gridSizer.Add(item=self.tnorth,
+                      flag=wx.ALIGN_CENTER_HORIZONTAL |
                       wx.ALIGN_CENTER_VERTICAL |
-                      wx.ALL, border = 5, pos = (1, 2))
+                      wx.ALL, border=5, pos=(1, 2))
         # west
-        gridSizer.Add(item = self.MakeLabel(text = _("West"), parent = panel),
-                      flag = wx.ALIGN_RIGHT |
+        gridSizer.Add(item=self.MakeLabel(text=_("West"), parent=panel),
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL |
-                      wx.LEFT | wx.TOP | wx.BOTTOM, border = 5, pos = (2, 0))
-        gridSizer.Add(item = self.twest,
-                      flag = wx.ALIGN_RIGHT |
+                      wx.LEFT | wx.TOP | wx.BOTTOM, border=5, pos=(2, 0))
+        gridSizer.Add(item=self.twest,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL |
-                      wx.ALL, border = 5,  pos = (2, 1))
+                      wx.ALL, border=5, pos=(2, 1))
 
-        gridSizer.Add(item = wx.StaticBitmap(panel, wx.ID_ANY, self.img, (-1, -1),
-                                           (self.img.GetWidth(), self.img.GetHeight())),
-                      flag = wx.ALIGN_CENTER |
-                      wx.ALIGN_CENTER_VERTICAL |
-                      wx.ALL, border = 5, pos = (2, 2))
+        gridSizer.Add(
+            item=wx.StaticBitmap(
+                panel, wx.ID_ANY, self.img, (-1, -1),
+                (self.img.GetWidth(),
+                 self.img.GetHeight())),
+            flag=wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
+            pos=(2, 2))
 
         # east
-        gridSizer.Add(item = self.teast,
-                      flag = wx.ALIGN_CENTER_HORIZONTAL |
+        gridSizer.Add(item=self.teast,
+                      flag=wx.ALIGN_CENTER_HORIZONTAL |
                       wx.ALIGN_CENTER_VERTICAL |
-                      wx.ALL, border = 5,  pos = (2, 3))
-        gridSizer.Add(item = self.MakeLabel(text = _("East"), parent = panel),
-                      flag = wx.ALIGN_LEFT |
+                      wx.ALL, border=5, pos=(2, 3))
+        gridSizer.Add(item=self.MakeLabel(text=_("East"), parent=panel),
+                      flag=wx.ALIGN_LEFT |
                       wx.ALIGN_CENTER_VERTICAL |
-                      wx.RIGHT | wx.TOP | wx.BOTTOM, border = 5, pos = (2, 4))
+                      wx.RIGHT | wx.TOP | wx.BOTTOM, border=5, pos=(2, 4))
         # south
-        gridSizer.Add(item = self.tsouth,
-                      flag = wx.ALIGN_CENTER_HORIZONTAL |
+        gridSizer.Add(item=self.tsouth,
+                      flag=wx.ALIGN_CENTER_HORIZONTAL |
                       wx.ALIGN_CENTER_VERTICAL |
-                      wx.ALL, border = 5, pos = (3, 2))
-        gridSizer.Add(item = self.MakeLabel(text = _("South"), parent = panel),
-                      flag = wx.ALIGN_TOP | wx.ALIGN_CENTER_HORIZONTAL |
-                      wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5, pos = (4, 2))
+                      wx.ALL, border=5, pos=(3, 2))
+        gridSizer.Add(item=self.MakeLabel(text=_("South"), parent=panel),
+                      flag=wx.ALIGN_TOP | wx.ALIGN_CENTER_HORIZONTAL |
+                      wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5, pos=(4, 2))
         # ns-res
-        gridSizer.Add(item = self.MakeLabel(text = _("N-S resolution"), parent = panel),
-                      flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER |
-                      wx.TOP | wx.LEFT | wx.RIGHT, border = 5, pos = (5, 1))
-        gridSizer.Add(item = self.tnsres,
-                      flag = wx.ALIGN_RIGHT |
+        gridSizer.Add(item=self.MakeLabel(text=_("N-S resolution"), parent=panel),
+                      flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER |
+                      wx.TOP | wx.LEFT | wx.RIGHT, border=5, pos=(5, 1))
+        gridSizer.Add(item=self.tnsres,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL |
-                      wx.ALL, border = 5,  pos = (6, 1))
+                      wx.ALL, border=5, pos=(6, 1))
         # ew-res
-        gridSizer.Add(item = self.MakeLabel(text = _("E-W resolution"), parent = panel),
-                      flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER |
-                      wx.TOP | wx.LEFT | wx.RIGHT, border = 5, pos = (5, 3))
-        gridSizer.Add(item = self.tewres,
-                      flag = wx.ALIGN_RIGHT |
+        gridSizer.Add(item=self.MakeLabel(text=_("E-W resolution"), parent=panel),
+                      flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER |
+                      wx.TOP | wx.LEFT | wx.RIGHT, border=5, pos=(5, 3))
+        gridSizer.Add(item=self.tewres,
+                      flag=wx.ALIGN_RIGHT |
                       wx.ALIGN_CENTER_VERTICAL |
-                      wx.ALL, border = 5,  pos = (6, 3))
+                      wx.ALL, border=5, pos=(6, 3))
         # rows/cols/cells
-        gridSizer.Add(item = self.lrows,
-                      flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER |
-                      wx.ALL, border = 5, pos = (7, 1))
+        gridSizer.Add(item=self.lrows,
+                      flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER |
+                      wx.ALL, border=5, pos=(7, 1))
 
-        gridSizer.Add(item = self.lcells,
-                      flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER |
-                      wx.ALL, border = 5, pos = (7, 2))
+        gridSizer.Add(item=self.lcells,
+                      flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER |
+                      wx.ALL, border=5, pos=(7, 2))
 
-        gridSizer.Add(item = self.lcols,
-                      flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER |
-                      wx.ALL, border = 5, pos = (7, 3))
+        gridSizer.Add(item=self.lcols,
+                      flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER |
+                      wx.ALL, border=5, pos=(7, 3))
 
         # 3D
-        settings3DSizer.Add(item = self.settings3D,
-                            flag = wx.ALL,
-                            border = 5)
+        settings3DSizer.Add(item=self.settings3D,
+                            flag=wx.ALL,
+                            border=5)
 
         # buttons
-        buttonSizer.Add(item = self.bcancel, proportion = 1,
-                        flag = wx.ALIGN_RIGHT |
+        buttonSizer.Add(item=self.bcancel, proportion=1,
+                        flag=wx.ALIGN_RIGHT |
                         wx.ALIGN_CENTER_VERTICAL |
-                        wx.ALL, border = 10)
-        buttonSizer.Add(item = self.bset, proportion = 1,
-                        flag = wx.ALIGN_CENTER |
+                        wx.ALL, border=10)
+        buttonSizer.Add(item=self.bset, proportion=1,
+                        flag=wx.ALIGN_CENTER |
                         wx.ALIGN_CENTER_VERTICAL |
-                        wx.ALL, border = 10)
+                        wx.ALL, border=10)
 
-        frameSizer.Add(item = gridSizer, proportion = 1,
-                       flag = wx.ALL | wx.ALIGN_CENTER, border = 5)
-        frameSizer.Add(item = settings3DSizer, proportion = 0,
-                       flag = wx.ALL | wx.ALIGN_CENTER, border = 5)
-        frameSizer.Add(item = buttonSizer, proportion = 0,
-                       flag = wx.ALL | wx.ALIGN_RIGHT, border = 5)
+        frameSizer.Add(item=gridSizer, proportion=1,
+                       flag=wx.ALL | wx.ALIGN_CENTER, border=5)
+        frameSizer.Add(item=settings3DSizer, proportion=0,
+                       flag=wx.ALL | wx.ALIGN_CENTER, border=5)
+        frameSizer.Add(item=buttonSizer, proportion=0,
+                       flag=wx.ALL | wx.ALIGN_RIGHT, border=5)
 
         self.SetAutoLayout(True)
         panel.SetSizer(frameSizer)
@@ -434,10 +485,10 @@
 
         except ValueError as e:
             if len(event.GetString()) > 0 and event.GetString() != '-':
-                dlg = wx.MessageBox(parent = self,
-                                    message = _("Invalid value: %s") % e,
-                                    caption = _("Error"),
-                                    style = wx.OK | wx.ICON_ERROR)
+                dlg = wx.MessageBox(parent=self,
+                                    message=_("Invalid value: %s") % e,
+                                    caption=_("Error"),
+                                    style=wx.OK | wx.ICON_ERROR)
                 # reset values
                 self.tnorth.SetValue(str(self.north))
                 self.tsouth.SetValue(str(self.south))
@@ -470,28 +521,29 @@
         self.ldepth.SetLabel(_("Depth: %d" % self.depth))
         self.lcells3.SetLabel(_("3D Cells: %d" % self.cells3))
 
-    def OnSetButton(self, event = None):
+    def OnSetButton(self, event=None):
         """Set default region"""
         ret = RunCommand('g.region',
-                         flags = 'sgpa',
-                         n = self.north,
-                         s = self.south,
-                         e = self.east,
-                         w = self.west,
-                         nsres = self.nsres,
-                         ewres = self.ewres,
-                         t = self.top,
-                         b = self.bottom,
-                         tbres = self.tbres)
+                         flags='sgpa',
+                         n=self.north,
+                         s=self.south,
+                         e=self.east,
+                         w=self.west,
+                         nsres=self.nsres,
+                         ewres=self.ewres,
+                         t=self.top,
+                         b=self.bottom,
+                         tbres=self.tbres)
         if ret == 0:
             self.Destroy()
 
     def OnCancel(self, event):
         self.Destroy()
 
+
 class TransList(wx.VListBox):
     """Creates a multiline listbox for selecting datum transforms"""
-        
+
     def OnDrawItem(self, dc, rect, n):
         if self.GetSelection() == n:
             c = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)
@@ -504,7 +556,7 @@
 
     def OnMeasureItem(self, n):
         height = 0
-        if self._getItemText(n) == None:
+        if self._getItemText(n) is None:
             return
         for line in self._getItemText(n).splitlines():
             w, h = self.GetTextExtent(line)
@@ -514,23 +566,26 @@
     def _getItemText(self, item):
         global transformlist
         transitem = transformlist[item]
-        if transitem.strip() !='':
+        if transitem.strip() != '':
             return transitem
 
+
 class SelectTransformDialog(wx.Dialog):
     """Dialog for selecting datum transformations"""
-    def __init__(self, parent, transforms, title = _("Select datum transformation"),
-                 pos = wx.DefaultPosition, size = wx.DefaultSize, 
-                 style = wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER):
 
+    def __init__(self, parent, transforms,
+                 title=_("Select datum transformation"),
+                 pos=wx.DefaultPosition, size=wx.DefaultSize,
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
+
         wx.Dialog.__init__(self, parent, wx.ID_ANY, title, pos, size, style)
 
         global transformlist
         self.CentreOnParent()
-        
+
         # default transform number
         self.transnum = 0
-        
+
         panel = scrolled.ScrolledPanel(self, wx.ID_ANY)
         sizer = wx.BoxSizer(wx.VERTICAL)
 
@@ -543,16 +598,17 @@
         #
         # dialog body
         #
-        bodyBox = wx.StaticBox(parent = panel, id = wx.ID_ANY,
-                               label = " %s " % _("Select from list of datum transformations"))
-        bodySizer = wx.StaticBoxSizer(bodyBox)       
-        
+        bodyBox = wx.StaticBox(
+            parent=panel, id=wx.ID_ANY, label=" %s " %
+            _("Select from list of datum transformations"))
+        bodySizer = wx.StaticBoxSizer(bodyBox)
+
         # add no transform option
         transforms = '---\n\n0\nDo not apply any datum transformations\n\n' + transforms
-        
+
         transformlist = transforms.split('---')
         tlistlen = len(transformlist)
-        
+
         # calculate size for transform list
         height = 0
         width = 0
@@ -560,59 +616,67 @@
             w, h = self.GetTextExtent(line)
             height += h
             width = max(width, w)
-            
+
         height = height + 5
-        if height > 400: height = 400
+        if height > 400:
+            height = 400
         width = width + 5
-        if width > 400: width = 400
+        if width > 400:
+            width = 400
 
         #
         # VListBox for displaying and selecting transformations
         #
-        self.translist = TransList(panel, id = -1, size = (width, height), style = wx.SUNKEN_BORDER)
+        self.translist = TransList(
+            panel, id=-1, size=(width, height),
+            style=wx.SUNKEN_BORDER)
         self.translist.SetItemCount(tlistlen)
         self.translist.SetSelection(2)
         self.translist.SetFocus()
-        
+
         self.Bind(wx.EVT_LISTBOX, self.ClickTrans, self.translist)
 
-        bodySizer.Add(item = self.translist, proportion = 1, flag = wx.ALIGN_CENTER|wx.ALL|wx.EXPAND)
+        bodySizer.Add(
+            item=self.translist,
+            proportion=1,
+            flag=wx.ALIGN_CENTER | wx.ALL | wx.EXPAND)
 
         #
         # buttons
         #
         btnsizer = wx.StdDialogButtonSizer()
 
-        btn = wx.Button(parent = panel, id = wx.ID_OK)
+        btn = wx.Button(parent=panel, id=wx.ID_OK)
         btn.SetDefault()
         btnsizer.AddButton(btn)
 
-        btn = wx.Button(parent = panel, id = wx.ID_CANCEL)
+        btn = wx.Button(parent=panel, id=wx.ID_CANCEL)
         btnsizer.AddButton(btn)
         btnsizer.Realize()
 
-        sizer.Add(item = bodySizer, proportion = 1,
-                  flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
+        sizer.Add(item=bodySizer, proportion=1,
+                  flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
 
-        sizer.Add(item = btnsizer, proportion = 0,
-                  flag =  wx.ALL | wx.ALIGN_RIGHT, border = 5)
+        sizer.Add(item=btnsizer, proportion=0,
+                  flag=wx.ALL | wx.ALIGN_RIGHT, border=5)
 
         sizer.Fit(panel)
 
         self.SetSize(self.GetBestSize())
         self.Layout()
-        
+
     def ClickTrans(self, event):
         """Get the number of the datum transform to use in g.proj"""
         self.transnum = event.GetSelection()
         self.transnum = self.transnum - 1
-    
+
     def GetTransform(self):
         """Get the number of the datum transform to use in g.proj"""
         self.transnum = self.translist.GetSelection()
         self.transnum = self.transnum - 1
         return self.transnum
 
+
 def testRegionDef():
     import sys
     import wx.lib.inspection
@@ -620,7 +684,7 @@
 
     app = wx.App()
 
-    dlg = RegionDef(None, location = grass.gisenv()["LOCATION_NAME"])
+    dlg = RegionDef(None, location=grass.gisenv()["LOCATION_NAME"])
     dlg.Show()
     wx.lib.inspection.InspectionTool().Show()
     app.MainLoop()

Modified: grass/trunk/gui/wxpython/location_wizard/wizard.py
===================================================================
--- grass/trunk/gui/wxpython/location_wizard/wizard.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/location_wizard/wizard.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -41,12 +41,12 @@
 import wx.wizard as wiz
 import wx.lib.scrolledpanel as scrolled
 
-from core                    import globalvar
-from core                    import utils
+from core import globalvar
+from core import utils
 from core.utils import _
-from core.gcmd               import RunCommand, GError, GMessage, GWarning
-from gui_core.widgets        import GenericValidator
-from location_wizard.base    import BaseClass
+from core.gcmd import RunCommand, GError, GMessage, GWarning
+from gui_core.widgets import GenericValidator
+from location_wizard.base import BaseClass
 from location_wizard.dialogs import SelectTransformDialog
 
 from grass.script import core as grass
@@ -61,112 +61,135 @@
 global wizerror
 global translist
 
+
 class TitledPage(BaseClass, wiz.WizardPageSimple):
     """Class to make wizard pages. Generic methods to make labels,
     text entries, and buttons.
     """
+
     def __init__(self, parent, title):
 
         self.page = wiz.WizardPageSimple.__init__(self, parent)
 
         # page title
-        self.title = wx.StaticText(parent = self, id = wx.ID_ANY, label = title)
+        self.title = wx.StaticText(parent=self, id=wx.ID_ANY, label=title)
         self.title.SetFont(wx.Font(13, wx.SWISS, wx.NORMAL, wx.BOLD))
 
         # main sizers
         self.pagesizer = wx.BoxSizer(wx.VERTICAL)
-        self.sizer = wx.GridBagSizer(vgap = 0, hgap = 0)
+        self.sizer = wx.GridBagSizer(vgap=0, hgap=0)
         self.sizer.SetCols(5)
         self.sizer.SetRows(6)
-        
+
     def DoLayout(self):
         """Do page layout"""
-        self.pagesizer.Add(item = self.title, proportion = 0,
-                           flag = wx.ALIGN_CENTRE | wx.ALL,
-                           border = 5)
-        self.pagesizer.Add(item = wx.StaticLine(self, -1), proportion = 0,
-                           flag = wx.EXPAND | wx.ALL,
-                           border = 0)
-        self.pagesizer.Add(item = self.sizer, proportion = 1,
-                           flag = wx.EXPAND)
-        
+        self.pagesizer.Add(item=self.title, proportion=0,
+                           flag=wx.ALIGN_CENTRE | wx.ALL,
+                           border=5)
+        self.pagesizer.Add(item=wx.StaticLine(self, -1), proportion=0,
+                           flag=wx.EXPAND | wx.ALL,
+                           border=0)
+        self.pagesizer.Add(item=self.sizer, proportion=1,
+                           flag=wx.EXPAND)
+
         self.SetAutoLayout(True)
         self.SetSizer(self.pagesizer)
         self.Layout()
 
+
 class DatabasePage(TitledPage):
     """Wizard page for setting GIS data directory and location name"""
+
     def __init__(self, wizard, parent, grassdatabase):
-        TitledPage.__init__(self, wizard, _("Define GRASS Database and Location Name"))
+        TitledPage.__init__(self, wizard, _(
+            "Define GRASS Database and Location Name"))
 
-        self.grassdatabase  = grassdatabase
-        self.location       = ''
-        self.locTitle       = ''
-        
+        self.grassdatabase = grassdatabase
+        self.location = ''
+        self.locTitle = ''
+
         # buttons
         self.bbrowse = self.MakeButton(_("Browse"))
 
         # text controls
-        self.tgisdbase = self.MakeTextCtrl(grassdatabase, size = (300, -1))
-        self.tlocation = self.MakeTextCtrl("newLocation", size = (300, -1))
+        self.tgisdbase = self.MakeTextCtrl(grassdatabase, size=(300, -1))
+        self.tlocation = self.MakeTextCtrl("newLocation", size=(300, -1))
         self.tlocation.SetFocus()
-        self.tlocation.SetValidator(GenericValidator(grass.legal_name, self._nameValidationFailed))
-        self.tlocTitle = self.MakeTextCtrl(size = (400, -1))
-        
+        self.tlocation.SetValidator(
+            GenericValidator(
+                grass.legal_name,
+                self._nameValidationFailed))
+        self.tlocTitle = self.MakeTextCtrl(size=(400, -1))
+
         # layout
-        self.sizer.Add(item = self.MakeLabel(_("GIS Data Directory:")),
-                       flag = wx.ALIGN_RIGHT |
+        self.sizer.Add(item=self.MakeLabel(_("GIS Data Directory:")),
+                       flag=wx.ALIGN_RIGHT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5,
-                       pos = (1, 1))
-        self.sizer.Add(item = self.tgisdbase,
-                       flag = wx.ALIGN_LEFT |
+                       wx.ALL, border=5,
+                       pos=(1, 1))
+        self.sizer.Add(item=self.tgisdbase,
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5,
-                       pos = (1, 2))
-        self.sizer.Add(item = self.bbrowse,
-                       flag = wx.ALIGN_LEFT |
+                       wx.ALL, border=5,
+                       pos=(1, 2))
+        self.sizer.Add(item=self.bbrowse,
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5,
-                       pos = (1, 3))
-        
-        self.sizer.Add(item = self.MakeLabel("%s:" % _("Project Location"),
-                                             tooltip = _("Name of location directory in GIS Data Directory")),
-                       flag = wx.ALIGN_RIGHT |
+                       wx.ALL, border=5,
+                       pos=(1, 3))
+
+        self.sizer.Add(
+            item=self.MakeLabel(
+                "%s:" %
+                _("Project Location"),
+                tooltip=_("Name of location directory in GIS Data Directory")),
+            flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5,
+            pos=(
+                2,
+                1))
+        self.sizer.Add(item=self.tlocation,
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5,
-                       pos = (2, 1))
-        self.sizer.Add(item = self.tlocation,
-                       flag = wx.ALIGN_LEFT |
-                       wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5,
-                       pos = (2, 2))
+                       wx.ALL, border=5,
+                       pos=(2, 2))
 
-        self.sizer.Add(item = self.MakeLabel("%s:" % _("Location Title"),
-                                             tooltip = _("Optional location title, "
-                                                         "you can leave this field blank.")),
-                       flag = wx.ALIGN_RIGHT |
-                       wx.ALIGN_TOP | wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5,
-                       pos = (3, 1))
-        self.sizer.Add(item = self.tlocTitle,
-                       flag = wx.ALIGN_LEFT |
+        self.sizer.Add(
+            item=self.MakeLabel(
+                "%s:" %
+                _("Location Title"),
+                tooltip=_(
+                    "Optional location title, "
+                    "you can leave this field blank.")),
+            flag=wx.ALIGN_RIGHT | wx.ALIGN_TOP | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5,
+            pos=(
+                3,
+                1))
+        self.sizer.Add(item=self.tlocTitle,
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5,
-                       pos = (3, 2), span  =  (1, 2))
+                       wx.ALL, border=5,
+                       pos=(3, 2), span=(1, 2))
         self.sizer.AddGrowableCol(3)
-        
+
         # bindings
-        self.Bind(wx.EVT_BUTTON,                self.OnBrowse, self.bbrowse)
+        self.Bind(wx.EVT_BUTTON, self.OnBrowse, self.bbrowse)
         self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
-        self.tgisdbase.Bind(wx.EVT_TEXT,        self.OnChangeName)
-        self.tlocation.Bind(wx.EVT_TEXT,        self.OnChangeName)
+        self.tgisdbase.Bind(wx.EVT_TEXT, self.OnChangeName)
+        self.tlocation.Bind(wx.EVT_TEXT, self.OnChangeName)
 
     def _nameValidationFailed(self, ctrl):
-        message = _("Name <%(name)s> is not a valid name for location. "
-                    "Please use only ASCII characters excluding %(chars)s "
-                    "and space.") % {'name': ctrl.GetValue(), 'chars': '/"\'@,=*~'}
-        GError(parent=self, message=message, caption=_("Invalid location name"))
+        message = _(
+            "Name <%(name)s> is not a valid name for location. "
+            "Please use only ASCII characters excluding %(chars)s "
+            "and space.") % {
+            'name': ctrl.GetValue(),
+            'chars': '/"\'@,=*~'}
+        GError(
+            parent=self,
+            message=message,
+            caption=_("Invalid location name"))
 
     def OnChangeName(self, event):
         """Name for new location was changed"""
@@ -186,16 +209,19 @@
         if dlg.ShowModal() == wx.ID_OK:
             self.grassdatabase = dlg.GetPath()
             self.tgisdbase.SetValue(self.grassdatabase)
-            
+
         dlg.Destroy()
 
-    def OnPageChanging(self, event = None):
+    def OnPageChanging(self, event=None):
         error = None
-        if os.path.isdir(os.path.join(self.tgisdbase.GetValue(), self.tlocation.GetValue())):
+        if os.path.isdir(
+            os.path.join(
+                self.tgisdbase.GetValue(),
+                self.tlocation.GetValue())):
             error = _("Location already exists in GRASS Database.")
 
         if error:
-            GError(parent = self,
+            GError(parent=self,
                    message="%s <%s>.%s%s" % (_("Unable to create location"),
                                              str(self.tlocation.GetValue()),
                                              os.linesep,
@@ -203,75 +229,82 @@
             event.Veto()
             return
 
-        self.location      = self.tlocation.GetValue()
+        self.location = self.tlocation.GetValue()
         self.grassdatabase = self.tgisdbase.GetValue()
-        self.locTitle      = self.tlocTitle.GetValue()
+        self.locTitle = self.tlocTitle.GetValue()
         if os.linesep in self.locTitle or \
                 len(self.locTitle) > 255:
-            GWarning(parent = self,
-                     message = _("Title of the location is limited only to one line and "
-                                 "256 characters. The rest of the text will be ignored."))
+            GWarning(
+                parent=self, message=_(
+                    "Title of the location is limited only to one line and "
+                    "256 characters. The rest of the text will be ignored."))
             self.locTitle = self.locTitle.split(os.linesep)[0][:255]
-            
+
+
 class CoordinateSystemPage(TitledPage):
     """Wizard page for choosing method for location creation"""
+
     def __init__(self, wizard, parent):
-        TitledPage.__init__(self, wizard, _("Choose method for creating a new location"))
-        
+        TitledPage.__init__(self, wizard, _(
+            "Choose method for creating a new location"))
+
         self.parent = parent
         global coordsys
-        
+
         # toggles
-        self.radioEpsg = wx.RadioButton(parent = self, id = wx.ID_ANY,
-                                        label = _("Select EPSG code of spatial reference system"),
-                                        style  =  wx.RB_GROUP)
-        self.radioIau = wx.RadioButton(parent = self, id = wx.ID_ANY,
-                                        label = _("Select IAU code of spatial reference system"))
-        self.radioFile = wx.RadioButton(parent = self, id = wx.ID_ANY,
-                                        label = _("Read projection and datum terms from a "
-                                                  "georeferenced data file"))
-        self.radioWkt = wx.RadioButton(parent = self, id = wx.ID_ANY,
-                                       label = _("Read projection and datum terms from a "
-                                                 "Well Known Text (WKT) .prj file"))
-        self.radioSrs = wx.RadioButton(parent = self, id = wx.ID_ANY,
-                                       label = _("Select coordinate system parameters from a list"))
-        self.radioProj = wx.RadioButton(parent = self, id = wx.ID_ANY,
-                                        label = _("Specify projection and datum terms using custom "
-                                                  "PROJ.4 parameters"))
-        self.radioXy = wx.RadioButton(parent = self, id = wx.ID_ANY,
-                                      label = _("Create a generic Cartesian coordinate system (XY)"))
-        
+        self.radioEpsg = wx.RadioButton(parent=self, id=wx.ID_ANY, label=_(
+            "Select EPSG code of spatial reference system"), style=wx.RB_GROUP)
+        self.radioIau = wx.RadioButton(
+            parent=self, id=wx.ID_ANY,
+            label=_("Select IAU code of spatial reference system"))
+        self.radioFile = wx.RadioButton(
+            parent=self, id=wx.ID_ANY, label=_(
+                "Read projection and datum terms from a "
+                "georeferenced data file"))
+        self.radioWkt = wx.RadioButton(
+            parent=self, id=wx.ID_ANY, label=_(
+                "Read projection and datum terms from a "
+                "Well Known Text (WKT) .prj file"))
+        self.radioSrs = wx.RadioButton(parent=self, id=wx.ID_ANY, label=_(
+            "Select coordinate system parameters from a list"))
+        self.radioProj = wx.RadioButton(
+            parent=self, id=wx.ID_ANY, label=_(
+                "Specify projection and datum terms using custom "
+                "PROJ.4 parameters"))
+        self.radioXy = wx.RadioButton(parent=self, id=wx.ID_ANY, label=_(
+            "Create a generic Cartesian coordinate system (XY)"))
+
         # layout
         self.sizer.SetVGap(10)
-        self.sizer.Add(item = self.radioEpsg,
-                       flag = wx.ALIGN_LEFT, pos = (1, 1))
-        self.sizer.Add(item = self.radioIau,
-                       flag = wx.ALIGN_LEFT, pos = (2, 1))
-        self.sizer.Add(item = self.radioFile,
-                       flag = wx.ALIGN_LEFT, pos = (3, 1))
-        self.sizer.Add(item = self.radioWkt,
-                       flag = wx.ALIGN_LEFT, pos = (4, 1))
-        self.sizer.Add(item = self.radioSrs,
-                       flag = wx.ALIGN_LEFT, pos = (5, 1))
-        self.sizer.Add(item = self.radioProj,
-                       flag = wx.ALIGN_LEFT, pos = (6, 1))
-        self.sizer.Add(item = self.radioXy,
-                       flag = wx.ALIGN_LEFT, pos = (7, 1))
+        self.sizer.Add(item=self.radioEpsg,
+                       flag=wx.ALIGN_LEFT, pos=(1, 1))
+        self.sizer.Add(item=self.radioIau,
+                       flag=wx.ALIGN_LEFT, pos=(2, 1))
+        self.sizer.Add(item=self.radioFile,
+                       flag=wx.ALIGN_LEFT, pos=(3, 1))
+        self.sizer.Add(item=self.radioWkt,
+                       flag=wx.ALIGN_LEFT, pos=(4, 1))
+        self.sizer.Add(item=self.radioSrs,
+                       flag=wx.ALIGN_LEFT, pos=(5, 1))
+        self.sizer.Add(item=self.radioProj,
+                       flag=wx.ALIGN_LEFT, pos=(6, 1))
+        self.sizer.Add(item=self.radioXy,
+                       flag=wx.ALIGN_LEFT, pos=(7, 1))
         self.sizer.AddGrowableCol(1)
 
         # bindings
-        self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id = self.radioEpsg.GetId())
-        self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id = self.radioIau.GetId())
-        self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id = self.radioFile.GetId())
-        self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id = self.radioWkt.GetId())
-        self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id = self.radioSrs.GetId())
-        self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id = self.radioProj.GetId())
-        self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id = self.radioXy.GetId())
-        self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED,  self.OnEnterPage)
-        
+        self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id=self.radioEpsg.GetId())
+        self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id=self.radioIau.GetId())
+        self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id=self.radioFile.GetId())
+        self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id=self.radioWkt.GetId())
+        self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id=self.radioSrs.GetId())
+        self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id=self.radioProj.GetId())
+        self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id=self.radioXy.GetId())
+        self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
+
     def OnEnterPage(self, event):
         global coordsys
-        
+
         if not coordsys:
             coordsys = "epsg"
             self.radioEpsg.SetValue(True)
@@ -290,7 +323,7 @@
                 self.radioProj.SetValue(True)
             if coordsys == "xy":
                 self.radioXy.SetValue(True)
-        
+
         if event.GetDirection():
             if coordsys == 'proj':
                 self.SetNext(self.parent.projpage)
@@ -313,10 +346,10 @@
             if coordsys == "xy":
                 self.SetNext(self.parent.sumpage)
                 self.parent.sumpage.SetPrev(self.parent.csystemspage)
-        
+
         if not wx.FindWindowById(wx.ID_FORWARD).IsEnabled():
             wx.FindWindowById(wx.ID_FORWARD).Enable()
-    
+
     def SetVal(self, event):
         """Choose method"""
         global coordsys
@@ -349,8 +382,10 @@
             self.SetNext(self.parent.sumpage)
             self.parent.sumpage.SetPrev(self.parent.csystemspage)
 
+
 class ProjectionsPage(TitledPage):
     """Wizard page for selecting projection (select coordinate system option)"""
+
     def __init__(self, wizard, parent):
         TitledPage.__init__(self, wizard, _("Choose projection"))
 
@@ -360,37 +395,37 @@
         self.p4proj = ''
 
         # text input
-        self.tproj = self.MakeTextCtrl("", size = (200,-1))
-        
+        self.tproj = self.MakeTextCtrl("", size=(200, -1))
+
         # search box
-        self.searchb = wx.SearchCtrl(self, size = (200,-1),
-                                     style = wx.TE_PROCESS_ENTER)
+        self.searchb = wx.SearchCtrl(self, size=(200, -1),
+                                     style=wx.TE_PROCESS_ENTER)
 
         # projection list
-        self.projlist = ItemList(self, data = self.parent.projdesc.items(),
-                                 columns = [_('Code'), _('Description')])
-        self.projlist.resizeLastColumn(30) 
+        self.projlist = ItemList(self, data=self.parent.projdesc.items(),
+                                 columns=[_('Code'), _('Description')])
+        self.projlist.resizeLastColumn(30)
 
         # layout
-        self.sizer.Add(item = self.MakeLabel(_("Projection code:")),
-                       flag = wx.ALIGN_LEFT |
+        self.sizer.Add(item=self.MakeLabel(_("Projection code:")),
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5, pos = (1, 1))
-        self.sizer.Add(item = self.tproj,
-                       flag = wx.ALIGN_RIGHT | wx.EXPAND | wx.ALL,
-                       border = 5, pos = (1, 2))
+                       wx.ALL, border=5, pos=(1, 1))
+        self.sizer.Add(item=self.tproj,
+                       flag=wx.ALIGN_RIGHT | wx.EXPAND | wx.ALL,
+                       border=5, pos=(1, 2))
 
-        self.sizer.Add(item = self.MakeLabel(_("Search in description:")),
-                       flag = wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
-                       border = 5, pos = (2, 1))
-        self.sizer.Add(item = self.searchb,
-                       flag = wx.ALIGN_RIGHT | wx.EXPAND | wx.ALL,
-                       border = 5, pos = (2, 2))
-        
-        self.sizer.Add(item = self.projlist,
-                       flag = wx.EXPAND |
+        self.sizer.Add(item=self.MakeLabel(_("Search in description:")),
+                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+                       border=5, pos=(2, 1))
+        self.sizer.Add(item=self.searchb,
+                       flag=wx.ALIGN_RIGHT | wx.EXPAND | wx.ALL,
+                       border=5, pos=(2, 2))
+
+        self.sizer.Add(item=self.projlist,
+                       flag=wx.EXPAND |
                        wx.ALIGN_LEFT |
-                       wx.ALL, border = 5, pos = (3, 1), span = (1, 3))
+                       wx.ALL, border=5, pos=(3, 1), span=(1, 3))
         self.sizer.AddGrowableCol(3)
         self.sizer.AddGrowableRow(3)
 
@@ -400,9 +435,9 @@
         self.searchb.Bind(wx.EVT_TEXT_ENTER, self.OnSearch)
         self.projlist.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
         self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
-        self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED,  self.OnEnterPage)
-        
-    def OnPageChanging(self,event):
+        self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
+
+    def OnPageChanging(self, event):
         if event.GetDirection() and self.proj not in self.parent.projections.keys():
             event.Veto()
 
@@ -413,13 +448,13 @@
         nextButton = wx.FindWindowById(wx.ID_FORWARD)
         if self.proj not in self.parent.projections.keys() and nextButton.IsEnabled():
             nextButton.Enable(False)
-        
+
         if self.proj in self.parent.projections.keys():
             if self.proj == 'stp':
-                wx.MessageBox('Currently State Plane projections must be selected using the '
-                              'text-based setup (g.setproj), or entered by EPSG code or '
-                              'custom PROJ.4 terms.',
-                              'Warning', wx.ICON_WARNING)
+                wx.MessageBox(
+                    'Currently State Plane projections must be selected using the '
+                    'text-based setup (g.setproj), or entered by EPSG code or '
+                    'custom PROJ.4 terms.', 'Warning', wx.ICON_WARNING)
                 self.proj = ''
                 self.tproj.SetValue(self.proj)
                 nextButton.Enable(False)
@@ -439,15 +474,16 @@
             wx.FindWindowById(wx.ID_FORWARD).Enable(True)
 
         event.Skip()
-    
+
     def OnSearch(self, event):
         """Search projection by desc"""
         str = event.GetString()
         try:
-            self.proj, self.projdesc = self.projlist.Search(index = [0,1], pattern = event.GetString())
+            self.proj, self.projdesc = self.projlist.Search(
+                index=[0, 1], pattern=event.GetString())
         except:
             self.proj = self.projdesc = ''
-            
+
         event.Skip()
 
     def OnItemSelected(self, event):
@@ -457,26 +493,27 @@
         # set values
         self.proj = self.projlist.GetItem(index, 0).GetText().lower()
         self.tproj.SetValue(self.proj)
-        
+
         event.Skip()
 
+
 class ItemList(wx.ListCtrl,
                listmix.ListCtrlAutoWidthMixin,
                listmix.ColumnSorterMixin):
     """Generic list (for projections, ellipsoids, etc.)"""
 
-    def __init__(self, parent, columns, data = None):
-        wx.ListCtrl.__init__(self, parent = parent, id = wx.ID_ANY,
-                             style = wx.LC_REPORT |
-                             wx.LC_VIRTUAL | 
+    def __init__(self, parent, columns, data=None):
+        wx.ListCtrl.__init__(self, parent=parent, id=wx.ID_ANY,
+                             style=wx.LC_REPORT |
+                             wx.LC_VIRTUAL |
                              wx.LC_HRULES |
                              wx.LC_VRULES |
                              wx.LC_SINGLE_SEL |
-                             wx.LC_SORT_ASCENDING, size = (550, 125))
+                             wx.LC_SORT_ASCENDING, size=(550, 125))
 
         # original data or None
         self.sourceData = data
-        
+
         #
         # insert columns
         #
@@ -488,47 +525,49 @@
         # add some attributes
         #
         self.attr1 = wx.ListItemAttr()
-        self.attr1.SetBackgroundColour(wx.Colour(238,238,238))
+        self.attr1.SetBackgroundColour(wx.Colour(238, 238, 238))
         self.attr2 = wx.ListItemAttr()
         self.attr2.SetBackgroundColour("white")
 
         if self.sourceData:
             self.Populate()
-        
+
         for i in range(self.GetColumnCount()):
             self.SetColumnWidth(i, wx.LIST_AUTOSIZE_USEHEADER)
             if self.GetColumnWidth(i) < 80:
                 self.SetColumnWidth(i, 80)
-        
+
         #
         # listmix
         #
         listmix.ListCtrlAutoWidthMixin.__init__(self)
         listmix.ColumnSorterMixin.__init__(self, self.GetColumnCount())
-            
+
         self.il = wx.ImageList(16, 16)
-        self.sm_up = self.il.Add(wx.ArtProvider_GetBitmap(wx.ART_GO_UP,   wx.ART_TOOLBAR,
-                                                          (16,16)))
-        self.sm_dn = self.il.Add(wx.ArtProvider_GetBitmap(wx.ART_GO_DOWN, wx.ART_TOOLBAR,
-                                                          (16,16)))
+        self.sm_up = self.il.Add(
+            wx.ArtProvider_GetBitmap(
+                wx.ART_GO_UP, wx.ART_TOOLBAR, (16, 16)))
+        self.sm_dn = self.il.Add(
+            wx.ArtProvider_GetBitmap(
+                wx.ART_GO_DOWN, wx.ART_TOOLBAR, (16, 16)))
         self.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
 
         #
         # sort by first column
         #
         if self.sourceData:
-            self.SortListItems(col = 0, ascending = True)
+            self.SortListItems(col=0, ascending=True)
 
         #
         # bindings
         #
         self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColumnClick)
 
-    def Populate(self, data = None, update = False):
+    def Populate(self, data=None, update=False):
         """Populate list"""
-        self.itemDataMap  = {}
+        self.itemDataMap = {}
         self.itemIndexMap = []
-        
+
         if data is None:
             data = self.sourceData
         elif update:
@@ -541,23 +580,23 @@
             for value in data:
                 self.itemDataMap[row] = [value[0]]
                 for i in range(1, len(value)):
-                     self.itemDataMap[row].append(value[i])
+                    self.itemDataMap[row].append(value[i])
                 self.itemIndexMap.append(row)
                 row += 1
 
             self.SetItemCount(row)
-            
+
             # set column width
             self.SetColumnWidth(0, 80)
             self.SetColumnWidth(1, 300)
-            
+
             self.SendSizeEvent()
-            
-        except StandardError as e:
-            wx.MessageBox(parent = self,
-                          message = _("Unable to read list: %s") % e,
-                          caption = _("Error"), style = wx.OK | wx.ICON_ERROR)
 
+        except Exception as e:
+            wx.MessageBox(parent=self,
+                          message=_("Unable to read list: %s") % e,
+                          caption=_("Error"), style=wx.OK | wx.ICON_ERROR)
+
     def OnColumnClick(self, event):
         """Sort by column"""
         self._col = event.GetColumn()
@@ -586,12 +625,12 @@
     def OnGetItemAttr(self, item):
         """Get item attributes"""
         index = self.itemIndexMap[item]
-        if ( index % 2) == 0:
+        if (index % 2) == 0:
             return self.attr2
         else:
             return self.attr1
 
-    def SortItems(self, sorter = cmp):
+    def SortItems(self, sorter=cmp):
         """Sort items"""
         items = list(self.itemDataMap.keys())
         items.sort(self.Sorter)
@@ -599,7 +638,7 @@
 
         # redraw the list
         self.Refresh()
-        
+
     def Sorter(self, key1, key2):
         colName = self.GetColumn(self._col).GetText()
         ascending = self._colSortFlag[self._col]
@@ -607,15 +646,15 @@
         item1 = self.itemDataMap[key1][self._col]
         item2 = self.itemDataMap[key2][self._col]
 
-        if type(item1) == type('') or type(item2) == type(''):
+        if isinstance(item1, type('')) or isinstance(item2, type('')):
             cmpVal = locale.strcoll(str(item1), str(item2))
         else:
             cmpVal = cmp(item1, item2)
 
-
-        # If the items are equal then pick something else to make the sort value unique
+        # If the items are equal then pick something else to make the sort
+        # value unique
         if cmpVal == 0:
-            cmpVal = apply(cmp, self.GetSecondarySortValues(self._col, key1, key2))
+            cmpVal = cmp(*self.GetSecondarySortValues(self._col, key1, key2))
 
         if ascending:
             return cmpVal
@@ -626,7 +665,7 @@
         """Used by listmix.ColumnSorterMixin"""
         return self
 
-    def Search (self, index, pattern):
+    def Search(self, index, pattern):
         """Search projection by description
         Return first found item or None
         """
@@ -653,59 +692,62 @@
         else:
             return []
 
+
 class ProjParamsPage(TitledPage):
     """Wizard page for selecting method of setting coordinate system
     parameters (select coordinate system option)
     """
+
     def __init__(self, wizard, parent):
         TitledPage.__init__(self, wizard, _("Choose projection parameters"))
         global coordsys
-        
+
         self.parent = parent
         self.panel = None
         self.prjParamSizer = None
-        
+
         self.pparam = dict()
-        
+
         self.p4projparams = ''
         self.projdesc = ''
 
-
-        radioSBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                                 label = " %s " % _("Select datum or ellipsoid (next page)"))
+        radioSBox = wx.StaticBox(
+            parent=self, id=wx.ID_ANY, label=" %s " %
+            _("Select datum or ellipsoid (next page)"))
         radioSBSizer = wx.StaticBoxSizer(radioSBox)
-        self.sizer.Add(item = radioSBSizer, pos = (0, 1),
-                       flag = wx.EXPAND | wx.ALIGN_TOP | wx.TOP, border = 10)
+        self.sizer.Add(item=radioSBSizer, pos=(0, 1),
+                       flag=wx.EXPAND | wx.ALIGN_TOP | wx.TOP, border=10)
         self.sizer.AddGrowableCol(1)
-        
-        self.radio1 = wx.RadioButton(parent = self, id = wx.ID_ANY, 
-                                     label = _("Datum with associated ellipsoid"),
-                                     style  =  wx.RB_GROUP)
-        self.radioEpsg = wx.RadioButton(parent = self, id = wx.ID_ANY,
-                                     label = _("Ellipsoid only"))   
-        
+
+        self.radio1 = wx.RadioButton(
+            parent=self, id=wx.ID_ANY,
+            label=_("Datum with associated ellipsoid"),
+            style=wx.RB_GROUP)
+        self.radioEpsg = wx.RadioButton(parent=self, id=wx.ID_ANY,
+                                        label=_("Ellipsoid only"))
+
         # default button setting
         if self.radio1.GetValue() == False and self.radioEpsg.GetValue() == False:
             self.radio1.SetValue(True)
             self.SetNext(self.parent.datumpage)
-            #            self.parent.sumpage.SetPrev(self.parent.datumpage)  
-        
-        radioSBSizer.Add(item = self.radio1,
-                         flag = wx.ALIGN_LEFT | wx.RIGHT, border = 20)
-        radioSBSizer.Add(item = self.radioEpsg,
-                         flag = wx.ALIGN_LEFT)
-        
+            #            self.parent.sumpage.SetPrev(self.parent.datumpage)
+
+        radioSBSizer.Add(item=self.radio1,
+                         flag=wx.ALIGN_LEFT | wx.RIGHT, border=20)
+        radioSBSizer.Add(item=self.radioEpsg,
+                         flag=wx.ALIGN_LEFT)
+
         # bindings
-        self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id = self.radio1.GetId())
-        self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id = self.radioEpsg.GetId())
+        self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id=self.radio1.GetId())
+        self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id=self.radioEpsg.GetId())
         self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChange)
         self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
-        
+
     def OnParamEntry(self, event):
         """Parameter value changed"""
-        id  = event.GetId()
+        id = event.GetId()
         val = event.GetString()
-        
+
         if id not in self.pparam:
             event.Skip()
             return
@@ -717,16 +759,16 @@
             if val < 1:
                 win.SetValue(1)
             elif val > 60:
-                    win.SetValue(60)
-        
+                win.SetValue(60)
+
         if param['type'] == 'bool':
             param['value'] = event.GetSelection()
         else:
             param['value'] = val
-        
+
         event.Skip()
-        
-    def OnPageChange(self,event=None):
+
+    def OnPageChange(self, event=None):
         """Go to next page"""
         if event.GetDirection():
             self.p4projparams = ''
@@ -738,98 +780,115 @@
                         self.p4projparams += (' +' + param['proj4'])
                 else:
                     if param['value'] is None:
-                        wx.MessageBox(parent = self,
-                                      message = _('You must enter a value for %s') % param['desc'],
-                                      caption = _('Error'), style = wx.ICON_ERROR | wx.CENTRE)
+                        wx.MessageBox(
+                            parent=self,
+                            message=_('You must enter a value for %s') %
+                            param['desc'],
+                            caption=_('Error'),
+                            style=wx.ICON_ERROR | wx.CENTRE)
                         event.Veto()
                     else:
-                        self.p4projparams += (' +' + param['proj4'] + '=' + str(param['value']))
+                        self.p4projparams += (' +' +
+                                              param['proj4'] +
+                                              '=' +
+                                              str(param['value']))
 
-    def OnEnterPage(self,event):
+    def OnEnterPage(self, event):
         """Page entered"""
         self.projdesc = self.parent.projections[self.parent.projpage.proj][0]
         if self.prjParamSizer is None:
             # entering page for the first time
-            self.paramSBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                                     label = _(" Enter parameters for %s projection ") % self.projdesc)
+            self.paramSBox = wx.StaticBox(
+                parent=self,
+                id=wx.ID_ANY,
+                label=_(" Enter parameters for %s projection ") %
+                self.projdesc)
             paramSBSizer = wx.StaticBoxSizer(self.paramSBox)
-            
-            self.panel = scrolled.ScrolledPanel(parent = self, id = wx.ID_ANY)
+
+            self.panel = scrolled.ScrolledPanel(parent=self, id=wx.ID_ANY)
             self.panel.SetupScrolling()
-            
-            self.prjParamSizer = wx.GridBagSizer(vgap = 0, hgap = 0) 
-            
-            self.sizer.Add(item = paramSBSizer, pos = (1, 1),
-                           flag = wx.EXPAND)
+
+            self.prjParamSizer = wx.GridBagSizer(vgap=0, hgap=0)
+
+            self.sizer.Add(item=paramSBSizer, pos=(1, 1),
+                           flag=wx.EXPAND)
             self.sizer.AddGrowableRow(1)
-            paramSBSizer.Add(item = self.panel, proportion = 1, 
-                             flag = wx.ALIGN_CENTER | wx.EXPAND)
-            
+            paramSBSizer.Add(item=self.panel, proportion=1,
+                             flag=wx.ALIGN_CENTER | wx.EXPAND)
+
             paramSBSizer.Fit(self.panel)
             self.panel.SetSizer(self.prjParamSizer)
-                    
+
         if event.GetDirection():
             self.prjParamSizer.Clear(True)
-            self.paramSBox.SetLabel(_(" Enter parameters for %s projection ") % self.projdesc)
+            self.paramSBox.SetLabel(
+                _(" Enter parameters for %s projection ") %
+                self.projdesc)
             self.pparam = dict()
             row = 0
-            for paramgrp in self.parent.projections[self.parent.projpage.proj][1]:
+            for paramgrp in self.parent.projections[
+                    self.parent.projpage.proj][1]:
                 # get parameters
                 id = wx.NewId()
-                param = self.pparam[id] = { 'type' : self.parent.paramdesc[paramgrp[0]][0],
-                                            'proj4': self.parent.paramdesc[paramgrp[0]][1],
-                                            'desc' : self.parent.paramdesc[paramgrp[0]][2] }
-                
+                param = self.pparam[id] = {
+                    'type': self.parent.paramdesc[
+                        paramgrp[0]][0], 'proj4': self.parent.paramdesc[
+                        paramgrp[0]][1], 'desc': self.parent.paramdesc[
+                        paramgrp[0]][2]}
+
                 # default values
                 if param['type'] == 'bool':
                     param['value'] = 0
                 elif param['type'] == 'zone':
-                    param['value'] = 30 
+                    param['value'] = 30
                     param['desc'] += ' (1-60)'
                 else:
                     param['value'] = paramgrp[2]
-                
-                label = wx.StaticText(parent = self.panel, id = wx.ID_ANY, label = param['desc'], 
-                                      style = wx.ALIGN_RIGHT | wx.ST_NO_AUTORESIZE)
+
+                label = wx.StaticText(
+                    parent=self.panel,
+                    id=wx.ID_ANY,
+                    label=param['desc'],
+                    style=wx.ALIGN_RIGHT | wx.ST_NO_AUTORESIZE)
                 if param['type'] == 'bool':
-                    win = wx.Choice(parent = self.panel, id = id, size = (100,-1), 
-                                    choices = [_('No'), _('Yes')])  
+                    win = wx.Choice(parent=self.panel, id=id, size=(100, -1),
+                                    choices=[_('No'), _('Yes')])
                     win.SetSelection(param['value'])
                     win.Bind(wx.EVT_CHOICE, self.OnParamEntry)
                 elif param['type'] == 'zone':
-                    win = wx.SpinCtrl(parent = self.panel, id = id,
-                                      size = (100, -1), 
-                                      style = wx.SP_ARROW_KEYS | wx.SP_WRAP,
-                                      min = 1, max = 60)
+                    win = wx.SpinCtrl(parent=self.panel, id=id,
+                                      size=(100, -1),
+                                      style=wx.SP_ARROW_KEYS | wx.SP_WRAP,
+                                      min=1, max=60)
                     win.SetValue(param['value'])
                     win.Bind(wx.EVT_SPINCTRL, self.OnParamEntry)
                     win.Bind(wx.EVT_TEXT, self.OnParamEntry)
                 else:
-                    win = wx.TextCtrl(parent = self.panel, id = id,
-                                      value = param['value'],
+                    win = wx.TextCtrl(parent=self.panel, id=id,
+                                      value=param['value'],
                                       size=(100, -1))
                     win.Bind(wx.EVT_TEXT, self.OnParamEntry)
                     if paramgrp[1] == 'noask':
                         win.Enable(False)
-                    
-                self.prjParamSizer.Add(item = label, pos = (row, 1),
-                                       flag = wx.ALIGN_RIGHT | 
+
+                self.prjParamSizer.Add(item=label, pos=(row, 1),
+                                       flag=wx.ALIGN_RIGHT |
                                        wx.ALIGN_CENTER_VERTICAL |
-                                       wx.RIGHT, border = 5)
-                self.prjParamSizer.Add(item = win, pos = (row, 2),
-                                       flag = wx.ALIGN_LEFT | 
+                                       wx.RIGHT, border=5)
+                self.prjParamSizer.Add(item=win, pos=(row, 2),
+                                       flag=wx.ALIGN_LEFT |
                                        wx.ALIGN_CENTER_VERTICAL |
-                                       wx.LEFT, border = 5)           
+                                       wx.LEFT, border=5)
                 row += 1
-        
+
         self.panel.SetSize(self.panel.GetBestSize())
         self.panel.Layout()
         self.Layout()
         self.Update()
-        
+
         if not wx.FindWindowById(wx.ID_FORWARD).IsEnabled():
             wx.FindWindowById(wx.ID_FORWARD).Enable()
-        
+
         event.Skip()
 
     def SetVal(self, event):
@@ -840,7 +899,8 @@
         elif event.GetId() == self.radioEpsg.GetId():
             self.SetNext(self.parent.ellipsepage)
             self.parent.sumpage.SetPrev(self.parent.ellipsepage)
-    
+
+
 class DatumPage(TitledPage):
     """Wizard page for selecting datum (with associated ellipsoid)
     and datum transformation parameters (select coordinate system option)
@@ -857,44 +917,45 @@
         self.proj4params = ''
 
         # text input
-        self.tdatum = self.MakeTextCtrl("", size = (200,-1))
+        self.tdatum = self.MakeTextCtrl("", size=(200, -1))
 
         # search box
-        self.searchb = wx.SearchCtrl(self, size = (200,-1),
-                                     style = wx.TE_PROCESS_ENTER)
+        self.searchb = wx.SearchCtrl(self, size=(200, -1),
+                                     style=wx.TE_PROCESS_ENTER)
 
         # create list control for datum/elipsoid list
         data = []
         for key in self.parent.datums.keys():
-            data.append([key, self.parent.datums[key][0], self.parent.datums[key][1]])
-        self.datumlist = ItemList(self,
-                                  data = data,
-                                  columns = [_('Code'), _('Ellipsoid'), _('Description')])
-        self.datumlist.resizeLastColumn(10) 
-        
+            data.append([key, self.parent.datums[key][
+                        0], self.parent.datums[key][1]])
+        self.datumlist = ItemList(
+            self, data=data, columns=[
+                _('Code'), _('Ellipsoid'), _('Description')])
+        self.datumlist.resizeLastColumn(10)
+
         # layout
-        self.sizer.Add(item = self.MakeLabel(_("Datum code:")),
-                       flag = wx.ALIGN_LEFT |
+        self.sizer.Add(item=self.MakeLabel(_("Datum code:")),
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5, pos = (1, 1))
-        self.sizer.Add(item = self.tdatum,
-                       flag = wx.ALIGN_LEFT |
+                       wx.ALL, border=5, pos=(1, 1))
+        self.sizer.Add(item=self.tdatum,
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5, pos = (1, 2))
+                       wx.ALL, border=5, pos=(1, 2))
 
-        self.sizer.Add(item = self.MakeLabel(_("Search in description:")),
-                       flag = wx.ALIGN_LEFT |
+        self.sizer.Add(item=self.MakeLabel(_("Search in description:")),
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5, pos = (2, 1))
-        self.sizer.Add(item = self.searchb,
-                       flag = wx.ALIGN_LEFT |
+                       wx.ALL, border=5, pos=(2, 1))
+        self.sizer.Add(item=self.searchb,
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5, pos = (2, 2))
+                       wx.ALL, border=5, pos=(2, 2))
 
-        self.sizer.Add(item = self.datumlist,
-                       flag = wx.EXPAND |
+        self.sizer.Add(item=self.datumlist,
+                       flag=wx.EXPAND |
                        wx.ALIGN_LEFT |
-                       wx.ALL, border = 5, pos = (3, 1), span = (1, 4))
+                       wx.ALL, border=5, pos=(3, 1), span=(1, 4))
         self.sizer.AddGrowableCol(4)
         self.sizer.AddGrowableRow(3)
 
@@ -912,25 +973,26 @@
     def OnPageChanging(self, event):
         self.proj4params = ''
         proj = self.parent.projpage.p4proj
-        
+
         if event.GetDirection():
             if self.datum not in self.parent.datums:
                 event.Veto()
             else:
-                # check for datum tranforms            
-#                proj4string = self.parent.CreateProj4String() + ' +datum=%s' % self.datum
+                # check for datum tranforms
+                #                proj4string = self.parent.CreateProj4String() + ' +datum=%s' % self.datum
                 ret = RunCommand('g.proj',
-                                 read = True,
-                                 proj4 = '%s' % proj,
-                                 datum = '%s' % self.datum, 
-                                 datum_trans = '-1',
-                                 flags = 't')
+                                 read=True,
+                                 proj4='%s' % proj,
+                                 datum='%s' % self.datum,
+                                 datum_trans='-1',
+                                 flags='t')
 #                wx.Messagebox('here')
                 if ret != '':
                     dtrans = ''
                     # open a dialog to select datum transform number
-                    dlg = SelectTransformDialog(self.parent.parent, transforms=ret)
-                    
+                    dlg = SelectTransformDialog(
+                        self.parent.parent, transforms=ret)
+
                     if dlg.ShowModal() == wx.ID_OK:
                         dtrans = dlg.GetTransform()
                         if dtrans == '':
@@ -941,18 +1003,20 @@
                         dlg.Destroy()
                         event.Veto()
                         return 'Datum transform is required.'
-                    
+
                     self.parent.datum_trans = dtrans
-                
+
             self.GetNext().SetPrev(self)
             self.parent.ellipsepage.ellipse = self.ellipse
-            self.parent.ellipsepage.ellipseparams = self.parent.ellipsoids[self.ellipse][1]
+            self.parent.ellipsepage.ellipseparams = self.parent.ellipsoids[
+                self.ellipse][1]
 
-    def OnEnterPage(self,event):
+    def OnEnterPage(self, event):
         self.parent.datum_trans = None
         if event.GetDirection():
             if len(self.datum) == 0:
-                # disable 'next' button by default when entering from previous page
+                # disable 'next' button by default when entering from previous
+                # page
                 wx.FindWindowById(wx.ID_FORWARD).Enable(False)
             else:
                 wx.FindWindowById(wx.ID_FORWARD).Enable(True)
@@ -982,17 +1046,22 @@
                 self.datumparams.remove('dz=0.0')
             except:
                 pass
-            
+
             nextButton.Enable(True)
-            
-        self.Update()    
+
+        self.Update()
         event.Skip()
 
     def OnDSearch(self, event):
         """Search geodetic datum by desc"""
-        str =  self.searchb.GetValue()
+        str = self.searchb.GetValue()
         try:
-            self.datum, self.ellipsoid, self.datumdesc = self.datumlist.Search(index = [0,1,2], pattern = str)
+            self.datum, self.ellipsoid, self.datumdesc = self.datumlist.Search(
+                index=[
+                    0,
+                    1,
+                    2],
+                pattern=str)
         except:
             self.datum = self.datumdesc = self.ellipsoid = ''
 
@@ -1005,9 +1074,10 @@
 
         self.datum = self.datumlist.GetItem(index, 0).GetText()
         self.tdatum.SetValue(self.datum)
-        
+
         event.Skip()
 
+
 class EllipsePage(TitledPage):
     """Wizard page for selecting ellipsoid (select coordinate system option)"""
 
@@ -1022,17 +1092,17 @@
         self.proj4params = ''
 
         # text input
-        self.tellipse = self.MakeTextCtrl("", size = (200,-1))
+        self.tellipse = self.MakeTextCtrl("", size=(200, -1))
 
         # search box
-        self.searchb = wx.SearchCtrl(self, size = (200,-1),
-                                     style = wx.TE_PROCESS_ENTER)
+        self.searchb = wx.SearchCtrl(self, size=(200, -1),
+                                     style=wx.TE_PROCESS_ENTER)
         # radio buttons
-        self.radio1 = wx.RadioButton(parent = self, id = wx.ID_ANY,
-                        label = _("Earth based"),
-                        style  =  wx.RB_GROUP)
-        self.radioEpsg = wx.RadioButton(parent = self, id = wx.ID_ANY,
-                        label = _("Planetary bodies"))
+        self.radio1 = wx.RadioButton(parent=self, id=wx.ID_ANY,
+                                     label=_("Earth based"),
+                                     style=wx.RB_GROUP)
+        self.radioEpsg = wx.RadioButton(parent=self, id=wx.ID_ANY,
+                                        label=_("Planetary bodies"))
 
         # create list control for ellipse list
         data = []
@@ -1040,40 +1110,40 @@
         for key in self.parent.ellipsoids.keys():
             data.append([key, self.parent.ellipsoids[key][0]])
 
-        self.ellipselist = ItemList(self, data = data,
-                                    columns = [_('Code'), _('Description')])
-        self.ellipselist.resizeLastColumn(30)                             
+        self.ellipselist = ItemList(self, data=data,
+                                    columns=[_('Code'), _('Description')])
+        self.ellipselist.resizeLastColumn(30)
 
         # layout
 
-        self.sizer.Add(item = self.MakeLabel(_("Ellipsoid code:")),
-                       flag = wx.ALIGN_RIGHT |
+        self.sizer.Add(item=self.MakeLabel(_("Ellipsoid code:")),
+                       flag=wx.ALIGN_RIGHT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5, pos = (1, 1))
-        self.sizer.Add(item = self.tellipse,
-                       flag = wx.ALIGN_LEFT |
+                       wx.ALL, border=5, pos=(1, 1))
+        self.sizer.Add(item=self.tellipse,
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5, pos = (1, 2))
-        self.sizer.Add(item = self.radio1,
-                       flag = wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.LEFT, 
-                       border = 25, pos = (1, 3))
+                       wx.ALL, border=5, pos=(1, 2))
+        self.sizer.Add(item=self.radio1,
+                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
+                       border=25, pos=(1, 3))
 
-        self.sizer.Add(item = self.MakeLabel(_("Search in description:")),
-                       flag = wx.ALIGN_RIGHT |
+        self.sizer.Add(item=self.MakeLabel(_("Search in description:")),
+                       flag=wx.ALIGN_RIGHT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5, pos = (2, 1))
-        self.sizer.Add(item = self.searchb,
-                       flag = wx.ALIGN_LEFT |
+                       wx.ALL, border=5, pos=(2, 1))
+        self.sizer.Add(item=self.searchb,
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5, pos = (2, 2))
-        self.sizer.Add(item = self.radioEpsg,
-                       flag = wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
-                       border = 25, pos = (2, 3))
+                       wx.ALL, border=5, pos=(2, 2))
+        self.sizer.Add(item=self.radioEpsg,
+                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
+                       border=25, pos=(2, 3))
 
-        self.sizer.Add(item = self.ellipselist,
-                       flag = wx.EXPAND |
+        self.sizer.Add(item=self.ellipselist,
+                       flag=wx.EXPAND |
                        wx.ALIGN_LEFT |
-                       wx.ALL, border = 5, pos = (3, 1), span = (1, 4))
+                       wx.ALL, border=5, pos=(3, 1), span=(1, 4))
         self.sizer.AddGrowableCol(4)
         self.sizer.AddGrowableRow(3)
 
@@ -1083,13 +1153,19 @@
         self.tellipse.Bind(wx.EVT_TEXT_ENTER, self.OnText)
         self.searchb.Bind(wx.EVT_TEXT_ENTER, self.OnSearch)
 
-        self.radio1.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id = self.radio1.GetId())
-        self.radioEpsg.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id = self.radioEpsg.GetId())
+        self.radio1.Bind(
+            wx.EVT_RADIOBUTTON,
+            self.SetVal,
+            id=self.radio1.GetId())
+        self.radioEpsg.Bind(
+            wx.EVT_RADIOBUTTON,
+            self.SetVal,
+            id=self.radioEpsg.GetId())
 
         self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
         self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
 
-    def OnEnterPage(self,event):
+    def OnEnterPage(self, event):
         if len(self.ellipse) == 0:
             # disable 'next' button by default
             wx.FindWindowById(wx.ID_FORWARD).Enable(False)
@@ -1100,25 +1176,26 @@
 
     def OnPageChanging(self, event):
         if event.GetDirection() \
-          and self.ellipse not in self.parent.ellipsoids \
-          and self.ellipse not in self.parent.planetary_ellipsoids:
+                and self.ellipse not in self.parent.ellipsoids \
+                and self.ellipse not in self.parent.planetary_ellipsoids:
             event.Veto()
 
-        #print self.ellipse, self.ellipsedesc, self.ellipseparams
+        # print self.ellipse, self.ellipsedesc, self.ellipseparams
 
         self.proj4params = ''
         self.GetNext().SetPrev(self)
         self.parent.datumpage.datumparams = ''
         # self.GetNext().SetPrev(self) (???)
 
-    #FIXME: index number doesn't translate when you've given a valid name from the other list
+    # FIXME: index number doesn't translate when you've given a valid name
+    # from the other list
     def OnText(self, event):
         """Ellipspoid code changed"""
         self.ellipse = event.GetString()
         nextButton = wx.FindWindowById(wx.ID_FORWARD)
         if len(self.ellipse) == 0 or \
-          (self.ellipse not in self.parent.ellipsoids and \
-           self.ellipse not in self.parent.planetary_ellipsoids):
+            (self.ellipse not in self.parent.ellipsoids and
+             self.ellipse not in self.parent.planetary_ellipsoids):
             nextButton.Enable(False)
             self.ellipsedesc = ''
             self.ellipseparams = ''
@@ -1128,33 +1205,36 @@
             self.ellipseparams = self.parent.ellipsoids[self.ellipse][1]
             nextButton.Enable(True)
         elif self.ellipse in self.parent.planetary_ellipsoids:
-            self.ellipsedesc = self.parent.planetary_ellipsoids[self.ellipse][0]
-            self.ellipseparams = self.parent.planetary_ellipsoids[self.ellipse][1]
+            self.ellipsedesc = self.parent.planetary_ellipsoids[
+                self.ellipse][0]
+            self.ellipseparams = self.parent.planetary_ellipsoids[
+                self.ellipse][1]
             nextButton.Enable(True)
-        #print self.ellipse, self.ellipsedesc, self.ellipseparams
+        # print self.ellipse, self.ellipsedesc, self.ellipseparams
 
     def OnSearch(self, event):
         """Search ellipsoid by desc"""
         try:
-            self.ellipse, self.ellipsedesc = \
-                self.ellipselist.Search(index=[0,1], pattern=event.GetString())
+            self.ellipse, self.ellipsedesc = self.ellipselist.Search(
+                index=[0, 1], pattern=event.GetString())
             if self.scope is 'earth':
                 self.ellipseparams = self.parent.ellipsoids[self.ellipse][1]
             else:
-                self.ellipseparams = self.parent.planetary_ellipsoids[self.ellipse][1]
+                self.ellipseparams = self.parent.planetary_ellipsoids[
+                    self.ellipse][1]
         except:
             self.ellipse = self.ellipsedesc = self.ellipseparams = ''
 
         event.Skip()
 
-    def OnItemSelected(self,event):
+    def OnItemSelected(self, event):
         """Ellipsoid selected"""
         index = event.m_itemIndex
         item = event.GetItem()
 
         self.ellipse = self.ellipselist.GetItem(index, 0).GetText()
         self.tellipse.SetValue(self.ellipse)
-        
+
         event.Skip()
 
     def SetVal(self, event):
@@ -1170,7 +1250,7 @@
             for key in self.parent.planetary_ellipsoids.keys():
                 data.append([key, self.parent.planetary_ellipsoids[key][0]])
 
-        self.ellipselist.Populate(data = data, update = True)
+        self.ellipselist.Populate(data=data, update=True)
 
 
 class GeoreferencedFilePage(TitledPage):
@@ -1183,19 +1263,19 @@
         self.georeffile = ''
 
         # create controls
-        self.lfile= self.MakeLabel(_("Georeferenced file:"))
-        self.tfile = self.MakeTextCtrl(size = (300,-1))
+        self.lfile = self.MakeLabel(_("Georeferenced file:"))
+        self.tfile = self.MakeTextCtrl(size=(300, -1))
         self.bbrowse = self.MakeButton(_("Browse"))
 
         # do layout
-        self.sizer.Add(item = self.lfile, flag = wx.ALIGN_LEFT |
+        self.sizer.Add(item=self.lfile, flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTRE_VERTICAL |
-                       wx.ALL, border = 5, pos = (1, 1))
-        self.sizer.Add(item = self.tfile, flag = wx.ALIGN_LEFT |
+                       wx.ALL, border=5, pos=(1, 1))
+        self.sizer.Add(item=self.tfile, flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTRE_VERTICAL |
-                       wx.ALL, border = 5, pos = (1, 2))
-        self.sizer.Add(item = self.bbrowse, flag = wx.ALIGN_LEFT |
-                       wx.ALL, border = 5, pos = (1, 3))
+                       wx.ALL, border=5, pos=(1, 2))
+        self.sizer.Add(item=self.bbrowse, flag=wx.ALIGN_LEFT |
+                       wx.ALL, border=5, pos=(1, 3))
         self.sizer.AddGrowableCol(3)
 
         self.bbrowse.Bind(wx.EVT_BUTTON, self.OnBrowse)
@@ -1247,29 +1327,31 @@
 
         event.Skip()
 
+
 class WKTPage(TitledPage):
     """Wizard page for selecting WKT file to use
     for setting coordinate system parameters"""
 
     def __init__(self, wizard, parent):
-        TitledPage.__init__(self, wizard, _("Select Well Known Text (WKT) .prj file"))
+        TitledPage.__init__(self, wizard, _(
+            "Select Well Known Text (WKT) .prj file"))
 
         self.wktfile = ''
 
         # create controls
-        self.lfile= self.MakeLabel(_("WKT .prj file:"))
-        self.tfile = self.MakeTextCtrl(size = (300,-1))
+        self.lfile = self.MakeLabel(_("WKT .prj file:"))
+        self.tfile = self.MakeTextCtrl(size=(300, -1))
         self.bbrowse = self.MakeButton(_("Browse"))
 
         # do layout
-        self.sizer.Add(item = self.lfile, flag = wx.ALIGN_LEFT |
+        self.sizer.Add(item=self.lfile, flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTRE_VERTICAL |
-                       wx.ALL, border = 5, pos = (1, 1))
-        self.sizer.Add(item = self.tfile, flag = wx.ALIGN_LEFT |
+                       wx.ALL, border=5, pos=(1, 1))
+        self.sizer.Add(item=self.tfile, flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTRE_VERTICAL |
-                       wx.ALL, border = 5, pos = (1, 2))
-        self.sizer.Add(item = self.bbrowse, flag = wx.ALIGN_LEFT |
-                       wx.ALL, border = 5, pos = (1, 3))
+                       wx.ALL, border=5, pos=(1, 2))
+        self.sizer.Add(item=self.bbrowse, flag=wx.ALIGN_LEFT |
+                       wx.ALL, border=5, pos=(1, 3))
         self.sizer.AddGrowableCol(3)
 
         self.bbrowse.Bind(wx.EVT_BUTTON, self.OnBrowse)
@@ -1308,11 +1390,12 @@
 
     def OnBrowse(self, event):
         """Choose file"""
-        dlg = wx.FileDialog(parent = self,
-                            message = _("Select Well Known Text (WKT) .prj file"),
-                            defaultDir = os.getcwd(),
-                            wildcard = "PRJ files (*.prj)|*.prj|Files (*.*)|*.*",
-                            style = wx.FD_OPEN)
+        dlg = wx.FileDialog(
+            parent=self,
+            message=_("Select Well Known Text (WKT) .prj file"),
+            defaultDir=os.getcwd(),
+            wildcard="PRJ files (*.prj)|*.prj|Files (*.*)|*.*",
+            style=wx.FD_OPEN)
 
         if dlg.ShowModal() == wx.ID_OK:
             path = dlg.GetPath()
@@ -1321,6 +1404,7 @@
 
         event.Skip()
 
+
 class EPSGPage(TitledPage):
     """Wizard page for selecting EPSG code for
     setting coordinate system parameters"""
@@ -1334,55 +1418,62 @@
         self.epsgparams = ''
 
         # labels
-        self.lfile = self.MakeLabel(_("Path to the EPSG-codes file:"),
-                                    style = wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
-        self.lcode = self.MakeLabel(_("EPSG code:"),
-                                    style = wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
+        self.lfile = self.MakeLabel(
+            _("Path to the EPSG-codes file:"),
+            style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
+        self.lcode = self.MakeLabel(
+            _("EPSG code:"),
+            style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
         # text input
         epsgdir = utils.PathJoin(os.environ["GRASS_PROJSHARE"], 'epsg')
-        self.tfile = self.MakeTextCtrl(text = epsgdir, size = (200,-1),
-                                       style = wx.TE_PROCESS_ENTER)
-        self.tcode = self.MakeTextCtrl(size = (200,-1))
+        self.tfile = self.MakeTextCtrl(text=epsgdir, size=(200, -1),
+                                       style=wx.TE_PROCESS_ENTER)
+        self.tcode = self.MakeTextCtrl(size=(200, -1))
 
         # buttons
         self.bbrowse = self.MakeButton(_("Browse"))
-        
+
         # search box
-        self.searchb = wx.SearchCtrl(self, size = (200,-1),
-                                     style = wx.TE_PROCESS_ENTER)
+        self.searchb = wx.SearchCtrl(self, size=(200, -1),
+                                     style=wx.TE_PROCESS_ENTER)
 
-        self.epsglist = ItemList(self, data = None,
-                                 columns = [_('Code'), _('Description'), _('Parameters')])
+        self.epsglist = ItemList(
+            self,
+            data=None,
+            columns=[
+                _('Code'),
+                _('Description'),
+                _('Parameters')])
 
         # layout
-        self.sizer.Add(item = self.lfile,
-                       flag = wx.ALIGN_LEFT |
+        self.sizer.Add(item=self.lfile,
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5, pos = (1, 1), span = (1, 2))
-        self.sizer.Add(item = self.tfile,
-                       flag = wx.ALIGN_LEFT |
+                       wx.ALL, border=5, pos=(1, 1), span=(1, 2))
+        self.sizer.Add(item=self.tfile,
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5, pos = (1, 3))
-        self.sizer.Add(item = self.bbrowse,
-                       flag = wx.ALIGN_LEFT |
+                       wx.ALL, border=5, pos=(1, 3))
+        self.sizer.Add(item=self.bbrowse,
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5, pos = (1, 4))
-        self.sizer.Add(item = self.lcode,
-                       flag = wx.ALIGN_LEFT |
+                       wx.ALL, border=5, pos=(1, 4))
+        self.sizer.Add(item=self.lcode,
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5, pos = (2, 1), span = (1, 2))
-        self.sizer.Add(item = self.tcode,
-                       flag = wx.ALIGN_LEFT |
+                       wx.ALL, border=5, pos=(2, 1), span=(1, 2))
+        self.sizer.Add(item=self.tcode,
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5, pos = (2, 3))
-        self.sizer.Add(item = self.searchb,
-                       flag = wx.ALIGN_LEFT |
+                       wx.ALL, border=5, pos=(2, 3))
+        self.sizer.Add(item=self.searchb,
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5, pos = (3, 3))
-        
-        self.sizer.Add(item = self.epsglist,
-                       flag = wx.ALIGN_LEFT | wx.EXPAND, pos = (4, 1),
-                       span = (1, 4))
+                       wx.ALL, border=5, pos=(3, 3))
+
+        self.sizer.Add(item=self.epsglist,
+                       flag=wx.ALIGN_LEFT | wx.EXPAND, pos=(4, 1),
+                       span=(1, 4))
         self.sizer.AddGrowableCol(3)
         self.sizer.AddGrowableRow(4)
 
@@ -1407,7 +1498,7 @@
 
         # load default epsg database file
         self.OnBrowseCodes(None)
-        
+
         event.Skip()
 
     def OnPageChanging(self, event):
@@ -1418,16 +1509,17 @@
             else:
                 # check for datum transforms
                 ret = RunCommand('g.proj',
-                                 read = True,
-                                 epsg = self.epsgcode,
-                                 datum_trans = '-1',
-                                 flags = 't')
-                
+                                 read=True,
+                                 epsg=self.epsgcode,
+                                 datum_trans='-1',
+                                 flags='t')
+
                 if ret != '':
                     dtrans = ''
                     # open a dialog to select datum transform number
-                    dlg = SelectTransformDialog(self.parent.parent, transforms = ret)
-                    
+                    dlg = SelectTransformDialog(
+                        self.parent.parent, transforms=ret)
+
                     if dlg.ShowModal() == wx.ID_OK:
                         dtrans = dlg.GetTransform()
                         if dtrans == '':
@@ -1438,7 +1530,7 @@
                         dlg.Destroy()
                         event.Veto()
                         return 'Datum transform is required.'
-                    
+
                     self.parent.datum_trans = dtrans
             self.GetNext().SetPrev(self)
 
@@ -1448,9 +1540,9 @@
             self.epsgcode = int(self.epsgcode)
         except:
             self.epsgcode = None
-            
+
         nextButton = wx.FindWindowById(wx.ID_FORWARD)
-        
+
         if self.epsgcode and self.epsgCodeDict and \
                 self.epsgcode in self.epsgCodeDict.keys():
             self.epsgdesc = self.epsgCodeDict[self.epsgcode][0]
@@ -1458,14 +1550,14 @@
             if not nextButton.IsEnabled():
                 nextButton.Enable(True)
         else:
-            self.epsgcode = None # not found
+            self.epsgcode = None  # not found
             if nextButton.IsEnabled():
                 nextButton.Enable(False)
             self.epsgdesc = self.epsgparams = ''
-        
+
     def OnSearch(self, event):
-        value =  self.searchb.GetValue()
-        
+        value = self.searchb.GetValue()
+
         if value == '':
             self.epsgcode = None
             self.epsgdesc = self.epsgparams = ''
@@ -1475,28 +1567,33 @@
         else:
             try:
                 self.epsgcode, self.epsgdesc, self.epsgparams = \
-                        self.epsglist.Search(index=[0,1,2], pattern=value)
-            except (IndexError, ValueError): # -> no item found
+                    self.epsglist.Search(index=[0, 1, 2], pattern=value)
+            except (IndexError, ValueError):  # -> no item found
                 self.epsgcode = None
                 self.epsgdesc = self.epsgparams = ''
                 self.tcode.SetValue('')
 
         event.Skip()
-        
+
     def OnBrowse(self, event):
         """Define path for EPSG code file"""
         path = os.path.dirname(self.tfile.GetValue())
         if not path:
             path = os.getcwd()
-        
-        dlg = wx.FileDialog(parent = self, message = _("Choose EPSG codes file"),
-                            defaultDir = path, defaultFile = "", wildcard = "*", style = wx.FD_OPEN)
-        
+
+        dlg = wx.FileDialog(
+            parent=self,
+            message=_("Choose EPSG codes file"),
+            defaultDir=path,
+            defaultFile="",
+            wildcard="*",
+            style=wx.FD_OPEN)
+
         if dlg.ShowModal() == wx.ID_OK:
             path = dlg.GetPath()
             self.tfile.SetValue(path)
             self.OnBrowseCodes(None)
-        
+
         dlg.Destroy()
 
         event.Skip()
@@ -1511,24 +1608,27 @@
         self.tcode.SetValue(str(self.epsgcode))
 
         event.Skip()
-        
-    def OnBrowseCodes(self, event, search = None):
+
+    def OnBrowseCodes(self, event, search=None):
         """Browse EPSG codes"""
         try:
             self.epsgCodeDict = utils.ReadEpsgCodes(self.tfile.GetValue())
         except OpenError as e:
-            GError(parent = self,
-                   message = _("Unable to read EPGS codes: {}").format(e), showTraceback=False)
-            self.epsglist.Populate(list(), update = True)
+            GError(
+                parent=self,
+                message=_("Unable to read EPGS codes: {}").format(e),
+                showTraceback=False)
+            self.epsglist.Populate(list(), update=True)
             return
-        
+
         data = list()
         for code, val in self.epsgCodeDict.iteritems():
             if code is not None:
                 data.append((code, val[0], val[1]))
-        
-        self.epsglist.Populate(data, update = True)
 
+        self.epsglist.Populate(data, update=True)
+
+
 class IAUPage(TitledPage):
     """Wizard page for selecting IAU code/WKT for
     setting coordinate system parameters"""
@@ -1542,55 +1642,66 @@
         self.epsgparams = ''
 
         # labels
-        self.lfile = self.MakeLabel(_("Path to the IAU-codes file:"),
-                                    style = wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
-        self.lcode = self.MakeLabel(_("IAU code:"),
-                                    style = wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
+        self.lfile = self.MakeLabel(
+            _("Path to the IAU-codes file:"),
+            style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
+        self.lcode = self.MakeLabel(
+            _("IAU code:"),
+            style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
         # text input
-        epsgdir = utils.PathJoin(globalvar.ETCDIR,"proj","ogr_csv",'iau2009.csv')
-        self.tfile = self.MakeTextCtrl(text = epsgdir, size = (200,-1),
-                                       style = wx.TE_PROCESS_ENTER)
-        self.tcode = self.MakeTextCtrl(size = (200,-1))
+        epsgdir = utils.PathJoin(
+            globalvar.ETCDIR,
+            "proj",
+            "ogr_csv",
+            'iau2009.csv')
+        self.tfile = self.MakeTextCtrl(text=epsgdir, size=(200, -1),
+                                       style=wx.TE_PROCESS_ENTER)
+        self.tcode = self.MakeTextCtrl(size=(200, -1))
 
         # buttons
         self.bbrowse = self.MakeButton(_("Browse"))
-        
+
         # search box
-        self.searchb = wx.SearchCtrl(self, size = (200,-1),
-                                     style = wx.TE_PROCESS_ENTER)
+        self.searchb = wx.SearchCtrl(self, size=(200, -1),
+                                     style=wx.TE_PROCESS_ENTER)
 
-        self.epsglist = ItemList(self, data = None,
-                                 columns = [_('Code'), _('Description'), _('Parameters')])
+        self.epsglist = ItemList(
+            self,
+            data=None,
+            columns=[
+                _('Code'),
+                _('Description'),
+                _('Parameters')])
 
         # layout
-        self.sizer.Add(item = self.lfile,
-                       flag = wx.ALIGN_LEFT |
+        self.sizer.Add(item=self.lfile,
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5, pos = (1, 1), span = (1, 2))
-        self.sizer.Add(item = self.tfile,
-                       flag = wx.ALIGN_LEFT |
+                       wx.ALL, border=5, pos=(1, 1), span=(1, 2))
+        self.sizer.Add(item=self.tfile,
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5, pos = (1, 3))
-        self.sizer.Add(item = self.bbrowse,
-                       flag = wx.ALIGN_LEFT |
+                       wx.ALL, border=5, pos=(1, 3))
+        self.sizer.Add(item=self.bbrowse,
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5, pos = (1, 4))
-        self.sizer.Add(item = self.lcode,
-                       flag = wx.ALIGN_LEFT |
+                       wx.ALL, border=5, pos=(1, 4))
+        self.sizer.Add(item=self.lcode,
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5, pos = (2, 1), span = (1, 2))
-        self.sizer.Add(item = self.tcode,
-                       flag = wx.ALIGN_LEFT |
+                       wx.ALL, border=5, pos=(2, 1), span=(1, 2))
+        self.sizer.Add(item=self.tcode,
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5, pos = (2, 3))
-        self.sizer.Add(item = self.searchb,
-                       flag = wx.ALIGN_LEFT |
+                       wx.ALL, border=5, pos=(2, 3))
+        self.sizer.Add(item=self.searchb,
+                       flag=wx.ALIGN_LEFT |
                        wx.ALIGN_CENTER_VERTICAL |
-                       wx.ALL, border = 5, pos = (3, 3))
-        
-        self.sizer.Add(item = self.epsglist,
-                       flag = wx.ALIGN_LEFT | wx.EXPAND, pos = (4, 1),
-                       span = (1, 4))
+                       wx.ALL, border=5, pos=(3, 3))
+
+        self.sizer.Add(item=self.epsglist,
+                       flag=wx.ALIGN_LEFT | wx.EXPAND, pos=(4, 1),
+                       span=(1, 4))
         self.sizer.AddGrowableCol(3)
         self.sizer.AddGrowableRow(4)
 
@@ -1615,7 +1726,7 @@
 
         # load default epsg database file
         self.OnBrowseCodes(None)
-        
+
         event.Skip()
 
     def OnPageChanging(self, event):
@@ -1626,16 +1737,17 @@
             else:
                 # check for datum transforms
                 ret = RunCommand('g.proj',
-                                 read = True,
-                                 proj4 = self.epsgparams,
-                                 datum_trans = '-1',
-                                 flags = 't')
-                
+                                 read=True,
+                                 proj4=self.epsgparams,
+                                 datum_trans='-1',
+                                 flags='t')
+
                 if ret != '':
                     dtrans = ''
                     # open a dialog to select datum transform number
-                    dlg = SelectTransformDialog(self.parent.parent, transforms = ret)
-                    
+                    dlg = SelectTransformDialog(
+                        self.parent.parent, transforms=ret)
+
                     if dlg.ShowModal() == wx.ID_OK:
                         dtrans = dlg.GetTransform()
                         if dtrans == '':
@@ -1646,21 +1758,22 @@
                         dlg.Destroy()
                         event.Veto()
                         return 'Datum transform is required.'
-                    
+
                     self.parent.datum_trans = dtrans
                     self.parent.epsgcode = self.epsgcode
                     self.parent.epsgdesc = self.epsgdesc
 
-                # prepare +nadgrids or +towgs84 terms for Summary page. first convert them:
-                ret, projlabel, err = RunCommand('g.proj',
-                                                 flags = 'jft',
-                                                 proj4 = self.epsgparams,
-                                                 datum_trans = self.parent.datum_trans,
-                                                 getErrorMsg = True,
-                                                 read = True)
-                # splitting on space alone would break for grid files with space in pathname
+                # prepare +nadgrids or +towgs84 terms for Summary page. first
+                # convert them:
+                ret, projlabel, err = RunCommand(
+                    'g.proj', flags='jft', proj4=self.epsgparams,
+                    datum_trans=self.parent.datum_trans, getErrorMsg=True,
+                    read=True)
+                # splitting on space alone would break for grid files with
+                # space in pathname
                 for projterm in projlabel.split(' +'):
-                    if projterm.find("towgs84=") != -1 or projterm.find("nadgrids=") != -1:
+                    if projterm.find(
+                            "towgs84=") != -1 or projterm.find("nadgrids=") != -1:
                         self.custom_dtrans_string = ' +%s' % projterm
                         break
 
@@ -1672,24 +1785,24 @@
             self.epsgcode = int(self.epsgcode)
         except:
             self.epsgcode = None
-            
+
         nextButton = wx.FindWindowById(wx.ID_FORWARD)
 
-        #if self.epsgcode and self.epsgcode in self.epsgCodeDict.keys():
+        # if self.epsgcode and self.epsgcode in self.epsgCodeDict.keys():
         if self.epsgcode:
             self.epsgdesc = self.epsgCodeDict[self.epsgcode][0]
             self.epsgparams = self.epsgCodeDict[self.epsgcode][1]
             if not nextButton.IsEnabled():
                 nextButton.Enable(True)
         else:
-            self.epsgcode = None # not found
+            self.epsgcode = None  # not found
             if nextButton.IsEnabled():
                 nextButton.Enable(False)
             self.epsgdesc = self.epsgparams = ''
-        
+
     def OnSearch(self, event):
-        value =  self.searchb.GetValue()
-        
+        value = self.searchb.GetValue()
+
         if value == '':
             self.epsgcode = None
             self.epsgdesc = self.epsgparams = ''
@@ -1699,28 +1812,33 @@
         else:
             try:
                 self.epsgcode, self.epsgdesc, self.epsgparams = \
-                        self.epsglist.Search(index=[0,1,2], pattern=value)
-            except (IndexError, ValueError): # -> no item found
+                    self.epsglist.Search(index=[0, 1, 2], pattern=value)
+            except (IndexError, ValueError):  # -> no item found
                 self.epsgcode = None
                 self.epsgdesc = self.epsgparams = ''
                 self.tcode.SetValue('')
 
         event.Skip()
-        
+
     def OnBrowse(self, event):
         """Define path for IAU code file"""
         path = os.path.dirname(self.tfile.GetValue())
         if not path:
             path = os.getcwd()
-        
-        dlg = wx.FileDialog(parent = self, message = _("Choose IAU codes file"),
-                            defaultDir = path, defaultFile = "", wildcard = "*", style = wx.FD_OPEN)
-        
+
+        dlg = wx.FileDialog(
+            parent=self,
+            message=_("Choose IAU codes file"),
+            defaultDir=path,
+            defaultFile="",
+            wildcard="*",
+            style=wx.FD_OPEN)
+
         if dlg.ShowModal() == wx.ID_OK:
             path = dlg.GetPath()
             self.tfile.SetValue(path)
             self.OnBrowseCodes(None)
-        
+
         dlg.Destroy()
 
         event.Skip()
@@ -1731,53 +1849,58 @@
         item = event.GetItem()
 
         self.epsgcode = int(self.epsglist.GetItem(index, 0).GetText())
-	#This is here that the index 2 (aka WKT) should be loaded in a variable
+        # This is here that the index 2 (aka WKT) should be loaded in a
+        # variable
         self.epsgdesc = self.epsglist.GetItem(index, 1).GetText()
         self.tcode.SetValue(str(self.epsgcode))
 
         event.Skip()
-        
-    def OnBrowseCodes(self, event, search = None):
+
+    def OnBrowseCodes(self, event, search=None):
         """Browse IAU codes"""
         try:
             self.epsgCodeDict = utils.ReadEpsgCodes(self.tfile.GetValue())
         except OpenError as e:
-            GError(parent = self,
-                   message = _("Unable to read IAU codes: {}").format(e), showTraceback=False)
-            self.epsglist.Populate(list(), update = True)
+            GError(
+                parent=self,
+                message=_("Unable to read IAU codes: {}").format(e),
+                showTraceback=False)
+            self.epsglist.Populate(list(), update=True)
             return
-        
+
         data = list()
         for code, val in self.epsgCodeDict.iteritems():
             if code is not None:
                 data.append((code, val[0], val[1]))
-        
-        self.epsglist.Populate(data, update = True)
 
-        
+        self.epsglist.Populate(data, update=True)
+
+
 class CustomPage(TitledPage):
     """Wizard page for entering custom PROJ.4 string
     for setting coordinate system parameters"""
 
     def __init__(self, wizard, parent):
-        TitledPage.__init__(self, wizard,
-                            _("Choose method of specifying georeferencing parameters"))
+        TitledPage.__init__(
+            self, wizard,
+            _("Choose method of specifying georeferencing parameters"))
         global coordsys
         self.customstring = ''
         self.parent = parent
 
         # widgets
-        self.text_proj4string = self.MakeTextCtrl(size = (400, 200),
-                                                  style = wx.TE_MULTILINE)
-        self.label_proj4string = self.MakeLabel(_("Enter PROJ.4 parameters string:"))
+        self.text_proj4string = self.MakeTextCtrl(size=(400, 200),
+                                                  style=wx.TE_MULTILINE)
+        self.label_proj4string = self.MakeLabel(
+            _("Enter PROJ.4 parameters string:"))
 
         # layout
         self.sizer.Add(self.label_proj4string,
-                       flag = wx.ALIGN_LEFT | wx.ALL,
-                       border = 5, pos = (1, 1))
+                       flag=wx.ALIGN_LEFT | wx.ALL,
+                       border=5, pos=(1, 1))
         self.sizer.Add(self.text_proj4string,
-                       flag = wx.ALIGN_LEFT | wx.ALL | wx.EXPAND, 
-                       border = 5, pos = (2, 1), span = (1, 2))
+                       flag=wx.ALIGN_LEFT | wx.ALL | wx.EXPAND,
+                       border=5, pos=(2, 1), span=(1, 2))
         self.sizer.AddGrowableRow(2)
         self.sizer.AddGrowableCol(2)
 
@@ -1803,22 +1926,22 @@
             # check for datum tranforms
             # FIXME: -t flag is a hack-around for trac bug #1849
             ret, out, err = RunCommand('g.proj',
-                                       read = True, getErrorMsg = True,
-                                       proj4 = self.customstring, 
-                                       datum_trans = '-1',
-                                       flags = 't')
+                                       read=True, getErrorMsg=True,
+                                       proj4=self.customstring,
+                                       datum_trans='-1',
+                                       flags='t')
             if ret != 0:
-                wx.MessageBox(parent = self,
-                              message = err,
-                              caption = _("Error"),
-                              style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
+                wx.MessageBox(parent=self,
+                              message=err,
+                              caption=_("Error"),
+                              style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
                 event.Veto()
                 return
 
             if out:
                 dtrans = ''
                 # open a dialog to select datum transform number
-                dlg = SelectTransformDialog(self.parent.parent, transforms = out)
+                dlg = SelectTransformDialog(self.parent.parent, transforms=out)
 
                 if dlg.ShowModal() == wx.ID_OK:
                     dtrans = dlg.GetTransform()
@@ -1830,24 +1953,27 @@
                     dlg.Destroy()
                     event.Veto()
                     return _('Datum transform is required.')
-                
+
                 self.parent.datum_trans = dtrans
 
-                # prepare +nadgrids or +towgs84 terms for Summary page. first convert them:
+                # prepare +nadgrids or +towgs84 terms for Summary page. first
+                # convert them:
                 ret, projlabel, err = RunCommand('g.proj',
-                                                 flags = 'jft',
-                                                 proj4 = self.customstring,
-                                                 datum_trans = dtrans,
-                                                 getErrorMsg = True,
-                                                 read = True)
-                # splitting on space alone would break for grid files with space in pathname
+                                                 flags='jft',
+                                                 proj4=self.customstring,
+                                                 datum_trans=dtrans,
+                                                 getErrorMsg=True,
+                                                 read=True)
+                # splitting on space alone would break for grid files with
+                # space in pathname
                 for projterm in projlabel.split(' +'):
-                    if projterm.find("towgs84=") != -1 or projterm.find("nadgrids=") != -1:
+                    if projterm.find(
+                            "towgs84=") != -1 or projterm.find("nadgrids=") != -1:
                         self.custom_dtrans_string = ' +%s' % projterm
                         break
 
         self.GetNext().SetPrev(self)
-            
+
     def GetProjstring(self, event):
         """Change proj string"""
         # TODO: check PROJ.4 syntax
@@ -1860,86 +1986,94 @@
             if not nextButton.IsEnabled():
                 nextButton.Enable()
 
+
 class SummaryPage(TitledPage):
     """Shows summary result of choosing coordinate system parameters
     prior to creating location"""
+
     def __init__(self, wizard, parent):
         TitledPage.__init__(self, wizard, _("Summary"))
         self.parent = parent
 
-        self.panelTitle = scrolled.ScrolledPanel(parent = self, id = wx.ID_ANY)
-        self.panelProj4string = scrolled.ScrolledPanel(parent = self, id = wx.ID_ANY)
-        self.panelProj = scrolled.ScrolledPanel(parent = self, id = wx.ID_ANY)
+        self.panelTitle = scrolled.ScrolledPanel(parent=self, id=wx.ID_ANY)
+        self.panelProj4string = scrolled.ScrolledPanel(
+            parent=self, id=wx.ID_ANY)
+        self.panelProj = scrolled.ScrolledPanel(parent=self, id=wx.ID_ANY)
 
         # labels
-        self.ldatabase    = self.MakeLabel()
-        self.llocation    = self.MakeLabel()
-        self.llocTitle    = self.MakeLabel(parent = self.panelTitle)
-        self.lprojection  = self.MakeLabel(parent = self.panelProj)
-        self.lproj4string = self.MakeLabel(parent = self.panelProj4string)
-        
+        self.ldatabase = self.MakeLabel()
+        self.llocation = self.MakeLabel()
+        self.llocTitle = self.MakeLabel(parent=self.panelTitle)
+        self.lprojection = self.MakeLabel(parent=self.panelProj)
+        self.lproj4string = self.MakeLabel(parent=self.panelProj4string)
+
         self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
-        
+
         # do sub-page layout
         self._doLayout()
-        
+
     def _doLayout(self):
         """Do page layout"""
 
         titleSizer = wx.BoxSizer(wx.VERTICAL)
-        titleSizer.Add(item = self.llocTitle, proportion = 1,
-                       flag = wx.EXPAND | wx.ALL, border = 5)
-        self.panelTitle.SetSizer(titleSizer)        
-        
+        titleSizer.Add(item=self.llocTitle, proportion=1,
+                       flag=wx.EXPAND | wx.ALL, border=5)
+        self.panelTitle.SetSizer(titleSizer)
+
         projSizer = wx.BoxSizer(wx.VERTICAL)
-        projSizer.Add(item = self.lprojection, proportion = 1,
-                       flag = wx.EXPAND | wx.ALL, border = 5)
-        self.panelProj.SetSizer(projSizer)        
-        
+        projSizer.Add(item=self.lprojection, proportion=1,
+                      flag=wx.EXPAND | wx.ALL, border=5)
+        self.panelProj.SetSizer(projSizer)
+
         proj4stringSizer = wx.BoxSizer(wx.VERTICAL)
-        proj4stringSizer.Add(item = self.lproj4string, proportion = 1,
-                       flag = wx.EXPAND | wx.ALL, border = 5)
+        proj4stringSizer.Add(item=self.lproj4string, proportion=1,
+                             flag=wx.EXPAND | wx.ALL, border=5)
         self.panelProj4string.SetSizer(proj4stringSizer)
 
         self.panelProj4string.SetupScrolling()
-        self.panelProj.SetupScrolling(scroll_y = False)
-        self.panelTitle.SetupScrolling(scroll_y = False)
+        self.panelProj.SetupScrolling(scroll_y=False)
+        self.panelTitle.SetupScrolling(scroll_y=False)
 
-        self.sizer.Add(item = self.MakeLabel(_("GRASS Database:")),
-                       flag = wx.ALIGN_LEFT | wx.ALL,
-                       border = 5, pos = (1, 0))
-        self.sizer.Add(item = self.ldatabase, 
-                       flag = wx.ALIGN_LEFT | wx.ALL,
-                       border = 5, pos = (1, 1))
-        self.sizer.Add(item = self.MakeLabel(_("Location Name:")),
-                       flag = wx.ALIGN_LEFT | wx.ALL,
-                       border = 5, pos = (2, 0))
-        self.sizer.Add(item = self.llocation,
-                       flag = wx.ALIGN_LEFT | wx.ALL,
-                       border = 5, pos = (2, 1))
-        self.sizer.Add(item = self.MakeLabel(_("Location Title:")),
-                       flag = wx.ALIGN_LEFT | wx.ALL,
-                       border = 5, pos = (3, 0))
-        self.sizer.Add(item = self.panelTitle,
-                       flag = wx.ALIGN_LEFT | wx.ALL | wx.EXPAND,
-                       border = 0, pos = (3, 1))
-        self.sizer.Add(item = self.MakeLabel(_("Projection:")),
-                       flag = wx.ALIGN_LEFT | wx.ALL,
-                       border = 5, pos = (4, 0))
-        self.sizer.Add(item = self.panelProj,
-                       flag = wx.ALIGN_LEFT | wx.ALL | wx.EXPAND,
-                       border = 0, pos = (4, 1))
-        self.sizer.Add(item = self.MakeLabel(_("PROJ.4 definition:\n (non-definitive)")),
-                       flag = wx.ALIGN_LEFT | wx.ALL,
-                       border = 5, pos = (5, 0))
-        self.sizer.Add(item = self.panelProj4string,
-                       flag = wx.ALIGN_LEFT | wx.ALL | wx.EXPAND,
-                       border = 0, pos = (5, 1))
+        self.sizer.Add(item=self.MakeLabel(_("GRASS Database:")),
+                       flag=wx.ALIGN_LEFT | wx.ALL,
+                       border=5, pos=(1, 0))
+        self.sizer.Add(item=self.ldatabase,
+                       flag=wx.ALIGN_LEFT | wx.ALL,
+                       border=5, pos=(1, 1))
+        self.sizer.Add(item=self.MakeLabel(_("Location Name:")),
+                       flag=wx.ALIGN_LEFT | wx.ALL,
+                       border=5, pos=(2, 0))
+        self.sizer.Add(item=self.llocation,
+                       flag=wx.ALIGN_LEFT | wx.ALL,
+                       border=5, pos=(2, 1))
+        self.sizer.Add(item=self.MakeLabel(_("Location Title:")),
+                       flag=wx.ALIGN_LEFT | wx.ALL,
+                       border=5, pos=(3, 0))
+        self.sizer.Add(item=self.panelTitle,
+                       flag=wx.ALIGN_LEFT | wx.ALL | wx.EXPAND,
+                       border=0, pos=(3, 1))
+        self.sizer.Add(item=self.MakeLabel(_("Projection:")),
+                       flag=wx.ALIGN_LEFT | wx.ALL,
+                       border=5, pos=(4, 0))
+        self.sizer.Add(item=self.panelProj,
+                       flag=wx.ALIGN_LEFT | wx.ALL | wx.EXPAND,
+                       border=0, pos=(4, 1))
+        self.sizer.Add(
+            item=self.MakeLabel(
+                _("PROJ.4 definition:\n (non-definitive)")),
+            flag=wx.ALIGN_LEFT | wx.ALL,
+            border=5,
+            pos=(
+                5,
+                0))
+        self.sizer.Add(item=self.panelProj4string,
+                       flag=wx.ALIGN_LEFT | wx.ALL | wx.EXPAND,
+                       border=0, pos=(5, 1))
         self.sizer.AddGrowableCol(1)
         self.sizer.AddGrowableRow(3, 1)
         self.sizer.AddGrowableRow(4, 1)
         self.sizer.AddGrowableRow(5, 5)
-   
+
     def OnEnterPage(self, event):
         """Insert values into text controls for summary of location
         creation options
@@ -1953,7 +2087,7 @@
         dtrans = self.parent.datum_trans
         global coordsys
 
-        #print coordsys,proj4string
+        # print coordsys,proj4string
         if coordsys in ('proj', 'epsg', 'iau', 'wkt', 'file'):
             extra_opts = {}
             extra_opts['location'] = 'location'
@@ -1967,8 +2101,8 @@
                     extra_opts['datum_trans'] = dtrans
 
                 ret, projlabel, err = RunCommand('g.proj',
-                                                 flags = 'jf',
-                                                 proj4 = proj4string,
+                                                 flags='jf',
+                                                 proj4=proj4string,
                                                  **extra_opts)
             elif coordsys == 'iau':
                 addl_opts = {}
@@ -1977,52 +2111,50 @@
                     extra_opts['datum_trans'] = dtrans
 
                 ret, projlabel, err = RunCommand('g.proj',
-                                                 flags = 'jf',
-                                                 proj4 = iauproj4string,
+                                                 flags='jf',
+                                                 proj4=iauproj4string,
                                                  **extra_opts)
             elif coordsys == 'epsg':
                 ret, projlabel, err = RunCommand('g.proj',
-                                                 flags = 'jft',
-                                                 epsg = epsgcode,
-                                                 datum_trans = dtrans,
+                                                 flags='jft',
+                                                 epsg=epsgcode,
+                                                 datum_trans=dtrans,
                                                  **extra_opts)
             elif coordsys == 'file':
-                ret, projlabel, err = RunCommand('g.proj',
-                                                 flags = 'jft',
-                                                 georef = self.parent.filepage.georeffile,
-                                                 **extra_opts)
+                ret, projlabel, err = RunCommand(
+                    'g.proj', flags='jft',
+                    georef=self.parent.filepage.georeffile, **extra_opts)
             elif coordsys == 'wkt':
-                ret, projlabel, err = RunCommand('g.proj',
-                                                 flags = 'jft',
-                                                 wkt = self.parent.wktpage.wktfile,
-                                                 **extra_opts)
+                ret, projlabel, err = RunCommand(
+                    'g.proj', flags='jft', wkt=self.parent.wktpage.wktfile, **extra_opts)
 
             finishButton = wx.FindWindowById(wx.ID_FORWARD)
             if ret == 0:
                 if datum != '':
                     projlabel = projlabel + '+datum=%s' % datum
-                self.lproj4string.SetLabel(projlabel.replace(' +', os.linesep + '+'))
+                self.lproj4string.SetLabel(
+                    projlabel.replace(' +', os.linesep + '+'))
                 finishButton.Enable(True)
             else:
-                GError(err, parent = self)
+                GError(err, parent=self)
                 self.lproj4string.SetLabel('')
                 finishButton.Enable(False)
-        
+
         projdesc = self.parent.projpage.projdesc
         ellipsedesc = self.parent.ellipsepage.ellipsedesc
         datumdesc = self.parent.datumpage.datumdesc
-        #print projdesc,ellipsedesc,datumdesc
+        # print projdesc,ellipsedesc,datumdesc
         self.ldatabase.SetLabel(database)
         self.llocation.SetLabel(location)
         self.llocTitle.SetLabel(self.parent.startpage.locTitle)
-        
+
         label = ''
         if coordsys == 'epsg':
             label = 'EPSG code %s (%s)' % (self.parent.epsgpage.epsgcode,
                                            self.parent.epsgpage.epsgdesc)
         elif coordsys == 'iau':
             label = 'IAU code %s (%s)' % (self.parent.iaupage.epsgcode,
-                                           self.parent.iaupage.epsgdesc)
+                                          self.parent.iaupage.epsgdesc)
         elif coordsys == 'file':
             label = 'matches file %s' % self.parent.filepage.georeffile
 
@@ -2039,17 +2171,24 @@
         elif coordsys == 'custom':
             label = _("custom")
             combo_str = self.parent.custompage.customstring + \
-                        self.parent.custompage.custom_dtrans_string
-            self.lproj4string.SetLabel(('%s' % combo_str.replace(' +', os.linesep + '+')))
+                self.parent.custompage.custom_dtrans_string
+            self.lproj4string.SetLabel(
+                ('%s' %
+                 combo_str.replace(
+                     ' +',
+                     os.linesep +
+                     '+')))
 
         self.lprojection.SetLabel(label)
-        
+
     def OnFinish(self, event):
-        dlg = wx.MessageDialog(parent = self.wizard,
-                               message = _("Do you want to create GRASS location <%s>?") % location,
-                               caption = _("Create new location?"),
-                               style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
-        
+        dlg = wx.MessageDialog(
+            parent=self.wizard,
+            message=_("Do you want to create GRASS location <%s>?") %
+            location,
+            caption=_("Create new location?"),
+            style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+
         if dlg.ShowModal() == wx.ID_NO:
             dlg.Destroy()
             event.Veto()
@@ -2057,27 +2196,29 @@
             dlg.Destroy()
             event.Skip()
 
+
 class LocationWizard(wx.Object):
     """Start wizard here and finish wizard here
     """
+
     def __init__(self, parent, grassdatabase):
         self.__cleanUp()
-        
+
         global coordsys
         self.parent = parent
-        
+
         #
         # define wizard image
         #
         imagePath = os.path.join(globalvar.IMGDIR, "loc_wizard_qgis.png")
         wizbmp = wx.Image(imagePath, wx.BITMAP_TYPE_PNG)
         wizbmp = wizbmp.ConvertToBitmap()
-        
+
         #
         # get georeferencing information from tables in $GISBASE/etc
         #
         self.__readData()
-        
+
         #
         # datum transform number and list of datum transforms
         #
@@ -2090,16 +2231,18 @@
         #
         # define wizard pages
         #
-        self.wizard = WizardWithHelpButton(parent, id = wx.ID_ANY,
-                                           title = _("Define new GRASS Location"),
-                                           bitmap = wizbmp)
+        self.wizard = WizardWithHelpButton(
+            parent,
+            id=wx.ID_ANY,
+            title=_("Define new GRASS Location"),
+            bitmap=wizbmp)
         self.wizard.Bind(wiz.EVT_WIZARD_HELP, self.OnHelp)
 
         self.startpage = DatabasePage(self.wizard, self, grassdatabase)
         self.csystemspage = CoordinateSystemPage(self.wizard, self)
         self.projpage = ProjectionsPage(self.wizard, self)
         self.datumpage = DatumPage(self.wizard, self)
-        self.paramspage = ProjParamsPage(self.wizard,self)
+        self.paramspage = ProjParamsPage(self.wizard, self)
         self.epsgpage = EPSGPage(self.wizard, self)
         self.iaupage = IAUPage(self.wizard, self)
         self.filepage = GeoreferencedFilePage(self.wizard, self)
@@ -2145,7 +2288,7 @@
         self.custompage.SetNext(self.sumpage)
 
         self.sumpage.SetPrev(self.csystemspage)
-        
+
         #
         # do pages layout
         #
@@ -2164,11 +2307,11 @@
         self.wizard.FitToPage(self.datumpage)
         size = self.wizard.GetPageSize()
         self.wizard.SetPageSize((size[0], size[1] + 75))
-        
+
         # new location created?
-        self.location = None 
+        self.location = None
         success = False
-        
+
         # location created in different GIS database?
         self.altdb = False
 
@@ -2184,23 +2327,23 @@
                 self.georeffile = self.filepage.georeffile
                 # FIXME here was code for setting default region, what for is this if:
                 # if self.altdb == False:
-                    
-            else: # -> error
+
+            else:  # -> error
                 self.wizard.Destroy()
-                GError(parent = self.parent,
-                       message = "%s" % _("Unable to create new location. "
-                                          "Location <%(loc)s> not created.\n\n"
-                                          "Details: %(err)s") % \
-                           { 'loc' : self.startpage.location,
-                             'err' : msg })
-        else: # -> canceled
+                GError(parent=self.parent,
+                       message="%s" % _("Unable to create new location. "
+                                        "Location <%(loc)s> not created.\n\n"
+                                        "Details: %(err)s") %
+                       {'loc': self.startpage.location,
+                        'err': msg})
+        else:  # -> canceled
             self.wizard.Destroy()
-            GMessage(parent = self.parent,
-                     message = _("Location wizard canceled. "
-                                 "Location not created."))
-            
+            GMessage(parent=self.parent,
+                     message=_("Location wizard canceled. "
+                               "Location not created."))
+
         self.__cleanUp()
-        
+
     def __cleanUp(self):
         global coordsys
         global north
@@ -2210,7 +2353,7 @@
         global resolution
         global wizerror
         global translist
-        
+
         coordsys = None
         north = None
         south = None
@@ -2233,12 +2376,15 @@
                 paramslist = params.split(';')
                 plist = []
                 for p in paramslist:
-                    if p == '': continue
+                    if p == '':
+                        continue
                     p1, pdefault = p.split(',')
                     pterm, pask = p1.split('=')
                     p = [pterm.strip(), pask.strip(), pdefault.strip()]
                     plist.append(p)
-                self.projections[proj.lower().strip()] = (projdesc.strip(), plist)
+                self.projections[
+                    proj.lower().strip()] = (
+                    projdesc.strip(), plist)
                 self.projdesc[proj.lower().strip()] = projdesc.strip()
             except:
                 continue
@@ -2259,7 +2405,9 @@
             datumdesc = datumdesc.strip('"')
             paramlist = params.split()
             ellipsoid = paramlist.pop(0)
-            self.datums[datum] = (ellipsoid, datumdesc.replace('_', ' '), paramlist)
+            self.datums[datum] = (
+                ellipsoid, datumdesc.replace(
+                    '_', ' '), paramlist)
         f.close()
 
         # read Earth-based ellipsiod definitions
@@ -2279,7 +2427,12 @@
         f.close()
 
         # read Planetary ellipsiod definitions
-        f = open(os.path.join(globalvar.ETCDIR, "proj", "ellipse.table.solar.system"), "r")
+        f = open(
+            os.path.join(
+                globalvar.ETCDIR,
+                "proj",
+                "ellipse.table.solar.system"),
+            "r")
         self.planetary_ellipsoids = {}
         for line in f.readlines():
             line = line.expandtabs(1)
@@ -2314,16 +2467,16 @@
         """
         database = self.startpage.grassdatabase
         location = self.startpage.location
-        
+
         # location already exists?
-        if os.path.isdir(os.path.join(database,location)):
-            GError(parent = self.wizard,
-                   message = "%s <%s>: %s" % \
-                       (_("Unable to create new location"),
-                        os.path.join(database, location),
-                        _("Location already exists in GRASS Database.")))
+        if os.path.isdir(os.path.join(database, location)):
+            GError(parent=self.wizard,
+                   message="%s <%s>: %s" %
+                   (_("Unable to create new location"),
+                    os.path.join(database, location),
+                    _("Location already exists in GRASS Database.")))
             return None
-        
+
         # current GISDbase or a new one?
         current_gdb = grass.gisenv()['GISDBASE'].decode(sys.stdin.encoding)
         if current_gdb != database:
@@ -2331,108 +2484,110 @@
             if os.path.isdir(database) != True:
                 # create new directory
                 os.mkdir(database)
-            
+
             # change to new GISDbase directory
             RunCommand('g.gisenv',
-                       parent = self.wizard,
-                       set = 'GISDBASE=%s' % database)
-            
-            wx.MessageBox(parent = self.wizard,
-                          message = _("Location <%(loc)s> will be created "
-                                    "in GIS data directory <%(dir)s>. "
-                                    "You will need to change the default GIS "
-                                    "data directory in the GRASS startup screen.") % \
-                              { 'loc' : location, 'dir' : database},
-                          caption = _("New GIS data directory"), 
-                          style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
-            
+                       parent=self.wizard,
+                       set='GISDBASE=%s' % database)
+
+            wx.MessageBox(
+                parent=self.wizard,
+                message=_(
+                    "Location <%(loc)s> will be created "
+                    "in GIS data directory <%(dir)s>. "
+                    "You will need to change the default GIS "
+                    "data directory in the GRASS startup screen.") %
+                {'loc': location, 'dir': database},
+                caption=_("New GIS data directory"),
+                style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
+
             # location created in alternate GISDbase
             self.altdb = True
-        
+
         global coordsys
         try:
             if coordsys == "xy":
-                grass.create_location(dbase = self.startpage.grassdatabase,
-                                      location = self.startpage.location,
-                                      desc = self.startpage.locTitle)
+                grass.create_location(dbase=self.startpage.grassdatabase,
+                                      location=self.startpage.location,
+                                      desc=self.startpage.locTitle)
             elif coordsys == "proj":
-                grass.create_location(dbase = self.startpage.grassdatabase,
-                                      location = self.startpage.location,
-                                      proj4 = self.CreateProj4String(),
-                                      datum = self.datumpage.datum,
-                                      datum_trans = self.datum_trans,
-                                      desc = self.startpage.locTitle)
+                grass.create_location(dbase=self.startpage.grassdatabase,
+                                      location=self.startpage.location,
+                                      proj4=self.CreateProj4String(),
+                                      datum=self.datumpage.datum,
+                                      datum_trans=self.datum_trans,
+                                      desc=self.startpage.locTitle)
             elif coordsys == 'custom':
                 addl_opts = {}
                 if self.datum_trans is not None:
                     addl_opts['datum_trans'] = self.datum_trans
 
-                grass.create_location(dbase = self.startpage.grassdatabase,
-                                      location = self.startpage.location,
-                                      proj4 = self.custompage.customstring,
-                                      desc = self.startpage.locTitle,
+                grass.create_location(dbase=self.startpage.grassdatabase,
+                                      location=self.startpage.location,
+                                      proj4=self.custompage.customstring,
+                                      desc=self.startpage.locTitle,
                                       **addl_opts)
             elif coordsys == "epsg":
                 if not self.epsgpage.epsgcode:
                     return _('EPSG code missing.')
-                
-                grass.create_location(dbase = self.startpage.grassdatabase,
-                                      location = self.startpage.location,
-                                      epsg = self.epsgpage.epsgcode,
-                                      datum = self.datumpage.datum,
-                                      datum_trans = self.datum_trans,
-                                      desc = self.startpage.locTitle)
+
+                grass.create_location(dbase=self.startpage.grassdatabase,
+                                      location=self.startpage.location,
+                                      epsg=self.epsgpage.epsgcode,
+                                      datum=self.datumpage.datum,
+                                      datum_trans=self.datum_trans,
+                                      desc=self.startpage.locTitle)
             elif coordsys == "iau":
                 if not self.iaupage.epsgcode:
                     return _('IAU code missing.')
-                
-                grass.create_location(dbase = self.startpage.grassdatabase,
-                                      location = self.startpage.location,
-                                      proj4 = self.iaupage.epsgparams,
-                                      datum = self.datumpage.datum,
-                                      datum_trans = self.datum_trans,
-                                      desc = self.startpage.locTitle)
+
+                grass.create_location(dbase=self.startpage.grassdatabase,
+                                      location=self.startpage.location,
+                                      proj4=self.iaupage.epsgparams,
+                                      datum=self.datumpage.datum,
+                                      datum_trans=self.datum_trans,
+                                      desc=self.startpage.locTitle)
             elif coordsys == "file":
                 if not self.filepage.georeffile or \
                         not os.path.isfile(self.filepage.georeffile):
                     return _("File <%s> not found." % self.filepage.georeffile)
-                
-                grass.create_location(dbase = self.startpage.grassdatabase,
-                                      location = self.startpage.location,
-                                      filename = self.filepage.georeffile,
-                                      desc = self.startpage.locTitle)
+
+                grass.create_location(dbase=self.startpage.grassdatabase,
+                                      location=self.startpage.location,
+                                      filename=self.filepage.georeffile,
+                                      desc=self.startpage.locTitle)
             elif coordsys == "wkt":
                 if not self.wktpage.wktfile or \
                         not os.path.isfile(self.wktpage.wktfile):
                     return _("File <%s> not found." % self.wktpage.wktfile)
-                
-                grass.create_location(dbase = self.startpage.grassdatabase,
-                                      location = self.startpage.location,
-                                      wkt = self.wktpage.wktfile,
-                                      desc = self.startpage.locTitle)
-        
+
+                grass.create_location(dbase=self.startpage.grassdatabase,
+                                      location=self.startpage.location,
+                                      wkt=self.wktpage.wktfile,
+                                      desc=self.startpage.locTitle)
+
         except grass.ScriptError as e:
             return e.value
-        
+
         return None
-    
+
     def CreateProj4String(self):
         """Constract PROJ.4 string"""
         location = self.startpage.location
         proj = self.projpage.p4proj
         projdesc = self.projpage.projdesc
         proj4params = self.paramspage.p4projparams
-                
+
 #        datum = self.datumpage.datum
         if self.datumpage.datumdesc:
-            datumdesc = self.datumpage.datumdesc +' - ' + self.datumpage.ellipse
+            datumdesc = self.datumpage.datumdesc + ' - ' + self.datumpage.ellipse
         else:
             datumdesc = ''
-        datumparams = self.datumpage.datumparams        
+        datumparams = self.datumpage.datumparams
         ellipse = self.ellipsepage.ellipse
         ellipsedesc = self.ellipsepage.ellipsedesc
         ellipseparams = self.ellipsepage.ellipseparams
-        
+
         #
         # creating PROJ.4 string
         #
@@ -2447,11 +2602,11 @@
             else:
                 item = ' +' + item
             proj4string = '%s %s' % (proj4string, item)
-        
+
         # set datum transform parameters if relevant
         if datumparams:
             for item in datumparams:
-                proj4string = '%s +%s' % (proj4string,item)
+                proj4string = '%s +%s' % (proj4string, item)
 
         proj4string = '%s +no_defs' % proj4string
 
@@ -2461,11 +2616,13 @@
         """'Help' button clicked"""
 
         # help text in lib/init/helptext.html
-        RunCommand('g.manual', entry = 'helptext')
+        RunCommand('g.manual', entry='helptext')
 
+
 class WizardWithHelpButton(wiz.Wizard):
+
     def __init__(self, parent, id, title, bitmap):
         pre = wiz.PreWizard()
         pre.SetExtraStyle(wx.wizard.WIZARD_EX_HELPBUTTON)
-        pre.Create(parent = parent, id = id, title = title, bitmap = bitmap)
+        pre.Create(parent=parent, id=id, title=title, bitmap=bitmap)
         self.PostCreate(pre)

Modified: grass/trunk/gui/wxpython/mapdisp/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/mapdisp/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/mapdisp/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -6,4 +6,4 @@
     'toolbars',
     'frame',
     'gprint',
-    ]
+]

Modified: grass/trunk/gui/wxpython/mapdisp/frame.py
===================================================================
--- grass/trunk/gui/wxpython/mapdisp/frame.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/mapdisp/frame.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -30,25 +30,25 @@
 import wx
 import wx.aui
 
-from core.render        import Map
-from mapdisp.toolbars   import MapToolbar, NvizIcons
-from mapdisp.gprint     import PrintOptions
-from core.gcmd          import GError, GMessage, RunCommand
-from dbmgr.dialogs      import DisplayAttributesDialog
-from core.utils         import ListOfCatsToRange, GetLayerNameFromCmd, _
+from core.render import Map
+from mapdisp.toolbars import MapToolbar, NvizIcons
+from mapdisp.gprint import PrintOptions
+from core.gcmd import GError, GMessage, RunCommand
+from dbmgr.dialogs import DisplayAttributesDialog
+from core.utils import ListOfCatsToRange, GetLayerNameFromCmd, _
 from gui_core.dialogs import GetImageHandlers, ImageSizeDialog
-from core.debug         import Debug
-from core.settings      import UserSettings
-from gui_core.mapdisp   import SingleMapFrame
+from core.debug import Debug
+from core.settings import UserSettings
+from gui_core.mapdisp import SingleMapFrame
 from mapwin.base import MapWindowProperties
-from gui_core.query     import QueryDialog, PrepareQueryResults
+from gui_core.query import QueryDialog, PrepareQueryResults
 from mapwin.buffered import BufferedMapWindow
 from mapwin.decorations import TextLayerDialog, \
     LegendController, BarscaleController, ArrowController
-from modules.histogram  import HistogramFrame
-from wxplot.histogram   import HistogramPlotFrame
-from wxplot.profile     import ProfileFrame
-from wxplot.scatter     import ScatterFrame
+from modules.histogram import HistogramFrame
+from wxplot.histogram import HistogramPlotFrame
+from wxplot.profile import ProfileFrame
+from wxplot.scatter import ScatterFrame
 from mapwin.analysis import ProfileController, MeasureDistanceController, \
     MeasureAreaController
 from gui_core.forms import GUI
@@ -66,13 +66,14 @@
     """Main frame for map display window. Drawing takes place in
     child double buffered drawing window.
     """
-    def __init__(self, parent, giface, title = _("GRASS GIS - Map display"),
-                 toolbars = ["map"], statusbar = True,
-                 tree = None, notebook = None, lmgr = None,
-                 page = None, Map = None, auimgr = None, name = 'MapWindow', **kwargs):
+
+    def __init__(self, parent, giface, title=_("GRASS GIS - Map display"),
+                 toolbars=["map"], statusbar=True,
+                 tree=None, notebook=None, lmgr=None,
+                 page=None, Map=None, auimgr=None, name='MapWindow', **kwargs):
         """Main map display window with toolbars, statusbar and
         2D map window, 3D map window and digitizer.
-        
+
         :param toolbars: array of activated toolbars, e.g. ['map', 'digit']
         :param statusbar: True to add statusbar
         :param tree: reference to layer tree
@@ -84,9 +85,9 @@
         :param name: frame name
         :param kwargs: wx.Frame attributes
         """
-        SingleMapFrame.__init__(self, parent = parent, title = title,
-                                Map = Map, auimgr = auimgr, name = name, **kwargs)
-        
+        SingleMapFrame.__init__(self, parent=parent, title=title,
+                                Map=Map, auimgr=auimgr, name=name, **kwargs)
+
         self._giface = giface
         # Layer Manager object
         # need by GLWindow (a lot), VDigitWindow (a little bit)
@@ -124,7 +125,7 @@
         self.statusbarManager = None
         if statusbar:
             self.CreateStatusbar()
-        
+
         # init decoration objects
         self.decorations = {}
         self.legend = LegendController(self.Map, self._giface)
@@ -141,16 +142,17 @@
         #
         # Init map display (buffered DC & set default cursor)
         #
-        self.MapWindow2D = BufferedMapWindow(self, giface = self._giface,
-                                             Map=self.Map,
-                                             properties=self.mapWindowProperties,
-                                             overlays=self.decorations)
+        self.MapWindow2D = BufferedMapWindow(
+            self, giface=self._giface, Map=self.Map,
+            properties=self.mapWindowProperties, overlays=self.decorations)
         self.MapWindow2D.mapQueried.connect(self.Query)
         self.MapWindow2D.overlayActivated.connect(self._activateOverlay)
         self.MapWindow2D.overlayHidden.connect(self._hideOverlay)
         self.MapWindow2D.overlayHidden.connect(self._hideOverlay)
         for overlay in (self.legend, self.barscale, self.arrow):
-            overlay.overlayChanged.connect(lambda: self.MapWindow2D.UpdateMap(render=False, renderVector=False))
+            overlay.overlayChanged.connect(
+                lambda: self.MapWindow2D.UpdateMap(
+                    render=False, renderVector=False))
         self._setUpMapWindow(self.MapWindow2D)
 
         self.MapWindow2D.mouseHandlerUnregistered.connect(self.ResetPointer)
@@ -165,22 +167,22 @@
         # used by vector digitizer
         self.MapWindowVDigit = None
         # used by Nviz (3D display mode)
-        self.MapWindow3D = None 
+        self.MapWindow3D = None
 
         if 'map' in self.toolbars:
             self.toolbars['map'].SelectDefault()
-        
+
         #
         # Bind various events
         #
-        self.Bind(wx.EVT_CLOSE,    self.OnCloseWindow)
-        self.Bind(wx.EVT_SIZE,     self.OnSize)
-        
+        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
+        self.Bind(wx.EVT_SIZE, self.OnSize)
+
         #
         # Update fancy gui style
         #
         self._mgr.AddPane(self.MapWindow, wx.aui.AuiPaneInfo().CentrePane().
-                          Dockable(False).BestSize((-1,-1)).Name('2d').
+                          Dockable(False).BestSize((-1, -1)).Name('2d').
                           CloseButton(False).DestroyOnClose(True).
                           Layer(0))
         self._mgr.Update()
@@ -213,7 +215,7 @@
     def CreateStatusbar(self):
         if self.statusbarManager:
             return
-        
+
         # items for choice
         self.statusbarItems = [sb.SbCoordinates,
                                sb.SbRegionExtent,
@@ -225,31 +227,34 @@
                                sb.SbMapScale,
                                sb.SbGoTo,
                                sb.SbProjection]
-                            
+
         self.statusbarItemsHiddenInNviz = (sb.SbAlignExtent,
                                            sb.SbDisplayGeometry,
                                            sb.SbShowRegion,
                                            sb.SbResolution,
                                            sb.SbMapScale)
-        
+
         # create statusbar and its manager
-        statusbar = self.CreateStatusBar(number = 4, style = 0)
+        statusbar = self.CreateStatusBar(number=4, style=0)
         if globalvar.wxPython3:
             statusbar.SetMinHeight(24)
         statusbar.SetStatusWidths([-5, -2, -1, -1])
-        self.statusbarManager = sb.SbManager(mapframe = self, statusbar = statusbar)
-        
+        self.statusbarManager = sb.SbManager(
+            mapframe=self, statusbar=statusbar)
+
         # fill statusbar manager
-        self.statusbarManager.AddStatusbarItemsByClass(self.statusbarItems, mapframe = self, statusbar = statusbar)
-        self.statusbarManager.AddStatusbarItem(sb.SbMask(self, statusbar = statusbar, position = 2))
-        sbRender = sb.SbRender(self, statusbar = statusbar, position = 3)
+        self.statusbarManager.AddStatusbarItemsByClass(
+            self.statusbarItems, mapframe=self, statusbar=statusbar)
+        self.statusbarManager.AddStatusbarItem(
+            sb.SbMask(self, statusbar=statusbar, position=2))
+        sbRender = sb.SbRender(self, statusbar=statusbar, position=3)
         self.statusbarManager.AddStatusbarItem(sbRender)
-        
+
         self.statusbarManager.Update()
-        
+
         #
         self.Map.GetRenderMgr().updateProgress.connect(self.statusbarManager.SetProgress)
-        
+
     def GetMapWindow(self):
         return self.MapWindow
 
@@ -262,11 +267,11 @@
             grassVersion = "?"
 
         gisenv = grass.gisenv()
-        title = _("GRASS GIS %(version)s Map Display: %(id)s - Location: %(loc)s@%(mapset)s") % \
-            {'version': grassVersion,
-             'id': str(displayId),
-             'loc': gisenv["LOCATION_NAME"],
-             'mapset': gisenv["MAPSET"]}
+        title = _("GRASS GIS %(version)s Map Display: %(id)s - Location: %(loc)s@%(mapset)s") % {
+            'version': grassVersion,
+            'id': str(displayId),
+            'loc': gisenv["LOCATION_NAME"],
+            'mapset': gisenv["MAPSET"]}
 
         self.SetTitle(title)
 
@@ -275,49 +280,48 @@
         """
         from vdigit.main import haveVDigit, VDigit
         from vdigit.toolbars import VDigitToolbar
-        
+
         if not haveVDigit:
             from vdigit import errorMsg
-            
+
             self.toolbars['map'].combo.SetValue(_("2D view"))
-            
+
             GError(_("Unable to start wxGUI vector digitizer.\n"
-                     "Details: %s") % errorMsg, parent = self)
+                     "Details: %s") % errorMsg, parent=self)
             return
 
         if not self.MapWindowVDigit:
             from vdigit.mapwindow import VDigitWindow
-            self.MapWindowVDigit = VDigitWindow(parent=self, giface=self._giface,
-                                                properties=self.mapWindowProperties,
-                                                Map=self.Map, tree=self.tree,
-                                                lmgr=self._layerManager,
-                                                overlays=self.decorations)
+            self.MapWindowVDigit = VDigitWindow(
+                parent=self, giface=self._giface,
+                properties=self.mapWindowProperties, Map=self.Map,
+                tree=self.tree, lmgr=self._layerManager,
+                overlays=self.decorations)
             self._setUpMapWindow(self.MapWindowVDigit)
             self.MapWindowVDigit.digitizingInfo.connect(
                 lambda text:
                 self.statusbarManager.statusbarItems['coordinates'].SetAdditionalInfo(text))
             self.MapWindowVDigit.digitizingInfoUnavailable.connect(
-                lambda:
-                self.statusbarManager.statusbarItems['coordinates'].SetAdditionalInfo(None))
+                lambda: self.statusbarManager.statusbarItems['coordinates'].SetAdditionalInfo(None))
             self.MapWindowVDigit.Show()
-            self._mgr.AddPane(self.MapWindowVDigit, wx.aui.AuiPaneInfo().CentrePane().
-                          Dockable(False).BestSize((-1,-1)).Name('vdigit').
-                          CloseButton(False).DestroyOnClose(True).
-                          Layer(0))
-        
+            self._mgr.AddPane(
+                self.MapWindowVDigit, wx.aui.AuiPaneInfo().CentrePane(). Dockable(False).BestSize(
+                    (-1, -1)).Name('vdigit'). CloseButton(False).DestroyOnClose(True). Layer(0))
+
         self._switchMapWindow(self.MapWindowVDigit)
-        
+
         if self._mgr.GetPane('2d').IsShown():
             self._mgr.GetPane('2d').Hide()
         elif self._mgr.GetPane('3d').IsShown():
             self._mgr.GetPane('3d').Hide()
         self._mgr.GetPane('vdigit').Show()
         if 'vdigit' not in self.toolbars:
-            self.toolbars['vdigit'] = VDigitToolbar(parent=self, toolSwitcher=self._toolSwitcher,
-                                                    MapWindow = self.MapWindow,
-                                                    digitClass=VDigit, giface=self._giface)
+            self.toolbars['vdigit'] = VDigitToolbar(
+                parent=self, toolSwitcher=self._toolSwitcher,
+                MapWindow=self.MapWindow, digitClass=VDigit,
+                giface=self._giface)
         self.MapWindowVDigit.SetToolbar(self.toolbars['vdigit'])
-        
+
         self._mgr.AddPane(self.toolbars['vdigit'],
                           wx.aui.AuiPaneInfo().
                           Name("vdigittoolbar").Caption(_("Vector Digitizer Toolbar")).
@@ -328,51 +332,70 @@
                           BestSize((self.toolbars['vdigit'].GetBestSize())))
         # change mouse to draw digitized line
         self.MapWindow.mouse['box'] = "point"
-        self.MapWindow.zoomtype     = 0
-        self.MapWindow.pen          = wx.Pen(colour = 'red',   width = 2, style = wx.SOLID)
-        self.MapWindow.polypen      = wx.Pen(colour = 'green', width = 2, style = wx.SOLID)
+        self.MapWindow.zoomtype = 0
+        self.MapWindow.pen = wx.Pen(colour='red', width=2, style=wx.SOLID)
+        self.MapWindow.polypen = wx.Pen(
+            colour='green', width=2, style=wx.SOLID)
 
     def AddNviz(self):
         """Add 3D view mode window
         """
         from nviz.main import haveNviz, GLWindow, errorMsg
-        
+
         # check for GLCanvas and OpenGL
         if not haveNviz:
             self.toolbars['map'].combo.SetValue(_("2D view"))
-            GError(parent = self,
-                   message = _("Unable to switch to 3D display mode.\nThe Nviz python extension "
-                               "was not found or loaded properly.\n"
-                               "Switching back to 2D display mode.\n\nDetails: %s" % errorMsg))
+            GError(
+                parent=self, message=_(
+                    "Unable to switch to 3D display mode.\nThe Nviz python extension "
+                    "was not found or loaded properly.\n"
+                    "Switching back to 2D display mode.\n\nDetails: %s" %
+                    errorMsg))
             return
 
         # here was disabling 3D for other displays, now done on starting3dMode
 
         self.toolbars['map'].Enable2D(False)
         # add rotate tool to map toolbar
-        self.toolbars['map'].InsertTool((('rotate', NvizIcons['rotate'],
-                                          self.OnRotate, wx.ITEM_CHECK, 7),)) # 7 is position
-        self._toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self.toolbars['map'],
-                                          tool=self.toolbars['map'].rotate)
+        self.toolbars['map'].InsertTool(
+            (('rotate',
+              NvizIcons['rotate'],
+              self.OnRotate,
+              wx.ITEM_CHECK,
+              7),
+             ))  # 7 is position
+        self._toolSwitcher.AddToolToGroup(
+            group='mouseUse', toolbar=self.toolbars['map'],
+            tool=self.toolbars['map'].rotate)
         self.toolbars['map'].InsertTool((('flyThrough', NvizIcons['flyThrough'],
                                           self.OnFlyThrough, wx.ITEM_CHECK, 8),))
-        self._toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self.toolbars['map'],
-                                          tool=self.toolbars['map'].flyThrough)
+        self._toolSwitcher.AddToolToGroup(
+            group='mouseUse', toolbar=self.toolbars['map'],
+            tool=self.toolbars['map'].flyThrough)
         # update status bar
-        
-        self.statusbarManager.HideStatusbarChoiceItemsByClass(self.statusbarItemsHiddenInNviz)
+
+        self.statusbarManager.HideStatusbarChoiceItemsByClass(
+            self.statusbarItemsHiddenInNviz)
         self.statusbarManager.SetMode(0)
-        
+
         # erase map window
         self.MapWindow.EraseMap()
-        
-        self._giface.WriteCmdLog(_("Starting 3D view mode..."), notification=Notification.HIGHLIGHT)
+
+        self._giface.WriteCmdLog(
+            _("Starting 3D view mode..."),
+            notification=Notification.HIGHLIGHT)
         self.SetStatusText(_("Please wait, loading data..."), 0)
-        
+
         # create GL window
         if not self.MapWindow3D:
-            self.MapWindow3D = GLWindow(self, giface = self._giface, id = wx.ID_ANY, frame = self,
-                                        Map = self.Map, tree = self.tree, lmgr = self._layerManager)
+            self.MapWindow3D = GLWindow(
+                self,
+                giface=self._giface,
+                id=wx.ID_ANY,
+                frame=self,
+                Map=self.Map,
+                tree=self.tree,
+                lmgr=self._layerManager)
             self._setUpMapWindow(self.MapWindow3D)
             self.MapWindow3D.mapQueried.connect(self.Query)
             self._switchMapWindow(self.MapWindow3D)
@@ -383,23 +406,23 @@
 
             # switch from MapWindow to MapWindowGL
             self._mgr.GetPane('2d').Hide()
-            self._mgr.AddPane(self.MapWindow3D, wx.aui.AuiPaneInfo().CentrePane().
-                              Dockable(False).BestSize((-1,-1)).Name('3d').
-                              CloseButton(False).DestroyOnClose(True).
-                              Layer(0))
-            
+            self._mgr.AddPane(
+                self.MapWindow3D, wx.aui.AuiPaneInfo().CentrePane(). Dockable(False).BestSize(
+                    (-1, -1)).Name('3d'). CloseButton(False).DestroyOnClose(True). Layer(0))
+
             self.MapWindow3D.Show()
-            self.MapWindow3D.ResetViewHistory()            
+            self.MapWindow3D.ResetViewHistory()
             self.MapWindow3D.UpdateView(None)
             self.MapWindow3D.overlayActivated.connect(self._activateOverlay)
             self.MapWindow3D.overlayHidden.connect(self._hideOverlay)
             self.legend.overlayChanged.connect(self.MapWindow3D.UpdateOverlays)
         else:
             self._switchMapWindow(self.MapWindow3D)
-            os.environ['GRASS_REGION'] = self.Map.SetRegion(windres = True, windres3 = True)
+            os.environ['GRASS_REGION'] = self.Map.SetRegion(
+                windres=True, windres3=True)
             self.MapWindow3D.GetDisplay().Init()
             del os.environ['GRASS_REGION']
-            
+
             # switch from MapWindow to MapWindowGL
             self._mgr.GetPane('2d').Hide()
             self._mgr.GetPane('3d').Show()
@@ -416,13 +439,14 @@
         # update overlays needs to be called after because getClientSize
         # is called during update and it must give reasonable values
         wx.CallAfter(self.MapWindow3D.UpdateOverlays)
-        
+
         self.SetStatusText("", 0)
         self._mgr.Update()
 
     def Disable3dMode(self):
         """Disables 3D mode (NVIZ) in user interface."""
-        # TODO: this is broken since item is removed but switch is drived by index
+        # TODO: this is broken since item is removed but switch is drived by
+        # index
         if '3D' in self.toolbars['map'].combo.GetString(1):
             self.toolbars['map'].combo.Delete(1)
 
@@ -433,18 +457,19 @@
             self.toolbars['map'].RemoveTool(self.toolbars['map'].flyThrough)
         except AttributeError:
             pass
-        
+
         # update status bar
-        self.statusbarManager.ShowStatusbarChoiceItemsByClass(self.statusbarItemsHiddenInNviz)
-        self.statusbarManager.SetMode(UserSettings.Get(group = 'display',
-                                                       key = 'statusbarMode',
-                                                       subkey = 'selection'))
+        self.statusbarManager.ShowStatusbarChoiceItemsByClass(
+            self.statusbarItemsHiddenInNviz)
+        self.statusbarManager.SetMode(UserSettings.Get(group='display',
+                                                       key='statusbarMode',
+                                                       subkey='selection'))
         self.SetStatusText(_("Please wait, unloading data..."), 0)
         # unloading messages from library cause highlight anyway
         self._giface.WriteCmdLog(_("Switching back to 2D view mode..."),
                                  notification=Notification.NO_NOTIFICATION)
         if self.MapWindow3D:
-            self.MapWindow3D.OnClose(event = None)
+            self.MapWindow3D.OnClose(event=None)
         # switch from MapWindowGL to MapWindow
         self._mgr.GetPane('2d').Show()
         self._mgr.GetPane('3d').Hide()
@@ -465,8 +490,8 @@
         self.MapWindow.UpdateMap()
         self._mgr.Update()
         self.GetMapToolbar().SelectDefault()
-        
-    def AddToolbar(self, name, fixed = False):
+
+    def AddToolbar(self, name, fixed=False):
         """Add defined toolbar to the window
 
         Currently recognized toolbars are:
@@ -479,8 +504,9 @@
         # default toolbar
         if name == "map":
             if 'map' not in self.toolbars:
-                self.toolbars['map'] = MapToolbar(self, toolSwitcher=self._toolSwitcher)
-            
+                self.toolbars['map'] = MapToolbar(
+                    self, toolSwitcher=self._toolSwitcher)
+
             self._mgr.AddPane(self.toolbars['map'],
                               wx.aui.AuiPaneInfo().
                               Name("maptoolbar").Caption(_("Map Toolbar")).
@@ -489,18 +515,18 @@
                               BottomDockable(False).TopDockable(True).
                               CloseButton(False).Layer(2).
                               BestSize((self.toolbars['map'].GetBestSize())))
-            
+
         # vector digitizer
         elif name == "vdigit":
             self.toolbars['map'].combo.SetValue(_("Vector digitizer"))
             self._addToolbarVDigit()
-        
+
         if fixed:
             self.toolbars['map'].combo.Disable()
-         
+
         self._mgr.Update()
-        
-    def RemoveToolbar (self, name, destroy=False):
+
+    def RemoveToolbar(self, name, destroy=False):
         """Removes defined toolbar from the window
 
         :param name toolbar to remove
@@ -508,21 +534,22 @@
         """
         self._mgr.DetachPane(self.toolbars[name])
         if destroy:
-            self._toolSwitcher.RemoveToolbarFromGroup('mouseUse', self.toolbars[name])
+            self._toolSwitcher.RemoveToolbarFromGroup(
+                'mouseUse', self.toolbars[name])
             self.toolbars[name].Destroy()
             self.toolbars.pop(name)
         else:
             self.toolbars[name].Hide()
-        
+
         if name == 'vdigit':
             self._mgr.GetPane('vdigit').Hide()
             self._mgr.GetPane('2d').Show()
             self._switchMapWindow(self.MapWindow2D)
 
         self.toolbars['map'].Enable2D(True)
-        
+
         self._mgr.Update()
-    
+
     def IsPaneShown(self, name):
         """Check if pane (toolbar, mapWindow ...) of given name is currently shown"""
         if self._mgr.GetPane(name).IsOk():
@@ -531,7 +558,7 @@
 
     def RemoveQueryLayer(self):
         """Removes temporary map layers (queries)"""
-        qlayer = self.GetMap().GetListOfLayers(name = globalvar.QUERYLAYER)
+        qlayer = self.GetMap().GetListOfLayers(name=globalvar.QUERYLAYER)
         for layer in qlayer:
             self.GetMap().DeleteLayer(layer)
 
@@ -539,30 +566,30 @@
         """Re-render map composition (each map layer)
         """
         self.RemoveQueryLayer()
-        
+
         # deselect features in vdigit
         if self.GetToolbar('vdigit'):
             if self.MapWindow.digit:
                 self.MapWindow.digit.GetDisplay().SetSelected([])
-            self.MapWindow.UpdateMap(render = True, renderVector = True)
+            self.MapWindow.UpdateMap(render=True, renderVector=True)
         else:
-            self.MapWindow.UpdateMap(render = True)
+            self.MapWindow.UpdateMap(render=True)
 
         # reset dialog with selected features
         if self.dialogs['vselect']:
             self.dialogs['vselect'].Reset()
-        
+
         # update statusbar
         self.StatusbarUpdate()
 
     def OnPointer(self, event):
         """Pointer button clicked
-        """      
+        """
         self.MapWindow.SetModePointer()
 
         if self.GetToolbar('vdigit'):
             self.toolbars['vdigit'].action['id'] = -1
-            self.toolbars['vdigit'].action['desc']=''
+            self.toolbars['vdigit'].action['desc'] = ''
 
     def OnSelect(self, event):
         """Vector feature selection button clicked
@@ -574,10 +601,12 @@
                 GMessage(_("No map layer selected. Operation canceled."))
                 return
 
-            self.dialogs['vselect'] = VectorSelectBase(self.parent, self._giface)
+            self.dialogs['vselect'] = VectorSelectBase(
+                self.parent, self._giface)
             self.dialogs['vselect'].CreateDialog(createButton=True)
-            self.dialogs['vselect'].onCloseDialog.connect(self._onCloseVectorSelectDialog)
-            
+            self.dialogs['vselect'].onCloseDialog.connect(
+                self._onCloseVectorSelectDialog)
+
     def _onCloseVectorSelectDialog(self):
         self.dialogs['vselect'] = None
 
@@ -585,7 +614,7 @@
         """Rotate 3D view
         """
         self.MapWindow.mouse['use'] = "rotate"
-        
+
         # change the cursor
         self.MapWindow.SetNamedCursor('hand')
 
@@ -593,7 +622,7 @@
         """Fly-through mode
         """
         self.MapWindow.mouse['use'] = "fly"
-        
+
         # change the cursor
         self.MapWindow.SetNamedCursor('hand')
         self.MapWindow.SetFocus()
@@ -604,7 +633,7 @@
         filetype, ltype = self._prepareSaveToFile()
         if not ltype:
             return
-        
+
         # get size
         dlg = ImageSizeDialog(self)
         dlg.CentreOnParent()
@@ -613,34 +642,34 @@
             return
         width, height = dlg.GetValues()
         dlg.Destroy()
-        
+
         # get filename
-        dlg = wx.FileDialog(parent = self,
-                            message = _("Choose a file name to save the image "
-                                        "(no need to add extension)"),
-                            wildcard = filetype,
-                            style = wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
-        
+        dlg = wx.FileDialog(parent=self,
+                            message=_("Choose a file name to save the image "
+                                      "(no need to add extension)"),
+                            wildcard=filetype,
+                            style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
+
         if dlg.ShowModal() == wx.ID_OK:
             path = dlg.GetPath()
             if not path:
                 dlg.Destroy()
                 return
-            
+
             base, ext = os.path.splitext(path)
             fileType = ltype[dlg.GetFilterIndex()]['type']
-            extType  = ltype[dlg.GetFilterIndex()]['ext']
+            extType = ltype[dlg.GetFilterIndex()]['ext']
             if ext != extType:
                 path = base + '.' + extType
-            
+
             self.MapWindow.SaveToFile(path, fileType,
                                       width, height)
-            
+
         dlg.Destroy()
 
     def DOutFile(self, command):
         """Saves map to image by running d.out.file from gui or d.mon.
-        Command is expected to be validated by parser.        
+        Command is expected to be validated by parser.
         """
         filetype, ltype = self._prepareSaveToFile()
         if not ltype:
@@ -687,7 +716,8 @@
         """Saves currently loaded composition of layers as a raster map.
         """
         if self.IsPaneShown('3d'):
-            self._giface.WriteError(_('d.to.rast can be used only in 2D mode.'))
+            self._giface.WriteError(
+                _('d.to.rast can be used only in 2D mode.'))
             return
         outputRaster = None
         overwrite = False
@@ -708,8 +738,9 @@
         dOutFileCmd = ['d.out.file', 'output=' + pngFile, 'format=png']
         self.DOutFile(dOutFileCmd)
         # import back as red, green, blue rasters
-        returncode, messages = RunCommand('r.in.gdal', flags='o', input=pngFile, output=tmpName,
-                                          quiet=True, overwrite=overwrite, getErrorMsg=True)
+        returncode, messages = RunCommand(
+            'r.in.gdal', flags='o', input=pngFile, output=tmpName, quiet=True,
+            overwrite=overwrite, getErrorMsg=True)
         if not returncode == 0:
             self._giface.WriteError(_('Failed to run d.to.rast:\n') + messages)
             return
@@ -722,13 +753,23 @@
             self._giface.WriteError(_('Failed to run d.to.rast:\n') + messages)
             return
         # composite
-        returncode, messages = RunCommand('r.composite', red=tmpName + '.red',
-                                          green=tmpName + '.green', blue=tmpName + '.blue',
-                                          output=outputRaster, quiet=True,
-                                          overwrite=overwrite, getErrorMsg=True)
+        returncode, messages = RunCommand(
+            'r.composite', red=tmpName + '.red', green=tmpName + '.green',
+            blue=tmpName + '.blue', output=outputRaster, quiet=True,
+            overwrite=overwrite, getErrorMsg=True)
         grass.del_temp_region()
-        RunCommand('g.remove', type='raster', flags='f', quiet=True,
-                   name=[tmpName + '.red', tmpName + '.green', tmpName + '.blue'])
+        RunCommand(
+            'g.remove',
+            type='raster',
+            flags='f',
+            quiet=True,
+            name=[
+                tmpName +
+                '.red',
+                tmpName +
+                '.green',
+                tmpName +
+                '.blue'])
         if not returncode == 0:
             self._giface.WriteError(_('Failed to run d.to.rast:\n') + messages)
             grass.try_remove(pngFile)
@@ -757,13 +798,15 @@
         """Get wildcards and format extensions."""
         if self.IsPaneShown('3d'):
             filetype = "TIF file (*.tif)|*.tif|PPM file (*.ppm)|*.ppm"
-            ltype = [{ 'ext' : 'tif', 'type' : 'tif' },
-                     { 'ext' : 'ppm', 'type' : 'ppm' }]
+            ltype = [{'ext': 'tif', 'type': 'tif'},
+                     {'ext': 'ppm', 'type': 'ppm'}]
         else:
             img = self.MapWindow.img
             if not img:
-                GMessage(parent = self,
-                         message = _("Nothing to render (empty map). Operation canceled."))
+                GMessage(
+                    parent=self,
+                    message=_(
+                        "Nothing to render (empty map). Operation canceled."))
                 return None, None
             filetype, ltype = GetImageHandlers(img)
         return filetype, ltype
@@ -798,7 +841,7 @@
         Debug.msg(2, "MapFrame.OnCloseWindow(): function starts")
         pgnum = None
         self.Map.Clean()
-        
+
         # close edited map and 3D tools properly
         if self.GetToolbar('vdigit'):
             maplayer = self.toolbars['vdigit'].GetLayer()
@@ -818,7 +861,7 @@
         Debug.msg(2, "MapFrame.OnCloseWindow(): function ends")
 
     def Query(self, x, y):
-        """Query selected layers. 
+        """Query selected layers.
 
         :param x,y: coordinates
         """
@@ -850,17 +893,21 @@
                     lmap = digitToolbar.GetLayer().GetName()
                     for name in vect:
                         if lmap == name:
-                            self._giface.WriteWarning(_("Vector map <%s> "
-                                                                      "opened for editing - skipped.") % lmap)
+                            self._giface.WriteWarning(
+                                _("Vector map <%s> " "opened for editing - skipped.") % lmap)
                             vect.remove(name)
 
         if not (rast + vect):
-            GMessage(parent = self,
-                     message = _('No raster or vector map layer selected for querying.'))
+            GMessage(
+                parent=self,
+                message=_(
+                    'No raster or vector map layer selected for querying.'))
             return
 
-        # set query snap distance for v.what at map unit equivalent of 10 pixels
-        qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) / self.Map.width)
+        # set query snap distance for v.what at map unit equivalent of 10
+        # pixels
+        qdist = 10.0 * (
+            (self.Map.region['e'] - self.Map.region['w']) / self.Map.width)
 
         # TODO: replace returning None by exception or so
         try:
@@ -874,7 +921,7 @@
             if rast:
                 self.MapWindow.QuerySurface(x, y)
             if vect:
-                self.QueryMap(east, north, qdist, rast = [], vect = vect)
+                self.QueryMap(east, north, qdist, rast=[], vect=vect)
 
     def SetQueryLayersAndActivate(self, ltype, maps):
         """Activate query mode and set layers to query.
@@ -887,7 +934,7 @@
 
     def QueryMap(self, east, north, qdist, rast, vect):
         """Query raster or vector map layers by r/v.what
-        
+
         :param east,north: coordinates
         :param qdist: query distance
         :param rast: raster map names
@@ -896,11 +943,12 @@
         Debug.msg(1, "QueryMap(): raster=%s vector=%s" % (','.join(rast),
                                                           ','.join(vect)))
         if self._highlighter_layer is None:
-            self._highlighter_layer = VectorSelectHighlighter(mapdisp=self._giface.GetMapDisplay(), giface=self._giface)
+            self._highlighter_layer = VectorSelectHighlighter(
+                mapdisp=self._giface.GetMapDisplay(), giface=self._giface)
 
         # use display region settings instead of computation region settings
         self.tmpreg = os.getenv("GRASS_REGION")
-        os.environ["GRASS_REGION"] = self.Map.SetRegion(windres = False)
+        os.environ["GRASS_REGION"] = self.Map.SetRegion(windres=False)
 
         rastQuery = []
         vectQuery = []
@@ -908,14 +956,18 @@
             rastQuery = grass.raster_what(map=rast, coord=(east, north),
                                           localized=True)
         if vect:
-            encoding = UserSettings.Get(group='atm', key='encoding', subkey='value')
+            encoding = UserSettings.Get(
+                group='atm', key='encoding', subkey='value')
             try:
-                vectQuery = grass.vector_what(map=vect, coord=(east, north), distance=qdist,
-                                              encoding=encoding)
+                vectQuery = grass.vector_what(
+                    map=vect, coord=(east, north),
+                    distance=qdist, encoding=encoding)
             except grass.ScriptError:
-                GError(parent=self,
-                       message=_("Failed to query vector map(s) <{maps}>. "
-                                 "Check database settings and topology.").format(maps=','.join(vect)))
+                GError(
+                    parent=self, message=_(
+                        "Failed to query vector map(s) <{maps}>. "
+                        "Check database settings and topology.").format(
+                        maps=','.join(vect)))
         self._QueryMapDone()
 
         self._highlighter_layer.Clear()
@@ -923,14 +975,15 @@
             self._queryHighlight(vectQuery)
 
         result = rastQuery + vectQuery
-        result = PrepareQueryResults(coordinates = (east, north), result = result)
+        result = PrepareQueryResults(coordinates=(east, north), result=result)
         if self.dialogs['query']:
             self.dialogs['query'].Raise()
             self.dialogs['query'].SetData(result)
         else:
-            self.dialogs['query'] = QueryDialog(parent = self, data = result)
+            self.dialogs['query'] = QueryDialog(parent=self, data=result)
             self.dialogs['query'].Bind(wx.EVT_CLOSE, self._oncloseQueryDialog)
-            self.dialogs['query'].redirectOutput.connect(self._onRedirectQueryOutput)
+            self.dialogs['query'].redirectOutput.connect(
+                self._onRedirectQueryOutput)
             self.dialogs['query'].Show()
 
     def _oncloseQueryDialog(self, event):
@@ -944,7 +997,8 @@
     def _onRedirectQueryOutput(self, output, style='log'):
         """Writes query output into console"""
         if style == 'log':
-            self._giface.WriteLog(output, notification=Notification.MAKE_VISIBLE)
+            self._giface.WriteLog(
+                output, notification=Notification.MAKE_VISIBLE)
         elif style == 'cmd':
             self._giface.WriteCmdLog(output)
 
@@ -970,27 +1024,27 @@
                 del os.environ["GRASS_REGION"]
         elif 'GRASS_REGION' in os.environ:
             del os.environ["GRASS_REGION"]
-        
+
         if hasattr(self, "tmpreg"):
             del self.tmpreg
-        
+
     def OnQuery(self, event):
         """Query tools menu"""
         self.MapWindow.mouse['use'] = "query"
         self.MapWindow.mouse['box'] = "point"
         self.MapWindow.zoomtype = 0
-        
+
         # change the cursor
         self.MapWindow.SetNamedCursor('cross')
-        
-    def AddTmpVectorMapLayer(self, name, cats, useId = False, addLayer = True):
+
+    def AddTmpVectorMapLayer(self, name, cats, useId=False, addLayer=True):
         """Add temporal vector map layer to map composition
 
         :param name: name of map layer
-        :param useId: use feature id instead of category 
+        :param useId: use feature id instead of category
         """
         # color settings from ATM
-        color = UserSettings.Get(group = 'atm', key = 'highlight', subkey = 'color')
+        color = UserSettings.Get(group='atm', key='highlight', subkey='color')
         colorStr = str(color[0]) + ":" + \
             str(color[1]) + ":" + \
             str(color[2])
@@ -1002,7 +1056,7 @@
         layerSelected = self._giface.GetLayerList().GetSelectedLayer()
         if not layerSelected:
             return None
-        
+
         vparam = layerSelected.cmd
         for p in vparam:
             if '=' in p:
@@ -1011,17 +1065,25 @@
                     icon = pval
                 elif parg == 'size':
                     size = float(pval)
-        
-        pattern = ["d.vect",
-                   "map=%s" % name,
-                   "color=%s" % colorStr,
-                   "fill_color=%s" % colorStr,
-                   "width=%d"  % UserSettings.Get(group = 'atm', key = 'highlight', subkey = 'width')]
+
+        pattern = [
+            "d.vect",
+            "map=%s" %
+            name,
+            "color=%s" %
+            colorStr,
+            "fill_color=%s" %
+            colorStr,
+            "width=%d" %
+            UserSettings.Get(
+                group='atm',
+                key='highlight',
+                subkey='width')]
         if icon != '':
             pattern.append('icon=%s' % icon)
         if size > 0:
             pattern.append('size=%i' % size)
-        
+
         if useId:
             cmd = pattern
             cmd.append('-i')
@@ -1040,10 +1102,10 @@
                 args['ltype'] = 'vector'
             else:
                 args['ltype'] = 'command'
-                
-            return self.Map.AddLayer(name = globalvar.QUERYLAYER, command = cmd,
-                                     active = True, hidden = True, opacity = 1.0,
-                                     render = True, **args)
+
+            return self.Map.AddLayer(name=globalvar.QUERYLAYER, command=cmd,
+                                     active=True, hidden=True, opacity=1.0,
+                                     render=True, **args)
         else:
             return cmd
 
@@ -1058,9 +1120,12 @@
 
         :param controller: measurement class (MeasureDistanceController, MeasureAreaController)
         """
-        self.measureController = controller(self._giface, mapWindow=self.GetMapWindow())
-        # assure that the mode is ended and lines are cleared whenever other tool is selected
-        self._toolSwitcher.toggleToolChanged.connect(lambda: self.measureController.Stop())
+        self.measureController = controller(
+            self._giface, mapWindow=self.GetMapWindow())
+        # assure that the mode is ended and lines are cleared whenever other
+        # tool is selected
+        self._toolSwitcher.toggleToolChanged.connect(
+            lambda: self.measureController.Stop())
         self.measureController.Start()
 
     def OnProfile(self, event):
@@ -1075,8 +1140,8 @@
 
     def Profile(self, rasters=None):
         """Launch profile tool"""
-        self.profileController = ProfileController(self._giface,
-                                                   mapWindow=self.GetMapWindow())
+        self.profileController = ProfileController(
+            self._giface, mapWindow=self.GetMapWindow())
         win = ProfileFrame(parent=self, rasterList=rasters,
                            units=self.Map.projinfo['units'],
                            controller=self.profileController)
@@ -1094,10 +1159,10 @@
             if layer.maplayer.GetType() == 'raster':
                 raster.append(layer.maplayer.GetName())
 
-        win = HistogramPlotFrame(parent = self, rasterList = raster)
+        win = HistogramPlotFrame(parent=self, rasterList=raster)
         win.CentreOnParent()
         win.Show()
-        
+
     def OnScatterplot(self, event):
         """Init PyPlot scatterplot display canvas and tools
         """
@@ -1107,8 +1172,8 @@
             if layer.maplayer.GetType() == 'raster':
                 raster.append(layer.maplayer.GetName())
 
-        win = ScatterFrame(parent = self, rasterList = raster)
-        
+        win = ScatterFrame(parent=self, rasterList=raster)
+
         win.CentreOnParent()
         win.Show()
         # Open raster select dialog to make sure that at least 2 rasters (and the desired rasters)
@@ -1119,7 +1184,7 @@
         """Init histogram display canvas and tools
         """
         win = HistogramFrame(self, giface=self._giface)
-        
+
         win.CentreOnParent()
         win.Show()
         win.Refresh()
@@ -1128,7 +1193,7 @@
     def _activateOverlay(self, overlayId):
         """Launch decoration dialog according to overlay id.
 
-        :param overlayId: id of overlay        
+        :param overlayId: id of overlay
         """
         if overlayId > 100:
             self.OnAddText(None)
@@ -1142,7 +1207,7 @@
     def _hideOverlay(self, overlayId):
         """Hide overlay.
 
-        :param overlayId: id of overlay        
+        :param overlayId: id of overlay
         """
         self.decorations[overlayId].Hide()
 
@@ -1179,9 +1244,8 @@
             #            barcmd = 'd.barscale'
 
             # decoration overlay control dialog
-            GUI(parent=self, giface=self._giface, show=True,
-                modal=False).ParseCommand(self.barscale.cmd,
-                                          completed=(self.barscale.GetOptData, None, None))
+            GUI(parent=self, giface=self._giface, show=True, modal=False).ParseCommand(
+                self.barscale.cmd, completed=(self.barscale.GetOptData, None, None))
 
         self.MapWindow.mouse['use'] = 'pointer'
 
@@ -1205,14 +1269,17 @@
                             continue
                         param, val = param_val
                         if param == 'raster':
-                            self.legend.cmd[idx] = 'raster={rast}'.format(rast=layer.maplayer.name)
+                            self.legend.cmd[idx] = 'raster={rast}'.format(
+                                rast=layer.maplayer.name)
                             isMap = True
                         elif param in ('use', 'range'):
                             # clear range or use to avoid problems
                             del self.legend.cmd[idx]
 
                     if not isMap:  # for the first time
-                        self.legend.cmd.append('raster=%s' % layer.maplayer.name)
+                        self.legend.cmd.append(
+                            'raster=%s' %
+                            layer.maplayer.name)
                     break
 
         if not showDialog and self.legend.CmdIsValid():
@@ -1229,9 +1296,8 @@
                 self.legend.dialog.Destroy()
                 self.legend.dialog = None
         if not self.legend.dialog:
-            GUI(parent=self, giface=self._giface, show=True,
-                modal=False).ParseCommand(self.legend.cmd,
-                                          completed=(self.legend.GetOptData, None, None))
+            GUI(parent=self, giface=self._giface, show=True, modal=False).ParseCommand(
+                self.legend.cmd, completed=(self.legend.GetOptData, None, None))
 
         self.MapWindow.mouse['use'] = 'pointer'
 
@@ -1239,7 +1305,8 @@
         """Handler for north arrow menu selection."""
         if self.IsPaneShown('3d'):
             # here was opening of appearance page of nviz notebook
-            # but now moved to MapWindow3D where are other problematic nviz calls
+            # but now moved to MapWindow3D where are other problematic nviz
+            # calls
             self.MapWindow3D.SetDrawArrow((70, 70))
             return
 
@@ -1261,9 +1328,8 @@
             else:
                 self.arrow.dialog.Show()
         else:
-            GUI(parent=self, giface=self._giface, show=True,
-                modal=False).ParseCommand(self.arrow.cmd,
-                                          completed=(self.arrow.GetOptData, None, None))
+            GUI(parent=self, giface=self._giface, show=True, modal=False).ParseCommand(
+                self.arrow.cmd, completed=(self.arrow.GetOptData, None, None))
 
         self.MapWindow.mouse['use'] = 'pointer'
 
@@ -1279,17 +1345,17 @@
                 id = max(self.MapWindow.textdict.keys()) + 1
             else:
                 id = 101
-        
-        self.dialogs['text'] = TextLayerDialog(parent = self, ovlId = id, 
-                                               title = _('Add text layer'),
-                                               size = (400, 200))
+
+        self.dialogs['text'] = TextLayerDialog(parent=self, ovlId=id,
+                                               title=_('Add text layer'),
+                                               size=(400, 200))
         self.dialogs['text'].CenterOnParent()
 
         # If OK button pressed in decoration control dialog
         if self.dialogs['text'].ShowModal() == wx.ID_OK:
             text = self.dialogs['text'].GetValues()['text']
             active = self.dialogs['text'].GetValues()['active']
-        
+
             # delete object if it has no text or is not active
             if text == '' or active == False:
                 try:
@@ -1300,32 +1366,37 @@
                         self.MapWindow3D.UpdateOverlays()
                         self.MapWindow.UpdateMap()
                     else:
-                        self.MapWindow2D.UpdateMap(render = False, renderVector = False)
+                        self.MapWindow2D.UpdateMap(
+                            render=False, renderVector=False)
                 except:
                     pass
                 return
 
-            
             self.MapWindow.textdict[id] = self.dialogs['text'].GetValues()
-            
+
             if self.IsPaneShown('3d'):
                 self.MapWindow3D.UpdateOverlays()
                 self.MapWindow3D.UpdateMap()
             else:
                 self.MapWindow2D.pdc.ClearId(id)
                 self.MapWindow2D.pdc.SetId(id)
-                self.MapWindow2D.UpdateMap(render = False, renderVector = False)
-            
+                self.MapWindow2D.UpdateMap(render=False, renderVector=False)
+
         self.MapWindow.mouse['use'] = 'pointer'
-        
+
     def GetOptData(self, dcmd, type, params, propwin):
         """Callback method for decoration overlay command generated by
         dialog created in menuform.py
         """
         # Reset comand and rendering options in render.Map. Always render decoration.
         # Showing/hiding handled by PseudoDC
-        self.Map.ChangeOverlay(ovltype = type, type = 'overlay', name = '', command = dcmd,
-                               active = True, render = False)
+        self.Map.ChangeOverlay(
+            ovltype=type,
+            type='overlay',
+            name='',
+            command=dcmd,
+            active=True,
+            render=False)
         self.params[type] = params
         self.propwin[type] = propwin
 
@@ -1336,21 +1407,21 @@
         Debug.msg(3, "MapFrame.OnZoomToMap()")
         layers = None
         if self.IsStandalone():
-            layers = self.MapWindow.GetMap().GetListOfLayers(active = False)
-        
-        self.MapWindow.ZoomToMap(layers = layers)
+            layers = self.MapWindow.GetMap().GetListOfLayers(active=False)
 
+        self.MapWindow.ZoomToMap(layers=layers)
+
     def OnZoomToRaster(self, event):
         """Set display extents to match selected raster map (ignore NULLs)
         """
-        self.MapWindow.ZoomToMap(ignoreNulls = True)
-        
+        self.MapWindow.ZoomToMap(ignoreNulls=True)
+
     def OnZoomToSaved(self, event):
         """Set display geometry to match extents in
         saved region file
         """
         self.MapWindow.SetRegion(zoomOnly=True)
-        
+
     def OnSetDisplayToWind(self, event):
         """Set computational region (WIND file) to match display
         extents
@@ -1362,7 +1433,7 @@
         file
         """
         self.MapWindow.SetRegion(zoomOnly=False)
- 
+
     def OnSetExtentToWind(self, event):
         """Set compulational region extent interactively"""
         self.MapWindow.SetModeDrawRegion()
@@ -1370,41 +1441,49 @@
     def OnSaveDisplayRegion(self, event):
         """Save display extents to named region file.
         """
-        self.MapWindow.SaveRegion(display = True)
+        self.MapWindow.SaveRegion(display=True)
 
     def OnSaveWindRegion(self, event):
         """Save computational region to named region file.
         """
-        self.MapWindow.SaveRegion(display = False)
-        
+        self.MapWindow.SaveRegion(display=False)
+
     def OnZoomMenu(self, event):
         """Popup Zoom menu
         """
         zoommenu = wx.Menu()
-        
-        for label, handler in ((_('Zoom to default region'), self.OnZoomToDefault),
-                               (_('Zoom to saved region'), self.OnZoomToSaved),
-                               (None, None),
-                               (_('Set computational region extent from display'), self.OnSetDisplayToWind),
-                               (_('Set computational region extent interactively'), self.OnSetExtentToWind),
-                               (_('Set computational region from named region'),   self.OnSetWindToRegion),
-                               (None, None),
-                               (_('Save display geometry to named region'), self.OnSaveDisplayRegion),
-                               (_('Save computational region to named region'), self.OnSaveWindRegion)):
+
+        for label, handler in (
+            (_('Zoom to default region'),
+             self.OnZoomToDefault),
+            (_('Zoom to saved region'),
+             self.OnZoomToSaved),
+            (None, None),
+            (_('Set computational region extent from display'),
+             self.OnSetDisplayToWind),
+            (_('Set computational region extent interactively'),
+             self.OnSetExtentToWind),
+            (_('Set computational region from named region'),
+             self.OnSetWindToRegion),
+            (None, None),
+            (_('Save display geometry to named region'),
+             self.OnSaveDisplayRegion),
+            (_('Save computational region to named region'),
+             self.OnSaveWindRegion)):
             if label:
                 mid = wx.MenuItem(zoommenu, wx.ID_ANY, label)
                 zoommenu.AppendItem(mid)
                 self.Bind(wx.EVT_MENU, handler, mid)
             else:
                 zoommenu.AppendSeparator()
-        
+
         # Popup the menu. If an item is selected then its handler will
         # be called before PopupMenu returns.
         self.PopupMenu(zoommenu)
         zoommenu.Destroy()
 
-    def SetProperties(self, render = False, mode = 0, showCompExtent = False,
-                      constrainRes = False, projection = False, alignExtent = True):
+    def SetProperties(self, render=False, mode=0, showCompExtent=False,
+                      constrainRes=False, projection=False, alignExtent=True):
         """Set properies of map display window"""
         self.mapWindowProperties.autoRender = render
         self.statusbarManager.SetMode(mode)
@@ -1413,7 +1492,7 @@
         self.mapWindowProperties.alignExtent = alignExtent
         self.mapWindowProperties.resolution = constrainRes
         self.SetProperty('projection', projection)
-        
+
     def IsStandalone(self):
         """Check if Map display is standalone
 
@@ -1456,12 +1535,12 @@
         return self.dialogs.get(name, None)
 
     def OnVNet(self, event):
-        """Dialog for v.net* modules 
+        """Dialog for v.net* modules
         """
         if self.dialogs['vnet']:
             self.dialogs['vnet'].Raise()
             return
-        
+
         from vnet.dialogs import VNETDialog
         self.dialogs['vnet'] = VNETDialog(parent=self, giface=self._giface)
         self.dialogs['vnet'].CenterOnScreen()
@@ -1490,18 +1569,30 @@
 
         self.rdigit = RDigitController(self._giface,
                                        mapWindow=self.GetMapWindow())
-        self.toolbars['rdigit'] = RDigitToolbar(parent=self, controller=self.rdigit,
-                                                toolSwitcher=self._toolSwitcher)
+        self.toolbars['rdigit'] = RDigitToolbar(
+            parent=self, controller=self.rdigit,
+            toolSwitcher=self._toolSwitcher)
         # connect signals
-        self.rdigit.newRasterCreated.connect(self.toolbars['rdigit'].NewRasterAdded)
-        self.rdigit.newRasterCreated.connect(lambda name: self._giface.mapCreated.emit(name=name, ltype='raster'))
-        self.rdigit.newFeatureCreated.connect(self.toolbars['rdigit'].UpdateCellValues)
-        self.rdigit.uploadMapCategories.connect(self.toolbars['rdigit'].UpdateCellValues)
-        self.rdigit.showNotification.connect(lambda text: self.SetStatusText(text, 0))
+        self.rdigit.newRasterCreated.connect(
+            self.toolbars['rdigit'].NewRasterAdded)
+        self.rdigit.newRasterCreated.connect(
+            lambda name: self._giface.mapCreated.emit(
+                name=name, ltype='raster'))
+        self.rdigit.newFeatureCreated.connect(
+            self.toolbars['rdigit'].UpdateCellValues)
+        self.rdigit.uploadMapCategories.connect(
+            self.toolbars['rdigit'].UpdateCellValues)
+        self.rdigit.showNotification.connect(
+            lambda text: self.SetStatusText(text, 0))
         self.rdigit.quitDigitizer.connect(self.QuitRDigit)
-        self.rdigit.Bind(EVT_UPDATE_PROGRESS,
-                         lambda evt: self.statusbarManager.SetProgress(evt.range, evt.value, evt.text))
-        rasters = self.GetMap().GetListOfLayers(ltype='raster', mapset=grass.gisenv()['MAPSET'])
+        self.rdigit.Bind(
+            EVT_UPDATE_PROGRESS,
+            lambda evt: self.statusbarManager.SetProgress(
+                evt.range,
+                evt.value,
+                evt.text))
+        rasters = self.GetMap().GetListOfLayers(
+            ltype='raster', mapset=grass.gisenv()['MAPSET'])
         self.toolbars['rdigit'].UpdateRasterLayers(rasters)
         self.toolbars['rdigit'].SelectDefault()
 
@@ -1523,7 +1614,8 @@
     def _updateRDigitLayers(self, layer):
         mapset = grass.gisenv()['MAPSET']
         self.toolbars['rdigit'].UpdateRasterLayers(
-            rasters=self.GetMap().GetListOfLayers(ltype='raster', mapset=mapset))
+            rasters=self.GetMap().GetListOfLayers(
+                ltype='raster', mapset=mapset))
 
     def QuitRDigit(self):
         """Calls digitizer cleanup, removes digitizer object and disconnects

Modified: grass/trunk/gui/wxpython/mapdisp/gprint.py
===================================================================
--- grass/trunk/gui/wxpython/mapdisp/gprint.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/mapdisp/gprint.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -16,12 +16,14 @@
 @author Michael Barton (Arizona State University)
 """
 
-import  wx
+import wx
 
 from core.gcmd import GMessage
 from core.utils import _
 
+
 class MapPrint(wx.Printout):
+
     def __init__(self, canvas):
         wx.Printout.__init__(self)
         self.canvas = canvas
@@ -92,7 +94,9 @@
 
         return True
 
+
 class PrintOptions(wx.Object):
+
     def __init__(self, parent, mapwin):
         self.mapframe = parent
         self.mapwin = mapwin
@@ -116,7 +120,7 @@
         # this makes a copy of the wx.PrintData instead of just saving
         # a reference to the one inside the PrintDialogData that will
         # be destroyed when the dialog is destroyed
-        self.printData = wx.PrintData( dlg.GetPageSetupData().GetPrintData() )
+        self.printData = wx.PrintData(dlg.GetPageSetupData().GetPrintData())
 
         dlg.Destroy()
 
@@ -150,5 +154,6 @@
             GMessage(_("There was a problem printing.\n"
                        "Perhaps your current printer is not set correctly?"))
         else:
-            self.printData = wx.PrintData( printer.GetPrintDialogData().GetPrintData() )
+            self.printData = wx.PrintData(
+                printer.GetPrintDialogData().GetPrintData())
         printout.Destroy()

Modified: grass/trunk/gui/wxpython/mapdisp/main.py
===================================================================
--- grass/trunk/gui/wxpython/mapdisp/main.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/mapdisp/main.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -35,16 +35,16 @@
 from grass.script.setup import set_gui_path
 set_gui_path()
 
-from core          import globalvar
+from core import globalvar
 import wx
 
-from core          import utils
-from core.giface   import StandaloneGrassInterface
-from core.gcmd     import RunCommand
-from core.render   import Map, MapLayer, Overlay, RenderMapMgr
+from core import utils
+from core.giface import StandaloneGrassInterface
+from core.gcmd import RunCommand
+from core.render import Map, MapLayer, Overlay, RenderMapMgr
 from core.utils import _
 from mapdisp.frame import MapFrame
-from core.debug    import Debug
+from core.debug import Debug
 from core.settings import UserSettings
 
 from grass.script.utils import try_remove
@@ -53,15 +53,17 @@
 from grass.pydispatch.signal import Signal
 
 # for standalone app
-monFile = { 'cmd' : None,
-            'map' : None,
-            'env' : None,
-            }
+monFile = {'cmd': None,
+           'map': None,
+           'env': None,
+           }
 monName = None
 monSize = list(globalvar.MAP_WINDOW_SIZE)
 monDecor = False
 
+
 class DMonMap(Map):
+
     def __init__(self, giface, cmdfile=None, mapfile=None):
         """Map composition (stack of map layers and overlays)
 
@@ -69,16 +71,17 @@
         :param mapfile: full path to the map file (defined by d.mon)
         """
         Map.__init__(self)
-        
+
         self._giface = giface
 
         # environment settings
-        self.env   = dict()
+        self.env = dict()
 
         self.cmdfile = cmdfile
 
         # list of layers for rendering added from cmd file
-        # TODO temporary solution, layer managment by different tools in GRASS should be resovled
+        # TODO temporary solution, layer managment by different tools in GRASS
+        # should be resovled
         self.ownedLayers = []
 
         if mapfile:
@@ -89,15 +92,17 @@
         self.mapfile = monFile['map']
         if os.path.splitext(self.mapfile)[1] != '.ppm':
             self.mapfile += '.ppm'
-        
-        # signal sent when d.out.file/d.to.rast appears in cmd file, attribute is cmd
+
+        # signal sent when d.out.file/d.to.rast appears in cmd file, attribute
+        # is cmd
         self.saveToFile = Signal('DMonMap.saveToFile')
         self.dToRast = Signal('DMonMap.dToRast')
-        # signal sent when d.what.rast/vect appears in cmd file, attribute is cmd
+        # signal sent when d.what.rast/vect appears in cmd file, attribute is
+        # cmd
         self.query = Signal('DMonMap.query')
 
         self.renderMgr = RenderMapMgr(self)
-        
+
     def GetLayersFromCmdFile(self):
         """Get list of map layers from cmdfile
         """
@@ -109,7 +114,8 @@
             fd = open(self.cmdfile, 'r')
             lines = fd.readlines()
             fd.close()
-            # detect d.out.file, delete the line from the cmd file and export graphics
+            # detect d.out.file, delete the line from the cmd file and export
+            # graphics
             if len(lines) > 0:
                 if lines[-1].startswith('d.out.file') or \
                    lines[-1].startswith('d.to.rast'):
@@ -128,12 +134,14 @@
                     fd.writelines(lines[:-1])
                     fd.close()
                     if '=' in utils.split(dWhatCmd)[1]:
-                        maps = utils.split(dWhatCmd)[1].split('=')[1].split(',')
+                        maps = utils.split(dWhatCmd)[1].split('=')[
+                            1].split(',')
                     else:
                         maps = utils.split(dWhatCmd)[1].split(',')
-                    self.query.emit(ltype=utils.split(dWhatCmd)[0].split('.')[-1], maps=maps)
+                    self.query.emit(ltype=utils.split(dWhatCmd)[
+                                    0].split('.')[-1], maps=maps)
                     return
-            
+
             existingLayers = self.GetListOfLayers()
 
             # holds new rendreing order for every layer in existingLayers
@@ -153,19 +161,19 @@
                         pass
                     render_env[k] = v
                     continue
-                
+
                 cmd = utils.split(line.strip())
-                
+
                 ltype = None
                 try:
                     ltype = utils.command2ltype[cmd[0]]
                 except KeyError:
                     grass.warning(_("Unsupported command %s.") % cmd[0])
                     continue
-                
-                name = utils.GetLayerNameFromCmd(cmd, fullyQualified = True,
-                                                 layerType = ltype)[0]
 
+                name = utils.GetLayerNameFromCmd(cmd, fullyQualified=True,
+                                                 layerType=ltype)[0]
+
                 args = {}
                 if ltype in ('barscale', 'rastleg', 'northarrow'):
                     classLayer = Overlay
@@ -178,39 +186,48 @@
                 else:
                     classLayer = MapLayer
                     args['ltype'] = ltype
-                
-                mapLayer = classLayer(name = name, cmd = cmd, Map = None,
-                                      hidden = True, render = False, mapfile = mapFile, **args)
-                mapLayer.GetRenderMgr().updateProgress.connect(self.GetRenderMgr().ReportProgress)
+
+                mapLayer = classLayer(
+                    name=name,
+                    cmd=cmd,
+                    Map=None,
+                    hidden=True,
+                    render=False,
+                    mapfile=mapFile,
+                    **args)
+                mapLayer.GetRenderMgr().updateProgress.connect(
+                    self.GetRenderMgr().ReportProgress)
                 if render_env:
                     mapLayer.GetRenderMgr().UpdateRenderEnv(render_env)
                     render_env = dict()
-                    
+
                 exists = False
                 for i, layer in enumerate(existingLayers):
-                    if layer.GetCmd(string=True) == mapLayer.GetCmd(string=True):
+                    if layer.GetCmd(
+                            string=True) == mapLayer.GetCmd(
+                            string=True):
                         exists = True
 
-                        if layersOrder[i] == -1: 
-                            layersOrder[i] = next_layer;
+                        if layersOrder[i] == -1:
+                            layersOrder[i] = next_layer
                             next_layer += 1
                         # layer must be put higher in render order (same cmd was insered more times)
                         # TODO delete rendurant cmds from cmd file?
                         else:
                             for j, l_order in enumerate(layersOrder):
                                 if l_order > layersOrder[i]:
-                                    layersOrder[j] -= 1;
-                            layersOrder[i] = next_layer - 1;
+                                    layersOrder[j] -= 1
+                            layersOrder[i] = next_layer - 1
 
                         break
                 if exists:
                     continue
-                
+
                 newLayer = self._addLayer(mapLayer)
-                                
+
                 existingLayers.append(newLayer)
                 self.ownedLayers.append(newLayer)
-                
+
                 layersOrder.append(next_layer)
                 next_layer += 1
 
@@ -219,7 +236,7 @@
             reorderedLayers = [-1] * next_layer
             for i, layer in enumerate(existingLayers):
 
-                # owned layer was not found in cmd file -> is deleted 
+                # owned layer was not found in cmd file -> is deleted
                 if layersOrder[i] == -1 and layer in self.ownedLayers:
                     self.ownedLayers.remove(layer)
                     self.DeleteLayer(layer)
@@ -227,36 +244,38 @@
                 # other layer e. g. added by wx.vnet are added to the top
                 elif layersOrder[i] == -1 and layer not in self.ownedLayers:
                     reorderedLayers.append(layer)
-                
-                # owned layer found in cmd file is added into proper rendering position
+
+                # owned layer found in cmd file is added into proper rendering
+                # position
                 else:
                     reorderedLayers[layersOrder[i]] = layer
-            
+
             self.SetLayers(reorderedLayers)
-            
+
         except IOError as e:
-            grass.warning(_("Unable to read cmdfile '%(cmd)s'. Details: %(det)s") % \
-                              { 'cmd' : self.cmdfile, 'det' : e })
+            grass.warning(
+                _("Unable to read cmdfile '%(cmd)s'. Details: %(det)s") %
+                {'cmd': self.cmdfile, 'det': e})
             return
-        
-        Debug.msg(1, "Map.GetLayersFromCmdFile(): cmdfile=%s, nlayers=%d" % \
+
+        Debug.msg(1, "Map.GetLayersFromCmdFile(): cmdfile=%s, nlayers=%d" %
                   (self.cmdfile, nlayers))
-        
+
         self._giface.updateMap.emit(render=False)
-        
+
     def Render(self, *args, **kwargs):
         """Render layer to image.
 
         For input params and returned data see overridden method in Map class.
         """
         return Map.Render(self, *args, **kwargs)
-    
+
     def AddLayer(self, *args, **kwargs):
         """Adds generic map layer to list of layers.
 
         For input params and returned data see overridden method in Map class.
         """
-        driver = UserSettings.Get(group = 'display', key = 'driver', subkey = 'type')
+        driver = UserSettings.Get(group='display', key='driver', subkey='type')
 
         if driver == 'png':
             os.environ["GRASS_RENDER_IMMEDIATE"] = "png"
@@ -272,6 +291,7 @@
 
 class Layer(object):
     """@implements core::giface::Layer"""
+
     def __init__(self, maplayer):
         self._maplayer = maplayer
 
@@ -284,14 +304,15 @@
             return self._maplayer
         elif name == 'type':
             return self._maplayer.GetType()
-            #elif name == 'ctrl':
+            # elif name == 'ctrl':
         elif name == 'label':
             return self._maplayer.GetName()
-            #elif name == 'propwin':
+            # elif name == 'propwin':
 
 
 class LayerList(object):
     """@implements core::giface::LayerList"""
+
     def __init__(self, map, giface):
         self._map = map
         self._giface = giface
@@ -358,10 +379,11 @@
 
 class DMonGrassInterface(StandaloneGrassInterface):
     """@implements GrassInterface"""
+
     def __init__(self, mapframe):
         StandaloneGrassInterface.__init__(self)
         self._mapframe = mapframe
-        
+
     def GetLayerList(self):
         return LayerList(self._mapframe.GetMap(), giface=self)
 
@@ -377,17 +399,17 @@
     def ShowStatusbar(self, show=True):
         if not self._mapframe.statusbarManager:
             self._mapframe.CreateStatusbar()
-        
+
         self._mapframe.statusbarManager.Show(show)
 
     def IsStatusbarShown(self):
         if not self._mapframe.statusbarManager:
             return False
-        
+
         return self._mapframe.statusbarManager.IsShown()
 
     def ShowAllToolbars(self, show=True):
-        if not show: # hide
+        if not show:  # hide
             action = self._mapframe.RemoveToolbar
         else:
             action = self._mapframe.AddToolbar
@@ -396,19 +418,21 @@
             toolbars.append('map')
         for toolbar in toolbars:
             action(toolbar)
-    
+
     def AreAllToolbarsShown(self):
         toolbar = self._mapframe.GetMapToolbar()
         if toolbar is None:
             return False
-        
+
         return toolbar.IsShown()
 
+
 class DMonFrame(MapFrame):
+
     def OnZoomToMap(self, event):
         layers = self.MapWindow.GetMap().GetListOfLayers()
-        self.MapWindow.ZoomToMap(layers = layers)
-        
+        self.MapWindow.ZoomToMap(layers=layers)
+
     def OnSize(self, event):
         super(DMonFrame, self).OnSize(event)
 
@@ -421,8 +445,10 @@
                 print 'GRASS_RENDER_HEIGHT={}'.format(height)
             else:
                 print line.rstrip('\n')
-    
+
+
 class MapApp(wx.App):
+
     def OnInit(self):
         if not globalvar.CheckWxVersion([2, 9]):
             wx.InitAllImageHandlers()
@@ -431,9 +457,9 @@
         # actual use of StandaloneGrassInterface not yet tested
         # needed for adding functionality in future
         self._giface = DMonGrassInterface(None)
-        
+
         return True
-    
+
     def CreateMapFrame(self, name, decorations=True):
         toolbars = []
         if decorations:
@@ -442,32 +468,41 @@
         if __name__ == "__main__":
             self.cmdTimeStamp = os.path.getmtime(monFile['cmd'])
             self.Map = DMonMap(giface=self._giface, cmdfile=monFile['cmd'],
-                               mapfile = monFile['map'])
-            
+                               mapfile=monFile['map'])
+
             self.timer = wx.PyTimer(self.watcher)
-            #check each 0.5s
+            # check each 0.5s
             global mtime
             mtime = 500
             self.timer.Start(mtime)
         else:
             self.Map = None
-        
-        self.mapFrm = DMonFrame(parent=None, id=wx.ID_ANY, title=name, Map=self.Map,
-                                giface=self._giface, size=monSize,
-                                toolbars=toolbars, statusbar=decorations)
-        
+
+        self.mapFrm = DMonFrame(
+            parent=None,
+            id=wx.ID_ANY,
+            title=name,
+            Map=self.Map,
+            giface=self._giface,
+            size=monSize,
+            toolbars=toolbars,
+            statusbar=decorations)
+
         # FIXME: hack to solve dependency
         self._giface._mapframe = self.mapFrm
-        
+
         self.mapFrm.GetMapWindow().SetAlwaysRenderEnabled(False)
 
         self.Map.saveToFile.connect(lambda cmd: self.mapFrm.DOutFile(cmd))
         self.Map.dToRast.connect(lambda cmd: self.mapFrm.DToRast(cmd))
-        self.Map.query.connect(lambda ltype, maps: \
-                               self.mapFrm.SetQueryLayersAndActivate(ltype=ltype, maps=maps))
+        self.Map.query.connect(
+            lambda ltype,
+            maps: self.mapFrm.SetQueryLayersAndActivate(
+                ltype=ltype,
+                maps=maps))
 
         return self.mapFrm
-    
+
     def OnExit(self):
         if __name__ == "__main__":
             # stop the timer
@@ -475,25 +510,25 @@
             # terminate thread
             for f in monFile.itervalues():
                 try_remove(f)
-            
+
     def watcher(self):
         """Redraw, if new layer appears (check's timestamp of
         cmdfile)
         """
         ###
-        ### TODO: find a better solution
+        # TODO: find a better solution
         ###
-        ### the check below disabled, it's too much invasive to call
-        ### g.gisenv in the watcher...
+        # the check below disabled, it's too much invasive to call
+        # g.gisenv in the watcher...
         # try:
-            # GISBASE and other system enviromental variables can not be used
-            # since the process inherited them from GRASS
-            # raises exception when vaiable does not exists
-            ### grass.gisenv()['GISDBASE']
+        # GISBASE and other system enviromental variables can not be used
+        # since the process inherited them from GRASS
+        # raises exception when vaiable does not exists
+        # grass.gisenv()['GISDBASE']
         # except KeyError:
         #    self.timer.Stop()
         #    return
-        
+
         # todo: events
         try:
             currentCmdFileTime = os.path.getmtime(monFile['cmd'])
@@ -514,17 +549,17 @@
     if len(sys.argv) != 6:
         print __doc__
         sys.exit(0)
-    
+
     # set command variable
     monName = sys.argv[1]
     monPath = sys.argv[2]
-    monFile = { 'map' : os.path.join(monPath, 'map.ppm'),
-                'cmd' : os.path.join(monPath, 'cmd'),
-                'env' : os.path.join(monPath, 'env') }
+    monFile = {'map': os.path.join(monPath, 'map.ppm'),
+               'cmd': os.path.join(monPath, 'cmd'),
+               'env': os.path.join(monPath, 'env')}
 
     # monitor size
     monSize = (int(sys.argv[3]), int(sys.argv[4]))
-    
+
     monDecor = not bool(int(sys.argv[5]))
     grass.verbose(_("Starting map display <%s>...") % (monName))
 
@@ -535,19 +570,19 @@
         grass.fatal(_("Unable to create file <%s>") % pidFile)
     fd.write("%s\n" % os.getpid())
     fd.close()
-        
+
     RunCommand('g.gisenv',
-               set = 'MONITOR_%s_PID=%d' % (monName.upper(), os.getpid()))
+               set='MONITOR_%s_PID=%d' % (monName.upper(), os.getpid()))
 
     start = time.time()
     gmMap = MapApp(0)
     mapFrame = gmMap.CreateMapFrame(monName, monDecor)
     mapFrame.Show()
-    Debug.msg(1, "WxMonitor started in %.6f sec" % \
-                  (time.time() - start))
-    
+    Debug.msg(1, "WxMonitor started in %.6f sec" %
+              (time.time() - start))
+
     gmMap.MainLoop()
-    
+
     grass.verbose(_("Stopping map display <%s>...") % (monName))
 
     # clean up GRASS env variables
@@ -555,8 +590,8 @@
         shutil.rmtree(monPath)
     except OSError:
         pass
-    
+
     RunCommand('g.gisenv',
-               unset = 'MONITOR')
-    
+               unset='MONITOR')
+
     sys.exit(0)

Modified: grass/trunk/gui/wxpython/mapdisp/statusbar.py
===================================================================
--- grass/trunk/gui/wxpython/mapdisp/statusbar.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/mapdisp/statusbar.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -34,26 +34,29 @@
 import copy
 import wx
 
-from core          import utils
-from core.gcmd     import GMessage, RunCommand
+from core import utils
+from core.gcmd import GMessage, RunCommand
 from core.settings import UserSettings
 from core.utils import _
 
-from grass.script  import core as grass
+from grass.script import core as grass
 
 from grass.pydispatch.signal import Signal
 
+
 class SbException:
     """Exception class used in SbManager and SbItems"""
+
     def __init__(self, message):
         self.message = message
+
     def __str__(self):
         return self.message
 
 
 class SbManager:
     """Statusbar manager for wx.Statusbar and SbItems.
-    
+
     Statusbar manager manages items added by AddStatusbarItem method.
     Provides progress bar (SbProgress) and choice (wx.Choice).
     Items with position 0 are shown according to choice selection.
@@ -62,30 +65,31 @@
     and call Update method to show particular widgets.
     User settings (group = 'display', key = 'statusbarMode', subkey = 'selection')
     are taken into account.
-    
+
     .. todo::
-        generalize access to UserSettings (specify group, etc.) 
+        generalize access to UserSettings (specify group, etc.)
 
     .. todo::
         add GetMode method using name instead of index
     """
+
     def __init__(self, mapframe, statusbar):
         """Connects manager to statusbar
-        
+
         Creates choice and progress bar.
         """
         self.mapFrame = mapframe
         self.statusbar = statusbar
-        
+
         self.choice = wx.Choice(self.statusbar, wx.ID_ANY)
-        
+
         self.choice.Bind(wx.EVT_CHOICE, self.OnToggleStatus)
-        
+
         self.statusbarItems = dict()
-        
+
         self._postInitialized = False
         self._modeIndexSet = False
-        
+
         self.progressbar = SbProgress(self.mapFrame, self.statusbar, self)
         self.progressbar.progressShown.connect(self._progressShown)
         self.progressbar.progressHidden.connect(self._progressHidden)
@@ -93,66 +97,66 @@
         self._oldStatus = ''
 
         self._hiddenItems = {}
-    
+
     def SetProperty(self, name, value):
         """Sets property represented by one of contained SbItems
-            
+
         :param name: name of SbItem (from name attribute)
         :param value: value to be set
         """
         self.statusbarItems[name].SetValue(value)
-        
+
     def GetProperty(self, name):
         """Returns property represented by one of contained SbItems
-        
+
         :param name: name of SbItem (from name attribute)
         """
         return self.statusbarItems[name].GetValue()
-        
+
     def HasProperty(self, name):
         """Checks whether property is represented by one of contained SbItems
-        
+
         :param name: name of SbItem (from name attribute)
-        
+
         :return: True if particular SbItem is contained, False otherwise
         """
         if name in self.statusbarItems:
             return True
         return False
-    
+
     def AddStatusbarItem(self, item):
         """Adds item to statusbar
-        
-        If item position is 0, item is managed by choice.        
-        
+
+        If item position is 0, item is managed by choice.
+
         :func:`AddStatusbarItemsByClass`
         """
         self.statusbarItems[item.name] = item
         if item.GetPosition() == 0:
-            self.choice.Append(item.label, clientData = item) #attrError?
-            
+            self.choice.Append(item.label, clientData=item)  # attrError?
+
     def AddStatusbarItemsByClass(self, itemClasses, **kwargs):
         """Adds items to statusbar
 
         :param list itemClasses: list of classes of items to be add
         :param kwargs: SbItem constructor parameters
-        
+
         :func:`AddStatusbarItem`
         """
         for Item in itemClasses:
             item = Item(**kwargs)
             self.AddStatusbarItem(item)
-                      
+
     def HideStatusbarChoiceItemsByClass(self, itemClasses):
         """Hides items showed in choice
-        
+
         Hides items with position 0 (items showed in choice) by removing
         them from choice.
-        
+
         :param itemClasses list of classes of items to be hided
-        
+
         :func:`ShowStatusbarChoiceItemsByClass`
-        
+
         .. todo::
             consider adding similar function which would take item names
         """
@@ -164,18 +168,18 @@
                     index.append(i)
                     self._hiddenItems[i] = item
         # must be sorted in reverse order to be removed correctly
-        for i in sorted(index, reverse = True):
+        for i in sorted(index, reverse=True):
             self.choice.Delete(i)
-        
+
     def ShowStatusbarChoiceItemsByClass(self, itemClasses):
         """Shows items showed in choice
-        
+
         Shows items with position 0 (items showed in choice) by adding
         them to choice.
         Items are restored in their old positions.
-        
+
         :param itemClasses list of classes of items to be showed
-        
+
         :func:`HideStatusbarChoiceItemsByClass`
         """
         # must be sorted to be inserted correctly
@@ -183,38 +187,38 @@
             item = self._hiddenItems[pos]
             if item.__class__ in itemClasses:
                 self.choice.Insert(item.label, pos, item)
-        
+
     def ShowItem(self, itemName):
         """Invokes showing of particular item
-        
+
         :func:`Update`
         """
         if self.statusbarItems[itemName].GetPosition() != 0 or \
            not self.progressbar.IsShown():
             self.statusbarItems[itemName].Show()
-        
+
     def _postInit(self):
         """Post-initialization method
-        
+
         It sets internal user settings,
         set choice's selection (from user settings) and does reposition.
         It needs choice filled by items.
         it is called automatically.
         """
-        UserSettings.Set(group = 'display',
-                         key = 'statusbarMode',
-                         subkey = 'choices',
-                         value = self.choice.GetItems(),
+        UserSettings.Set(group='display',
+                         key='statusbarMode',
+                         subkey='choices',
+                         value=self.choice.GetItems(),
                          settings_type='internal')
 
         if not self._modeIndexSet:
-            self.choice.SetSelection(UserSettings.Get(group = 'display',
-                                                      key = 'statusbarMode',
-                                                      subkey = 'selection'))
+            self.choice.SetSelection(UserSettings.Get(group='display',
+                                                      key='statusbarMode',
+                                                      subkey='selection'))
         self.Reposition()
-        
+
         self._postInitialized = True
-        
+
     def Update(self):
         """Updates statusbar
 
@@ -229,33 +233,33 @@
                 if not self.progressbar.IsShown():
                     item.Hide()
             else:
-                item.Update() # mask, render
+                item.Update()  # mask, render
 
         if self.progressbar.IsShown():
             pass
         elif self.choice.GetCount() > 0:
             item = self.choice.GetClientData(self.choice.GetSelection())
             item.Update()
-        
+
     def Reposition(self):
         """Reposition items in statusbar
-        
+
         Set positions to all items managed by statusbar manager.
         It should not be necessary to call it manually.
         """
-        
+
         widgets = []
         for item in self.statusbarItems.values():
             widgets.append((item.GetPosition(), item.GetWidget()))
-            
+
         widgets.append((1, self.choice))
         widgets.append((1, self.progressbar.GetWidget()))
-                
+
         for idx, win in widgets:
             if not win:
                 continue
             rect = self.statusbar.GetFieldRect(idx)
-            if idx == 0: # show region / mapscale / process bar
+            if idx == 0:  # show region / mapscale / process bar
                 # -> size
                 wWin, hWin = win.GetBestSize()
                 # -> position
@@ -265,19 +269,19 @@
                 # else:
                 x, y = rect.x + 3, rect.y - 1
                 w, h = wWin, rect.height + 2
-            else: # choice || auto-rendering
+            else:  # choice || auto-rendering
                 x, y = rect.x, rect.y
                 w, h = rect.width, rect.height + 1
                 if win == self.progressbar.GetWidget():
                     wWin = rect.width - 6
-                if idx == 2: # mask
+                if idx == 2:  # mask
                     x += 5
                     y += 4
-                elif idx == 3: # render
+                elif idx == 3:  # render
                     x += 5
             win.SetPosition((x, y))
             win.SetSize((w, h))
-        
+
     def GetProgressBar(self):
         """Returns progress bar"""
         return self.progressbar
@@ -294,21 +298,21 @@
         """Toggle status text
         """
         self.Update()
-        if event.GetSelection() == 3: # use something better than magic numbers
+        if event.GetSelection() == 3:  # use something better than magic numbers
             # show computation region extent by default
             self.statusbarItems['region'].SetValue(True)
             # redraw map if auto-rendering is enabled
             if self.mapFrame.IsAutoRendered():
                 self.mapFrame.OnRender(None)
-        
+
     def SetMode(self, modeIndex):
         """Sets current mode
-        
+
         Mode is usually driven by user through choice.
         """
         self._modeIndexSet = True
         self.choice.SetSelection(modeIndex)
-    
+
     def GetMode(self):
         """Returns current mode"""
         return self.choice.GetSelection()
@@ -328,9 +332,10 @@
         """Check if statusbar is shown"""
         return self.statusbar.IsShown()
 
+
 class SbItem:
     """Base class for statusbar items.
-    
+
     Each item represents functionality (or action) controlled by statusbar
     and related to MapFrame.
     One item is usually connected with one widget but it is not necessary.
@@ -338,80 +343,83 @@
     Items are not widgets but can provide interface to them.
     Items usually has requirements to MapFrame instance
     (specified as MapFrame.methodname or MapWindow.methodname).
-    
+
     .. todo::
         consider externalizing position (see SbProgress use in SbManager)
     """
-    def __init__(self, mapframe, statusbar, position = 0):
+
+    def __init__(self, mapframe, statusbar, position=0):
         """
-        
+
         :param mapframe: instance of class with MapFrame interface
         :param statusbar: statusbar instance (wx.Statusbar)
         :param position: item position in statusbar
-        
+
         .. todo::
             rewrite Update also in derived classes to take in account item position
         """
         self.mapFrame = mapframe
         self.statusbar = statusbar
         self.position = position
-    
+
     def Show(self):
         """Invokes showing of underlying widget.
-        
+
         In derived classes it can do what is appropriate for it,
         e.g. showing text on statusbar (only).
         """
         self.widget.Show()
-        
+
     def Hide(self):
         self.widget.Hide()
-        
+
     def SetValue(self, value):
         self.widget.SetValue(value)
-    
+
     def GetValue(self):
         return self.widget.GetValue()
-        
+
     def GetPosition(self):
         return self.position
-    
+
     def GetWidget(self):
         """Returns underlaying winget.
-        
+
         :return: widget or None if doesn't exist
         """
         return self.widget
-    
+
     def _update(self, longHelp):
         """Default implementation for Update method.
-        
+
         :param longHelp: True to enable long help (help from toolbars)
         """
         self.statusbar.SetStatusText("", 0)
         self.Show()
         self.mapFrame.StatusbarEnableLongHelp(longHelp)
-        
+
     def Update(self):
         """Called when statusbar action is activated (e.g. through wx.Choice).
         """
-        self._update(longHelp = False)
+        self._update(longHelp=False)
 
+
 class SbRender(SbItem):
     """Checkbox to enable and disable auto-rendering.
-    
+
     Requires MapFrame.OnRender method.
     """
-    def __init__(self, mapframe, statusbar, position = 0):
+
+    def __init__(self, mapframe, statusbar, position=0):
         SbItem.__init__(self, mapframe, statusbar, position)
         self.name = 'render'
         self._properties = mapframe.mapWindowProperties
-        self.widget = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
-                                  label = _("Render"))
-        
+        self.widget = wx.CheckBox(parent=self.statusbar, id=wx.ID_ANY,
+                                  label=_("Render"))
+
         self.widget.SetValue(self._properties.autoRender)
         self.widget.Hide()
-        self.widget.SetToolTip(wx.ToolTip (_("Enable/disable auto-rendering")))
+        self.widget.SetToolTip(wx.ToolTip(_("Enable/disable auto-rendering")))
 
         self._connectAutoRender()
         self.widget.Bind(wx.EVT_CHECKBOX, self._onCheckbox)
@@ -432,28 +440,33 @@
 
     def Update(self):
         self.Show()
-        
+
+
 class SbShowRegion(SbItem):
     """Checkbox to enable and disable showing of computational region.
-    
+
     Requires MapFrame.OnRender, MapFrame.IsAutoRendered, MapFrame.GetWindow.
     """
-    def __init__(self, mapframe, statusbar, position = 0):
+
+    def __init__(self, mapframe, statusbar, position=0):
         SbItem.__init__(self, mapframe, statusbar, position)
         self.name = 'region'
         self.label = _("Show comp. extent")
         self._properties = mapframe.mapWindowProperties
 
-        self.widget = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
-                                  label = _("Show computational extent"))
+        self.widget = wx.CheckBox(parent=self.statusbar, id=wx.ID_ANY,
+                                  label=_("Show computational extent"))
         self.widget.SetValue(self._properties.showRegion)
         self.widget.Hide()
-        self.widget.SetToolTip(wx.ToolTip (_("Show/hide computational "
-                                             "region extent (set with g.region). "
-                                             "Display region drawn as a blue box inside the "
-                                             "computational region, "
-                                             "computational region inside a display region "
-                                             "as a red box).")))
+        self.widget.SetToolTip(
+            wx.ToolTip(
+                _(
+                    "Show/hide computational "
+                    "region extent (set with g.region). "
+                    "Display region drawn as a blue box inside the "
+                    "computational region, "
+                    "computational region inside a display region "
+                    "as a red box).")))
         self.widget.Bind(wx.EVT_CHECKBOX, self.OnToggleShowRegion)
         self._connectShowRegion()
 
@@ -468,7 +481,7 @@
 
     def OnToggleShowRegion(self, event):
         """Shows/Hides extent (comp. region) in map canvas.
-        
+
         Shows or hides according to checkbox value.
 
         .. todo::
@@ -488,26 +501,32 @@
         SbItem.SetValue(self, value)
         self._connectShowRegion()
 
+
 class SbAlignExtent(SbItem):
     """Checkbox to select zoom behavior.
-    
+
     Used by BufferedWindow (through MapFrame property).
     See tooltip for explanation.
     """
-    def __init__(self, mapframe, statusbar, position = 0):
+
+    def __init__(self, mapframe, statusbar, position=0):
         SbItem.__init__(self, mapframe, statusbar, position)
         self.name = 'alignExtent'
         self.label = _("Display mode")
         self._properties = mapframe.mapWindowProperties
 
-        self.widget = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
-                                  label = _("Align region extent based on display size"))
+        self.widget = wx.CheckBox(
+            parent=self.statusbar, id=wx.ID_ANY,
+            label=_("Align region extent based on display size"))
         self.widget.SetValue(self._properties.alignExtent)
         self.widget.Hide()
-        self.widget.SetToolTip(wx.ToolTip (_("Align region extent based on display "
-                                             "size from center point. "
-                                             "Default value for new map displays can "
-                                             "be set up in 'User GUI settings' dialog.")))      
+        self.widget.SetToolTip(
+            wx.ToolTip(
+                _(
+                    "Align region extent based on display "
+                    "size from center point. "
+                    "Default value for new map displays can "
+                    "be set up in 'User GUI settings' dialog.")))
         self._connectAlignExtent()
         self.widget.Bind(wx.EVT_CHECKBOX, self._onCheckbox)
 
@@ -531,23 +550,27 @@
 
 class SbResolution(SbItem):
     """Checkbox to select used display resolution.
-    
-    Requires MapFrame.OnRender method. 
+
+    Requires MapFrame.OnRender method.
     """
-    def __init__(self, mapframe, statusbar, position = 0):
+
+    def __init__(self, mapframe, statusbar, position=0):
         SbItem.__init__(self, mapframe, statusbar, position)
         self.name = 'resolution'
         self.label = _("Display resolution")
         self._properties = self.mapFrame.mapWindowProperties
-        self.widget = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
-                                  label = _("Constrain display resolution to computational settings"))
+        self.widget = wx.CheckBox(parent=self.statusbar, id=wx.ID_ANY, label=_(
+            "Constrain display resolution to computational settings"))
         self.widget.SetValue(self._properties.resolution)
         self.widget.Hide()
-        self.widget.SetToolTip(wx.ToolTip (_("Constrain display resolution "
-                                             "to computational region settings. "
-                                             "Default value for new map displays can "
-                                             "be set up in 'User GUI settings' dialog.")))
-                                            
+        self.widget.SetToolTip(
+            wx.ToolTip(
+                _(
+                    "Constrain display resolution "
+                    "to computational region settings. "
+                    "Default value for new map displays can "
+                    "be set up in 'User GUI settings' dialog.")))
+
         self.widget.Bind(wx.EVT_CHECKBOX, self.OnToggleUpdateMap)
         self._connectResolutionChange()
 
@@ -573,19 +596,20 @@
 
 class SbMapScale(SbItem):
     """Editable combobox to get/set current map scale.
-    
+
     Requires MapFrame.GetMapScale, MapFrame.SetMapScale
     and MapFrame.GetWindow (and GetWindow().UpdateMap()).
     """
-    def __init__(self, mapframe, statusbar, position = 0):
+
+    def __init__(self, mapframe, statusbar, position=0):
         SbItem.__init__(self, mapframe, statusbar, position)
         self.name = 'mapscale'
         self.label = _("Map scale")
-        
-        self.widget = wx.ComboBox(parent = self.statusbar, id = wx.ID_ANY,
-                                                    style = wx.TE_PROCESS_ENTER,
-                                                    size = (150, -1))
-        
+
+        self.widget = wx.ComboBox(parent=self.statusbar, id=wx.ID_ANY,
+                                  style=wx.TE_PROCESS_ENTER,
+                                  size=(150, -1))
+
         self.widget.SetItems(['1:1000',
                               '1:5000',
                               '1:10000',
@@ -594,14 +618,17 @@
                               '1:100000',
                               '1:1000000'])
         self.widget.Hide()
-        self.widget.SetToolTip(wx.ToolTip (_("As everyone's monitors and resolutions "
-                                            "are set differently these values are not "
-                                            "true map scales, but should get you into "
-                                            "the right neighborhood.")))
-                                            
+        self.widget.SetToolTip(
+            wx.ToolTip(
+                _(
+                    "As everyone's monitors and resolutions "
+                    "are set differently these values are not "
+                    "true map scales, but should get you into "
+                    "the right neighborhood.")))
+
         self.widget.Bind(wx.EVT_TEXT_ENTER, self.OnChangeMapScale)
         self.widget.Bind(wx.EVT_COMBOBOX, self.OnChangeMapScale)
-        
+
         self.lastMapScale = None
 
     def Update(self):
@@ -610,8 +637,8 @@
         try:
             self.SetValue("1:%ld" % (scale + 0.5))
         except TypeError:
-            pass # FIXME, why this should happen?
-        
+            pass  # FIXME, why this should happen?
+
         self.lastMapScale = scale
         self.Show()
 
@@ -630,67 +657,67 @@
         except ValueError:
             self.SetValue('1:%ld' % int(self.lastMapScale))
             return
-        
+
         self.mapFrame.SetMapScale(value)
-        
+
         # redraw a map
         self.mapFrame.GetWindow().UpdateMap()
         self.GetWidget().SetFocus()
-        
-        
+
+
 class SbGoTo(SbItem):
     """Textctrl to set coordinates which to focus on.
-    
+
     Requires MapFrame.GetWindow, MapWindow.GoTo method.
     """
-    
-    def __init__(self, mapframe, statusbar, position = 0):
+
+    def __init__(self, mapframe, statusbar, position=0):
         SbItem.__init__(self, mapframe, statusbar, position)
         self.name = 'goto'
         self.label = _("Go to")
-        
-        self.widget = wx.TextCtrl(parent = self.statusbar, id = wx.ID_ANY,
-                                                value = "", style = wx.TE_PROCESS_ENTER,
-                                                size = (300, -1))
-        
+
+        self.widget = wx.TextCtrl(parent=self.statusbar, id=wx.ID_ANY,
+                                  value="", style=wx.TE_PROCESS_ENTER,
+                                  size=(300, -1))
+
         self.widget.Hide()
-        
+
         self.widget.Bind(wx.EVT_TEXT_ENTER, self.OnGoTo)
-    
+
     def ReprojectENToMap(self, e, n, useDefinedProjection):
         """Reproject east, north from user defined projection
-        
+
         :param e,n: coordinate (for DMS string, else float or string)
         :param useDefinedProjection: projection defined by user in settings dialog
-        
+
         @throws SbException if useDefinedProjection is True and projection is not defined in UserSettings
         """
         if useDefinedProjection:
-            settings = UserSettings.Get(group = 'projection', key = 'statusbar', subkey = 'proj4')
+            settings = UserSettings.Get(
+                group='projection', key='statusbar', subkey='proj4')
             if not settings:
-                raise SbException(_("Projection not defined (check the settings)"))
+                raise SbException(
+                    _("Projection not defined (check the settings)"))
             else:
                 # reproject values
                 projIn = settings
                 projOut = RunCommand('g.proj',
-                                     flags = 'jf',
-                                     read = True)
+                                     flags='jf',
+                                     read=True)
                 proj = projIn.split(' ')[0].split('=')[1]
                 if proj in ('ll', 'latlong', 'longlat'):
                     e, n = utils.DMS2Deg(e, n)
-                    proj, coord1 = utils.ReprojectCoordinates(coord = (e, n),
-                                                              projIn = projIn,
-                                                              projOut = projOut, flags = 'd')
+                    proj, coord1 = utils.ReprojectCoordinates(
+                        coord=(e, n), projIn=projIn, projOut=projOut, flags='d')
                     e, n = coord1
                 else:
                     e, n = float(e), float(n)
-                    proj, coord1 = utils.ReprojectCoordinates(coord = (e, n),
-                                                              projIn = projIn,
-                                                              projOut = projOut, flags = 'd')
+                    proj, coord1 = utils.ReprojectCoordinates(
+                        coord=(e, n), projIn=projIn, projOut=projOut, flags='d')
                     e, n = coord1
         elif self.mapFrame.GetMap().projinfo['proj'] == 'll':
             e, n = utils.DMS2Deg(e, n)
-        else: 
+        else:
             e, n = float(e), float(n)
         return e, n
 
@@ -699,221 +726,258 @@
         """
         try:
             e, n = self.GetValue().split(';')
-            e, n = self.ReprojectENToMap(e, n, self.mapFrame.GetProperty('projection'))
+            e, n = self.ReprojectENToMap(
+                e, n, self.mapFrame.GetProperty('projection'))
             self.mapFrame.GetWindow().GoTo(e, n)
             self.widget.SetFocus()
         except ValueError:
             # FIXME: move this code to MapWindow/BufferedWindow/MapFrame
             region = self.mapFrame.GetMap().GetCurrentRegion()
-            precision = int(UserSettings.Get(group = 'projection', key = 'format',
-                                             subkey = 'precision'))
-            format = UserSettings.Get(group = 'projection', key = 'format',
-                                      subkey = 'll')
-            if self.mapFrame.GetMap().projinfo['proj'] == 'll' and format == 'DMS':
-                self.SetValue("%s" % utils.Deg2DMS(region['center_easting'], 
-                                                                            region['center_northing'],
-                                                                            precision = precision))
+            precision = int(UserSettings.Get(group='projection', key='format',
+                                             subkey='precision'))
+            format = UserSettings.Get(group='projection', key='format',
+                                      subkey='ll')
+            if self.mapFrame.GetMap().projinfo[
+                    'proj'] == 'll' and format == 'DMS':
+                self.SetValue("%s" % utils.Deg2DMS(region['center_easting'],
+                                                   region['center_northing'],
+                                                   precision=precision))
             else:
-                self.SetValue("%.*f; %.*f" % \
-                               (precision, region['center_easting'],
-                                precision, region['center_northing']))
+                self.SetValue("%.*f; %.*f" %
+                              (precision, region['center_easting'],
+                               precision, region['center_northing']))
         except SbException as e:
-            # FIXME: this may be useless since statusbar update checks user defined projection and this exception raises when user def proj does not exists
+            # FIXME: this may be useless since statusbar update checks user
+            # defined projection and this exception raises when user def proj
+            # does not exists
             self.statusbar.SetStatusText(str(e), 0)
 
     def GetCenterString(self, map):
         """Get current map center in appropriate format"""
         region = map.GetCurrentRegion()
-        precision = int(UserSettings.Get(group = 'projection', key = 'format',
-                                         subkey = 'precision'))
-        format = UserSettings.Get(group = 'projection', key = 'format',
-                                  subkey = 'll')
-        projection = UserSettings.Get(group='projection', key='statusbar', subkey='proj4')
-        
+        precision = int(UserSettings.Get(group='projection', key='format',
+                                         subkey='precision'))
+        format = UserSettings.Get(group='projection', key='format',
+                                  subkey='ll')
+        projection = UserSettings.Get(
+            group='projection',
+            key='statusbar',
+            subkey='proj4')
+
         if self.mapFrame.GetProperty('projection'):
             if not projection:
-                raise SbException(_("Projection not defined (check the settings)"))
+                raise SbException(
+                    _("Projection not defined (check the settings)"))
             else:
-                proj, coord  = utils.ReprojectCoordinates(coord = (region['center_easting'],
-                                                                   region['center_northing']),
-                                                          projOut = projection,
-                                                          flags = 'd')
+                proj, coord = utils.ReprojectCoordinates(
+                    coord=(region['center_easting'],
+                           region['center_northing']),
+                    projOut=projection, flags='d')
                 if coord:
-                    if proj in ('ll', 'latlong', 'longlat') and format == 'DMS':
+                    if proj in ('ll', 'latlong',
+                                'longlat') and format == 'DMS':
                         return "%s" % utils.Deg2DMS(coord[0],
-                                                                                coord[1],
-                                                                                precision = precision)
+                                                    coord[1],
+                                                    precision=precision)
                     else:
-                        return "%.*f; %.*f" % (precision, coord[0], precision, coord[1])
+                        return "%.*f; %.*f" % (precision,
+                                               coord[0], precision, coord[1])
                 else:
-                    raise SbException(_("Error in projection (check the settings)"))
+                    raise SbException(
+                        _("Error in projection (check the settings)"))
         else:
-            if self.mapFrame.GetMap().projinfo['proj'] == 'll' and format == 'DMS':
-                return "%s" % utils.Deg2DMS(region['center_easting'], region['center_northing'],
-                                                                      precision = precision)
+            if self.mapFrame.GetMap().projinfo[
+                    'proj'] == 'll' and format == 'DMS':
+                return "%s" % utils.Deg2DMS(
+                    region['center_easting'],
+                    region['center_northing'],
+                    precision=precision)
             else:
-                return "%.*f; %.*f" % (precision, region['center_easting'], precision, region['center_northing'])
+                return "%.*f; %.*f" % (
+                    precision, region['center_easting'],
+                    precision, region['center_northing'])
 
-
     def SetCenter(self):
         """Set current map center as item value"""
         center = self.GetCenterString(self.mapFrame.GetMap())
         self.SetValue(center)
-        
+
     def Update(self):
         self.statusbar.SetStatusText("")
-        
+
         try:
             self.SetCenter()
             self.Show()
         except SbException as e:
             self.statusbar.SetStatusText(str(e), 0)
-                        
+
         # disable long help
         self.mapFrame.StatusbarEnableLongHelp(False)
-        
 
+
 class SbProjection(SbItem):
     """Checkbox to enable user defined projection (can be set in settings)"""
-    def __init__(self, mapframe, statusbar, position = 0):
+
+    def __init__(self, mapframe, statusbar, position=0):
         SbItem.__init__(self, mapframe, statusbar, position)
         self.name = 'projection'
         self.label = _("Projection")
-        
+
         self.defaultLabel = _("Use defined projection")
-        
-        self.widget = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
-                                  label = self.defaultLabel)
-        
+
+        self.widget = wx.CheckBox(parent=self.statusbar, id=wx.ID_ANY,
+                                  label=self.defaultLabel)
+
         self.widget.SetValue(False)
-        
+
         # necessary?
         size = self.widget.GetSize()
         self.widget.SetMinSize((size[0] + 150, size[1]))
-        
+
         self.widget.Hide()
-        self.widget.SetToolTip(wx.ToolTip (_("Reproject coordinates displayed "
-                                             "in the statusbar. Projection can be "
-                                             "defined in GUI preferences dialog "
-                                             "(tab 'Projection')")))
-                                            
+        self.widget.SetToolTip(
+            wx.ToolTip(
+                _(
+                    "Reproject coordinates displayed "
+                    "in the statusbar. Projection can be "
+                    "defined in GUI preferences dialog "
+                    "(tab 'Projection')")))
+
     def Update(self):
         self.statusbar.SetStatusText("")
-        epsg = UserSettings.Get(group = 'projection', key = 'statusbar', subkey = 'epsg')
+        epsg = UserSettings.Get(
+            group='projection',
+            key='statusbar',
+            subkey='epsg')
         if epsg:
             label = '%s (EPSG: %s)' % (self.defaultLabel, epsg)
             self.widget.SetLabel(label)
         else:
             self.widget.SetLabel(self.defaultLabel)
         self.Show()
-        
+
         # disable long help
         self.mapFrame.StatusbarEnableLongHelp(False)
-        
 
+
 class SbMask(SbItem):
     """StaticText to show whether mask is activated."""
-    def __init__(self, mapframe, statusbar, position = 0):
+
+    def __init__(self, mapframe, statusbar, position=0):
         SbItem.__init__(self, mapframe, statusbar, position)
         self.name = 'mask'
-        
-        self.widget = wx.StaticText(parent = self.statusbar, id = wx.ID_ANY, label = _('MASK'))
+
+        self.widget = wx.StaticText(
+            parent=self.statusbar,
+            id=wx.ID_ANY,
+            label=_('MASK'))
         self.widget.SetForegroundColour(wx.Colour(255, 0, 0))
         self.widget.Hide()
-        
+
     def Update(self):
-        if grass.find_file(name = 'MASK', element = 'cell',
-                           mapset = grass.gisenv()['MAPSET'])['name']:
+        if grass.find_file(name='MASK', element='cell',
+                           mapset=grass.gisenv()['MAPSET'])['name']:
             self.Show()
         else:
             self.Hide()
-        
+
+
 class SbTextItem(SbItem):
     """Base class for items without widgets.
-    
+
     Only sets statusbar text.
     """
-    def __init__(self, mapframe, statusbar, position = 0):
+
+    def __init__(self, mapframe, statusbar, position=0):
         SbItem.__init__(self, mapframe, statusbar, position)
-        
+
         self.text = None
-        
+
     def Show(self):
         self.statusbar.SetStatusText(self.GetValue(), self.position)
-        
+
     def Hide(self):
         self.statusbar.SetStatusText("", self.position)
-        
+
     def SetValue(self, value):
         self.text = value
-    
+
     def GetValue(self):
         return self.text
-            
+
     def GetWidget(self):
         return None
-    
+
     def Update(self):
-        self._update(longHelp = True)
+        self._update(longHelp=True)
 
+
 class SbDisplayGeometry(SbTextItem):
     """Show current display resolution."""
-    def __init__(self, mapframe, statusbar, position = 0):
+
+    def __init__(self, mapframe, statusbar, position=0):
         SbTextItem.__init__(self, mapframe, statusbar, position)
         self.name = 'displayGeometry'
         self.label = _("Display geometry")
-        
+
     def Show(self):
         region = copy.copy(self.mapFrame.GetMap().GetCurrentRegion())
         if self.mapFrame.mapWindowProperties.resolution:
-            compRegion = self.mapFrame.GetMap().GetRegion(add3d = False)
-            region['rows'] = abs(int((region['n'] - region['s']) / compRegion['nsres']) + 0.5)
-            region['cols'] = abs(int((region['e'] - region['w']) / compRegion['ewres']) + 0.5)
+            compRegion = self.mapFrame.GetMap().GetRegion(add3d=False)
+            region['rows'] = abs(
+                int((region['n'] - region['s']) / compRegion['nsres']) + 0.5)
+            region['cols'] = abs(
+                int((region['e'] - region['w']) / compRegion['ewres']) + 0.5)
             region['nsres'] = compRegion['nsres']
             region['ewres'] = compRegion['ewres']
         self.SetValue("rows=%d; cols=%d; nsres=%.2f; ewres=%.2f" %
-                     (region["rows"], region["cols"],
-                      region["nsres"], region["ewres"]))
+                      (region["rows"], region["cols"],
+                       region["nsres"], region["ewres"]))
         SbTextItem.Show(self)
 
+
 class SbCoordinates(SbTextItem):
     """Show map coordinates when mouse moves.
-    
+
     Requires MapWindow.GetLastEN method."""
-    def __init__(self, mapframe, statusbar, position = 0):
+
+    def __init__(self, mapframe, statusbar, position=0):
         SbTextItem.__init__(self, mapframe, statusbar, position)
         self.name = 'coordinates'
         self.label = _("Coordinates")
         self._additionalInfo = None
         self._basicValue = None
-        
+
     def Show(self):
         """Show the last map window coordinates.
 
         .. todo::
             remove last EN call and use coordinates comming from signal
         """
-        precision = int(UserSettings.Get(group = 'projection', key = 'format',
-                             subkey = 'precision'))
-        format = UserSettings.Get(group = 'projection', key = 'format',
-                                       subkey = 'll')
+        precision = int(UserSettings.Get(group='projection', key='format',
+                                         subkey='precision'))
+        format = UserSettings.Get(group='projection', key='format',
+                                  subkey='ll')
         projection = self.mapFrame.GetProperty('projection')
         try:
             e, n = self.mapFrame.GetWindow().GetLastEN()
-            self._basicValue = self.ReprojectENFromMap(e, n, projection, precision, format)
+            self._basicValue = self.ReprojectENFromMap(
+                e, n, projection, precision, format)
             if self._additionalInfo:
-                value = "{coords} ({additionalInfo})".format(coords=self._basicValue,
-                                                             additionalInfo=self._additionalInfo)
+                value = "{coords} ({additionalInfo})".format(
+                    coords=self._basicValue, additionalInfo=self._additionalInfo)
             else:
                 value = self._basicValue
             self.SetValue(value)
         except SbException as e:
             self.SetValue(e.message)
-        # TODO: remove these excepts, they just hide errors, solve problems differently
+        # TODO: remove these excepts, they just hide errors, solve problems
+        # differently
         except TypeError as e:
             self.SetValue("")
         except AttributeError:
-            self.SetValue("") # during initialization MapFrame has no MapWindow
+            # during initialization MapFrame has no MapWindow
+            self.SetValue("")
         SbTextItem.Show(self)
 
     def SetAdditionalInfo(self, text):
@@ -929,62 +993,71 @@
         """
         self._additionalInfo = text
 
-    def ReprojectENFromMap(self, e, n, useDefinedProjection, precision, format):
+    def ReprojectENFromMap(
+            self, e, n, useDefinedProjection, precision, format):
         """Reproject east, north to user defined projection.
-        
+
         :param e,n: coordinate
-        
+
         @throws SbException if useDefinedProjection is True and projection is not defined in UserSettings
         """
         if useDefinedProjection:
-            settings = UserSettings.Get(group = 'projection', key = 'statusbar', subkey = 'proj4')
+            settings = UserSettings.Get(
+                group='projection', key='statusbar', subkey='proj4')
             if not settings:
-                raise SbException(_("Projection not defined (check the settings)"))
+                raise SbException(
+                    _("Projection not defined (check the settings)"))
             else:
                 # reproject values
-                proj, coord  = utils.ReprojectCoordinates(coord = (e, n),
-                                                          projOut = settings,
-                                                          flags = 'd')
+                proj, coord = utils.ReprojectCoordinates(coord=(e, n),
+                                                         projOut=settings,
+                                                         flags='d')
                 if coord:
                     e, n = coord
-                    if proj in ('ll', 'latlong', 'longlat') and format == 'DMS':
-                        return utils.Deg2DMS(e, n, precision = precision)
+                    if proj in ('ll', 'latlong',
+                                'longlat') and format == 'DMS':
+                        return utils.Deg2DMS(e, n, precision=precision)
                     else:
                         return "%.*f; %.*f" % (precision, e, precision, n)
                 else:
-                    raise SbException(_("Error in projection (check the settings)"))
+                    raise SbException(
+                        _("Error in projection (check the settings)"))
         else:
-            if self.mapFrame.GetMap().projinfo['proj'] == 'll' and format == 'DMS':
-                return utils.Deg2DMS(e, n, precision = precision)
+            if self.mapFrame.GetMap().projinfo[
+                    'proj'] == 'll' and format == 'DMS':
+                return utils.Deg2DMS(e, n, precision=precision)
             else:
                 return "%.*f; %.*f" % (precision, e, precision, n)
-        
+
+
 class SbRegionExtent(SbTextItem):
     """Shows current display region"""
-    def __init__(self, mapframe, statusbar, position = 0):
+
+    def __init__(self, mapframe, statusbar, position=0):
         SbTextItem.__init__(self, mapframe, statusbar, position)
         self.name = 'displayRegion'
         self.label = _("Extent")
-        
+
     def Show(self):
-        precision = int(UserSettings.Get(group = 'projection', key = 'format',
-                             subkey = 'precision'))
-        format = UserSettings.Get(group = 'projection', key = 'format',
-                                       subkey = 'll')
-        projection = self.mapFrame.GetProperty('projection')        
+        precision = int(UserSettings.Get(group='projection', key='format',
+                                         subkey='precision'))
+        format = UserSettings.Get(group='projection', key='format',
+                                  subkey='ll')
+        projection = self.mapFrame.GetProperty('projection')
         region = self._getRegion()
         try:
-            regionReprojected = self.ReprojectRegionFromMap(region, projection, precision, format)
+            regionReprojected = self.ReprojectRegionFromMap(
+                region, projection, precision, format)
             self.SetValue(regionReprojected)
         except SbException as e:
             self.SetValue(e.message)
         SbTextItem.Show(self)
-    
+
     def _getRegion(self):
         """Get current display region"""
-        return self.mapFrame.GetMap().GetCurrentRegion() # display region
-        
-    def _formatRegion(self, w, e, s, n, nsres, ewres, precision = None):
+        return self.mapFrame.GetMap().GetCurrentRegion()  # display region
+
+    def _formatRegion(self, w, e, s, n, nsres, ewres, precision=None):
         """Format display region string for statusbar
 
         :param nsres,ewres: unused
@@ -994,118 +1067,134 @@
                                                  precision, s, precision, n)
         else:
             return "%s - %s, %s - %s" % (w, e, s, n)
-         
-           
-    def ReprojectRegionFromMap(self, region, useDefinedProjection, precision, format):
+
+    def ReprojectRegionFromMap(
+            self, region, useDefinedProjection, precision, format):
         """Reproject region values
-        
+
         .. todo::
             reorganize this method to remove code useful only for derived class SbCompRegionExtent
         """
         if useDefinedProjection:
-            settings = UserSettings.Get(group = 'projection', key = 'statusbar', subkey = 'proj4')
-            
+            settings = UserSettings.Get(
+                group='projection', key='statusbar', subkey='proj4')
+
             if not settings:
-                raise SbException(_("Projection not defined (check the settings)"))
+                raise SbException(
+                    _("Projection not defined (check the settings)"))
             else:
                 projOut = settings
-                proj, coord1 = utils.ReprojectCoordinates(coord = (region["w"], region["s"]),
-                                                          projOut = projOut, flags = 'd')
-                proj, coord2 = utils.ReprojectCoordinates(coord = (region["e"], region["n"]),
-                                                          projOut = projOut, flags = 'd')
+                proj, coord1 = utils.ReprojectCoordinates(
+                    coord=(region["w"], region["s"]), projOut=projOut, flags='d')
+                proj, coord2 = utils.ReprojectCoordinates(
+                    coord=(region["e"], region["n"]), projOut=projOut, flags='d')
                 # useless, used in derived class
-                proj, coord3 = utils.ReprojectCoordinates(coord = (0.0, 0.0),
-                                                          projOut = projOut, flags = 'd')
-                proj, coord4 = utils.ReprojectCoordinates(coord = (region["ewres"], region["nsres"]),
-                                                          projOut = projOut, flags = 'd')
+                proj, coord3 = utils.ReprojectCoordinates(
+                    coord=(0.0, 0.0), projOut=projOut, flags='d')
+                proj, coord4 = utils.ReprojectCoordinates(
+                    coord=(
+                        region
+                        ["ewres"],
+                        region
+                        ["nsres"]),
+                    projOut=projOut,
+                    flags='d')
                 if coord1 and coord2:
-                    if proj in ('ll', 'latlong', 'longlat') and format == 'DMS':
-                        w, s = utils.Deg2DMS(coord1[0], coord1[1], string = False,
-                                             precision = precision)
-                        e, n = utils.Deg2DMS(coord2[0], coord2[1], string = False,
-                                             precision = precision)
-                        ewres, nsres = utils.Deg2DMS(abs(coord3[0]) - abs(coord4[0]),
-                                                         abs(coord3[1]) - abs(coord4[1]),
-                                                         string = False, hemisphere = False,
-                                                         precision = precision)
-                        return self._formatRegion(w = w, s = s, e = e, n = n, ewres = ewres, nsres = nsres)
+                    if proj in ('ll', 'latlong',
+                                'longlat') and format == 'DMS':
+                        w, s = utils.Deg2DMS(
+                            coord1[0], coord1[1], string=False, precision=precision)
+                        e, n = utils.Deg2DMS(
+                            coord2[0], coord2[1], string=False, precision=precision)
+                        ewres, nsres = utils.Deg2DMS(
+                            abs(coord3[0]) - abs(coord4[0]),
+                            abs(coord3[1]) - abs(coord4[1]),
+                            string=False, hemisphere=False,
+                            precision=precision)
+                        return self._formatRegion(
+                            w=w, s=s, e=e, n=n, ewres=ewres, nsres=nsres)
                     else:
                         w, s = coord1
                         e, n = coord2
                         ewres, nsres = coord3
-                        return self._formatRegion(w = w, s = s, e = e, n = n, ewres = ewres,
-                                                  nsres = nsres, precision = precision)
+                        return self._formatRegion(
+                            w=w, s=s, e=e, n=n, ewres=ewres, nsres=nsres,
+                            precision=precision)
                 else:
-                    raise SbException(_("Error in projection (check the settings)"))
-                
+                    raise SbException(
+                        _("Error in projection (check the settings)"))
+
         else:
-            if self.mapFrame.GetMap().projinfo['proj'] == 'll' and format == 'DMS':
+            if self.mapFrame.GetMap().projinfo[
+                    'proj'] == 'll' and format == 'DMS':
                 w, s = utils.Deg2DMS(region["w"], region["s"],
-                                     string = False, precision = precision)
+                                     string=False, precision=precision)
                 e, n = utils.Deg2DMS(region["e"], region["n"],
-                                     string = False, precision = precision)
+                                     string=False, precision=precision)
                 ewres, nsres = utils.Deg2DMS(region['ewres'], region['nsres'],
-                                             string = False, precision = precision)
-                return self._formatRegion(w = w, s = s, e = e, n = n, ewres = ewres, nsres = nsres)
+                                             string=False, precision=precision)
+                return self._formatRegion(
+                    w=w, s=s, e=e, n=n, ewres=ewres, nsres=nsres)
             else:
                 w, s = region["w"], region["s"]
                 e, n = region["e"], region["n"]
                 ewres, nsres = region['ewres'], region['nsres']
-                return self._formatRegion(w = w, s = s, e = e, n = n, ewres = ewres,
-                                          nsres = nsres, precision = precision)
-                                
-                                
+                return self._formatRegion(w=w, s=s, e=e, n=n, ewres=ewres,
+                                          nsres=nsres, precision=precision)
+
+
 class SbCompRegionExtent(SbRegionExtent):
     """Shows computational region."""
-    def __init__(self, mapframe, statusbar, position = 0):
+
+    def __init__(self, mapframe, statusbar, position=0):
         SbRegionExtent.__init__(self, mapframe, statusbar, position)
         self.name = 'computationalRegion'
         self.label = _("Computational region")
-        
-    def _formatRegion(self, w, e, s, n, ewres, nsres, precision = None):
+
+    def _formatRegion(self, w, e, s, n, ewres, nsres, precision=None):
         """Format computational region string for statusbar"""
         if precision is not None:
-            return "%.*f - %.*f, %.*f - %.*f (%.*f, %.*f)" % (precision, w, precision, e,
-                                                              precision, s, precision, n,
-                                                              precision, ewres, precision, nsres)
+            return "%.*f - %.*f, %.*f - %.*f (%.*f, %.*f)" % (
+                precision, w, precision, e, precision, s, precision, n,
+                precision, ewres, precision, nsres)
         else:
             return "%s - %s, %s - %s (%s, %s)" % (w, e, s, n, ewres, nsres)
-        
+
     def _getRegion(self):
         """Returns computational region."""
-        return self.mapFrame.GetMap().GetRegion() # computational region
-        
-        
+        return self.mapFrame.GetMap().GetRegion()  # computational region
+
+
 class SbProgress(SbItem):
     """General progress bar to show progress.
-    
+
     Underlaying widget is wx.Gauge.
     """
-    def __init__(self, mapframe, statusbar, sbManager, position = 0):
+
+    def __init__(self, mapframe, statusbar, sbManager, position=0):
         self.progressShown = Signal('SbProgress.progressShown')
         self.progressHidden = Signal('SbProgress.progressHidden')
         SbItem.__init__(self, mapframe, statusbar, position)
         self.name = 'progress'
         self.sbManager = sbManager
         # on-render gauge
-        self.widget = wx.Gauge(parent = self.statusbar, id = wx.ID_ANY,
-                               range = 0, style = wx.GA_HORIZONTAL)
+        self.widget = wx.Gauge(parent=self.statusbar, id=wx.ID_ANY,
+                               range=0, style=wx.GA_HORIZONTAL)
         self.Hide()
-        
-        
+
     def GetRange(self):
         """Returns progress range."""
         return self.widget.GetRange()
-    
+
     def SetRange(self, range):
         """Sets progress range."""
-        if range > 0:        
+        if range > 0:
             if self.GetRange() != range:
                 self.widget.SetRange(range)
             self.Show()
         else:
             self.Hide()
-    
+
     def Show(self):
         if not self.IsShown():
             self.progressShown.emit()
@@ -1131,10 +1220,9 @@
         if value == self.GetRange():
             self.Hide()
 
-
     def GetWidget(self):
         """Returns underlaying winget.
-        
+
         :return: widget or None if doesn't exist
         """
         return self.widget

Modified: grass/trunk/gui/wxpython/mapdisp/test_mapdisp.py
===================================================================
--- grass/trunk/gui/wxpython/mapdisp/test_mapdisp.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/mapdisp/test_mapdisp.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -68,6 +68,7 @@
 
 class MapdispGrassInterface(StandaloneGrassInterface):
     """@implements GrassInterface"""
+
     def __init__(self, map_):
         StandaloneGrassInterface.__init__(self)
         self._map = map_
@@ -93,12 +94,20 @@
 
 
 class TextShower(object):
+
     def __init__(self, parent, title):
         self._cf = wx.Frame(parent=parent, title=title)
         self._cp = wx.Panel(parent=self._cf, id=wx.ID_ANY)
         self._cs = wx.BoxSizer(wx.VERTICAL)
-        self._cl = wx.StaticText(parent=self._cp, id=wx.ID_ANY, label="No text set yet")
-        self._cs.Add(item=self._cl, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
+        self._cl = wx.StaticText(
+            parent=self._cp,
+            id=wx.ID_ANY,
+            label="No text set yet")
+        self._cs.Add(
+            item=self._cl,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
         self._cp.SetSizer(self._cs)
         self._cp.Layout()
         self._cf.Show()
@@ -108,22 +117,31 @@
 
 
 class Tester(object):
+
     def _listenToAllMapWindowSignals(self, window):
         output = sys.stderr
         # will make bad thigs after it is closed but who cares
         coordinatesShower = TextShower(window, "Coordinates")
 
         window.zoomChanged.connect(lambda: output.write("zoomChanged\n"))
-        window.zoomHistoryUnavailable.connect(lambda: output.write("zoomHistoryUnavailable\n"))
-        window.zoomHistoryAvailable.connect(lambda: output.write("zoomHistoryAvailable\n"))
+        window.zoomHistoryUnavailable.connect(
+            lambda: output.write("zoomHistoryUnavailable\n"))
+        window.zoomHistoryAvailable.connect(
+            lambda: output.write("zoomHistoryAvailable\n"))
 
         window.mapQueried.connect(lambda: output.write("mapQueried\n"))
         window.mouseEntered.connect(lambda: output.write("mouseEntered\n"))
-        window.mouseLeftUpPointer.connect(lambda: output.write("mouseLeftUpPointer\n"))
+        window.mouseLeftUpPointer.connect(
+            lambda: output.write("mouseLeftUpPointer\n"))
         window.mouseLeftUp.connect(lambda: output.write("mouseLeftUp\n"))
-        window.mouseMoving.connect(lambda x, y: coordinatesShower.SetLabel("%s , %s" % (x, y)))
-        window.mouseHandlerRegistered.connect(lambda: output.write("mouseHandlerRegistered\n"))
-        window.mouseHandlerUnregistered.connect(lambda: output.write("mouseHandlerUnregistered\n"))
+        window.mouseMoving.connect(
+            lambda x, y: coordinatesShower.SetLabel(
+                "%s , %s" %
+                (x, y)))
+        window.mouseHandlerRegistered.connect(
+            lambda: output.write("mouseHandlerRegistered\n"))
+        window.mouseHandlerUnregistered.connect(
+            lambda: output.write("mouseHandlerUnregistered\n"))
 
     def testMapWindow(self, giface, map_):
         self.frame = wx.Frame(parent=None, title=_("Map window test frame"))
@@ -154,7 +172,8 @@
         frame.Show()
 
     def testMapWindowApi(self, giface, map_):
-        self.frame = wx.Frame(parent=None, title=_("Map window API test frame"))
+        self.frame = wx.Frame(parent=None,
+                              title=_("Map window API test frame"))
         panel = wx.Panel(parent=self.frame, id=wx.ID_ANY)
         sizer = wx.BoxSizer(wx.VERTICAL)
 
@@ -183,8 +202,8 @@
         self.frame.Show()
 
     def testMapWindowDistance(self, giface, map_):
-        self.frame = wx.Frame(parent=None,
-                              title=_("Map window distance measurement test frame"))
+        self.frame = wx.Frame(parent=None, title=_(
+            "Map window distance measurement test frame"))
         panel = wx.Panel(parent=self.frame, id=wx.ID_ANY)
         sizer = wx.BoxSizer(wx.VERTICAL)
 
@@ -263,11 +282,11 @@
     def testMapWindowRlisetup(self, map_):
         self.frame = wx.Frame(parent=None,
                               title=_("Map window rlisetup test frame"))
-                              
+
         RLiSetupMapPanel(parent=self.frame, map_=map_)
         self.frame.Show()
 
-        
+
 def main():
     """Sets the GRASS display driver
     """

Modified: grass/trunk/gui/wxpython/mapdisp/toolbars.py
===================================================================
--- grass/trunk/gui/wxpython/mapdisp/toolbars.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/mapdisp/toolbars.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -19,76 +19,85 @@
 import wx
 
 from gui_core.toolbars import BaseToolbar, BaseIcons
-from nviz.main         import haveNviz
-from vdigit.main       import haveVDigit
-from icons.icon        import MetaIcon
+from nviz.main import haveNviz
+from vdigit.main import haveVDigit
+from icons.icon import MetaIcon
 from core.utils import _
 
-MapIcons =  {
-    'query'      : MetaIcon(img = 'info',
-                            label = _('Query raster/vector map(s)'),
-                            desc = _('Query selected raster/vector map(s)')),
-    'select'     : MetaIcon(img = 'select',
-                            label = _('Select vector feature(s)'),
-                            desc = _('Select features interactively from vector map')),
-    'addBarscale': MetaIcon(img = 'scalebar-add',
-                            label = _('Show/hide scale bar')),
-    'addLegend'  : MetaIcon(img = 'legend-add',
-                            label = _('Show/hide legend')),
-    'addNorthArrow': MetaIcon(img = 'north-arrow-add',
-                              label = _('Show/hide north arrow')),
-    'analyze'    : MetaIcon(img = 'layer-raster-analyze',
-                            label = _('Analyze map'),
-                            desc = _('Measuring, profiling, histogramming, ...')),
+MapIcons = {
+    'query': MetaIcon(img='info',
+                      label=_('Query raster/vector map(s)'),
+                      desc=_('Query selected raster/vector map(s)')),
+    'select': MetaIcon(img='select',
+                       label=_('Select vector feature(s)'),
+                       desc=_('Select features interactively from vector map')),
+    'addBarscale': MetaIcon(img='scalebar-add',
+                            label=_('Show/hide scale bar')),
+    'addLegend': MetaIcon(img='legend-add',
+                          label=_('Show/hide legend')),
+    'addNorthArrow': MetaIcon(img='north-arrow-add',
+                              label=_('Show/hide north arrow')),
+    'analyze': MetaIcon(img='layer-raster-analyze',
+                        label=_('Analyze map'),
+                        desc=_('Measuring, profiling, histogramming, ...')),
     'measureDistance': MetaIcon(img='measure-length',
                                 label=_('Measure distance')),
-    'measureArea' : MetaIcon(img='area-measure',
-                             label=_('Measure area')),
-    'profile'    : MetaIcon(img = 'layer-raster-profile',
-                            label = _('Profile surface map')),
-    'scatter'    : MetaIcon(img = 'layer-raster-profile',
-                            label = _("Create bivariate scatterplot of raster maps")),
-    'addText'    : MetaIcon(img = 'text-add',
-                            label = _('Add text layer')),
-    'histogram'  : MetaIcon(img = 'layer-raster-histogram',
-                            label = _('Create histogram of raster map')),
-    'vnet'       : MetaIcon(img = 'vector-tools',
-                            label = _('Vector network analysis tool')),
-    }
+    'measureArea': MetaIcon(img='area-measure',
+                            label=_('Measure area')),
+    'profile': MetaIcon(img='layer-raster-profile',
+                        label=_('Profile surface map')),
+    'scatter': MetaIcon(img='layer-raster-profile',
+                        label=_("Create bivariate scatterplot of raster maps")),
+    'addText': MetaIcon(img='text-add',
+                        label=_('Add text layer')),
+    'histogram': MetaIcon(img='layer-raster-histogram',
+                          label=_('Create histogram of raster map')),
+    'vnet': MetaIcon(img='vector-tools',
+                     label=_('Vector network analysis tool')),
+}
 
 NvizIcons = {
-    'rotate'    : MetaIcon(img = '3d-rotate',
-                           label = _('Rotate 3D scene'),
-                           desc = _('Drag with mouse to rotate 3D scene')), 
-    'flyThrough': MetaIcon(img = 'flythrough',
-                           label = _('Fly-through mode'),
-                           desc = _('Drag with mouse, hold Ctrl down for different mode'
-                                    ' or Shift to accelerate')),
-    'zoomIn'    : BaseIcons['zoomIn'].SetLabel(desc = _('Click mouse to zoom')),
-    'zoomOut'   : BaseIcons['zoomOut'].SetLabel(desc = _('Click mouse to unzoom'))
-    }
+    'rotate': MetaIcon(
+        img='3d-rotate',
+        label=_('Rotate 3D scene'),
+        desc=_('Drag with mouse to rotate 3D scene')),
+    'flyThrough': MetaIcon(
+        img='flythrough',
+        label=_('Fly-through mode'),
+        desc=_(
+            'Drag with mouse, hold Ctrl down for different mode'
+            ' or Shift to accelerate')),
+    'zoomIn': BaseIcons['zoomIn'].SetLabel(
+        desc=_('Click mouse to zoom')),
+    'zoomOut': BaseIcons['zoomOut'].SetLabel(
+        desc=_('Click mouse to unzoom'))}
 
+
 class MapToolbar(BaseToolbar):
     """Map Display toolbar
     """
+
     def __init__(self, parent, toolSwitcher):
         """Map Display constructor
 
         :param parent: reference to MapFrame
         """
-        BaseToolbar.__init__(self, parent=parent, toolSwitcher=toolSwitcher) # MapFrame
-        
+        BaseToolbar.__init__(
+            self,
+            parent=parent,
+            toolSwitcher=toolSwitcher)  # MapFrame
+
         self.InitToolbar(self._toolbarData())
         self._default = self.pointer
-        
+
         # optional tools
         toolNum = 0
-        choices = [ _('2D view'), ]
-        self.toolId = { '2d' : toolNum }
+        choices = [_('2D view'), ]
+        self.toolId = {'2d': toolNum}
         toolNum += 1
         if self.parent.GetLayerManager():
             log = self.parent.GetLayerManager().GetLogWindow()
-        
+
         if haveNviz:
             choices.append(_('3D view'))
             self.toolId['3d'] = toolNum
@@ -98,7 +107,7 @@
             if self.parent.GetLayerManager():
                 log.WriteCmdLog(_('3D view mode not available'))
                 log.WriteWarning(_('Reason: %s') % str(errorMsg))
-            
+
             self.toolId['3d'] = -1
 
         if haveVDigit:
@@ -108,39 +117,44 @@
         else:
             from vdigit.main import errorMsg
             if self.parent.GetLayerManager():
-              log.WriteCmdLog(_('Vector digitizer not available'))
-              log.WriteWarning(_('Reason: %s') % errorMsg)
-              log.WriteLog(_('Note that the wxGUI\'s vector digitizer is currently disabled '
-                             '(hopefully this will be fixed soon). '
-                             'Please keep an eye out for updated versions of GRASS. '
-                             'In the meantime you can use "v.digit" from the Develop Vector menu.'), wrap = 60)
-            
+                log.WriteCmdLog(_('Vector digitizer not available'))
+                log.WriteWarning(_('Reason: %s') % errorMsg)
+                log.WriteLog(
+                    _(
+                        'Note that the wxGUI\'s vector digitizer is currently disabled '
+                        '(hopefully this will be fixed soon). '
+                        'Please keep an eye out for updated versions of GRASS. '
+                        'In the meantime you can use "v.digit" from the Develop Vector menu.'),
+                    wrap=60)
+
             self.toolId['vdigit'] = -1
         choices.append(_("Raster digitizer"))
         self.toolId['rdigit'] = toolNum
 
-        self.combo = wx.ComboBox(parent = self, id = wx.ID_ANY,
-                                 choices = choices,
-                                 style = wx.CB_READONLY, size = (110, -1))
+        self.combo = wx.ComboBox(parent=self, id=wx.ID_ANY,
+                                 choices=choices,
+                                 style=wx.CB_READONLY, size=(110, -1))
         self.combo.SetSelection(0)
-        
+
         self.comboid = self.AddControl(self.combo)
         self.parent.Bind(wx.EVT_COMBOBOX, self.OnSelectTool, self.comboid)
-        
+
         # realize the toolbar
         self.Realize()
-        
+
         # workaround for Mac bug. May be fixed by 2.8.8, but not before then.
         self.combo.Hide()
         self.combo.Show()
-        
-        for tool in (self.pointer, self.select, self.query, self.pan, self.zoomIn, self.zoomOut):
-            self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=tool)
-        
+
+        for tool in (self.pointer, self.select, self.query,
+                     self.pan, self.zoomIn, self.zoomOut):
+            self.toolSwitcher.AddToolToGroup(
+                group='mouseUse', toolbar=self, tool=tool)
+
         self.EnableTool(self.zoomBack, False)
-        
-        self.FixSize(width = 90)
-        
+
+        self.FixSize(width=90)
+
     def _toolbarData(self):
         """Toolbar data"""
         return self._getToolbarData((
@@ -179,27 +193,28 @@
             ('saveFile', BaseIcons['saveFile'],
              self.parent.SaveToFile),
         ))
+
     def InsertTool(self, data):
         """Insert tool to toolbar
-        
+
         :param data: toolbar data"""
         data = self._getToolbarData(data)
         for tool in data:
             self.CreateTool(*tool)
         self.Realize()
-        
+
         self.parent._mgr.GetPane('mapToolbar').BestSize(self.GetBestSize())
         self.parent._mgr.Update()
-        
+
     def RemoveTool(self, tool):
         """Remove tool from toolbar
-        
+
         :param tool: tool id"""
         self.DeleteTool(tool)
-        
+
         self.parent._mgr.GetPane('mapToolbar').BestSize(self.GetBestSize())
         self.parent._mgr.Update()
-        
+
     def ChangeToolsDesc(self, mode2d):
         """Change description of zoom tools for 2D/3D view"""
         if mode2d:
@@ -212,21 +227,21 @@
                     tmp = list(data)
                     tmp[4] = icons[tool].GetDesc()
                     self._data[i] = tuple(tmp)
-        
+
     def OnSelectTool(self, event):
         """Select / enable tool available in tools list
         """
-        tool =  event.GetSelection()
+        tool = event.GetSelection()
 
         if tool == self.toolId['2d']:
             self.ExitToolbars()
-            self.Enable2D(True)         
-        
+            self.Enable2D(True)
+
         elif tool == self.toolId['3d'] and \
                 not (self.parent.MapWindow3D and self.parent.IsPaneShown('3d')):
             self.ExitToolbars()
             self.parent.AddNviz()
-            
+
         elif tool == self.toolId['vdigit'] and \
                 not self.parent.GetToolbar('vdigit'):
             self.ExitToolbars()
@@ -242,21 +257,25 @@
         """
         self._onMenu(((MapIcons["measureDistance"], self.parent.OnMeasureDistance),
                       (MapIcons["measureArea"], self.parent.OnMeasureArea),
-                      (MapIcons["profile"],     self.parent.OnProfile),
-                      (MapIcons["scatter"],     self.parent.OnScatterplot),
-                      (MapIcons["histogram"],   self.parent.OnHistogramPyPlot),
+                      (MapIcons["profile"], self.parent.OnProfile),
+                      (MapIcons["scatter"], self.parent.OnScatterplot),
+                      (MapIcons["histogram"], self.parent.OnHistogramPyPlot),
                       (BaseIcons["histogramD"], self.parent.OnHistogram),
-                      (MapIcons["vnet"],        self.parent.OnVNet)))
-        
+                      (MapIcons["vnet"], self.parent.OnVNet)))
+
     def OnDecoration(self, event):
         """Decorations overlay menu
         """
-        self._onMenu(((MapIcons["addLegend"], lambda evt: self.parent.AddLegend()),
-                      (MapIcons["addBarscale"], lambda evt: self.parent.AddBarscale()),
-                      (MapIcons["addNorthArrow"], lambda evt: self.parent.AddArrow()),
-                      (MapIcons["addText"], self.parent.OnAddText)))
+        self._onMenu(
+            ((MapIcons["addLegend"],
+              lambda evt: self.parent.AddLegend()),
+             (MapIcons["addBarscale"],
+              lambda evt: self.parent.AddBarscale()),
+                (MapIcons["addNorthArrow"],
+                 lambda evt: self.parent.AddArrow()),
+                (MapIcons["addText"],
+                 self.parent.OnAddText)))
 
-        
     def ExitToolbars(self):
         if self.parent.GetToolbar('vdigit'):
             self.parent.toolbars['vdigit'].OnExit()

Modified: grass/trunk/gui/wxpython/mapswipe/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/mapswipe/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/mapswipe/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -4,4 +4,4 @@
     'mapwindow',
     'toolbars',
     'frame',
-    ]
+]

Modified: grass/trunk/gui/wxpython/mapswipe/dialogs.py
===================================================================
--- grass/trunk/gui/wxpython/mapswipe/dialogs.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/mapswipe/dialogs.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -28,7 +28,7 @@
 from core.layerlist import LayerList
 from core.settings import UserSettings
 from gui_core.simplelmgr import SimpleLayerManager, SIMPLE_LMGR_RASTER, \
-   SIMPLE_LMGR_VECTOR, SIMPLE_LMGR_RGB, SIMPLE_LMGR_TB_LEFT, SIMPLE_LMGR_TB_RIGHT
+    SIMPLE_LMGR_VECTOR, SIMPLE_LMGR_RGB, SIMPLE_LMGR_TB_LEFT, SIMPLE_LMGR_TB_RIGHT
 
 from grass.pydispatch.signal import Signal
 
@@ -39,6 +39,7 @@
     There are two modes - simple (only two raster maps),
     or two layer lists.
     """
+
     def __init__(self, parent, title=_("Select raster maps"),
                  first=None, second=None,
                  firstLayerList=None, secondLayerList=None):
@@ -109,19 +110,35 @@
         panel = wx.Panel(self)
         sizer = wx.BoxSizer(wx.VERTICAL)
 
-        self._firstRaster = gselect.Select(parent=panel, type='raster',
-                                           size=globalvar.DIALOG_GSELECT_SIZE,
-                                           validator=SimpleValidator(callback=self.ValidatorCallback))
+        self._firstRaster = gselect.Select(
+            parent=panel,
+            type='raster',
+            size=globalvar.DIALOG_GSELECT_SIZE,
+            validator=SimpleValidator(
+                callback=self.ValidatorCallback))
 
-        self._secondRaster = gselect.Select(parent=panel, type='raster',
-                                            size=globalvar.DIALOG_GSELECT_SIZE,
-                                            validator=SimpleValidator(callback=self.ValidatorCallback))
-        sizer.Add(wx.StaticText(panel, label=_("Name of top/left raster map:")),
-                  proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
+        self._secondRaster = gselect.Select(
+            parent=panel,
+            type='raster',
+            size=globalvar.DIALOG_GSELECT_SIZE,
+            validator=SimpleValidator(
+                callback=self.ValidatorCallback))
+        sizer.Add(
+            wx.StaticText(
+                panel,
+                label=_("Name of top/left raster map:")),
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
         sizer.Add(self._firstRaster, proportion=0,
                   flag=wx.EXPAND | wx.ALL, border=1)
-        sizer.Add(wx.StaticText(panel, label=_("Name of bottom/right raster map:")),
-                  proportion=0, flag=wx.EXPAND | wx.ALL, border=1)
+        sizer.Add(
+            wx.StaticText(
+                panel,
+                label=_("Name of bottom/right raster map:")),
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=1)
         sizer.Add(self._secondRaster, proportion=0,
                   flag=wx.EXPAND | wx.ALL, border=1)
 
@@ -136,14 +153,24 @@
         panel = wx.Panel(self)
         sizer = wx.BoxSizer(wx.HORIZONTAL)
 
-        self._firstLmgr = SimpleLayerManager(parent=panel, layerList=self._firstLayerList,
-                                             lmgrStyle=SIMPLE_LMGR_RASTER | SIMPLE_LMGR_RGB |
-                                             SIMPLE_LMGR_VECTOR | SIMPLE_LMGR_TB_LEFT)
-        self._secondLmgr = SimpleLayerManager(parent=panel, layerList=self._secondLayerList,
-                                              lmgrStyle=SIMPLE_LMGR_RASTER | SIMPLE_LMGR_RGB |
-                                              SIMPLE_LMGR_VECTOR | SIMPLE_LMGR_TB_RIGHT)
-        sizer.Add(self._firstLmgr, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
-        sizer.Add(self._secondLmgr, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
+        self._firstLmgr = SimpleLayerManager(
+            parent=panel, layerList=self._firstLayerList,
+            lmgrStyle=SIMPLE_LMGR_RASTER | SIMPLE_LMGR_RGB | SIMPLE_LMGR_VECTOR |
+            SIMPLE_LMGR_TB_LEFT)
+        self._secondLmgr = SimpleLayerManager(
+            parent=panel, layerList=self._secondLayerList,
+            lmgrStyle=SIMPLE_LMGR_RASTER | SIMPLE_LMGR_RGB | SIMPLE_LMGR_VECTOR |
+            SIMPLE_LMGR_TB_RIGHT)
+        sizer.Add(
+            self._firstLmgr,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        sizer.Add(
+            self._secondLmgr,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
         panel.SetSizer(sizer)
         sizer.Fit(panel)
 
@@ -152,12 +179,15 @@
     def _switchMode(self, simple):
         if simple:
             self._switchSizer.Show(self._firstPanel, show=True, recursive=True)
-            self._switchSizer.Show(self._secondPanel, show=False, recursive=True)
+            self._switchSizer.Show(
+                self._secondPanel, show=False, recursive=True)
             self.btnSwitch.SetLabel(_("Switch to advanced mode"))
             self.btnCancel.SetLabel(_("Cancel"))
         else:
-            self._switchSizer.Show(self._firstPanel, show=False, recursive=True)
-            self._switchSizer.Show(self._secondPanel, show=True, recursive=True)
+            self._switchSizer.Show(
+                self._firstPanel, show=False, recursive=True)
+            self._switchSizer.Show(
+                self._secondPanel, show=True, recursive=True)
             self.btnSwitch.SetLabel(_("Switch to simple mode"))
             self.btnCancel.SetLabel(_("Close"))
 
@@ -182,9 +212,11 @@
             return
 
         if win == self._firstRaster.GetTextCtrl():
-            GMessage(parent=self, message=_("Name of the first map is missing."))
+            GMessage(parent=self, message=_(
+                "Name of the first map is missing."))
         else:
-            GMessage(parent=self, message=_("Name of the second map is missing."))
+            GMessage(parent=self, message=_(
+                "Name of the second map is missing."))
 
     def _ok(self):
         self._apply()
@@ -197,7 +229,8 @@
     def GetValues(self):
         """Get raster maps"""
         if self.IsSimpleMode():
-            return (self._firstRaster.GetValue(), self._secondRaster.GetValue())
+            return (self._firstRaster.GetValue(),
+                    self._secondRaster.GetValue())
         else:
             return (self._firstLayerList, self._secondLayerList)
 
@@ -215,10 +248,12 @@
 
 class PreferencesDialog(PreferencesBaseDialog):
     """Mapswipe preferences dialog"""
+
     def __init__(self, parent, giface, title=_("Map Swipe settings"),
                  settings=UserSettings):
-        PreferencesBaseDialog.__init__(self, parent=parent, giface=giface, title=title,
-                                       settings=settings, size=(-1, 300))
+        PreferencesBaseDialog.__init__(
+            self, parent=parent, giface=giface, title=title, settings=settings,
+            size=(-1, 300))
 
         # create notebook pages
         self._createMirrorModePage(self.notebook)
@@ -238,61 +273,104 @@
         gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
 
         row = 0
-        gridSizer.Add(item=wx.StaticText(parent=panel,
-                                         label=_("Color:")),
-                      flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
-        color = csel.ColourSelect(parent=panel,
-                                  colour=UserSettings.Get(group='mapswipe',
-                                                          key='cursor', subkey='color'),
-                                  size=globalvar.DIALOG_COLOR_SIZE)
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                label=_("Color:")),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                row,
+                0))
+        color = csel.ColourSelect(
+            parent=panel,
+            colour=UserSettings.Get(
+                group='mapswipe',
+                key='cursor',
+                subkey='color'),
+            size=globalvar.DIALOG_COLOR_SIZE)
         color.SetName('GetColour')
         self.winId['mapswipe:cursor:color'] = color.GetId()
 
         gridSizer.Add(item=color, pos=(row, 1), flag=wx.ALIGN_RIGHT)
 
         row += 1
-        gridSizer.Add(item=wx.StaticText(parent=panel,
-                                         label=_("Shape:")),
-                      flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
-        cursors = wx.Choice(parent=panel,
-                            choices=self.settings.Get(group='mapswipe', key='cursor',
-                                                      subkey=['type', 'choices'], settings_type='internal'),
-                            name="GetSelection")
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                label=_("Shape:")),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                row,
+                0))
+        cursors = wx.Choice(
+            parent=panel,
+            choices=self.settings.Get(
+                group='mapswipe',
+                key='cursor',
+                subkey=[
+                    'type',
+                    'choices'],
+                settings_type='internal'),
+            name="GetSelection")
         cursors.SetSelection(self.settings.Get(group='mapswipe', key='cursor',
                                                subkey=['type', 'selection']))
         self.winId['mapswipe:cursor:type:selection'] = cursors.GetId()
 
-        gridSizer.Add(item=cursors, flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
-                      pos=(row, 1))
+        gridSizer.Add(item=cursors, flag=wx.ALIGN_RIGHT |
+                      wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, pos=(row, 1))
 
         row += 1
-        gridSizer.Add(item=wx.StaticText(parent=panel,
-                                         label=_("Line width:")),
-                      flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
-        width = wx.SpinCtrl(parent=panel, min=1, max=10,
-                            initial=self.settings.Get(group='mapswipe', key='cursor',
-                                                      subkey='width'),
-                            name="GetValue")
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                label=_("Line width:")),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                row,
+                0))
+        width = wx.SpinCtrl(
+            parent=panel,
+            min=1,
+            max=10,
+            initial=self.settings.Get(
+                group='mapswipe',
+                key='cursor',
+                subkey='width'),
+            name="GetValue")
         self.winId['mapswipe:cursor:width'] = width.GetId()
 
-        gridSizer.Add(item=width, flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
-                      pos=(row, 1))
+        gridSizer.Add(item=width, flag=wx.ALIGN_RIGHT |
+                      wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, pos=(row, 1))
 
         row += 1
-        gridSizer.Add(item=wx.StaticText(parent=panel,
-                                         label=_("Size:")),
-                      flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
-        size = wx.SpinCtrl(parent=panel, min=4, max=50,
-                           initial=self.settings.Get(group='mapswipe', key='cursor',
-                                                     subkey='size'),
-                           name="GetValue")
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                label=_("Size:")),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                row,
+                0))
+        size = wx.SpinCtrl(
+            parent=panel,
+            min=4,
+            max=50,
+            initial=self.settings.Get(
+                group='mapswipe',
+                key='cursor',
+                subkey='size'),
+            name="GetValue")
         self.winId['mapswipe:cursor:size'] = size.GetId()
 
-        gridSizer.Add(item=size, flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
-                      pos=(row, 1))
+        gridSizer.Add(item=size, flag=wx.ALIGN_RIGHT |
+                      wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, pos=(row, 1))
 
         gridSizer.AddGrowableCol(1)
-        sizer.Add(item=gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=3)
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=3)
         border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=3)
         panel.SetSizer(border)
 

Modified: grass/trunk/gui/wxpython/mapswipe/frame.py
===================================================================
--- grass/trunk/gui/wxpython/mapswipe/frame.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/mapswipe/frame.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -21,29 +21,30 @@
 
 import grass.script as grass
 
-from gui_core.mapdisp   import DoubleMapFrame
-from gui_core.dialogs   import GetImageHandlers
+from gui_core.mapdisp import DoubleMapFrame
+from gui_core.dialogs import GetImageHandlers
 from mapwin.base import MapWindowProperties
 from core import globalvar
-from core.render        import Map
-from mapdisp            import statusbar as sb
-from core.debug         import Debug
-from core.gcmd          import GError, GMessage
+from core.render import Map
+from mapdisp import statusbar as sb
+from core.debug import Debug
+from core.gcmd import GError, GMessage
 from core.utils import _
 from core.layerlist import LayerListToRendererConverter
 from gui_core.query import QueryDialog, PrepareQueryResults
 
-from mapswipe.toolbars  import SwipeMapToolbar, SwipeMainToolbar, SwipeMiscToolbar
+from mapswipe.toolbars import SwipeMapToolbar, SwipeMainToolbar, SwipeMiscToolbar
 from mapswipe.mapwindow import SwipeBufferedWindow
-from mapswipe.dialogs   import SwipeMapDialog, PreferencesDialog
+from mapswipe.dialogs import SwipeMapDialog, PreferencesDialog
 
 
 class SwipeMapFrame(DoubleMapFrame):
-    def __init__(self, parent  = None, giface = None, 
-                 title = _("GRASS GIS Map Swipe"), name = "swipe", **kwargs):
-        DoubleMapFrame.__init__(self, parent = parent, title = title, name = name,
-                                firstMap = Map(), secondMap = Map(), **kwargs)
-        Debug.msg (1, "SwipeMapFrame.__init__()")
+
+    def __init__(self, parent=None, giface=None,
+                 title=_("GRASS GIS Map Swipe"), name="swipe", **kwargs):
+        DoubleMapFrame.__init__(self, parent=parent, title=title, name=name,
+                                firstMap=Map(), secondMap=Map(), **kwargs)
+        Debug.msg(1, "SwipeMapFrame.__init__()")
         #
         # Add toolbars
         #
@@ -59,29 +60,34 @@
         #
         # create widgets
         #
-        self.splitter = MapSplitter(parent = self, id = wx.ID_ANY)
+        self.splitter = MapSplitter(parent=self, id=wx.ID_ANY)
 
-        self.sliderH = wx.Slider(self, id = wx.ID_ANY, style = wx.SL_HORIZONTAL)
-        self.sliderV = wx.Slider(self, id = wx.ID_ANY, style = wx.SL_VERTICAL)
-        
+        self.sliderH = wx.Slider(self, id=wx.ID_ANY, style=wx.SL_HORIZONTAL)
+        self.sliderV = wx.Slider(self, id=wx.ID_ANY, style=wx.SL_VERTICAL)
+
         self.mapWindowProperties = MapWindowProperties()
         self.mapWindowProperties.setValuesFromUserSettings()
-        self.mapWindowProperties.autoRenderChanged.connect(self.OnAutoRenderChanged)
-        self.firstMapWindow = SwipeBufferedWindow(parent = self.splitter, giface = self._giface,
-                                                  properties=self.mapWindowProperties,
-                                                  Map = self.firstMap)
-        self.secondMapWindow = SwipeBufferedWindow(parent = self.splitter, giface = self._giface,
-                                                   properties=self.mapWindowProperties,
-                                                   Map = self.secondMap)
+        self.mapWindowProperties.autoRenderChanged.connect(
+            self.OnAutoRenderChanged)
+        self.firstMapWindow = SwipeBufferedWindow(
+            parent=self.splitter, giface=self._giface,
+            properties=self.mapWindowProperties, Map=self.firstMap)
+        self.secondMapWindow = SwipeBufferedWindow(
+            parent=self.splitter, giface=self._giface,
+            properties=self.mapWindowProperties, Map=self.secondMap)
         # bind query signal
         self.firstMapWindow.mapQueried.connect(self.Query)
         self.secondMapWindow.mapQueried.connect(self.Query)
 
         # bind tracking cursosr to mirror it
-        self.firstMapWindow.Bind(wx.EVT_MOTION, lambda evt: self.TrackCursor(evt))
-        self.secondMapWindow.Bind(wx.EVT_MOTION, lambda evt: self.TrackCursor(evt))
+        self.firstMapWindow.Bind(
+            wx.EVT_MOTION,
+            lambda evt: self.TrackCursor(evt))
+        self.secondMapWindow.Bind(
+            wx.EVT_MOTION,
+            lambda evt: self.TrackCursor(evt))
 
-        self.MapWindow = self.firstMapWindow # current by default
+        self.MapWindow = self.firstMapWindow  # current by default
         self.firstMapWindow.zoomhistory = self.secondMapWindow.zoomhistory
         self.SetBindRegions(True)
 
@@ -103,7 +109,7 @@
         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
 
         self.SetSize((800, 600))
-        
+
         self._mgr.Update()
 
         self.rasters = {'first': None, 'second': None}
@@ -135,14 +141,14 @@
 
         event.Skip()
 
-    def ActivateFirstMap(self, event = None):
+    def ActivateFirstMap(self, event=None):
         """Switch tracking direction"""
         super(SwipeMapFrame, self).ActivateFirstMap(event)
 
         self.firstMapWindow.ClearLines()
         self.firstMapWindow.Refresh()
 
-    def ActivateSecondMap(self, event = None):
+    def ActivateSecondMap(self, event=None):
         """Switch tracking direction"""
         super(SwipeMapFrame, self).ActivateSecondMap(event)
 
@@ -151,11 +157,12 @@
 
     def CallAfterInit(self):
         self.InitSliderBindings()
-        self.splitter.SplitVertically(self.firstMapWindow, self.secondMapWindow, 0)
+        self.splitter.SplitVertically(
+            self.firstMapWindow, self.secondMapWindow, 0)
         self.splitter.Init()
         if not (self.rasters['first'] and self.rasters['second']):
             self.OnSelectLayers(event=None)
-        
+
     def InitStatusbar(self):
         """Init statusbar (default items)."""
         # items for choice
@@ -169,20 +176,23 @@
                                sb.SbMapScale,
                                sb.SbGoTo,
                                sb.SbProjection]
-        
+
         # create statusbar and its manager
-        statusbar = self.CreateStatusBar(number = 4, style = 0)
+        statusbar = self.CreateStatusBar(number=4, style=0)
         if globalvar.wxPython3:
             statusbar.SetMinHeight(24)
         statusbar.SetStatusWidths([-5, -2, -1, -1])
-        self.statusbarManager = sb.SbManager(mapframe = self, statusbar = statusbar)
-        
+        self.statusbarManager = sb.SbManager(
+            mapframe=self, statusbar=statusbar)
+
         # fill statusbar manager
-        self.statusbarManager.AddStatusbarItemsByClass(self.statusbarItems, mapframe = self, statusbar = statusbar)
-        self.statusbarManager.AddStatusbarItem(sb.SbMask(self, statusbar = statusbar, position = 2))
-        sbRender = sb.SbRender(self, statusbar = statusbar, position = 3)
+        self.statusbarManager.AddStatusbarItemsByClass(
+            self.statusbarItems, mapframe=self, statusbar=statusbar)
+        self.statusbarManager.AddStatusbarItem(
+            sb.SbMask(self, statusbar=statusbar, position=2))
+        sbRender = sb.SbRender(self, statusbar=statusbar, position=3)
         self.statusbarManager.AddStatusbarItem(sbRender)
-        
+
         self.statusbarManager.Update()
 
     def ResetSlider(self):
@@ -193,19 +203,25 @@
         self.slider.SetRange(0, size)
         self.slider.SetValue(self.splitter.GetSashPosition())
 
-
     def InitSliderBindings(self):
         self.sliderH.Bind(wx.EVT_SPIN, self.OnSliderPositionChanging)
-        self.sliderH.Bind(wx.EVT_SCROLL_THUMBRELEASE, self.OnSliderPositionChanged)
+        self.sliderH.Bind(
+            wx.EVT_SCROLL_THUMBRELEASE,
+            self.OnSliderPositionChanged)
         self.sliderV.Bind(wx.EVT_SPIN, self.OnSliderPositionChanging)
-        self.sliderV.Bind(wx.EVT_SCROLL_THUMBRELEASE, self.OnSliderPositionChanged)
-        self.splitter.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGING, self.OnSashChanging)
-        self.splitter.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGED, self.OnSashChanged)
+        self.sliderV.Bind(
+            wx.EVT_SCROLL_THUMBRELEASE,
+            self.OnSliderPositionChanged)
+        self.splitter.Bind(
+            wx.EVT_SPLITTER_SASH_POS_CHANGING,
+            self.OnSashChanging)
+        self.splitter.Bind(
+            wx.EVT_SPLITTER_SASH_POS_CHANGED,
+            self.OnSashChanged)
 
-
     def OnSliderPositionChanging(self, event):
         """Slider changes its position, sash must be moved too."""
-        Debug.msg (5, "SwipeMapFrame.OnSliderPositionChanging()")
+        Debug.msg(5, "SwipeMapFrame.OnSliderPositionChanging()")
 
         self.GetFirstWindow().movingSash = True
         self.GetSecondWindow().movingSash = True
@@ -217,27 +233,27 @@
 
     def OnSliderPositionChanged(self, event):
         """Slider position changed, sash must be moved too."""
-        Debug.msg (5, "SwipeMapFrame.OnSliderPositionChanged()")
+        Debug.msg(5, "SwipeMapFrame.OnSliderPositionChanged()")
 
         self.splitter.SetSashPosition(event.GetPosition())
         self.splitter.OnSashChanged(None)
 
     def OnSashChanging(self, event):
         """Sash position is changing, slider must be moved too."""
-        Debug.msg (5, "SwipeMapFrame.OnSashChanging()")
+        Debug.msg(5, "SwipeMapFrame.OnSashChanging()")
 
         self.slider.SetValue(self.splitter.GetSashPosition())
         event.Skip()
 
     def OnSashChanged(self, event):
         """Sash position changed, slider must be moved too."""
-        Debug.msg (5, "SwipeMapFrame.OnSashChanged()")
+        Debug.msg(5, "SwipeMapFrame.OnSashChanged()")
 
         self.OnSashChanging(event)
         event.Skip()
 
     def OnSize(self, event):
-        Debug.msg (4, "SwipeMapFrame.OnSize()")
+        Debug.msg(4, "SwipeMapFrame.OnSize()")
         self.resize = time.clock()
         super(SwipeMapFrame, self).OnSize(event)
 
@@ -249,7 +265,7 @@
             sizeAll = self.splitter.GetSize()
             w1.SetClientSize(sizeAll)
             w2.SetClientSize(sizeAll)
-            
+
             w1.OnSize(event)
             w2.OnSize(event)
             self.ResetSlider()
@@ -263,7 +279,7 @@
 
     def AddToolbar(self, name):
         """Add defined toolbar to the window
-        
+
         Currently known toolbars are:
          - 'swipeMap'          - basic map toolbar
          - 'swipeMain'         - swipe functionality
@@ -271,60 +287,60 @@
         if name == "swipeMap":
             self.toolbars[name] = SwipeMapToolbar(self, self._toolSwitcher)
             self._mgr.AddPane(self.toolbars[name],
-                      wx.aui.AuiPaneInfo().
-                      Name(name).Caption(_("Map Toolbar")).
-                      ToolbarPane().Top().
-                      LeftDockable(False).RightDockable(False).
-                      BottomDockable(False).TopDockable(True).
-                      CloseButton(False).Layer(2).Row(1).
-                      BestSize((self.toolbars[name].GetBestSize())))
+                              wx.aui.AuiPaneInfo().
+                              Name(name).Caption(_("Map Toolbar")).
+                              ToolbarPane().Top().
+                              LeftDockable(False).RightDockable(False).
+                              BottomDockable(False).TopDockable(True).
+                              CloseButton(False).Layer(2).Row(1).
+                              BestSize((self.toolbars[name].GetBestSize())))
 
         if name == "swipeMain":
             self.toolbars[name] = SwipeMainToolbar(self)
 
             self._mgr.AddPane(self.toolbars[name],
-                      wx.aui.AuiPaneInfo().
-                      Name(name).Caption(_("Main Toolbar")).
-                      ToolbarPane().Top().
-                      LeftDockable(False).RightDockable(False).
-                      BottomDockable(False).TopDockable(True).
-                      CloseButton(False).Layer(2).Row(1).
-                      BestSize((self.toolbars[name].GetBestSize())))
+                              wx.aui.AuiPaneInfo().
+                              Name(name).Caption(_("Main Toolbar")).
+                              ToolbarPane().Top().
+                              LeftDockable(False).RightDockable(False).
+                              BottomDockable(False).TopDockable(True).
+                              CloseButton(False).Layer(2).Row(1).
+                              BestSize((self.toolbars[name].GetBestSize())))
 
         if name == "swipeMisc":
             self.toolbars[name] = SwipeMiscToolbar(self)
 
             self._mgr.AddPane(self.toolbars[name],
-                      wx.aui.AuiPaneInfo().
-                      Name(name).Caption(_("Misc Toolbar")).
-                      ToolbarPane().Top().
-                      LeftDockable(False).RightDockable(False).
-                      BottomDockable(False).TopDockable(True).
-                      CloseButton(False).Layer(2).Row(1).
-                      BestSize((self.toolbars[name].GetBestSize())))
+                              wx.aui.AuiPaneInfo().
+                              Name(name).Caption(_("Misc Toolbar")).
+                              ToolbarPane().Top().
+                              LeftDockable(False).RightDockable(False).
+                              BottomDockable(False).TopDockable(True).
+                              CloseButton(False).Layer(2).Row(1).
+                              BestSize((self.toolbars[name].GetBestSize())))
 
     def _addPanes(self):
         """Add splitter window and sliders to aui manager"""
         # splitter window
         self._mgr.AddPane(self.splitter, wx.aui.AuiPaneInfo().
-                  Name('splitter').CaptionVisible(False).PaneBorder(True).
-                  Dockable(False).Floatable(False).CloseButton(False).
-                  Center().Layer(1).BestSize((self.splitter.GetBestSize())))
+                          Name('splitter').CaptionVisible(False).PaneBorder(True).
+                          Dockable(False).Floatable(False).CloseButton(False).
+                          Center().Layer(1).BestSize((self.splitter.GetBestSize())))
 
         # sliders
         self._mgr.AddPane(self.sliderH, wx.aui.AuiPaneInfo().
-                  Name('sliderH').CaptionVisible(False).PaneBorder(False).
-                  CloseButton(False).Gripper(True).GripperTop(False).
-                  BottomDockable(True).TopDockable(True).
-                  LeftDockable(False).RightDockable(False).
-                  Bottom().Layer(1).BestSize((self.sliderH.GetBestSize())))
+                          Name('sliderH').CaptionVisible(False).PaneBorder(False).
+                          CloseButton(False).Gripper(True).GripperTop(False).
+                          BottomDockable(True).TopDockable(True).
+                          LeftDockable(False).RightDockable(False).
+                          Bottom().Layer(1).BestSize((self.sliderH.GetBestSize())))
 
         self._mgr.AddPane(self.sliderV, wx.aui.AuiPaneInfo().
-                  Name('sliderV').CaptionVisible(False).PaneBorder(False).
-                  CloseButton(False).Gripper(True).GripperTop(True).
-                  BottomDockable(False).TopDockable(False).
-                  LeftDockable(True).RightDockable(True).
-                  Right().Layer(1).BestSize((self.sliderV.GetBestSize())))
+                          Name('sliderV').CaptionVisible(False).PaneBorder(False).
+                          CloseButton(False).Gripper(True).GripperTop(True).
+                          BottomDockable(False).TopDockable(False).
+                          LeftDockable(True).RightDockable(True).
+                          Right().Layer(1).BestSize((self.sliderV.GetBestSize())))
 
     def ZoomToMap(self):
         """
@@ -357,11 +373,12 @@
                                  firstLayerList=None, secondLayerList=None)
             dlg.applyChanges.connect(self.OnApplyInputChanges)
             # connect to convertor object to convert to Map
-            # store reference to convertor is needed otherwise it would be discarded
-            self._firstConverter = self._connectSimpleLmgr(dlg.GetFirstSimpleLmgr(),
-                                                           self.GetFirstMap())
-            self._secondConverter = self._connectSimpleLmgr(dlg.GetSecondSimpleLmgr(),
-                                                            self.GetSecondMap())
+            # store reference to convertor is needed otherwise it would be
+            # discarded
+            self._firstConverter = self._connectSimpleLmgr(
+                dlg.GetFirstSimpleLmgr(), self.GetFirstMap())
+            self._secondConverter = self._connectSimpleLmgr(
+                dlg.GetSecondSimpleLmgr(), self.GetSecondMap())
             self._inputDialog = dlg
             dlg.CentreOnParent()
             dlg.Show()
@@ -397,15 +414,18 @@
             if not (res1 and res2) and first and second:
                 message = ''
                 if not res1:
-                    message += _("Map <%s> not found. ") % self.rasters['first']
+                    message += _("Map <%s> not found. ") % self.rasters[
+                        'first']
                 if not res2:
-                    message += _("Map <%s> not found.") % self.rasters['second']
-                    GError(parent = self, message = message)
+                    message += _("Map <%s> not found.") % self.rasters[
+                        'second']
+                    GError(parent=self, message=message)
                     return
             self.ZoomToMap()
         else:
             LayerListToRendererConverter(self.GetFirstMap()).ConvertAll(first)
-            LayerListToRendererConverter(self.GetSecondMap()).ConvertAll(second)
+            LayerListToRendererConverter(
+                self.GetSecondMap()).ConvertAll(second)
 
         self.SetRasterNames()
         if self.IsAutoRendered():
@@ -413,38 +433,47 @@
 
     def SetFirstRaster(self, name):
         """Set raster map to first Map"""
-        raster = grass.find_file(name = name, element = 'cell')
+        raster = grass.find_file(name=name, element='cell')
         if raster['fullname']:
             self.rasters['first'] = raster['fullname']
-            self.SetLayer(name = raster['fullname'], mapInstance = self.GetFirstMap())
+            self.SetLayer(
+                name=raster['fullname'],
+                mapInstance=self.GetFirstMap())
             return True
 
         return False
 
     def SetSecondRaster(self, name):
         """Set raster map to second Map"""
-        raster = grass.find_file(name = name, element = 'cell')
+        raster = grass.find_file(name=name, element='cell')
         if raster['fullname']:
             self.rasters['second'] = raster['fullname']
-            self.SetLayer(name = raster['fullname'], mapInstance = self.GetSecondMap())
+            self.SetLayer(
+                name=raster['fullname'],
+                mapInstance=self.GetSecondMap())
             return True
 
         return False
 
     def SetLayer(self, name, mapInstance):
         """Sets layer in Map.
-        
+
         :param name: layer (raster) name
         """
-        Debug.msg (3, "SwipeMapFrame.SetLayer(): name=%s" % name)
-        
+        Debug.msg(3, "SwipeMapFrame.SetLayer(): name=%s" % name)
+
         # this simple application enables to keep only one raster
         mapInstance.DeleteAllLayers()
         cmdlist = ['d.rast', 'map=%s' % name]
         # add layer to Map instance (core.render)
-        newLayer = mapInstance.AddLayer(ltype = 'raster', command = cmdlist, active = True,
-                                        name = name, hidden = False, opacity = 1.0,
-                                        render = True)
+        newLayer = mapInstance.AddLayer(
+            ltype='raster',
+            command=cmdlist,
+            active=True,
+            name=name,
+            hidden=False,
+            opacity=1.0,
+            render=True)
 
     def OnSwitchWindows(self, event):
         """Switch windows position."""
@@ -517,32 +546,32 @@
         """
         img = self.firstMapWindow.img or self.secondMapWindow.img
         if not img:
-            GMessage(parent = self,
-                     message = _("Nothing to render (empty map). Operation canceled."))
+            GMessage(parent=self, message=_(
+                "Nothing to render (empty map). Operation canceled."))
             return
         filetype, ltype = GetImageHandlers(img)
-        
+
         # get filename
-        dlg = wx.FileDialog(parent = self,
-                            message = _("Choose a file name to save the image "
-                                        "(no need to add extension)"),
-                            wildcard = filetype,
-                            style = wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
-        
+        dlg = wx.FileDialog(parent=self,
+                            message=_("Choose a file name to save the image "
+                                      "(no need to add extension)"),
+                            wildcard=filetype,
+                            style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
+
         if dlg.ShowModal() == wx.ID_OK:
             path = dlg.GetPath()
             if not path:
                 dlg.Destroy()
                 return
-            
+
             base, ext = os.path.splitext(path)
             fileType = ltype[dlg.GetFilterIndex()]['type']
-            extType  = ltype[dlg.GetFilterIndex()]['ext']
+            extType = ltype[dlg.GetFilterIndex()]['ext']
             if ext != extType:
                 path = base + '.' + extType
-            
+
             self._saveToFile(path, fileType)
-            
+
         dlg.Destroy()
 
     def OnSwitchOrientation(self, event):
@@ -552,13 +581,15 @@
         splitter = self.splitter
         splitter.Unsplit()
         if splitter.GetSplitMode() == wx.SPLIT_HORIZONTAL:
-            splitter.SplitVertically(self.firstMapWindow, self.secondMapWindow, 0)
+            splitter.SplitVertically(
+                self.firstMapWindow, self.secondMapWindow, 0)
             self.slider = self.sliderH
             if self._mode == 'swipe':
                 self._mgr.GetPane('sliderH').Show()
                 self._mgr.GetPane('sliderV').Hide()
         else:
-            splitter.SplitHorizontally(self.firstMapWindow, self.secondMapWindow, 0)
+            splitter.SplitHorizontally(
+                self.firstMapWindow, self.secondMapWindow, 0)
             self.slider = self.sliderV
             if self._mode == 'swipe':
                 self._mgr.GetPane('sliderV').Show()
@@ -607,9 +638,11 @@
     def SetRasterNames(self):
         if not self._inputDialog or self._inputDialog.IsSimpleMode():
             if self.rasters['first']:
-                self.GetFirstWindow().SetRasterNameText(self.rasters['first'], 101)
+                self.GetFirstWindow().SetRasterNameText(
+                    self.rasters['first'], 101)
             if self.rasters['second']:
-                self.GetSecondWindow().SetRasterNameText(self.rasters['second'], 102)
+                self.GetSecondWindow().SetRasterNameText(
+                    self.rasters['second'], 102)
         else:
             self.GetFirstWindow().SetRasterNameText('', 101)
             self.GetSecondWindow().SetRasterNameText('', 102)
@@ -619,41 +652,66 @@
 
         :param x,y: coordinates
         """
-        rasters = ([layer.GetName() for layer in
-                    self.GetFirstMap().GetListOfLayers(ltype='raster', active=True)],
-                   [layer.GetName() for layer in
-                    self.GetSecondMap().GetListOfLayers(ltype='raster', active=True)])
-        vectors = ([layer.GetName() for layer in
-                    self.GetFirstMap().GetListOfLayers(ltype='vector', active=True)],
-                   [layer.GetName() for layer in
-                    self.GetSecondMap().GetListOfLayers(ltype='vector', active=True)])
+        rasters = (
+            [layer.GetName()
+             for layer in self.GetFirstMap().GetListOfLayers(
+                 ltype='raster', active=True)],
+            [layer.GetName()
+             for layer in self.GetSecondMap().GetListOfLayers(
+                 ltype='raster', active=True)])
+        vectors = (
+            [layer.GetName()
+             for layer in self.GetFirstMap().GetListOfLayers(
+                 ltype='vector', active=True)],
+            [layer.GetName()
+             for layer in self.GetSecondMap().GetListOfLayers(
+                 ltype='vector', active=True)])
 
         if not (rasters[0] + rasters[1] + vectors[0] + vectors[1]):
-            GMessage(parent=self,
-                     message=_('No raster or vector map layer selected for querying.'))
+            GMessage(
+                parent=self,
+                message=_(
+                    'No raster or vector map layer selected for querying.'))
             return
 
-        # set query snap distance for v.what at map unit equivalent of 10 pixels
-        qdist = 10.0 * ((self.GetFirstMap().region['e'] -
-                         self.GetFirstMap().region['w']) / self.GetFirstMap().width)
+        # set query snap distance for v.what at map unit equivalent of 10
+        # pixels
+        qdist = 10.0 * (
+            (self.GetFirstMap().region['e'] - self.GetFirstMap().region['w']) /
+            self.GetFirstMap().width)
 
         east, north = self.GetFirstWindow().Pixel2Cell((x, y))
 
         # use display region settings instead of computation region settings
         self.tmpreg = os.getenv("GRASS_REGION")
-        os.environ["GRASS_REGION"] = self.GetFirstMap().SetRegion(windres=False)
+        os.environ["GRASS_REGION"] = self.GetFirstMap(
+        ).SetRegion(windres=False)
 
         result = []
         if rasters[0]:
-            result.extend(grass.raster_what(map=rasters[0], coord=(east, north),
-                                            localized=True))
+            result.extend(
+                grass.raster_what(
+                    map=rasters[0],
+                    coord=(east, north),
+                    localized=True))
         if vectors[0]:
-            result.extend(grass.vector_what(map=vectors[0], coord=(east, north), distance=qdist))
+            result.extend(
+                grass.vector_what(
+                    map=vectors[0],
+                    coord=(east, north),
+                    distance=qdist))
         if rasters[1]:
-            result.extend(grass.raster_what(map=rasters[1], coord=(east, north),
-                                            localized=True))
+            result.extend(
+                grass.raster_what(
+                    map=rasters[1],
+                    coord=(east, north),
+                    localized=True))
         if vectors[1]:
-            result.extend(grass.vector_what(map=vectors[1], coord=(east, north), distance=qdist))
+            result.extend(
+                grass.vector_what(
+                    map=vectors[1],
+                    coord=(east, north),
+                    distance=qdist))
 
         self._QueryMapDone()
 
@@ -664,7 +722,8 @@
         else:
             self._queryDialog = QueryDialog(parent=self, data=result)
             self._queryDialog.Bind(wx.EVT_CLOSE, self._oncloseQueryDialog)
-            self._queryDialog.redirectOutput.connect(lambda output: self._giface.WriteLog(output))
+            self._queryDialog.redirectOutput.connect(
+                lambda output: self._giface.WriteLog(output))
             self._queryDialog.Show()
 
     def _oncloseQueryDialog(self, event):
@@ -694,7 +753,7 @@
         return True
 
     def OnHelp(self, event):
-        self._giface.Help(entry = 'wxGUI.mapswipe')
+        self._giface.Help(entry='wxGUI.mapswipe')
 
     def OnPreferences(self, event):
         if not self._preferencesDialog:
@@ -712,12 +771,13 @@
 
 class MapSplitter(wx.SplitterWindow):
     """Splitter window for displaying two maps"""
+
     def __init__(self, parent, id):
-        wx.SplitterWindow.__init__(self, parent = parent, id = id,
-                                   style = wx.SP_LIVE_UPDATE
+        wx.SplitterWindow.__init__(self, parent=parent, id=id,
+                                   style=wx.SP_LIVE_UPDATE
                                    )
         Debug.msg(2, "MapSplitter.__init__()")
-        
+
         self.sashWidthMin = 1
         self.sashWidthMax = 10
         self.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGED, self.OnSashChanged)
@@ -728,7 +788,7 @@
         self._moveSash = enable
 
     def Init(self):
-        self.OnSashChanged(evt = None)
+        self.OnSashChanged(evt=None)
         self.SetMinimumPaneSize(0)
         self.SetSashSize(self.sashWidthMin)
 
@@ -763,13 +823,13 @@
         w1, w2 = self.GetWindow1(), self.GetWindow2()
         w1.movingSash = False
         w2.movingSash = False
-        
+
         wx.CallAfter(self.SashChanged)
 
     def SashChanged(self):
         Debug.msg(5, "MapSplitter.SashChanged()")
 
-        w1, w2 = self.GetWindow1(), self.GetWindow2() 
+        w1, w2 = self.GetWindow1(), self.GetWindow2()
         w1.SetImageCoords((0, 0))
         if self.GetSplitMode() == wx.SPLIT_VERTICAL:
             w = w1.GetSize()[0]
@@ -778,8 +838,8 @@
             h = w1.GetSize()[1]
             w2.SetImageCoords((0, -h))
 
-        w1.UpdateMap(render = False, renderVector = False)
-        w2.UpdateMap(render = False, renderVector = False)
+        w1.UpdateMap(render=False, renderVector=False)
+        w2.UpdateMap(render=False, renderVector=False)
 
         pos = self.GetSashPosition()
         self.last = pos

Modified: grass/trunk/gui/wxpython/mapswipe/g.gui.mapswipe.py
===================================================================
--- grass/trunk/gui/wxpython/mapswipe/g.gui.mapswipe.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/mapswipe/g.gui.mapswipe.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -52,10 +52,10 @@
     options, flags = gscript.parser()
 
     import wx
-    
+
     from grass.script.setup import set_gui_path
     set_gui_path()
-    
+
     from core.settings import UserSettings
     from core.globalvar import CheckWxVersion
     from core.giface import StandaloneGrassInterface

Modified: grass/trunk/gui/wxpython/mapswipe/mapwindow.py
===================================================================
--- grass/trunk/gui/wxpython/mapswipe/mapwindow.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/mapswipe/mapwindow.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -32,11 +32,12 @@
 
 
 class SwipeBufferedWindow(BufferedMapWindow):
-    """A subclass of BufferedWindow class. 
+    """A subclass of BufferedWindow class.
 
     Enables to draw the image translated.
     Special mouse events with changed coordinates are used.
     """
+
     def __init__(self, parent, giface, Map, properties, **kwargs):
         BufferedMapWindow.__init__(self, parent=parent, giface=giface, Map=Map,
                                    properties=properties, **kwargs)
@@ -106,7 +107,9 @@
 
     def SetImageCoords(self, coords):
         """Sets coordinates of rendered image"""
-        Debug.msg(3, "SwipeBufferedWindow.SetImageCoords(): coords = %s, %s" % (coords[0], coords[1]))
+        Debug.msg(
+            3, "SwipeBufferedWindow.SetImageCoords(): coords = %s, %s" %
+            (coords[0], coords[1]))
         self.specialCoords = coords
 
     def OnSize(self, event):
@@ -124,8 +127,9 @@
         if pdctype == 'image':
             coords = self.GetImageCoords()
 
-        return super(SwipeBufferedWindow, self).Draw(pdc, img, drawid, pdctype, coords, pen, brush)
-        
+        return super(SwipeBufferedWindow, self).Draw(
+            pdc, img, drawid, pdctype, coords, pen, brush)
+
     def OnLeftDown(self, event):
         """Left mouse button pressed.
 
@@ -142,7 +146,7 @@
             if 99 in idlist:
                 idlist.remove(99)
             if idlist:
-                self.dragid = idlist[0] #drag whatever is on top
+                self.dragid = idlist[0]  # drag whatever is on top
         else:
             super(SwipeBufferedWindow, self).OnLeftDown(event)
 
@@ -151,7 +155,7 @@
 
         Coordinates must be adjusted.
         """
-        if (self.mouse['use'] == 'pointer' and self.dragid != None):
+        if (self.mouse['use'] == 'pointer' and self.dragid is not None):
             evX, evY = event.GetPositionTuple()
             imX, imY = self.GetImageCoords()
             self.DragItem(self.dragid, (evX + imX, evY + imY))
@@ -161,7 +165,9 @@
     def TranslateImage(self, dx, dy):
         """Translate image and redraw.
         """
-        Debug.msg(5, "SwipeBufferedWindow.TranslateImage(): dx = %s, dy = %s" % (dx, dy))
+        Debug.msg(
+            5, "SwipeBufferedWindow.TranslateImage(): dx = %s, dy = %s" %
+            (dx, dy))
 
         self.pdc.TranslateId(self.imageId, dx, dy)
         self.Refresh()
@@ -170,35 +176,61 @@
         """Sets text label with map name."""
         self.textdict[textId] = {'bbox': wx.Rect(), 'coords': [10, 10],
                                  'font': self.GetFont(), 'color': wx.BLACK,
-                                 'background' : wx.LIGHT_GREY,
+                                 'background': wx.LIGHT_GREY,
                                  'rotation': 0, 'text': name,
                                  'active': True}
 
-    def MouseDraw(self, pdc = None, begin = None, end = None):
+    def MouseDraw(self, pdc=None, begin=None, end=None):
         """Overriden method to recompute coordinates back to original values
         so that e.g. drawing of zoom box is done properly"""
         Debug.msg(5, "SwipeBufferedWindow.MouseDraw()")
 
         offsetX, offsetY = self.GetImageCoords()
-        begin = (self.mouse['begin'][0] + offsetX, self.mouse['begin'][1] + offsetY)
+        begin = (
+            self.mouse['begin'][0] +
+            offsetX,
+            self.mouse['begin'][1] +
+            offsetY)
         end = (self.mouse['end'][0] + offsetX, self.mouse['end'][1] + offsetY)
         super(SwipeBufferedWindow, self).MouseDraw(pdc, begin, end)
 
     def DrawMouseCursor(self, coords):
         """Draw moving cross."""
         self.pdcTmp.ClearId(self.lineid)
-        color = UserSettings.Get(group='mapswipe', key='cursor', subkey='color')
-        cursType = UserSettings.Get(group='mapswipe', key='cursor', subkey=['type', 'selection'])
+        color = UserSettings.Get(
+            group='mapswipe',
+            key='cursor',
+            subkey='color')
+        cursType = UserSettings.Get(
+            group='mapswipe', key='cursor', subkey=[
+                'type', 'selection'])
         size = UserSettings.Get(group='mapswipe', key='cursor', subkey='size')
-        width = UserSettings.Get(group='mapswipe', key='cursor', subkey='width')
+        width = UserSettings.Get(
+            group='mapswipe',
+            key='cursor',
+            subkey='width')
         if cursType == 0:
-            self.lineid = self.DrawCross(pdc=self.pdcTmp, coords=coords, size=size,
-                                         pen=wx.Pen(wx.Colour(*color), width))
+            self.lineid = self.DrawCross(
+                pdc=self.pdcTmp,
+                coords=coords,
+                size=size,
+                pen=wx.Pen(
+                    wx.Colour(
+                        *color),
+                    width))
         elif cursType == 1:
-            self.lineid = self.DrawRectangle(pdc=self.pdcTmp,
-                                             point1=(coords[0] - size / 2, coords[1] - size / 2),
-                                             point2=(coords[0] + size / 2, coords[1] + size / 2),
-                                             pen=wx.Pen(wx.Colour(*color), width))
+            self.lineid = self.DrawRectangle(
+                pdc=self.pdcTmp,
+                point1=(
+                    coords[0] - size / 2,
+                    coords[1] - size / 2),
+                point2=(
+                    coords[0] + size / 2,
+                    coords[1] + size / 2),
+                pen=wx.Pen(
+                    wx.Colour(
+                        *color),
+                    width))
         elif cursType == 2:
             self.lineid = self.DrawCircle(pdc=self.pdcTmp,
                                           coords=coords, radius=size / 2,
@@ -207,17 +239,17 @@
 
 class _MouseEvent(wx.PyCommandEvent):
     """
-    This event class takes a regular wxWindows mouse event as a parameter, 
-    and wraps it so that there is access to all the original methods. This 
+    This event class takes a regular wxWindows mouse event as a parameter,
+    and wraps it so that there is access to all the original methods. This
     is similar to subclassing, but you can't subclass a wxWindows event.
 
     The goal is to be able to it just like a regular mouse event.
 
-    Difference is that it is a CommandEvent, which propagates up the 
+    Difference is that it is a CommandEvent, which propagates up the
     window hierarchy until it is handled.
     """
 
-    def __init__(self, EventType, NativeEvent, WinID, changed = None):
+    def __init__(self, EventType, NativeEvent, WinID, changed=None):
         Debug.msg(5, "_MouseEvent:__init__()")
 
         wx.PyCommandEvent.__init__(self)
@@ -234,7 +266,7 @@
 
     def GetX(self):
         return self.changed[0]
-        
+
     def GetY(self):
         return self.changed[1]
 

Modified: grass/trunk/gui/wxpython/mapswipe/toolbars.py
===================================================================
--- grass/trunk/gui/wxpython/mapswipe/toolbars.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/mapswipe/toolbars.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -23,18 +23,25 @@
 from core.utils import _
 
 
-swipeIcons = {'tools': MetaIcon(img='tools', label=_("Tools")),
-              'quit': BaseIcons['quit'].SetLabel(_("Quit Map Swipe")),
-              'addRast': BaseIcons['addRast'].SetLabel(_("Select raster maps")),
-              'query': MetaIcon(img='info',
-                                label=_('Query raster/vector map(s)'),
-                                desc=_('Query selected raster/vector map(s)')),
-              }
+swipeIcons = {
+    'tools': MetaIcon(
+        img='tools',
+        label=_("Tools")),
+    'quit': BaseIcons['quit'].SetLabel(
+        _("Quit Map Swipe")),
+    'addRast': BaseIcons['addRast'].SetLabel(
+        _("Select raster maps")),
+    'query': MetaIcon(
+        img='info',
+        label=_('Query raster/vector map(s)'),
+        desc=_('Query selected raster/vector map(s)')),
+}
 
 
 class SwipeMapToolbar(BaseToolbar):
     """Map toolbar (to control map zoom and rendering)
     """
+
     def __init__(self, parent, toolSwitcher):
         """Map toolbar constructor
         """
@@ -46,8 +53,10 @@
         # realize the toolbar
         self.Realize()
 
-        for tool in (self.pointer, self.query, self.pan, self.zoomIn, self.zoomOut):
-            self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=tool)
+        for tool in (self.pointer, self.query, self.pan,
+                     self.zoomIn, self.zoomOut):
+            self.toolSwitcher.AddToolToGroup(
+                group='mouseUse', toolbar=self, tool=tool)
 
         self.EnableTool(self.zoomBack, False)
 
@@ -93,6 +102,7 @@
 class SwipeMainToolbar(BaseToolbar):
     """Toolbar with tools related to application functionality
     """
+
     def __init__(self, parent):
         """Toolbar constructor
         """
@@ -103,13 +113,18 @@
         # add tool to toggle active map window
         self.toggleModeId = wx.NewId()
         self.toggleMode = wx.Choice(parent=self, id=self.toggleModeId)
-        for label, cdata in zip([_('Swipe mode'), _('Mirror mode')], ['swipe', 'mirror']):
+        for label, cdata in zip(
+                [_('Swipe mode'),
+                 _('Mirror mode')],
+                ['swipe', 'mirror']):
             self.toggleMode.Append(label, cdata)
         self.toggleMode.SetSelection(0)
         self.toggleMode.SetSize(self.toggleMode.GetBestSize())
-        self.toggleMode.Bind(wx.EVT_CHOICE,
-                             lambda event:
-                             self.parent.SetViewMode(self.toggleMode.GetClientData(event.GetSelection())))
+        self.toggleMode.Bind(
+            wx.EVT_CHOICE,
+            lambda event: self.parent.SetViewMode(
+                self.toggleMode.GetClientData(
+                    event.GetSelection())))
         self.InsertControl(3, self.toggleMode)
 
         help = _("Choose view mode")
@@ -137,7 +152,8 @@
 
         for label, itype, handler, desc in (
             (_("Switch orientation"),
-             wx.ITEM_NORMAL, self.parent.OnSwitchOrientation, "switchOrientation"),
+             wx.ITEM_NORMAL, self.parent.OnSwitchOrientation,
+             "switchOrientation"),
             (_("Switch maps"),
              wx.ITEM_NORMAL, self.parent.OnSwitchWindows, "switchMaps")):
             # Add items to the menu
@@ -156,6 +172,7 @@
 class SwipeMiscToolbar(BaseToolbar):
     """Toolbar with miscellaneous tools related to app
     """
+
     def __init__(self, parent):
         """Toolbar constructor
         """

Modified: grass/trunk/gui/wxpython/mapwin/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/mapwin/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/mapwin/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -4,4 +4,4 @@
     'analysis',
     'decorations',
     'base',
-    ]
+]

Modified: grass/trunk/gui/wxpython/mapwin/analysis.py
===================================================================
--- grass/trunk/gui/wxpython/mapwin/analysis.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/mapwin/analysis.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -32,6 +32,7 @@
 
 class AnalysisControllerBase:
     """Base class for analysis which require drawing line in map display."""
+
     def __init__(self, giface, mapWindow):
         """
 
@@ -61,7 +62,8 @@
             item = self._registeredGraphics.AddItem(coords=[[x, y]])
             item.SetPropertyVal('penName', 'analysisPen')
         else:
-            # needed to switch mouse begin and end to draw intermediate line properly
+            # needed to switch mouse begin and end to draw intermediate line
+            # properly
             coords = self._registeredGraphics.GetItem(0).GetCoords()[-1]
             self._mapWindow.mouse['begin'] = self._mapWindow.Cell2Pixel(coords)
 
@@ -118,7 +120,8 @@
         self._mapWindow.UpdateMap(render=False)
 
         if restore:
-            # restore mouse['use'] and cursor to the state before measuring starts
+            # restore mouse['use'] and cursor to the state before measuring
+            # starts
             self._mapWindow.SetNamedCursor(self._oldCursor)
             self._mapWindow.mouse['use'] = self._oldMouseUse
 
@@ -129,8 +132,8 @@
         self._oldMouseUse = self._mapWindow.mouse['use']
         self._oldCursor = self._mapWindow.GetNamedCursor()
 
-        self._registeredGraphics = self._mapWindow.RegisterGraphicsToDraw(graphicsType=self._graphicsType,
-                                                                          mapCoords=True)
+        self._registeredGraphics = self._mapWindow.RegisterGraphicsToDraw(
+            graphicsType=self._graphicsType, mapCoords=True)
 
         self._connectAll()
 
@@ -138,7 +141,8 @@
         # TODO: better solution for drawing this line
         self._mapWindow.mouse['use'] = None
         self._mapWindow.mouse['box'] = "line"
-        self._mapWindow.pen = wx.Pen(colour='red', width=2, style=wx.SHORT_DASH)
+        self._mapWindow.pen = wx.Pen(
+            colour='red', width=2, style=wx.SHORT_DASH)
 
         self._registeredGraphics.AddPen('analysisPen', self._getPen())
 
@@ -150,8 +154,10 @@
     """Class controls profiling in map display.
     It should be used inside ProfileFrame
     """
+
     def __init__(self, giface, mapWindow):
-        AnalysisControllerBase.__init__(self, giface=giface, mapWindow=mapWindow)
+        AnalysisControllerBase.__init__(
+            self, giface=giface, mapWindow=mapWindow)
 
         self.transectChanged = Signal('ProfileController.transectChanged')
         self._graphicsType = 'line'
@@ -172,7 +178,9 @@
         self._mapWindow.mouseLeftUp.connect(self._addPoint)
 
     def _getPen(self):
-        return wx.Pen(colour=wx.Colour(0, 100, 0), width=2, style=wx.SHORT_DASH)
+        return wx.Pen(
+            colour=wx.Colour(0, 100, 0),
+            width=2, style=wx.SHORT_DASH)
 
     def Stop(self, restore=True):
         AnalysisControllerBase.Stop(self, restore=restore)
@@ -182,8 +190,10 @@
 
 class MeasureDistanceController(AnalysisControllerBase):
     """Class controls measuring distance in map display."""
+
     def __init__(self, giface, mapWindow):
-        AnalysisControllerBase.__init__(self, giface=giface, mapWindow=mapWindow)
+        AnalysisControllerBase.__init__(
+            self, giface=giface, mapWindow=mapWindow)
 
         self._projInfo = self._mapWindow.Map.projinfo
         self._totaldist = 0.0  # total measured distance
@@ -229,11 +239,14 @@
         # initiating output (and write a message)
         # e.g., in Layer Manager switch to output console
         # TODO: this should be something like: write important message or write tip
-        # TODO: mixed 'switching' and message? no, measuring handles 'swithing' on its own
-        self._giface.WriteWarning(_('Click and drag with left mouse button '
-                                    'to measure.%s'
-                                    'Double click with left button to clear.') %
-                                   (os.linesep))
+        # TODO: mixed 'switching' and message? no, measuring handles 'swithing'
+        # on its own
+        self._giface.WriteWarning(
+            _(
+                'Click and drag with left mouse button '
+                'to measure.%s'
+                'Double click with left button to clear.') %
+            (os.linesep))
         if self._projInfo['proj'] != 'xy':
             mapunits = self._projInfo['units']
             self._giface.WriteCmdLog(_('Measuring distance') + ' ('
@@ -257,7 +270,8 @@
         :param beginpt,endpt: EN coordinates
         """
         # move also Distance method?
-        dist, (north, east) = self._mapWindow.Distance(beginpt, endpt, screen=False)
+        dist, (north, east) = self._mapWindow.Distance(
+            beginpt, endpt, screen=False)
 
         dist = round(dist, 3)
         mapunits = self._projInfo['units']
@@ -274,7 +288,8 @@
         strdist = str(d)
         strtotdist = str(td)
 
-        if self._projInfo['proj'] == 'xy' or 'degree' not in self._projInfo['unit']:
+        if self._projInfo[
+                'proj'] == 'xy' or 'degree' not in self._projInfo['unit']:
             angle = int(math.degrees(math.atan2(north, east)) + 0.5)
             # uncomment below (or flip order of atan2(y,x) above) to use
             #   the mathematical theta convention (CCW from +x axis)
@@ -282,11 +297,12 @@
             if angle < 0:
                 angle = 360 + angle
 
-            mstring = '%s = %s %s\n%s = %s %s\n%s = %d %s\n%s' \
-                % (_('segment'), strdist, dunits,
-                   _('total distance'), strtotdist, tdunits,
-                   _('bearing'), angle, _('degrees (clockwise from grid-north)'),
-                   '-' * 60)
+            mstring = '%s = %s %s\n%s = %s %s\n%s = %d %s\n%s' % (
+                _('segment'),
+                strdist, dunits, _('total distance'),
+                strtotdist, tdunits, _('bearing'),
+                angle, _('degrees (clockwise from grid-north)'),
+                '-' * 60)
         else:
             mstring = '%s = %s %s\n%s = %s %s\n%s' \
                 % (_('segment'), strdist, dunits,
@@ -300,8 +316,10 @@
 
 class MeasureAreaController(AnalysisControllerBase):
     """Class controls measuring area in map display."""
+
     def __init__(self, giface, mapWindow):
-        AnalysisControllerBase.__init__(self, giface=giface, mapWindow=mapWindow)
+        AnalysisControllerBase.__init__(
+            self, giface=giface, mapWindow=mapWindow)
         self._graphicsType = 'polygon'
 
     def _doAnalysis(self, coords):
@@ -339,10 +357,12 @@
             return
         AnalysisControllerBase.Start(self)
 
-        self._giface.WriteWarning(_('Click and drag with left mouse button '
-                                    'to measure.%s'
-                                    'Double click with left button to clear.') %
-                                   (os.linesep))
+        self._giface.WriteWarning(
+            _(
+                'Click and drag with left mouse button '
+                'to measure.%s'
+                'Double click with left button to clear.') %
+            (os.linesep))
         self._giface.WriteCmdLog(_('Measuring area:'))
 
     def MeasureArea(self, coords):
@@ -352,16 +372,24 @@
         """
         # TODO: make sure appending first point is needed for m.measure
         coordinates = coords + [coords[0]]
-        coordinates = ','.join([str(item) for sublist in coordinates for item in sublist])
-        result = RunCommand('m.measure', flags='g', coordinates=coordinates, read=True).strip()
+        coordinates = ','.join([str(item)
+                                for sublist in coordinates for item in
+                                sublist])
+        result = RunCommand(
+            'm.measure',
+            flags='g',
+            coordinates=coordinates,
+            read=True).strip()
         result = parse_key_val(result)
         if 'units' not in result:
-            self._giface.WriteWarning(_("Units not recognized, measurement failed."))
+            self._giface.WriteWarning(
+                _("Units not recognized, measurement failed."))
             unit = ''
         else:
             unit = result['units'].split(',')[1]
         if 'area' not in result:
             text = _("Area: {area} {unit}\n").format(area=0, unit=unit)
         else:
-            text = _("Area: {area} {unit}\n").format(area=result['area'], unit=unit)
+            text = _("Area: {area} {unit}\n").format(
+                area=result['area'], unit=unit)
         self._giface.WriteLog(text, notification=Notification.MAKE_VISIBLE)

Modified: grass/trunk/gui/wxpython/mapwin/base.py
===================================================================
--- grass/trunk/gui/wxpython/mapwin/base.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/mapwin/base.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -22,7 +22,7 @@
 import wx
 
 from core.settings import UserSettings
-from core.gcmd     import GError
+from core.gcmd import GError
 from core.utils import _
 
 from grass.script import core as grass
@@ -30,15 +30,20 @@
 
 
 class MapWindowProperties(object):
+
     def __init__(self):
         self._resolution = None
-        self.resolutionChanged = Signal('MapWindowProperties.resolutionChanged')
+        self.resolutionChanged = Signal(
+            'MapWindowProperties.resolutionChanged')
         self._autoRender = None
-        self.autoRenderChanged = Signal('MapWindowProperties.autoRenderChanged')
+        self.autoRenderChanged = Signal(
+            'MapWindowProperties.autoRenderChanged')
         self._showRegion = None
-        self.showRegionChanged = Signal('MapWindowProperties.showRegionChanged')
+        self.showRegionChanged = Signal(
+            'MapWindowProperties.showRegionChanged')
         self._alignExtent = None
-        self.alignExtentChanged = Signal('MapWindowProperties.alignExtentChanged')
+        self.alignExtentChanged = Signal(
+            'MapWindowProperties.alignExtentChanged')
 
     def setValuesFromUserSettings(self):
         """Convenient function to get values from user settings into this object."""
@@ -105,15 +110,18 @@
      - Pixel2Cell
      - Cell2Pixel (if it is possible)
     """
+
     def __init__(self, parent, giface, Map):
         self.parent = parent
         self.Map = Map
         self._giface = giface
 
         # Emitted when someone registers as mouse event handler
-        self.mouseHandlerRegistered = Signal('MapWindow.mouseHandlerRegistered')
+        self.mouseHandlerRegistered = Signal(
+            'MapWindow.mouseHandlerRegistered')
         # Emitted when mouse event handler is unregistered
-        self.mouseHandlerUnregistered = Signal('MapWindow.mouseHandlerUnregistered')
+        self.mouseHandlerUnregistered = Signal(
+            'MapWindow.mouseHandlerUnregistered')
         # emitted after double click in pointer mode on legend, text, scalebar
         self.overlayActivated = Signal('MapWindow.overlayActivated')
         # emitted when overlay should be hidden
@@ -122,11 +130,11 @@
         # mouse attributes -- position on the screen, begin and end of
         # dragging, and type of drawing
         self.mouse = {
-            'begin': [0, 0], # screen coordinates
-            'end'  : [0, 0],
-            'use'  : "pointer",
-            'box'  : "point"
-            }
+            'begin': [0, 0],  # screen coordinates
+            'end': [0, 0],
+            'use': "pointer",
+            'box': "point"
+        }
         # last east, north coordinates, changes on mouse motion
         self.lastEN = None
 
@@ -136,21 +144,21 @@
         # dictionary where event types are stored as keys and lists of
         # handlers for these types as values
         self.handlersContainer = {
-            wx.EVT_LEFT_DOWN : [],
-            wx.EVT_LEFT_UP : [],
-            wx.EVT_LEFT_DCLICK : [],
-            wx.EVT_MIDDLE_DOWN : [],
-            wx.EVT_MIDDLE_UP : [],
-            wx.EVT_MIDDLE_DCLICK : [],
-            wx.EVT_RIGHT_DOWN : [],
-            wx.EVT_RIGHT_UP : [],
-            wx.EVT_RIGHT_DCLICK : [],
-            wx.EVT_MOTION : [],
-            wx.EVT_ENTER_WINDOW : [],
-            wx.EVT_LEAVE_WINDOW : [],
-            wx.EVT_MOUSEWHEEL : [],
-            wx.EVT_MOUSE_EVENTS : []
-            }
+            wx.EVT_LEFT_DOWN: [],
+            wx.EVT_LEFT_UP: [],
+            wx.EVT_LEFT_DCLICK: [],
+            wx.EVT_MIDDLE_DOWN: [],
+            wx.EVT_MIDDLE_UP: [],
+            wx.EVT_MIDDLE_DCLICK: [],
+            wx.EVT_RIGHT_DOWN: [],
+            wx.EVT_RIGHT_UP: [],
+            wx.EVT_RIGHT_DCLICK: [],
+            wx.EVT_MOTION: [],
+            wx.EVT_ENTER_WINDOW: [],
+            wx.EVT_LEAVE_WINDOW: [],
+            wx.EVT_MOUSEWHEEL: [],
+            wx.EVT_MOUSE_EVENTS: []
+        }
 
         # available cursors
         self._cursors = {
@@ -159,7 +167,7 @@
             "hand": wx.StockCursor(wx.CURSOR_HAND),
             "pencil": wx.StockCursor(wx.CURSOR_PENCIL),
             "sizenwse": wx.StockCursor(wx.CURSOR_SIZENWSE)
-            }
+        }
 
         # default cursor for window is arrow (at least we rely on it here)
         # but we need to define attribute here
@@ -180,7 +188,7 @@
             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
@@ -191,11 +199,13 @@
                 handler(event)
             except:
                 handlers.remove(handler)
-                GError(parent=self,
-                       message=_("Error occurred during calling of handler: %s \n"
-                                 "Handler was unregistered.") % handler.__name__)
+                GError(
+                    parent=self, message=_(
+                        "Error occurred during calling of handler: %s \n"
+                        "Handler was unregistered.") %
+                    handler.__name__)
 
-        event.Skip() 
+        event.Skip()
 
     def RegisterMouseEventHandler(self, event, handler, cursor=None):
         """Binds event handler
@@ -245,20 +255,20 @@
         self.mouseHandlerRegistered.emit()
         # inserts handler into list
         for containerEv, handlers in self.handlersContainer.iteritems():
-            if event == containerEv: 
+            if event == containerEv:
                 handlers.append(handler)
-        
+
         self.mouse['useBeforeGenericEvent'] = self.mouse['use']
         self.mouse['use'] = 'genericEvent'
-        
+
         if cursor:
             self._overriddenCursor = self.GetNamedCursor()
             self.SetNamedCursor(cursor)
-        
+
         return True
 
     def UnregisterAllHandlers(self):
-        """Unregisters all registered handlers 
+        """Unregisters all registered handlers
 
         @depreciated This method is depreciated. Use Signals or drawing API instead.
 
@@ -271,11 +281,11 @@
                     handler("unregistered")
                     handlers.remove(handler)
                 except:
-                    GError(parent = self,
-                           message = _("Error occurred during unregistration of handler: %s \n \
+                    GError(parent=self,
+                           message=_("Error occurred during unregistration of handler: %s \n \
                                        Handler was unregistered.") % handler.__name__)
                     handlers.remove(handler)
-        
+
     def UnregisterMouseEventHandler(self, event, handler):
         """Unbinds event handler for event
 
@@ -288,11 +298,11 @@
 
         :param handler: handler to unbind
         :param event: event from which handler will be unbinded
-        
+
         :return: True if successful
         :return: False if event cannot be unbind
         """
-        # removes handler from list 
+        # removes handler from list
         for containerEv, handlers in self.handlersContainer.iteritems():
             if event != containerEv:
                 continue
@@ -301,27 +311,27 @@
                 if handler in handlers:
                     handlers.remove(handler)
                 else:
-                    grass.warning(_("Handler: %s was not registered") \
-                                      % handler.__name__)
+                    grass.warning(_("Handler: %s was not registered")
+                                  % handler.__name__)
             except:
-                GError(parent = self,
-                       message = _("Error occurred during unregistration of handler: %s \n \
+                GError(parent=self,
+                       message=_("Error occurred during unregistration of handler: %s \n \
                                        Handler was unregistered") % handler.__name__)
-                handlers.remove(handler) 
-        
+                handlers.remove(handler)
+
         # restore mouse use (previous state)
         self.mouse['use'] = self.mouse['useBeforeGenericEvent']
-        
+
         # restore overridden cursor
         if self._overriddenCursor:
             self.SetNamedCursor(self._overriddenCursor)
 
         self.mouseHandlerUnregistered.emit()
         return True
-    
+
     def Pixel2Cell(self, xyCoords):
         raise NotImplementedError()
-    
+
     def Cell2Pixel(self, enCoords):
         raise NotImplementedError()
 

Modified: grass/trunk/gui/wxpython/mapwin/buffered.py
===================================================================
--- grass/trunk/gui/wxpython/mapwin/buffered.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/mapwin/buffered.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -33,12 +33,12 @@
 
 import grass.script as grass
 
-from gui_core.dialogs   import SavedRegion
-from core.gcmd          import RunCommand, GException, GError, GMessage
-from core.debug         import Debug
-from core.settings      import UserSettings
+from gui_core.dialogs import SavedRegion
+from core.gcmd import RunCommand, GException, GError, GMessage
+from core.debug import Debug
+from core.settings import UserSettings
 from mapwin.base import MapWindowBase
-from core.utils         import GetGEventAttribsForHandler, _
+from core.utils import GetGEventAttribsForHandler, _
 import core.utils as utils
 from mapwin.graphics import GraphicsSet
 from core.gthread import gThread
@@ -60,9 +60,10 @@
     can also save the drawing to file by calling the
     SaveToFile() method.
     """
+
     def __init__(self, parent, giface, Map, properties,
                  id=wx.ID_ANY, overlays=None,
-                 style = wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):
+                 style=wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):
         """
         :param parent: parent window
         :param giface: grass interface instance
@@ -75,24 +76,27 @@
         MapWindowBase.__init__(self, parent=parent, giface=giface, Map=Map)
         wx.Window.__init__(self, parent=parent, id=id, style=style, **kwargs)
         self.SetBackgroundColour("white")
-        
+
         self._properties = properties
         # this class should not ask for digit, this is a hack
         self.digit = None
 
         # flags
-        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()
+        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)
-        # List of wx.Point tuples defining a polyline (geographical coordinates)
+        # pen for drawing polylines (measurements, profiles, etc)
+        self.polypen = None
+        # List of wx.Point tuples defining a polyline (geographical
+        # coordinates)
         self.polycoords = []
         # ID of rubber band line
         self.lineid = None
-        # ID of poly line resulting from cumulative rubber band lines (e.g. measurement)
+        # ID of poly line resulting from cumulative rubber band lines (e.g.
+        # measurement)
         self.plineid = None
 
         # following class members deals with merging more updateMap request
@@ -117,9 +121,11 @@
         self.mapQueried = Signal('BufferedWindow.mapQueried')
 
         # Emitted when the zoom history stack is emptied
-        self.zoomHistoryUnavailable = Signal('BufferedWindow.zoomHistoryUnavailable')
+        self.zoomHistoryUnavailable = Signal(
+            'BufferedWindow.zoomHistoryUnavailable')
         # Emitted when the zoom history stack is not empty
-        self.zoomHistoryAvailable = Signal('BufferedWindow.zoomHistoryAvailable')
+        self.zoomHistoryAvailable = Signal(
+            'BufferedWindow.zoomHistoryAvailable')
 
         # Emitted when map enters the window
         self.mouseEntered = Signal('BufferedWindow.mouseEntered')
@@ -142,52 +148,58 @@
         self.mouseMoving = Signal('BufferedWindow.mouseMoving')
 
         # event bindings
-        self.Bind(wx.EVT_PAINT,           self.OnPaint)
-        self.Bind(wx.EVT_SIZE,            self.OnSize)
-        self.Bind(wx.EVT_IDLE,            self.OnIdle)
+        self.Bind(wx.EVT_PAINT, self.OnPaint)
+        self.Bind(wx.EVT_SIZE, self.OnSize)
+        self.Bind(wx.EVT_IDLE, self.OnIdle)
 
         self._bindMouseEvents()
 
         self.processMouse = True
 
         # render output objects
-        self.img     = None   # wx.Image object (self.mapfile)
+        self.img = None   # wx.Image object (self.mapfile)
         # decoration overlays
         self.overlays = overlays
-        self._overlayNames = {0:  _("legend"), 1: _("scale bar"), 2: _("north arrow")}
+        self._overlayNames = {
+            0: _("legend"),
+            1: _("scale bar"),
+            2: _("north arrow")}
         # images and their PseudoDC ID's for painting and dragging
         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)
+        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
+        # offset for dialog (e.g. DisplayAttributesDialog)
+        self.dialogOffset = 5
 
         # 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.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._buffer = wx.EmptyBitmap(
+            max(1, self.Map.width),
+            max(1, self.Map.height))
 
-        self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x:None)
+        self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
 
         # rerender when Map reports change
         self.Map.layerChanged.connect(self.OnUpdateMap)
         self.Map.GetRenderMgr().renderDone.connect(self._updateMFinished)
-        
+
         # vars for handling mouse clicks
-        self.dragid   = -1
-        self.lastpos  = (0, 0)
+        self.dragid = -1
+        self.lastpos = (0, 0)
 
         # list for registration of graphics to draw
         self.graphicsSetList = []
@@ -200,15 +212,16 @@
     def DisactivateWin(self):
         """Use when the class instance is hidden in MapFrame."""
         self.Map.layerChanged.disconnect(self.OnUpdateMap)
-    
+
     def ActivateWin(self):
         """Used when the class instance is activated in MapFrame."""
         self.Map.layerChanged.connect(self.OnUpdateMap)
-        
+
     def _definePseudoDC(self):
         """Define PseudoDC objects to use
         """
-        # create PseudoDC used for background map, map decorations like scales and legends
+        # create PseudoDC used for background map, map decorations like scales
+        # and legends
         self.pdc = wx.PseudoDC()
         # used for digitization tool
         self.pdcVector = None
@@ -219,7 +232,7 @@
 
     def _bindMouseEvents(self):
         self.Bind(wx.EVT_MOUSE_EVENTS, self.MouseActions)
-        self.Bind(wx.EVT_MOTION,       self.OnMotion)
+        self.Bind(wx.EVT_MOTION, self.OnMotion)
         self.Bind(wx.EVT_CONTEXT_MENU, self.OnContextMenu)
 
     def OnContextMenu(self, event):
@@ -233,17 +246,31 @@
 
         if not hasattr(self, "popupCopyCoordinates"):
             self.popupCopyCoordinates = wx.NewId()
-            self.Bind(wx.EVT_MENU, self.OnCopyCoordinates, id = self.popupCopyCoordinates)
-        menu.Append(self.popupCopyCoordinates, _("Copy coordinates to clipboard"))
+            self.Bind(
+                wx.EVT_MENU,
+                self.OnCopyCoordinates,
+                id=self.popupCopyCoordinates)
+        menu.Append(
+            self.popupCopyCoordinates,
+            _("Copy coordinates to clipboard"))
         menu.AppendSeparator()
         if not hasattr(self, "popupShowAllToolbars"):
             self.popupShowAllToolbars = wx.NewId()
-            self.Bind(wx.EVT_MENU, self.OnShowAllToolbars, id = self.popupShowAllToolbars)
-        menu.Append(self.popupShowAllToolbars, _("Hide toolbars") if self._giface.AreAllToolbarsShown() else _("Show toolbars"))
+            self.Bind(
+                wx.EVT_MENU,
+                self.OnShowAllToolbars,
+                id=self.popupShowAllToolbars)
+        menu.Append(self.popupShowAllToolbars, _("Hide toolbars")
+                    if self._giface.AreAllToolbarsShown() else
+                    _("Show toolbars"))
         if not hasattr(self, "popupShowStatusbar"):
             self.popupShowStatusbar = wx.NewId()
-            self.Bind(wx.EVT_MENU, self.OnShowStatusbar, id = self.popupShowStatusbar)
-        menu.Append(self.popupShowStatusbar, _("Hide statusbar") if self._giface.IsStatusbarShown() else _("Show statusbar"))
+            self.Bind(
+                wx.EVT_MENU,
+                self.OnShowStatusbar,
+                id=self.popupShowStatusbar)
+        menu.Append(self.popupShowStatusbar, _("Hide statusbar")
+                    if self._giface.IsStatusbarShown() else _("Show statusbar"))
 
         pos = self.ScreenToClient(event.GetPosition())
         idlist = self.pdc.FindObjects(pos[0], pos[1], self.hitradius)
@@ -256,14 +283,17 @@
             self.Bind(wx.EVT_MENU,
                       lambda evt: self.overlayHidden.emit(overlayId=idlist[0]),
                       id=self._hide)
-            menu.Append(self._hide,
-                        _("Hide {overlay}").format(overlay=self._overlayNames[idlist[0]]))
+            menu.Append(
+                self._hide,
+                _("Hide {overlay}").format(
+                    overlay=self._overlayNames[
+                        idlist[0]]))
 
             if idlist[0] == 0:
                 self._resizeLegend = wx.NewId()
                 self.Bind(wx.EVT_MENU,
-                      lambda evt: self.overlays[idlist[0]].StartResizing(),
-                      id=self._resizeLegend)
+                          lambda evt: self.overlays[idlist[0]].StartResizing(),
+                          id=self._resizeLegend)
                 menu.Append(self._resizeLegend, _("Resize legend"))
         self.PopupMenu(menu)
         menu.Destroy()
@@ -289,7 +319,7 @@
 
         if img and pdctype == 'image':
             # self.imagedict[img]['coords'] = coords
-            self.select[self.imagedict[img]['id']] = False # ?
+            self.select[self.imagedict[img]['id']] = False  # ?
 
         pdc.BeginDrawing()
 
@@ -300,14 +330,14 @@
 
         pdc.SetBackground(bg)
 
-        Debug.msg (5, "BufferedWindow.Draw(): id=%s, pdctype = %s, coord=%s" % \
-                       (drawid, pdctype, coords))
+        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
+        if pdctype == 'clear':  # erase the display
             bg = wx.WHITE_BRUSH
             # bg = wx.Brush(self.GetBackgroundColour())
             pdc.SetBackground(bg)
@@ -318,37 +348,49 @@
             self.Refresh()
             return
 
-        if pdctype == 'image': # draw selected image
+        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))
+            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
+        elif pdctype == 'box':  # draw a box on top of the map
             if pen:
                 if not brush:
                     brush = wx.Brush(wx.CYAN, wx.TRANSPARENT)
                 pdc.SetBrush(brush)
                 pdc.SetPen(pen)
-                x2 = max(coords[0],coords[2])
-                x1 = min(coords[0],coords[2])
-                y2 = max(coords[1],coords[3])
-                y1 = min(coords[1],coords[3])
-                rwidth = x2-x1
-                rheight = y2-y1
+                x2 = max(coords[0], coords[2])
+                x1 = min(coords[0], coords[2])
+                y2 = max(coords[1], coords[3])
+                y1 = min(coords[1], coords[3])
+                rwidth = x2 - x1
+                rheight = y2 - y1
                 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
+        elif pdctype == 'line':  # draw a line on top of the map
             if pen:
                 pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
                 pdc.SetPen(pen)
-                pdc.DrawLinePoint(wx.Point(coords[0], coords[1]),wx.Point(coords[2], coords[3]))
-                pdc.SetIdBounds(drawid, wx.Rect(coords[0], coords[1], coords[2], coords[3]))
+                pdc.DrawLinePoint(
+                    wx.Point(
+                        coords[0], coords[1]), wx.Point(
+                        coords[2], coords[3]))
+                pdc.SetIdBounds(
+                    drawid, wx.Rect(
+                        coords[0],
+                        coords[1],
+                        coords[2],
+                        coords[3]))
 
         # polyline is a series of connected lines defined as sequence of points
-        # lines are individual, not connected lines which must be drawn as 1 object (e.g. cross)
+        # lines are individual, not connected lines which must be drawn as 1
+        # object (e.g. cross)
         elif pdctype in ('polyline', 'lines'):
             if pen:
                 pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
@@ -358,8 +400,15 @@
                 if pdctype == 'polyline':
                     i = 1
                     while i < len(coords):
-                        pdc.DrawLinePoint(wx.Point(coords[i - 1][0], coords[i - 1][1]),
-                                          wx.Point(coords[i][0], coords[i][1]))
+                        pdc.DrawLinePoint(
+                            wx.Point(
+                                coords[
+                                    i - 1][0],
+                                coords[
+                                    i - 1][1]),
+                            wx.Point(
+                                coords[i][0],
+                                coords[i][1]))
                         i += 1
                 else:
                     for line in coords:
@@ -398,18 +447,26 @@
                 h = max(coords, key=lambda x: x[1])[1] - y
                 pdc.SetIdBounds(drawid, wx.Rect(x, y, w, h))
 
-        elif pdctype == 'circle': # draw circle
+        elif pdctype == 'circle':  # draw circle
             if pen:
                 pdc.SetPen(pen)
                 if not brush:
                     brush = wx.TRANSPARENT_BRUSH
                 pdc.SetBrush(brush)
                 radius = abs(coords[2] - coords[0]) / 2
-                pdc.DrawCircle(max(coords[0], coords[2]) - radius,
-                               max(coords[1], coords[3]) - radius, radius=radius)
-                pdc.SetIdBounds(drawid, wx.Rect(coords[0], coords[1], coords[2], coords[3]))
+                pdc.DrawCircle(
+                    max(coords[0],
+                        coords[2]) - radius, max(coords[1],
+                                                 coords[3]) - radius,
+                    radius=radius)
+                pdc.SetIdBounds(
+                    drawid, wx.Rect(
+                        coords[0],
+                        coords[1],
+                        coords[2],
+                        coords[3]))
 
-        elif pdctype == 'point': # draw point
+        elif pdctype == 'point':  # draw point
             if pen:
                 pdc.SetPen(pen)
                 pdc.DrawPoint(coords[0], coords[1])
@@ -419,9 +476,9 @@
                                coords[1] + 5)
                 pdc.SetIdBounds(drawid, wx.Rect(coordsBound))
 
-        elif pdctype == 'text': # draw text on top of map
+        elif pdctype == 'text':  # draw text on top of map
             if not img['active']:
-                return # only draw active text
+                return  # only draw active text
             if 'rotation' in img:
                 rotation = float(img['rotation'])
             else:
@@ -436,7 +493,11 @@
             if rotation == 0:
                 pdc.DrawText(img['text'], coords[0], coords[1])
             else:
-                pdc.DrawRotatedText(img['text'], coords[0], coords[1], rotation)
+                pdc.DrawRotatedText(
+                    img['text'],
+                    coords[0],
+                    coords[1],
+                    rotation)
             pdc.SetIdBounds(drawid, bbox)
 
         pdc.EndDrawing()
@@ -445,7 +506,7 @@
 
         return drawid
 
-    def TextBounds(self, textinfo, relcoords = False):
+    def TextBounds(self, textinfo, relcoords=False):
         """Return text boundary data
 
         :param textinfo: text metadata (text, font, color, rotation)
@@ -463,8 +524,8 @@
         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))
+        Debug.msg(4, "BufferedWindow.TextBounds(): text=%s, rotation=%f" %
+                  (textinfo['text'], rotation))
 
         self.Update()
 
@@ -493,7 +554,7 @@
             relCoords = (boxw, 0)
         bbox[2] = boxw
         bbox[3] = boxh
-        bbox.Inflate(h,h)
+        bbox.Inflate(h, h)
         if relcoords:
             return coords, bbox, relCoords
         else:
@@ -522,7 +583,7 @@
             self.redrawAll = True
             switchDraw = True
 
-        if self.redrawAll: # redraw pdc and pdcVector
+        if self.redrawAll:  # redraw pdc and pdcVector
             # draw to the dc using the calculated clipping rect
             self.pdc.DrawToDCClipped(dc, rgn)
 
@@ -537,7 +598,7 @@
                     self.pdcVector.DrawToDCClipped(dc, rgn)
 
             self.bufferLast = None
-        else: # do not redraw pdc and pdcVector
+        else:  # do not redraw pdc and pdcVector
             if self.bufferLast is None:
                 # draw to the dc
                 self.pdc.DrawToDC(dc)
@@ -553,12 +614,14 @@
 
                 # 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.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 semitransparent objects (e.g. region box, raster digitizer objects)
+        # draw semitransparent objects (e.g. region box, raster digitizer
+        # objects)
         try:
             gcdc = wx.GCDC(dc)
             self.pdcTransparent.DrawToDC(gcdc)
@@ -595,21 +658,23 @@
             # current drawing in it, so it can be used to save the image to
             # a file, or whatever.
             self._buffer.Destroy()
-            self._buffer = wx.EmptyBitmap(max(1, self.Map.width), max(1, self.Map.height))
+            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
+            if self.img and self.Map.width + self.Map.height > 0:  # scale image after resize
                 self.img = self.img.Scale(self.Map.width, self.Map.height)
                 if len(self.Map.GetListOfLayers()) > 0:
                     self.UpdateMap()
                     updatemap = False
 
             if updatemap:
-                self.UpdateMap(render = True)
+                self.UpdateMap(render=True)
             self.resize = False
         elif self.resize:
             event.RequestMore()
@@ -625,17 +690,22 @@
         :param width: image width
         :param height: image height
         """
-        Debug.msg(1, "MapWindow.SaveToFile(): %s (%dx%d)", FileName, width, height)
-        
+        Debug.msg(
+            1,
+            "MapWindow.SaveToFile(): %s (%dx%d)",
+            FileName,
+            width,
+            height)
+
         self._fileName = FileName
         self._fileType = FileType
-        
-        self._busy = wx.BusyInfo(message = _("Please wait, exporting image..."),
-                                 parent = self)
+
+        self._busy = wx.BusyInfo(message=_("Please wait, exporting image..."),
+                                 parent=self)
         wx.Yield()
 
         self.Map.ChangeMapSize((width, height))
-        self.Map.Render(force = True, windres = self._properties.resolution)
+        self.Map.Render(force=True, windres=self._properties.resolution)
         renderMgr = self.Map.GetRenderMgr()
         renderMgr.renderDone.disconnect(self._updateMFinished)
         renderMgr.renderDone.connect(self._saveToFileDone)
@@ -643,16 +713,19 @@
     def _saveToFileDone(self):
         renderMgr = self.Map.GetRenderMgr()
         renderMgr.renderDone.disconnect(self._saveToFileDone)
-        
-        ibuffer = wx.EmptyBitmap(max(1, self.Map.width), max(1, self.Map.height))
-        
+
+        ibuffer = wx.EmptyBitmap(
+            max(1, self.Map.width),
+            max(1, self.Map.height))
+
         img = self.GetImage()
         self.pdc.RemoveAll()
-        self.Draw(self.pdc, img, drawid = 99)
+        self.Draw(self.pdc, img, drawid=99)
 
         # compute size ratio to move overlay accordingly
         cSize = self.GetClientSizeTuple()
-        ratio = float(self.Map.width) / cSize[0], float(self.Map.height) / cSize[1]
+        ratio = float(
+            self.Map.width) / cSize[0], float(self.Map.height) / cSize[1]
 
         # redraw legend, scalebar
         for img in self.GetOverlay():
@@ -660,18 +733,18 @@
             if self.imagedict[img]['layer'].IsActive():
                 id = self.imagedict[img]['id']
                 coords = int(ratio[0] * self.overlays[id].coords[0]),\
-                         int(ratio[1] * self.overlays[id].coords[1])
-                self.Draw(self.pdc, img = img, drawid = id,
-                          pdctype = self.overlays[id].pdcType, coords = coords)
+                    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]
             oldCoords = textinfo['coords']
             textinfo['coords'] = ratio[0] * textinfo['coords'][0],\
-                                 ratio[1] * textinfo['coords'][1]
-            self.Draw(self.pdc, img = self.textdict[id], drawid = id,
-                      pdctype = 'text')
+                ratio[1] * textinfo['coords'][1]
+            self.Draw(self.pdc, img=self.textdict[id], drawid=id,
+                      pdctype='text')
             # set back old coordinates
             textinfo['coords'] = oldCoords
 
@@ -683,17 +756,17 @@
         if self.digit:
             self.pdcVector.DrawToDC(dc)
         ibuffer.SaveFile(self._fileName, self._fileType)
-        
+
         self._busy.Destroy()
         del self._busy
         del self._fileName
         del self._fileType
-        
+
         renderMgr.renderDone.connect(self._updateMFinished)
-        
-        self.UpdateMap(render = True)
+
+        self.UpdateMap(render=True)
         self.Refresh()
-        
+
     def GetOverlay(self):
         """Converts rendered overlay files to wx.Image
 
@@ -702,17 +775,18 @@
         :return: list of images
         """
         imgs = []
-        for overlay in self.Map.GetListOfLayers(ltype = "overlay", active = True):
-            if overlay.mapfile is not None \
-               and os.path.isfile(overlay.mapfile) and os.path.getsize(overlay.mapfile):
+        for overlay in self.Map.GetListOfLayers(ltype="overlay", active=True):
+            if overlay.mapfile is not None and os.path.isfile(
+                    overlay.mapfile) and os.path.getsize(
+                    overlay.mapfile):
                 img = utils.autoCropImageFromFile(overlay.mapfile)
 
                 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 }
+                self.imagedict[img] = {'id': overlay.id,
+                                       'layer': overlay}
                 imgs.append(img)
 
         return imgs
@@ -735,11 +809,11 @@
             if self.imagedict[key]['id'] == imgId:
                 del self.imagedict[key]
 
-        self.imagedict[img] = { 'id': imgId }
+        self.imagedict[img] = {'id': imgId}
 
         return img
 
-    def SetAlwaysRenderEnabled(self, alwaysRender = True):
+    def SetAlwaysRenderEnabled(self, alwaysRender=True):
         self.alwaysRender = alwaysRender
 
     def IsAlwaysRenderEnabled(self):
@@ -829,29 +903,29 @@
         """
         :func:`UpdateMap` for arguments description.
         """
-        Debug.msg (1, "BufferedWindow.UpdateMap(): started "
-                   "(render=%s, renderVector=%s)" % (render, renderVector))
+        Debug.msg(1, "BufferedWindow.UpdateMap(): started "
+                  "(render=%s, renderVector=%s)" % (render, renderVector))
 
         self.resize = False
 
         # was if self.Map.cmdfile and ...
         if self.IsAlwaysRenderEnabled() and self.img is None:
             render = True
-        
+
         try:
             if render:
                 # update display size
                 self.Map.ChangeMapSize(self.GetClientSize())
-                
+
             self.Map.Render(force=render,
                             windres=self._properties.resolution)
         except GException as e:
-                GError(message=e.value)
+            GError(message=e.value)
 
     def _updateMFinished(self, renderVector=True):
-        Debug.msg (1, "BufferedWindow.UpdateMap(): finished")
-        self.img = self.GetImage() # id=99
-        
+        Debug.msg(1, "BufferedWindow.UpdateMap(): finished")
+        self.img = self.GetImage()  # id=99
+
         #
         # clear pseudoDcs
         #
@@ -860,26 +934,26 @@
                     self.pdcTmp):
             pdc.Clear()
             pdc.RemoveAll()
-        
+
         #
         # draw background map image to PseudoDC
         #
         if not self.img:
-            self.Draw(self.pdc, pdctype = 'clear')
+            self.Draw(self.pdc, pdctype='clear')
         else:
             try:
                 id = self.imagedict[self.img]['id']
             except Exception as e:
                 Debug.mgs(1, "UpdateMap() failed: %s", e)
                 return False
-            self.Draw(self.pdc, self.img, drawid = id)
+            self.Draw(self.pdc, self.img, drawid=id)
 
         #
         # render vector map layer
         #
         if renderVector and self.digit:
             self._updateMap()
-        
+
         #
         # render overlays
         #
@@ -887,23 +961,23 @@
             # draw any active and defined overlays
             if self.imagedict[img]['layer'].IsActive():
                 id = self.imagedict[img]['id']
-                self.Draw(self.pdc, img = img, drawid = id,
-                          pdctype = self.overlays[id].pdcType,
-                          coords = self.overlays[id].coords)
-        
+                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])
-        
+            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:
+        if len(self.graphicsSetList) > 0:
             penOrig = self.pen
             polypenOrig = self.polypen
 
@@ -911,9 +985,9 @@
                 try:
                     item.Draw()
                 except:
-                    GError(parent = self,
-                           message = _('Unable to draw registered graphics. '
-                                       'The graphics was unregistered.'))
+                    GError(parent=self,
+                           message=_('Unable to draw registered graphics. '
+                                     'The graphics was unregistered.'))
                     self.UnregisterGraphicsToDraw(item)
 
             self.pen = penOrig
@@ -923,7 +997,7 @@
             self.DrawLines(self.pdcTmp)
 
         return True
-    
+
     def DrawCompRegionExtent(self):
         """Draw computational region extent in the display
 
@@ -935,11 +1009,13 @@
             dispReg = self.Map.GetCurrentRegion()
             reg = None
             if utils.isInRegion(dispReg, compReg):
-                self.polypen = wx.Pen(colour = wx.Colour(0, 0, 255, 128), width = 3, style = wx.SOLID)
+                self.polypen = wx.Pen(
+                    colour=wx.Colour(0, 0, 255, 128),
+                    width=3, style=wx.SOLID)
                 reg = dispReg
             else:
-                self.polypen = wx.Pen(colour = wx.Colour(255, 0, 0, 128),
-                                      width = 3, style = wx.SOLID)
+                self.polypen = wx.Pen(colour=wx.Colour(255, 0, 0, 128),
+                                      width=3, style=wx.SOLID)
                 reg = compReg
 
             regionCoords = []
@@ -954,13 +1030,13 @@
     def EraseMap(self):
         """Erase map canvas
         """
-        self.Draw(self.pdc, pdctype = 'clear')
+        self.Draw(self.pdc, pdctype='clear')
 
         if self.digit:
-            self.Draw(self.pdcVector, pdctype = 'clear')
+            self.Draw(self.pdcVector, pdctype='clear')
 
         self.Draw(self.pdcTransparent, pdctype='clear')
-        self.Draw(self.pdcTmp, pdctype = 'clear')
+        self.Draw(self.pdcTmp, pdctype='clear')
 
         self.Map.AbortAllThreads()
 
@@ -984,36 +1060,37 @@
     def DragItem(self, id, coords):
         """Drag an overlay decoration item
         """
-        if id == 99 or id == '' or id is None: return
-        Debug.msg (5, "BufferedWindow.DragItem(): id=%d" % id)
+        if id == 99 or id == '' or id is None:
+            return
+        Debug.msg(5, "BufferedWindow.DragItem(): id=%d" % id)
         x, y = self.lastpos
         dx = coords[0] - x
         dy = coords[1] - y
         self.pdc.SetBackground(wx.Brush(self.GetBackgroundColour()))
         r = self.pdc.GetIdBounds(id)
 
-        if type(r) is list:
+        if isinstance(r, list):
             r = wx.Rect(r[0], r[1], r[2], r[3])
-        if id > 100: # text dragging
-            rtop = (r[0],r[1]-r[3],r[2],r[3])
+        if id > 100:  # text dragging
+            rtop = (r[0], r[1] - r[3], r[2], r[3])
             r = r.Union(rtop)
-            rleft = (r[0]-r[2],r[1],r[2],r[3])
+            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:
+        if isinstance(r2, list):
             r2 = wx.Rect(r[0], r[1], r[2], r[3])
-        if id > 100: # text
+        if id > 100:  # text
             self.textdict[id]['bbox'] = r2
             self.textdict[id]['coords'][0] += dx
             self.textdict[id]['coords'][1] += dy
         r = r.Union(r2)
-        r.Inflate(4,4)
+        r.Inflate(4, 4)
         self.RefreshRect(r, False)
         self.lastpos = (coords[0], coords[1])
 
-    def MouseDraw(self, pdc = None, begin = None, end = None):
+    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'].
@@ -1024,18 +1101,18 @@
         if begin is None:
             begin = self.mouse['begin']
         if end is None:
-            end   = self.mouse['end']
+            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]))
+        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],
                            end[0], end[1]]
             r = pdc.GetIdBounds(boxid)
-            if type(r) is list:
+            if isinstance(r, list):
                 r = wx.Rect(r[0], r[1], r[2], r[3])
             r.Inflate(4, 4)
             try:
@@ -1044,27 +1121,31 @@
                 pass
             self.RefreshRect(r, False)
             pdc.SetId(boxid)
-            self.Draw(pdc, drawid = boxid, pdctype = 'box', coords = mousecoords)
+            self.Draw(pdc, drawid=boxid, pdctype='box', coords=mousecoords)
 
         elif self.mouse['box'] == "line":
             self.lineid = wx.ID_NEW
-            mousecoords = [begin[0], begin[1], \
+            mousecoords = [begin[0], begin[1],
                            end[0], end[1]]
-            x1 = min(begin[0],end[0])
-            x2 = max(begin[0],end[0])
-            y1 = min(begin[1],end[1])
-            y2 = max(begin[1],end[1])
-            r = wx.Rect(x1,y1,x2-x1,y2-y1)
-            r.Inflate(4,4)
+            x1 = min(begin[0], end[0])
+            x2 = max(begin[0], end[0])
+            y1 = min(begin[1], end[1])
+            y2 = max(begin[1], end[1])
+            r = wx.Rect(x1, y1, x2 - x1, y2 - y1)
+            r.Inflate(4, 4)
             try:
                 pdc.ClearId(self.lineid)
             except:
                 pass
             self.RefreshRect(r, False)
             pdc.SetId(self.lineid)
-            self.Draw(pdc, drawid = self.lineid, pdctype = 'line', coords = mousecoords)
+            self.Draw(
+                pdc,
+                drawid=self.lineid,
+                pdctype='line',
+                coords=mousecoords)
 
-    def DrawLines(self, pdc = None, polycoords = None):
+    def DrawLines(self, pdc=None, polycoords=None):
         """Draw polyline in PseudoDC
 
         Set self.pline to wx.NEW_ID + 1
@@ -1086,10 +1167,14 @@
             for p in polycoords:
                 coords.append(self.Cell2Pixel(p))
 
-            self.Draw(pdc, drawid = self.plineid, pdctype = 'polyline', coords = coords)
+            self.Draw(
+                pdc,
+                drawid=self.plineid,
+                pdctype='polyline',
+                coords=coords)
 
-            Debug.msg (4, "BufferedWindow.DrawLines(): coords=%s, id=%s" % \
-                           (coords, self.plineid))
+            Debug.msg(4, "BufferedWindow.DrawLines(): coords=%s, id=%s" %
+                      (coords, self.plineid))
 
             return self.plineid
 
@@ -1106,13 +1191,18 @@
         :param pen: pen to be used
         :param drawid: id of the drawn object (used by PseudoDC)
         """
-        Debug.msg (4, "BufferedWindow.DrawPolylines(): coords=%s" % coords)
-        self.lineId = self.Draw(pdc, drawid=None, pdctype='polyline', coords=coords, pen=pen)
+        Debug.msg(4, "BufferedWindow.DrawPolylines(): coords=%s" % coords)
+        self.lineId = self.Draw(
+            pdc,
+            drawid=None,
+            pdctype='polyline',
+            coords=coords,
+            pen=pen)
 
         return self.lineid
 
-    def DrawCross(self, pdc, coords, size, rotation = 0, pen = None,
-                  text = None, textAlign = 'lr', textOffset = (5, 5), drawid=None):
+    def DrawCross(self, pdc, coords, size, rotation=0, pen=None,
+                  text=None, textAlign='lr', textOffset=(5, 5), drawid=None):
         """Draw cross in PseudoDC
 
         .. todo::
@@ -1126,27 +1216,63 @@
         :param textOffset: offset for text (from center point)
         :param drawid: id of the drawn object (used by PseudoDC)
         """
-        Debug.msg(4, "BufferedWindow.DrawCross(): pdc=%s, coords=%s, size=%d" % \
+        Debug.msg(4, "BufferedWindow.DrawCross(): pdc=%s, coords=%s, size=%d" %
                   (pdc, coords, size))
-        coordsCross = ((coords[0], coords[1] - size, coords[0], coords[1] + size),
-                       (coords[0] - size, coords[1], coords[0] + size, coords[1]))
+        coordsCross = (
+            (coords[0],
+             coords[1] - size,
+                coords[0],
+                coords[1] + size),
+            (coords[0] - size,
+             coords[1],
+                coords[0] + size,
+                coords[1]))
 
-        self.lineid = self.Draw(pdc, drawid=drawid, pdctype='lines', coords=coordsCross, pen=pen)
+        self.lineid = self.Draw(
+            pdc,
+            drawid=drawid,
+            pdctype='lines',
+            coords=coordsCross,
+            pen=pen)
 
         if not text:
             return self.lineid
 
         if textAlign == 'ul':
-            coord = [coords[0] - textOffset[0], coords[1] - textOffset[1], 0, 0]
+            coord = [
+                coords[0] -
+                textOffset[0],
+                coords[1] -
+                textOffset[1],
+                0,
+                0]
         elif textAlign == 'ur':
-            coord = [coords[0] + textOffset[0], coords[1] - textOffset[1], 0, 0]
+            coord = [
+                coords[0] +
+                textOffset[0],
+                coords[1] -
+                textOffset[1],
+                0,
+                0]
         elif textAlign == 'lr':
-            coord = [coords[0] + textOffset[0], coords[1] + textOffset[1], 0, 0]
+            coord = [
+                coords[0] +
+                textOffset[0],
+                coords[1] +
+                textOffset[1],
+                0,
+                0]
         else:
-            coord = [coords[0] - textOffset[0], coords[1] + textOffset[1], 0, 0]
+            coord = [
+                coords[0] -
+                textOffset[0],
+                coords[1] +
+                textOffset[1],
+                0,
+                0]
 
-        self.Draw(pdc, img = text,
-                  pdctype = 'text', coords = coord, pen = pen)
+        self.Draw(pdc, img=text,
+                  pdctype='text', coords=coord, pen=pen)
 
         return self.lineid
 
@@ -1159,11 +1285,17 @@
         :param pen: pen
         :param drawid: id of the drawn object (used by PseudoDC)
         """
-        Debug.msg(4, "BufferedWindow.DrawRectangle(): pdc=%s, point1=%s, point2=%s" % \
-                  (pdc, point1, point2))
+        Debug.msg(
+            4, "BufferedWindow.DrawRectangle(): pdc=%s, point1=%s, point2=%s" %
+            (pdc, point1, point2))
         coords = [point1[0], point1[1], point2[0], point2[1]]
-        self.lineid = self.Draw(pdc, drawid=drawid, pdctype='box', coords=coords,
-                                pen=pen, brush=brush)
+        self.lineid = self.Draw(
+            pdc,
+            drawid=drawid,
+            pdctype='box',
+            coords=coords,
+            pen=pen,
+            brush=brush)
         return self.lineid
 
     def DrawCircle(self, pdc, coords, radius, pen, brush=None, drawid=None):
@@ -1175,12 +1307,18 @@
         :param pen: pen
         :param drawid: id of the drawn object (used by PseudoDC)
         """
-        Debug.msg(4, "BufferedWindow.DrawCircle(): pdc=%s, coords=%s, radius=%s" %
-                  (pdc, coords, radius))
+        Debug.msg(
+            4, "BufferedWindow.DrawCircle(): pdc=%s, coords=%s, radius=%s" %
+            (pdc, coords, radius))
         newcoords = [coords[0] - radius, coords[1] - radius,
                      coords[0] + radius, coords[1] + radius]
-        self.lineid = self.Draw(pdc, drawid=drawid, pdctype='circle', coords=newcoords,
-                                pen=pen, brush=brush)
+        self.lineid = self.Draw(
+            pdc,
+            drawid=drawid,
+            pdctype='circle',
+            coords=newcoords,
+            pen=pen,
+            brush=brush)
         return self.lineid
 
     def DrawPolygon(self, pdc, coords, pen, brush=None, drawid=None):
@@ -1208,8 +1346,8 @@
         if zoomtype > 0:
             begin = (position[0] - self.Map.width / 4,
                      position[1] - self.Map.height / 4)
-            end   = (position[0] + self.Map.width / 4,
-                     position[1] + self.Map.height / 4)
+            end = (position[0] + self.Map.width / 4,
+                   position[1] + self.Map.height / 4)
         else:
             begin = ((self.Map.width - position[0]) / 2,
                      (self.Map.height - position[1]) / 2)
@@ -1271,36 +1409,36 @@
     def OnMouseWheel(self, event):
         """Mouse wheel moved
         """
-        zoomBehaviour = UserSettings.Get(group = 'display',
-                                         key = 'mouseWheelZoom',
-                                         subkey = 'selection')
+        zoomBehaviour = UserSettings.Get(group='display',
+                                         key='mouseWheelZoom',
+                                         subkey='selection')
         if zoomBehaviour == 2:
             event.Skip()
             return
 
         self.processMouse = False
-        current  = event.GetPositionTuple()[:]
+        current = event.GetPositionTuple()[:]
         wheel = event.GetWheelRotation()
-        Debug.msg (5, "BufferedWindow.MouseAction(): wheel=%d" % wheel)
+        Debug.msg(5, "BufferedWindow.MouseAction(): wheel=%d" % wheel)
 
         if wheel > 0:
             zoomtype = 1
         else:
             zoomtype = -1
-        if UserSettings.Get(group = 'display',
-                            key = 'scrollDirection',
-                            subkey = 'selection'):
+        if UserSettings.Get(group='display',
+                            key='scrollDirection',
+                            subkey='selection'):
             zoomtype *= -1
         # zoom 1/2 of the screen (TODO: settings)
         if zoomBehaviour == 0:  # zoom and recenter
-            begin, end = self._computeZoomToPointAndRecenter(position = current, zoomtype = zoomtype)
+            begin, end = self._computeZoomToPointAndRecenter(
+                position=current, zoomtype=zoomtype)
 
         elif zoomBehaviour == 1:  # zoom to current cursor position
-            begin = (current[0]/2, current[1]/2)
-            end = ((self.Map.width - current[0])/2 + current[0],
-                   (self.Map.height - current[1])/2 + current[1])
+            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)
 
@@ -1313,8 +1451,8 @@
     def OnDragging(self, event):
         """Mouse dragging
         """
-        Debug.msg (5, "BufferedWindow.MouseAction(): Dragging")
-        current  = event.GetPositionTuple()[:]
+        Debug.msg(5, "BufferedWindow.MouseAction(): Dragging")
+        current = event.GetPositionTuple()[:]
         previous = self.mouse['begin']
         move = (current[0] - previous[0],
                 current[1] - previous[1])
@@ -1332,28 +1470,28 @@
         # dragging decoration overlay item
         elif (self.mouse['use'] == 'pointer' and
                 not digitToolbar and
-                self.dragid != None):
+                self.dragid is not None):
             coords = event.GetPositionTuple()
             self.DragItem(self.dragid, coords)
 
         # dragging anything else - rubber band box or line
         else:
             if (self.mouse['use'] == 'pointer' and
-                not digitToolbar):
+                    not digitToolbar):
                 return
 
             self.mouse['end'] = event.GetPositionTuple()[:]
             if (event.LeftIsDown() and
                 not (digitToolbar and
-                    digitToolbar.GetAction() in ("moveLine",) and
+                     digitToolbar.GetAction() in ("moveLine",) and
                      self.digit.GetDisplay().GetSelected() > 0)):
-                self.MouseDraw(pdc = self.pdcTmp)
+                self.MouseDraw(pdc=self.pdcTmp)
 
     def OnLeftDown(self, event):
         """Left mouse button pressed
         """
-        Debug.msg (5, "BufferedWindow.OnLeftDown(): use=%s" % \
-                   self.mouse["use"])
+        Debug.msg(5, "BufferedWindow.OnLeftDown(): use=%s" %
+                  self.mouse["use"])
 
         self.mouse['begin'] = event.GetPositionTuple()[:]
 
@@ -1375,7 +1513,7 @@
             if 99 in idlist:
                 idlist.remove(99)
             if idlist != []:
-                self.dragid = idlist[0] #drag whatever is on top
+                self.dragid = idlist[0]  # drag whatever is on top
         else:
             pass
         coords = self.Pixel2Cell(self.mouse['begin'])
@@ -1388,8 +1526,8 @@
 
         Emits mapQueried signal when mouse use is 'query'.
         """
-        Debug.msg (5, "BufferedWindow.OnLeftUp(): use=%s" % \
-                       self.mouse["use"])
+        Debug.msg(5, "BufferedWindow.OnLeftUp(): use=%s" %
+                  self.mouse["use"])
 
         self.mouse['end'] = event.GetPositionTuple()[:]
         coordinates = self.Pixel2Cell(self.mouse['end'])
@@ -1403,14 +1541,17 @@
                 # set region for click (zero-width box)
                 if begin[0] - end[0] == 0 or \
                         begin[1] - end[1] == 0:
-                    begin, end = self._computeZoomToPointAndRecenter(position = end, zoomtype = self.zoomtype)
+                    begin, end = self._computeZoomToPointAndRecenter(
+                        position=end, zoomtype=self.zoomtype)
             self.Zoom(begin, end, self.zoomtype)
 
             # redraw map
-            self.UpdateMap(render = True)
+            self.UpdateMap(render=True)
 
         elif self.mouse["use"] == "query":
-            self.mapQueried.emit(x=self.mouse['end'][0], y=self.mouse['end'][1])
+            self.mapQueried.emit(
+                x=self.mouse['end'][0],
+                y=self.mouse['end'][1])
 
         elif self.mouse["use"] == "pointer" and \
                 self.digit:
@@ -1421,9 +1562,12 @@
             # 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)
+                self.overlays[
+                    self.dragid].coords = self.pdc.GetIdBounds(
+                    self.dragid)
             elif self.dragid > 100 and self.dragid in self.textdict:
-                self.textdict[self.dragid]['bbox'] = self.pdc.GetIdBounds(self.dragid)
+                self.textdict[self.dragid][
+                    'bbox'] = self.pdc.GetIdBounds(self.dragid)
             else:
                 pass
             self.dragid = None
@@ -1453,22 +1597,26 @@
                        n=north, s=south, e=east, w=west)
 
             # redraw map
-            self.UpdateMap(render = False)
+            self.UpdateMap(render=False)
 
-       # TODO: decide which coordinates to send (e, n, mouse['begin'], mouse['end'])
+       # TODO: decide which coordinates to send (e, n, mouse['begin'],
+       # mouse['end'])
         self.mouseLeftUp.emit(x=coordinates[0], y=coordinates[1])
 
     def OnButtonDClick(self, event):
         """Mouse button double click
         """
-        Debug.msg (5, "BufferedWindow.OnButtonDClick(): use=%s" % \
-                   self.mouse["use"])
+        Debug.msg(5, "BufferedWindow.OnButtonDClick(): use=%s" %
+                  self.mouse["use"])
 
         screenCoords = event.GetPosition()
 
         if self.mouse['use'] == 'pointer':
             # select overlay decoration options dialog
-            idlist  = self.pdc.FindObjects(screenCoords[0], screenCoords[1], self.hitradius)
+            idlist = self.pdc.FindObjects(
+                screenCoords[0],
+                screenCoords[1],
+                self.hitradius)
             if idlist:
                 self.dragid = idlist[0]
                 self.overlayActivated.emit(overlayId=self.dragid)
@@ -1479,8 +1627,8 @@
     def OnRightDown(self, event):
         """Right mouse button pressed
         """
-        Debug.msg (5, "BufferedWindow.OnRightDown(): use=%s" % \
-                   self.mouse["use"])
+        Debug.msg(5, "BufferedWindow.OnRightDown(): use=%s" %
+                  self.mouse["use"])
 
         if self.digit:
             self._onRightDown(event)
@@ -1490,8 +1638,8 @@
     def OnRightUp(self, event):
         """Right mouse button released
         """
-        Debug.msg (5, "BufferedWindow.OnRightUp(): use=%s" % \
-                   self.mouse["use"])
+        Debug.msg(5, "BufferedWindow.OnRightUp(): use=%s" %
+                  self.mouse["use"])
 
         if self.digit:
             self._onRightUp(event)
@@ -1519,12 +1667,12 @@
 
         # set region in zoom or pan
         begin = self.mouse['begin']
-        end   = self.mouse['end']
+        end = self.mouse['end']
 
-        self.Zoom(begin, end, 0) # no zoom
+        self.Zoom(begin, end, 0)  # no zoom
 
         # redraw map
-        self.UpdateMap(render = True)
+        self.UpdateMap(render=True)
 
     def OnMouseEnter(self, event):
         """Mouse entered window and no mouse buttons were pressed
@@ -1548,7 +1696,8 @@
         e, n = self.GetLastEN()
         if wx.TheClipboard.Open():
             do = wx.TextDataObject()
-            # TODO: put delimiter in settings and apply also for Go to in statusbar
+            # TODO: put delimiter in settings and apply also for Go to in
+            # statusbar
             delim = ','
             do.SetText(str(e) + delim + str(n))
             wx.TheClipboard.SetData(do)
@@ -1562,7 +1711,7 @@
         """Show/hide all toolbars"""
         self._giface.ShowAllToolbars(not self._giface.AreAllToolbarsShown())
 
-    def ClearLines(self, pdc = None):
+    def ClearLines(self, pdc=None):
         """Clears temporary drawn lines from PseudoDC
         """
         if not pdc:
@@ -1606,7 +1755,7 @@
         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
+        east = w + x * res
         north = n - y * res
 
         return (east, north)
@@ -1615,7 +1764,7 @@
         """Convert real word coordinates to image coordinates
         """
         try:
-            east  = float(enCoords[0])
+            east = float(enCoords[0])
             north = float(enCoords[1])
         except:
             return None
@@ -1628,7 +1777,7 @@
         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
+        x = (east - w) / res
         y = (n - north) / res
 
         return (x, y)
@@ -1642,7 +1791,7 @@
 
         # 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:
+        if abs(x2 - x1) > 5 and abs(y2 - y1) > 5 and zoomtype != 0:
             if x1 > x2:
                 x1, x2 = x2, x1
             if y1 > y2:
@@ -1656,10 +1805,9 @@
             # zoom out
             elif zoomtype < 0:
                 newreg['w'], newreg['n'] = self.Pixel2Cell((-x1 * 2, -y1 * 2))
-                newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width  + 2 * \
-                                                                (self.Map.width  - x2),
-                                                            self.Map.height + 2 * \
-                                                                (self.Map.height - y2)))
+                newreg['e'], newreg['s'] = self.Pixel2Cell(
+                    (self.Map.width + 2 * (self.Map.width - x2),
+                     self.Map.height + 2 * (self.Map.height - y2)))
         # pan
         elif zoomtype == 0:
             dx = x1 - x2
@@ -1668,7 +1816,7 @@
                 dx = x1 - self.Map.width / 2
                 dy = y1 - self.Map.height / 2
             newreg['w'], newreg['n'] = self.Pixel2Cell((dx, dy))
-            newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width  + dx,
+            newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + dx,
                                                         self.Map.height + dy))
 
         # if new region has been calculated, set the values
@@ -1684,8 +1832,10 @@
             # calculate new center point and display resolution
             self.Map.region['center_easting'] = ce
             self.Map.region['center_northing'] = cn
-            self.Map.region['ewres'] = (newreg['e'] - newreg['w']) / self.Map.width
-            self.Map.region['nsres'] = (newreg['n'] - newreg['s']) / self.Map.height
+            self.Map.region['ewres'] = (
+                newreg['e'] - newreg['w']) / self.Map.width
+            self.Map.region['nsres'] = (
+                newreg['n'] - newreg['s']) / self.Map.height
             if self._properties.alignExtent:
                 self.Map.AlignExtentFromDisplay()
             else:
@@ -1720,9 +1870,9 @@
             self.zoomHistoryUnavailable.emit()
 
         # zoom to selected region
-        self.Map.GetRegion(n = zoom[0], s = zoom[1],
-                           e = zoom[2], w = zoom[3],
-                           update = True)
+        self.Map.GetRegion(n=zoom[0], s=zoom[1],
+                           e=zoom[2], w=zoom[3],
+                           update=True)
         # update map
         self.UpdateMap()
 
@@ -1744,7 +1894,7 @@
         :return: removed history item if exists (or None)
         """
         removed = None
-        self.zoomhistory.append((n,s,e,w))
+        self.zoomhistory.append((n, s, e, w))
 
         if len(self.zoomhistory) > 10:
             removed = self.zoomhistory.pop(0)
@@ -1791,7 +1941,7 @@
         """Reset zoom history"""
         self.zoomhistory = list()
 
-    def ZoomToMap(self, layers = None, ignoreNulls = False, render = True):
+    def ZoomToMap(self, layers=None, ignoreNulls=False, render=True):
         """Set display extents to match selected raster
         or vector map(s).
 
@@ -1820,8 +1970,8 @@
                 if self.digit and \
                         self.toolbar.GetLayer() == l:
                     w, s, b, e, n, t = self.digit.GetDisplay().GetMapBoundingBox()
-                    self.Map.GetRegion(n = n, s = s, w = w, e = e,
-                                       update = True)
+                    self.Map.GetRegion(n=n, s=s, w=w, e=e,
+                                       update=True)
                     updated = True
                 else:
                     vect.append(l.name)
@@ -1856,8 +2006,8 @@
     def ZoomToDefault(self):
         """Set display geometry to match default region settings
         """
-        self.Map.region = self.Map.GetRegion(default = True)
-        self.Map.AdjustRegion() # aling region extent to the display
+        self.Map.region = self.Map.GetRegion(default=True)
+        self.Map.AdjustRegion()  # aling region extent to the display
 
         self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
                          self.Map.region['e'], self.Map.region['w'])
@@ -1880,7 +2030,7 @@
 
         # add to zoom history
         self.ZoomHistory(region['n'], region['s'],
-                                   region['e'], region['w'])
+                         region['e'], region['w'])
         self.UpdateMap()
 
     def DisplayToWind(self):
@@ -1895,19 +2045,19 @@
         # for user to set explicitly with g.region
         new = self.Map.AlignResolution()
         RunCommand('g.region',
-                   parent = self,
-                   overwrite = True,
-                   n = new['n'],
-                   s = new['s'],
-                   e = new['e'],
-                   w = new['w'],
-                   rows = int(new['rows']),
-                   cols = int(new['cols']))
+                   parent=self,
+                   overwrite=True,
+                   n=new['n'],
+                   s=new['s'],
+                   e=new['e'],
+                   w=new['w'],
+                   rows=int(new['rows']),
+                   cols=int(new['cols']))
 
         if tmpreg:
             os.environ["GRASS_REGION"] = tmpreg
 
-        self.UpdateMap(render = False)
+        self.UpdateMap(render=False)
 
     def SetRegion(self, zoomOnly=True):
         """Set display extents/compulational region from named region
@@ -1919,26 +2069,28 @@
             label = _('Zoom to saved region extents')
         else:
             label = _('Set compulational region from named region')
-        dlg = SavedRegion(parent = self,
-                          title = label,
-                          loadsave = 'load')
+        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)
+        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.Map.GetRegion(regionName=region,
+                               update=True)
 
             self.ZoomHistory(self.Map.region['n'],
                              self.Map.region['s'],
@@ -1947,12 +2099,12 @@
         else:
             # set computation region from named region file
             RunCommand('g.region',
-                       parent = self,
-                       region = region)
+                       parent=self,
+                       region=region)
 
         self.UpdateMap()
 
-    def SaveRegion(self, display = True):
+    def SaveRegion(self, display=True):
         """Save display extents/compulational region to named region
         file.
 
@@ -1963,17 +2115,21 @@
         else:
             title = _("Save computational region to region file")
 
-        dlg = SavedRegion(parent = self, title = title, loadsave = 'save')
+        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,
-                                      message = _("Region file <%s> already exists. "
-                                                  "Do you want to overwrite it?") % (dlg.GetName()),
-                                      caption = _("Warning"), style = wx.YES_NO | wx.CENTRE)
+        if grass.find_file(name=dlg.GetName(), element='windows')['name']:
+            overwrite = wx.MessageBox(
+                parent=self,
+                message=_(
+                    "Region file <%s> already exists. "
+                    "Do you want to overwrite it?") %
+                (dlg.GetName()),
+                caption=_("Warning"),
+                style=wx.YES_NO | wx.CENTRE)
             if overwrite != wx.YES:
                 dlg.Destroy()
                 return
@@ -1991,10 +2147,10 @@
         :param name: region name
         """
         RunCommand('g.region',
-                   overwrite = True,
-                   parent = self,
-                   flags = 'u',
-                   save = name)
+                   overwrite=True,
+                   parent=self,
+                   flags='u',
+                   save=name)
 
     def _saveDisplayRegion(self, name):
         """Save display extents to region file
@@ -2008,21 +2164,21 @@
             del os.environ["GRASS_REGION"]
 
         RunCommand('g.region',
-                   overwrite = True,
-                   parent = self,
-                   flags = 'u',
-                   n = new['n'],
-                   s = new['s'],
-                   e = new['e'],
-                   w = new['w'],
-                   rows = int(new['rows']),
-                   cols = int(new['cols']),
-                   save = name)
+                   overwrite=True,
+                   parent=self,
+                   flags='u',
+                   n=new['n'],
+                   s=new['s'],
+                   e=new['e'],
+                   w=new['w'],
+                   rows=int(new['rows']),
+                   cols=int(new['cols']),
+                   save=name)
 
         if tmpreg:
             os.environ["GRASS_REGION"] = tmpreg
 
-    def Distance(self, beginpt, endpt, screen = True):
+    def Distance(self, beginpt, endpt, screen=True):
         """Calculates distance
 
         Ctypes required for LL-locations
@@ -2038,7 +2194,7 @@
             e1, n1 = beginpt
             e2, n2 = endpt
 
-        dEast  = (e2 - e1)
+        dEast = (e2 - e1)
         dNorth = (n2 - n1)
 
         if self.Map.projinfo['proj'] == 'll' and haveCtypes:
@@ -2052,8 +2208,9 @@
         """Get render.Map() instance"""
         return self.Map
 
-    def RegisterGraphicsToDraw(self, graphicsType, pdc=None, setStatusFunc=None, drawFunc=None,
-                               mapCoords=True):
+    def RegisterGraphicsToDraw(
+            self, graphicsType, pdc=None, setStatusFunc=None, drawFunc=None,
+            mapCoords=True):
         """This method registers graphics to draw.
 
         :param type: (string) - graphics type: "point", "line" or "rectangle"

Modified: grass/trunk/gui/wxpython/mapwin/decorations.py
===================================================================
--- grass/trunk/gui/wxpython/mapwin/decorations.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/mapwin/decorations.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -23,7 +23,7 @@
 
 import wx
 from wx.lib.expando import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED
-        
+
 from grass.pydispatch.signal import Signal
 try:
     from PIL import Image
@@ -31,11 +31,13 @@
 except ImportError:
     hasPIL = False
 
+
 class OverlayId:
     legendId = 0
     barscaleId = 1
-    arrowId = 2 
-    
+    arrowId = 2
+
+
 class OverlayController(object):
 
     """Base class for decorations (barscale, legend) controller."""
@@ -78,7 +80,8 @@
 
     def GetCoords(self):
         if self._coords is None:  # initial position
-            x, y = self.GetPlacement((self._renderer.width, self._renderer.height))
+            x, y = self.GetPlacement(
+                (self._renderer.width, self._renderer.height))
             self._coords = [x, y]
         return self._coords
 
@@ -159,14 +162,18 @@
         self.Show()
 
     def _add(self):
-        self._overlay = self._renderer.AddOverlay(id=self._id, ltype=self._name,
-                                                  command=self.cmd, active=False,
-                                                  render=True, hidden=True)
+        self._overlay = self._renderer.AddOverlay(
+            id=self._id,
+            ltype=self._name,
+            command=self.cmd,
+            active=False,
+            render=True,
+            hidden=True)
         # check if successful
 
     def _update(self):
         self._renderer.ChangeOverlay(id=self._id, command=self._cmd)
-        
+
     def CmdIsValid(self):
         """If command is valid"""
         return True
@@ -177,8 +184,10 @@
         :param screensize: screen size
         """
         if not hasPIL:
-            self._giface.WriteWarning(_("Please install Python Imaging Library (PIL)\n"
-                                        "for better control of legend and other decorations."))
+            self._giface.WriteWarning(
+                _(
+                    "Please install Python Imaging Library (PIL)\n"
+                    "for better control of legend and other decorations."))
             return 0, 0
         for param in self._cmd:
             if not param.startswith('at'):
@@ -196,7 +205,8 @@
         OverlayController.__init__(self, renderer, giface)
         self._id = OverlayId.barscaleId
         self._name = 'barscale'
-        # different from default because the reference point is not in the middle
+        # different from default because the reference point is not in the
+        # middle
         self._defaultAt = 'at=0,98'
         self._cmd = ['d.barscale', self._defaultAt]
 
@@ -207,7 +217,8 @@
         OverlayController.__init__(self, renderer, giface)
         self._id = OverlayId.arrowId
         self._name = 'arrow'
-        # different from default because the reference point is not in the middle
+        # different from default because the reference point is not in the
+        # middle
         self._defaultAt = 'at=85.0,25.0'
         self._cmd = ['d.northarrow', self._defaultAt]
 
@@ -224,13 +235,16 @@
 
     def GetPlacement(self, screensize):
         if not hasPIL:
-            self._giface.WriteWarning(_("Please install Python Imaging Library (PIL)\n"
-                                        "for better control of legend and other decorations."))
+            self._giface.WriteWarning(
+                _(
+                    "Please install Python Imaging Library (PIL)\n"
+                    "for better control of legend and other decorations."))
             return 0, 0
         for param in self._cmd:
             if not param.startswith('at'):
                 continue
-            b, t, l, r = [float(number) for number in param.split('=')[1].split(',')]  # pylint: disable-msg=W0612
+            b, t, l, r = [float(number) for number in param.split(
+                '=')[1].split(',')]  # pylint: disable-msg=W0612
             x = int((l / 100.) * screensize[0])
             y = int((1 - t / 100.) * screensize[1])
 
@@ -292,7 +306,10 @@
         window = self._giface.GetMapWindow()
         window.mouseLeftUp.disconnect(self._finishResizing)
         screenSize = window.GetClientSizeTuple()
-        self.ResizeLegend(window.mouse["begin"], window.mouse["end"], screenSize)
+        self.ResizeLegend(
+            window.mouse["begin"],
+            window.mouse["end"],
+            screenSize)
         self._giface.GetMapDisplay().GetMapToolbar().SelectDefault()
         # redraw
         self.overlayChanged.emit()
@@ -301,10 +318,17 @@
 class TextLayerDialog(wx.Dialog):
     """!Controls setting options and displaying/hiding map overlay decorations
     """
+
     def __init__(self, parent, ovlId, title, name='text', size=wx.DefaultSize,
                  style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
 
-        wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=title, style=style, size=size)
+        wx.Dialog.__init__(
+            self,
+            parent=parent,
+            id=wx.ID_ANY,
+            title=title,
+            style=style,
+            size=size)
 
         self.ovlId = ovlId
         self.parent = parent
@@ -313,8 +337,10 @@
             self.currText = self.parent.MapWindow.textdict[self.ovlId]['text']
             self.currFont = self.parent.MapWindow.textdict[self.ovlId]['font']
             self.currClr = self.parent.MapWindow.textdict[self.ovlId]['color']
-            self.currRot = self.parent.MapWindow.textdict[self.ovlId]['rotation']
-            self.currCoords = self.parent.MapWindow.textdict[self.ovlId]['coords']
+            self.currRot = self.parent.MapWindow.textdict[
+                self.ovlId]['rotation']
+            self.currCoords = self.parent.MapWindow.textdict[
+                self.ovlId]['coords']
             self.currBB = self.parent.MapWindow.textdict[self.ovlId]['bbox']
         else:
             self.currClr = wx.BLACK
@@ -333,16 +359,25 @@
         if self.parent.Map.GetOverlay(self.ovlId) is None:
             self.chkbox.SetValue(True)
         else:
-            self.chkbox.SetValue(self.parent.MapWindow.overlays[self.ovlId]['layer'].IsActive())
+            self.chkbox.SetValue(
+                self.parent.MapWindow.overlays[
+                    self.ovlId]['layer'].IsActive())
         box.Add(item=self.chkbox, span=(1, 2),
                 pos=(0, 0))
 
         # text entry
-        box.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Text:")),
-                flag=wx.ALIGN_CENTER_VERTICAL,
-                pos=(1, 0))
+        box.Add(
+            item=wx.StaticText(
+                parent=self,
+                id=wx.ID_ANY,
+                label=_("Text:")),
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                1,
+                0))
 
-        self.textentry = ExpandoTextCtrl(parent=self, id=wx.ID_ANY, value="", size=(300, -1))
+        self.textentry = ExpandoTextCtrl(
+            parent=self, id=wx.ID_ANY, value="", size=(300, -1))
         self.textentry.SetFont(self.currFont)
         self.textentry.SetForegroundColour(self.currClr)
         self.textentry.SetValue(self.currText)
@@ -354,11 +389,19 @@
                 pos=(1, 1))
 
         # rotation
-        box.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Rotation:")),
-                flag=wx.ALIGN_CENTER_VERTICAL,
-                pos=(2, 0))
-        self.rotation = wx.SpinCtrl(parent=self, id=wx.ID_ANY, value="", pos=(30, 50),
-                                    size=(75, -1), style=wx.SP_ARROW_KEYS)
+        box.Add(
+            item=wx.StaticText(
+                parent=self,
+                id=wx.ID_ANY,
+                label=_("Rotation:")),
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                2,
+                0))
+        self.rotation = wx.SpinCtrl(
+            parent=self, id=wx.ID_ANY, value="", pos=(
+                30, 50), size=(
+                75, -1), style=wx.SP_ARROW_KEYS)
         self.rotation.SetRange(-360, 360)
         self.rotation.SetValue(int(self.currRot))
         box.Add(item=self.rotation,
@@ -366,9 +409,15 @@
                 pos=(2, 1))
 
         # font
-        box.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Font:")),
-                flag=wx.ALIGN_CENTER_VERTICAL,
-                pos=(3, 0))
+        box.Add(
+            item=wx.StaticText(
+                parent=self,
+                id=wx.ID_ANY,
+                label=_("Font:")),
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                3,
+                0))
         fontbtn = wx.Button(parent=self, id=wx.ID_ANY, label=_("Set font"))
         box.Add(item=fontbtn,
                 flag=wx.ALIGN_RIGHT,
@@ -381,13 +430,15 @@
 
         # note
         box = wx.BoxSizer(wx.HORIZONTAL)
-        label = wx.StaticText(parent=self, id=wx.ID_ANY,
-                              label=_("Drag text with mouse in pointer mode "
-                                      "to position.\nDouble-click to change options"))
+        label = wx.StaticText(
+            parent=self, id=wx.ID_ANY, label=_(
+                "Drag text with mouse in pointer mode "
+                "to position.\nDouble-click to change options"))
         box.Add(item=label, proportion=0,
                 flag=wx.ALIGN_CENTRE | wx.ALL, border=5)
-        self.sizer.Add(item=box, proportion=0,
-                       flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER | wx.ALL, border=5)
+        self.sizer.Add(
+            item=box, proportion=0, flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL |
+            wx.ALIGN_CENTER | wx.ALL, border=5)
 
         line = wx.StaticLine(parent=self, id=wx.ID_ANY,
                              size=(20, -1), style=wx.LI_HORIZONTAL)
@@ -412,12 +463,12 @@
 
         # bindings
         self.Bind(EVT_ETC_LAYOUT_NEEDED, self.OnRefit, self.textentry)
-        self.Bind(wx.EVT_BUTTON,     self.OnSelectFont, fontbtn)
-        self.Bind(wx.EVT_TEXT,       self.OnText,       self.textentry)
-        self.Bind(wx.EVT_SPINCTRL,   self.OnRotation,   self.rotation)
+        self.Bind(wx.EVT_BUTTON, self.OnSelectFont, fontbtn)
+        self.Bind(wx.EVT_TEXT, self.OnText, self.textentry)
+        self.Bind(wx.EVT_SPINCTRL, self.OnRotation, self.rotation)
 
         self.SetMinSize((400, 230))
-        
+
     def OnRefit(self, event):
         """Resize text entry to match text"""
         self.sizer.Fit(self)

Modified: grass/trunk/gui/wxpython/mapwin/graphics.py
===================================================================
--- grass/trunk/gui/wxpython/mapwin/graphics.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/mapwin/graphics.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -32,10 +32,10 @@
             RegisterGraphicsToDraw in BufferedWindow class.
         """
         self.pens = {
-            "default":  wx.Pen(colour=wx.BLACK, width=2, style=wx.SOLID),
-            "selected":  wx.Pen(colour=wx.GREEN, width=2, style=wx.SOLID),
-            "unused":  wx.Pen(colour=wx.LIGHT_GREY, width=2, style=wx.SOLID),
-            "highest":  wx.Pen(colour=wx.RED, width=2, style=wx.SOLID)
+            "default": wx.Pen(colour=wx.BLACK, width=2, style=wx.SOLID),
+            "selected": wx.Pen(colour=wx.GREEN, width=2, style=wx.SOLID),
+            "unused": wx.Pen(colour=wx.LIGHT_GREY, width=2, style=wx.SOLID),
+            "highest": wx.Pen(colour=wx.RED, width=2, style=wx.SOLID)
         }
         self.brushes = {
             'default': wx.TRANSPARENT_BRUSH
@@ -58,10 +58,11 @@
             self.properties["size"] = 5
 
             self.properties["text"] = {}
-            self.properties["text"]['font'] = wx.Font(pointSize=self.properties["size"],
-                                                      family=wx.FONTFAMILY_DEFAULT,
-                                                      style=wx.FONTSTYLE_NORMAL,
-                                                      weight=wx.FONTWEIGHT_NORMAL)
+            self.properties["text"]['font'] = wx.Font(
+                pointSize=self.properties["size"],
+                family=wx.FONTFAMILY_DEFAULT,
+                style=wx.FONTSTYLE_NORMAL,
+                weight=wx.FONTWEIGHT_NORMAL)
             self.properties["text"]['active'] = True
 
             self.drawFunc = self.parentMapWin.DrawCross
@@ -89,7 +90,8 @@
 
             if self.graphicsType == "point":
                 if item.GetPropertyVal("penName"):
-                    self.parentMapWin.pen = self.pens[item.GetPropertyVal("penName")]
+                    self.parentMapWin.pen = self.pens[
+                        item.GetPropertyVal("penName")]
                 else:
                     self.parentMapWin.pen = self.pens["default"]
 
@@ -106,7 +108,8 @@
                     self.properties["text"]['coords'] = [coords[0] + size,
                                                          coords[1] + size,
                                                          size, size]
-                    self.properties["text"]['color'] = self.parentMapWin.pen.GetColour()
+                    self.properties["text"][
+                        'color'] = self.parentMapWin.pen.GetColour()
                     self.properties["text"]['text'] = label
 
                 self.drawFunc(pdc=self.pdc, drawid=item.GetId(),
@@ -121,7 +124,9 @@
                     pen = self.pens["default"]
 
                 if self.mapCoords:
-                    coords = [self.parentMapWin.Cell2Pixel(coords) for coords in item.GetCoords()]
+                    coords = [
+                        self.parentMapWin.Cell2Pixel(coords)
+                        for coords in item.GetCoords()]
                 else:
                     coords = item.GetCoords()
 
@@ -138,13 +143,19 @@
                 else:
                     brush = self.brushes["default"]
                 if self.mapCoords:
-                    coords = [self.parentMapWin.Cell2Pixel(coords) for coords in item.GetCoords()]
+                    coords = [
+                        self.parentMapWin.Cell2Pixel(coords)
+                        for coords in item.GetCoords()]
                 else:
                     coords = item.GetCoords()
 
-                self.drawFunc(pdc=self.pdc, pen=pen, brush=brush, drawid=item.GetId(),
-                              point1=coords[0],
-                              point2=coords[1])
+                self.drawFunc(
+                    pdc=self.pdc,
+                    pen=pen,
+                    brush=brush,
+                    drawid=item.GetId(),
+                    point1=coords[0],
+                    point2=coords[1])
 
             elif self.graphicsType == "polygon":
                 if item.GetPropertyVal("penName"):
@@ -156,7 +167,9 @@
                 else:
                     brush = self.brushes["default"]
                 if self.mapCoords:
-                    coords = [self.parentMapWin.Cell2Pixel(coords) for coords in item.GetCoords()]
+                    coords = [
+                        self.parentMapWin.Cell2Pixel(coords)
+                        for coords in item.GetCoords()]
                 else:
                     coords = item.GetCoords()
 
@@ -337,7 +350,9 @@
         """
         if drawNum < len(self.itemsList) and drawNum >= 0 and \
                 item in self.itemsList:
-            self.itemsList.insert(drawNum, self.itemsList.pop(self.itemsList.index(item)))
+            self.itemsList.insert(
+                drawNum, self.itemsList.pop(
+                    self.itemsList.index(item)))
             return True
 
         return False
@@ -365,7 +380,8 @@
 
 class GraphicsSetItem:
 
-    def __init__(self, coords, penName=None, brushName=None, label=None, hide=False):
+    def __init__(self, coords, penName=None,
+                 brushName=None, label=None, hide=False):
         """Could be point or line according to graphicsType in
         GraphicsSet class
 

Modified: grass/trunk/gui/wxpython/modules/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/modules/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/modules/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -4,4 +4,4 @@
     'vclean',
     'colorrules',
     'histogram',
-    ]
+]

Modified: grass/trunk/gui/wxpython/modules/colorrules.py
===================================================================
--- grass/trunk/gui/wxpython/modules/colorrules.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/modules/colorrules.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -28,73 +28,76 @@
 import tempfile
 
 import wx
-import wx.lib.colourselect     as csel
-import wx.lib.scrolledpanel    as scrolled
+import wx.lib.colourselect as csel
+import wx.lib.scrolledpanel as scrolled
 import wx.lib.filebrowsebutton as filebrowse
 
 import grass.script as grass
 from grass.script.task import cmdlist_to_tuple
 
-from core             import globalvar
-from core             import utils
+from core import globalvar
+from core import utils
 from core.utils import _
-from core.gcmd        import GMessage, RunCommand, GError
+from core.gcmd import GMessage, RunCommand, GError
 from gui_core.gselect import Select, LayerSelect, ColumnSelect, VectorDBInfo
-from core.render      import Map
-from gui_core.forms   import GUI
-from core.debug       import Debug as Debug
-from core.settings    import UserSettings
+from core.render import Map
+from gui_core.forms import GUI
+from core.debug import Debug as Debug
+from core.settings import UserSettings
 from gui_core.widgets import ColorTablesComboBox
 
+
 class RulesPanel:
-    def __init__(self, parent, mapType, attributeType, properties, panelWidth = 180):
+
+    def __init__(self, parent, mapType, attributeType,
+                 properties, panelWidth=180):
         """Create rules panel
-        
+
         :param mapType: raster/vector
         :param attributeType: color/size for choosing widget type
         :param properties: properties of classes derived from ColorTable
         :param panelWidth: width of scroll panel"""
-        
+
         self.ruleslines = {}
         self.mapType = mapType
         self.attributeType = attributeType
         self.properties = properties
         self.parent = parent
         self.panelWidth = panelWidth
-        
-        self.mainSizer = wx.FlexGridSizer(cols = 3, vgap = 6, hgap = 4)
+
+        self.mainSizer = wx.FlexGridSizer(cols=3, vgap=6, hgap=4)
         # put small border at the top of panel
         for i in range(3):
-            self.mainSizer.Add(item = wx.Size(3, 3))
-        
-        self.mainPanel = scrolled.ScrolledPanel(parent, id = wx.ID_ANY,
-                                          size = (self.panelWidth, 300),
-                                          style = wx.TAB_TRAVERSAL | wx.SUNKEN_BORDER)
-                
+            self.mainSizer.Add(item=wx.Size(3, 3))
+
+        self.mainPanel = scrolled.ScrolledPanel(
+            parent, id=wx.ID_ANY, size=(self.panelWidth, 300),
+            style=wx.TAB_TRAVERSAL | wx.SUNKEN_BORDER)
+
         # (un)check all
-        self.checkAll = wx.CheckBox(parent, id = wx.ID_ANY, label = _("Check all"))
+        self.checkAll = wx.CheckBox(parent, id=wx.ID_ANY, label=_("Check all"))
         self.checkAll.SetValue(True)
         # clear button
-        self.clearAll = wx.Button(parent, id = wx.ID_ANY, label = _("Clear all"))
+        self.clearAll = wx.Button(parent, id=wx.ID_ANY, label=_("Clear all"))
         #  determines how many rules should be added
-        self.numRules = wx.SpinCtrl(parent, id = wx.ID_ANY,
-                                    min = 1, max = 1e6, initial = 1)
+        self.numRules = wx.SpinCtrl(parent, id=wx.ID_ANY,
+                                    min=1, max=1e6, initial=1)
         # add rules
-        self.btnAdd = wx.Button(parent, id = wx.ID_ADD)
-        
+        self.btnAdd = wx.Button(parent, id=wx.ID_ADD)
+
         self.btnAdd.Bind(wx.EVT_BUTTON, self.OnAddRules)
         self.checkAll.Bind(wx.EVT_CHECKBOX, self.OnCheckAll)
         self.clearAll.Bind(wx.EVT_BUTTON, self.OnClearAll)
 
         self.mainPanel.SetSizer(self.mainSizer)
         self.mainPanel.SetAutoLayout(True)
-        self.mainPanel.SetupScrolling()    
-    
+        self.mainPanel.SetupScrolling()
+
     def Clear(self):
         """Clear and widgets and delete information"""
         self.ruleslines.clear()
         self.mainSizer.Clear(deleteWindows=True)
-    
+
     def OnCheckAll(self, event):
         """(Un)check all rules"""
         check = event.GetInt()
@@ -103,134 +106,141 @@
                 child.SetValue(check)
             else:
                 child.Enable(check)
-                
+
     def OnClearAll(self, event):
         """Delete all widgets in panel"""
         self.Clear()
-        
+
     def OnAddRules(self, event):
         """Add rules button pressed"""
         nrules = self.numRules.GetValue()
         self.AddRules(nrules)
-        
-    def AddRules(self, nrules, start = False):
+
+    def AddRules(self, nrules, start=False):
         """Add rules
-         
+
         :param start: set widgets (not append)
         """
-       
+
         snum = len(self.ruleslines.keys())
         if start:
             snum = 0
         for num in range(snum, snum + nrules):
             # enable
-            enable = wx.CheckBox(parent = self.mainPanel, id = num)
+            enable = wx.CheckBox(parent=self.mainPanel, id=num)
             enable.SetValue(True)
             enable.SetName('enable')
             enable.Bind(wx.EVT_CHECKBOX, self.OnRuleEnable)
             # value
-            txt_ctrl = wx.TextCtrl(parent = self.mainPanel, id = 1000 + num,
-                                   size = (80, -1),
-                                   style = wx.TE_NOHIDESEL)
+            txt_ctrl = wx.TextCtrl(parent=self.mainPanel, id=1000 + num,
+                                   size=(80, -1),
+                                   style=wx.TE_NOHIDESEL)
             if self.mapType == 'vector':
                 txt_ctrl.SetToolTipString(_("Enter vector attribute values"))
             txt_ctrl.Bind(wx.EVT_TEXT, self.OnRuleValue)
             txt_ctrl.SetName('source')
             if self.attributeType == 'color':
                 # color
-                columnCtrl = csel.ColourSelect(self.mainPanel, id = 2000 + num,
-                                               size  =  globalvar.DIALOG_COLOR_SIZE)
+                columnCtrl = csel.ColourSelect(
+                    self.mainPanel, id=2000 + num,
+                    size=globalvar.DIALOG_COLOR_SIZE)
                 columnCtrl.Bind(csel.EVT_COLOURSELECT, self.OnRuleColor)
                 columnCtrl.SetName('target')
                 if not start:
-                    self.ruleslines[enable.GetId()] = { 'value' : '',
-                                                        'color': "0:0:0" }
+                    self.ruleslines[enable.GetId()] = {'value': '',
+                                                       'color': "0:0:0"}
             else:
                 # size or width
                 init = 2
                 if self.attributeType == 'size':
                     init = 100
-                columnCtrl = wx.SpinCtrl(self.mainPanel, id = 2000 + num,
-                                         size = (50, -1), min = 1, max = 1e4,
-                                         initial = init)
+                columnCtrl = wx.SpinCtrl(self.mainPanel, id=2000 + num,
+                                         size=(50, -1), min=1, max=1e4,
+                                         initial=init)
                 columnCtrl.Bind(wx.EVT_SPINCTRL, self.OnRuleSize)
                 columnCtrl.Bind(wx.EVT_TEXT, self.OnRuleSize)
                 columnCtrl.SetName('target')
                 if not start:
-                    self.ruleslines[enable.GetId()] = { 'value' : '',
-                                                        self.attributeType: init }
-        
-            self.mainSizer.Add(item = enable, proportion = 0,
-                              flag = wx.ALIGN_CENTER_VERTICAL)
-            self.mainSizer.Add(item = txt_ctrl, proportion = 0,
-                              flag = wx.ALIGN_CENTER | wx.RIGHT, border = 5)
-            self.mainSizer.Add(item = columnCtrl, proportion = 0,
-                              flag = wx.ALIGN_CENTER | wx.RIGHT, border = 10)
-        
+                    self.ruleslines[
+                        enable.GetId()] = {
+                        'value': '',
+                        self.attributeType: init}
+
+            self.mainSizer.Add(item=enable, proportion=0,
+                               flag=wx.ALIGN_CENTER_VERTICAL)
+            self.mainSizer.Add(item=txt_ctrl, proportion=0,
+                               flag=wx.ALIGN_CENTER | wx.RIGHT, border=5)
+            self.mainSizer.Add(item=columnCtrl, proportion=0,
+                               flag=wx.ALIGN_CENTER | wx.RIGHT, border=10)
+
         self.mainPanel.Layout()
-        self.mainPanel.SetupScrolling(scroll_x = False)
-    
+        self.mainPanel.SetupScrolling(scroll_x=False)
+
     def OnRuleEnable(self, event):
         """Rule enabled/disabled"""
         id = event.GetId()
-        
+
         if event.IsChecked():
             self.mainPanel.FindWindowById(id + 1000).Enable()
             self.mainPanel.FindWindowById(id + 2000).Enable()
             if self.mapType == 'vector' and not self.parent.GetParent().colorTable:
                 vals = []
-                vals.append(self.mainPanel.FindWindowById(id + 1000).GetValue())
+                vals.append(
+                    self.mainPanel.FindWindowById(
+                        id + 1000).GetValue())
                 try:
-                    vals.append(self.mainPanel.FindWindowById(id + 1 + 1000).GetValue())
+                    vals.append(
+                        self.mainPanel.FindWindowById(
+                            id + 1 + 1000).GetValue())
                 except AttributeError:
                     vals.append(None)
                 value = self.SQLConvert(vals)
             else:
                 value = self.mainPanel.FindWindowById(id + 1000).GetValue()
             color = self.mainPanel.FindWindowById(id + 2000).GetValue()
-            
+
             if self.attributeType == 'color':
-            # color
+                # color
                 color_str = str(color[0]) + ':' \
-                          + str(color[1]) + ':' \
-                          + str(color[2])
-                self.ruleslines[id] = {'value' : value,
-                                       'color' : color_str }
-                
+                    + str(color[1]) + ':' \
+                    + str(color[2])
+                self.ruleslines[id] = {'value': value,
+                                       'color': color_str}
+
             else:
-            # size or width
-                self.ruleslines[id] = {'value' : value,
-                                       self.attributeType  : float(color) }
-        
+                # size or width
+                self.ruleslines[id] = {'value': value,
+                                       self.attributeType: float(color)}
+
         else:
             self.mainPanel.FindWindowById(id + 1000).Disable()
             self.mainPanel.FindWindowById(id + 2000).Disable()
             del self.ruleslines[id]
-        
+
     def OnRuleColor(self, event):
         """Rule color changed"""
         num = event.GetId()
-        
+
         rgba_color = event.GetValue()
-        
+
         rgb_string = str(rgba_color[0]) + ':' \
-                   + str(rgba_color[1]) + ':' \
-                   + str(rgba_color[2])
-        
-        self.ruleslines[num-2000]['color'] = rgb_string
-     
+            + str(rgba_color[1]) + ':' \
+            + str(rgba_color[2])
+
+        self.ruleslines[num - 2000]['color'] = rgb_string
+
     def OnRuleSize(self, event):
         """Rule size changed"""
         num = event.GetId()
         size = event.GetInt()
-        
+
         self.ruleslines[num - 2000][self.attributeType] = size
-        
+
     def OnRuleValue(self, event):
         """Rule value changed"""
         num = event.GetId()
         val = event.GetString().strip()
-        
+
         if val == '':
             return
         try:
@@ -246,8 +256,8 @@
         else:
             self.SetVectorRule(num, val)
 
-    def SetRasterRule(self, num, val): 
-        """Set raster rule"""     
+    def SetRasterRule(self, num, val):
+        """Set raster rule"""
         self.ruleslines[num - 1000]['value'] = val
 
     def SetVectorRule(self, num, val):
@@ -259,65 +269,76 @@
         except AttributeError:
             vals.append(None)
         self.ruleslines[num - 1000]['value'] = self.SQLConvert(vals)
-            
-    def Enable(self, enable = True):
+
+    def Enable(self, enable=True):
         """Enable/Disable all widgets"""
         for child in self.mainPanel.GetChildren():
             child.Enable(enable)
         sql = True
-        self.LoadRulesline(sql)# todo
+        self.LoadRulesline(sql)  # todo
         self.btnAdd.Enable(enable)
         self.numRules.Enable(enable)
         self.checkAll.Enable(enable)
         self.clearAll.Enable(enable)
-        
-        
+
     def LoadRules(self):
-        message = ""        
+        message = ""
         for item in range(len(self.ruleslines)):
             try:
-                self.mainPanel.FindWindowById(item + 1000).SetValue(self.ruleslines[item]['value'])
-                r, g, b = (0, 0, 0) # default
+                self.mainPanel.FindWindowById(
+                    item +
+                    1000).SetValue(
+                    self.ruleslines[item]['value'])
+                r, g, b = (0, 0, 0)  # default
                 if not self.ruleslines[item][self.attributeType]:
                     if self.attributeType == 'color':
-                        self.ruleslines[item][self.attributeType] = '%d:%d:%d' % (r, g, b)
+                        self.ruleslines[item][
+                            self.attributeType] = '%d:%d:%d' % (
+                            r, g, b)
                     elif self.attributeType == 'size':
-                        self.ruleslines[item][self.attributeType] = 100                
+                        self.ruleslines[item][self.attributeType] = 100
                     elif self.attributeType == 'width':
                         self.ruleslines[item][self.attributeType] = 2
-                    
+
                 if self.attributeType == 'color':
                     try:
-                        r, g, b = map(int, self.ruleslines[item][self.attributeType].split(':'))
+                        r, g, b = map(
+                            int, self.ruleslines[item][
+                                self.attributeType].split(':'))
                     except ValueError as e:
-                        message =  _("Bad color format. Use color format '0:0:0'")
-                    self.mainPanel.FindWindowById(item + 2000).SetValue((r, g, b))
+                        message = _(
+                            "Bad color format. Use color format '0:0:0'")
+                    self.mainPanel.FindWindowById(
+                        item + 2000).SetValue((r, g, b))
                 else:
                     value = float(self.ruleslines[item][self.attributeType])
                     self.mainPanel.FindWindowById(item + 2000).SetValue(value)
             except:
                 continue
-                
+
         if message:
-            GMessage(parent = self.parent, message = message)
+            GMessage(parent=self.parent, message=message)
             return False
-        
+
         return True
-                
+
     def SQLConvert(self, vals):
         """Prepare value for SQL query"""
         if vals[0].isdigit():
             sqlrule = '%s=%s' % (self.properties['sourceColumn'], vals[0])
             if vals[1]:
-                sqlrule += ' AND %s<%s' % (self.properties['sourceColumn'], vals[1])
+                sqlrule += ' AND %s<%s' % (
+                    self.properties['sourceColumn'], vals[1])
         else:
             sqlrule = '%s=%s' % (self.properties['sourceColumn'], vals[0])
-        
-        return sqlrule  
 
+        return sqlrule
+
+
 class ColorTable(wx.Frame):
-    def __init__(self, parent, title, layerTree = None, id = wx.ID_ANY,
-                 style = wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER,
+
+    def __init__(self, parent, title, layerTree=None, id=wx.ID_ANY,
+                 style=wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER,
                  **kwargs):
         """Dialog for interactively entering rules for map management
         commands
@@ -327,56 +348,63 @@
         """
         self.parent = parent        # GMFrame ?
         self.layerTree = layerTree  # LayerTree or None
-        
-        wx.Frame.__init__(self, parent, id, title, style = style, **kwargs)
-        
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
-        
-        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
-        
+
+        wx.Frame.__init__(self, parent, id, title, style=style, **kwargs)
+
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass.ico'),
+                wx.BITMAP_TYPE_ICO))
+
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
         # instance of render.Map to be associated with display
-        self.Map  = Map() 
-        
+        self.Map = Map()
+
         # input map to change
         self.inmap = ''
-        
+
         # reference to layer with preview
         self.layer = None
-        
+
         # layout
         self._doLayout()
-        
+
         # bindings
-        self.Bind(wx.EVT_BUTTON, self.OnHelp,             self.btnHelp)
-        self.selectionInput.Bind(wx.EVT_TEXT,             self.OnSelectionInput)
-        self.Bind(wx.EVT_BUTTON, self.OnCancel,           self.btnCancel)
-        self.Bind(wx.EVT_BUTTON, self.OnApply,            self.btnApply)
-        self.Bind(wx.EVT_BUTTON, self.OnOK,               self.btnOK)
+        self.Bind(wx.EVT_BUTTON, self.OnHelp, self.btnHelp)
+        self.selectionInput.Bind(wx.EVT_TEXT, self.OnSelectionInput)
+        self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
+        self.Bind(wx.EVT_BUTTON, self.OnApply, self.btnApply)
+        self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOK)
         self.Bind(wx.EVT_BUTTON, self.OnLoadDefaultTable, self.btnDefault)
-        
-        self.Bind(wx.EVT_CLOSE,  self.OnCloseWindow)
-       
+
+        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
+
         self.Bind(wx.EVT_BUTTON, self.OnPreview, self.btnPreview)
-        
+
     def _initLayer(self):
         """Set initial layer when opening dialog"""
         # set map layer from layer tree, first selected,
         # if not the right type, than select another
         try:
             sel = self.layerTree.layer_selected
-            if sel and self.layerTree.GetLayerInfo(sel, key = 'type') == self.mapType:
+            if sel and self.layerTree.GetLayerInfo(
+                    sel, key='type') == self.mapType:
                 layer = sel
             else:
-                layer = self.layerTree.FindItemByData(key = 'type', value = self.mapType)
+                layer = self.layerTree.FindItemByData(
+                    key='type', value=self.mapType)
         except:
             layer = None
         if layer:
-            mapLayer = self.layerTree.GetLayerInfo(layer, key = 'maplayer')
+            mapLayer = self.layerTree.GetLayerInfo(layer, key='maplayer')
             name = mapLayer.GetName()
             type = mapLayer.GetType()
             self.selectionInput.SetValue(name)
             self.inmap = name
-    
+
     def _createMapSelection(self, parent):
         """Create map selection part of dialog"""
         # top controls
@@ -384,161 +412,190 @@
             maplabel = _('Select raster map:')
         else:
             maplabel = _('Select vector map:')
-        inputBox = wx.StaticBox(parent, id = wx.ID_ANY,
-                                label = " %s " % maplabel)
+        inputBox = wx.StaticBox(parent, id=wx.ID_ANY,
+                                label=" %s " % maplabel)
         inputSizer = wx.StaticBoxSizer(inputBox, wx.VERTICAL)
 
-        self.selectionInput = Select(parent = parent, id = wx.ID_ANY,
-                                     size = globalvar.DIALOG_GSELECT_SIZE,
-                                     type = self.mapType)
+        self.selectionInput = Select(parent=parent, id=wx.ID_ANY,
+                                     size=globalvar.DIALOG_GSELECT_SIZE,
+                                     type=self.mapType)
         # layout
-        inputSizer.Add(item = self.selectionInput,
-                       flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND, border = 5)
-        
+        inputSizer.Add(
+            item=self.selectionInput,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND,
+            border=5)
+
         return inputSizer
-    
+
     def _createFileSelection(self, parent):
         """Create file (open/save rules) selection part of dialog"""
-        inputBox = wx.StaticBox(parent, id = wx.ID_ANY,
-                                label = " %s " % _("Import or export color table:"))
+        inputBox = wx.StaticBox(
+            parent, id=wx.ID_ANY, label=" %s " %
+            _("Import or export color table:"))
         inputSizer = wx.StaticBoxSizer(inputBox, wx.HORIZONTAL)
-        
-        self.loadRules = filebrowse.FileBrowseButton(parent = parent, id = wx.ID_ANY, fileMask = '*',
-                                                     labelText = '',
-                                                     dialogTitle = _('Choose file to load color table'),
-                                                     buttonText = _('Load'),
-                                                     toolTip = _("Type filename or click to choose "
-                                                                 "file and load color table"),
-                                                     startDirectory = os.getcwd(), fileMode = wx.FD_OPEN,
-                                                     changeCallback = self.OnLoadRulesFile)
-        self.saveRules = filebrowse.FileBrowseButton(parent = parent, id = wx.ID_ANY, fileMask = '*',
-                                                     labelText = '',
-                                                     dialogTitle = _('Choose file to save color table'),
-                                                     toolTip = _("Type filename or click to choose "
-                                                                 "file and save color table"),
-                                                     buttonText = _('Save'),
-                                                     startDirectory = os.getcwd(), fileMode = wx.FD_SAVE,
-                                                     changeCallback = self.OnSaveRulesFile)
 
-        colorTable = ColorTablesComboBox(parent = parent, size=globalvar.DIALOG_COMBOBOX_SIZE,
-                               choices = utils.GetColorTables(), name="colorTableChoice")
-        self.btnSet = wx.Button(parent = parent, id = wx.ID_ANY, label = _("&Set"), name = 'btnSet')
+        self.loadRules = filebrowse.FileBrowseButton(
+            parent=parent, id=wx.ID_ANY, fileMask='*', labelText='',
+            dialogTitle=_('Choose file to load color table'),
+            buttonText=_('Load'),
+            toolTip=_(
+                "Type filename or click to choose "
+                "file and load color table"),
+            startDirectory=os.getcwd(),
+            fileMode=wx.FD_OPEN, changeCallback=self.OnLoadRulesFile)
+        self.saveRules = filebrowse.FileBrowseButton(
+            parent=parent, id=wx.ID_ANY, fileMask='*', labelText='',
+            dialogTitle=_('Choose file to save color table'),
+            toolTip=_(
+                "Type filename or click to choose "
+                "file and save color table"),
+            buttonText=_('Save'),
+            startDirectory=os.getcwd(),
+            fileMode=wx.FD_SAVE, changeCallback=self.OnSaveRulesFile)
+
+        colorTable = ColorTablesComboBox(
+            parent=parent,
+            size=globalvar.DIALOG_COMBOBOX_SIZE,
+            choices=utils.GetColorTables(),
+            name="colorTableChoice")
+        self.btnSet = wx.Button(
+            parent=parent,
+            id=wx.ID_ANY,
+            label=_("&Set"),
+            name='btnSet')
         self.btnSet.Bind(wx.EVT_BUTTON, self.OnSetTable)
         self.btnSet.Enable(False)
-        
+
         # layout
-        gridSizer =  wx.GridBagSizer(hgap = 2, vgap = 2)
-        
-        gridSizer.Add(item = wx.StaticText(parent, label = _("Load color table:")),
-                      pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = colorTable, pos = (0, 1))
-        gridSizer.Add(item = self.btnSet, pos = (0, 2), flag = wx.ALIGN_RIGHT)
-        gridSizer.Add(item = wx.StaticText(parent, label = _('Load color table from file:')),
-                      pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = self.loadRules, pos = (1, 1), span = (1, 2), flag = wx.EXPAND)
-        gridSizer.Add(item = wx.StaticText(parent, label = _('Save color table to file:')),
-                      pos = (2, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = self.saveRules, pos = (2, 1), span = (1, 2), flag = wx.EXPAND)
-        
+        gridSizer = wx.GridBagSizer(hgap=2, vgap=2)
+
+        gridSizer.Add(item=wx.StaticText(parent, label=_("Load color table:")),
+                      pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(item=colorTable, pos=(0, 1))
+        gridSizer.Add(item=self.btnSet, pos=(0, 2), flag=wx.ALIGN_RIGHT)
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent, label=_('Load color table from file:')), pos=(
+                1, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=self.loadRules, pos=(
+                1, 1), span=(
+                1, 2), flag=wx.EXPAND)
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent, label=_('Save color table to file:')), pos=(
+                2, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=self.saveRules, pos=(
+                2, 1), span=(
+                1, 2), flag=wx.EXPAND)
+
         gridSizer.AddGrowableCol(1)
-        inputSizer.Add(gridSizer, proportion = 1, flag = wx.EXPAND | wx.ALL,
-                       border = 5)
-        
+        inputSizer.Add(gridSizer, proportion=1, flag=wx.EXPAND | wx.ALL,
+                       border=5)
+
         if self.mapType == 'vector':
             # parent is collapsible pane
             parent.SetSizer(inputSizer)
-        
-        return inputSizer   
-         
+
+        return inputSizer
+
     def _createPreview(self, parent):
         """Create preview"""
         # initialize preview display
         self.InitDisplay()
-        self.preview = BufferedWindow(parent, id = wx.ID_ANY, size = (400, 300),
-                                      Map = self.Map)
+        self.preview = BufferedWindow(parent, id=wx.ID_ANY, size=(400, 300),
+                                      Map=self.Map)
         self.preview.EraseMap()
-        
+
     def _createButtons(self, parent):
         """Create buttons for leaving dialog"""
-        self.btnHelp    = wx.Button(parent, id = wx.ID_HELP)
-        self.btnCancel  = wx.Button(parent, id = wx.ID_CANCEL)
-        self.btnApply   = wx.Button(parent, id = wx.ID_APPLY) 
-        self.btnOK      = wx.Button(parent, id = wx.ID_OK)
-        self.btnDefault = wx.Button(parent, id = wx.ID_ANY,
-                                    label = _("Reload default table"))
-        
+        self.btnHelp = wx.Button(parent, id=wx.ID_HELP)
+        self.btnCancel = wx.Button(parent, id=wx.ID_CANCEL)
+        self.btnApply = wx.Button(parent, id=wx.ID_APPLY)
+        self.btnOK = wx.Button(parent, id=wx.ID_OK)
+        self.btnDefault = wx.Button(parent, id=wx.ID_ANY,
+                                    label=_("Reload default table"))
+
         self.btnOK.SetDefault()
         self.btnOK.Enable(False)
         self.btnApply.Enable(False)
         self.btnDefault.Enable(False)
-        
+
         # layout
         btnSizer = wx.BoxSizer(wx.HORIZONTAL)
-        btnSizer.Add(wx.Size(-1, -1), proportion = 1)
+        btnSizer.Add(wx.Size(-1, -1), proportion=1)
         btnSizer.Add(self.btnDefault,
-                     flag = wx.LEFT | wx.RIGHT, border = 5)
+                     flag=wx.LEFT | wx.RIGHT, border=5)
         btnSizer.Add(self.btnHelp,
-                     flag = wx.LEFT | wx.RIGHT, border = 5)
+                     flag=wx.LEFT | wx.RIGHT, border=5)
         btnSizer.Add(self.btnCancel,
-                     flag = wx.LEFT | wx.RIGHT, border = 5)
+                     flag=wx.LEFT | wx.RIGHT, border=5)
         btnSizer.Add(self.btnApply,
-                     flag = wx.LEFT | wx.RIGHT, border = 5)
+                     flag=wx.LEFT | wx.RIGHT, border=5)
         btnSizer.Add(self.btnOK,
-                     flag = wx.LEFT | wx.RIGHT, border = 5)
-        
+                     flag=wx.LEFT | wx.RIGHT, border=5)
+
         return btnSizer
-    
+
     def _createBody(self, parent):
         """Create dialog body consisting of rules and preview"""
-        bodySizer =  wx.GridBagSizer(hgap = 5, vgap = 5)
+        bodySizer = wx.GridBagSizer(hgap=5, vgap=5)
 
         row = 0
         # label with range
-        self.cr_label = wx.StaticText(parent, id = wx.ID_ANY)
-        bodySizer.Add(item = self.cr_label, pos = (row, 0), span = (1, 3),
-                      flag = wx.ALL, border = 5)
+        self.cr_label = wx.StaticText(parent, id=wx.ID_ANY)
+        bodySizer.Add(item=self.cr_label, pos=(row, 0), span=(1, 3),
+                      flag=wx.ALL, border=5)
 
         row += 1
         # color table
-        self.rulesPanel = RulesPanel(parent = parent, mapType = self.mapType,
-                                     attributeType = self.attributeType, properties = self.properties)
-        
-        bodySizer.Add(item = self.rulesPanel.mainPanel, pos = (row, 0),
-                      span = (1, 2), flag = wx.EXPAND)
+        self.rulesPanel = RulesPanel(
+            parent=parent,
+            mapType=self.mapType,
+            attributeType=self.attributeType,
+            properties=self.properties)
+
+        bodySizer.Add(item=self.rulesPanel.mainPanel, pos=(row, 0),
+                      span=(1, 2), flag=wx.EXPAND)
         # add two rules as default
         self.rulesPanel.AddRules(2)
-        
+
         # preview window
-        self._createPreview(parent = parent)
-        bodySizer.Add(item = self.preview, pos = (row, 2),
-                      flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER)
-        
+        self._createPreview(parent=parent)
+        bodySizer.Add(item=self.preview, pos=(row, 2),
+                      flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER)
+
         row += 1
         # add ckeck all and clear all
-        bodySizer.Add(item = self.rulesPanel.checkAll, flag = wx.ALIGN_CENTER_VERTICAL, 
-                      pos = (row, 0))
-        bodySizer.Add(item = self.rulesPanel.clearAll, pos = (row, 1))
-        
+        bodySizer.Add(
+            item=self.rulesPanel.checkAll,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                row,
+                0))
+        bodySizer.Add(item=self.rulesPanel.clearAll, pos=(row, 1))
+
         # preview button
-        self.btnPreview = wx.Button(parent, id = wx.ID_ANY,
-                                    label = _("Preview"))
-        bodySizer.Add(item = self.btnPreview, pos = (row, 2),
-                      flag = wx.ALIGN_RIGHT)
+        self.btnPreview = wx.Button(parent, id=wx.ID_ANY,
+                                    label=_("Preview"))
+        bodySizer.Add(item=self.btnPreview, pos=(row, 2),
+                      flag=wx.ALIGN_RIGHT)
         self.btnPreview.Enable(False)
-        self.btnPreview.SetToolTipString(_("Show preview of map "
-                                           "(current Map Display extent is used)."))
-        
-        row +=1
+        self.btnPreview.SetToolTipString(
+            _("Show preview of map " "(current Map Display extent is used)."))
+
+        row += 1
         # add rules button and spin to sizer
-        bodySizer.Add(item = self.rulesPanel.numRules, pos = (row, 0),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        bodySizer.Add(item = self.rulesPanel.btnAdd, pos = (row, 1))
-        
+        bodySizer.Add(item=self.rulesPanel.numRules, pos=(row, 0),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
+        bodySizer.Add(item=self.rulesPanel.btnAdd, pos=(row, 1))
+
         bodySizer.AddGrowableRow(1)
         bodySizer.AddGrowableCol(2)
 
-        return bodySizer    
-        
+        return bodySizer
+
     def InitDisplay(self):
         """Initialize preview display, set dimensions and region
         """
@@ -550,144 +607,158 @@
         """Window closed
         """
         self.OnCancel(event)
-          
+
     def OnApply(self, event):
         """Apply selected color table
-        
+
         :return: True on success otherwise False
         """
         ret = self.CreateColorTable()
         if not ret:
-            GMessage(parent = self, message = _("No valid color rules given."))
+            GMessage(parent=self, message=_("No valid color rules given."))
         else:
             # re-render preview and current map window
             self.OnPreview(None)
             display = self.layerTree.GetMapDisplay()
             if display and display.IsAutoRendered():
-                display.GetWindow().UpdateMap(render = True)
-        
+                display.GetWindow().UpdateMap(render=True)
+
         return ret
 
     def OnOK(self, event):
         """Apply selected color table and close the dialog"""
         if self.OnApply(event):
             self.OnCancel(event)
-    
+
     def OnCancel(self, event):
         """Do not apply any changes, remove associated
             rendered images and close the dialog"""
         self.Map.Clean()
         self.Destroy()
-        
+
     def OnSetTable(self, event):
         """Load pre-defined color table"""
         ct = self.FindWindowByName("colorTableChoice").GetValue()
         # save original color table
-        ctOriginal = RunCommand('r.colors.out', read = True, map = self.inmap, rules = '-')
+        ctOriginal = RunCommand(
+            'r.colors.out',
+            read=True,
+            map=self.inmap,
+            rules='-')
         # set new color table
-        ret, err = RunCommand('r.colors', map = self.inmap, color = ct, getErrorMsg = True)
+        ret, err = RunCommand('r.colors', map=self.inmap,
+                              color=ct, getErrorMsg=True)
         if ret != 0:
-            GError(err, parent = self)
+            GError(err, parent=self)
             return
-        ctNew = RunCommand('r.colors.out', read = True, map = self.inmap, rules = '-')
+        ctNew = RunCommand(
+            'r.colors.out',
+            read=True,
+            map=self.inmap,
+            rules='-')
         # restore original table
-        RunCommand('r.colors', map = self.inmap, rules = '-', stdin = ctOriginal)
+        RunCommand('r.colors', map=self.inmap, rules='-', stdin=ctOriginal)
         # load color table
         self.rulesPanel.Clear()
-        self.ReadColorTable(ctable = ctNew)
+        self.ReadColorTable(ctable=ctNew)
 
     def OnSaveRulesFile(self, event):
         """Save color table to file"""
         path = event.GetString()
         if not path:
             return
-        
+
         if os.path.exists(path):
-            dlgOw = wx.MessageDialog(parent,
-                                     message = _("File <%s> already already exists. "
-                                                 "Do you want to overwrite it?") % path,
-                                     caption = _("Overwrite?"),
-                                     style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+            dlgOw = wx.MessageDialog(
+                parent,
+                message=_(
+                    "File <%s> already already exists. "
+                    "Do you want to overwrite it?") %
+                path,
+                caption=_("Overwrite?"),
+                style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
             if dlgOw.ShowModal() != wx.ID_YES:
                 return
-        
-        rulestxt = ''   
+
+        rulestxt = ''
         for rule in self.rulesPanel.ruleslines.itervalues():
             if 'value' not in rule:
                 continue
             rulestxt += rule['value'] + ' ' + rule['color'] + '\n'
         if not rulestxt:
-            GMessage(message = _("Nothing to save."),
-                     parent = self)
+            GMessage(message=_("Nothing to save."),
+                     parent=self)
             return
-        
+
         fd = open(path, 'w')
         fd.write(rulestxt)
-        fd.close()            
-         
+        fd.close()
+
     def OnLoadRulesFile(self, event):
         """Load color table from file"""
         path = event.GetString()
         if not os.path.exists(path):
             return
-        
+
         self.rulesPanel.Clear()
-        
+
         fd = open(path, 'r')
-        self.ReadColorTable(ctable = fd.read())
+        self.ReadColorTable(ctable=fd.read())
         fd.close()
-        
+
     def ReadColorTable(self, ctable):
         """Read color table
-        
+
         :param table: color table in format coming from r.colors.out"""
-        
+
         rulesNumber = len(ctable.splitlines())
         self.rulesPanel.AddRules(rulesNumber)
-        
+
         minim = maxim = count = 0
         for line in ctable.splitlines():
             try:
                 value, color = map(lambda x: x.strip(), line.split(' '))
             except ValueError:
-                GMessage(parent = self, message = _("Invalid color table format"))
+                GMessage(parent=self, message=_("Invalid color table format"))
                 self.rulesPanel.Clear()
                 return
-            
+
             self.rulesPanel.ruleslines[count]['value'] = value
             self.rulesPanel.ruleslines[count]['color'] = color
-            self.rulesPanel.mainPanel.FindWindowById(count + 1000).SetValue(value)
+            self.rulesPanel.mainPanel.FindWindowById(
+                count + 1000).SetValue(value)
             rgb = list()
             for c in color.split(':'):
                 rgb.append(int(c))
-            self.rulesPanel.mainPanel.FindWindowById(count + 2000).SetColour(rgb)
+            self.rulesPanel.mainPanel.FindWindowById(
+                count + 2000).SetColour(rgb)
             # range
             try:
                 if float(value) < minim:
                     minim = float(value)
                 if float(value) > maxim:
                     maxim = float(value)
-            except ValueError: # nv, default
+            except ValueError:  # nv, default
                 pass
             count += 1
-        
+
         if self.mapType == 'vector':
             # raster min, max is known from r.info
             self.properties['min'], self.properties['max'] = minim, maxim
             self.SetRangeLabel()
-            
-        self.OnPreview(tmp = True)  
-         
+
+        self.OnPreview(tmp=True)
+
     def OnLoadDefaultTable(self, event):
         """Load internal color table"""
         self.LoadTable()
-        
-    def LoadTable(self, mapType = 'raster'):
+
+    def LoadTable(self, mapType='raster'):
         """Load current color table (using `r(v).colors.out`)
-        
+
         :param mapType: map type (raster or vector)"""
         self.rulesPanel.Clear()
-        
+
         if mapType == 'raster':
             cmd = ['r.colors.out',
                    'read=True',
@@ -698,90 +769,97 @@
                    'read=True',
                    'map=%s' % self.inmap,
                    'rules=-']
-            
-            if self.properties['sourceColumn'] and self.properties['sourceColumn'] != 'cat':
+
+            if self.properties['sourceColumn'] and self.properties[
+                    'sourceColumn'] != 'cat':
                 cmd.append('column=%s' % self.properties['sourceColumn'])
-            
+
         cmd = cmdlist_to_tuple(cmd)
-        
+
         if self.inmap:
             ctable = RunCommand(cmd[0], **cmd[1])
         else:
             self.OnPreview()
             return
-        
-        self.ReadColorTable(ctable = ctable)     
-    
-    def CreateColorTable(self, tmp = False):
+
+        self.ReadColorTable(ctable=ctable)
+
+    def CreateColorTable(self, tmp=False):
         """Creates color table
 
         :return: True on success
         :return: False on failure
         """
         rulestxt = ''
-        
+
         for rule in self.rulesPanel.ruleslines.itervalues():
-            if 'value' not in rule: # skip empty rules
+            if 'value' not in rule:  # skip empty rules
                 continue
-            
+
             if rule['value'] not in ('nv', 'default') and \
                     rule['value'][-1] != '%' and \
                     not self._IsNumber(rule['value']):
-                GError(_("Invalid rule value '%s'. Unable to apply color table.") % rule['value'],
-                       parent = self)
+                GError(
+                    _("Invalid rule value '%s'. Unable to apply color table.") %
+                    rule['value'], parent=self)
                 return False
-            
+
             rulestxt += rule['value'] + ' ' + rule['color'] + '\n'
-           
+
         if not rulestxt:
             return False
-        
+
         gtemp = utils.GetTempfile()
         output = open(gtemp, "w")
         try:
             output.write(rulestxt)
         finally:
             output.close()
-        
-        cmd = ['%s.colors' % self.mapType[0], #r.colors/v.colors
-                'map=%s' % self.inmap,
-                'rules=%s' % gtemp]
+
+        cmd = ['%s.colors' % self.mapType[0],  # r.colors/v.colors
+               'map=%s' % self.inmap,
+               'rules=%s' % gtemp]
         if self.mapType == 'vector' and self.properties['sourceColumn'] \
                 and self.properties['sourceColumn'] != 'cat':
             cmd.append('column=%s' % self.properties['sourceColumn'])
-        
+
         cmd = cmdlist_to_tuple(cmd)
-        ret = RunCommand(cmd[0], **cmd[1])               
+        ret = RunCommand(cmd[0], **cmd[1])
         if ret != 0:
             return False
-        
+
         return True
-    
+
     def DoPreview(self, ltype, cmdlist):
         """Update preview (based on computational region)"""
-        
+
         if not self.layer:
-            self.layer = self.Map.AddLayer(ltype = ltype, name = 'preview', command = cmdlist,
-                                           active = True, hidden = False, opacity = 1.0,
-                                           render = False) 
+            self.layer = self.Map.AddLayer(
+                ltype=ltype,
+                name='preview',
+                command=cmdlist,
+                active=True,
+                hidden=False,
+                opacity=1.0,
+                render=False)
         else:
             self.layer.SetCmd(cmdlist)
-        
+
         # apply new color table and display preview
-        self.CreateColorTable(tmp = True)
+        self.CreateColorTable(tmp=True)
         self.preview.UpdatePreview()
-        
+
     def RunHelp(self, cmd):
         """Show GRASS manual page"""
         RunCommand('g.manual',
-                   quiet = True,
-                   parent = self,
-                   entry = cmd)
+                   quiet=True,
+                   parent=self,
+                   entry=cmd)
 
     def SetMap(self, name):
         """Set map name and update dialog"""
         self.selectionInput.SetValue(name)
-        
+
     def _IsNumber(self, s):
         """Check if 's' is a number"""
         try:
@@ -789,89 +867,91 @@
             return True
         except ValueError:
             return False
-        
+
+
 class RasterColorTable(ColorTable):
+
     def __init__(self, parent, **kwargs):
         """Dialog for interactively entering color rules for raster maps"""
 
         self.mapType = 'raster'
-        self.attributeType = 'color' 
-        self.colorTable = True 
+        self.attributeType = 'color'
+        self.colorTable = True
         # raster properties
         self.properties = {
             # min cat in raster map
-            'min' : None,
+            'min': None,
             # max cat in raster map
-            'max' : None,
-            }        
-        
-        ColorTable.__init__(self, parent,
-                            title = _('Create new color table for raster map'), **kwargs)
-        
+            'max': None,
+        }
+
+        ColorTable.__init__(self, parent, title=_(
+            'Create new color table for raster map'), **kwargs)
+
         self._initLayer()
         self.Map.GetRenderMgr().renderDone.connect(self._restoreColorTable)
-            
-        # self.SetMinSize(self.GetSize()) 
+
+        # self.SetMinSize(self.GetSize())
         self.SetMinSize((650, 700))
-                
+
     def _doLayout(self):
         """Do main layout"""
         sizer = wx.BoxSizer(wx.VERTICAL)
         #
         # map selection
         #
-        mapSelection = self._createMapSelection(parent = self.panel)
-        sizer.Add(item = mapSelection, proportion = 0,
-                  flag = wx.ALL | wx.EXPAND, border = 5)
+        mapSelection = self._createMapSelection(parent=self.panel)
+        sizer.Add(item=mapSelection, proportion=0,
+                  flag=wx.ALL | wx.EXPAND, border=5)
         #
         # manage extern tables
         #
-        fileSelection = self._createFileSelection(parent = self.panel)
-        sizer.Add(item = fileSelection, proportion = 0,
-                  flag = wx.LEFT | wx.RIGHT | wx.EXPAND, border = 5)
+        fileSelection = self._createFileSelection(parent=self.panel)
+        sizer.Add(item=fileSelection, proportion=0,
+                  flag=wx.LEFT | wx.RIGHT | wx.EXPAND, border=5)
         #
         # body & preview
         #
-        bodySizer = self._createBody(parent = self.panel)
-        sizer.Add(item = bodySizer, proportion = 1,
-                  flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
+        bodySizer = self._createBody(parent=self.panel)
+        sizer.Add(item=bodySizer, proportion=1,
+                  flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=5)
         #
         # buttons
         #
-        btnSizer = self._createButtons(parent = self.panel)
-        sizer.Add(item = wx.StaticLine(parent = self.panel, id = wx.ID_ANY,
-                                       style = wx.LI_HORIZONTAL), proportion = 0,
-                                       flag = wx.EXPAND | wx.ALL, border = 5) 
-        
-        sizer.Add(item = btnSizer, proportion = 0,
-                  flag = wx.ALL | wx.ALIGN_RIGHT, border = 5)
-        
+        btnSizer = self._createButtons(parent=self.panel)
+        sizer.Add(item=wx.StaticLine(parent=self.panel, id=wx.ID_ANY,
+                                     style=wx.LI_HORIZONTAL), proportion=0,
+                  flag=wx.EXPAND | wx.ALL, border=5)
+
+        sizer.Add(item=btnSizer, proportion=0,
+                  flag=wx.ALL | wx.ALIGN_RIGHT, border=5)
+
         self.panel.SetSizer(sizer)
         sizer.Layout()
         sizer.Fit(self.panel)
         self.Layout()
-    
+
     def OnSelectionInput(self, event):
         """Raster map selected"""
         if event:
             self.inmap = event.GetString()
-        
+
         self.loadRules.SetValue('')
         self.saveRules.SetValue('')
-        
+
         if self.inmap:
-            if not grass.find_file(name = self.inmap, element = 'cell')['file']:
+            if not grass.find_file(name=self.inmap, element='cell')['file']:
                 self.inmap = None
-        
+
         if not self.inmap:
             for btn in (self.btnPreview, self.btnOK,
                         self.btnApply, self.btnDefault, self.btnSet):
                 btn.Enable(False)
             self.LoadTable()
             return
-        
-        info = grass.raster_info(map = self.inmap)
-        
+
+        info = grass.raster_info(map=self.inmap)
+
         if info:
             self.properties['min'] = info['min']
             self.properties['max'] = info['max']
@@ -883,51 +963,56 @@
                         self.btnApply, self.btnDefault, self.btnSet):
                 btn.Enable(False)
             self.preview.EraseMap()
-            self.cr_label.SetLabel(_('Enter raster category values or percents'))
+            self.cr_label.SetLabel(
+                _('Enter raster category values or percents'))
             return
-        
+
         if info['datatype'] == 'CELL':
             mapRange = _('range')
         else:
             mapRange = _('fp range')
-        self.cr_label.SetLabel(_('Enter raster category values or percents (%(range)s = %(min)d-%(max)d)') %
-                                 { 'range' : mapRange,
-                                   'min' : self.properties['min'],
-                                   'max' : self.properties['max'] })                       
-        
+        self.cr_label.SetLabel(
+            _('Enter raster category values or percents (%(range)s = %(min)d-%(max)d)') %
+            {
+                'range': mapRange,
+                'min': self.properties['min'],
+                'max': self.properties['max']})
+
         for btn in (self.btnPreview, self.btnOK,
                     self.btnApply, self.btnDefault, self.btnSet):
             btn.Enable()
-        
-    def OnPreview(self, tmp = True):
+
+    def OnPreview(self, tmp=True):
         """Update preview (based on computational region)"""
         if not self.inmap:
             self.preview.EraseMap()
             return
-        
+
         cmdlist = ['d.rast',
                    'map=%s' % self.inmap]
         ltype = 'raster'
-        
+
         # find existing color table and copy to temp file
         try:
             name, mapset = self.inmap.split('@')
         except ValueError:
             name = self.inmap
-            mapset = grass.find_file(self.inmap, element = 'cell')['mapset']
+            mapset = grass.find_file(self.inmap, element='cell')['mapset']
             if not mapset:
                 return
         self._tmp = tmp
         self._old_colrtable = None
         if mapset == grass.gisenv()['MAPSET']:
-            self._old_colrtable = grass.find_file(name = name, element = 'colr')['file']
+            self._old_colrtable = grass.find_file(
+                name=name, element='colr')['file']
         else:
-            self._old_colrtable = grass.find_file(name = name, element = 'colr2/' + mapset)['file']
-        
+            self._old_colrtable = grass.find_file(
+                name=name, element='colr2/' + mapset)['file']
+
         if self._old_colrtable:
             self._colrtemp = utils.GetTempfile()
             shutil.copyfile(self._old_colrtable, self._colrtemp)
-            
+
         ColorTable.DoPreview(self, ltype, cmdlist)
 
     def _restoreColorTable(self):
@@ -939,22 +1024,24 @@
                 del self._colrtemp, self._old_colrtable
             else:
                 RunCommand('r.colors',
-                           parent = self,
-                           flags = 'r',
-                           map = self.inmap)
+                           parent=self,
+                           flags='r',
+                           map=self.inmap)
             del self._tmp
-            
+
     def OnHelp(self, event):
         """Show GRASS manual page"""
         cmd = 'r.colors'
-        ColorTable.RunHelp(self, cmd = cmd)
-                     
+        ColorTable.RunHelp(self, cmd=cmd)
+
+
 class VectorColorTable(ColorTable):
+
     def __init__(self, parent, attributeType, **kwargs):
         """Dialog for interactively entering color rules for vector maps"""
         # dialog attributes
         self.mapType = 'vector'
-        self.attributeType = attributeType # color, size, width
+        self.attributeType = attributeType  # color, size, width
         # in version 7 v.colors used, otherwise color column only
         self.version7 = int(grass.version()['version'].split('.')[0]) >= 7
         self.colorTable = False
@@ -962,28 +1049,38 @@
         # vector properties
         self.properties = {
             # vector layer for attribute table to use for setting color
-            'layer' : 1, 
-            # vector attribute table used for setting color         
-            'table' : '',
+            'layer': 1,
+            # vector attribute table used for setting color
+            'table': '',
             # vector attribute column for assigning colors
-            'sourceColumn' : '', 
+            'sourceColumn': '',
             # vector attribute column to use for loading colors
-            'loadColumn' : '',
+            'loadColumn': '',
             # vector attribute column to use for storing colors
-            'storeColumn' : '',    
-            # vector attribute column for temporary storing colors   
-            'tmpColumn' : 'tmp_0',
+            'storeColumn': '',
+            # vector attribute column for temporary storing colors
+            'tmpColumn': 'tmp_0',
             # min value of attribute column/vector color table
             'min': None,
-            # max value of attribute column/vector color table            
+            # max value of attribute column/vector color table
             'max': None
-            }     
-        self.columnsProp = {'color': {'name': 'GRASSRGB', 'type1': 'varchar(11)', 'type2': ['character']},
-                            'size' : {'name': 'GRASSSIZE', 'type1': 'integer', 'type2': ['integer']},
-                            'width': {'name': 'GRASSWIDTH', 'type1': 'integer', 'type2': ['integer']}}
-        ColorTable.__init__(self, parent = parent,
-                            title = _('Create new color rules for vector map'), **kwargs)
-        
+        }
+        self.columnsProp = {
+            'color': {
+                'name': 'GRASSRGB',
+                'type1': 'varchar(11)',
+                'type2': ['character']},
+            'size': {
+                'name': 'GRASSSIZE',
+                'type1': 'integer',
+                'type2': ['integer']},
+            'width': {
+                'name': 'GRASSWIDTH',
+                'type1': 'integer',
+                'type2': ['integer']}}
+        ColorTable.__init__(self, parent=parent, title=_(
+            'Create new color rules for vector map'), **kwargs)
+
         # additional bindings for vector color management
         self.Bind(wx.EVT_COMBOBOX, self.OnLayerSelection, self.layerSelect)
 
@@ -991,150 +1088,164 @@
         self.fromColumn.Bind(wx.EVT_TEXT, self.OnFromColSelection)
         self.toColumn.Bind(wx.EVT_TEXT, self.OnToColSelection)
         self.Bind(wx.EVT_BUTTON, self.OnAddColumn, self.addColumn)
-        
+
         self._initLayer()
         if self.colorTable:
-            self.cr_label.SetLabel(_("Enter vector attribute values or percents:"))
+            self.cr_label.SetLabel(
+                _("Enter vector attribute values or percents:"))
         else:
             self.cr_label.SetLabel(_("Enter vector attribute values:"))
-        
-        #self.SetMinSize(self.GetSize()) 
+
+        # self.SetMinSize(self.GetSize())
         self.SetMinSize((650, 700))
-        
+
         self.CentreOnScreen()
         self.Show()
-    
+
     def _createVectorAttrb(self, parent):
         """Create part of dialog with layer/column selection"""
-        inputBox = wx.StaticBox(parent = parent, id = wx.ID_ANY,
-                                label = " %s " % _("Select vector columns"))
-        cb_vl_label = wx.StaticText(parent, id = wx.ID_ANY,
-                                             label = _('Layer:'))
-        cb_vc_label = wx.StaticText(parent, id = wx.ID_ANY,
-                                         label = _('Attribute column:'))
-                                        
+        inputBox = wx.StaticBox(parent=parent, id=wx.ID_ANY,
+                                label=" %s " % _("Select vector columns"))
+        cb_vl_label = wx.StaticText(parent, id=wx.ID_ANY,
+                                    label=_('Layer:'))
+        cb_vc_label = wx.StaticText(parent, id=wx.ID_ANY,
+                                    label=_('Attribute column:'))
+
         if self.attributeType == 'color':
-            labels =  [_("Load color from column:"), _("Save color to column:")]
+            labels = [_("Load color from column:"), _("Save color to column:")]
         elif self.attributeType == 'size':
-            labels =  [_("Load size from column:"), _("Save size to column:")]
+            labels = [_("Load size from column:"), _("Save size to column:")]
         elif self.attributeType == 'width':
-            labels =  [_("Load width from column:"), _("Save width to column:")]
-            
+            labels = [_("Load width from column:"), _("Save width to column:")]
+
         if self.version7 and self.attributeType == 'color':
-            self.useColumn = wx.CheckBox(parent, id = wx.ID_ANY,
-                                  label = _("Use color column instead of color table:"))
+            self.useColumn = wx.CheckBox(
+                parent, id=wx.ID_ANY,
+                label=_("Use color column instead of color table:"))
             self.useColumn.Bind(wx.EVT_CHECKBOX, self.OnCheckColumn)
-        
-        fromColumnLabel = wx.StaticText(parent, id = wx.ID_ANY,
-                                            label = labels[0])
-        toColumnLabel = wx.StaticText(parent, id = wx.ID_ANY,
-                                            label = labels[1])
-                                                
-        self.rgb_range_label = wx.StaticText(parent, id = wx.ID_ANY)
+
+        fromColumnLabel = wx.StaticText(parent, id=wx.ID_ANY,
+                                        label=labels[0])
+        toColumnLabel = wx.StaticText(parent, id=wx.ID_ANY,
+                                      label=labels[1])
+
+        self.rgb_range_label = wx.StaticText(parent, id=wx.ID_ANY)
         self.layerSelect = LayerSelect(parent)
         self.sourceColumn = ColumnSelect(parent)
         self.fromColumn = ColumnSelect(parent)
         self.toColumn = ColumnSelect(parent)
-        self.addColumn = wx.Button(parent, id = wx.ID_ANY,
-                                             label = _('Add column'))
-        self.addColumn.SetToolTipString(_("Add GRASSRGB column to current attribute table."))
-        
+        self.addColumn = wx.Button(parent, id=wx.ID_ANY,
+                                   label=_('Add column'))
+        self.addColumn.SetToolTipString(
+            _("Add GRASSRGB column to current attribute table."))
+
         # layout
         inputSizer = wx.StaticBoxSizer(inputBox, wx.VERTICAL)
-        vSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
+        vSizer = wx.GridBagSizer(hgap=5, vgap=5)
         row = 0
-        vSizer.Add(cb_vl_label, pos = (row, 0),
-                   flag = wx.ALIGN_CENTER_VERTICAL)
-        vSizer.Add(self.layerSelect,  pos = (row, 1),
-                   flag = wx.ALIGN_CENTER_VERTICAL)
+        vSizer.Add(cb_vl_label, pos=(row, 0),
+                   flag=wx.ALIGN_CENTER_VERTICAL)
+        vSizer.Add(self.layerSelect, pos=(row, 1),
+                   flag=wx.ALIGN_CENTER_VERTICAL)
         row += 1
-        vSizer.Add(cb_vc_label, pos = (row, 0),
-                   flag = wx.ALIGN_CENTER_VERTICAL)
-        vSizer.Add(self.sourceColumn, pos = (row, 1),
-                   flag = wx.ALIGN_CENTER_VERTICAL)
-        vSizer.Add(self.rgb_range_label, pos = (row, 2),
-                   flag = wx.ALIGN_CENTER_VERTICAL)
-        row += 1   
+        vSizer.Add(cb_vc_label, pos=(row, 0),
+                   flag=wx.ALIGN_CENTER_VERTICAL)
+        vSizer.Add(self.sourceColumn, pos=(row, 1),
+                   flag=wx.ALIGN_CENTER_VERTICAL)
+        vSizer.Add(self.rgb_range_label, pos=(row, 2),
+                   flag=wx.ALIGN_CENTER_VERTICAL)
+        row += 1
         if self.version7 and self.attributeType == 'color':
-            vSizer.Add(self.useColumn, pos = (row, 0), span = (1, 2),
-                       flag = wx.ALIGN_CENTER_VERTICAL)
+            vSizer.Add(self.useColumn, pos=(row, 0), span=(1, 2),
+                       flag=wx.ALIGN_CENTER_VERTICAL)
             row += 1
-            
-        vSizer.Add(fromColumnLabel, pos = (row, 0),
-                  flag = wx.ALIGN_CENTER_VERTICAL)
-        vSizer.Add(self.fromColumn, pos = (row, 1),
-                   flag = wx.ALIGN_CENTER_VERTICAL)
+
+        vSizer.Add(fromColumnLabel, pos=(row, 0),
+                   flag=wx.ALIGN_CENTER_VERTICAL)
+        vSizer.Add(self.fromColumn, pos=(row, 1),
+                   flag=wx.ALIGN_CENTER_VERTICAL)
         row += 1
-        vSizer.Add(toColumnLabel, pos = (row, 0),
-                  flag = wx.ALIGN_CENTER_VERTICAL)
-        vSizer.Add(self.toColumn, pos = (row, 1),
-                   flag = wx.ALIGN_CENTER_VERTICAL)
-        vSizer.Add(self.addColumn, pos = (row, 2),
-                   flag = wx.ALIGN_CENTER_VERTICAL)
-        inputSizer.Add(item = vSizer,
-                       flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND, border = 5)
-        self.colorColumnSizer = vSizer        
-        return inputSizer 
-       
+        vSizer.Add(toColumnLabel, pos=(row, 0),
+                   flag=wx.ALIGN_CENTER_VERTICAL)
+        vSizer.Add(self.toColumn, pos=(row, 1),
+                   flag=wx.ALIGN_CENTER_VERTICAL)
+        vSizer.Add(self.addColumn, pos=(row, 2),
+                   flag=wx.ALIGN_CENTER_VERTICAL)
+        inputSizer.Add(
+            item=vSizer,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND,
+            border=5)
+        self.colorColumnSizer = vSizer
+        return inputSizer
+
     def _doLayout(self):
         """Do main layout"""
-        scrollPanel = scrolled.ScrolledPanel(parent = self.panel, id = wx.ID_ANY,
-                                             style = wx.TAB_TRAVERSAL)
+        scrollPanel = scrolled.ScrolledPanel(parent=self.panel, id=wx.ID_ANY,
+                                             style=wx.TAB_TRAVERSAL)
         scrollPanel.SetupScrolling()
         sizer = wx.BoxSizer(wx.VERTICAL)
         #
         # map selection
         #
-        mapSelection = self._createMapSelection(parent = scrollPanel)
-        sizer.Add(item = mapSelection, proportion = 0,
-                  flag = wx.ALL | wx.EXPAND, border = 5)
+        mapSelection = self._createMapSelection(parent=scrollPanel)
+        sizer.Add(item=mapSelection, proportion=0,
+                  flag=wx.ALL | wx.EXPAND, border=5)
         #
         # manage extern tables
         #
         if self.version7 and self.attributeType == 'color':
-            self.cp = wx.CollapsiblePane(scrollPanel, label = _("Import or export color table"),
-                                         winid = wx.ID_ANY,
-                                        style = wx.CP_DEFAULT_STYLE|wx.CP_NO_TLW_RESIZE)
-            self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnPaneChanged, self.cp)
-        
-            self._createFileSelection(parent = self.cp.GetPane())
-            sizer.Add(item = self.cp, proportion = 0,
-                      flag = wx.ALL | wx.EXPAND, border = 5)
+            self.cp = wx.CollapsiblePane(
+                scrollPanel,
+                label=_("Import or export color table"),
+                winid=wx.ID_ANY,
+                style=wx.CP_DEFAULT_STYLE | wx.CP_NO_TLW_RESIZE)
+            self.Bind(
+                wx.EVT_COLLAPSIBLEPANE_CHANGED,
+                self.OnPaneChanged,
+                self.cp)
+
+            self._createFileSelection(parent=self.cp.GetPane())
+            sizer.Add(item=self.cp, proportion=0,
+                      flag=wx.ALL | wx.EXPAND, border=5)
         #
         # set vector attributes
         #
-        vectorAttrb = self._createVectorAttrb(parent = scrollPanel)
-        sizer.Add(item = vectorAttrb, proportion = 0,
-                  flag = wx.ALL | wx.EXPAND, border = 5)
+        vectorAttrb = self._createVectorAttrb(parent=scrollPanel)
+        sizer.Add(item=vectorAttrb, proportion=0,
+                  flag=wx.ALL | wx.EXPAND, border=5)
         #
         # body & preview
         #
-        bodySizer = self._createBody(parent = scrollPanel)
-        sizer.Add(item = bodySizer, proportion = 1,
-                  flag = wx.ALL | wx.EXPAND, border = 5)
-        
+        bodySizer = self._createBody(parent=scrollPanel)
+        sizer.Add(item=bodySizer, proportion=1,
+                  flag=wx.ALL | wx.EXPAND, border=5)
+
         scrollPanel.SetSizer(sizer)
-        scrollPanel.Fit()        
-        
+        scrollPanel.Fit()
+
         #
         # buttons
         #
         btnSizer = self._createButtons(self.panel)
-        
+
         mainsizer = wx.BoxSizer(wx.VERTICAL)
-        mainsizer.Add(scrollPanel, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
-        mainsizer.Add(item = wx.StaticLine(parent = self.panel, id = wx.ID_ANY,
-                                       style = wx.LI_HORIZONTAL), proportion = 0,
-                                       flag = wx.EXPAND | wx.ALL, border = 5) 
-        mainsizer.Add(item = btnSizer, proportion = 0,
-                  flag = wx.ALL | wx.ALIGN_RIGHT | wx.EXPAND, border = 5)
-        
+        mainsizer.Add(
+            scrollPanel,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        mainsizer.Add(item=wx.StaticLine(parent=self.panel, id=wx.ID_ANY,
+                                         style=wx.LI_HORIZONTAL), proportion=0,
+                      flag=wx.EXPAND | wx.ALL, border=5)
+        mainsizer.Add(item=btnSizer, proportion=0,
+                      flag=wx.ALL | wx.ALIGN_RIGHT | wx.EXPAND, border=5)
+
         self.panel.SetSizer(mainsizer)
         mainsizer.Layout()
-        mainsizer.Fit(self.panel)     
+        mainsizer.Fit(self.panel)
         self.Layout()
-        
-    def OnPaneChanged(self, event = None):
+
+    def OnPaneChanged(self, event=None):
         # redo the layout
         self.Layout()
         # and also change the labels
@@ -1142,29 +1253,32 @@
             self.cp.SetLabel('')
         else:
             self.cp.SetLabel(_("Import or export color table"))
-        
+
     def CheckMapset(self):
         """Check if current vector is in current mapset"""
-        if grass.find_file(name = self.inmap,
-                           element = 'vector')['mapset'] == grass.gisenv()['MAPSET']:
+        if grass.find_file(name=self.inmap, element='vector')[
+                'mapset'] == grass.gisenv()['MAPSET']:
             return True
         else:
-            return False 
-         
+            return False
+
     def NoConnection(self, vectorName):
-        dlg = wx.MessageDialog(parent = self,
-                                message = _("Database connection for vector map <%s> "
-                                            "is not defined in DB file.  Do you want to create and "
-                                            "connect new attribute table?") % vectorName,
-                                caption = _("No database connection defined"),
-                                style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
+        dlg = wx.MessageDialog(
+            parent=self,
+            message=_(
+                "Database connection for vector map <%s> "
+                "is not defined in DB file.  Do you want to create and "
+                "connect new attribute table?") %
+            vectorName,
+            caption=_("No database connection defined"),
+            style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
         if dlg.ShowModal() == wx.ID_YES:
             dlg.Destroy()
-            GUI(parent = self).ParseCommand(['v.db.addtable', 'map=' + self.inmap], 
-                                            completed = (self.CreateAttrTable, self.inmap, ''))
+            GUI(parent=self).ParseCommand(['v.db.addtable', 'map=' + self.inmap],
+                                          completed=(self.CreateAttrTable, self.inmap, ''))
         else:
             dlg.Destroy()
-  
+
     def OnCheckColumn(self, event):
         """Use color column instead of color table"""
         if self.useColumn.GetValue():
@@ -1173,7 +1287,7 @@
             self.fromColumn.Enable(True)
             self.toColumn.Enable(True)
             self.colorTable = False
-            
+
             if self.properties['loadColumn']:
                 self.LoadTable()
             else:
@@ -1185,12 +1299,12 @@
             self.toColumn.Enable(False)
             self.colorTable = True
             self.LoadTable()
-            
+
     def EnableVectorAttributes(self, enable):
         """Enable/disable part of dialog connected with db"""
         for child in self.colorColumnSizer.GetChildren():
             child.GetWindow().Enable(enable)
-    
+
     def DisableClearAll(self):
         """Enable, disable the whole dialog"""
         self.rulesPanel.Clear()
@@ -1199,7 +1313,7 @@
         self.btnOK.Enable(False)
         self.btnApply.Enable(False)
         self.preview.EraseMap()
-        
+
     def OnSelectionInput(self, event):
         """Vector map selected"""
         if event:
@@ -1207,51 +1321,54 @@
                 # switch to another map -> delete temporary column
                 self.DeleteTemporaryColumn()
             self.inmap = event.GetString()
-            
-        if self.version7 and self.attributeType == 'color': 
+
+        if self.version7 and self.attributeType == 'color':
             self.loadRules.SetValue('')
             self.saveRules.SetValue('')
-        
+
         if self.inmap:
-            if not grass.find_file(name = self.inmap, element = 'vector')['file']:
+            if not grass.find_file(name=self.inmap, element='vector')['file']:
                 self.inmap = None
-        
+
         self.UpdateDialog()
-       
+
     def UpdateDialog(self):
         """Update dialog after map selection"""
-        
+
         if not self.inmap:
             self.DisableClearAll()
             return
-        
+
         if not self.CheckMapset():
             # v.colors doesn't need the map to be in current mapset
             if not (self.version7 and self.attributeType == 'color'):
-                message = _("Selected map <%(map)s> is not in current mapset <%(mapset)s>. "
-                            "Attribute table cannot be edited.") % \
-                            { 'map' : self.inmap,
-                              'mapset' : grass.gisenv()['MAPSET'] }
-                wx.CallAfter(GMessage, parent = self, message = message)
+                message = _(
+                    "Selected map <%(map)s> is not in current mapset <%(mapset)s>. "
+                    "Attribute table cannot be edited.") % {
+                    'map': self.inmap,
+                    'mapset': grass.gisenv()['MAPSET']}
+                wx.CallAfter(GMessage, parent=self, message=message)
                 self.DisableClearAll()
                 return
-                
+
         # check for db connection
         self.dbInfo = VectorDBInfo(self.inmap)
         enable = True
 
-        if not len(self.dbInfo.layers): # no connection
-            if not (self.version7 and self.attributeType == 'color'): # otherwise it doesn't matter
+        if not len(self.dbInfo.layers):  # no connection
+            if not (self.version7 and self.attributeType ==
+                    'color'):  # otherwise it doesn't matter
                 wx.CallAfter(self.NoConnection, self.inmap)
                 enable = False
-            for combo in (self.layerSelect, self.sourceColumn, self.fromColumn, self.toColumn):
+            for combo in (self.layerSelect, self.sourceColumn,
+                          self.fromColumn, self.toColumn):
                 combo.SetValue("")
                 combo.Clear()
             for prop in ('sourceColumn', 'loadColumn', 'storeColumn'):
                 self.properties[prop] = ''
             self.EnableVectorAttributes(False)
-        else: # db connection exist
-        # initialize layer selection combobox
+        else:  # db connection exist
+            # initialize layer selection combobox
             self.EnableVectorAttributes(True)
             self.layerSelect.InsertLayers(self.inmap)
             # initialize attribute table for layer=1
@@ -1259,85 +1376,95 @@
             self.layerSelect.SetStringSelection(self.properties['layer'])
             layer = int(self.properties['layer'])
             self.properties['table'] = self.dbInfo.layers[layer]['table']
-            
+
             if self.attributeType == 'color':
-                self.AddTemporaryColumn(type = 'varchar(11)')
+                self.AddTemporaryColumn(type='varchar(11)')
             else:
-                self.AddTemporaryColumn(type = 'integer')
-            
-            # initialize column selection comboboxes 
-            
-            self.OnLayerSelection(event = None)
+                self.AddTemporaryColumn(type='integer')
 
+            # initialize column selection comboboxes
+
+            self.OnLayerSelection(event=None)
+
         if self.version7 and self.attributeType == 'color':
             self.useColumn.SetValue(False)
-            self.OnCheckColumn(event = None) 
+            self.OnCheckColumn(event=None)
             self.useColumn.Enable(self.CheckMapset())
-                    
+
         self.LoadTable()
-            
+
         self.btnPreview.Enable(enable)
         self.btnOK.Enable(enable)
-        self.btnApply.Enable(enable)   
-    
+        self.btnApply.Enable(enable)
+
     def AddTemporaryColumn(self, type):
         """Add temporary column to not overwrite the original values,
         need to be deleted when closing dialog and unloading map
-        
+
         :param type: type of column (e.g. vachar(11))"""
         if not self.CheckMapset():
             return
         # because more than one dialog with the same map can be opened we must test column name and
         # create another one
-        while self.properties['tmpColumn'] in self.dbInfo.GetTableDesc(self.properties['table']).keys():
+        while self.properties['tmpColumn'] in self.dbInfo.GetTableDesc(self.properties[
+                                                                       'table']).keys():
             name, idx = self.properties['tmpColumn'].split('_')
             idx = int(idx)
             idx += 1
             self.properties['tmpColumn'] = name + '_' + str(idx)
-        
+
         if self.version7:
             modul = 'v.db.addcolumn'
         else:
             modul = 'v.db.addcol'
         ret = RunCommand(modul,
-                         parent = self,
-                         map = self.inmap,
-                         layer = self.properties['layer'],
-                         column = '%s %s' % (self.properties['tmpColumn'], type))
-        
+                         parent=self,
+                         map=self.inmap,
+                         layer=self.properties['layer'],
+                         column='%s %s' % (self.properties['tmpColumn'], type))
+
     def DeleteTemporaryColumn(self):
         """Delete temporary column"""
         if not self.CheckMapset():
             return
-        
+
         if self.inmap:
             if self.version7:
                 modul = 'v.db.dropcolumn'
             else:
                 modul = 'v.db.dropcol'
             ret = RunCommand(modul,
-                             map = self.inmap,
-                             layer = self.properties['layer'],
-                             column = self.properties['tmpColumn'])
-        
+                             map=self.inmap,
+                             layer=self.properties['layer'],
+                             column=self.properties['tmpColumn'])
+
     def OnLayerSelection(self, event):
         # reset choices in column selection comboboxes if layer changes
         vlayer = int(self.layerSelect.GetStringSelection())
-        self.sourceColumn.InsertColumns(vector = self.inmap, layer = vlayer,
-                                        type = ['integer', 'double precision'], dbInfo = self.dbInfo,
-                                        excludeCols = ['tmpColumn'])
+        self.sourceColumn.InsertColumns(
+            vector=self.inmap, layer=vlayer,
+            type=['integer', 'double precision'],
+            dbInfo=self.dbInfo, excludeCols=['tmpColumn'])
         self.sourceColumn.SetValue('cat')
         self.properties['sourceColumn'] = self.sourceColumn.GetValue()
-        
+
         if self.attributeType == 'color':
             type = ['character']
         else:
             type = ['integer']
-        self.fromColumn.InsertColumns(vector = self.inmap, layer = vlayer, type = type,
-                                      dbInfo = self.dbInfo, excludeCols = ['tmpColumn'])
-        self.toColumn.InsertColumns(vector = self.inmap, layer = vlayer, type = type,
-                                    dbInfo = self.dbInfo, excludeCols = ['tmpColumn'])
-        
+        self.fromColumn.InsertColumns(
+            vector=self.inmap,
+            layer=vlayer,
+            type=type,
+            dbInfo=self.dbInfo,
+            excludeCols=['tmpColumn'])
+        self.toColumn.InsertColumns(
+            vector=self.inmap,
+            layer=vlayer,
+            type=type,
+            dbInfo=self.dbInfo,
+            excludeCols=['tmpColumn'])
+
         v = self.columnsProp[self.attributeType]['name']
         found = False
         if v in self.fromColumn.GetColumns():
@@ -1351,39 +1478,45 @@
         else:
             self.properties['loadColumn'] = ''
             self.properties['storeColumn'] = ''
-        
+
         if event:
             self.LoadTable()
         self.Update()
-        
+
     def OnSourceColumnSelection(self, event):
         self.properties['sourceColumn'] = event.GetString()
-        
+
         self.LoadTable()
-    
+
     def OnAddColumn(self, event):
         """Add GRASS(RGB,SIZE,WIDTH) column if it doesn't exist"""
-        if self.columnsProp[self.attributeType]['name'] not in self.fromColumn.GetColumns():
+        if self.columnsProp[self.attributeType][
+                'name'] not in self.fromColumn.GetColumns():
             if self.version7:
                 modul = 'v.db.addcolumn'
             else:
                 modul = 'v.db.addcol'
-            ret = RunCommand(modul,
-                             map = self.inmap,
-                             layer = self.properties['layer'],
-                             columns = '%s %s' % (self.columnsProp[self.attributeType]['name'],
-                                                  self.columnsProp[self.attributeType]['type1']))
-            self.toColumn.InsertColumns(self.inmap, self.properties['layer'],
-                                        type = self.columnsProp[self.attributeType]['type2'])
-            self.toColumn.SetValue(self.columnsProp[self.attributeType]['name'])
+            ret = RunCommand(
+                modul, map=self.inmap, layer=self.properties['layer'], columns='%s %s' %
+                (self.columnsProp[
+                    self.attributeType]['name'], self.columnsProp[
+                    self.attributeType]['type1']))
+            self.toColumn.InsertColumns(
+                self.inmap,
+                self.properties['layer'],
+                type=self.columnsProp[
+                    self.attributeType]['type2'])
+            self.toColumn.SetValue(
+                self.columnsProp[
+                    self.attributeType]['name'])
             self.properties['storeColumn'] = self.toColumn.GetValue()
-            
+
             self.LoadTable()
         else:
-            GMessage(parent = self,
-                     message = _("%s column already exists.") % \
-                         self.columnsProp[self.attributeType]['name'])
-                        
+            GMessage(parent=self,
+                     message=_("%s column already exists.") %
+                     self.columnsProp[self.attributeType]['name'])
+
     def CreateAttrTable(self, dcmd, layer, params, propwin):
         """Create attribute table"""
         if dcmd:
@@ -1392,94 +1525,96 @@
             if ret == 0:
                 self.OnSelectionInput(None)
                 return True
-            
-        for combo in (self.layerSelect, self.sourceColumn, self.fromColumn, self.toColumn):
+
+        for combo in (self.layerSelect, self.sourceColumn,
+                      self.fromColumn, self.toColumn):
             combo.SetValue("")
             combo.Disable()
-        return False    
-    
+        return False
+
     def LoadTable(self):
         """Load table"""
         if self.colorTable:
-            ColorTable.LoadTable(self, mapType = 'vector')
+            ColorTable.LoadTable(self, mapType='vector')
         else:
             self.LoadRulesFromColumn()
-            
+
     def LoadRulesFromColumn(self):
         """Load current column (GRASSRGB, size column)"""
-        
+
         self.rulesPanel.Clear()
         if not self.properties['sourceColumn']:
             self.preview.EraseMap()
             return
-        
-        busy = wx.BusyInfo(message = _("Please wait, loading data from attribute table..."),
-                           parent = self)
+
+        busy = wx.BusyInfo(
+            message=_("Please wait, loading data from attribute table..."),
+            parent=self)
         wx.Yield()
-        
+
         columns = self.properties['sourceColumn']
         if self.properties['loadColumn']:
             columns += ',' + self.properties['loadColumn']
-        
-        sep = ';'            
+
+        sep = ';'
         if self.inmap:
-            outFile = tempfile.NamedTemporaryFile(mode = 'w+b')
+            outFile = tempfile.NamedTemporaryFile(mode='w+b')
             ret = RunCommand('v.db.select',
-                             quiet = True,
-                             flags = 'c',
-                             map = self.inmap,
-                             layer = self.properties['layer'],
-                             columns = columns,
-                             sep = sep,
-                             stdout = outFile)
+                             quiet=True,
+                             flags='c',
+                             map=self.inmap,
+                             layer=self.properties['layer'],
+                             columns=columns,
+                             sep=sep,
+                             stdout=outFile)
         else:
             self.preview.EraseMap()
             busy.Destroy()
             return
-        
+
         outFile.seek(0)
         i = 0
         minim = maxim = 0.0
         limit = 1000
-        
+
         colvallist = []
         readvals = False
-        
+
         while True:
             # os.linesep doesn't work here (MSYS)
             record = outFile.readline().replace('\n', '')
             if not record:
                 break
             self.rulesPanel.ruleslines[i] = {}
-            
+
             if not self.properties['loadColumn']:
                 col1 = record
                 col2 = None
             else:
                 col1, col2 = record.split(sep)
-            
+
             if float(col1) < minim:
                 minim = float(col1)
             if float(col1) > maxim:
                 maxim = float(col1)
 
-                
-            # color rules list should only have unique values of col1, not all records
-            if col1 not in colvallist:                
+            # color rules list should only have unique values of col1, not all
+            # records
+            if col1 not in colvallist:
                 self.rulesPanel.ruleslines[i]['value'] = col1
                 self.rulesPanel.ruleslines[i][self.attributeType] = col2
 
-                colvallist.append(col1)            
+                colvallist.append(col1)
                 i += 1
-            
+
             if i > limit and readvals == False:
-                dlg = wx.MessageDialog (parent = self, message = _(
-                                        "Number of loaded records reached %d, "
-                                        "displaying all the records will be time-consuming "
-                                        "and may lead to computer freezing, "
-                                        "do you still want to continue?") % i,
-                                        caption = _("Too many records"),
-                                        style  =  wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
+                dlg = wx.MessageDialog(parent=self, message=_(
+                    "Number of loaded records reached %d, "
+                    "displaying all the records will be time-consuming "
+                    "and may lead to computer freezing, "
+                    "do you still want to continue?") % i,
+                    caption=_("Too many records"),
+                    style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
                 if dlg.ShowModal() == wx.ID_YES:
                     readvals = True
                     dlg.Destroy()
@@ -1488,95 +1623,108 @@
                     dlg.Destroy()
                     self.updateColumn = False
                     return
-            
-        self.rulesPanel.AddRules(i, start = True)
+
+        self.rulesPanel.AddRules(i, start=True)
         ret = self.rulesPanel.LoadRules()
-        
+
         self.properties['min'], self.properties['max'] = minim, maxim
         self.SetRangeLabel()
-        
+
         if ret:
-            self.OnPreview()   
+            self.OnPreview()
         else:
             self.rulesPanel.Clear()
-    
+
         busy.Destroy()
-        
+
     def SetRangeLabel(self):
         """Set labels with info about attribute column range"""
-        
+
         if self.properties['sourceColumn']:
-            ctype = self.dbInfo.GetTableDesc(self.properties['table'])[self.properties['sourceColumn']]['ctype']
+            ctype = self.dbInfo.GetTableDesc(
+                self.properties['table'])[
+                self.properties['sourceColumn']]['ctype']
         else:
             ctype = int
-        
+
         range = ''
         if self.properties['min'] or self.properties['max']:
             if ctype == float:
                 range = "%s: %.1f - %.1f)" % (_("range"),
-                                              self.properties['min'], self.properties['max'])
+                                              self.properties['min'],
+                                              self.properties['max'])
             elif ctype == int:
                 range = "%s: %d - %d)" % (_("range"),
-                                          self.properties['min'], self.properties['max'])
+                                          self.properties['min'],
+                                          self.properties['max'])
         if range:
             if self.colorTable:
-                self.cr_label.SetLabel(_("Enter vector attribute values or percents %s:") % range)
+                self.cr_label.SetLabel(
+                    _("Enter vector attribute values or percents %s:") %
+                    range)
             else:
-                self.cr_label.SetLabel(_("Enter vector attribute values %s:") % range)
+                self.cr_label.SetLabel(
+                    _("Enter vector attribute values %s:") %
+                    range)
         else:
             if self.colorTable:
-                self.cr_label.SetLabel(_("Enter vector attribute values or percents:"))
+                self.cr_label.SetLabel(
+                    _("Enter vector attribute values or percents:"))
             else:
                 self.cr_label.SetLabel(_("Enter vector attribute values:"))
-                
+
     def OnFromColSelection(self, event):
         """Selection in combobox (for loading values) changed"""
         self.properties['loadColumn'] = event.GetString()
-        
+
         self.LoadTable()
-    
+
     def OnToColSelection(self, event):
         """Selection in combobox (for storing values) changed"""
         self.properties['storeColumn'] = event.GetString()
-    
-    def OnPreview(self, event = None, tmp = True):
+
+    def OnPreview(self, event=None, tmp=True):
         """Update preview (based on computational region)"""
         if self.colorTable:
             self.OnTablePreview(tmp)
         else:
-            self.OnColumnPreview() 
-                                 
+            self.OnColumnPreview()
+
     def OnTablePreview(self, tmp):
         """Update preview (based on computational region)"""
         if not self.inmap:
             self.preview.EraseMap()
             return
-        
+
         ltype = 'vector'
         cmdlist = ['d.vect',
                    'map=%s' % self.inmap]
-        
+
         # find existing color table and copy to temp file
         try:
             name, mapset = self.inmap.split('@')
         except ValueError:
             name = self.inmap
-            mapset = grass.find_file(self.inmap, element = 'cell')['mapset']
+            mapset = grass.find_file(self.inmap, element='cell')['mapset']
             if not mapset:
                 return
-            
+
         old_colrtable = None
         if mapset == grass.gisenv()['MAPSET']:
-            old_colrtable = grass.find_file(name = 'colr', element = os.path.join('vector', name))['file']
+            old_colrtable = grass.find_file(
+                name='colr', element=os.path.join(
+                    'vector', name))['file']
         else:
-            old_colrtable = grass.find_file(name = name, element = os.path.join('vcolr2', mapset))['file']
-            
+            old_colrtable = grass.find_file(
+                name=name, element=os.path.join(
+                    'vcolr2', mapset))['file']
+
         if old_colrtable:
             colrtemp = utils.GetTempfile()
             shutil.copyfile(old_colrtable, colrtemp)
-            
-        ColorTable.DoPreview(self, ltype, cmdlist)  
-        
+
+        ColorTable.DoPreview(self, ltype, cmdlist)
+
         # restore previous color table
         if tmp:
             if old_colrtable:
@@ -1584,57 +1732,62 @@
                 os.remove(colrtemp)
             else:
                 RunCommand('v.colors',
-                           parent = self,
-                           flags = 'r',
-                           map = self.inmap)
+                           parent=self,
+                           flags='r',
+                           map=self.inmap)
+
     def OnColumnPreview(self):
         """Update preview (based on computational region)"""
         if not self.inmap or not self.properties['tmpColumn']:
             self.preview.EraseMap()
             return
-        
+
         cmdlist = ['d.vect',
                    'map=%s' % self.inmap,
                    'type=point,line,boundary,area']
-                
+
         if self.attributeType == 'color':
             cmdlist.append('rgb_column=%s' % self.properties['tmpColumn'])
         elif self.attributeType == 'size':
             cmdlist.append('size_column=%s' % self.properties['tmpColumn'])
         elif self.attributeType == 'width':
             cmdlist.append('width_column=%s' % self.properties['tmpColumn'])
-            
+
         ltype = 'vector'
-        
+
         ColorTable.DoPreview(self, ltype, cmdlist)
-        
+
     def OnHelp(self, event):
         """Show GRASS manual page"""
         cmd = 'v.colors'
-        ColorTable.RunHelp(self, cmd = cmd)
-        
+        ColorTable.RunHelp(self, cmd=cmd)
+
     def UseAttrColumn(self, useAttrColumn):
         """Find layers and apply the changes in d.vect command"""
-        layers = self.layerTree.FindItemByData(key = 'name', value = self.inmap)
+        layers = self.layerTree.FindItemByData(key='name', value=self.inmap)
         if not layers:
             return
         for layer in layers:
-            if self.layerTree.GetLayerInfo(layer, key = 'type') != 'vector':
+            if self.layerTree.GetLayerInfo(layer, key='type') != 'vector':
                 continue
-            cmdlist = self.layerTree.GetLayerInfo(layer, key = 'maplayer').GetCmd()
-            
+            cmdlist = self.layerTree.GetLayerInfo(
+                layer, key='maplayer').GetCmd()
+
             if self.attributeType == 'color':
                 if useAttrColumn:
-                    cmdlist[1].update({'rgb_column': self.properties['storeColumn']})
+                    cmdlist[1].update(
+                        {'rgb_column': self.properties['storeColumn']})
                 else:
                     cmdlist[1].pop('rgb_column', None)
             elif self.attributeType == 'size':
-                cmdlist[1].update({'size_column': self.properties['storeColumn']})
+                cmdlist[1].update(
+                    {'size_column': self.properties['storeColumn']})
             elif self.attributeType == 'width':
-                cmdlist[1].update({'width_column' :self.properties['storeColumn']})
-            self.layerTree.SetLayerInfo(layer, key = 'cmd', value = cmdlist)
-        
-    def CreateColorTable(self, tmp = False):
+                cmdlist[1].update(
+                    {'width_column': self.properties['storeColumn']})
+            self.layerTree.SetLayerInfo(layer, key='cmd', value=cmdlist)
+
+    def CreateColorTable(self, tmp=False):
         """Create color rules (color table or color column)"""
         if self.colorTable:
             ret = ColorTable.CreateColorTable(self)
@@ -1643,9 +1796,9 @@
                 ret = self.UpdateColorColumn(tmp)
             else:
                 ret = True
-        
+
         return ret
-        
+
     def UpdateColorColumn(self, tmp):
         """Creates color table
 
@@ -1653,38 +1806,38 @@
         :return: False on failure
         """
         rulestxt = ''
-        
+
         for rule in self.rulesPanel.ruleslines.itervalues():
-            if 'value' not in rule: # skip empty rules
+            if 'value' not in rule:  # skip empty rules
                 break
-            
+
             if tmp:
                 rgb_col = self.properties['tmpColumn']
             else:
                 rgb_col = self.properties['storeColumn']
                 if not self.properties['storeColumn']:
-                    GMessage(parent = self.parent,
-                             message = _("Please select column to save values to."))
-            
-            rulestxt += "UPDATE %s SET %s='%s' WHERE %s ;\n" % (self.properties['table'],
-                                                                rgb_col,
-                                                                rule[self.attributeType],
-                                                                rule['value'])
+                    GMessage(parent=self.parent, message=_(
+                        "Please select column to save values to."))
+
+            rulestxt += "UPDATE %s SET %s='%s' WHERE %s ;\n" % (
+                self.properties['table'],
+                rgb_col, rule[self.attributeType],
+                rule['value'])
         if not rulestxt:
             return False
-        
+
         gtemp = utils.GetTempfile()
         output = open(gtemp, "w")
         try:
             output.write(rulestxt)
         finally:
             output.close()
-        
+
         RunCommand('db.execute',
-                   parent = self,
-                   input = gtemp)
+                   parent=self,
+                   input=gtemp)
         return True
-    
+
     def OnCancel(self, event):
         """Do not apply any changes and close the dialog"""
         self.DeleteTemporaryColumn()
@@ -1693,7 +1846,7 @@
 
     def OnApply(self, event):
         """Apply selected color table
-        
+
         :return: True on success otherwise False
         """
         if self.colorTable:
@@ -1701,28 +1854,30 @@
         else:
             if not self.properties['storeColumn']:
                 GError(_("No color column defined. Operation canceled."),
-                       parent = self)
+                       parent=self)
                 return
-            
+
             self.UseAttrColumn(True)
-        
+
         return ColorTable.OnApply(self, event)
-        
+
+
 class ThematicVectorTable(VectorColorTable):
+
     def __init__(self, parent, vectorType, **kwargs):
         """Dialog for interactively entering color/size rules
         for vector maps for thematic mapping in nviz"""
         self.vectorType = vectorType
-        VectorColorTable.__init__(self, parent = parent, **kwargs)
-              
-        self.SetTitle(_("Thematic mapping for vector map in 3D view"))       
-                    
+        VectorColorTable.__init__(self, parent=parent, **kwargs)
+
+        self.SetTitle(_("Thematic mapping for vector map in 3D view"))
+
     def _initLayer(self):
         """Set initial layer when opening dialog"""
-        self.inmap = self.parent.GetLayerData(nvizType = 'vector', nameOnly = True)
+        self.inmap = self.parent.GetLayerData(nvizType='vector', nameOnly=True)
         self.selectionInput.SetValue(self.inmap)
         self.selectionInput.Disable()
-        
+
     def OnApply(self, event):
         """Apply selected color table
 
@@ -1730,86 +1885,92 @@
         """
         ret = self.CreateColorTable()
         if not ret:
-            GMessage(parent = self, message = _("No valid color rules given."))
-        
-        data = self.parent.GetLayerData(nvizType = 'vector')
-        data['vector']['points']['thematic']['layer'] = int(self.properties['layer'])
-        
+            GMessage(parent=self, message=_("No valid color rules given."))
+
+        data = self.parent.GetLayerData(nvizType='vector')
+        data['vector']['points']['thematic'][
+            'layer'] = int(self.properties['layer'])
+
         value = None
         if self.properties['storeColumn']:
             value = self.properties['storeColumn']
-            
+
         if not self.colorTable:
             if self.attributeType == 'color':
-                data['vector'][self.vectorType]['thematic']['rgbcolumn'] = value
+                data['vector'][self.vectorType][
+                    'thematic']['rgbcolumn'] = value
             else:
-                data['vector'][self.vectorType]['thematic']['sizecolumn'] = value
+                data['vector'][self.vectorType][
+                    'thematic']['sizecolumn'] = value
         else:
             if self.attributeType == 'color':
                 data['vector'][self.vectorType]['thematic']['rgbcolumn'] = None
             else:
-                data['vector'][self.vectorType]['thematic']['sizecolumn'] = None
-        
+                data['vector'][self.vectorType][
+                    'thematic']['sizecolumn'] = None
+
         data['vector'][self.vectorType]['thematic']['update'] = None
-        
-        from nviz.main            import haveNviz
+
+        from nviz.main import haveNviz
         if haveNviz:
-            from nviz.mapwindow   import wxUpdateProperties
-            
-            event = wxUpdateProperties(data = data)
+            from nviz.mapwindow import wxUpdateProperties
+
+            event = wxUpdateProperties(data=data)
             wx.PostEvent(self.parent.mapWindow, event)
-        
+
         self.parent.mapWindow.Refresh(False)
-        
+
         return ret
-           
+
+
 class BufferedWindow(wx.Window):
     """A Buffered window class"""
+
     def __init__(self, parent, id,
-                 style = wx.NO_FULL_REPAINT_ON_RESIZE,
-                 Map = None, **kwargs):
-        
-        wx.Window.__init__(self, parent, id, style = style, **kwargs)
+                 style=wx.NO_FULL_REPAINT_ON_RESIZE,
+                 Map=None, **kwargs):
 
+        wx.Window.__init__(self, parent, id, style=style, **kwargs)
+
         self.parent = parent
         self.Map = Map
-        
+
         # re-render the map from GRASS or just redraw image
         self.render = True
         # indicates whether or not a resize event has taken place
-        self.resize = False 
+        self.resize = False
 
         #
         # event bindings
         #
-        self.Bind(wx.EVT_PAINT,        self.OnPaint)
-        self.Bind(wx.EVT_IDLE,         self.OnIdle)
+        self.Bind(wx.EVT_PAINT, self.OnPaint)
+        self.Bind(wx.EVT_IDLE, self.OnIdle)
         self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
 
         #
         # render output objects
         #
         # image file to be rendered
-        self.mapfile = None 
+        self.mapfile = None
         # wx.Image object (self.mapfile)
         self.img = None
 
         self.pdc = wx.PseudoDC()
         # will store an off screen empty bitmap for saving to file
-        self._Buffer = None 
+        self._Buffer = None
 
         # make sure that extents are updated at init
         self.Map.region = self.Map.GetRegion()
         self.Map.SetRegion()
         self.Map.GetRenderMgr().renderDone.connect(self._updatePreviewFinished)
 
-    def Draw(self, pdc, img = None, pdctype = 'image'):
+    def Draw(self, pdc, img=None, pdctype='image'):
         """Draws preview or clears window"""
         pdc.BeginDrawing()
 
-        Debug.msg (3, "BufferedWindow.Draw(): pdctype=%s" % (pdctype))
+        Debug.msg(3, "BufferedWindow.Draw(): pdctype=%s" % (pdctype))
 
-        if pdctype == 'clear': # erase the display
+        if pdctype == 'clear':  # erase the display
             bg = wx.WHITE_BRUSH
             pdc.SetBackground(bg)
             pdc.Clear()
@@ -1822,8 +1983,8 @@
             pdc.SetBackground(bg)
             bitmap = wx.BitmapFromImage(img)
             w, h = bitmap.GetSize()
-            pdc.DrawBitmap(bitmap, 0, 0, True) # draw the composite map
-            
+            pdc.DrawBitmap(bitmap, 0, 0, True)  # draw the composite map
+
         pdc.EndDrawing()
         self.Refresh()
 
@@ -1831,24 +1992,24 @@
         """Draw pseudo DC to buffer"""
         self._Buffer = wx.EmptyBitmap(self.Map.width, self.Map.height)
         dc = wx.BufferedPaintDC(self, self._Buffer)
-        
+
         # use PrepareDC to set position correctly
         # probably does nothing, removed from wxPython 2.9
         # self.PrepareDC(dc)
-        
+
         # we need to clear the dc BEFORE calling PrepareDC
         bg = wx.Brush(self.GetBackgroundColour())
         dc.SetBackground(bg)
         dc.Clear()
-        
+
         # create a clipping rect from our position and size
         # and the Update Region
         rgn = self.GetUpdateRegion()
         r = rgn.GetBox()
-        
+
         # draw to the dc using the calculated clipping rect
         self.pdc.DrawToDCClipped(dc, r)
-        
+
     def OnSize(self, event):
         """Init image size to match window size"""
         # set size of the input image
@@ -1863,7 +2024,7 @@
         self.img = self.GetImage()
 
         # update map display
-        if self.img and self.Map.width + self.Map.height > 0: # scale image during resize
+        if self.img and self.Map.width + self.Map.height > 0:  # scale image during resize
             self.img = self.img.Scale(self.Map.width, self.Map.height)
             self.render = False
             self.UpdatePreview()
@@ -1887,43 +2048,45 @@
             img = wx.Image(self.Map.mapfile, wx.BITMAP_TYPE_ANY)
         else:
             img = None
-        
+
         return img
-    
-    def UpdatePreview(self, img = None):
+
+    def UpdatePreview(self, img=None):
         """Update canvas if window changes geometry"""
-        Debug.msg (2, "BufferedWindow.UpdatePreview(%s): render=%s" % (img, self.render))
-        
+        Debug.msg(
+            2, "BufferedWindow.UpdatePreview(%s): render=%s" %
+            (img, self.render))
+
         if not self.render:
             return
-        
+
         # extent is taken from current map display
         try:
-            self.Map.region = copy.deepcopy(self.parent.parent.GetLayerTree().GetMap().GetCurrentRegion())
+            self.Map.region = copy.deepcopy(
+                self.parent.parent.GetLayerTree().GetMap().GetCurrentRegion())
         except AttributeError:
             self.Map.region = self.Map.GetRegion()
         # render new map images
-        self.mapfile = self.Map.Render(force = self.render)
+        self.mapfile = self.Map.Render(force=self.render)
 
     def _updatePreviewFinished(self):
         if not self.render:
             return
-        
+
         self.img = self.GetImage()
         self.resize = False
-        
+
         if not self.img:
             return
-        
+
         # paint images to PseudoDC
         self.pdc.Clear()
         self.pdc.RemoveAll()
         # draw map image background
-        self.Draw(self.pdc, self.img, pdctype = 'image')
-        
+        self.Draw(self.pdc, self.img, pdctype='image')
+
         self.resize = False
-        
+
     def EraseMap(self):
         """Erase preview"""
-        self.Draw(self.pdc, pdctype = 'clear')
-    
+        self.Draw(self.pdc, pdctype='clear')

Modified: grass/trunk/gui/wxpython/modules/extensions.py
===================================================================
--- grass/trunk/gui/wxpython/modules/extensions.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/modules/extensions.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -25,56 +25,70 @@
 
 from grass.script import task as gtask
 
-from core             import globalvar
-from core.gcmd        import GError, RunCommand, GException, GMessage
-from core.utils       import SetAddOnPath, _
+from core import globalvar
+from core.gcmd import GError, RunCommand, GException, GMessage
+from core.utils import SetAddOnPath, _
 from core.gthread import gThread
-from core.menutree    import TreeModel, ModuleNode
+from core.menutree import TreeModel, ModuleNode
 from gui_core.widgets import GListCtrl, SearchModuleWidget
 from gui_core.treeview import CTreeView
-from core.toolboxes   import toolboxesOutdated
+from core.toolboxes import toolboxesOutdated
 
 
 class InstallExtensionWindow(wx.Frame):
-    def __init__(self, parent, giface, id = wx.ID_ANY,
-                 title = _("Fetch & install extension from GRASS Addons"), **kwargs):
+
+    def __init__(self, parent, giface, id=wx.ID_ANY, title=_(
+            "Fetch & install extension from GRASS Addons"), **kwargs):
         self.parent = parent
         self._giface = giface
-        self.options = dict() # list of options
+        self.options = dict()  # list of options
 
-        wx.Frame.__init__(self, parent = parent, id = id, title = title, **kwargs)
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
-        
-        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
+        wx.Frame.__init__(self, parent=parent, id=id, title=title, **kwargs)
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass.ico'),
+                wx.BITMAP_TYPE_ICO))
 
-        self.repoBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
-                                    label = " %s " % _("Repository (leave empty to use the official one)"))
-        self.treeBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
-                                    label = " %s " % _("List of extensions - double-click to install"))
-        
-        self.repo = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY)
-        
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
+        self.repoBox = wx.StaticBox(
+            parent=self.panel, id=wx.ID_ANY, label=" %s " %
+            _("Repository (leave empty to use the official one)"))
+        self.treeBox = wx.StaticBox(
+            parent=self.panel, id=wx.ID_ANY, label=" %s " %
+            _("List of extensions - double-click to install"))
+
+        self.repo = wx.TextCtrl(parent=self.panel, id=wx.ID_ANY)
+
         # modelBuilder loads data into tree model
         self.modelBuilder = ExtensionTreeModelBuilder()
         # tree view displays model data
-        self.tree = CTreeView(parent=self.panel, model=self.modelBuilder.GetModel())
-        
-        self.search = SearchModuleWidget(parent=self.panel, model=self.modelBuilder.GetModel(),
-                                         showChoice = False)
-        self.search.showSearchResult.connect(lambda result: self.tree.Select(result))
+        self.tree = CTreeView(
+            parent=self.panel,
+            model=self.modelBuilder.GetModel())
+
+        self.search = SearchModuleWidget(
+            parent=self.panel,
+            model=self.modelBuilder.GetModel(),
+            showChoice=False)
+        self.search.showSearchResult.connect(
+            lambda result: self.tree.Select(result))
         # show text in statusbar when notification appears
-        self.search.showNotification.connect(lambda message: self.SetStatusText(message))
+        self.search.showNotification.connect(
+            lambda message: self.SetStatusText(message))
         # load data in different thread
         self.thread = gThread()
 
-        self.optionBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
-                                      label = " %s " % _("Options"))
+        self.optionBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
+                                      label=" %s " % _("Options"))
         task = gtask.parse_interface('g.extension')
         ignoreFlags = ['l', 'c', 'g', 'a', 'f', 't', 'help', 'quiet']
         if sys.platform == 'win32':
             ignoreFlags.append('d')
             ignoreFlags.append('i')
-        
+
         for f in task.get_options()['flags']:
             name = f.get('name', '')
             desc = f.get('label', '')
@@ -84,25 +98,30 @@
                 continue
             if name in ignoreFlags:
                 continue
-            self.options[name] = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
-                                             label = desc)
+            self.options[name] = wx.CheckBox(parent=self.panel, id=wx.ID_ANY,
+                                             label=desc)
         defaultUrl = ''  # default/official one will be used when option empty
-        self.repo.SetValue(task.get_param(value='url').get('default', defaultUrl))
+        self.repo.SetValue(
+            task.get_param(
+                value='url').get(
+                'default',
+                defaultUrl))
 
-        self.statusbar = self.CreateStatusBar(number = 1)
-        
-        self.btnFetch = wx.Button(parent = self.panel, id = wx.ID_ANY,
-                                  label = _("&Fetch"))
+        self.statusbar = self.CreateStatusBar(number=1)
+
+        self.btnFetch = wx.Button(parent=self.panel, id=wx.ID_ANY,
+                                  label=_("&Fetch"))
         self.btnFetch.SetToolTipString(_("Fetch list of available modules "
                                          "from GRASS Addons SVN repository"))
-        self.btnClose = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
-        self.btnInstall = wx.Button(parent = self.panel, id = wx.ID_ANY,
-                                    label = _("&Install"))
-        self.btnInstall.SetToolTipString(_("Install selected add-ons GRASS module"))
+        self.btnClose = wx.Button(parent=self.panel, id=wx.ID_CLOSE)
+        self.btnInstall = wx.Button(parent=self.panel, id=wx.ID_ANY,
+                                    label=_("&Install"))
+        self.btnInstall.SetToolTipString(
+            _("Install selected add-ons GRASS module"))
         self.btnInstall.Enable(False)
-        self.btnHelp = wx.Button(parent = self.panel, id = wx.ID_HELP)
+        self.btnHelp = wx.Button(parent=self.panel, id=wx.ID_HELP)
         self.btnHelp.SetToolTipString(_("Show g.extension manual page"))
-        
+
         self.btnClose.Bind(wx.EVT_BUTTON, lambda evt: self.Close())
         self.btnFetch.Bind(wx.EVT_BUTTON, self.OnFetch)
         self.btnInstall.Bind(wx.EVT_BUTTON, self.OnInstall)
@@ -112,7 +131,7 @@
         self.tree.contextMenu.connect(self.OnContextMenu)
 
         wx.CallAfter(self._fetch)
-        
+
         self._layout()
 
     def _layout(self):
@@ -120,56 +139,56 @@
         sizer = wx.BoxSizer(wx.VERTICAL)
         repoSizer = wx.StaticBoxSizer(self.repoBox, wx.VERTICAL)
         repo1Sizer = wx.BoxSizer(wx.HORIZONTAL)
-        repo1Sizer.Add(item = self.repo, proportion = 1,
-                      flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL, border = 1)
-        repo1Sizer.Add(item = self.btnFetch, proportion = 0,
-                      flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL, border = 1)
-        repoSizer.Add(item = repo1Sizer,
-                      flag = wx.EXPAND)
-        
+        repo1Sizer.Add(item=self.repo, proportion=1,
+                       flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL, border=1)
+        repo1Sizer.Add(item=self.btnFetch, proportion=0,
+                       flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL, border=1)
+        repoSizer.Add(item=repo1Sizer,
+                      flag=wx.EXPAND)
+
         findSizer = wx.BoxSizer(wx.HORIZONTAL)
-        findSizer.Add(item = self.search, proportion = 1)
-        
+        findSizer.Add(item=self.search, proportion=1)
+
         treeSizer = wx.StaticBoxSizer(self.treeBox, wx.HORIZONTAL)
-        treeSizer.Add(item = self.tree, proportion = 1,
-                      flag = wx.ALL | wx.EXPAND, border = 1)
+        treeSizer.Add(item=self.tree, proportion=1,
+                      flag=wx.ALL | wx.EXPAND, border=1)
 
         # options
         optionSizer = wx.StaticBoxSizer(self.optionBox, wx.VERTICAL)
         for key in self.options.keys():
-            optionSizer.Add(item = self.options[key], proportion = 0)
-        
+            optionSizer.Add(item=self.options[key], proportion=0)
+
         btnSizer = wx.BoxSizer(wx.HORIZONTAL)
-        btnSizer.Add(item = self.btnHelp, proportion = 0)
+        btnSizer.Add(item=self.btnHelp, proportion=0)
         btnSizer.AddStretchSpacer()
-        btnSizer.Add(item = self.btnClose, proportion = 0,
-                     flag = wx.RIGHT, border = 5)
-        btnSizer.Add(item = self.btnInstall, proportion = 0)
-        
-        sizer.Add(item = repoSizer, proportion = 0,
-                  flag = wx.ALL | wx.EXPAND, border = 3)
-        sizer.Add(item = findSizer, proportion = 0,
-                  flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
-        sizer.Add(item = treeSizer, proportion = 1,
-                  flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
-        sizer.Add(item = optionSizer, proportion = 0,
-                        flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
-        sizer.Add(item = btnSizer, proportion = 0,
-                  flag = wx.ALIGN_RIGHT | wx.ALL | wx.EXPAND, border = 5)
-        
+        btnSizer.Add(item=self.btnClose, proportion=0,
+                     flag=wx.RIGHT, border=5)
+        btnSizer.Add(item=self.btnInstall, proportion=0)
+
+        sizer.Add(item=repoSizer, proportion=0,
+                  flag=wx.ALL | wx.EXPAND, border=3)
+        sizer.Add(item=findSizer, proportion=0,
+                  flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
+        sizer.Add(item=treeSizer, proportion=1,
+                  flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
+        sizer.Add(item=optionSizer, proportion=0,
+                  flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
+        sizer.Add(item=btnSizer, proportion=0,
+                  flag=wx.ALIGN_RIGHT | wx.ALL | wx.EXPAND, border=5)
+
         self.panel.SetSizer(sizer)
         sizer.Fit(self.panel)
-        
+
         self.Layout()
 
     def _getCmd(self):
         item = self.tree.GetSelected()
         if not item or 'command' not in item[0].data:
-            GError(_("Extension not defined"), parent = self)
+            GError(_("Extension not defined"), parent=self)
             return
 
         name = item[0].data['command']
-        
+
         flags = list()
         for key in self.options.keys():
             if self.options[key].IsChecked():
@@ -177,7 +196,7 @@
                     flags.append('-%s' % key)
                 else:
                     flags.append('--%s' % key)
-        
+
         return ['g.extension'] + flags + ['extension=' + name,
                                           'url=' + self.repo.GetValue().strip()]
 
@@ -188,35 +207,42 @@
     def _fetch(self):
         """Fetch list of available extensions"""
         wx.BeginBusyCursor()
-        self.SetStatusText(_("Fetching list of modules from GRASS-Addons SVN (be patient)..."), 0)
+        self.SetStatusText(
+            _("Fetching list of modules from GRASS-Addons SVN (be patient)..."), 0)
         try:
-            self.thread.Run(callable=self.modelBuilder.Load, url=self.repo.GetValue().strip(),
-                            ondone=lambda event: self._fetchDone())
+            self.thread.Run(
+                callable=self.modelBuilder.Load,
+                url=self.repo.GetValue().strip(),
+                ondone=lambda event: self._fetchDone())
         except GException as e:
             self._fetchDone()
-            GError(unicode(e), parent = self, showTraceback = False)
-            
+            GError(unicode(e), parent=self, showTraceback=False)
+
     def _fetchDone(self):
         self.tree.RefreshItems()
-        nitems = len(self.modelBuilder.GetModel().SearchNodes(key='command', value='*'))
+        nitems = len(
+            self.modelBuilder.GetModel().SearchNodes(
+                key='command', value='*'))
         self.SetStatusText(_("%d extensions loaded") % nitems, 0)
         wx.EndBusyCursor()
-        
+
     def OnContextMenu(self, node):
-        if not hasattr (self, "popupID"):
+        if not hasattr(self, "popupID"):
             self.popupID = dict()
             for key in ('install', 'help'):
                 self.popupID[key] = wx.NewId()
-        
+
         data = node.data
         if data and 'command' in data:
             self.popupMenu = wx.Menu()
-            self.popupMenu.Append(self.popupID['install'], text = _("Install"))
-            self.Bind(wx.EVT_MENU, self.OnInstall, id = self.popupID['install'])
+            self.popupMenu.Append(self.popupID['install'], text=_("Install"))
+            self.Bind(wx.EVT_MENU, self.OnInstall, id=self.popupID['install'])
             self.popupMenu.AppendSeparator()
-            self.popupMenu.Append(self.popupID['help'], text = _("Show manual page"))
-            self.Bind(wx.EVT_MENU, self.OnItemHelp, id = self.popupID['help'])
-            
+            self.popupMenu.Append(
+                self.popupID['help'],
+                text=_("Show manual page"))
+            self.Bind(wx.EVT_MENU, self.OnItemHelp, id=self.popupID['help'])
+
             self.PopupMenu(self.popupMenu)
             self.popupMenu.Destroy()
 
@@ -224,19 +250,19 @@
         data = node.data
         if data and 'command' in data:
             self.OnInstall(event=None)
-        
+
     def OnInstall(self, event):
         """Install selected extension"""
         log = self.parent.GetLogWindow()
         cmd = self._getCmd()
         if cmd:
-            log.RunCmd(cmd, onDone = self.OnDone)
-        
+            log.RunCmd(cmd, onDone=self.OnDone)
+
     def OnDone(self, event):
         if event.returncode == 0:
             if not os.getenv('GRASS_ADDON_BASE'):
-                SetAddOnPath(key = 'BASE')
-            
+                SetAddOnPath(key='BASE')
+
             globalvar.UpdateGRASSAddOnCommands()
             toolboxesOutdated()
 
@@ -244,7 +270,7 @@
         item = self.tree.GetSelected()
         if not item or 'command' not in item[0].data:
             return
-        
+
         self._giface.Help(entry=item[0].data['command'], online=True)
 
     def OnHelp(self, event):
@@ -260,8 +286,10 @@
             self.SetStatusText(data.get('description', ''), 0)
             self.btnInstall.Enable(True)
 
+
 class ExtensionTreeModelBuilder:
     """Tree model of available extensions."""
+
     def __init__(self):
         self.mainNodes = dict()
         self.model = TreeModel(ModuleNode)
@@ -271,7 +299,7 @@
                        'raster', 'raster3D', 'sites', 'vector', 'wxGUI', 'other'):
             node = self.model.AppendNode(parent=self.model.root, label=prefix)
             self.mainNodes[prefix] = node
-        
+
     def GetModel(self):
         return self.model
 
@@ -280,41 +308,40 @@
         for node in self.mainNodes.values():
             for child in reversed(node.children):
                 self.model.RemoveNode(child)
-        
+
     def _expandPrefix(self, c):
-        name = { 'd'  : 'display',
-                 'db' : 'database',
-                 'g'  : 'general',
-                 'i'  : 'imagery',
-                 'm'  : 'misc',
-                 'ps' : 'postscript',
-                 'p'  : 'paint',
-                 'r'  : 'raster',
-                 'r3' : 'raster3D',
-                 's'  : 'sites',
-                 'v'  : 'vector',
-                 'wx' : 'wxGUI',
-                 ''   : 'other' }
-        
+        name = {'d': 'display',
+                'db': 'database',
+                'g': 'general',
+                'i': 'imagery',
+                'm': 'misc',
+                'ps': 'postscript',
+                'p': 'paint',
+                'r': 'raster',
+                'r3': 'raster3D',
+                's': 'sites',
+                'v': 'vector',
+                'wx': 'wxGUI',
+                '': 'other'}
+
         if c in name:
             return name[c]
-        
+
         return c
-    
-    def Load(self, url, full = True):
+
+    def Load(self, url, full=True):
         """Load list of extensions"""
         self._emptyTree()
-        
+
         if full:
             flags = 'g'
         else:
             flags = 'l'
-        retcode, ret, msg = RunCommand('g.extension', read = True, getErrorMsg = True,
-                                       url=url,
-                                       flags = flags, quiet = True)
+        retcode, ret, msg = RunCommand(
+            'g.extension', read=True, getErrorMsg=True, url=url, flags=flags, quiet=True)
         if retcode != 0:
             raise GException(_("Unable to load extensions. %s") % msg)
-        
+
         currentNode = None
         for line in ret.splitlines():
             if full:
@@ -331,7 +358,8 @@
                         prefix = ''
                         name = value
                     mainNode = self.mainNodes[self._expandPrefix(prefix)]
-                    currentNode = self.model.AppendNode(parent=mainNode, label=value)
+                    currentNode = self.model.AppendNode(
+                        parent=mainNode, label=value)
                     currentNode.data = {'command': value}
                 else:
                     if currentNode is not None:
@@ -342,67 +370,90 @@
                 except ValueError:
                     prefix = ''
                     name = line.strip()
-                
+
                 if self._expandPrefix(prefix) == prefix:
                     prefix = ''
                 module = prefix + '.' + name
                 mainNode = self.mainNodes[self._expandPrefix(prefix)]
-                currentNode = self.model.AppendNode(parent=mainNode, label=module)
+                currentNode = self.model.AppendNode(
+                    parent=mainNode, label=module)
                 currentNode.data = {'command': module,
                                     'keywords': '',
-                                    'description': ''}        
-        
+                                    'description': ''}
+
+
 class ManageExtensionWindow(wx.Frame):
-    def __init__(self, parent, id = wx.ID_ANY,
-                 title = _("Manage installed GRASS Addons extensions"), **kwargs):
+
+    def __init__(
+            self, parent, id=wx.ID_ANY,
+            title=_("Manage installed GRASS Addons extensions"),
+            **kwargs):
         self.parent = parent
-        
-        wx.Frame.__init__(self, parent = parent, id = id, title = title, **kwargs)
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
-        
-        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
 
-        self.extBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
-                                   label = " %s " % _("List of installed extensions"))
-        
-        self.extList = CheckListExtension(parent = self.panel)
+        wx.Frame.__init__(self, parent=parent, id=id, title=title, **kwargs)
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass.ico'),
+                wx.BITMAP_TYPE_ICO))
 
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
+        self.extBox = wx.StaticBox(
+            parent=self.panel, id=wx.ID_ANY, label=" %s " %
+            _("List of installed extensions"))
+
+        self.extList = CheckListExtension(parent=self.panel)
+
         # buttons
-        self.btnUninstall = wx.Button(parent = self.panel, id = wx.ID_REMOVE, label=_("Uninstall"))
-        self.btnUninstall.SetToolTipString(_("Uninstall selected Addons extensions"))
-        self.btnUpdate = wx.Button(parent = self.panel, id = wx.ID_REFRESH, label=_("Reinstall"))
-        self.btnUpdate.SetToolTipString(_("Reinstall selected Addons extensions"))
+        self.btnUninstall = wx.Button(
+            parent=self.panel,
+            id=wx.ID_REMOVE,
+            label=_("Uninstall"))
+        self.btnUninstall.SetToolTipString(
+            _("Uninstall selected Addons extensions"))
+        self.btnUpdate = wx.Button(
+            parent=self.panel,
+            id=wx.ID_REFRESH,
+            label=_("Reinstall"))
+        self.btnUpdate.SetToolTipString(
+            _("Reinstall selected Addons extensions"))
 
-        self.btnClose = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
-        
+        self.btnClose = wx.Button(parent=self.panel, id=wx.ID_CLOSE)
+
         self.btnUninstall.Bind(wx.EVT_BUTTON, self.OnUninstall)
         self.btnUpdate.Bind(wx.EVT_BUTTON, self.OnUpdate)
         self.btnClose.Bind(wx.EVT_BUTTON, lambda evt: self.Close())
-        
+
         self._layout()
-        
+
     def _layout(self):
         """Do layout"""
         sizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         extSizer = wx.StaticBoxSizer(self.extBox, wx.HORIZONTAL)
-        extSizer.Add(item = self.extList, proportion = 1,
-                     flag = wx.ALL | wx.EXPAND, border = 1)
-        
+        extSizer.Add(item=self.extList, proportion=1,
+                     flag=wx.ALL | wx.EXPAND, border=1)
+
         btnSizer = wx.BoxSizer(wx.HORIZONTAL)
-        btnSizer.Add(item = self.btnClose, proportion = 0,
-                     flag = wx.RIGHT, border = 5)
-        btnSizer.Add(item = self.btnUpdate, proportion = 0, flag=wx.RIGHT, border=5)
-        btnSizer.Add(item = self.btnUninstall, proportion = 0)
-        
-        sizer.Add(item = extSizer, proportion = 1,
-                  flag = wx.ALL | wx.EXPAND, border = 3)
-        sizer.Add(item = btnSizer, proportion = 0,
-                  flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
-        
+        btnSizer.Add(item=self.btnClose, proportion=0,
+                     flag=wx.RIGHT, border=5)
+        btnSizer.Add(
+            item=self.btnUpdate,
+            proportion=0,
+            flag=wx.RIGHT,
+            border=5)
+        btnSizer.Add(item=self.btnUninstall, proportion=0)
+
+        sizer.Add(item=extSizer, proportion=1,
+                  flag=wx.ALL | wx.EXPAND, border=3)
+        sizer.Add(item=btnSizer, proportion=0,
+                  flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
+
         self.panel.SetSizer(sizer)
         sizer.Fit(self.panel)
-        
+
         self.Layout()
 
     def _getSelectedExtensions(self):
@@ -410,9 +461,9 @@
         if not eList:
             GMessage(_("No extension selected. "
                        "Operation canceled."),
-                     parent = self)
+                     parent=self)
             return []
-        
+
         return eList
 
     def OnUninstall(self, event):
@@ -420,26 +471,34 @@
         eList = self._getSelectedExtensions()
         if not eList:
             return
-        
+
         for ext in eList:
-            files = RunCommand('g.extension', parent = self, read = True, quiet = True,
-                               extension = ext, operation = 'remove').splitlines()
+            files = RunCommand(
+                'g.extension',
+                parent=self,
+                read=True,
+                quiet=True,
+                extension=ext,
+                operation='remove').splitlines()
             if len(files) > 10:
                 files = files[:10]
                 files.append('...')
-            dlg = wx.MessageDialog(parent = self,
-                                   message = _("List of files to be removed:\n%(files)s\n\n"
-                                               "Do you want really to remove <%(ext)s> extension?") % \
-                                       { 'files' : os.linesep.join(files), 'ext' : ext },
-                                   caption = _("Remove extension"),
-                                   style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
-            
-            if dlg.ShowModal() ==  wx.ID_YES:
-                RunCommand('g.extension', flags = 'f', parent = self, quiet = True,
-                           extension = ext, operation = 'remove')
-        
+            dlg = wx.MessageDialog(
+                parent=self,
+                message=_(
+                    "List of files to be removed:\n%(files)s\n\n"
+                    "Do you want really to remove <%(ext)s> extension?") %
+                {'files': os.linesep.join(files),
+                 'ext': ext},
+                caption=_("Remove extension"),
+                style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
+
+            if dlg.ShowModal() == wx.ID_YES:
+                RunCommand('g.extension', flags='f', parent=self, quiet=True,
+                           extension=ext, operation='remove')
+
         self.extList.LoadData()
-        
+
         # update prompt
         globalvar.UpdateGRASSAddOnCommands(eList)
         toolboxesOutdated()
@@ -449,30 +508,32 @@
         eList = self._getSelectedExtensions()
         if not eList:
             return
-        
+
         log = self.parent.GetLogWindow()
-        
+
         for ext in eList:
             log.RunCmd(['g.extension', 'extension=%s' % ext,
                         'operation=add'])
-        
+
+
 class CheckListExtension(GListCtrl):
     """List of mapset/owner/group"""
+
     def __init__(self, parent):
         GListCtrl.__init__(self, parent)
-        
+
         # load extensions
         self.InsertColumn(0, _('Extension'))
         self.LoadData()
-        
+
     def LoadData(self):
         """Load data into list"""
         self.DeleteAllItems()
         for ext in RunCommand('g.extension',
-                              quiet = True, parent = self, read = True,
-                              flags = 'a').splitlines():
+                              quiet=True, parent=self, read=True,
+                              flags='a').splitlines():
             if ext:
-                self.InsertStringItem(sys.maxint, ext)
+                self.InsertStringItem(sys.maxsize, ext)
 
     def GetExtensions(self):
         """Get extensions to be un-installed
@@ -483,5 +544,5 @@
                 name = self.GetItemText(i)
                 if name:
                     extList.append(name)
-        
+
         return extList

Modified: grass/trunk/gui/wxpython/modules/histogram.py
===================================================================
--- grass/trunk/gui/wxpython/modules/histogram.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/modules/histogram.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -22,17 +22,18 @@
 
 import wx
 
-from core                 import globalvar
-from core.render          import Map
-from gui_core.forms       import GUI
-from mapdisp.gprint       import PrintOptions
-from core.utils           import GetLayerNameFromCmd, _
-from gui_core.dialogs     import GetImageHandlers, ImageSizeDialog
+from core import globalvar
+from core.render import Map
+from gui_core.forms import GUI
+from mapdisp.gprint import PrintOptions
+from core.utils import GetLayerNameFromCmd, _
+from gui_core.dialogs import GetImageHandlers, ImageSizeDialog
 from gui_core.preferences import DefaultFontDialog
-from core.debug           import Debug
-from core.gcmd            import GError
-from gui_core.toolbars    import BaseToolbar, BaseIcons
+from core.debug import Debug
+from core.gcmd import GError
+from gui_core.toolbars import BaseToolbar, BaseIcons
 
+
 class BufferedWindow(wx.Window):
     """A Buffered window class.
 
@@ -41,90 +42,99 @@
     can also save the drawing to file by calling the
     SaveToFile(self,file_name,file_type) method.
     """
-    def __init__(self, parent, id = wx.ID_ANY,
-                 style = wx.NO_FULL_REPAINT_ON_RESIZE,
-                 Map = None, **kwargs):
-        
-        wx.Window.__init__(self, parent, id = id, style = style, **kwargs)
-        
+
+    def __init__(self, parent, id=wx.ID_ANY,
+                 style=wx.NO_FULL_REPAINT_ON_RESIZE,
+                 Map=None, **kwargs):
+
+        wx.Window.__init__(self, parent, id=id, style=style, **kwargs)
+
         self.parent = parent
         self.Map = Map
         self.mapname = self.parent.mapname
-        
+
         #
         # Flags
         #
         self.render = True  # re-render the map from GRASS or just redraw image
-        self.resize = False # indicates whether or not a resize event has taken place
-        self.dragimg = None # initialize variable for map panning
+        self.resize = False  # indicates whether or not a resize event has taken place
+        self.dragimg = None  # initialize variable for map panning
         self.pen = None     # pen for drawing zoom boxes, etc.
-        
+
         #
         # Event bindings
         #
-        self.Bind(wx.EVT_PAINT,        self.OnPaint)
-        self.Bind(wx.EVT_SIZE,         self.OnSize)
-        self.Bind(wx.EVT_IDLE,         self.OnIdle)
-        
+        self.Bind(wx.EVT_PAINT, self.OnPaint)
+        self.Bind(wx.EVT_SIZE, self.OnSize)
+        self.Bind(wx.EVT_IDLE, self.OnIdle)
+
         #
         # Render output objects
         #
-        self.mapfile = None # image file to be rendered
+        self.mapfile = None  # image file to be rendered
         self.img = ""       # wx.Image object (self.mapfile)
-        
-        self.imagedict = {} # images and their PseudoDC ID's for painting and dragging
-        
+
+        self.imagedict = {}  # images and their PseudoDC ID's for painting and dragging
+
         self.pdc = wx.PseudoDC()
         # 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._buffer = wx.EmptyBitmap(
+            max(1, self.Map.width),
+            max(1, self.Map.height))
+
         # make sure that extents are updated at init
         self.Map.region = self.Map.GetRegion()
-        self.Map.SetRegion() 
-        
-        self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x:None)
-        
-    def Draw(self, pdc, img = None, drawid = None, pdctype = 'image', coords = [0,0,0,0]):
+        self.Map.SetRegion()
+
+        self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
+
+    def Draw(self, pdc, img=None, drawid=None,
+             pdctype='image', coords=[0, 0, 0, 0]):
         """Draws histogram or clears window
         """
-        if drawid == None:
-            if pdctype == 'image' :
+        if drawid is None:
+            if pdctype == 'image':
                 drawid = imagedict[img]
             elif pdctype == 'clear':
-                drawid == None
+                drawid is None
             else:
                 drawid = wx.NewId()
         else:
             pdc.SetId(drawid)
-        
+
         pdc.BeginDrawing()
-        
-        Debug.msg (3, "BufferedWindow.Draw(): id=%s, pdctype=%s, coord=%s" % (drawid, pdctype, coords))
-        
-        if pdctype == 'clear': # erase the display
+
+        Debug.msg(
+            3, "BufferedWindow.Draw(): id=%s, pdctype=%s, coord=%s" %
+            (drawid, pdctype, coords))
+
+        if pdctype == 'clear':  # erase the display
             bg = wx.WHITE_BRUSH
             pdc.SetBackground(bg)
             pdc.Clear()
             self.Refresh()
             pdc.EndDrawing()
             return
-        
+
         if pdctype == 'image':
             bg = wx.TRANSPARENT_BRUSH
             pdc.SetBackground(bg)
             bitmap = wx.BitmapFromImage(img)
-            w,h = bitmap.GetSize()
-            pdc.DrawBitmap(bitmap, coords[0], coords[1], True) # draw the composite map
-            pdc.SetIdBounds(drawid, (coords[0],coords[1],w,h))
-        
+            w, h = bitmap.GetSize()
+            pdc.DrawBitmap(
+                bitmap, coords[0],
+                coords[1],
+                True)  # draw the composite map
+            pdc.SetIdBounds(drawid, (coords[0], coords[1], w, h))
+
         pdc.EndDrawing()
         self.Refresh()
-        
+
     def OnPaint(self, event):
         """Draw psuedo DC to buffer
         """
         dc = wx.BufferedPaintDC(self, self._buffer)
-        
+
         # use PrepareDC to set position correctly
         # probably does nothing, removed from wxPython 2.9
         # self.PrepareDC(dc)
@@ -137,31 +147,31 @@
         rgn = self.GetUpdateRegion()
         r = rgn.GetBox()
         # draw to the dc using the calculated clipping rect
-        self.pdc.DrawToDCClipped(dc,r)
-        
+        self.pdc.DrawToDCClipped(dc, r)
+
     def OnSize(self, event):
         """Init image size to match window size
         """
         # set size of the input image
         self.Map.width, self.Map.height = self.GetClientSize()
-        
+
         # Make new off screen bitmap: this bitmap will always have the
         # current drawing in it, so it can be used to save the image to
         # a file, or whatever.
         self._buffer = wx.EmptyBitmap(self.Map.width, self.Map.height)
-        
+
         # get the image to be rendered
         self.img = self.GetImage()
-        
+
         # update map display
-        if self.img and self.Map.width + self.Map.height > 0: # scale image during resize
+        if self.img and self.Map.width + self.Map.height > 0:  # scale image during resize
             self.img = self.img.Scale(self.Map.width, self.Map.height)
             self.render = False
             self.UpdateHist()
-        
+
         # re-render image on idle
         self.resize = True
-        
+
     def OnIdle(self, event):
         """Only re-render a histogram image from GRASS during idle
         time instead of multiple times during resizing.
@@ -170,7 +180,7 @@
             self.render = True
             self.UpdateHist()
         event.Skip()
-        
+
     def SaveToFile(self, FileName, FileType, width, height):
         """This will save the contents of the buffer to the specified
         file. See the wx.Windows docs for wx.Bitmap::SaveFile for the
@@ -179,21 +189,21 @@
         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 = True)
+        self.Map.Render(force=True, windres=True)
         img = self.GetImage()
-        self.Draw(self.pdc, img, drawid = 99)
+        self.Draw(self.pdc, img, drawid=99)
         dc = wx.BufferedDC(None, ibuffer)
         dc.Clear()
         # probably does nothing, removed from wxPython 2.9
         # self.PrepareDC(dc)
         self.pdc.DrawToDC(dc)
         ibuffer.SaveFile(FileName, FileType)
-        
+
         busy.Destroy()
-        
+
     def GetImage(self):
         """Converts files to wx.Image
         """
@@ -202,89 +212,109 @@
             img = wx.Image(self.Map.mapfile, wx.BITMAP_TYPE_ANY)
         else:
             img = None
-        
-        self.imagedict[img] = 99 # set image PeudoDC ID
+
+        self.imagedict[img] = 99  # set image PeudoDC ID
         return img
-    
-    def UpdateHist(self, img = None):
+
+    def UpdateHist(self, img=None):
         """Update canvas if histogram options changes or window
         changes geometry
         """
-        Debug.msg (2, "BufferedWindow.UpdateHist(%s): render=%s" % (img, self.render))
+        Debug.msg(
+            2, "BufferedWindow.UpdateHist(%s): render=%s" %
+            (img, self.render))
         oldfont = ""
         oldencoding = ""
-        
+
         if self.render:
             # render new map images
             # set default font and encoding environmental variables
             if "GRASS_FONT" in os.environ:
                 oldfont = os.environ["GRASS_FONT"]
-            if self.parent.font != "": os.environ["GRASS_FONT"] = self.parent.font
+            if self.parent.font != "":
+                os.environ["GRASS_FONT"] = self.parent.font
             if "GRASS_ENCODING" in os.environ:
                 oldencoding = os.environ["GRASS_ENCODING"]
-            if self.parent.encoding != None and self.parent.encoding != "ISO-8859-1":
+            if self.parent.encoding is not None and self.parent.encoding != "ISO-8859-1":
                 os.environ[GRASS_ENCODING] = self.parent.encoding
-            
+
             # using active comp region
-            self.Map.GetRegion(update = True)
-            
+            self.Map.GetRegion(update=True)
+
             self.Map.width, self.Map.height = self.GetClientSize()
-            self.mapfile = self.Map.Render(force = self.render)
+            self.mapfile = self.Map.Render(force=self.render)
             self.img = self.GetImage()
             self.resize = False
-        
-        if not self.img: return
+
+        if not self.img:
+            return
         try:
             id = self.imagedict[self.img]
         except:
             return
-        
+
         # paint images to PseudoDC
         self.pdc.Clear()
         self.pdc.RemoveAll()
-        self.Draw(self.pdc, self.img, drawid = id) # draw map image background
-        
+        self.Draw(self.pdc, self.img, drawid=id)  # draw map image background
+
         self.resize = False
-        
+
         # update statusbar
         # Debug.msg (3, "BufferedWindow.UpdateHist(%s): region=%s" % self.Map.region)
         self.Map.SetRegion()
-        self.parent.statusbar.SetStatusText("Image/Raster map <%s>" % self.parent.mapname)
-        
+        self.parent.statusbar.SetStatusText(
+            "Image/Raster map <%s>" %
+            self.parent.mapname)
+
         # set default font and encoding environmental variables
         if oldfont != "":
             os.environ["GRASS_FONT"] = oldfont
         if oldencoding != "":
             os.environ["GRASS_ENCODING"] = oldencoding
-        
+
     def EraseMap(self):
         """Erase the map display
         """
-        self.Draw(self.pdc, pdctype = 'clear')
-        
+        self.Draw(self.pdc, pdctype='clear')
+
+
 class HistogramFrame(wx.Frame):
     """Main frame for hisgram display window. Uses d.histogram
     rendered onto canvas
     """
+
     def __init__(self, parent, giface, id=wx.ID_ANY,
-                 title = _("GRASS GIS Histogramming Tool (d.histogram)"),
-                 size = wx.Size(500, 350),
-                 style = wx.DEFAULT_FRAME_STYLE, **kwargs):
-        wx.Frame.__init__(self, parent, id, title, size = size, style = style, **kwargs)
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
+                 title=_("GRASS GIS Histogramming Tool (d.histogram)"),
+                 size=wx.Size(500, 350),
+                 style=wx.DEFAULT_FRAME_STYLE, **kwargs):
+        wx.Frame.__init__(
+            self,
+            parent,
+            id,
+            title,
+            size=size,
+            style=style,
+            **kwargs)
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass.ico'),
+                wx.BITMAP_TYPE_ICO))
 
         self._giface = giface
-        self.Map   = Map()         # instance of render.Map to be associated with display
+        self.Map = Map()         # instance of render.Map to be associated with display
         self.layer = None          # reference to layer with histogram
-        
+
         # Init variables
         self.params = {}  # previously set histogram parameters
-        self.propwin = '' # ID of properties dialog
-        
+        self.propwin = ''  # ID of properties dialog
+
         self.font = ""
-        self.encoding = 'ISO-8859-1' # default encoding for display fonts
-        
-        self.toolbar = HistogramToolbar(parent = self)
+        self.encoding = 'ISO-8859-1'  # default encoding for display fonts
+
+        self.toolbar = HistogramToolbar(parent=self)
         # workaround for http://trac.wxwidgets.org/ticket/13888
         if sys.platform != 'darwin':
             self.SetToolBar(self.toolbar)
@@ -299,27 +329,35 @@
             self.mapname = layers[0].maplayer.name
 
         # Add statusbar
-        self.statusbar = self.CreateStatusBar(number = 1, style = 0)
+        self.statusbar = self.CreateStatusBar(number=1, style=0)
         # self.statusbar.SetStatusWidths([-2, -1])
         hist_frame_statusbar_fields = ["Histogramming %s" % self.mapname]
         for i in range(len(hist_frame_statusbar_fields)):
             self.statusbar.SetStatusText(hist_frame_statusbar_fields[i], i)
-        
+
         # Init map display
-        self.InitDisplay() # initialize region values
-        
+        self.InitDisplay()  # initialize region values
+
         # initialize buffered DC
-        self.HistWindow = BufferedWindow(self, id = wx.ID_ANY, Map = self.Map) # initialize buffered DC
-        
+        self.HistWindow = BufferedWindow(
+            self, id=wx.ID_ANY, Map=self.Map)  # initialize buffered DC
+
         # Bind various events
-        self.Bind(wx.EVT_CLOSE,    self.OnCloseWindow)
-        
+        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
+
         # Init print module and classes
         self.printopt = PrintOptions(self, self.HistWindow)
-        
+
         # Add layer to the map
-        self.layer = self.Map.AddLayer(ltype = "command", name = 'histogram', command = [['d.histogram']],
-                                       active = False, hidden = False, opacity = 1, render = False)
+        self.layer = self.Map.AddLayer(
+            ltype="command",
+            name='histogram',
+            command=[
+                ['d.histogram']],
+            active=False,
+            hidden=False,
+            opacity=1,
+            render=False)
         if self.mapname:
             self.SetHistLayer(self.mapname, None)
         else:
@@ -331,84 +369,90 @@
         """
         self.width, self.height = self.GetClientSize()
         self.Map.geom = self.width, self.height
-        
+
     def OnOptions(self, event):
         """Change histogram settings"""
         cmd = ['d.histogram']
         if self.mapname != '':
             cmd.append('map=%s' % self.mapname)
-        module = GUI(parent = self)
-        module.ParseCommand(cmd, completed = (self.GetOptData, None, self.params))
+        module = GUI(parent=self)
+        module.ParseCommand(
+            cmd,
+            completed=(
+                self.GetOptData,
+                None,
+                self.params))
 
     def GetOptData(self, dcmd, layer, params, propwin):
         """Callback method for histogram command generated by dialog
         created in menuform.py
         """
         if dcmd:
-            name, found = GetLayerNameFromCmd(dcmd, fullyQualified = True,
-                                              layerType = 'raster')
+            name, found = GetLayerNameFromCmd(dcmd, fullyQualified=True,
+                                              layerType='raster')
             if not found:
-                GError(parent = propwin,
-                       message = _("Raster map <%s> not found") % name)
+                GError(parent=propwin,
+                       message=_("Raster map <%s> not found") % name)
                 return
-            
+
             self.SetHistLayer(name, dcmd)
         self.params = params
         self.propwin = propwin
         self.HistWindow.UpdateHist()
-        
-    def SetHistLayer(self, name, cmd = None):
+
+    def SetHistLayer(self, name, cmd=None):
         """Set histogram layer
         """
         self.mapname = name
         if not cmd:
-            cmd = ['d.histogram',('map=%s' % self.mapname)]
-        self.layer = self.Map.ChangeLayer(layer = self.layer,
-                                          command = [cmd],
-                                          active = True)
-        
+            cmd = ['d.histogram', ('map=%s' % self.mapname)]
+        self.layer = self.Map.ChangeLayer(layer=self.layer,
+                                          command=[cmd],
+                                          active=True)
+
         return self.layer
 
     def SetHistFont(self, event):
         """Set font for histogram. If not set, font will be default
         display font.
         """
-        dlg = DefaultFontDialog(parent = self, id = wx.ID_ANY,
-                                title = _('Select font for histogram text'))        
+        dlg = DefaultFontDialog(parent=self, id=wx.ID_ANY,
+                                title=_('Select font for histogram text'))
         dlg.fontlb.SetStringSelection(self.font, True)
-        
+
         if dlg.ShowModal() == wx.ID_CANCEL:
             dlg.Destroy()
             return
-        
-        # set default font type, font, and encoding to whatever selected in dialog
-        if dlg.font != None:
+
+        # set default font type, font, and encoding to whatever selected in
+        # dialog
+        if dlg.font is not None:
             self.font = dlg.font
-        if dlg.encoding != None:
+        if dlg.encoding is not None:
             self.encoding = dlg.encoding
-        
+
         dlg.Destroy()
         self.HistWindow.UpdateHist()
 
     def OnErase(self, event):
         """Erase the histogram display
         """
-        self.HistWindow.Draw(self.HistWindow.pdc, pdctype = 'clear')
-        
+        self.HistWindow.Draw(self.HistWindow.pdc, pdctype='clear')
+
     def OnRender(self, event):
         """Re-render histogram
         """
         self.HistWindow.UpdateHist()
-        
+
     def GetWindow(self):
         """Get buffered window"""
         return self.HistWindow
-    
+
     def SaveToFile(self, event):
         """Save to file
         """
         filetype, ltype = GetImageHandlers(self.HistWindow.img)
-        
+
         # get size
         dlg = ImageSizeDialog(self)
         dlg.CentreOnParent()
@@ -417,58 +461,58 @@
             return
         width, height = dlg.GetValues()
         dlg.Destroy()
-        
+
         # get filename
-        dlg = wx.FileDialog(parent = self,
-                            message = _("Choose a file name to save the image "
-                                        "(no need to add extension)"),
-                            wildcard = filetype,
+        dlg = wx.FileDialog(parent=self,
+                            message=_("Choose a file name to save the image "
+                                      "(no need to add extension)"),
+                            wildcard=filetype,
                             style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
-        
+
         if dlg.ShowModal() == wx.ID_OK:
             path = dlg.GetPath()
             if not path:
                 dlg.Destroy()
                 return
-            
+
             base, ext = os.path.splitext(path)
             fileType = ltype[dlg.GetFilterIndex()]['type']
-            extType  = ltype[dlg.GetFilterIndex()]['ext']
+            extType = ltype[dlg.GetFilterIndex()]['ext']
             if ext != extType:
                 path = base + '.' + extType
-            
+
             self.HistWindow.SaveToFile(path, fileType,
                                        width, height)
-        
+
         self.HistWindow.UpdateHist()
         dlg.Destroy()
-        
+
     def PrintMenu(self, event):
         """Print options and output menu
         """
         point = wx.GetMousePosition()
         printmenu = wx.Menu()
         # Add items to the menu
-        setup = wx.MenuItem(printmenu, id = wx.ID_ANY, text = _('Page setup'))
+        setup = wx.MenuItem(printmenu, id=wx.ID_ANY, text=_('Page setup'))
         printmenu.AppendItem(setup)
         self.Bind(wx.EVT_MENU, self.printopt.OnPageSetup, setup)
-        
-        preview = wx.MenuItem(printmenu, id = wx.ID_ANY, text = _('Print preview'))
+
+        preview = wx.MenuItem(printmenu, id=wx.ID_ANY, text=_('Print preview'))
         printmenu.AppendItem(preview)
         self.Bind(wx.EVT_MENU, self.printopt.OnPrintPreview, preview)
-        
-        doprint = wx.MenuItem(printmenu, id = wx.ID_ANY, text = _('Print display'))
+
+        doprint = wx.MenuItem(printmenu, id=wx.ID_ANY, text=_('Print display'))
         printmenu.AppendItem(doprint)
         self.Bind(wx.EVT_MENU, self.printopt.OnDoPrint, doprint)
-        
+
         # Popup the menu.  If an item is selected then its handler
         # will be called before PopupMenu returns.
         self.PopupMenu(printmenu)
         printmenu.Destroy()
-        
+
     def OnQuit(self, event):
         self.Close(True)
-        
+
     def OnCloseWindow(self, event):
         """Window closed
         Also remove associated rendered images
@@ -479,10 +523,12 @@
             pass
         self.Map.Clean()
         self.Destroy()
-        
+
+
 class HistogramToolbar(BaseToolbar):
     """Histogram toolbar (see histogram.py)
     """
+
     def __init__(self, parent):
         BaseToolbar.__init__(self, parent)
 
@@ -491,10 +537,10 @@
             parent.SetToolBar(self)
 
         self.InitToolbar(self._toolbarData())
-        
+
         # realize the toolbar
         self.Realize()
-        
+
     def _toolbarData(self):
         """Toolbar data"""
         return self._getToolbarData((('histogram', BaseIcons["histogramD"],

Modified: grass/trunk/gui/wxpython/modules/import_export.py
===================================================================
--- grass/trunk/gui/wxpython/modules/import_export.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/modules/import_export.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -23,7 +23,7 @@
 import os
 
 import wx
-import wx.lib.flatnotebook  as FN
+import wx.lib.flatnotebook as FN
 import wx.lib.filebrowsebutton as filebrowse
 
 from grass.script import core as grass
@@ -37,33 +37,36 @@
 from core.utils import GetValidLayerName, _
 from core.settings import UserSettings, GetDisplayVectSettings
 
+
 class ImportDialog(wx.Dialog):
     """Dialog for bulk import of various data (base class)"""
+
     def __init__(self, parent, giface, itype,
-                 id = wx.ID_ANY, title = _("Multiple import"),
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
-        self.parent = parent    # GMFrame 
+                 id=wx.ID_ANY, title=_("Multiple import"),
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
+        self.parent = parent    # GMFrame
         self._giface = giface  # used to add layers
         self.importType = itype
         self.options = dict()   # list of options
         self.options_par = dict()
-        
+
         self.commandId = -1  # id of running command
-        
-        wx.Dialog.__init__(self, parent, id, title, style = style,
-                           name = "MultiImportDialog")
-        
-        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
-        
-        self.layerBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY)
+
+        wx.Dialog.__init__(self, parent, id, title, style=style,
+                           name="MultiImportDialog")
+
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
+        self.layerBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY)
         if self.importType == 'gdal':
             label = _("List of raster layers")
         elif self.importType == 'ogr':
             label = _("List of vector layers")
         else:
             label = _("List of %s layers") % self.importType.upper()
-        self.layerBox.SetLabel(" %s - %s " % (label, _("right click to (un)select all")))
-        
+        self.layerBox.SetLabel(" %s - %s " %
+                               (label, _("right click to (un)select all")))
+
         # list of layers
         columns = [_('Layer id'),
                    _('Layer name'),
@@ -74,108 +77,128 @@
         elif itype == 'gdal':
             columns.insert(2, _('Projection match'))
 
-        self.list = LayersList(parent = self.panel, columns = columns)
+        self.list = LayersList(parent=self.panel, columns=columns)
         self.list.LoadData()
-        
-        self.overwrite = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
-                                     label = _("Allow output files to overwrite existing files"))
-        self.overwrite.SetValue(UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'))
-        
-        self.add = wx.CheckBox(parent = self.panel, id = wx.ID_ANY)
-        self.closeOnFinish = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
-                                     label = _("Close dialog on finish"))
-        self.closeOnFinish.SetValue(UserSettings.Get(group = 'cmd', key = 'closeDlg', subkey = 'enabled'))
-        
+
+        self.overwrite = wx.CheckBox(
+            parent=self.panel, id=wx.ID_ANY,
+            label=_("Allow output files to overwrite existing files"))
+        self.overwrite.SetValue(
+            UserSettings.Get(
+                group='cmd',
+                key='overwrite',
+                subkey='enabled'))
+
+        self.add = wx.CheckBox(parent=self.panel, id=wx.ID_ANY)
+        self.closeOnFinish = wx.CheckBox(parent=self.panel, id=wx.ID_ANY,
+                                         label=_("Close dialog on finish"))
+        self.closeOnFinish.SetValue(
+            UserSettings.Get(
+                group='cmd',
+                key='closeDlg',
+                subkey='enabled'))
+
         #
         # buttons
         #
         # cancel
-        self.btn_close = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
+        self.btn_close = wx.Button(parent=self.panel, id=wx.ID_CLOSE)
         self.btn_close.SetToolTipString(_("Close dialog"))
         self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
         # run
-        self.btn_run = wx.Button(parent = self.panel, id = wx.ID_OK, label = _("&Import"))
+        self.btn_run = wx.Button(
+            parent=self.panel,
+            id=wx.ID_OK,
+            label=_("&Import"))
         self.btn_run.SetToolTipString(_("Import selected layers"))
         self.btn_run.SetDefault()
         self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
 
         self.Bind(wx.EVT_CLOSE, lambda evt: self.Destroy())
 
+        self.notebook = GNotebook(parent=self,
+                                  style=FN.FNB_FANCY_TABS | FN.FNB_BOTTOM |
+                                  FN.FNB_NO_X_BUTTON)
 
-        self.notebook = GNotebook(parent = self,
-                                  style = FN.FNB_FANCY_TABS | FN.FNB_BOTTOM |
-                                          FN.FNB_NO_X_BUTTON)
+        self.notebook.AddPage(page=self.panel,
+                              text=_('Source settings'),
+                              name='source')
 
-        self.notebook.AddPage(page = self.panel, 
-                              text=_('Source settings'), 
-                              name = 'source')
-    
         self.createSettingsPage()
 
     def createSettingsPage(self):
 
-        self._blackList = { 'enabled' : True,
-                            'items'   : {self._getCommand() : {'params' : self._getBlackListedParameters(),
-                                                               'flags' :  self._getBlackListedFlags()}}}
+        self._blackList = {
+            'enabled': True,
+            'items': {
+                self._getCommand(): {
+                    'params': self._getBlackListedParameters(),
+                    'flags': self._getBlackListedFlags()}}}
 
         grass_task = gtask.parse_interface(self._getCommand(),
-                                            blackList=self._blackList)
+                                           blackList=self._blackList)
 
-        self.advancedPagePanel = CmdPanel(parent=self, giface=None, task=grass_task, frame=None)
+        self.advancedPagePanel = CmdPanel(
+            parent=self, giface=None, task=grass_task, frame=None)
 
-        self.notebook.AddPage(page = self.advancedPagePanel, 
-                              text=_('Import settings'), 
-                              name = 'settings')
+        self.notebook.AddPage(page=self.advancedPagePanel,
+                              text=_('Import settings'),
+                              name='settings')
 
     def doLayout(self):
         """Do layout"""
         dialogSizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         # dsn input
-        dialogSizer.Add(item = self.dsnInput, proportion = 0,
-                        flag = wx.EXPAND)
-        
+        dialogSizer.Add(item=self.dsnInput, proportion=0,
+                        flag=wx.EXPAND)
+
         #
         # list of DXF layers
         #
         layerSizer = wx.StaticBoxSizer(self.layerBox, wx.HORIZONTAL)
 
-        layerSizer.Add(item = self.list, proportion = 1,
-                      flag = wx.ALL | wx.EXPAND, border = 5)
-        
-        dialogSizer.Add(item = layerSizer, proportion = 1,
-                        flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
-        
-        dialogSizer.Add(item = self.overwrite, proportion = 0,
-                        flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
-        
-        dialogSizer.Add(item = self.add, proportion = 0,
-                        flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
-        
-        dialogSizer.Add(item = self.closeOnFinish, proportion = 0,
-                        flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
+        layerSizer.Add(item=self.list, proportion=1,
+                       flag=wx.ALL | wx.EXPAND, border=5)
+
+        dialogSizer.Add(
+            item=layerSizer,
+            proportion=1,
+            flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
+            border=5)
+
+        dialogSizer.Add(item=self.overwrite, proportion=0,
+                        flag=wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
+
+        dialogSizer.Add(item=self.add, proportion=0,
+                        flag=wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
+
+        dialogSizer.Add(item=self.closeOnFinish, proportion=0,
+                        flag=wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
         #
         # buttons
         #
-        btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
-        
-        btnsizer.Add(item = self.btn_close, proportion = 0,
-                     flag = wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,
-                     border = 10)
-        
-        btnsizer.Add(item = self.btn_run, proportion = 0,
-                     flag = wx.RIGHT | wx.ALIGN_CENTER,
-                     border = 10)
-        
-        dialogSizer.Add(item = btnsizer, proportion = 0,
-                        flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM | wx.ALIGN_RIGHT,
-                        border = 10)
-        
+        btnsizer = wx.BoxSizer(orient=wx.HORIZONTAL)
+
+        btnsizer.Add(item=self.btn_close, proportion=0,
+                     flag=wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,
+                     border=10)
+
+        btnsizer.Add(item=self.btn_run, proportion=0,
+                     flag=wx.RIGHT | wx.ALIGN_CENTER,
+                     border=10)
+
+        dialogSizer.Add(
+            item=btnsizer,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM | wx.ALIGN_RIGHT,
+            border=10)
+
         # dialogSizer.SetSizeHints(self.panel)
         self.panel.SetAutoLayout(True)
         self.panel.SetSizer(dialogSizer)
         dialogSizer.Fit(self.panel)
-        
+
         # auto-layout seems not work here - FIXME
         size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 225, 550)
         self.SetMinSize(size)
@@ -187,7 +210,7 @@
     def _getCommand(self):
         """Get command"""
         raise NotImplementedError()
-    
+
     def _getBlackListedParameters(self):
         """Get parameters which will not be showed in Settings page"""
         raise NotImplementedError()
@@ -196,7 +219,7 @@
         """Get flags which will not be showed in Settings page"""
         raise NotImplementedError()
 
-    def OnClose(self, event = None):
+    def OnClose(self, event=None):
         """Close dialog"""
         self.Close()
 
@@ -204,7 +227,7 @@
         """Import/Link data (each layes as separate vector map)"""
         pass
 
-    def AddLayers(self, returncode, cmd = None, userData = None):
+    def AddLayers(self, returncode, cmd=None, userData=None):
         """Add imported/linked layers into layer tree"""
         if not self.add.IsChecked() or returncode != 0:
             return
@@ -215,12 +238,12 @@
         # * persuade import tools to report map names
         self.commandId += 1
         layer, output = self.list.GetLayers()[self.commandId][:2]
-        
+
         if '@' not in output:
             name = output + '@' + grass.gisenv()['MAPSET']
         else:
             name = output
-        
+
         # add imported layers into layer tree
         # an alternative would be emit signal (mapCreated) and (optionally)
         # connect to this signal
@@ -230,24 +253,25 @@
                 nBands = int(userData.get('nbands', 1))
             else:
                 nBands = 1
-            
-            if UserSettings.Get(group = 'rasterLayer', key = 'opaque', subkey = 'enabled'):
+
+            if UserSettings.Get(group='rasterLayer',
+                                key='opaque', subkey='enabled'):
                 nFlag = True
             else:
                 nFlag = False
-            
-            for i in range(1, nBands+1):
+
+            for i in range(1, nBands + 1):
                 nameOrig = name
                 if nBands > 1:
                     mapName, mapsetName = name.split('@')
                     mapName += '.%d' % i
                     name = mapName + '@' + mapsetName
-                    
+
                 cmd = ['d.rast',
                        'map=%s' % name]
                 if nFlag:
                     cmd.append('-n')
-                
+
                 llist.AddLayer(ltype='raster',
                                name=name, checked=True,
                                cmd=cmd)
@@ -273,7 +297,7 @@
         pass
 
     def _getLayersToReprojetion(self, projMatch_idx, grassName_idx):
-        """If there are layers with different projection from loation projection, 
+        """If there are layers with different projection from loation projection,
            show dialog to user to explicitly select layers which will be reprojected..."""
         differentProjLayers = []
         data = self.list.GetData(checked=True)
@@ -286,13 +310,16 @@
             if self.layersData[layerId][projMatch_idx] == 0:
                 dt = [itm[0], itm[grassName_idx]]
                 differentProjLayers.append(tuple(dt))
-        
+
         layers = self.list.GetLayers()
-        
+
         if differentProjLayers and '-o' not in self.getSettingsPageCmd():
 
-            dlg = RerojectionDialog(parent=self, giface=self._giface, data=differentProjLayers)
-                
+            dlg = RerojectionDialog(
+                parent=self,
+                giface=self._giface,
+                data=differentProjLayers)
+
             ret = dlg.ShowModal()
 
             if ret == wx.ID_OK:
@@ -302,15 +329,18 @@
                     idx = itm[-1]
                     layers.pop(idx)
             else:
-                return None;
+                return None
 
         return layers
 
     def getSettingsPageCmd(self):
 
-        return self.advancedPagePanel.createCmd(ignoreErrors=True, ignoreRequired=True)
+        return self.advancedPagePanel.createCmd(
+            ignoreErrors=True, ignoreRequired=True)
 
+
 class GdalImportDialog(ImportDialog):
+
     def __init__(self, parent, giface, link=False):
         """Dialog for bulk import of various raster data
 
@@ -325,14 +355,14 @@
 
         self.layersData = []
 
-        ImportDialog.__init__(self, parent, giface=giface, itype='gdal') 
+        ImportDialog.__init__(self, parent, giface=giface, itype='gdal')
         if link:
             self.SetTitle(_("Link external raster data"))
         else:
             self.SetTitle(_("Import raster data"))
-        
-        self.dsnInput = GdalSelect(parent = self, panel = self.panel,
-                                   ogr = False, link = link)
+
+        self.dsnInput = GdalSelect(parent=self, panel=self.panel,
+                                   ogr=False, link=link)
         self.dsnInput.AttachSettings()
         self.dsnInput.reloadDataRequired.connect(self.reload)
 
@@ -340,9 +370,13 @@
             self.add.SetLabel(_("Add linked layers into layer tree"))
         else:
             self.add.SetLabel(_("Add imported layers into layer tree"))
-        
-        self.add.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
 
+        self.add.SetValue(
+            UserSettings.Get(
+                group='cmd',
+                key='addNewLayer',
+                subkey='enabled'))
+
         if link:
             self.btn_run.SetLabel(_("&Link"))
             self.btn_run.SetToolTipString(_("Link selected layers"))
@@ -354,8 +388,8 @@
 
     def reload(self, data, listData):
 
-        self.list.LoadData(listData);
-        self.layersData = data;
+        self.list.LoadData(listData)
+        self.layersData = data
 
     def OnRun(self, event):
         """Import/Link data (each layes as separate vector map)"""
@@ -365,19 +399,19 @@
         data = self._getLayersToReprojetion(2, 3)
 
         if data is None:
-            return;
+            return
 
         if not data:
             GMessage(_("No layers selected. Operation canceled."),
-                     parent = self)
+                     parent=self)
             return
-        
-        dsn  = self.dsnInput.GetDsn()
-        ext  = self.dsnInput.GetFormatExt()
-        
+
+        dsn = self.dsnInput.GetDsn()
+        ext = self.dsnInput.GetFormatExt()
+
         for layer, output, listId in data:
             userData = {}
-          
+
             if self.dsnInput.GetType() == 'dir':
                 idsn = os.path.join(dsn, layer)
             else:
@@ -385,8 +419,8 @@
 
             # check number of bands
             nBandsStr = RunCommand('r.in.gdal',
-                                    flags = 'p',
-                                    input = idsn, read = True)
+                                   flags='p',
+                                   input=idsn, read=True)
             nBands = -1
             if nBandsStr:
                 try:
@@ -395,23 +429,27 @@
                     pass
             if nBands < 0:
                 GWarning(_("Unable to determine number of raster bands"),
-                        parent = self)
+                         parent=self)
             nBands = 1
 
             userData['nbands'] = nBands
             cmd = self.getSettingsPageCmd()
             cmd.append('input=%s' % dsn)
             cmd.append('output=%s' % output)
-            
+
             if self.overwrite.IsChecked():
                 cmd.append('--overwrite')
-            
-            if UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled') and \
-                    '--overwrite' not in cmd:
+
+            if UserSettings.Get(group='cmd', key='overwrite',
+                                subkey='enabled') and '--overwrite' not in cmd:
                 cmd.append('--overwrite')
-            
+
             # run in Layer Manager
-            self._giface.RunCmd(cmd, onDone=self.OnCmdDone, userData=userData, addLayer=False)
+            self._giface.RunCmd(
+                cmd,
+                onDone=self.OnCmdDone,
+                userData=userData,
+                addLayer=False)
 
     def OnCmdDone(self, event):
         """Load layers and close if required"""
@@ -426,9 +464,9 @@
     def _getCommand(self):
         """Get command"""
         if self.link:
-                return 'r.external'
+            return 'r.external'
         else:
-                return 'r.import'
+            return 'r.import'
 
     def _getBlackListedParameters(self):
         """Get flags which will not be showed in Settings page"""
@@ -438,7 +476,9 @@
         """Get flags which will not be showed in Settings page"""
         return ['overwrite']
 
+
 class OgrImportDialog(ImportDialog):
+
     def __init__(self, parent, giface, link=False):
         """Dialog for bulk import of various vector data
 
@@ -458,9 +498,9 @@
             self.SetTitle(_("Link external vector data"))
         else:
             self.SetTitle(_("Import vector data"))
-        
-        self.dsnInput = GdalSelect(parent = self, panel = self.panel,
-                                   ogr = True, link = link)
+
+        self.dsnInput = GdalSelect(parent=self, panel=self.panel,
+                                   ogr=True, link=link)
         self.dsnInput.AttachSettings()
         self.dsnInput.reloadDataRequired.connect(self.reload)
 
@@ -468,9 +508,13 @@
             self.add.SetLabel(_("Add linked layers into layer tree"))
         else:
             self.add.SetLabel(_("Add imported layers into layer tree"))
-        
-        self.add.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
 
+        self.add.SetValue(
+            UserSettings.Get(
+                group='cmd',
+                key='addNewLayer',
+                subkey='enabled'))
+
         if link:
             self.btn_run.SetLabel(_("&Link"))
             self.btn_run.SetToolTipString(_("Link selected layers"))
@@ -482,28 +526,27 @@
 
     def reload(self, data, listData):
 
-        self.list.LoadData(listData);
-        self.layersData = data;
+        self.list.LoadData(listData)
+        self.layersData = data
 
     def OnRun(self, event):
         """Import/Link data (each layes as separate vector map)"""
         self.commandId = -1
         data = self.list.GetLayers()
 
-
         data = self._getLayersToReprojetion(3, 4)
 
         if data is None:
-            return;
+            return
 
         if not data:
             GMessage(_("No layers selected. Operation canceled."),
-                     parent = self)
+                     parent=self)
             return
-        
-        dsn  = self.dsnInput.GetDsn()
-        ext  = self.dsnInput.GetFormatExt()
-        
+
+        dsn = self.dsnInput.GetDsn()
+        ext = self.dsnInput.GetFormatExt()
+
         # determine data driver for PostGIS links
         self.popOGR = False
         if  self.dsnInput.GetType() == 'db' and \
@@ -511,7 +554,7 @@
                 'GRASS_VECTOR_OGR' not in os.environ:
             self.popOGR = True
             os.environ['GRASS_VECTOR_OGR'] = '1'
-        
+
         for layer, output, listId in data:
             userData = {}
 
@@ -522,10 +565,10 @@
             else:
                 geometry = None
 
-                #TODO
-                #if geometry:
+                # TODO
+                # if geometry:
                 #    cmd.append('geometry=%s' % geometry)
-             
+
             cmd = self.getSettingsPageCmd()
             cmd.append('input=%s' % dsn)
             cmd.append('layer=%s' % layer)
@@ -533,14 +576,18 @@
 
             if self.overwrite.IsChecked():
                 cmd.append('--overwrite')
-            
-            #TODO options
-            if UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled') and \
-                    '--overwrite' not in cmd:
+
+            # TODO options
+            if UserSettings.Get(group='cmd', key='overwrite',
+                                subkey='enabled') and '--overwrite' not in cmd:
                 cmd.append('--overwrite')
-            
+
             # run in Layer Manager
-            self._giface.RunCmd(cmd, onDone = self.OnCmdDone, userData = userData, addLayer=False)
+            self._giface.RunCmd(
+                cmd,
+                onDone=self.OnCmdDone,
+                userData=userData,
+                addLayer=False)
 
     def OnCmdDone(self, event):
         """Load layers and close if required"""
@@ -558,7 +605,7 @@
     def _getCommand(self):
         """Get command"""
         if self.link:
-           return 'v.external'
+            return 'v.external'
         else:
             return 'v.import'
 
@@ -570,9 +617,11 @@
         """Get flags which will not be showed in Settings page"""
         return ['overwrite']
 
+
 class GdalOutputDialog(wx.Dialog):
-    def __init__(self, parent, id = wx.ID_ANY, ogr = False,
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, *kwargs):
+
+    def __init__(self, parent, id=wx.ID_ANY, ogr=False,
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, *kwargs):
         """Dialog for setting output format for rasters/vectors
 
         .. todo::
@@ -584,68 +633,72 @@
         :param style: window style
         :param *kwargs: other wx.Dialog's arguments
         """
-        self.parent = parent # GMFrame 
+        self.parent = parent  # GMFrame
         self.ogr = ogr
-        wx.Dialog.__init__(self, parent, id = id, style = style, *kwargs)
+        wx.Dialog.__init__(self, parent, id=id, style=style, *kwargs)
         if self.ogr:
             self.SetTitle(_("Define output format for vector data"))
         else:
             self.SetTitle(_("Define output format for raster data"))
-        
-        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
 
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
         # buttons
-        self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
+        self.btnCancel = wx.Button(parent=self.panel, id=wx.ID_CANCEL)
         self.btnCancel.SetToolTipString(_("Close dialog"))
-        self.btnOk = wx.Button(parent = self.panel, id = wx.ID_OK)
+        self.btnOk = wx.Button(parent=self.panel, id=wx.ID_OK)
         self.btnOk.SetToolTipString(_("Set external format and close dialog"))
         self.btnOk.SetDefault()
-        
-        self.dsnInput = GdalSelect(parent = self, panel = self.panel,
-                                   ogr = ogr,
-                                   exclude = ['file', 'protocol'], dest = True)
+
+        self.dsnInput = GdalSelect(parent=self, panel=self.panel,
+                                   ogr=ogr,
+                                   exclude=['file', 'protocol'], dest=True)
         self.dsnInput.AttachSettings()
-        
+
         self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
         self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOk)
-        
+
         self._layout()
 
     def _layout(self):
         dialogSizer = wx.BoxSizer(wx.VERTICAL)
-        
-        dialogSizer.Add(item = self.dsnInput, proportion = 1,
-                        flag = wx.EXPAND)
 
-        btnSizer = wx.BoxSizer(orient = wx.HORIZONTAL)
-        btnSizer.Add(item = self.btnCancel, proportion = 0,
-                     flag = wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,
-                     border = 10)
-        btnSizer.Add(item = self.btnOk, proportion = 0,
-                     flag = wx.RIGHT | wx.ALIGN_CENTER,
-                     border = 10)
-        
-        dialogSizer.Add(item = btnSizer, proportion = 0,
-                        flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM | wx.TOP | wx.ALIGN_RIGHT,
-                        border = 10)
-        
+        dialogSizer.Add(item=self.dsnInput, proportion=1,
+                        flag=wx.EXPAND)
+
+        btnSizer = wx.BoxSizer(orient=wx.HORIZONTAL)
+        btnSizer.Add(item=self.btnCancel, proportion=0,
+                     flag=wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,
+                     border=10)
+        btnSizer.Add(item=self.btnOk, proportion=0,
+                     flag=wx.RIGHT | wx.ALIGN_CENTER,
+                     border=10)
+
+        dialogSizer.Add(
+            item=btnSizer,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM | wx.TOP | wx.ALIGN_RIGHT,
+            border=10)
+
         self.panel.SetAutoLayout(True)
         self.panel.SetSizer(dialogSizer)
         dialogSizer.Fit(self.panel)
 
-        size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 225, self.GetBestSize()[1] + 35)
+        size = wx.Size(
+            globalvar.DIALOG_GSELECT_SIZE[0] + 225,
+            self.GetBestSize()[1] + 35)
         self.SetMinSize(size)
         self.SetSize((size.width, size.height))
         self.Layout()
-        
+
     def OnCancel(self, event):
         self.Destroy()
-        
+
     def OnOK(self, event):
         if self.dsnInput.GetType() == 'native':
             RunCommand('v.external.out',
-                       parent = self,
-                       flags = 'r')
+                       parent=self,
+                       flags='r')
         else:
             dsn = self.dsnInput.GetDsn()
             frmt = self.dsnInput.GetFormat()
@@ -653,31 +706,41 @@
             if not dsn:
                 GMessage(_("No data source selected."), parent=self)
                 return
-            
+
             RunCommand('v.external.out',
-                       parent = self,
-                       output = dsn, format = frmt,
-                       options = options)
+                       parent=self,
+                       output=dsn, format=frmt,
+                       options=options)
         self.Close()
-        
+
+
 class DxfImportDialog(ImportDialog):
     """Dialog for bulk import of DXF layers"""
+
     def __init__(self, parent, giface):
         ImportDialog.__init__(self, parent, giface=giface, itype='dxf',
-                              title = _("Import DXF layers"))
+                              title=_("Import DXF layers"))
         self._giface = giface
-        self.dsnInput = filebrowse.FileBrowseButton(parent = self.panel, id = wx.ID_ANY, 
-                                                    size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
-                                                    dialogTitle = _('Choose DXF file to import'),
-                                                    buttonText = _('Browse'),
-                                                    startDirectory = os.getcwd(), fileMode = 0,
-                                                    changeCallback = self.OnSetDsn,
-                                                    fileMask = "DXF File (*.dxf)|*.dxf")
-        
+        self.dsnInput = filebrowse.FileBrowseButton(
+            parent=self.panel,
+            id=wx.ID_ANY,
+            size=globalvar.DIALOG_GSELECT_SIZE,
+            labelText='',
+            dialogTitle=_('Choose DXF file to import'),
+            buttonText=_('Browse'),
+            startDirectory=os.getcwd(),
+            fileMode=0,
+            changeCallback=self.OnSetDsn,
+            fileMask="DXF File (*.dxf)|*.dxf")
+
         self.add.SetLabel(_("Add imported layers into layer tree"))
-        
-        self.add.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
-        
+
+        self.add.SetValue(
+            UserSettings.Get(
+                group='cmd',
+                key='addNewLayer',
+                subkey='enabled'))
+
         self.doLayout()
 
     def _getCommand(self):
@@ -687,19 +750,19 @@
     def _getBlackListedParameters(self):
 
         return ['input', 'output', 'layers']
-    
+
     def OnRun(self, event):
         """Import/Link data (each layes as separate vector map)"""
         data = self.list.GetLayers()
         if not data:
             GMessage(_("No layers selected."), parent=self)
             return
-        
+
         # hide dialog
         self.Hide()
-        
+
         inputDxf = self.dsnInput.GetValue()
-        
+
         for layer, output, itemId in data:
 
             cmd = self.getSettingsPageCmd()
@@ -710,11 +773,11 @@
             for key in self.options.keys():
                 if self.options[key].IsChecked():
                     cmd.append('-%s' % key)
-            
-            if self.overwrite.IsChecked() or \
-                    UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'):
+
+            if self.overwrite.IsChecked() or UserSettings.Get(
+                    group='cmd', key='overwrite', subkey='enabled'):
                 cmd.append('--overwrite')
-            
+
             # run in Layer Manager
             self._giface.RunCmd(cmd, onDone=self.OnCmdDone, addLayer=False)
 
@@ -732,25 +795,25 @@
         """Input DXF file defined, update list of layer widget"""
         path = event.GetString()
         if not path:
-            return 
-        
-        data = list()        
+            return
+
+        data = list()
         ret = RunCommand('v.in.dxf',
-                         quiet = True,
-                         parent = self,
-                         read = True,
-                         flags = 'l',
-                         input = path)
+                         quiet=True,
+                         parent=self,
+                         read=True,
+                         flags='l',
+                         input=path)
         if not ret:
             self.list.LoadData()
             return
-            
+
         for line in ret.splitlines():
             layerId = line.split(':')[0].split(' ')[1]
             layerName = line.split(':')[1].strip()
             grassName = GetValidLayerName(layerName)
             data.append((layerId, layerName.strip(), grassName.strip()))
-        
+
         self.list.LoadData(data)
 
     def _getCommand(self):
@@ -768,29 +831,29 @@
 
 class RerojectionDialog(wx.Dialog):
     """ """
+
     def __init__(self, parent, giface, data,
-                 id = wx.ID_ANY, title = _("Reprojection"),
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
-        self.parent = parent    # GMFrame 
+                 id=wx.ID_ANY, title=_("Reprojection"),
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
+        self.parent = parent    # GMFrame
         self._giface = giface  # used to add layers
-        
-        wx.Dialog.__init__(self, parent, id, title, style = style,
-                           name = "MultiImportDialog")
 
+        wx.Dialog.__init__(self, parent, id, title, style=style,
+                           name="MultiImportDialog")
 
-        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
 
         # list of layers
         columns = [_('Layer id'),
                    _('Name for output GRASS map')]
 
-        self.list = GListCtrl(parent = self.panel)
+        self.list = GListCtrl(parent=self.panel)
 
         for i in range(len(columns)):
             self.list.InsertColumn(i, columns[i])
-        
+
         width = (65, 180)
-        
+
         for i in range(len(width)):
             self.list.SetColumnWidth(col=i, width=width[i])
 
@@ -798,19 +861,24 @@
 
         self.layerBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY)
 
-        self.labelText = wx.StaticText(parent=self.panel, id=wx.ID_ANY, label=_("Projection of following layers do not match with projection of current location. "))
-        
+        self.labelText = wx.StaticText(parent=self.panel, id=wx.ID_ANY, label=_(
+            "Projection of following layers do not match with projection of current location. "))
+
         label = _("Layers to be reprojected")
-        self.layerBox.SetLabel(" %s - %s " % (label, _("right click to (un)select all")))
+        self.layerBox.SetLabel(" %s - %s " %
+                               (label, _("right click to (un)select all")))
 
         #
         # buttons
         #
         # cancel
-        self.btn_close = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
+        self.btn_close = wx.Button(parent=self.panel, id=wx.ID_CANCEL)
 
         # run
-        self.btn_run = wx.Button(parent = self.panel, id = wx.ID_OK, label = _("&Import && reproject"))
+        self.btn_run = wx.Button(
+            parent=self.panel,
+            id=wx.ID_OK,
+            label=_("&Import && reproject"))
         self.btn_run.SetToolTipString(_("Reproject selected layers"))
         self.btn_run.SetDefault()
 
@@ -820,35 +888,39 @@
         """Do layout"""
         dialogSizer = wx.BoxSizer(wx.VERTICAL)
 
-        dialogSizer.Add(item = self.labelText,
-                        flag = wx.ALL | wx.EXPAND, border = 5)
-        
+        dialogSizer.Add(item=self.labelText,
+                        flag=wx.ALL | wx.EXPAND, border=5)
+
         layerSizer = wx.StaticBoxSizer(self.layerBox, wx.HORIZONTAL)
 
+        layerSizer.Add(item=self.list, proportion=1,
+                       flag=wx.ALL | wx.EXPAND, border=5)
 
-        layerSizer.Add(item = self.list, proportion = 1,
-                      flag = wx.ALL | wx.EXPAND, border = 5)
-        
-        dialogSizer.Add(item = layerSizer, proportion = 1,
-                        flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
+        dialogSizer.Add(
+            item=layerSizer,
+            proportion=1,
+            flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
+            border=5)
 
         #
         # buttons
         #
-        btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
-        
-        btnsizer.Add(item = self.btn_close, proportion = 0,
-                     flag = wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,
-                     border = 10)
-        
-        btnsizer.Add(item = self.btn_run, proportion = 0,
-                     flag = wx.RIGHT | wx.ALIGN_CENTER,
-                     border = 10)
-        
-        dialogSizer.Add(item = btnsizer, proportion = 0,
-                        flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM | wx.ALIGN_RIGHT,
-                        border = 10)
-   
+        btnsizer = wx.BoxSizer(orient=wx.HORIZONTAL)
+
+        btnsizer.Add(item=self.btn_close, proportion=0,
+                     flag=wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,
+                     border=10)
+
+        btnsizer.Add(item=self.btn_run, proportion=0,
+                     flag=wx.RIGHT | wx.ALIGN_CENTER,
+                     border=10)
+
+        dialogSizer.Add(
+            item=btnsizer,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM | wx.ALIGN_RIGHT,
+            border=10)
+
         self.panel.SetSizer(dialogSizer)
         dialogSizer.Fit(self.panel)
 

Modified: grass/trunk/gui/wxpython/modules/mapsets_picker.py
===================================================================
--- grass/trunk/gui/wxpython/modules/mapsets_picker.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/modules/mapsets_picker.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -13,15 +13,15 @@
 def main():
     app = wx.App()
 
-    dlg = MapsetAccess(parent = None)
+    dlg = MapsetAccess(parent=None)
     dlg.CenterOnScreen()
 
     if dlg.ShowModal() == wx.ID_OK:
         ms = dlg.GetMapsets()
         RunCommand('g.mapsets',
-                   parent = None,
-                   mapset = '%s' % ','.join(ms),
-                   operation = 'set')
+                   parent=None,
+                   mapset='%s' % ','.join(ms),
+                   operation='set')
 
     dlg.Destroy()
 

Modified: grass/trunk/gui/wxpython/modules/mcalc_builder.py
===================================================================
--- grass/trunk/gui/wxpython/modules/mcalc_builder.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/modules/mcalc_builder.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -22,21 +22,23 @@
 import wx
 import grass.script as grass
 
-from core             import globalvar
-from core.gcmd        import GError, RunCommand
-from core.giface      import StandaloneGrassInterface
+from core import globalvar
+from core.gcmd import GError, RunCommand
+from core.giface import StandaloneGrassInterface
 from core.utils import _
 from gui_core.gselect import Select
-from gui_core.forms   import GUI
+from gui_core.forms import GUI
 from gui_core.widgets import IntegerValidator
-from core.settings    import UserSettings
+from core.settings import UserSettings
 
+
 class MapCalcFrame(wx.Frame):
     """Mapcalc Frame class. Calculator-style window to create and run
     r(3).mapcalc statements.
     """
-    def __init__(self, parent, giface, cmd, id = wx.ID_ANY,
-                 style = wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER, **kwargs):
+
+    def __init__(self, parent, giface, cmd, id=wx.ID_ANY,
+                 style=wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER, **kwargs):
         self.parent = parent
         self._giface = giface
 
@@ -44,7 +46,7 @@
             self.log = self.parent.GetLogWindow()
         else:
             self.log = None
-        
+
         # grass command
         self.cmd = cmd
 
@@ -54,11 +56,16 @@
         if self.cmd == 'r3.mapcalc':
             self.rast3d = True
             title = _('GRASS GIS 3D Raster Map Calculator')
-            
-        wx.Frame.__init__(self, parent, id = id, title = title, **kwargs)
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
-        
-        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
+
+        wx.Frame.__init__(self, parent, id=id, title=title, **kwargs)
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass.ico'),
+                wx.BITMAP_TYPE_ICO))
+
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
         self.CreateStatusBar()
 
         #
@@ -66,47 +73,47 @@
         #
         self.heading = _('mapcalc statement')
         self.funct_dict = {
-            'abs(x)':'abs()',
-            'acos(x)':'acos()',
-            'asin(x)':'asin()',
-            'atan(x)':'atan()',
-            'atan(x,y)':'atan( , )',
-            'cos(x)':'cos()',
-            'double(x)':'double()',
-            'eval([x,y,...,]z)':'eval()',
-            'exp(x)':'exp()',
-            'exp(x,y)':'exp( , )',
-            'float(x)':'float()',
-            'graph(x,x1,y1[x2,y2..])':'graph( , , )',
-            'if(x)':'if()',
-            'if(x,a)':'if( , )',
-            'if(x,a,b)':'if( , , )',
-            'if(x,a,b,c)':'if( , , , )',
-            'int(x)':'int()',
-            'isnull(x)':'isnull()',
-            'log(x)':'log(',
-            'log(x,b)':'log( , )',
-            'max(x,y[,z...])':'max( , )',
-            'median(x,y[,z...])':'median( , )',
-            'min(x,y[,z...])':'min( , )',
-            'mode(x,y[,z...])':'mode( , )',
-            'not(x)':'not()',
-            'pow(x,y)':'pow( , )',
-            'rand(a,b)':'rand( , )',
-            'round(x)':'round()',
-            'sin(x)':'sin()',
-            'sqrt(x)':'sqrt()',
-            'tan(x)':'tan()',
-            'xor(x,y)':'xor( , )',
-            'row()':'row()',
-            'col()':'col()',
-            'x()':'x()',
-            'y()':'y()',
-            'ewres()':'ewres()',
-            'nsres()':'nsres()',
-            'null()':'null()'
-            }
-        
+            'abs(x)': 'abs()',
+            'acos(x)': 'acos()',
+            'asin(x)': 'asin()',
+            'atan(x)': 'atan()',
+            'atan(x,y)': 'atan( , )',
+            'cos(x)': 'cos()',
+            'double(x)': 'double()',
+            'eval([x,y,...,]z)': 'eval()',
+            'exp(x)': 'exp()',
+            'exp(x,y)': 'exp( , )',
+            'float(x)': 'float()',
+            'graph(x,x1,y1[x2,y2..])': 'graph( , , )',
+            'if(x)': 'if()',
+            'if(x,a)': 'if( , )',
+            'if(x,a,b)': 'if( , , )',
+            'if(x,a,b,c)': 'if( , , , )',
+            'int(x)': 'int()',
+            'isnull(x)': 'isnull()',
+            'log(x)': 'log(',
+            'log(x,b)': 'log( , )',
+            'max(x,y[,z...])': 'max( , )',
+            'median(x,y[,z...])': 'median( , )',
+            'min(x,y[,z...])': 'min( , )',
+            'mode(x,y[,z...])': 'mode( , )',
+            'not(x)': 'not()',
+            'pow(x,y)': 'pow( , )',
+            'rand(a,b)': 'rand( , )',
+            'round(x)': 'round()',
+            'sin(x)': 'sin()',
+            'sqrt(x)': 'sqrt()',
+            'tan(x)': 'tan()',
+            'xor(x,y)': 'xor( , )',
+            'row()': 'row()',
+            'col()': 'col()',
+            'x()': 'x()',
+            'y()': 'y()',
+            'ewres()': 'ewres()',
+            'nsres()': 'nsres()',
+            'null()': 'null()'
+        }
+
         if self.rast3d:
             self.funct_dict['z()'] = 'z()'
             self.funct_dict['tbres()'] = 'tbres()'
@@ -114,147 +121,189 @@
         else:
             element = 'cell'
 
-        # characters which can be in raster map name but the map name must be then quoted
+        # characters which can be in raster map name but the map name must be
+        # then quoted
         self.charactersToQuote = '+-&!<>%~?^|'
-        # stores last typed map name in Select widget to distinguish typing from selection
+        # stores last typed map name in Select widget to distinguish typing
+        # from selection
         self.lastMapName = ''
-        
-        self.operatorBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
+
+        self.operatorBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
                                         label=" %s " % _('Operators'))
-        self.outputBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
+        self.outputBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
                                       label=" %s " % _('Output'))
-        self.operandBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
+        self.operandBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
                                        label=" %s " % _('Operands'))
-        self.expressBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
+        self.expressBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
                                        label=" %s " % _('Expression'))
-        
+
         #
         # Buttons
         #
-        self.btn_clear = wx.Button(parent = self.panel, id = wx.ID_CLEAR)
-        self.btn_help = wx.Button(parent = self.panel, id = wx.ID_HELP)
-        self.btn_run = wx.Button(parent = self.panel, id = wx.ID_ANY, label = _("&Run"))
+        self.btn_clear = wx.Button(parent=self.panel, id=wx.ID_CLEAR)
+        self.btn_help = wx.Button(parent=self.panel, id=wx.ID_HELP)
+        self.btn_run = wx.Button(
+            parent=self.panel,
+            id=wx.ID_ANY,
+            label=_("&Run"))
         self.btn_run.SetForegroundColour(wx.Colour(35, 142, 35))
         self.btn_run.SetDefault()
-        self.btn_close = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
-        self.btn_save = wx.Button(parent = self.panel, id = wx.ID_SAVE)
+        self.btn_close = wx.Button(parent=self.panel, id=wx.ID_CLOSE)
+        self.btn_save = wx.Button(parent=self.panel, id=wx.ID_SAVE)
         self.btn_save.SetToolTipString(_('Save expression to file'))
-        self.btn_load = wx.Button(parent = self.panel, id = wx.ID_ANY,
-                                  label = _("&Load"))
+        self.btn_load = wx.Button(parent=self.panel, id=wx.ID_ANY,
+                                  label=_("&Load"))
         self.btn_load.SetToolTipString(_('Load expression from file'))
         self.btn_copy = wx.Button(parent=self.panel, id=wx.ID_COPY)
-        self.btn_copy.SetToolTipString(_("Copy the current command string to the clipboard"))
-        
-        self.btn = dict()        
-        self.btn['pow'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "^")
+        self.btn_copy.SetToolTipString(
+            _("Copy the current command string to the clipboard"))
+
+        self.btn = dict()
+        self.btn['pow'] = wx.Button(parent=self.panel, id=wx.ID_ANY, label="^")
         self.btn['pow'].SetToolTipString(_('exponent'))
-        self.btn['div'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "/")
+        self.btn['div'] = wx.Button(parent=self.panel, id=wx.ID_ANY, label="/")
         self.btn['div'].SetToolTipString(_('divide'))
-        self.btn['add'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "+")
+        self.btn['add'] = wx.Button(parent=self.panel, id=wx.ID_ANY, label="+")
         self.btn['add'].SetToolTipString(_('add'))
-        self.btn['minus'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "-")
+        self.btn['minus'] = wx.Button(
+            parent=self.panel, id=wx.ID_ANY, label="-")
         self.btn['minus'].SetToolTipString(_('subtract'))
-        self.btn['mod'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "%")
+        self.btn['mod'] = wx.Button(parent=self.panel, id=wx.ID_ANY, label="%")
         self.btn['mod'].SetToolTipString(_('modulus'))
-        self.btn['mult'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "*")
+        self.btn['mult'] = wx.Button(
+            parent=self.panel, id=wx.ID_ANY, label="*")
         self.btn['mult'].SetToolTipString(_('multiply'))
 
-        self.btn['parenl'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "(") 
-        self.btn['parenr'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = ")")
-        self.btn['lshift'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "<<")
+        self.btn['parenl'] = wx.Button(
+            parent=self.panel, id=wx.ID_ANY, label="(")
+        self.btn['parenr'] = wx.Button(
+            parent=self.panel, id=wx.ID_ANY, label=")")
+        self.btn['lshift'] = wx.Button(
+            parent=self.panel, id=wx.ID_ANY, label="<<")
         self.btn['lshift'].SetToolTipString(_('left shift'))
-        self.btn['rshift'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = ">>")
+        self.btn['rshift'] = wx.Button(
+            parent=self.panel, id=wx.ID_ANY, label=">>")
         self.btn['rshift'].SetToolTipString(_('right shift'))
-        self.btn['rshiftu'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = ">>>")
+        self.btn['rshiftu'] = wx.Button(
+            parent=self.panel, id=wx.ID_ANY, label=">>>")
         self.btn['rshiftu'].SetToolTipString(_('right shift (unsigned)'))
-        self.btn['gt'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = ">")
+        self.btn['gt'] = wx.Button(parent=self.panel, id=wx.ID_ANY, label=">")
         self.btn['gt'].SetToolTipString(_('greater than'))
-        self.btn['gteq'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = ">=")
+        self.btn['gteq'] = wx.Button(
+            parent=self.panel, id=wx.ID_ANY, label=">=")
         self.btn['gteq'].SetToolTipString(_('greater than or equal to'))
-        self.btn['lt'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "<")
+        self.btn['lt'] = wx.Button(parent=self.panel, id=wx.ID_ANY, label="<")
         self.btn['lt'].SetToolTipString(_('less than'))
-        self.btn['lteq'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "<=")
+        self.btn['lteq'] = wx.Button(
+            parent=self.panel, id=wx.ID_ANY, label="<=")
         self.btn['lteq'].SetToolTipString(_('less than or equal to'))
-        self.btn['eq'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "==")
+        self.btn['eq'] = wx.Button(parent=self.panel, id=wx.ID_ANY, label="==")
         self.btn['eq'].SetToolTipString(_('equal to'))
-        self.btn['noteq'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "!=")
+        self.btn['noteq'] = wx.Button(
+            parent=self.panel, id=wx.ID_ANY, label="!=")
         self.btn['noteq'].SetToolTipString(_('not equal to'))
 
-        self.btn['compl'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "~")
+        self.btn['compl'] = wx.Button(
+            parent=self.panel, id=wx.ID_ANY, label="~")
         self.btn['compl'].SetToolTipString(_('one\'s complement'))
-        self.btn['not'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "!")
+        self.btn['not'] = wx.Button(parent=self.panel, id=wx.ID_ANY, label="!")
         self.btn['not'].SetToolTipString(_('NOT'))
-        self.btn['andbit'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = '&&')
+        self.btn['andbit'] = wx.Button(
+            parent=self.panel, id=wx.ID_ANY, label='&&')
         self.btn['andbit'].SetToolTipString(_('bitwise AND'))
-        self.btn['orbit'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "|")
+        self.btn['orbit'] = wx.Button(
+            parent=self.panel, id=wx.ID_ANY, label="|")
         self.btn['orbit'].SetToolTipString(_('bitwise OR'))
-        self.btn['and'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "&&&&")
+        self.btn['and'] = wx.Button(
+            parent=self.panel, id=wx.ID_ANY, label="&&&&")
         self.btn['and'].SetToolTipString(_('logical AND'))
-        self.btn['andnull'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "&&&&&&")
+        self.btn['andnull'] = wx.Button(
+            parent=self.panel, id=wx.ID_ANY, label="&&&&&&")
         self.btn['andnull'].SetToolTipString(_('logical AND (ignores NULLs)'))
-        self.btn['or'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "||")
+        self.btn['or'] = wx.Button(parent=self.panel, id=wx.ID_ANY, label="||")
         self.btn['or'].SetToolTipString(_('logical OR'))
-        self.btn['ornull'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "|||")
+        self.btn['ornull'] = wx.Button(
+            parent=self.panel, id=wx.ID_ANY, label="|||")
         self.btn['ornull'].SetToolTipString(_('logical OR (ignores NULLs)'))
-        self.btn['cond'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "a ? b : c") 
+        self.btn['cond'] = wx.Button(
+            parent=self.panel,
+            id=wx.ID_ANY,
+            label="a ? b : c")
         self.btn['cond'].SetToolTipString(_('conditional'))
-        
+
         #
         # Text area
         #
-        self.text_mcalc = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY, size = (-1, 75),
-                                      style = wx.TE_MULTILINE)
+        self.text_mcalc = wx.TextCtrl(
+            parent=self.panel, id=wx.ID_ANY, size=(-1, 75),
+            style=wx.TE_MULTILINE)
         wx.CallAfter(self.text_mcalc.SetFocus)
-        
+
         #
         # Map and function insertion text and ComboBoxes
-        self.newmaplabel = wx.StaticText(parent = self.panel, id = wx.ID_ANY)
+        self.newmaplabel = wx.StaticText(parent=self.panel, id=wx.ID_ANY)
         if self.rast3d:
-            self.newmaplabel.SetLabel(_('Name for new 3D raster map to create'))
+            self.newmaplabel.SetLabel(
+                _('Name for new 3D raster map to create'))
         else:
             self.newmaplabel.SetLabel(_('Name for new raster map to create'))
-        self.newmaptxt = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY, size=(250, -1))
-        self.mapsellabel = wx.StaticText(parent = self.panel, id = wx.ID_ANY)
+        self.newmaptxt = wx.TextCtrl(
+            parent=self.panel, id=wx.ID_ANY, size=(250, -1))
+        self.mapsellabel = wx.StaticText(parent=self.panel, id=wx.ID_ANY)
         if self.rast3d:
             self.mapsellabel.SetLabel(_('Insert existing 3D raster map'))
         else:
             self.mapsellabel.SetLabel(_('Insert existing raster map'))
-        self.mapselect = Select(parent = self.panel, id = wx.ID_ANY, size = (250, -1),
-                                type = element, multiple = False)
-        self.functlabel = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                        label = _('Insert mapcalc function'))
-        self.function = wx.ComboBox(parent = self.panel, id = wx.ID_ANY, 
-                                    size = (250, -1), choices = sorted(self.funct_dict.keys()),
-                                    style = wx.CB_DROPDOWN |
-                                    wx.CB_READONLY | wx.TE_PROCESS_ENTER)
-        
-        self.overwrite = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
-                                     label=_("Allow output files to overwrite existing files"))
-        self.overwrite.SetValue(UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))
+        self.mapselect = Select(
+            parent=self.panel, id=wx.ID_ANY, size=(
+                250, -1), type=element, multiple=False)
+        self.functlabel = wx.StaticText(parent=self.panel, id=wx.ID_ANY,
+                                        label=_('Insert mapcalc function'))
+        self.function = wx.ComboBox(
+            parent=self.panel, id=wx.ID_ANY, size=(250, -1),
+            choices=sorted(self.funct_dict.keys()),
+            style=wx.CB_DROPDOWN | wx.CB_READONLY | wx.TE_PROCESS_ENTER)
 
-        self.randomSeed = wx.CheckBox(parent=self.panel,
-                                      label=_("Generate random seed for rand()"))
-        self.randomSeedStaticText = wx.StaticText(parent=self.panel, label=_("Seed:"))
+        self.overwrite = wx.CheckBox(
+            parent=self.panel, id=wx.ID_ANY,
+            label=_("Allow output files to overwrite existing files"))
+        self.overwrite.SetValue(
+            UserSettings.Get(
+                group='cmd',
+                key='overwrite',
+                subkey='enabled'))
+
+        self.randomSeed = wx.CheckBox(
+            parent=self.panel,
+            label=_("Generate random seed for rand()"))
+        self.randomSeedStaticText = wx.StaticText(
+            parent=self.panel, label=_("Seed:"))
         self.randomSeedText = wx.TextCtrl(parent=self.panel, size=(100, -1),
                                           validator=IntegerValidator())
-        self.randomSeedText.SetToolTipString(_("Integer seed for rand() function"))
+        self.randomSeedText.SetToolTipString(
+            _("Integer seed for rand() function"))
         self.randomSeed.SetValue(True)
         self.randomSeedStaticText.Disable()
         self.randomSeedText.Disable()
-        
 
-        self.addbox = wx.CheckBox(parent=self.panel,
-                                  label=_('Add created raster map into layer tree'), style = wx.NO_BORDER)
-        self.addbox.SetValue(UserSettings.Get(group='cmd', key='addNewLayer', subkey='enabled'))
+        self.addbox = wx.CheckBox(
+            parent=self.panel,
+            label=_('Add created raster map into layer tree'),
+            style=wx.NO_BORDER)
+        self.addbox.SetValue(
+            UserSettings.Get(
+                group='cmd',
+                key='addNewLayer',
+                subkey='enabled'))
         if not self.parent or self.parent.GetName() != 'LayerManager':
             self.addbox.Hide()
-        
+
         #
         # Bindings
         #
         for btn in self.btn.keys():
             self.btn[btn].Bind(wx.EVT_BUTTON, self.AddMark)
-        
+
         self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
         self.btn_clear.Bind(wx.EVT_BUTTON, self.OnClear)
         self.btn_run.Bind(wx.EVT_BUTTON, self.OnMCalcRun)
@@ -262,7 +311,7 @@
         self.btn_save.Bind(wx.EVT_BUTTON, self.OnSaveExpression)
         self.btn_load.Bind(wx.EVT_BUTTON, self.OnLoadExpression)
         self.btn_copy.Bind(wx.EVT_BUTTON, self.OnCopy)
-        
+
         # self.mapselect.Bind(wx.EVT_TEXT, self.OnSelectTextEvt)
         self.mapselect.Bind(wx.EVT_TEXT, self.OnSelect)
         self.function.Bind(wx.EVT_COMBOBOX, self._return_funct)
@@ -280,120 +329,123 @@
         # workaround for http://trac.wxwidgets.org/ticket/13628
         self.SetSize(self.GetBestSize())
 
-    def _return_funct(self,event):
+    def _return_funct(self, event):
         i = event.GetString()
         self._addSomething(self.funct_dict[i])
-        
+
         # reset
         win = self.FindWindowById(event.GetId())
         win.SetValue('')
-        
+
     def _layout(self):
         sizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         controlSizer = wx.BoxSizer(wx.HORIZONTAL)
         operatorSizer = wx.StaticBoxSizer(self.operatorBox, wx.HORIZONTAL)
         outOpeSizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         buttonSizer1 = wx.GridBagSizer(5, 1)
-        buttonSizer1.Add(item = self.btn['add'], pos = (0,0))
-        buttonSizer1.Add(item = self.btn['minus'], pos = (0,1))
-        buttonSizer1.Add(item = self.btn['mod'], pos = (5,0))
-        buttonSizer1.Add(item = self.btn['mult'], pos = (1,0))
-        buttonSizer1.Add(item = self.btn['div'], pos = (1,1))
-        buttonSizer1.Add(item = self.btn['pow'], pos = (5,1))
-        buttonSizer1.Add(item = self.btn['gt'], pos = (2,0))
-        buttonSizer1.Add(item = self.btn['gteq'], pos = (2,1))
-        buttonSizer1.Add(item = self.btn['eq'], pos = (4,0))
-        buttonSizer1.Add(item = self.btn['lt'], pos = (3,0))
-        buttonSizer1.Add(item = self.btn['lteq'], pos = (3,1))
-        buttonSizer1.Add(item = self.btn['noteq'], pos = (4,1))
+        buttonSizer1.Add(item=self.btn['add'], pos=(0, 0))
+        buttonSizer1.Add(item=self.btn['minus'], pos=(0, 1))
+        buttonSizer1.Add(item=self.btn['mod'], pos=(5, 0))
+        buttonSizer1.Add(item=self.btn['mult'], pos=(1, 0))
+        buttonSizer1.Add(item=self.btn['div'], pos=(1, 1))
+        buttonSizer1.Add(item=self.btn['pow'], pos=(5, 1))
+        buttonSizer1.Add(item=self.btn['gt'], pos=(2, 0))
+        buttonSizer1.Add(item=self.btn['gteq'], pos=(2, 1))
+        buttonSizer1.Add(item=self.btn['eq'], pos=(4, 0))
+        buttonSizer1.Add(item=self.btn['lt'], pos=(3, 0))
+        buttonSizer1.Add(item=self.btn['lteq'], pos=(3, 1))
+        buttonSizer1.Add(item=self.btn['noteq'], pos=(4, 1))
 
         buttonSizer2 = wx.GridBagSizer(5, 1)
-        buttonSizer2.Add(item = self.btn['and'], pos = (0,0))
-        buttonSizer2.Add(item = self.btn['andbit'], pos = (1,0))
-        buttonSizer2.Add(item = self.btn['andnull'], pos = (2,0))
-        buttonSizer2.Add(item = self.btn['or'], pos = (0,1))
-        buttonSizer2.Add(item = self.btn['orbit'], pos = (1,1))
-        buttonSizer2.Add(item = self.btn['ornull'], pos = (2,1))
-        buttonSizer2.Add(item = self.btn['lshift'], pos = (3,0))
-        buttonSizer2.Add(item = self.btn['rshift'], pos = (3,1))
-        buttonSizer2.Add(item = self.btn['rshiftu'], pos = (4,0))
-        buttonSizer2.Add(item = self.btn['cond'], pos = (5,0))
-        buttonSizer2.Add(item = self.btn['compl'], pos = (5,1))
-        buttonSizer2.Add(item = self.btn['not'], pos = (4,1))
+        buttonSizer2.Add(item=self.btn['and'], pos=(0, 0))
+        buttonSizer2.Add(item=self.btn['andbit'], pos=(1, 0))
+        buttonSizer2.Add(item=self.btn['andnull'], pos=(2, 0))
+        buttonSizer2.Add(item=self.btn['or'], pos=(0, 1))
+        buttonSizer2.Add(item=self.btn['orbit'], pos=(1, 1))
+        buttonSizer2.Add(item=self.btn['ornull'], pos=(2, 1))
+        buttonSizer2.Add(item=self.btn['lshift'], pos=(3, 0))
+        buttonSizer2.Add(item=self.btn['rshift'], pos=(3, 1))
+        buttonSizer2.Add(item=self.btn['rshiftu'], pos=(4, 0))
+        buttonSizer2.Add(item=self.btn['cond'], pos=(5, 0))
+        buttonSizer2.Add(item=self.btn['compl'], pos=(5, 1))
+        buttonSizer2.Add(item=self.btn['not'], pos=(4, 1))
 
         outputSizer = wx.StaticBoxSizer(self.outputBox, wx.VERTICAL)
-        outputSizer.Add(item = self.newmaplabel,
-                        flag = wx.ALIGN_CENTER | wx.BOTTOM | wx.TOP, border = 5)
-        outputSizer.Add(item = self.newmaptxt,
-                        flag = wx.EXPAND)
-        
+        outputSizer.Add(item=self.newmaplabel,
+                        flag=wx.ALIGN_CENTER | wx.BOTTOM | wx.TOP, border=5)
+        outputSizer.Add(item=self.newmaptxt,
+                        flag=wx.EXPAND)
+
         operandSizer = wx.StaticBoxSizer(self.operandBox, wx.HORIZONTAL)
-        
+
         buttonSizer3 = wx.GridBagSizer(7, 1)
-        buttonSizer3.Add(item = self.functlabel, pos = (0,0),
-                         span = (1,2), flag = wx.ALIGN_CENTER)
-        buttonSizer3.Add(item = self.function, pos = (1,0),
-                         span = (1,2))                         
-        buttonSizer3.Add(item = self.mapsellabel, pos = (2,0),
-                         span = (1,2), flag = wx.ALIGN_CENTER)
-        buttonSizer3.Add(item = self.mapselect, pos = (3,0),
-                         span = (1,2))
+        buttonSizer3.Add(item=self.functlabel, pos=(0, 0),
+                         span=(1, 2), flag=wx.ALIGN_CENTER)
+        buttonSizer3.Add(item=self.function, pos=(1, 0),
+                         span=(1, 2))
+        buttonSizer3.Add(item=self.mapsellabel, pos=(2, 0),
+                         span=(1, 2), flag=wx.ALIGN_CENTER)
+        buttonSizer3.Add(item=self.mapselect, pos=(3, 0),
+                         span=(1, 2))
         threebutton = wx.GridBagSizer(1, 2)
-        threebutton.Add(item = self.btn['parenl'], pos = (0,0),
-                         span = (1,1), flag = wx.ALIGN_LEFT)
-        threebutton.Add(item = self.btn['parenr'], pos = (0,1),
-                         span = (1,1), flag = wx.ALIGN_CENTER)
-        threebutton.Add(item = self.btn_clear, pos = (0,2),
-                         span = (1,1), flag = wx.ALIGN_RIGHT)
-        buttonSizer3.Add(item = threebutton, pos = (4,0),
-                         span = (1,1), flag = wx.ALIGN_CENTER)
+        threebutton.Add(item=self.btn['parenl'], pos=(0, 0),
+                        span=(1, 1), flag=wx.ALIGN_LEFT)
+        threebutton.Add(item=self.btn['parenr'], pos=(0, 1),
+                        span=(1, 1), flag=wx.ALIGN_CENTER)
+        threebutton.Add(item=self.btn_clear, pos=(0, 2),
+                        span=(1, 1), flag=wx.ALIGN_RIGHT)
+        buttonSizer3.Add(item=threebutton, pos=(4, 0),
+                         span=(1, 1), flag=wx.ALIGN_CENTER)
 
         buttonSizer4 = wx.BoxSizer(wx.HORIZONTAL)
-        buttonSizer4.Add(item = self.btn_load,
-                         flag = wx.ALL, border = 5)
-        buttonSizer4.Add(item = self.btn_save,
-                         flag = wx.ALL, border = 5)                         
-        buttonSizer4.Add(item = self.btn_copy,
-                         flag = wx.ALL, border = 5)                         
+        buttonSizer4.Add(item=self.btn_load,
+                         flag=wx.ALL, border=5)
+        buttonSizer4.Add(item=self.btn_save,
+                         flag=wx.ALL, border=5)
+        buttonSizer4.Add(item=self.btn_copy,
+                         flag=wx.ALL, border=5)
         buttonSizer4.AddSpacer(30)
-        buttonSizer4.Add(item = self.btn_help,
-                         flag = wx.ALL, border = 5)
-        buttonSizer4.Add(item = self.btn_run,
-                         flag = wx.ALL, border = 5)
-        buttonSizer4.Add(item = self.btn_close,
-                         flag = wx.ALL, border = 5)
-        
-        operatorSizer.Add(item = buttonSizer1, proportion = 0,
-                          flag = wx.ALL | wx.EXPAND, border = 5)
-        operatorSizer.Add(item = buttonSizer2, proportion = 0,
-                          flag = wx.TOP | wx.BOTTOM | wx.RIGHT | wx.EXPAND, border = 5)
-        
-        operandSizer.Add(item = buttonSizer3, proportion = 0,
-                         flag = wx.TOP | wx.BOTTOM | wx.RIGHT, border = 5)
-        
-        controlSizer.Add(item = operatorSizer, proportion = 1,
-                         flag = wx.RIGHT | wx.EXPAND, border = 5)
-        outOpeSizer.Add(item = outputSizer, proportion = 0,
-                         flag = wx.EXPAND)
-        outOpeSizer.Add(item = operandSizer, proportion = 1,
-                         flag = wx.EXPAND | wx.TOP, border = 5)
-        controlSizer.Add(item = outOpeSizer, proportion = 0,
-                         flag = wx.EXPAND)
+        buttonSizer4.Add(item=self.btn_help,
+                         flag=wx.ALL, border=5)
+        buttonSizer4.Add(item=self.btn_run,
+                         flag=wx.ALL, border=5)
+        buttonSizer4.Add(item=self.btn_close,
+                         flag=wx.ALL, border=5)
 
+        operatorSizer.Add(item=buttonSizer1, proportion=0,
+                          flag=wx.ALL | wx.EXPAND, border=5)
+        operatorSizer.Add(
+            item=buttonSizer2,
+            proportion=0,
+            flag=wx.TOP | wx.BOTTOM | wx.RIGHT | wx.EXPAND,
+            border=5)
+
+        operandSizer.Add(item=buttonSizer3, proportion=0,
+                         flag=wx.TOP | wx.BOTTOM | wx.RIGHT, border=5)
+
+        controlSizer.Add(item=operatorSizer, proportion=1,
+                         flag=wx.RIGHT | wx.EXPAND, border=5)
+        outOpeSizer.Add(item=outputSizer, proportion=0,
+                        flag=wx.EXPAND)
+        outOpeSizer.Add(item=operandSizer, proportion=1,
+                        flag=wx.EXPAND | wx.TOP, border=5)
+        controlSizer.Add(item=outOpeSizer, proportion=0,
+                         flag=wx.EXPAND)
+
         expressSizer = wx.StaticBoxSizer(self.expressBox, wx.HORIZONTAL)
-        expressSizer.Add(item = self.text_mcalc, proportion = 1,
-                         flag = wx.EXPAND)
+        expressSizer.Add(item=self.text_mcalc, proportion=1,
+                         flag=wx.EXPAND)
 
-        sizer.Add(item = controlSizer, proportion = 0,
-                  flag = wx.EXPAND | wx.ALL,
-                  border = 5)        
-        sizer.Add(item = expressSizer, proportion = 1,
-                  flag = wx.EXPAND | wx.LEFT | wx.RIGHT,
-                  border = 5)
-        sizer.Add(item = buttonSizer4, proportion = 0,
-                  flag = wx.ALIGN_RIGHT | wx.ALL, border = 3)
+        sizer.Add(item=controlSizer, proportion=0,
+                  flag=wx.EXPAND | wx.ALL,
+                  border=5)
+        sizer.Add(item=expressSizer, proportion=1,
+                  flag=wx.EXPAND | wx.LEFT | wx.RIGHT,
+                  border=5)
+        sizer.Add(item=buttonSizer4, proportion=0,
+                  flag=wx.ALIGN_RIGHT | wx.ALL, border=3)
 
         randomSizer = wx.BoxSizer(wx.HORIZONTAL)
         randomSizer.Add(item=self.randomSeed, proportion=0,
@@ -405,52 +457,78 @@
                   flag=wx.LEFT | wx.RIGHT,
                   border=5)
 
-        sizer.Add(item = self.overwrite, proportion = 0,
-                  flag = wx.LEFT | wx.RIGHT,
-                  border = 5)
+        sizer.Add(item=self.overwrite, proportion=0,
+                  flag=wx.LEFT | wx.RIGHT,
+                  border=5)
         if self.addbox.IsShown():
-            sizer.Add(item = self.addbox, proportion = 0,
-                      flag = wx.LEFT | wx.RIGHT,
-                      border = 5)
-        
+            sizer.Add(item=self.addbox, proportion=0,
+                      flag=wx.LEFT | wx.RIGHT,
+                      border=5)
+
         self.panel.SetAutoLayout(True)
         self.panel.SetSizer(sizer)
         sizer.Fit(self.panel)
-        
+
         self.Layout()
-        
-    def AddMark(self,event):
+
+    def AddMark(self, event):
         """Sends operators to insertion method
         """
-        if event.GetId() == self.btn['compl'].GetId(): mark = "~"
-        elif event.GetId() == self.btn['not'].GetId(): mark = "!"
-        elif event.GetId() == self.btn['pow'].GetId(): mark = "^"
-        elif event.GetId() == self.btn['div'].GetId(): mark = "/"
-        elif event.GetId() == self.btn['add'].GetId(): mark = "+"
-        elif event.GetId() == self.btn['minus'].GetId(): mark = "-"
-        elif event.GetId() == self.btn['mod'].GetId(): mark = "%"
-        elif event.GetId() == self.btn['mult'].GetId(): mark = "*"
-        elif event.GetId() == self.btn['lshift'].GetId(): mark = "<<"
-        elif event.GetId() == self.btn['rshift'].GetId(): mark = ">>"
-        elif event.GetId() == self.btn['rshiftu'].GetId(): mark = ">>>"
-        elif event.GetId() == self.btn['gt'].GetId(): mark = ">"
-        elif event.GetId() == self.btn['gteq'].GetId(): mark = ">="
-        elif event.GetId() == self.btn['lt'].GetId(): mark = "<"
-        elif event.GetId() == self.btn['lteq'].GetId(): mark = "<="
-        elif event.GetId() == self.btn['eq'].GetId(): mark = "=="
-        elif event.GetId() == self.btn['noteq'].GetId(): mark = "!="
-        elif event.GetId() == self.btn['andbit'].GetId(): mark = "&"
-        elif event.GetId() == self.btn['orbit'].GetId(): mark = "|"
-        elif event.GetId() == self.btn['or'].GetId(): mark =  "||"
-        elif event.GetId() == self.btn['ornull'].GetId(): mark = "|||"
-        elif event.GetId() == self.btn['and'].GetId(): mark = "&&"
-        elif event.GetId() == self.btn['andnull'].GetId(): mark = "&&&"
-        elif event.GetId() == self.btn['cond'].GetId(): mark = " ? : "
-        elif event.GetId() == self.btn['parenl'].GetId(): mark = "("
-        elif event.GetId() == self.btn['parenr'].GetId(): mark = ")"
+        if event.GetId() == self.btn['compl'].GetId():
+            mark = "~"
+        elif event.GetId() == self.btn['not'].GetId():
+            mark = "!"
+        elif event.GetId() == self.btn['pow'].GetId():
+            mark = "^"
+        elif event.GetId() == self.btn['div'].GetId():
+            mark = "/"
+        elif event.GetId() == self.btn['add'].GetId():
+            mark = "+"
+        elif event.GetId() == self.btn['minus'].GetId():
+            mark = "-"
+        elif event.GetId() == self.btn['mod'].GetId():
+            mark = "%"
+        elif event.GetId() == self.btn['mult'].GetId():
+            mark = "*"
+        elif event.GetId() == self.btn['lshift'].GetId():
+            mark = "<<"
+        elif event.GetId() == self.btn['rshift'].GetId():
+            mark = ">>"
+        elif event.GetId() == self.btn['rshiftu'].GetId():
+            mark = ">>>"
+        elif event.GetId() == self.btn['gt'].GetId():
+            mark = ">"
+        elif event.GetId() == self.btn['gteq'].GetId():
+            mark = ">="
+        elif event.GetId() == self.btn['lt'].GetId():
+            mark = "<"
+        elif event.GetId() == self.btn['lteq'].GetId():
+            mark = "<="
+        elif event.GetId() == self.btn['eq'].GetId():
+            mark = "=="
+        elif event.GetId() == self.btn['noteq'].GetId():
+            mark = "!="
+        elif event.GetId() == self.btn['andbit'].GetId():
+            mark = "&"
+        elif event.GetId() == self.btn['orbit'].GetId():
+            mark = "|"
+        elif event.GetId() == self.btn['or'].GetId():
+            mark = "||"
+        elif event.GetId() == self.btn['ornull'].GetId():
+            mark = "|||"
+        elif event.GetId() == self.btn['and'].GetId():
+            mark = "&&"
+        elif event.GetId() == self.btn['andnull'].GetId():
+            mark = "&&&"
+        elif event.GetId() == self.btn['cond'].GetId():
+            mark = " ? : "
+        elif event.GetId() == self.btn['parenl'].GetId():
+            mark = "("
+        elif event.GetId() == self.btn['parenr'].GetId():
+            mark = ")"
         self._addSomething(mark)
-        
-    ### unused
+
+    # unused
     # def OnSelectTextEvt(self, event):
     #     """Checks if user is typing or the event was emited by map selection.
     #     Prevents from changing focus.
@@ -459,14 +537,14 @@
     #     if not (abs(len(item) - len(self.lastMapName)) == 1 and \
     #         self.lastMapName in item or item in self.lastMapName):
     #         self.OnSelect(event)
-        
+
     #     self.lastMapName = item
 
     def OnSelect(self, event):
         """Gets raster map or function selection and send it to
-        insertion method. 
+        insertion method.
 
-        Checks for characters which can be in raster map name but 
+        Checks for characters which can be in raster map name but
         the raster map name must be then quoted.
         """
         win = self.FindWindowById(event.GetId())
@@ -504,7 +582,8 @@
             if self.randomSeed.IsChecked():
                 seed_flag = ' -s'
             else:
-                seed = " seed={val}".format(val=self.randomSeedText.GetValue().strip())
+                seed = " seed={val}".format(
+                    val=self.randomSeedText.GetValue().strip())
 
         return ('{cmd} "{new} = {expr}"{seed}{seed_flag}{overwrite}'
                 .format(cmd=cmd, expr=expr, new=self.newmaptxt.GetValue(),
@@ -513,11 +592,11 @@
     def _addSomething(self, what):
         """Inserts operators, map names, and functions into text area
         """
-        mcalcstr  = self.text_mcalc.GetValue()
-        position  = self.text_mcalc.GetInsertionPoint()
-        
+        mcalcstr = self.text_mcalc.GetValue()
+        position = self.text_mcalc.GetInsertionPoint()
+
         newmcalcstr = mcalcstr[:position]
-        
+
         position_offset = 0
         try:
             if newmcalcstr[-1] != ' ':
@@ -525,9 +604,9 @@
                 position_offset += 1
         except:
             pass
-        
+
         newmcalcstr += what + ' ' + mcalcstr[position:]
-        
+
         self.text_mcalc.SetValue(newmcalcstr)
         if len(what) > 0:
             match = re.search(pattern="\(.*\)", string=what)
@@ -539,25 +618,26 @@
         self.text_mcalc.SetInsertionPoint(position + position_offset)
         self.text_mcalc.Update()
         self.text_mcalc.SetFocus()
-        
-    def OnMCalcRun(self,event):
+
+    def OnMCalcRun(self, event):
         """Builds and runs r.mapcalc statement
         """
         name = self.newmaptxt.GetValue().strip()
         if not name:
-            GError(parent = self,
-                   message = _("You must enter the name of "
-                               "a new raster map to create."))
+            GError(parent=self,
+                   message=_("You must enter the name of "
+                             "a new raster map to create."))
             return
-        
-        if not (name[0] == '"' and name[-1] == '"') and any((char in name) for char in self.charactersToQuote):
+
+        if not(name[0] == '"' and name[-1] == '"') and any((char in name)
+                                                           for char in self.charactersToQuote):
             name = '"' + name + '"'
 
         expr = self.text_mcalc.GetValue().strip().replace("\n", " ")
         if not expr:
-            GError(parent = self,
-                   message = _("You must enter an expression "
-                               "to create a new raster map."))
+            GError(parent=self,
+                   message=_("You must enter an expression "
+                             "to create a new raster map."))
             return
 
         seed_flag = seed = None
@@ -576,7 +656,7 @@
                 cmd.append('--overwrite')
             cmd.append(str('expression=%s = %s' % (name, expr)))
 
-            self.log.RunCmd(cmd, onDone = self.OnDone)
+            self.log.RunCmd(cmd, onDone=self.OnDone)
             self.parent.Raise()
         else:
             if self.overwrite.IsChecked():
@@ -600,43 +680,47 @@
         """
         if event.returncode != 0:
             return
-        name = self.newmaptxt.GetValue().strip(' "') + '@' + grass.gisenv()['MAPSET']
+        name = self.newmaptxt.GetValue().strip(
+            ' "') + '@' + grass.gisenv()['MAPSET']
         ltype = 'raster'
         if self.rast3d:
             ltype = 'raster_3d'
-        self._giface.mapCreated.emit(name=name, ltype=ltype, add=self.addbox.IsChecked())
+        self._giface.mapCreated.emit(
+            name=name, ltype=ltype, add=self.addbox.IsChecked())
 
     def OnSaveExpression(self, event):
         """Saves expression to file
         """
         mctxt = self.newmaptxt.GetValue() + ' = ' + self.text_mcalc.GetValue() + os.linesep
-        
-        #dialog
-        dlg = wx.FileDialog(parent = self,
-                            message = _("Choose a file name to save the expression"),
-                            wildcard = _("Expression file (*)|*"),
-                            style = wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
+
+        # dialog
+        dlg = wx.FileDialog(
+            parent=self,
+            message=_("Choose a file name to save the expression"),
+            wildcard=_("Expression file (*)|*"),
+            style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
         if dlg.ShowModal() == wx.ID_OK:
             path = dlg.GetPath()
             if not path:
                 dlg.Destroy()
                 return
-            
+
             try:
                 fobj = open(path, 'w')
                 fobj.write(mctxt)
             finally:
                 fobj.close()
-        
+
         dlg.Destroy()
 
     def OnLoadExpression(self, event):
         """Load expression from file
         """
-        dlg = wx.FileDialog(parent = self,
-                            message = _("Choose a file name to load the expression"),
-                            wildcard = _("Expression file (*)|*"),
-                            style = wx.FD_OPEN)
+        dlg = wx.FileDialog(
+            parent=self,
+            message=_("Choose a file name to load the expression"),
+            wildcard=_("Expression file (*)|*"),
+            style=wx.FD_OPEN)
         if dlg.ShowModal() == wx.ID_OK:
             path = dlg.GetPath()
             if not path:
@@ -644,22 +728,22 @@
                 return
 
             try:
-                fobj = open(path,'r')
+                fobj = open(path, 'r')
                 mctxt = fobj.read()
             finally:
                 fobj.close()
-            
+
             try:
                 result, exp = mctxt.split('=', 1)
             except ValueError:
                 result = ''
                 exp = mctxt
-            
+
             self.newmaptxt.SetValue(result.strip())
             self.text_mcalc.SetValue(exp.strip())
             self.text_mcalc.SetFocus()
             self.text_mcalc.SetInsertionPointEnd()
-        
+
         dlg.Destroy()
 
     def OnCopy(self, event):
@@ -669,25 +753,30 @@
         if wx.TheClipboard.Open():
             wx.TheClipboard.SetData(cmddata)
             wx.TheClipboard.Close()
-            self.SetStatusText(_("'{cmd}' copied to clipboard").format(cmd=command))
+            self.SetStatusText(
+                _("'{cmd}' copied to clipboard").format(
+                    cmd=command))
 
     def OnClear(self, event):
         """Clears text area
         """
         self.text_mcalc.SetValue('')
-        
+
     def OnHelp(self, event):
         """Launches r.mapcalc help
         """
-        RunCommand('g.manual', parent = self, entry = self.cmd)
-        
-    def OnClose(self,event):
+        RunCommand('g.manual', parent=self, entry=self.cmd)
+
+    def OnClose(self, event):
         """Close window"""
         self.Destroy()
 
 if __name__ == "__main__":
-    
+
     app = wx.App(0)
-    frame = MapCalcFrame(parent = None, cmd = 'r.mapcalc', giface = StandaloneGrassInterface())
+    frame = MapCalcFrame(
+        parent=None,
+        cmd='r.mapcalc',
+        giface=StandaloneGrassInterface())
     frame.Show()
     app.MainLoop()

Modified: grass/trunk/gui/wxpython/modules/vclean.py
===================================================================
--- grass/trunk/gui/wxpython/modules/vclean.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/modules/vclean.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -19,18 +19,20 @@
 import wx
 import wx.lib.scrolledpanel as scrolled
 
-from core.gcmd        import RunCommand, GError
-from core             import globalvar
+from core.gcmd import RunCommand, GError
+from core import globalvar
 from core.utils import _
 from gui_core.gselect import Select
-from core.settings    import UserSettings
+from core.settings import UserSettings
 from grass.script import core as grass
 
 
 class VectorCleaningFrame(wx.Frame):
-    def __init__(self, parent, id=wx.ID_ANY, title=_('Set up vector cleaning tools'),
-                 style=wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER,
-                 **kwargs):
+
+    def __init__(
+            self, parent, id=wx.ID_ANY,
+        title=_('Set up vector cleaning tools'),
+            style=wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER, **kwargs):
         """
         Dialog for interactively defining vector cleaning tools
         """
@@ -49,7 +51,12 @@
         self.CreateStatusBar()
 
         # icon
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass.ico'),
+                wx.BITMAP_TYPE_ICO))
 
         self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
 
@@ -78,7 +85,7 @@
             _('remove small areas'),
             _('remove lines/boundaries of zero length'),
             _('remove small angles at nodes')
-            ]
+        ]
 
         self.tool_list = [
             'break',
@@ -94,7 +101,7 @@
             'rmarea',
             'rmline',
             'rmsa'
-            ]
+        ]
 
         self.ftype = [
             'point',
@@ -116,7 +123,7 @@
 
         # top controls
         self.inmaplabel = wx.StaticText(parent=self.panel, id=wx.ID_ANY,
-                                         label=_('Select input vector map:'))
+                                        label=_('Select input vector map:'))
         self.selectionInput = Select(parent=self.panel, id=wx.ID_ANY,
                                      size=globalvar.DIALOG_GSELECT_SIZE,
                                      type='vector')
@@ -129,13 +136,18 @@
                                          label=_('Select output vector map:'))
         self.selectionOutput = Select(parent=self.panel, id=wx.ID_ANY,
                                       size=globalvar.DIALOG_GSELECT_SIZE,
-                                      mapsets=[grass.gisenv()['MAPSET'],],
-                                      fullyQualified = False,
+                                      mapsets=[grass.gisenv()['MAPSET'], ],
+                                      fullyQualified=False,
                                       type='vector')
 
-        self.overwrite = wx.CheckBox(parent=self.panel, id=wx.ID_ANY,
-                                       label=_('Allow output files to overwrite existing files'))
-        self.overwrite.SetValue(UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))
+        self.overwrite = wx.CheckBox(
+            parent=self.panel, id=wx.ID_ANY,
+            label=_('Allow output files to overwrite existing files'))
+        self.overwrite.SetValue(
+            UserSettings.Get(
+                group='cmd',
+                key='overwrite',
+                subkey='enabled'))
 
         # cleaning tools
         self.ct_label = wx.StaticText(parent=self.panel, id=wx.ID_ANY,
@@ -155,10 +167,14 @@
 
         # Buttons
         self.btn_close = wx.Button(parent=self.panel, id=wx.ID_CLOSE)
-        self.btn_run = wx.Button(parent=self.panel, id=wx.ID_ANY, label=_("&Run"))
+        self.btn_run = wx.Button(
+            parent=self.panel,
+            id=wx.ID_ANY,
+            label=_("&Run"))
         self.btn_run.SetDefault()
         self.btn_clipboard = wx.Button(parent=self.panel, id=wx.ID_COPY)
-        self.btn_clipboard.SetToolTipString(_("Copy the current command string to the clipboard (Ctrl+C)"))
+        self.btn_clipboard.SetToolTipString(
+            _("Copy the current command string to the clipboard (Ctrl+C)"))
         self.btn_help = wx.Button(parent=self.panel, id=wx.ID_HELP)
 
         # bindings
@@ -187,10 +203,20 @@
         #
         inSizer = wx.GridBagSizer(hgap=5, vgap=5)
 
-        inSizer.Add(item=self.inmaplabel, pos=(0, 0),
-                       flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND, border=1)
-        inSizer.Add(item=self.selectionInput, pos=(1, 0),
-                       flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND, border=1)
+        inSizer.Add(
+            item=self.inmaplabel,
+            pos=(
+                0,
+                0),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND,
+            border=1)
+        inSizer.Add(
+            item=self.selectionInput,
+            pos=(
+                1,
+                0),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND,
+            border=1)
 
         self.ftype_check = [
             wx.CheckBox(parent=self.panel, id=wx.ID_ANY, label=_('point')),
@@ -199,13 +225,13 @@
             wx.CheckBox(parent=self.panel, id=wx.ID_ANY, label=_('centroid')),
             wx.CheckBox(parent=self.panel, id=wx.ID_ANY, label=_('area')),
             wx.CheckBox(parent=self.panel, id=wx.ID_ANY, label=_('face'))
-            ]
+        ]
 
         typeoptSizer = wx.BoxSizer(wx.HORIZONTAL)
         for num in range(0, self.n_ftypes):
             type_box = self.ftype_check[num]
             if self.ftype[num] in ('point', 'line', 'area'):
-                type_box.SetValue(True);
+                type_box.SetValue(True)
             typeoptSizer.Add(item=type_box, flag=wx.ALIGN_LEFT, border=1)
 
         self.ftypeSizer.Add(item=typeoptSizer,
@@ -213,10 +239,20 @@
 
         outSizer = wx.GridBagSizer(hgap=5, vgap=5)
 
-        outSizer.Add(item=self.outmaplabel, pos=(0, 0),
-                       flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND, border=1)
-        outSizer.Add(item=self.selectionOutput, pos=(1, 0),
-                       flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND, border=1)
+        outSizer.Add(
+            item=self.outmaplabel,
+            pos=(
+                0,
+                0),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND,
+            border=1)
+        outSizer.Add(
+            item=self.selectionOutput,
+            pos=(
+                1,
+                0),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND,
+            border=1)
         replaceSizer = wx.BoxSizer(wx.HORIZONTAL)
         replaceSizer.Add(item=self.overwrite, proportion=1,
                          flag=wx.ALL | wx.EXPAND, border=1)
@@ -236,10 +272,18 @@
 
         manageBoxSizer = wx.GridBagSizer(hgap=10, vgap=1)
         # start with row 1 for nicer layout
-        manageBoxSizer.Add(item=self.btn_add, pos=(1, 0), border=2, flag=wx.ALL | wx.EXPAND)
-        manageBoxSizer.Add(item=self.btn_remove, pos=(2, 0), border=2, flag=wx.ALL | wx.EXPAND)
-        manageBoxSizer.Add(item=self.btn_moveup, pos=(3, 0), border=2, flag=wx.ALL | wx.EXPAND)
-        manageBoxSizer.Add(item=self.btn_movedown, pos=(4, 0), border=2, flag=wx.ALL | wx.EXPAND)
+        manageBoxSizer.Add(
+            item=self.btn_add, pos=(1, 0),
+            border=2, flag=wx.ALL | wx.EXPAND)
+        manageBoxSizer.Add(
+            item=self.btn_remove, pos=(2, 0),
+            border=2, flag=wx.ALL | wx.EXPAND)
+        manageBoxSizer.Add(
+            item=self.btn_moveup, pos=(3, 0),
+            border=2, flag=wx.ALL | wx.EXPAND)
+        manageBoxSizer.Add(
+            item=self.btn_movedown, pos=(4, 0),
+            border=2, flag=wx.ALL | wx.EXPAND)
 
         bodySizer.Add(item=manageBoxSizer, pos=(1, 2),
                       flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5)
@@ -272,14 +316,14 @@
                   flag=wx.ALL | wx.EXPAND, border=5)
 
         sizer.Add(item=wx.StaticLine(parent=self, id=wx.ID_ANY,
-                  style=wx.LI_HORIZONTAL), proportion=0,
+                                     style=wx.LI_HORIZONTAL), proportion=0,
                   flag=wx.EXPAND | wx.ALL, border=5)
 
         sizer.Add(item=bodySizer, proportion=1,
                   flag=wx.ALL | wx.EXPAND, border=5)
 
         sizer.Add(item=wx.StaticLine(parent=self, id=wx.ID_ANY,
-                  style=wx.LI_HORIZONTAL), proportion=0,
+                                     style=wx.LI_HORIZONTAL), proportion=0,
                   flag=wx.EXPAND | wx.ALL, border=5)
 
         sizer.Add(item=btnSizer, proportion=0,
@@ -317,13 +361,16 @@
                                 wx.CB_READONLY | wx.TE_PROCESS_ENTER)
         self.Bind(wx.EVT_COMBOBOX, self.OnSetTool, tool_cbox)
         # threshold
-        txt_ctrl = wx.TextCtrl(parent=self.ct_panel, id=2000 + num, value='0.00',
-                               size=(100, -1),
-                               style=wx.TE_NOHIDESEL)
+        txt_ctrl = wx.TextCtrl(
+            parent=self.ct_panel, id=2000 + num, value='0.00', size=(100, -1),
+            style=wx.TE_NOHIDESEL)
         self.Bind(wx.EVT_TEXT, self.OnThreshValue, txt_ctrl)
 
         # select with tool number
-        select = wx.CheckBox(parent=self.ct_panel, id=num, label=str(num) + '.')
+        select = wx.CheckBox(
+            parent=self.ct_panel,
+            id=num,
+            label=str(num) + '.')
         select.SetValue(False)
         self.Bind(wx.EVT_CHECKBOX, self.OnSelect, select)
 
@@ -350,7 +397,9 @@
             self.FindWindowById(id + 1000).SetValue('')
             self.toolslines[id]['tool_desc'] = ''
             self.toolslines[id]['tool'] = ''
-            self.SetStatusText(_("%s. cleaning tool removed, will be ignored") % id)
+            self.SetStatusText(
+                _("%s. cleaning tool removed, will be ignored") %
+                id)
         else:
             self.SetStatusText(_("Please select a cleaning tool to remove"))
 
@@ -364,7 +413,10 @@
             up_toolline = self.toolslines[id_up]
 
             self.FindWindowById(id_up).SetValue(True)
-            self.FindWindowById(id_up + 1000).SetValue(this_toolline['tool_desc'])
+            self.FindWindowById(
+                id_up +
+                1000).SetValue(
+                this_toolline['tool_desc'])
             self.FindWindowById(id_up + 2000).SetValue(this_toolline['thresh'])
             self.toolslines[id_up] = this_toolline
 
@@ -390,8 +442,14 @@
             down_toolline = self.toolslines[id_down]
 
             self.FindWindowById(id_down).SetValue(True)
-            self.FindWindowById(id_down + 1000).SetValue(this_toolline['tool_desc'])
-            self.FindWindowById(id_down + 2000).SetValue(this_toolline['thresh'])
+            self.FindWindowById(
+                id_down +
+                1000).SetValue(
+                this_toolline['tool_desc'])
+            self.FindWindowById(
+                id_down +
+                2000).SetValue(
+                this_toolline['thresh'])
             self.toolslines[id_down] = this_toolline
 
             self.FindWindowById(id).SetValue(False)
@@ -414,7 +472,11 @@
         self.toolslines[tool_no]['tool_desc'] = self.tool_desc_list[num]
         self.toolslines[tool_no]['tool'] = self.tool_list[num]
 
-        self.SetStatusText(str(tool_no) + '. ' + _("cleaning tool: '%s'") % (self.tool_list[num]))
+        self.SetStatusText(
+            str(tool_no) +
+            '. ' +
+            _("cleaning tool: '%s'") %
+            (self.tool_list[num]))
 
     def OnThreshValue(self, event):
         """Threshold value was entered"""
@@ -422,10 +484,11 @@
         num = id - 2000
         self.toolslines[num]['thresh'] = self.FindWindowById(id).GetValue()
 
-        self.SetStatusText(_("Threshold for %(num)s. tool '%(tool)s': %(thresh)s") % \
-                           {'num': num,
-                            'tool': self.toolslines[num]['tool'],
-                            'thresh': self.toolslines[num]['thresh']})
+        self.SetStatusText(
+            _("Threshold for %(num)s. tool '%(tool)s': %(thresh)s") % {
+                'num': num,
+                'tool': self.toolslines[num]['tool'],
+                'thresh': self.toolslines[num]['thresh']})
 
     def OnSelect(self, event):
         """Tool was selected"""
@@ -467,10 +530,10 @@
 
         if self.log:
             cmd = [self.cmd,
-                  'input=%s' % self.inmap,
-                  'output=%s' % self.outmap,
-                  'tool=%s' % self.tools_string,
-                  'thres=%s' % self.thresh_string]
+                   'input=%s' % self.inmap,
+                   'output=%s' % self.outmap,
+                   'tool=%s' % self.tools_string,
+                   'thres=%s' % self.thresh_string]
             if self.ftype_string:
                 cmd.append('type=%s' % self.ftype_string)
             if self.overwrite.IsChecked():
@@ -509,8 +572,8 @@
         self.GetCmdStrings()
         cmdstring = '%s' % (self.cmd)
         # list -> string
-        cmdstring += ' input=%s output=%s type=%s tool=%s thres=%s' % \
-                     (self.inmap, self.outmap, self.ftype_string, self.tools_string, self.thresh_string)
+        cmdstring += ' input=%s output=%s type=%s tool=%s thres=%s' % (
+            self.inmap, self.outmap, self.ftype_string, self.tools_string, self.thresh_string)
         if self.overwrite.IsChecked():
             cmdstring += ' --overwrite'
 
@@ -518,7 +581,8 @@
         if wx.TheClipboard.Open():
             wx.TheClipboard.SetData(cmddata)
             wx.TheClipboard.Close()
-            self.SetStatusText(_("Vector cleaning command copied to clipboard"))
+            self.SetStatusText(
+                _("Vector cleaning command copied to clipboard"))
 
     def GetCmdStrings(self):
         self.tools_string = ''
@@ -545,7 +609,8 @@
                     first = 0
                 else:
                     self.tools_string += ',%s' % self.toolslines[num]['tool']
-                    self.thresh_string += ',%s' % self.toolslines[num]['thresh']
+                    self.thresh_string += ',%s' % self.toolslines[
+                        num]['thresh']
 
         self.inmap = self.selectionInput.GetValue()
         self.outmap = self.selectionOutput.GetValue()

Modified: grass/trunk/gui/wxpython/modules/vkrige.py
===================================================================
--- grass/trunk/gui/wxpython/modules/vkrige.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/modules/vkrige.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -16,15 +16,16 @@
 
 #@TODO move here imports related to wxGUI
 
-### generic imports
-import os, sys
+# generic imports
+import os
+import sys
 from tempfile import gettempdir
 import time
 import thread
 from core.utils import _
 
-### dependencies to be checked once, as they are quite
-### time-consuming. cfr. grass.parser.
+# dependencies to be checked once, as they are quite
+# time-consuming. cfr. grass.parser.
 
 try:
     import grass.script as grass
@@ -41,142 +42,241 @@
 #import help
 
 import wx
-#import wx.lib.plot as plot # for plotting the variogram.
+# import wx.lib.plot as plot # for plotting the variogram.
 import rpy2.robjects as robjects
 import rpy2.rinterface as rinterface
 
 # global variables
-maxint = 1e6 # instead of sys.maxint, not working with SpinCtrl on 64bit [reported by Bob Moskovitz]
+# instead of sys.maxint, not working with SpinCtrl on 64bit [reported by
+# Bob Moskovitz]
+maxint = 1e6
 
 #@TODO move away functions not regarding the GUI
 
+
 class KrigingPanel(wx.Panel):
     """Main panel. Contains all widgets except Menus and Statusbar. """
+
     def __init__(self, parent, Rinstance, controller, *args, **kwargs):
         wx.Panel.__init__(self, parent, *args, **kwargs)
-        
-        self.parent = parent 
+
+        self.parent = parent
         self.border = 4
-        
-        #    1. Input data 
-        InputBoxSizer = wx.StaticBoxSizer(wx.StaticBox(self, id = wx.ID_ANY, label = _("Input Data")), 
-                                          orient = wx.HORIZONTAL)
-        
-        flexSizer = wx.FlexGridSizer(cols = 3, hgap = 5, vgap = 5)
+
+        #    1. Input data
+        InputBoxSizer = wx.StaticBoxSizer(
+            wx.StaticBox(
+                self,
+                id=wx.ID_ANY,
+                label=_("Input Data")),
+            orient=wx.HORIZONTAL)
+
+        flexSizer = wx.FlexGridSizer(cols=3, hgap=5, vgap=5)
         flexSizer.AddGrowableCol(1)
 
-        flexSizer.Add(item = wx.StaticText(self, id = wx.ID_ANY, label = _("Point dataset:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        self.InputDataMap = gselect.VectorSelect(parent = self,
-                                                 ftype = 'points',
-                                                 updateOnPopup = False)
+        flexSizer.Add(
+            item=wx.StaticText(
+                self,
+                id=wx.ID_ANY,
+                label=_("Point dataset:")),
+            flag=wx.ALIGN_CENTER_VERTICAL)
+        self.InputDataMap = gselect.VectorSelect(parent=self,
+                                                 ftype='points',
+                                                 updateOnPopup=False)
         self.InputDataMap.SetFocus()
-        flexSizer.Add(item = self.InputDataMap, flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        RefreshButton = wx.Button(self, id = wx.ID_REFRESH)
+        flexSizer.Add(item=self.InputDataMap, flag=wx.ALIGN_CENTER_VERTICAL)
+
+        RefreshButton = wx.Button(self, id=wx.ID_REFRESH)
         RefreshButton.Bind(wx.EVT_BUTTON, self.OnButtonRefresh)
-        flexSizer.Add(item = RefreshButton, flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        flexSizer.Add(item = wx.StaticText(self, id = wx.ID_ANY, label = _("Numeric column:")),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        self.InputDataColumn = gselect.ColumnSelect(self, id = wx.ID_ANY)
-        flexSizer.Add(item = self.InputDataColumn)
-        
-        self.InputDataMap.GetChildren()[0].Bind(wx.EVT_TEXT, self.OnInputMapChanged)
-        self.InputDataColumn.GetChildren()[0].Bind(wx.EVT_TEXT, self.OnInputColumnChanged)
-        
-        InputBoxSizer.Add(item = flexSizer)
-        
-        #    2. Kriging. In book pages one for each R package. Includes variogram fit.
-        KrigingSizer = wx.StaticBoxSizer(wx.StaticBox(self, id = wx.ID_ANY, label = _("Kriging")), wx.HORIZONTAL)
+        flexSizer.Add(item=RefreshButton, flag=wx.ALIGN_CENTER_VERTICAL)
 
-        self.RPackagesBook = GNotebook(parent = self, style = globalvar.FNPageDStyle)
-        
-        for Rpackage in ["gstat"]: # , "geoR"]: #@TODO: enable it if/when it'll be implemented.
-            self.CreatePage(package = Rpackage, Rinstance = Rinstance, controller = controller)
-        
-        ## Command output. From menuform module, cmdPanel class
-        self._gconsole = gconsole.GConsole(guiparent = self)
-        self.goutput = goutput.GConsoleWindow(parent = self, gconsole = self._gconsole, margin = False)
+        flexSizer.Add(
+            item=wx.StaticText(
+                self,
+                id=wx.ID_ANY,
+                label=_("Numeric column:")),
+            flag=wx.ALIGN_CENTER_VERTICAL)
+        self.InputDataColumn = gselect.ColumnSelect(self, id=wx.ID_ANY)
+        flexSizer.Add(item=self.InputDataColumn)
+
+        self.InputDataMap.GetChildren()[0].Bind(
+            wx.EVT_TEXT, self.OnInputMapChanged)
+        self.InputDataColumn.GetChildren()[0].Bind(
+            wx.EVT_TEXT, self.OnInputColumnChanged)
+
+        InputBoxSizer.Add(item=flexSizer)
+
+        # 2. Kriging. In book pages one for each R package. Includes variogram
+        # fit.
+        KrigingSizer = wx.StaticBoxSizer(
+            wx.StaticBox(
+                self,
+                id=wx.ID_ANY,
+                label=_("Kriging")),
+            wx.HORIZONTAL)
+
+        self.RPackagesBook = GNotebook(
+            parent=self, style=globalvar.FNPageDStyle)
+
+        # , "geoR"]: #@TODO: enable it if/when it'll be implemented.
+        for Rpackage in ["gstat"]:
+            self.CreatePage(
+                package=Rpackage,
+                Rinstance=Rinstance,
+                controller=controller)
+
+        # Command output. From menuform module, cmdPanel class
+        self._gconsole = gconsole.GConsole(guiparent=self)
+        self.goutput = goutput.GConsoleWindow(
+            parent=self, gconsole=self._gconsole, margin=False)
         self.goutputId = self.RPackagesBook.GetPageCount()
-        self.outpage = self.RPackagesBook.AddPage(page = self.goutput, text = _("Command output"), name = 'output')
-        self._gconsole.Bind(gconsole.EVT_CMD_RUN,
-                            lambda event:
-                                self._switchPageHandler(event=event, notification=Notification.MAKE_VISIBLE))
-        self._gconsole.Bind(gconsole.EVT_CMD_DONE,
-                            lambda event:
-                                self._switchPageHandler(event=event, notification=Notification.RAISE_WINDOW))
+        self.outpage = self.RPackagesBook.AddPage(
+            page=self.goutput, text=_("Command output"), name='output')
+        self._gconsole.Bind(
+            gconsole.EVT_CMD_RUN,
+            lambda event: self._switchPageHandler(
+                event=event,
+                notification=Notification.MAKE_VISIBLE))
+        self._gconsole.Bind(
+            gconsole.EVT_CMD_DONE,
+            lambda event: self._switchPageHandler(
+                event=event,
+                notification=Notification.RAISE_WINDOW))
         self.RPackagesBook.SetSelection(0)
-        KrigingSizer.Add(self.RPackagesBook, proportion = 1, flag = wx.EXPAND)
-        
+        KrigingSizer.Add(self.RPackagesBook, proportion=1, flag=wx.EXPAND)
+
         #    3. Output Parameters.
-        OutputSizer = wx.StaticBoxSizer(wx.StaticBox(self, id = wx.ID_ANY, label = _("Output")), wx.HORIZONTAL)
-        
-        OutputParameters = wx.GridBagSizer(hgap = 5, vgap = 5)
-        OutputParameters.Add(item = wx.StaticText(self, id = wx.ID_ANY, label = _("Name for the output raster map:")),
-                             flag = wx.ALIGN_CENTER_VERTICAL,
-                             pos = (0, 0))
-        self.OutputMapName = gselect.Select(parent = self, id = wx.ID_ANY,
-                                            type = 'raster',
-                                            mapsets = [grass.gisenv()['MAPSET']])
-        OutputParameters.Add(item = self.OutputMapName, flag = wx.EXPAND | wx.ALL,
-                             pos = (0, 1))
-        self.VarianceRasterCheckbox = wx.CheckBox(self, id = wx.ID_ANY, label = _("Export variance map as well: "))
-        self.VarianceRasterCheckbox.SetValue(state = True)
-        OutputParameters.Add(item = self.VarianceRasterCheckbox,
-                             flag = wx.ALIGN_CENTER_VERTICAL,
-                             pos = (1, 0))
-        self.OutputVarianceMapName = gselect.Select(parent = self, id = wx.ID_ANY,
-                                            type = 'raster',
-                                            mapsets = [grass.gisenv()['MAPSET']])
-        self.VarianceRasterCheckbox.Bind(wx.EVT_CHECKBOX, self.OnVarianceCBChecked)
-        OutputParameters.Add(item = self.OutputVarianceMapName, flag = wx.EXPAND | wx.ALL,
-                             pos = (1, 1))
-        
-        self.OverwriteCheckBox = wx.CheckBox(self, id = wx.ID_ANY,
-                                             label = _("Allow output files to overwrite existing files"))
-        self.OverwriteCheckBox.SetValue(UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))
-        OutputParameters.Add(item = self.OverwriteCheckBox,
-                             pos = (2, 0), span = (1, 2))
-        
+        OutputSizer = wx.StaticBoxSizer(
+            wx.StaticBox(
+                self,
+                id=wx.ID_ANY,
+                label=_("Output")),
+            wx.HORIZONTAL)
+
+        OutputParameters = wx.GridBagSizer(hgap=5, vgap=5)
+        OutputParameters.Add(
+            item=wx.StaticText(
+                self, id=wx.ID_ANY,
+                label=_("Name for the output raster map:")),
+            flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 0))
+        self.OutputMapName = gselect.Select(parent=self, id=wx.ID_ANY,
+                                            type='raster',
+                                            mapsets=[grass.gisenv()['MAPSET']])
+        OutputParameters.Add(item=self.OutputMapName, flag=wx.EXPAND | wx.ALL,
+                             pos=(0, 1))
+        self.VarianceRasterCheckbox = wx.CheckBox(
+            self, id=wx.ID_ANY, label=_("Export variance map as well: "))
+        self.VarianceRasterCheckbox.SetValue(state=True)
+        OutputParameters.Add(item=self.VarianceRasterCheckbox,
+                             flag=wx.ALIGN_CENTER_VERTICAL,
+                             pos=(1, 0))
+        self.OutputVarianceMapName = gselect.Select(
+            parent=self, id=wx.ID_ANY, type='raster',
+            mapsets=[grass.gisenv()['MAPSET']])
+        self.VarianceRasterCheckbox.Bind(
+            wx.EVT_CHECKBOX, self.OnVarianceCBChecked)
+        OutputParameters.Add(
+            item=self.OutputVarianceMapName,
+            flag=wx.EXPAND | wx.ALL,
+            pos=(
+                1,
+                1))
+
+        self.OverwriteCheckBox = wx.CheckBox(self, id=wx.ID_ANY, label=_(
+            "Allow output files to overwrite existing files"))
+        self.OverwriteCheckBox.SetValue(
+            UserSettings.Get(
+                group='cmd',
+                key='overwrite',
+                subkey='enabled'))
+        OutputParameters.Add(item=self.OverwriteCheckBox,
+                             pos=(2, 0), span=(1, 2))
+
         OutputParameters.AddGrowableCol(1)
-        OutputSizer.Add(OutputParameters, proportion = 0, flag = wx.EXPAND | wx.ALL, border = self.border)
-        
+        OutputSizer.Add(
+            OutputParameters,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=self.border)
+
         #    4. Run Button and Quit Button
         ButtonSizer = wx.BoxSizer(wx.HORIZONTAL)
-        HelpButton = wx.Button(self, id = wx.ID_HELP)
+        HelpButton = wx.Button(self, id=wx.ID_HELP)
         HelpButton.Bind(wx.EVT_BUTTON, self.OnHelpButton)
-        QuitButton = wx.Button(self, id = wx.ID_EXIT)
+        QuitButton = wx.Button(self, id=wx.ID_EXIT)
         QuitButton.Bind(wx.EVT_BUTTON, self.OnCloseWindow)
-        self.RunButton = wx.Button(self, id = wx.ID_ANY, label = _("&Run")) # no stock ID for Run button.. 
+        # no stock ID for Run button..
+        self.RunButton = wx.Button(self, id=wx.ID_ANY, label=_("&Run"))
         self.RunButton.Bind(wx.EVT_BUTTON, self.OnRunButton)
-        self.RunButton.Enable(False) # disable it on loading the interface, as input map is not set
-        ButtonSizer.Add(HelpButton, proportion = 0, flag = wx.ALIGN_LEFT | wx.ALL, border = self.border)
-        ButtonSizer.Add(QuitButton, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = self.border)
-        ButtonSizer.Add(self.RunButton, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = self.border)
-        
+        # disable it on loading the interface, as input map is not set
+        self.RunButton.Enable(False)
+        ButtonSizer.Add(
+            HelpButton,
+            proportion=0,
+            flag=wx.ALIGN_LEFT | wx.ALL,
+            border=self.border)
+        ButtonSizer.Add(
+            QuitButton,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT | wx.ALL,
+            border=self.border)
+        ButtonSizer.Add(
+            self.RunButton,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT | wx.ALL,
+            border=self.border)
+
         #    Main Sizer. Add each child sizer as soon as it is ready.
         Sizer = wx.BoxSizer(wx.VERTICAL)
-        Sizer.Add(InputBoxSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = self.border)
-        Sizer.Add(KrigingSizer, proportion = 1, flag = wx.EXPAND | wx.ALL, border = self.border)
-        Sizer.Add(OutputSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = self.border)
-        Sizer.Add(ButtonSizer, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = self.border)
+        Sizer.Add(
+            InputBoxSizer,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=self.border)
+        Sizer.Add(
+            KrigingSizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=self.border)
+        Sizer.Add(
+            OutputSizer,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=self.border)
+        Sizer.Add(
+            ButtonSizer,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT | wx.ALL,
+            border=self.border)
         self.SetSizerAndFit(Sizer)
-        
+
         # last action of __init__: update imput data list.
         # it's performed in the few seconds gap while user examines interface before clicking anything.
         #@TODO: implement a splashcreen IF the maps cause a noticeable lag [markus' suggestion]
         self.InputDataMap.GetElementList()
-        
+
     def CreatePage(self, package, Rinstance, controller):
         """Creates the three notebook pages, one for each R package """
-        for package in ["gstat"]: #@TODO add here other packages when they will be implemented
-            classobj = eval("RBook"+package+"Panel")
-            setattr(self, "RBook"+package+"Panel", (classobj(self,
-                                                             id = wx.ID_ANY,
-                                                             Rinstance = Rinstance,
-                                                             controller = controller)))
-            self.RPackagesBook.AddPage(page = getattr(self, "RBook"+package+"Panel"), text = package)
+        for package in [
+                "gstat"]:  # @TODO add here other packages when they will be implemented
+            classobj = eval("RBook" + package + "Panel")
+            setattr(
+                self,
+                "RBook" +
+                package +
+                "Panel",
+                (classobj(
+                    self,
+                    id=wx.ID_ANY,
+                    Rinstance=Rinstance,
+                    controller=controller)))
+            self.RPackagesBook.AddPage(
+                page=getattr(
+                    self,
+                    "RBook" +
+                    package +
+                    "Panel"),
+                text=package)
 
     def OnButtonRefresh(self, event):
         """Forces refresh of list of available layers. """
@@ -188,15 +288,15 @@
         event.Skip()
 
     def OnHelpButton(self, event):
-        grass.run_command('g.manual', entry = 'v.krige')
+        grass.run_command('g.manual', entry='v.krige')
         event.Skip()
 
     def OnInputMapChanged(self, event):
         """Refreshes list of columns."""
         MapName = event.GetString()
-        self.InputDataColumn.InsertColumns(vector = MapName,
-                                   layer = 1, excludeKey = False,
-                                   type = ['integer', 'double precision'])
+        self.InputDataColumn.InsertColumns(
+            vector=MapName, layer=1, excludeKey=False,
+            type=['integer', 'double precision'])
 
     def OnInputColumnChanged(self, event):
         """Fills output map name TextCtrl """
@@ -204,51 +304,77 @@
         enable = bool(self.InputDataColumn.GetValue())
         self.RunButton.Enable(enable)
         self.RBookgstatPanel.PlotButton.Enable(enable)
-        
+
         if enable:
-            self.OutputMapName.SetValue(MapName.split("@")[0]+"_kriging")
-            self.OutputVarianceMapName.SetValue(MapName.split("@")[0]+"_kriging.var")
+            self.OutputMapName.SetValue(MapName.split("@")[0] + "_kriging")
+            self.OutputVarianceMapName.SetValue(
+                MapName.split("@")[0] + "_kriging.var")
         else:
             self.OutputMapName.SetValue('')
             self.OutputVarianceMapName.SetValue('')
-        
-    def OnRunButton(self,event):
+
+    def OnRunButton(self, event):
         """Execute R analysis. """
         #@FIXME: send data to main method instead of running it here.
-        
+
         #-1: get the selected notebook page. The user shall know that [s]he can modify settings in all
-        # pages, but only the selected one will be executed when Run is pressed.
+        # pages, but only the selected one will be executed when Run is
+        # pressed.
         SelectedPanel = self.RPackagesBook.GetCurrentPage()
-        
-        if self.RPackagesBook.GetPageText(self.RPackagesBook.GetSelection()) == 'Command output':
-            self._gconsole.WriteError("No parameters for running. Please select \"gstat\" tab, check parameters and re-run.")
-            return False # no break invoked by above function
-        
+
+        if self.RPackagesBook.GetPageText(
+                self.RPackagesBook.GetSelection()) == 'Command output':
+            self._gconsole.WriteError(
+                "No parameters for running. Please select \"gstat\" tab, check parameters and re-run.")
+            return False  # no break invoked by above function
+
         # mount command string as it would have been written on CLI
-        command = ["v.krige", "input=" + self.InputDataMap.GetValue(),
-                   "column=" + self.InputDataColumn.GetValue(),
-                   "output=" + self.OutputMapName.GetValue(), 
-                   "package=" + '%s' % self.RPackagesBook.GetPageText(self.RPackagesBook.GetSelection())]
-        
-        if not hasattr(SelectedPanel, 'VariogramCheckBox') or not SelectedPanel.VariogramCheckBox.IsChecked():
-            command.append("model=" + '%s' % SelectedPanel.ModelChoicebox.GetStringSelection().split(" ")[0])
-            
+        command = [
+            "v.krige",
+            "input=" +
+            self.InputDataMap.GetValue(),
+            "column=" +
+            self.InputDataColumn.GetValue(),
+            "output=" +
+            self.OutputMapName.GetValue(),
+            "package=" +
+            '%s' %
+            self.RPackagesBook.GetPageText(
+                self.RPackagesBook.GetSelection())]
+
+        if not hasattr(
+                SelectedPanel, 'VariogramCheckBox') or not SelectedPanel.VariogramCheckBox.IsChecked():
+            command.append(
+                "model=" + '%s' %
+                SelectedPanel.ModelChoicebox.GetStringSelection().split(" ")[0])
+
         for i in ['Sill', 'Nugget', 'Range', 'Kappa']:
-            if getattr(SelectedPanel, i+"ChextBox").IsChecked():
-                command.append(i.lower() + "=" + '%s' % getattr(SelectedPanel, i+'Ctrl').GetValue())
-        
+            if getattr(SelectedPanel, i + "ChextBox").IsChecked():
+                command.append(
+                    i.lower() +
+                    "=" +
+                    '%s' %
+                    getattr(
+                        SelectedPanel,
+                        i +
+                        'Ctrl').GetValue())
+
         if SelectedPanel.KrigingRadioBox.GetStringSelection() == "Block kriging":
-            command.append("block=" + '%s' % SelectedPanel.BlockSpinBox.GetValue())
+            command.append(
+                "block=" + '%s' %
+                SelectedPanel.BlockSpinBox.GetValue())
         if self.OverwriteCheckBox.IsChecked():
             command.append("--overwrite")
         if self.VarianceRasterCheckbox.IsChecked():
-            command.append("output_var=" + self.OutputVarianceMapName.GetValue())
-        
+            command.append(
+                "output_var=" +
+                self.OutputVarianceMapName.GetValue())
+
         # give it to the output console
         #@FIXME: it runs the command as a NEW instance. Reimports data, recalculates variogram fit..
-        #otherwise I can use Controller() and mimic RunCmd behaviour.
+        # otherwise I can use Controller() and mimic RunCmd behaviour.
         self._gconsole.RunCmd(command)
-    
+
     def OnVarianceCBChecked(self, event):
         self.OutputVarianceMapName.Enable(event.IsChecked())
 
@@ -270,21 +396,29 @@
 
 class KrigingModule(wx.Frame):
     """Kriging module for GRASS GIS. Depends on R and its packages gstat and geoR. """
+
     def __init__(self, parent, Rinstance, controller, *args, **kwargs):
         wx.Frame.__init__(self, parent, *args, **kwargs)
         # setting properties and all widgettery
         self.SetTitle(_("Kriging Module"))
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass_dialog.ico'), wx.BITMAP_TYPE_ICO))
-        self.log = Log(self) 
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass_dialog.ico'),
+                wx.BITMAP_TYPE_ICO))
+        self.log = Log(self)
         self.CreateStatusBar()
         self.log.message(_("Ready."))
-        
+
         self.Panel = KrigingPanel(self, Rinstance, controller)
         self.SetMinSize(self.GetBestSize())
         self.SetSize(self.GetBestSize())
-    
+
+
 class Log:
     """The log output is redirected to the status bar of the containing frame. """
+
     def __init__(self, parent):
         self.parent = parent
 
@@ -292,214 +426,289 @@
         """Updates status bar """
         self.parent.SetStatusText(text_string.strip())
 
+
 class RBookPanel(wx.Panel):
     """Generic notebook page with shared widgets and empty kriging functions. """
+
     def __init__(self, parent, *args, **kwargs):
         wx.Panel.__init__(self, parent, *args, **kwargs)
-        
+
         self.parent = parent
-        
-        self.VariogramSizer = wx.StaticBoxSizer(wx.StaticBox(self,
-                                                             id = wx.ID_ANY, 
-                                                             label = _("Variogram fitting")),
-                                                wx.HORIZONTAL)
+
+        self.VariogramSizer = wx.StaticBoxSizer(
+            wx.StaticBox(
+                self,
+                id=wx.ID_ANY,
+                label=_("Variogram fitting")),
+            wx.HORIZONTAL)
         self.LeftSizer = wx.BoxSizer(wx.VERTICAL)
         self.RightSizer = wx.BoxSizer(wx.VERTICAL)
-        self.ParametersSizer = wx.GridBagSizer(vgap = 5, hgap = 5)
+        self.ParametersSizer = wx.GridBagSizer(vgap=5, hgap=5)
 
-        self.VariogramSizer.Add(self.LeftSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = parent.border)
-        self.VariogramSizer.Add(self.RightSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = parent.border)
-        
+        self.VariogramSizer.Add(
+            self.LeftSizer,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=parent.border)
+        self.VariogramSizer.Add(
+            self.RightSizer,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=parent.border)
+
         # left side of Variogram fitting. The checkboxes and spinctrls.
-        self.PlotButton = wx.Button(self, id = wx.ID_ANY, label = _("Plot/refresh variogram")) # no stock ID for Run button.. 
+        # no stock ID for Run button..
+        self.PlotButton = wx.Button(
+            self, id=wx.ID_ANY, label=_("Plot/refresh variogram"))
         self.PlotButton.Bind(wx.EVT_BUTTON, self.OnPlotButton)
-        self.PlotButton.Enable(False) # grey it out until a suitable layer is available
-        self.LeftSizer.Add(self.PlotButton, proportion = 0, flag =  wx.ALL, border = parent.border)
-        self.LeftSizer.Add(self.ParametersSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = parent.border)
-        
+        # grey it out until a suitable layer is available
+        self.PlotButton.Enable(False)
+        self.LeftSizer.Add(
+            self.PlotButton,
+            proportion=0,
+            flag=wx.ALL,
+            border=parent.border)
+        self.LeftSizer.Add(
+            self.ParametersSizer,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=parent.border)
+
         self.ParametersList = ["Sill", "Nugget", "Range", "Kappa"]
-        MinValues = [0,0,1,0.1]
+        MinValues = [0, 0, 1, 0.1]
         for n in self.ParametersList:
-            setattr(self, n+"ChextBox", wx.CheckBox(self,
-                                                    id = self.ParametersList.index(n),
-                                                    label = _(n + ":")))
+            setattr(
+                self,
+                n + "ChextBox",
+                wx.CheckBox(
+                    self,
+                    id=self.ParametersList.index(n),
+                    label=_(
+                        n + ":")))
             # Kappa must be float
             if n == "Kappa":
-                setattr(self, n+"Ctrl", (wx.SpinCtrlDouble(self,
-                                                 id = wx.ID_ANY,
-                                                 min = MinValues[self.ParametersList.index(n)],
-                                                 max = maxint,
-                                                 inc = 0.1,
-                                                 initial = 0.5)))
+                setattr(
+                    self,
+                    n + "Ctrl",
+                    (wx.SpinCtrlDouble(
+                        self,
+                        id=wx.ID_ANY,
+                        min=MinValues[
+                            self.ParametersList.index(n)],
+                        max=maxint,
+                        inc=0.1,
+                        initial=0.5)))
             else:
-                setattr(self, n+"Ctrl", (wx.SpinCtrl(self,
-                                                 id = wx.ID_ANY,
-                                                 min = MinValues[self.ParametersList.index(n)],
-                                                 max = maxint)))
-            getattr(self, n+"ChextBox").Bind(wx.EVT_CHECKBOX,
-                                             self.UseValue,
-                                             id = self.ParametersList.index(n))
-            setattr(self, n+"Sizer", (wx.BoxSizer(wx.HORIZONTAL)))
-            self.ParametersSizer.Add(getattr(self, n+"ChextBox"),
-                                     flag = wx.ALIGN_CENTER_VERTICAL,
-                                     pos = (self.ParametersList.index(n),0))
-            self.ParametersSizer.Add(getattr(self, n+"Ctrl"),
-                                     flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL,
-                                     pos = (self.ParametersList.index(n),1))
-        
+                setattr(
+                    self,
+                    n + "Ctrl",
+                    (wx.SpinCtrl(
+                        self,
+                        id=wx.ID_ANY,
+                        min=MinValues[
+                            self.ParametersList.index(n)],
+                        max=maxint)))
+            getattr(self, n + "ChextBox").Bind(wx.EVT_CHECKBOX,
+                                               self.UseValue,
+                                               id=self.ParametersList.index(n))
+            setattr(self, n + "Sizer", (wx.BoxSizer(wx.HORIZONTAL)))
+            self.ParametersSizer.Add(getattr(self, n + "ChextBox"),
+                                     flag=wx.ALIGN_CENTER_VERTICAL,
+                                     pos=(self.ParametersList.index(n), 0))
+            self.ParametersSizer.Add(getattr(self, n + "Ctrl"),
+                                     flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL,
+                                     pos=(self.ParametersList.index(n), 1))
+
         # right side of the Variogram fitting. The plot area.
         #Plot = wx.StaticText(self, id= wx.ID_ANY, label = "Check Plot Variogram to interactively fit model.")
         #PlotPanel = wx.Panel(self)
         #self.PlotArea = plot.PlotCanvas(PlotPanel)
         #self.PlotArea.SetInitialSize(size = (250,250))
         #self.RightSizer.Add(PlotPanel, proportion=0, flag= wx.EXPAND|wx.ALL, border=parent.border)
-        
-        self.KrigingSizer = wx.StaticBoxSizer(wx.StaticBox(self,
-                                                             id = wx.ID_ANY,
-                                                             label = _("Kriging techniques")),
-                                                wx.VERTICAL)
-        
-        KrigingList = ["Ordinary kriging", "Block kriging"]#, "Universal kriging"] #@FIXME: i18n on the list?
+
+        self.KrigingSizer = wx.StaticBoxSizer(
+            wx.StaticBox(
+                self,
+                id=wx.ID_ANY,
+                label=_("Kriging techniques")),
+            wx.VERTICAL)
+
+        # , "Universal kriging"] #@FIXME: i18n on the list?
+        KrigingList = ["Ordinary kriging", "Block kriging"]
         self.KrigingRadioBox = wx.RadioBox(self,
-                                           id = wx.ID_ANY,
-                                           choices = KrigingList,
-                                           majorDimension = 1,
-                                           style = wx.RA_SPECIFY_COLS)
+                                           id=wx.ID_ANY,
+                                           choices=KrigingList,
+                                           majorDimension=1,
+                                           style=wx.RA_SPECIFY_COLS)
         self.KrigingRadioBox.Bind(wx.EVT_RADIOBOX, self.HideBlockOptions)
-        self.KrigingSizer.Add(self.KrigingRadioBox, proportion = 0, flag = wx.EXPAND | wx.ALL, border = parent.border)
-        
+        self.KrigingSizer.Add(
+            self.KrigingRadioBox,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=parent.border)
+
         # block kriging parameters. Size.
         BlockSizer = wx.BoxSizer(wx.HORIZONTAL)
-        BlockLabel = wx.StaticText(self, id = wx.ID_ANY, label = _("Block size:"))
-        self.BlockSpinBox = wx.SpinCtrl(self, id = wx.ID_ANY, min = 1, max = maxint)
-        self.BlockSpinBox.Enable(False) # default choice is Ordinary kriging so block param is disabled
-        BlockSizer.Add(BlockLabel, flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = parent.border)
-        BlockSizer.Add(self.BlockSpinBox, flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = parent.border)
-        self.KrigingSizer.Add(BlockSizer, flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = parent.border)
-        
+        BlockLabel = wx.StaticText(self, id=wx.ID_ANY, label=_("Block size:"))
+        self.BlockSpinBox = wx.SpinCtrl(self, id=wx.ID_ANY, min=1, max=maxint)
+        # default choice is Ordinary kriging so block param is disabled
+        self.BlockSpinBox.Enable(False)
+        BlockSizer.Add(
+            BlockLabel,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=parent.border)
+        BlockSizer.Add(
+            self.BlockSpinBox,
+            flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=parent.border)
+        self.KrigingSizer.Add(
+            BlockSizer,
+            flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=parent.border)
+
         self.Sizer = wx.BoxSizer(wx.VERTICAL)
-        self.Sizer.Add(self.VariogramSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = parent.border)
-        self.Sizer.Add(self.KrigingSizer,  proportion = 0, flag = wx.EXPAND | wx.ALL, border = parent.border)
-        
+        self.Sizer.Add(
+            self.VariogramSizer,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=parent.border)
+        self.Sizer.Add(
+            self.KrigingSizer,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=parent.border)
+
     def HideBlockOptions(self, event):
         self.BlockSpinBox.Enable(event.GetInt() == 1)
-    
-    def OnPlotButton(self,event):
+
+    def OnPlotButton(self, event):
         """Plots variogram with current options. """
         pass
-    
+
     def UseValue(self, event):
         """Enables/Disables the SpinCtrl in respect of the checkbox. """
         n = self.ParametersList[event.GetId()]
-        getattr(self, n+"Ctrl").Enable(event.IsChecked())
+        getattr(self, n + "Ctrl").Enable(event.IsChecked())
 
+
 class RBookgstatPanel(RBookPanel):
     """Subclass of RBookPanel, with specific gstat options and kriging functions. """
+
     def __init__(self, parent, Rinstance, controller, *args, **kwargs):
         RBookPanel.__init__(self, parent, *args, **kwargs)
-        
+
         # assigns Rinstance, that comes from the GUI call of v.krige.py.
         robjects = Rinstance
         self.controller = controller
-        
+
         if robjects.r.require('automap')[0]:
-            self.VariogramCheckBox = wx.CheckBox(self, id = wx.ID_ANY, label = _("Auto-fit variogram"))
-            self.LeftSizer.Insert(0,
-                                  self.VariogramCheckBox,
-                                  proportion = 0,
-                                  flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
-                                  border = 4)
+            self.VariogramCheckBox = wx.CheckBox(
+                self, id=wx.ID_ANY, label=_("Auto-fit variogram"))
+            self.LeftSizer.Insert(
+                0,
+                self.VariogramCheckBox,
+                proportion=0,
+                flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+                border=4)
             self.SetSizerAndFit(self.Sizer)
             self.VariogramCheckBox.Bind(wx.EVT_CHECKBOX, self.HideOptions)
-            self.VariogramCheckBox.SetValue(state = True) # check it by default
-        
+            self.VariogramCheckBox.SetValue(state=True)  # check it by default
+
         # Get list of available models. Show long name but use short one
         ModelFactor = robjects.r.vgm()
         ModelList = robjects.r.levels(ModelFactor[1])
         self.ModelListShort = robjects.r.levels(ModelFactor[0])
         #@FIXME: no other way to let the Python pick it up..
-        # and this is te wrong place where to load this list. should be at the very beginning.
-        self.ModelChoicebox = wx.Choice(self, id = wx.ID_ANY, choices = ModelList)
-        
+        # and this is te wrong place where to load this list. should be at the
+        # very beginning.
+        self.ModelChoicebox = wx.Choice(self, id=wx.ID_ANY, choices=ModelList)
+
         # disable model parameters' widgets by default
         for n in ["Sill", "Nugget", "Range", "Kappa"]:
-            getattr(self, n+"Ctrl").Enable(False)
+            getattr(self, n + "Ctrl").Enable(False)
         self.ModelChoicebox.Enable(False)
-        
+
         VariogramSubSizer = wx.BoxSizer(wx.HORIZONTAL)
-        VariogramSubSizer.Add(item = wx.StaticText(self,
-                                                 id =  wx.ID_ANY,
-                                                 label = _("Model: ")),
-                              flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL,
-                              border = 4)
-        VariogramSubSizer.Add(item = self.ModelChoicebox,
-                              flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL,
-                              border = 4)
-        
-        self.LeftSizer.Insert(2, item = VariogramSubSizer)
-        
+        VariogramSubSizer.Add(item=wx.StaticText(self,
+                                                 id=wx.ID_ANY,
+                                                 label=_("Model: ")),
+                              flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+                              border=4)
+        VariogramSubSizer.Add(item=self.ModelChoicebox,
+                              flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+                              border=4)
+
+        self.LeftSizer.Insert(2, item=VariogramSubSizer)
+
         self.SetSizerAndFit(self.Sizer)
-    
+
     def HideOptions(self, event):
         self.ModelChoicebox.Enable(not event.IsChecked())
         for n in ["Sill", "Nugget", "Range", "Kappa"]:
             if not event.IsChecked():
-                getattr(self, n+"Ctrl").Enable(True)
-                getattr(self, n+ "ChextBox").SetValue(True)
-                getattr(self, n+ "ChextBox").Enable(False) # grey it out keeping it checked.. improvable
+                getattr(self, n + "Ctrl").Enable(True)
+                getattr(self, n + "ChextBox").SetValue(True)
+                # grey it out keeping it checked.. improvable
+                getattr(self, n + "ChextBox").Enable(False)
             else:
-                getattr(self, n+"Ctrl").Enable(False)
-                getattr(self, n+ "ChextBox").SetValue(False)
-                getattr(self, n+ "ChextBox").Enable(True)
+                getattr(self, n + "Ctrl").Enable(False)
+                getattr(self, n + "ChextBox").SetValue(False)
+                getattr(self, n + "ChextBox").Enable(True)
         #@FIXME: was for n in self.ParametersSizer.GetChildren(): n.Enable(False) but doesn't work
-        
-    def OnPlotButton(self,event):
+
+    def OnPlotButton(self, event):
         """Plots variogram with current options. """
-        ## BIG WARNING: smell of code duplication. Fix this asap. emminchia!
-        #controller = Controller() # sed, if needed,
+        # BIG WARNING: smell of code duplication. Fix this asap. emminchia!
+        # controller = Controller() # sed, if needed,
         #controller = self.controller
         map = self.parent.InputDataMap.GetValue()
         column = self.parent.InputDataColumn.GetValue()
-        
+
         # import data or pick them up
         if self.controller.InputData is None:
-            self.controller.InputData = self.controller.ImportMap(map = map,
-                                                          column = column)
+            self.controller.InputData = self.controller.ImportMap(
+                map=map, column=column)
         # fit the variogram or pick it up
         #~ Formula = self.controller.ComposeFormula(column = column,
-                                            #~ isblock = self.KrigingRadioBox.GetStringSelection() == "Block kriging")
-        if hasattr(self, 'VariogramCheckBox') and self.VariogramCheckBox.IsChecked():
+            #~ isblock = self.KrigingRadioBox.GetStringSelection() == "Block kriging")
+        if hasattr(
+                self, 'VariogramCheckBox') and self.VariogramCheckBox.IsChecked():
             self.model = ''
-            for each in ("Sill","Nugget","Range","Kappa"):
-                if getattr(self, each+'ChextBox').IsChecked():
-                    setattr(self, each.lower(), getattr(self, each+"Ctrl").GetValue())
+            for each in ("Sill", "Nugget", "Range", "Kappa"):
+                if getattr(self, each + 'ChextBox').IsChecked():
+                    setattr(
+                        self, each.lower(), getattr(
+                            self, each + "Ctrl").GetValue())
                 else:
                     setattr(self, each.lower(), robjects.r('''NA'''))
-                    
+
         else:
-            self.model = self.ModelListShort[self.ModelChoicebox.GetSelection()]
-            for each in ("Sill","Nugget","Range","Kappa"):
-                if getattr(self, each+'ChextBox').IsChecked(): #@FIXME will be removed when chextboxes will be frozen
-                    setattr(self, each.lower(), getattr(self, each+"Ctrl").GetValue())
-                    
+            self.model = self.ModelListShort[
+                self.ModelChoicebox.GetSelection()]
+            for each in ("Sill", "Nugget", "Range", "Kappa"):
+                # @FIXME will be removed when chextboxes will be frozen
+                if getattr(self, each + 'ChextBox').IsChecked():
+                    setattr(
+                        self, each.lower(), getattr(
+                            self, each + "Ctrl").GetValue())
+
         isblock = self.KrigingRadioBox.GetStringSelection() == "Block kriging"
         if isblock is not '':
             self.predictor = 'x+y'
         else:
             self.predictor = '1'
-        
-        self.controller.Variogram = self.controller.FitVariogram(robjects.Formula(str(column) + "~" + self.predictor),
-                                                         self.controller.InputData,
-                                                         model = self.model,
-                                                         sill = self.sill,
-                                                         nugget = self.nugget,
-                                                         range = self.range,
-                                                         kappa = self.kappa)
 
+        self.controller.Variogram = self.controller.FitVariogram(
+            robjects.Formula(str(column) + "~" + self.predictor),
+            self.controller.InputData, model=self.model, sill=self.sill,
+            nugget=self.nugget, range=self.range, kappa=self.kappa)
+
         ''' Fill parameters with autofitted values '''
-        if hasattr(self, 'VariogramCheckBox') and self.VariogramCheckBox.IsChecked():
+        if hasattr(
+                self, 'VariogramCheckBox') and self.VariogramCheckBox.IsChecked():
             for i in range(len(self.ModelListShort)):
-                if self.ModelListShort[i] == self.controller.Variogram['model']:
+                if self.ModelListShort[
+                        i] == self.controller.Variogram['model']:
                     self.ModelChoicebox.SetSelection(i)
                     break
             if not getattr(self, 'SillChextBox').IsChecked():
@@ -514,30 +723,36 @@
             if not getattr(self, 'KappaChextBox').IsChecked():
                 self.kappa = self.controller.Variogram['variogrammodel'][3][1]
                 self.KappaCtrl.SetValue(self.kappa)
-            
+
         # use R plot function, in a separate window.
         thread.start_new_thread(self.plot, ())
-        
+
     def plot(self):
-        #robjects.r.X11()
-        #robjects.r.png("variogram.png")
-        textplot = robjects.r.plot(self.controller.Variogram['datavariogram'], 
+        # robjects.r.X11()
+        # robjects.r.png("variogram.png")
+        textplot = robjects.r.plot(self.controller.Variogram['datavariogram'],
                                    self.controller.Variogram['variogrammodel'])
         print textplot
         self.refresh()
-        #robjects.r['dev.off']()
+        # robjects.r['dev.off']()
 
     def refresh(self):
         while True:
             rinterface.process_revents()
             time.sleep(0.2)
-        
+
+
 class RBookgeoRPanel(RBookPanel):
     """Subclass of RBookPanel, with specific geoR options and kriging functions. """
+
     def __init__(self, parent, *args, **kwargs):
         RBookPanel.__init__(self, parent, *args, **kwargs)
         #@TODO: change these two lines as soon as geoR f(x)s are integrated.
         for n in self.GetChildren():
             n.Hide()
-        self.Sizer.Add(wx.StaticText(self, id = wx.ID_ANY, label = _("Work in progress! No functionality provided.")))
+        self.Sizer.Add(
+            wx.StaticText(
+                self,
+                id=wx.ID_ANY,
+                label=_("Work in progress! No functionality provided.")))
         self.SetSizerAndFit(self.Sizer)

Modified: grass/trunk/gui/wxpython/nviz/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/nviz/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/nviz/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -6,4 +6,4 @@
     'wxnviz',
     'workspace',
     'animation',
-    ]
+]

Modified: grass/trunk/gui/wxpython/nviz/animation.py
===================================================================
--- grass/trunk/gui/wxpython/nviz/animation.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/nviz/animation.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -11,7 +11,7 @@
 This program is free software under the GNU General Public License
 (>=v2). Read the file COPYING that comes with GRASS for details.
 
- at author Anna Kratochvilova <kratochanna gmail.com> 
+ at author Anna Kratochvilova <kratochanna gmail.com>
 """
 
 import os
@@ -22,27 +22,29 @@
 from grass.pydispatch.signal import Signal
 from core.utils import _
 
+
 class Animation:
     """Class represents animation as a sequence of states (views).
     It enables to record, replay the sequence and finally generate
     all image files. Recording and replaying is based on timer events.
     There is no frame interpolation like in the Tcl/Tk based Nviz.
     """
+
     def __init__(self, mapWindow, timer):
         """Animation constructor
-        
+
         Signals:
             animationFinished - emitted when animation finished
                               - attribute 'mode'
             animationUpdateIndex - emitted during animation to update gui
                                  - attributes 'index' and 'mode'
-        
+
         :param mapWindow: glWindow where rendering takes place
         :param timer: timer for recording and replaying
         """
         self.animationFinished = Signal('Animation.animationFinished')
         self.animationUpdateIndex = Signal('Animation.animationUpdateIndex')
-        
+
         self.animationList = []         # view states
         self.timer = timer
         self.mapWindow = mapWindow
@@ -52,36 +54,37 @@
         self.mode = 'record'            # current mode (record, play, save)
         self.paused = False             # recording/replaying paused
         self.currentFrame = 0           # index of current frame
-        self.fps = 24 # user settings   # Frames per second
-        
+        self.fps = 24  # user settings   # Frames per second
+
         self.stopSaving = False         # stop during saving images
         self.animationSaved = False     # current animation saved or not
-        
+
     def Start(self):
         """Start recording/playing"""
         self.timer.Start(self.GetInterval())
-        
+
     def Pause(self):
         """Pause recording/playing"""
         self.timer.Stop()
-        
+
     def Stop(self):
         """Stop recording/playing"""
         self.timer.Stop()
         self.PostFinishedEvent()
-        
+
     def Update(self):
         """Record/play next view state (on timer event)"""
         self.actions[self.mode]()
-    
+
     def Record(self):
         """Record new view state"""
-        self.animationList.append({'view' : copy.deepcopy(self.mapWindow.view),
-                                   'iview': copy.deepcopy(self.mapWindow.iview)})
+        self.animationList.append(
+            {'view': copy.deepcopy(self.mapWindow.view),
+             'iview': copy.deepcopy(self.mapWindow.iview)})
         self.currentFrame += 1
-        self.PostUpdateIndexEvent(index = self.currentFrame)
+        self.PostUpdateIndexEvent(index=self.currentFrame)
         self.animationSaved = False
-        
+
     def Play(self):
         """Render next frame"""
         if not self.animationList:
@@ -92,94 +95,94 @@
         except IndexError:
             # no more frames
             self.Stop()
-            
+
     def IterAnimation(self):
         params = self.animationList[self.currentFrame]
         self.UpdateView(params)
         self.currentFrame += 1
-        
-        self.PostUpdateIndexEvent(index = self.currentFrame)
-        
+
+        self.PostUpdateIndexEvent(index=self.currentFrame)
+
     def UpdateView(self, params):
         """Update view data in map window and render"""
         toolWin = self.mapWindow.GetToolWin()
-        toolWin.UpdateState(view = params['view'], iview = params['iview'])
-        
+        toolWin.UpdateState(view=params['view'], iview=params['iview'])
+
         self.mapWindow.UpdateView()
-        
+
         self.mapWindow.render['quick'] = True
         self.mapWindow.Refresh(False)
-        
+
     def IsRunning(self):
         """Test if timer is running"""
         return self.timer.IsRunning()
-        
+
     def SetMode(self, mode):
         """Start animation mode
-        
+
         :param mode: animation mode (record, play, save)
         """
         self.mode = mode
-        
+
     def GetMode(self):
         """Get animation mode (record, play, save)"""
         return self.mode
-        
+
     def IsPaused(self):
         """Test if animation is paused"""
         return self.paused
-        
+
     def SetPause(self, pause):
         self.paused = pause
-        
+
     def Exists(self):
         """Returns if an animation has been recorded"""
         return bool(self.animationList)
-        
+
     def GetFrameCount(self):
         """Return number of recorded frames"""
         return len(self.animationList)
-        
+
     def Clear(self):
         """Clear all records"""
         self.animationList = []
         self.currentFrame = 0
-        
+
     def GoToFrame(self, index):
         """Render frame of given index"""
         if index >= len(self.animationList):
             return
-            
+
         self.currentFrame = index
         params = self.animationList[self.currentFrame]
         self.UpdateView(params)
-        
+
     def PostFinishedEvent(self):
         """Animation ends"""
         self.animationFinished.emit(mode=self.mode)
-        
+
     def PostUpdateIndexEvent(self, index):
         """Frame index changed, update tool window"""
         self.animationUpdateIndex(index=index, mode=self.mode)
-        
+
     def StopSaving(self):
         """Abort image files generation"""
         self.stopSaving = True
-        
+
     def IsSaved(self):
         """"Test if animation has been saved (to images)"""
         return self.animationSaved
-        
+
     def SaveAnimationFile(self, path, prefix, format):
         """Generate image files
-        
+
         :param path: path to direcory
         :param prefix: file prefix
         :param format: index of image file format
         """
         w, h = self.mapWindow.GetClientSizeTuple()
         toolWin = self.mapWindow.GetToolWin()
-        
+
         formatter = ':04.0f'
         n = len(self.animationList)
         if n < 10:
@@ -194,17 +197,24 @@
         for params in self.animationList:
             if not self.stopSaving:
                 self.UpdateView(params)
-                number = ('{frame' + formatter +'}').format(frame=self.currentFrame)
-                filename = "{prefix}_{number}.{ext}".format(prefix=prefix,
-                                                            number=number,
-                                                            ext=self.formats[format])
+                number = (
+                    '{frame' +
+                    formatter +
+                    '}').format(
+                    frame=self.currentFrame)
+                filename = "{prefix}_{number}.{ext}".format(
+                    prefix=prefix, number=number, ext=self.formats[format])
                 filepath = os.path.join(path, filename)
-                self.mapWindow.SaveToFile(FileName = filepath, FileType = self.formats[format],
-                                                  width = w, height = h)
+                self.mapWindow.SaveToFile(
+                    FileName=filepath,
+                    FileType=self.formats[format],
+                    width=w,
+                    height=h)
                 self.currentFrame += 1
-                
+
                 wx.Yield()
-                toolWin.UpdateFrameIndex(index = self.currentFrame, goToFrame = False)
+                toolWin.UpdateFrameIndex(
+                    index=self.currentFrame, goToFrame=False)
             else:
                 self.stopSaving = False
                 break
@@ -216,7 +226,7 @@
         :param fps: frames per second
         """
         self.fps = fps
-    
+
     def GetInterval(self):
         """Return timer interval in ms"""
         return 1000. / self.fps

Modified: grass/trunk/gui/wxpython/nviz/main.py
===================================================================
--- grass/trunk/gui/wxpython/nviz/main.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/nviz/main.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -20,7 +20,7 @@
 errorMsg = ''
 
 try:
-    from wx   import glcanvas
+    from wx import glcanvas
     from nviz import mapwindow
     from nviz import tools
     from nviz import workspace
@@ -31,10 +31,10 @@
     errorMsg = err
 
 if haveNviz:
-    GLWindow       = mapwindow.GLWindow
+    GLWindow = mapwindow.GLWindow
     NvizToolWindow = tools.NvizToolWindow
-    NvizSettings   = workspace.NvizSettings
+    NvizSettings = workspace.NvizSettings
 else:
-    GLWindow       = None
+    GLWindow = None
     NvizToolWindow = None
-    NvizSettings   = None
+    NvizSettings = None

Modified: grass/trunk/gui/wxpython/nviz/mapwindow.py
===================================================================
--- grass/trunk/gui/wxpython/nviz/mapwindow.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/nviz/mapwindow.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -28,50 +28,54 @@
 from threading import Thread
 
 import wx
-from   wx.lib.newevent import NewEvent
-from   wx              import glcanvas
-from wx.glcanvas       import WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_DEPTH_SIZE
+from wx.lib.newevent import NewEvent
+from wx import glcanvas
+from wx.glcanvas import WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_DEPTH_SIZE
 
 import grass.script as grass
 from grass.pydispatch.signal import Signal
 
-from core.gcmd          import GMessage, GException, GError
-from core.debug         import Debug
+from core.gcmd import GMessage, GException, GError
+from core.debug import Debug
 from mapwin.base import MapWindowBase
-from core.settings      import UserSettings
-from nviz.workspace     import NvizSettings
-from nviz.animation     import Animation
-from nviz               import wxnviz
-from core.globalvar     import CheckWxVersion
-from core.utils         import str2rgb, _
+from core.settings import UserSettings
+from nviz.workspace import NvizSettings
+from nviz.animation import Animation
+from nviz import wxnviz
+from core.globalvar import CheckWxVersion
+from core.utils import str2rgb, _
 from core.giface import Notification
 
-wxUpdateProperties, EVT_UPDATE_PROP  = NewEvent()
-wxUpdateView,       EVT_UPDATE_VIEW  = NewEvent()
-wxUpdateLight,      EVT_UPDATE_LIGHT = NewEvent()
-wxUpdateCPlane,     EVT_UPDATE_CPLANE = NewEvent()
+wxUpdateProperties, EVT_UPDATE_PROP = NewEvent()
+wxUpdateView, EVT_UPDATE_VIEW = NewEvent()
+wxUpdateLight, EVT_UPDATE_LIGHT = NewEvent()
+wxUpdateCPlane, EVT_UPDATE_CPLANE = NewEvent()
 
+
 class NvizThread(Thread):
+
     def __init__(self, log, progressbar, window):
         Thread.__init__(self)
         Debug.msg(5, "NvizThread.__init__():")
         self.log = log
         self.progressbar = progressbar
         self.window = window
-        
+
         self._display = None
-        
+
         self.setDaemon(True)
 
     def run(self):
         self._display = wxnviz.Nviz(self.log, self.progressbar)
-        
+
     def GetDisplay(self):
         """Get display instance"""
         return self._display
 
+
 class GLWindow(MapWindowBase, glcanvas.GLCanvas):
     """OpenGL canvas for Map Display Window"""
+
     def __init__(self, parent, giface, frame, Map, tree, lmgr, id=wx.ID_ANY):
         """All parameters except for id are mandatory. The todo is to remove
         them completely."""
@@ -85,8 +89,17 @@
         # in wxpython 2.9, there is IsDisplaySupported
         if CheckWxVersion(version=[2, 8, 11]) and \
            sys.platform not in ('win32', 'darwin'):
-            depthBuffer = int(UserSettings.Get(group='display', key='nvizDepthBuffer', subkey='value'))
-            attribs = [WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_DEPTH_SIZE, depthBuffer, 0]
+            depthBuffer = int(
+                UserSettings.Get(
+                    group='display',
+                    key='nvizDepthBuffer',
+                    subkey='value'))
+            attribs = [
+                WX_GL_RGBA,
+                WX_GL_DOUBLEBUFFER,
+                WX_GL_DEPTH_SIZE,
+                depthBuffer,
+                0]
             glcanvas.GLCanvas.__init__(self, parent, id, attribList=attribs)
         else:
             glcanvas.GLCanvas.__init__(self, parent, id)
@@ -117,18 +130,18 @@
         if CheckWxVersion(version=[2, 9]):
             self.context = glcanvas.GLContext(self)
 
-        # render mode 
-        self.render = { 'quick' : False,
-                        # do not render vector lines in quick mode
-                        'vlines' : False,
-                        'vpoints' : False,
-                        'overlays': False }
+        # render mode
+        self.render = {'quick': False,
+                       # do not render vector lines in quick mode
+                       'vlines': False,
+                       'vpoints': False,
+                       'overlays': False}
         self.mouse = {
             'use': 'pointer'
-            }
+        }
 
         # list of loaded map layers (layer tree items)
-        self.layers  = list()
+        self.layers = list()
         # list of constant surfaces
         self.constants = list()
         # id of base surface (when vector is loaded and no surface exist)
@@ -138,7 +151,7 @@
         # list of query points
         self.qpoints = list()
         # list of past views
-        self.viewhistory  = []
+        self.viewhistory = []
         self.saveHistory = False
         # offset for dialog (e.g. DisplayAttributesDialog)
         self.dialogOffset = 5
@@ -152,212 +165,231 @@
         self.hitradius = 5
         # layer manager toolwindow
         self.toolWin = None
-        
+
         if self.lmgr:
             self.log = self.lmgr._gconsole
-            logerr = self.lmgr._gconsole.GetLog(err = True)
+            logerr = self.lmgr._gconsole.GetLog(err=True)
             logmsg = self.lmgr._gconsole.GetLog()
         else:
             self.log = logmsg = sys.stdout
             logerr = sys.stderr
-        
+
         # create nviz instance - use display region instead of computational
-        
-        os.environ['GRASS_REGION'] = self.Map.SetRegion(windres = True, windres3 = True)
+
+        os.environ['GRASS_REGION'] = self.Map.SetRegion(
+            windres=True, windres3=True)
         self.nvizThread = NvizThread(logerr,
                                      self.parent.GetProgressBar(),
                                      logmsg)
         self.nvizThread.start()
         time.sleep(.1)
         self._display = self.nvizThread.GetDisplay()
-        
+
         # GRASS_REGION needed only for initialization
         del os.environ['GRASS_REGION']
-        
+
         self.img = wx.Image(self.Map.mapfile, wx.BITMAP_TYPE_ANY)
-        
+
         # size of MapWindow, to avoid resizing if size is the same
         self.size = (0, 0)
-        
+
         # default values
         self.nvizDefault = NvizSettings()
-        self.view = copy.deepcopy(UserSettings.Get(group = 'nviz', key = 'view')) # copy
-        self.iview = UserSettings.Get(group='nviz', key='view', settings_type='internal')
-        self.light = copy.deepcopy(UserSettings.Get(group = 'nviz', key = 'light')) # copy
-        self.decoration = self.nvizDefault.SetDecorDefaultProp(type = 'arrow')
+        self.view = copy.deepcopy(
+            UserSettings.Get(
+                group='nviz',
+                key='view'))  # copy
+        self.iview = UserSettings.Get(
+            group='nviz', key='view', settings_type='internal')
+        self.light = copy.deepcopy(
+            UserSettings.Get(
+                group='nviz',
+                key='light'))  # copy
+        self.decoration = self.nvizDefault.SetDecorDefaultProp(type='arrow')
         self.decoration['scalebar'] = []
         self.decoration['arrow']['size'] = self._getDecorationSize()
         self.fly = self.InitFly()
-        
+
         # timer for flythrough
-        self.timerFly = wx.Timer(self, id = wx.NewId())
+        self.timerFly = wx.Timer(self, id=wx.NewId())
         # timer for animations
-        self.timerAnim = wx.Timer(self, id = wx.NewId())
-        self.animation = Animation(mapWindow = self, timer = self.timerAnim)        
-        
+        self.timerAnim = wx.Timer(self, id=wx.NewId())
+        self.animation = Animation(mapWindow=self, timer=self.timerAnim)
+
         self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
-        self.Bind(wx.EVT_SIZE,             self.OnSize)
-        self.Bind(wx.EVT_PAINT,            self.OnPaint)
+        self.Bind(wx.EVT_SIZE, self.OnSize)
+        self.Bind(wx.EVT_PAINT, self.OnPaint)
         self._bindMouseEvents()
-        
-        self.Bind(EVT_UPDATE_PROP,   self.UpdateMapObjProperties)
-        self.Bind(EVT_UPDATE_VIEW,   self.OnUpdateView)
-        self.Bind(EVT_UPDATE_LIGHT,  self.UpdateLight)
+
+        self.Bind(EVT_UPDATE_PROP, self.UpdateMapObjProperties)
+        self.Bind(EVT_UPDATE_VIEW, self.OnUpdateView)
+        self.Bind(EVT_UPDATE_LIGHT, self.UpdateLight)
         self.Bind(EVT_UPDATE_CPLANE, self.OnUpdateCPlane)
-        
+
         self.Bind(wx.EVT_TIMER, self.OnTimerAnim, self.timerAnim)
         self.Bind(wx.EVT_TIMER, self.OnTimerFly, self.timerFly)
         self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
         self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
-        
+
         self.Bind(wx.EVT_CLOSE, self.OnClose)
-        
+
         if CheckWxVersion(version=[2, 8, 11]) and \
            sys.platform not in ('win32', 'darwin'):
-               wx.CallLater(3000, self._warningDepthBuffer)
-        
+            wx.CallLater(3000, self._warningDepthBuffer)
+
         # cplanes cannot be initialized now
         wx.CallAfter(self.InitCPlanes)
 
     def _warningDepthBuffer(self):
         if not self.initView:
-            message=_("Opening 3D view was not successful. "
-                      "Please try to change the value of depth buffer "
-                      "in GUI Settings dialog > tab Map Display > Advanced "
-                      "and restart GUI.")
+            message = _("Opening 3D view was not successful. "
+                        "Please try to change the value of depth buffer "
+                        "in GUI Settings dialog > tab Map Display > Advanced "
+                        "and restart GUI.")
             GMessage(message)
 
     def InitFly(self):
         """Initialize fly through dictionary"""
-        fly = {'interval' : 10,             # interval for timerFly
+        fly = {'interval': 10,             # interval for timerFly
                'value': [0, 0, 0],          # calculated values for navigation
-               'mode' : 0,                  # fly through mode (0, 1)
-               'exag' : {                   # sensitivity
-                    'move' : UserSettings.Get(group = 'nviz', key = 'fly', subkey = ['exag', 'move']),
-                    'turn' : UserSettings.Get(group = 'nviz', key = 'fly', subkey = ['exag', 'turn'])},
-               'exagMultiplier' : 3,        # speed up by Shift
-               'flySpeed' : 4,              # speed of flying
-               'mouseControl' : None,       # if mouse or keys are used
-               'pos' : {'x' : 0, 'y' : 0},  # virtual mouse position when using arrows
-               'arrowStep' : 50,            # step in pixels (when using arrows)
-               'flySpeedStep' : 2,
-            }
-            
+               'mode': 0,                  # fly through mode (0, 1)
+               'exag': {                   # sensitivity
+                   'move': UserSettings.Get(group='nviz', key='fly', subkey=['exag', 'move']),
+                   'turn': UserSettings.Get(group='nviz', key='fly', subkey=['exag', 'turn'])},
+               'exagMultiplier': 3,        # speed up by Shift
+               'flySpeed': 4,              # speed of flying
+               'mouseControl': None,       # if mouse or keys are used
+               # virtual mouse position when using arrows
+               'pos': {'x': 0, 'y': 0},
+               'arrowStep': 50,            # step in pixels (when using arrows)
+               'flySpeedStep': 2,
+               }
+
         return fly
-        
+
     def OnTimerFly(self, event):
         """Fly event was emitted, move the scene"""
         if self.mouse['use'] != 'fly':
             return
-        
+
         if self.fly['mouseControl']:
             mx, my = self.ComputeMxMy(*self.mouse['tmp'])
         else:
-            mx, my = self.ComputeMxMy(self.fly['pos']['x'], self.fly['pos']['y'])
-            
-        self.ComputeFlyValues(mx = mx, my = my)
-        self._display.FlyThrough(flyInfo = self.fly['value'], mode = self.fly['mode'],
-                                 exagInfo = self.fly['exag'])
-        self.ChangeInnerView()                                 
+            mx, my = self.ComputeMxMy(
+                self.fly['pos']['x'],
+                self.fly['pos']['y'])
+
+        self.ComputeFlyValues(mx=mx, my=my)
+        self._display.FlyThrough(
+            flyInfo=self.fly['value'],
+            mode=self.fly['mode'],
+            exagInfo=self.fly['exag'])
+        self.ChangeInnerView()
         self.render['quick'] = True
         self.Refresh(False)
-        
+
     def ComputeMxMy(self, x, y):
-        """Compute values for flythrough navigation 
-        (ComputeFlyValues should follow). 
-        
+        """Compute values for flythrough navigation
+        (ComputeFlyValues should follow).
+
         Based on visualization/nviz/src/togl_flythrough.c.
         :param x,y: screen coordinates
         """
         sx, sy = self.GetClientSizeTuple()
         dx = dy = 0.01
-        
+
         mx = 2 * (float(x) / sx) - 1
         my = 2 * (float(y) / sy) - 1
-    
+
         if mx < - dx:
             mx += dx
         elif mx > dx:
             mx -= dx
         else:
-            mx = 0.0 # ?
+            mx = 0.0  # ?
         if my < - dy:
             my += dy
         elif my > dy:
             my -= dy
         else:
             my = 0.0
-    
+
         mx = mx / (1.0 - dx)
         my = my / (1.0 - dy)
-    
-        # Quadratic seems smoother 
+
+        # Quadratic seems smoother
         mx *= abs(mx)
         my *= abs(my)
-        
+
         return mx, my
-        
+
     def ComputeFlyValues(self, mx, my):
         """Compute parameters for fly-through navigation
-        
+
         :param mx,my: results from ComputeMxMy method
         """
         self.fly['value'] = [0, 0, 0]
-        
+
         if self.fly['mode'] == 0:
-            self.fly['value'][0] = self.fly['flySpeed'] * self.fly['interval'] / 1000. # forward */
-            self.fly['value'][1] = mx * 0.1 * self.fly['interval'] / 1000. # heading 
-            self.fly['value'][2] = my * 0.1 * self.fly['interval'] / 1000. # pitch 
+            self.fly['value'][0] = self.fly[
+                'flySpeed'] * self.fly['interval'] / 1000.  # forward */
+            self.fly['value'][
+                1] = mx * 0.1 * self.fly['interval'] / 1000.  # heading
+            self.fly['value'][
+                2] = my * 0.1 * self.fly['interval'] / 1000.  # pitch
         else:
-            self.fly['value'][0] = mx * 100.0 * self.fly['interval'] /1000.
-            self.fly['value'][2] = - my * 100.0 * self.fly['interval'] /1000.
-    
+            self.fly['value'][0] = mx * 100.0 * self.fly['interval'] / 1000.
+            self.fly['value'][2] = - my * 100.0 * self.fly['interval'] / 1000.
+
     def ChangeFlySpeed(self, increase):
         """Increase/decrease flight spped"""
         if increase:
             self.fly['flySpeed'] += self.fly['flySpeedStep']
         else:
             self.fly['flySpeed'] -= self.fly['flySpeedStep']
-        
+
     def __del__(self):
         """Stop timers if running, unload data"""
         self.StopTimer(self.timerAnim)
         self.StopTimer(self.timerFly)
-        self.UnloadDataLayers(force = True)
-    
+        self.UnloadDataLayers(force=True)
+
     def StopTimer(self, timer):
         """Stop timer if running"""
         if timer.IsRunning():
             timer.Stop()
-            
+
     def _bindMouseEvents(self):
-        self.Bind(wx.EVT_MOUSE_EVENTS,     self.OnMouseAction)
-        self.Bind(wx.EVT_MOTION,           self.OnMotion)
-        
+        self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouseAction)
+        self.Bind(wx.EVT_MOTION, self.OnMotion)
+
     def InitCPlanes(self):
         """Initialize cutting planes list"""
         for i in range(self._display.GetCPlanesCount()):
-            cplane = copy.deepcopy(UserSettings.Get(group = 'nviz', key = 'cplane'))
+            cplane = copy.deepcopy(
+                UserSettings.Get(
+                    group='nviz',
+                    key='cplane'))
             cplane['on'] = False
             self.cplanes.append(cplane)
-        
+
     def SetToolWin(self, toolWin):
         """Sets reference to nviz toolwindow in layer manager"""
         self.toolWin = toolWin
-        
+
     def GetToolWin(self):
         """Returns reference to nviz toolwindow in layer manager"""
         return self.toolWin
-            
+
     def OnClose(self, event):
         self.StopTimer(self.timerAnim)
         self.StopTimer(self.timerFly)
         # cleanup when window actually closes (on quit) and not just is hidden
-        self.UnloadDataLayers(force = True)
-        
+        self.UnloadDataLayers(force=True)
+
     def OnEraseBackground(self, event):
-        pass # do nothing, to avoid flashing on MSW
-    
+        pass  # do nothing, to avoid flashing on MSW
+
     def OnSize(self, event):
         size = self.GetClientSize()
         if CheckWxVersion(version=[2, 9]):
@@ -365,8 +397,8 @@
         else:
             context = self.GetContext()
         if self.size != size \
-            and context:
-            Debug.msg(3, "GLCanvas.OnSize(): w = %d, h = %d" % \
+                and context:
+            Debug.msg(3, "GLCanvas.OnSize(): w = %d, h = %d" %
                       (size.width, size.height))
             if CheckWxVersion(version=[2, 9]):
                 self.SetCurrent(self.context)
@@ -374,73 +406,73 @@
                 self.SetCurrent()
             self._display.ResizeWindow(size.width,
                                        size.height)
-        
+
             # reposition checkbox in statusbar
             self.parent.StatusbarReposition()
-            
+
             # update statusbar
             self.parent.StatusbarUpdate()
-            
+
         self.size = size
-        
+
         event.Skip()
-       
+
     def OnPaint(self, event):
         Debug.msg(1, "GLCanvas.OnPaint()")
-        
+
         self.render['overlays'] = True
         dc = wx.PaintDC(self)
         self.DoPaint()
-        
 
     def DoPaint(self):
         if CheckWxVersion(version=[2, 9]):
             self.SetCurrent(self.context)
         else:
             self.SetCurrent()
-        
+
         if not self.initView:
             self._display.InitView()
             self.initView = True
-        
+
         self.LoadDataLayers()
         self.UnloadDataLayers()
-        
+
         if not self.init:
             self.ResetView()
-            
+
             if hasattr(self.lmgr, "nviz"):
                 self.lmgr.nviz.UpdatePage('view')
                 self.lmgr.nviz.UpdatePage('light')
                 self.lmgr.nviz.UpdatePage('cplane')
                 self.lmgr.nviz.UpdatePage('decoration')
                 self.lmgr.nviz.UpdatePage('animation')
-                layer = self.tree.GetSelectedLayer(multi = False, checkedOnly = True)
+                layer = self.tree.GetSelectedLayer(
+                    multi=False, checkedOnly=True)
                 if layer:
-                    layer = self.tree.GetLayerInfo(layer, key = 'maplayer')
-                    if layer.type ==  'raster':
+                    layer = self.tree.GetLayerInfo(layer, key='maplayer')
+                    if layer.type == 'raster':
                         self.lmgr.nviz.UpdatePage('surface')
                         self.lmgr.nviz.UpdatePage('fringe')
-                    elif layer.type ==  'vector':
+                    elif layer.type == 'vector':
                         self.lmgr.nviz.UpdatePage('vector')
-                
+
                 self.lmgr.nviz.UpdateSettings()
-                
+
                 # update widgets
-                win = self.lmgr.nviz.FindWindowById( \
+                win = self.lmgr.nviz.FindWindowById(
                     self.lmgr.nviz.win['vector']['lines']['surface'])
                 win.SetItems(self.GetLayerNames('raster'))
-            
+
             self.init = True
-        
+
         self.UpdateMap()
-        
+
     def DrawImages(self):
         """Draw overlay image"""
         for texture in self.imagelist:
             if texture.IsActive():
                 texture.Draw()
-            
+
     def GetLegendRect(self):
         """Estimates legend size for dragging"""
         size = None
@@ -451,23 +483,24 @@
                     break
         if size:
             wSize = self.GetClientSizeTuple()
-            x, y = size[2]/100. * wSize[0], wSize[1] - (size[1]/100. * wSize[1])
+            x, y = size[
+                2] / 100. * wSize[0], wSize[1] - (size[1] / 100. * wSize[1])
             x += self.overlays[1].coords[0]
             y += self.overlays[1].coords[1]
-            w = (size[3] - size[2])/100. * wSize[0]
-            h = (size[1] - size[0])/100. * wSize[1]
-            
+            w = (size[3] - size[2]) / 100. * wSize[0]
+            h = (size[1] - size[0]) / 100. * wSize[1]
+
             rect = wx.Rect(x, y, w, h)
             return rect
-        
-        return wx.Rect()        
-        
+
+        return wx.Rect()
+
     def DrawTextImage(self, textDict, relCoords):
         """Draw overlay text"""
         bmp = wx.EmptyBitmap(textDict['bbox'][2], textDict['bbox'][3])
         memDC = wx.MemoryDC()
         memDC.SelectObject(bmp)
-        
+
         mask = self.view['background']['color']
         if mask == textDict['color']:
             mask = wx.WHITE
@@ -482,19 +515,19 @@
                                   textDict['rotation'])
         bmp.SetMaskColour(mask)
         memDC.DrawBitmap(bmp, 0, 0, 1)
-        
-        filename = grass.tempfile(create = False) + '.png'
+
+        filename = grass.tempfile(create=False) + '.png'
         bmp.SaveFile(filename, wx.BITMAP_TYPE_PNG)
         memDC.SelectObject(wx.NullBitmap)
-        
+
         return filename
-        
+
     def UpdateOverlays(self):
         """Converts rendered overlay files and text labels to wx.Image
             and then to textures so that they can be rendered by OpenGL.
             Updates self.imagelist"""
         self.Map.ChangeMapSize(self.GetClientSize())
-        self.Map.RenderOverlays(force = True)
+        self.Map.RenderOverlays(force=True)
 
         # delete textures
         for texture in self.imagelist:
@@ -504,126 +537,134 @@
                     texture.SetActive(False)
                 else:
                     texture.SetActive(True)
-            else: # text label
+            else:  # text label
                 if texture.GetId() not in self.textdict:
                     self.imagelist.remove(texture)
-                    
+
         # update images (only legend so far)
         for oid, overlay in self.overlays.iteritems():
-            if not overlay.IsShown() or oid in (1, 2): # 0 for barscale
+            if not overlay.IsShown() or oid in (1, 2):  # 0 for barscale
                 continue
-            if oid not in [t.GetId() for t in self.imagelist]: # new
-                self.CreateTexture(overlay = overlay.layer)
+            if oid not in [t.GetId() for t in self.imagelist]:  # new
+                self.CreateTexture(overlay=overlay.layer)
             else:
                 for t in self.imagelist:
-                    if t.GetId() == oid: # check if it is the same
+                    if t.GetId() == oid:  # check if it is the same
                         if not t.Corresponds(overlay):
                             self.imagelist.remove(t)
-                            t = self.CreateTexture(overlay = overlay.layer)
+                            t = self.CreateTexture(overlay=overlay.layer)
 
         # update text labels
         for textId in self.textdict.keys():
-            if textId not in [t.GetId() for t in self.imagelist]:# new
-                self.CreateTexture(textId = textId)
+            if textId not in [t.GetId() for t in self.imagelist]:  # new
+                self.CreateTexture(textId=textId)
             else:
                 for t in self.imagelist:
-                    if t.GetId() == textId: # check if it is the same
+                    if t.GetId() == textId:  # check if it is the same
                         self.textdict[textId]['bbox'] = t.textDict['bbox']
                         if not t.Corresponds(self.textdict[textId]):
                             self.imagelist.remove(t)
-                            t = self.CreateTexture(textId = textId)
-                        # always set coordinates, needed for synchr. 2D and 3D modes
+                            t = self.CreateTexture(textId=textId)
+                        # always set coordinates, needed for synchr. 2D and 3D
+                        # modes
                         t.SetCoords(self.textdict[textId]['coords'])
         self.Refresh()
-            
-    def CreateTexture(self, overlay = None, textId = None):
+
+    def CreateTexture(self, overlay=None, textId=None):
         """Create texture from overlay image or from textdict"""
-        if overlay: # legend  
-            texture = wxnviz.ImageTexture(filepath = overlay.mapfile, overlayId = overlay.id,
-                                          coords = list(self.overlays[overlay.id].coords),
-                                          cmd = overlay.GetCmd())
-            if overlay.id == 0: # legend
+        if overlay:  # legend
+            texture = wxnviz.ImageTexture(
+                filepath=overlay.mapfile,
+                overlayId=overlay.id,
+                coords=list(
+                    self.overlays[
+                        overlay.id].coords),
+                cmd=overlay.GetCmd())
+            if overlay.id == 0:  # legend
                 texture.SetBounds(self.GetLegendRect())
-        else: # text
+        else:  # text
             coords, bbox, relCoords = self.TextBounds(self.textdict[textId])
             self.textdict[textId]['coords'] = coords
             self.textdict[textId]['bbox'] = bbox
             file = self.DrawTextImage(self.textdict[textId], relCoords)
-            texture = wxnviz.TextTexture(filepath = file, overlayId = textId,
-                                         coords = coords, textDict = self.textdict[textId])
+            texture = wxnviz.TextTexture(
+                filepath=file, overlayId=textId, coords=coords,
+                textDict=self.textdict[textId])
             bbox.OffsetXY(*relCoords)
             texture.SetBounds(bbox)
-            
-        if not texture.textureId: # texture too big
-            GMessage(parent = self, message = 
-                     _("Image is too large, your OpenGL implementation "
-                       "supports maximum texture size %d px.") % texture.maxSize)
+
+        if not texture.textureId:  # texture too big
+            GMessage(
+                parent=self, message=_(
+                    "Image is too large, your OpenGL implementation "
+                    "supports maximum texture size %d px.") %
+                texture.maxSize)
             return texture
-            
+
         self.imagelist.append(texture)
-        
+
         return texture
-        
+
     def FindObjects(self, mouseX, mouseY, radius):
         """Find object which was clicked on"""
         for texture in self.imagelist:
             if texture.HitTest(mouseX, mouseY, radius):
                 return texture.id
         return -1
-        
+
     def OnTimerAnim(self, event):
-         self.animation.Update()
-         
+        self.animation.Update()
+
     def GetAnimation(self):
-         return self.animation
-         
+        return self.animation
+
     def OnKeyDown(self, event):
         """Key was pressed.
-        
+
         Used for fly-through mode.
         """
         if not self.mouse['use'] == 'fly':
             return
-            
+
         key = event.GetKeyCode()
-        if key == wx.WXK_CONTROL: # Mac ?
+        if key == wx.WXK_CONTROL:  # Mac ?
             self.fly['mode'] = 1
-            
-        elif key == wx.WXK_SHIFT: 
+
+        elif key == wx.WXK_SHIFT:
             self.fly['exag']['move'] *= self.fly['exagMultiplier']
             self.fly['exag']['turn'] *= self.fly['exagMultiplier']
-            
+
         elif key == wx.WXK_ESCAPE and self.timerFly.IsRunning() and not self.fly['mouseControl']:
             self.StopTimer(self.timerFly)
             self.fly['mouseControl'] = None
             self.render['quick'] = False
             self.Refresh(False)
-            
+
         elif key in (wx.WXK_UP, wx.WXK_DOWN, wx.WXK_LEFT, wx.WXK_RIGHT):
             if not self.fly['mouseControl']:
                 if not self.timerFly.IsRunning():
                     sx, sy = self.GetClientSizeTuple()
                     self.fly['pos']['x'] = sx / 2
                     self.fly['pos']['y'] = sy / 2
-                    self.fly['mouseControl'] = False # controlled by keyboard
+                    self.fly['mouseControl'] = False  # controlled by keyboard
                     self.timerFly.Start(self.fly['interval'])
-    
-                self.ProcessFlyByArrows(keyCode = key)
-                
+
+                self.ProcessFlyByArrows(keyCode=key)
+
             # change speed of flight when using mouse
             else:
                 if key == wx.WXK_UP:
-                    self.ChangeFlySpeed(increase = True)
+                    self.ChangeFlySpeed(increase=True)
                 elif key == wx.WXK_DOWN:
-                    self.ChangeFlySpeed(increase = False)
-        
+                    self.ChangeFlySpeed(increase=False)
+
         elif key in (wx.WXK_HOME, wx.WXK_PAGEUP) and self.timerFly.IsRunning():
-            self.ChangeFlySpeed(increase = True)
+            self.ChangeFlySpeed(increase=True)
         elif key in (wx.WXK_END, wx.WXK_PAGEDOWN) and self.timerFly.IsRunning():
-            self.ChangeFlySpeed(increase = False)
-            
+            self.ChangeFlySpeed(increase=False)
+
         event.Skip()
-        
+
     def ProcessFlyByArrows(self, keyCode):
         """Process arrow key during fly-through"""
         step = self.fly['arrowStep']
@@ -635,43 +676,45 @@
             self.fly['pos']['x'] -= step
         elif keyCode == wx.WXK_RIGHT:
             self.fly['pos']['x'] += step
-            
+
     def OnKeyUp(self, event):
         """Key was released.
-        
+
         Used for fly-through mode.
         """
         if not self.mouse['use'] == 'fly':
             return
-            
+
         key = event.GetKeyCode()
-        if key == wx.WXK_CONTROL: # Mac ?
+        if key == wx.WXK_CONTROL:  # Mac ?
             self.fly['mode'] = 0
-        elif key == wx.WXK_SHIFT: 
-            self.fly['exag']['move'] = math.floor(self.fly['exag']['move'] / self.fly['exagMultiplier'])
-            self.fly['exag']['turn'] = math.floor(self.fly['exag']['turn'] / self.fly['exagMultiplier'])
-        
+        elif key == wx.WXK_SHIFT:
+            self.fly['exag']['move'] = math.floor(
+                self.fly['exag']['move'] / self.fly['exagMultiplier'])
+            self.fly['exag']['turn'] = math.floor(
+                self.fly['exag']['turn'] / self.fly['exagMultiplier'])
+
         event.Skip()
-        
+
     def OnMouseAction(self, event):
         """Handle mouse events"""
         # 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    
+
+        # double click
         elif event.ButtonDClick():
             self.OnDClick(event)
 
@@ -687,36 +730,38 @@
 
     def OnMouseWheel(self, event):
         """Change perspective"""
-        if UserSettings.Get(group = 'display',
-                            key = 'mouseWheelZoom',
-                            subkey = 'selection') == 2:
+        if UserSettings.Get(group='display',
+                            key='mouseWheelZoom',
+                            subkey='selection') == 2:
             event.Skip()
             return
-            
+
         wheel = event.GetWheelRotation()
-        Debug.msg (5, "GLWindow.OnMouseWheel(): wheel = %d" % wheel)
+        Debug.msg(5, "GLWindow.OnMouseWheel(): wheel = %d" % wheel)
         if self.timerFly.IsRunning() and self.fly['mouseControl']:
             if wheel > 0:
-                self.ChangeFlySpeed(increase = True)
+                self.ChangeFlySpeed(increase=True)
             else:
-                self.ChangeFlySpeed(increase = False)
+                self.ChangeFlySpeed(increase=False)
         else:
-            if UserSettings.Get(group = 'display',
-                                key = 'scrollDirection',
-                                subkey = 'selection'):
+            if UserSettings.Get(group='display',
+                                key='scrollDirection',
+                                subkey='selection'):
                 wheel *= -1
-            self.DoZoom(zoomtype = wheel, pos = event.GetPositionTuple())
-            
+            self.DoZoom(zoomtype=wheel, pos=event.GetPositionTuple())
+
         # update statusbar
-        ### self.parent.StatusbarUpdate()
-            
+        # self.parent.StatusbarUpdate()
+
     def OnLeftDown(self, event):
         """On left mouse down"""
         self.mouse['begin'] = event.GetPositionTuple()
         self.mouse['tmp'] = event.GetPositionTuple()
         if self.mouse['use'] == "lookHere":
             size = self.GetClientSize()
-            self._display.LookHere(self.mouse['begin'][0], size[1] - self.mouse['begin'][1])
+            self._display.LookHere(
+                self.mouse['begin'][0],
+                size[1] - self.mouse['begin'][1])
             focus = self._display.GetFocus()
             for i, coord in enumerate(('x', 'y', 'z')):
                 self.iview['focus'][coord] = focus[i]
@@ -726,55 +771,58 @@
             toggle.SetValue(False)
             self.mouse['use'] = 'pointer'
             self.SetNamedCursor('default')
-                
+
         if self.mouse['use'] == 'arrow':
             pos = event.GetPosition()
             size = self.GetClientSize()
             self.SetDrawArrow((pos[0], size[1] - pos[1]))
-                
+
         if self.mouse['use'] == 'scalebar':
             pos = event.GetPosition()
             size = self.GetClientSize()
             self.SetDrawScalebar((pos[0], size[1] - pos[1]))
-        
+
         if self.mouse['use'] == 'pointer':
             # get decoration or text id
-            self.dragid = self.FindObjects(self.mouse['tmp'][0], self.mouse['tmp'][1],
-                                           self.hitradius)
+            self.dragid = self.FindObjects(
+                self.mouse['tmp'][0],
+                self.mouse['tmp'][1],
+                self.hitradius)
         if self.mouse['use'] == 'fly':
             if not self.timerFly.IsRunning():
                 self.timerFly.Start(self.fly['interval'])
                 self.fly['mouseControl'] = True
-            
-        event.Skip()    
-        
+
+        event.Skip()
+
     def OnDragging(self, event):
-                
+
         if self.mouse['use'] == 'pointer':
             if self.dragid >= 0:
                 self.DragItem(self.dragid, event.GetPositionTuple())
-            
-        if self.mouse['use'] == 'rotate':    
-            dx, dy = event.GetX() - self.mouse['tmp'][0], event.GetY() - self.mouse['tmp'][1]
-            
+
+        if self.mouse['use'] == 'rotate':
+            dx, dy = event.GetX(
+            ) - self.mouse['tmp'][0], event.GetY() - self.mouse['tmp'][1]
+
             angle, x, y, z = self._display.GetRotationParameters(dx, dy)
             self._display.Rotate(angle, x, y, z)
-            
+
             self.render['quick'] = True
             self.Refresh(False)
-            
+
         if self.mouse['use'] == 'pan':
             self.FocusPanning(event)
-            
+
         self.mouse['tmp'] = event.GetPositionTuple()
-                
+
         event.Skip()
-            
+
     def Pixel2Cell(self, xyCoords):
         """Convert image coordinates to real word coordinates
 
         :param xyCoords: image coordinates
-        
+
         :return: easting, northing
         :return: None on error
         """
@@ -782,27 +830,27 @@
         # UL -> LL
         x, y = xyCoords
         sid, x, y, z = self._display.GetPointOnSurface(x, size[1] - y)
-        
+
         if not sid:
             return None
-        
+
         return (x, y)
-    
+
     def DoZoom(self, zoomtype, pos):
         """Change perspective and focus"""
-        
+
         prev_value = self.view['persp']['value']
         if zoomtype > 0:
             value = -1 * self.view['persp']['step']
         else:
             value = self.view['persp']['step']
-        self.view['persp']['value'] +=  value
+        self.view['persp']['value'] += value
         if self.view['persp']['value'] < 1:
             self.view['persp']['value'] = 1
         elif self.view['persp']['value'] > 180:
             self.view['persp']['value'] = 180
-        
-        if prev_value !=  self.view['persp']['value']:
+
+        if prev_value != self.view['persp']['value']:
             if hasattr(self.lmgr, "nviz"):
                 self.lmgr.nviz.UpdateSettings()
                 x, y = pos[0], self.GetClientSize()[1] - pos[1]
@@ -812,14 +860,16 @@
                     focus = self._display.GetFocus()
                     for i, coord in enumerate(('x', 'y', 'z')):
                         self.iview['focus'][coord] = focus[i]
-                self._display.SetView(self.view['position']['x'], self.view['position']['y'],
-                                      self.iview['height']['value'],
-                                      self.view['persp']['value'],
-                                      self.view['twist']['value'])
+                self._display.SetView(
+                    self.view['position']['x'],
+                    self.view['position']['y'],
+                    self.iview['height']['value'],
+                    self.view['persp']['value'],
+                    self.view['twist']['value'])
                 self.saveHistory = True
             # redraw map
             self.DoPaint()
-            
+
     def OnLeftUp(self, event):
         self.mouse['end'] = event.GetPositionTuple()
         if self.mouse["use"] == "query":
@@ -831,7 +881,8 @@
 
         elif self.mouse["use"] in ('arrow', 'scalebar'):
             self.lmgr.nviz.FindWindowById(
-                    self.lmgr.nviz.win['decoration'][self.mouse["use"]]['place']).SetValue(False)
+                self.lmgr.nviz.win['decoration'][
+                    self.mouse["use"]]['place']).SetValue(False)
             if self.mouse["use"] == 'scalebar':
                 scalebarNum = len(self.decoration['scalebar'])
                 self.lmgr.nviz.AddScalebar(scalebarNum - 1)
@@ -839,7 +890,6 @@
                 self.lmgr.nviz.AddArrow()
             self.mouse['use'] = 'pointer'
             self.SetNamedCursor('default')
-            
 
         elif self.mouse['use'] == 'pointer':
             if self.dragid >= 0:
@@ -847,57 +897,63 @@
                 dy = self.mouse['end'][1] - self.mouse['begin'][1]
                 if self.dragid < 99:
                     coords = self.overlays[self.dragid].coords
-                    self.overlays[self.dragid].coords = [coords[0] + dx, coords[1] + dy]
-                else: # text
+                    self.overlays[
+                        self.dragid].coords = [
+                        coords[0] + dx, coords[1] + dy]
+                else:  # text
                     coords = self.textdict[self.dragid]['coords']
-                    self.textdict[self.dragid]['coords'] = [coords[0] + dx, coords[1] + dy]
+                    self.textdict[
+                        self.dragid]['coords'] = [
+                        coords[0] + dx,
+                        coords[1] + dy]
                 self.dragid = -1
                 self.render['quick'] = False
                 self.Refresh(False)
-            
+
         elif self.mouse['use'] == 'rotate':
             self._display.UnsetRotation()
             self.iview['rotation'] = self._display.GetRotationMatrix()
             self.saveHistory = True
             self.render['quick'] = False
             self.Refresh(False)
-            
+
         elif self.mouse['use'] == 'pan':
             self.saveHistory = True
             self.render['quick'] = False
             self.Refresh(False)
-            
+
         elif self.mouse['use'] == 'fly':
             if self.fly['mouseControl']:
                 self.StopTimer(self.timerFly)
                 self.fly['mouseControl'] = None
-                #for key in self.iview['dir'].keys():
-                    #self.iview[''][key] = -1
+                # for key in self.iview['dir'].keys():
+                #self.iview[''][key] = -1
                 # this causes sudden change, but it should be there
-                #if hasattr(self.lmgr, "nviz"):
-                    #self.lmgr.nviz.UpdateSettings()
-                    
+                # if hasattr(self.lmgr, "nviz"):
+                # self.lmgr.nviz.UpdateSettings()
+
                 self.render['quick'] = False
                 self.Refresh(False)
-            
+
         elif self.mouse['use'] == 'zoom':
-            self.DoZoom(zoomtype = self.zoomtype, pos = self.mouse['end'])
+            self.DoZoom(zoomtype=self.zoomtype, pos=self.mouse['end'])
         event.Skip()
-            
+
     def OnDClick(self, event):
         """On mouse double click"""
-        if self.mouse['use'] != 'pointer': return
+        if self.mouse['use'] != 'pointer':
+            return
         pos = event.GetPositionTuple()
         self.dragid = self.FindObjects(pos[0], pos[1], self.hitradius)
         self.overlayActivated.emit(overlayId=self.dragid)
-    
+
     def FocusPanning(self, event):
         """Simulation of panning using focus"""
         size = self.GetClientSizeTuple()
         id1, x1, y1, z1 = self._display.GetPointOnSurface(
-                      self.mouse['tmp'][0], size[1] - self.mouse['tmp'][1])
+            self.mouse['tmp'][0], size[1] - self.mouse['tmp'][1])
         id2, x2, y2, z2 = self._display.GetPointOnSurface(
-                      event.GetX(), size[1] - event.GetY())
+            event.GetX(), size[1] - event.GetY())
         if id1 and id1 == id2:
             dx, dy, dz = x2 - x1, y2 - y1, z2 - z1
             focus = self.iview['focus']
@@ -905,43 +961,44 @@
             focus['x'] -= dx
             focus['y'] -= dy
             focus['z'] -= dz
-            
-            #update properties
+
+            # update properties
             self.PostViewEvent()
-            
+
             self.mouse['tmp'] = event.GetPositionTuple()
             self.render['quick'] = True
             self.Refresh(False)
-            
+
     def HorizontalPanning(self, event):
         """Move all layers in horizontal (x, y) direction.
         Currently not used.
         """
         size = self.GetClientSizeTuple()
         id1, x1, y1, z1 = self._display.GetPointOnSurface(
-                      self.mouse['tmp'][0], size[1] - self.mouse['tmp'][1])
+            self.mouse['tmp'][0], size[1] - self.mouse['tmp'][1])
         id2, x2, y2, z2 = self._display.GetPointOnSurface(
-                      event.GetX(), size[1] - event.GetY())
-        
+            event.GetX(), size[1] - event.GetY())
+
         if id1 and id1 == id2:
             dx, dy = x2 - x1, y2 - y1
             # find raster and volume
             for item in self.layers:
-                mapLayer = self.tree.GetLayerInfo(item, key = 'maplayer')
-                  
-                data = self.tree.GetLayerInfo(item, key = 'nviz')
+                mapLayer = self.tree.GetLayerInfo(item, key='maplayer')
+
+                data = self.tree.GetLayerInfo(item, key='nviz')
                 if mapLayer.GetType() == 'raster':
                     data['surface']['position']['x'] += dx
                     data['surface']['position']['y'] += dy
                     data['surface']['position']['update'] = None
-                    
-                    #update properties
-                    evt = wxUpdateProperties(data = data)
+
+                    # update properties
+                    evt = wxUpdateProperties(data=data)
                     wx.PostEvent(self, evt)
-                    
-                    if event.CmdDown() and id1 == data['surface']['object']['id']:
+
+                    if event.CmdDown() and id1 == data[
+                            'surface']['object']['id']:
                         break
-                    
+
                 elif mapLayer.GetType() == 'raster_3d':
                     if 'x' not in data['volume']['position']:
                         data['volume']['position']['x'] = 0
@@ -950,21 +1007,21 @@
                     data['volume']['position']['x'] += dx
                     data['volume']['position']['y'] += dy
                     data['volume']['position']['update'] = None
-                    
-                    #update properties
-                    evt = wxUpdateProperties(data = data)
+
+                    # update properties
+                    evt = wxUpdateProperties(data=data)
                     wx.PostEvent(self, evt)
-                
+
             self.mouse['tmp'] = event.GetPositionTuple()
             self.render['quick'] = True
             self.Refresh(False)
-            
+
     def DragItem(self, id, coords):
         """Drag an overlay decoration item
         """
         if id is None:
             return
-        Debug.msg (5, "GLWindow.DragItem(): id=%d" % id)
+        Debug.msg(5, "GLWindow.DragItem(): id=%d" % id)
         x, y = self.mouse['tmp']
         dx = coords[0] - x
         dy = coords[1] - y
@@ -972,12 +1029,11 @@
             if texture.id == id:
                 texture.MoveTexture(dx, dy)
 
-
         self.render['quick'] = True
         self.Refresh(False)
-        
+
         self.mouse['tmp'] = coords
-        
+
     def ZoomBack(self):
         """Set previous view in history list
         """
@@ -985,54 +1041,54 @@
         if len(self.viewhistory) > 1:
             self.viewhistory.pop()
             view = copy.deepcopy(self.viewhistory[-1])
-        
+
         # disable tool if stack is empty
-        if len(self.viewhistory) < 2: # disable tool
+        if len(self.viewhistory) < 2:  # disable tool
             self.zoomHistoryUnavailable.emit()
-            
+
         # set view and update nviz view page
-        self.lmgr.nviz.UpdateState(view = view[0], iview = view[1])
+        self.lmgr.nviz.UpdateState(view=view[0], iview=view[1])
         self.lmgr.nviz.UpdatePage('view')
         # update map
         self.Refresh(False)
 
     def ViewHistory(self, view, iview):
         """Manages a list of last 10 views
-        
+
         :param view: view dictionary
         :param iview: view dictionary (internal)
-        
+
         :return: removed history item if exists (or None)
         """
         removed = None
         hview = copy.deepcopy(view)
         hiview = copy.deepcopy(iview)
-        
-        if not (self.viewhistory and self.viewhistory[-1] == (hview, hiview)):  
+
+        if not (self.viewhistory and self.viewhistory[-1] == (hview, hiview)):
             self.viewhistory.append((hview, hiview))
-            
+
         if len(self.viewhistory) > 10:
             removed = self.viewhistory.pop(0)
-        
+
         if removed:
             Debug.msg(4, "GLWindow.ViewHistory(): hist=%s, removed=%s" %
                       (self.viewhistory, removed))
         else:
             Debug.msg(4, "GLWindow.ViewHistory(): hist=%s" %
                       (self.viewhistory))
-        
+
         # update toolbar
         if len(self.viewhistory) > 1:
             self.zoomHistoryAvailable.emit()
         else:
             self.zoomHistoryUnavailable.emit()
 
-        return removed     
-    
+        return removed
+
     def ResetViewHistory(self):
         """Reset view history"""
         self.viewhistory = list()
-    
+
     def GoTo(self, e, n):
         """Focus on given point"""
         w = self.Map.region['w']
@@ -1042,59 +1098,64 @@
         focus = self.iview['focus']
         focus['x'], focus['y'] = e, n
         self.saveHistory = True
-        #update properties
+        # update properties
         self.PostViewEvent()
-        
+
         self.render['quick'] = False
         self.Refresh(False)
-        
+
     def QuerySurface(self, x, y):
         """Query surface on given position"""
         size = self.GetClientSizeTuple()
         result = self._display.QueryMap(x, size[1] - y)
         if result:
             self.qpoints.append((result['x'], result['y'], result['z']))
-            self.log.WriteLog("%-30s: %.3f" % (_("Easting"),   result['x']))
-            self.log.WriteLog("%-30s: %.3f" % (_("Northing"),  result['y']))
+            self.log.WriteLog("%-30s: %.3f" % (_("Easting"), result['x']))
+            self.log.WriteLog("%-30s: %.3f" % (_("Northing"), result['y']))
             self.log.WriteLog("%-30s: %.3f" % (_("Elevation"), result['z']))
             name = ''
             for item in self.layers:
-                if self.tree.GetLayerInfo(item, key = 'maplayer').type == 'raster' and\
-                    self.tree.GetLayerInfo(item, key = 'nviz')['surface']['object']['id'] == result['id']:
-                    name = self.tree.GetLayerInfo(item, key = 'maplayer').name
+                if self.tree.GetLayerInfo(item, key='maplayer').type == 'raster' and self.tree.GetLayerInfo(
+                        item, key='nviz')['surface']['object']['id'] == result['id']:
+                    name = self.tree.GetLayerInfo(item, key='maplayer').name
             self.log.WriteLog("%-30s: %s" % (_("Surface map name"), name))
-            self.log.WriteLog("%-30s: %s" % (_("Surface map elevation"), result['elevation']))
-            self.log.WriteLog("%-30s: %s" % (_("Surface map color"), result['color']))
+            self.log.WriteLog(
+                "%-30s: %s" %
+                (_("Surface map elevation"), result['elevation']))
+            self.log.WriteLog("%-30s: %s" %
+                              (_("Surface map color"), result['color']))
             if len(self.qpoints) > 1:
                 prev = self.qpoints[-2]
                 curr = self.qpoints[-1]
-                dxy = math.sqrt(pow(prev[0]-curr[0], 2) +
-                                pow(prev[1]-curr[1], 2))
-                dxyz = math.sqrt(pow(prev[0]-curr[0], 2) +
-                                 pow(prev[1]-curr[1], 2) +
-                                 pow(prev[2]-curr[2], 2))
-                self.log.WriteLog("%-30s: %.3f" % (_("XY distance from previous"), dxy))
-                self.log.WriteLog("%-30s: %.3f" % (_("XYZ distance from previous"), dxyz))
-                self.log.WriteLog("%-30s: %.3f" % (_("Distance along surface"),
-                                              self._display.GetDistanceAlongSurface(result['id'],
-                                                                                    (curr[0], curr[1]),
-                                                                                    (prev[0], prev[1]),
-                                                                                    useExag = False)))
-                self.log.WriteLog("%-30s: %.3f" % (_("Distance along exag. surface"),
-                                              self._display.GetDistanceAlongSurface(result['id'],
-                                                                                    (curr[0], curr[1]),
-                                                                                    (prev[0], prev[1]),
-                                                                                      useExag = True)))
+                dxy = math.sqrt(pow(prev[0] - curr[0], 2) +
+                                pow(prev[1] - curr[1], 2))
+                dxyz = math.sqrt(pow(prev[0] - curr[0], 2) +
+                                 pow(prev[1] - curr[1], 2) +
+                                 pow(prev[2] - curr[2], 2))
+                self.log.WriteLog(
+                    "%-30s: %.3f" %
+                    (_("XY distance from previous"), dxy))
+                self.log.WriteLog(
+                    "%-30s: %.3f" %
+                    (_("XYZ distance from previous"), dxyz))
+                self.log.WriteLog(
+                    "%-30s: %.3f" %
+                    (_("Distance along surface"), self._display.GetDistanceAlongSurface(
+                        result['id'], (curr[0], curr[1]), (prev[0], prev[1]), useExag=False)))
+                self.log.WriteLog(
+                    "%-30s: %.3f" %
+                    (_("Distance along exag. surface"), self._display.GetDistanceAlongSurface(
+                        result['id'], (curr[0], curr[1]), (prev[0], prev[1]), useExag=True)))
             self.log.WriteCmdLog('-' * 80)
         else:
             self.log.WriteLog(_("No point on surface"))
             self.log.WriteCmdLog('-' * 80)
-    
-    def PostViewEvent(self, zExag = False):
+
+    def PostViewEvent(self, zExag=False):
         """Change view settings"""
-        event = wxUpdateView(zExag = zExag)
+        event = wxUpdateView(zExag=zExag)
         wx.PostEvent(self, event)
-        
+
     def OnQueryVector(self, event):
         """Query vector on given position"""
         self.parent.QueryVector(*event.GetPosition())
@@ -1104,69 +1165,78 @@
         view = self.view
         iview = self.iview
         (view['position']['x'], view['position']['y'],
-        iview['height']['value']) = self._display.GetViewpointPosition()
+         iview['height']['value']) = self._display.GetViewpointPosition()
         for key, val in zip(('x', 'y', 'z'), self._display.GetViewdir()):
             iview['dir'][key] = val
-        
+
         iview['dir']['use'] = True
-        
+
     def OnUpdateView(self, event):
         """Change view settings"""
         if event:
-                self.UpdateView(zexag = event.zExag)
-                
+            self.UpdateView(zexag=event.zExag)
+
         self.saveHistory = True
         if event:
             event.Skip()
-            
-            
-    def UpdateView(self, zexag = False):
+
+    def UpdateView(self, zexag=False):
         """Change view settings"""
         view = self.view
         iview = self.iview
         if zexag and 'value' in view['z-exag']:
-            self._display.SetZExag(view['z-exag']['value'] / iview['z-exag']['llRatio'])
-        
+            self._display.SetZExag(
+                view['z-exag']['value'] /
+                iview['z-exag']['llRatio'])
+
         self._display.SetView(view['position']['x'], view['position']['y'],
                               iview['height']['value'],
                               view['persp']['value'],
                               view['twist']['value'])
-        
+
         if iview['dir']['use']:
-            self._display.SetViewdir(iview['dir']['x'], iview['dir']['y'], iview['dir']['z'])
-        
+            self._display.SetViewdir(
+                iview['dir']['x'],
+                iview['dir']['y'],
+                iview['dir']['z'])
+
         elif iview['focus']['x'] != -1:
-            self._display.SetFocus(self.iview['focus']['x'], self.iview['focus']['y'],
-                                   self.iview['focus']['z'])
-                                       
+            self._display.SetFocus(
+                self.iview['focus']['x'],
+                self.iview['focus']['y'],
+                self.iview['focus']['z'])
+
         if 'rotation' in iview:
             if iview['rotation']:
                 self._display.SetRotationMatrix(iview['rotation'])
             else:
                 self._display.ResetRotation()
-        
+
     def UpdateLight(self, event):
         """Change light settings"""
         data = self.light
-        self._display.SetLight(x = data['position']['x'], y = data['position']['y'],
-                               z = data['position']['z'] / 100., color = data['color'],
-                               bright = data['bright'] / 100.,
-                               ambient = data['ambient'] / 100.)
+        self._display.SetLight(
+            x=data['position']['x'],
+            y=data['position']['y'],
+            z=data['position']['z'] / 100.,
+            color=data['color'],
+            bright=data['bright'] / 100.,
+            ambient=data['ambient'] / 100.)
         self._display.DrawLightingModel()
         if event.refresh:
             self.Refresh(False)
-        
-    def UpdateMap(self, render = True):
+
+    def UpdateMap(self, render=True):
         """Updates the canvas anytime there is a change to the
         underlaying images or to the geometry of the canvas.
-        
+
         :param render: re-render map composition
         :type render: bool
         """
         start = time.clock()
-        
+
         self.resize = False
-        
+
         if self.render['quick'] is False:
             if sys.platform != 'darwin':  # causes recursion for some reason on Mac
                 self.parent.GetProgressBar().Show()
@@ -1178,19 +1248,19 @@
                 self.parent.GetProgressBar().SetValue(1)
             self._display.Draw(False, -1)
             if self.saveHistory:
-                self.ViewHistory(view = self.view, iview = self.iview)
+                self.ViewHistory(view=self.view, iview=self.iview)
                 self.saveHistory = False
         elif self.render['quick'] is True:
             # quick
             mode = wxnviz.DRAW_QUICK_SURFACE | wxnviz.DRAW_QUICK_VOLUME
             if self.render['vlines']:
-                mode |=  wxnviz.DRAW_QUICK_VLINES
+                mode |= wxnviz.DRAW_QUICK_VLINES
             if self.render['vpoints']:
-                mode |=  wxnviz.DRAW_QUICK_VPOINTS
+                mode |= wxnviz.DRAW_QUICK_VPOINTS
             self._display.Draw(True, mode)
-        else: # None -> reuse last rendered image
-            pass # TODO
-            
+        else:  # None -> reuse last rendered image
+            pass  # TODO
+
         self.SwapBuffers()
         # draw fringe after SwapBuffers, otherwise it don't have to be visible
         # on some computers
@@ -1201,46 +1271,44 @@
             if self.decoration['scalebar']:
                 self._display.DrawScalebar()
         if self.imagelist:
-            if ((self.render['quick'] and self.dragid > -1) or # during dragging
-                (not self.render['quick'] and self.dragid < 0)): # redraw
+            if ((self.render['quick'] and self.dragid > -1) or  # during dragging
+                    (not self.render['quick'] and self.dragid < 0)):  # redraw
                 self._display.Start2D()
                 self.DrawImages()
-                
-            
-            
+
         stop = time.clock()
-        
+
         if self.render['quick'] is False:
             if sys.platform != 'darwin':
                 self.parent.GetProgressBar().SetValue(2)
                 # hide process bar
                 self.parent.GetProgressBar().Hide()
 
-        Debug.msg(3, "GLWindow.UpdateMap(): quick = %d, -> time = %g" % \
-                      (self.render['quick'], (stop-start)))
-        
+        Debug.msg(3, "GLWindow.UpdateMap(): quick = %d, -> time = %g" %
+                  (self.render['quick'], (stop - start)))
+
     def EraseMap(self):
         """Erase the canvas
         """
         self._display.EraseMap()
         self.SwapBuffers()
-    
+
     def _getDecorationSize(self):
         """Get initial size of north arrow/scalebar"""
         size = self._display.GetLongDim() / 8.
         coef = 0.01
         if size < 1:
             coef = 100.
-        return int(size * coef)/coef
-    
+        return int(size * coef) / coef
+
     def SetDrawArrow(self, pos):
         """North arrow drawing.
 
         Also, opens Appearance page of nviz notebook (needs refactoring).
         """
-        if self._display.SetArrow(pos[0], pos[1], 
-                                 self.decoration['arrow']['size'],
-                                 self.decoration['arrow']['color']):
+        if self._display.SetArrow(pos[0], pos[1],
+                                  self.decoration['arrow']['size'],
+                                  self.decoration['arrow']['color']):
             self._display.DrawArrow()
             # update
             self.decoration['arrow']['show'] = True
@@ -1256,15 +1324,20 @@
         """Add scale bar, sets properties and draw"""
         if len(self.decoration['scalebar']) == 0:
             self.decoration['scalebar'].append(
-                    self.nvizDefault.SetDecorDefaultProp(type = 'scalebar')['scalebar'])
+                self.nvizDefault.SetDecorDefaultProp(
+                    type='scalebar')['scalebar'])
             self.decoration['scalebar'][0]['size'] = self._getDecorationSize()
         else:
-            self.decoration['scalebar'].append(copy.deepcopy(self.decoration['scalebar'][-1]))
+            self.decoration['scalebar'].append(
+                copy.deepcopy(self.decoration['scalebar'][-1]))
             self.decoration['scalebar'][-1]['id'] += 1
-        
-        ret = self._display.SetScalebar(self.decoration['scalebar'][-1]['id'], pos[0], pos[1], 
-                                 self.decoration['scalebar'][-1]['size'],
-                                 self.decoration['scalebar'][-1]['color'])
+
+        ret = self._display.SetScalebar(
+            self.decoration['scalebar'][-1]['id'],
+            pos[0],
+            pos[1],
+            self.decoration['scalebar'][-1]['size'],
+            self.decoration['scalebar'][-1]['color'])
         if ret:
             self._display.DrawScalebar()
             # update
@@ -1272,143 +1345,146 @@
             self.decoration['scalebar'][-1]['position']['y'] = pos[1]
             self.Refresh(False)
         self.lmgr.nviz.SetPage('decoration')
-        
+
     def IsLoaded(self, item):
         """Check if layer (item) is already loaded
-        
+
         :param item: layer item
         """
-        layer = self.tree.GetLayerInfo(item, key = 'maplayer')
-        data = self.tree.GetLayerInfo(item, key = 'nviz')
-        
+        layer = self.tree.GetLayerInfo(item, key='maplayer')
+        data = self.tree.GetLayerInfo(item, key='nviz')
+
         if not data:
             return 0
-        
-        if layer.type ==  'raster':
+
+        if layer.type == 'raster':
             if 'object' not in data['surface']:
                 return 0
-        elif layer.type ==  'vector':
+        elif layer.type == 'vector':
             if 'object' not in data['vector']['lines'] and \
                     'object' not in data['vector']['points']:
                 return 0
-        
+
         return 1
 
     def _GetDataLayers(self, item, litems):
         """Return get list of enabled map layers"""
         # load raster & vector maps
         while item and item.IsOk():
-            type = self.tree.GetLayerInfo(item, key = 'type')
-            if type ==  'group':
+            type = self.tree.GetLayerInfo(item, key='type')
+            if type == 'group':
                 item = self.tree.GetNextItem(item)
                 continue
-                
+
             if not item.IsChecked() or \
                     type not in ('raster', 'vector', 'raster_3d'):
                 item = self.tree.GetNextItem(item)
                 continue
-            
+
             litems.append(item)
-            
+
             item = self.tree.GetNextItem(item)
-        
+
     def LoadDataLayers(self):
         """Load raster/vector from current layer tree
-        
+
         .. todo::
             volumes
         """
         if not self.tree:
             return
-        
+
         listOfItems = []
         item = self.tree.GetFirstChild(self.tree.root)[0]
         self._GetDataLayers(item, listOfItems)
-        
+
         start = time.time()
-        
+
         while(len(listOfItems) > 0):
             item = listOfItems.pop()
-            type = self.tree.GetLayerInfo(item, key = 'type')
+            type = self.tree.GetLayerInfo(item, key='type')
             if item in self.layers:
                 continue
-            # "raster (double click to set properties)" - tries to load this 
+            # "raster (double click to set properties)" - tries to load this
             # layer - no idea how to fix it
-            if ' ' in self.tree.GetLayerInfo(item, key = 'maplayer').name:
+            if ' ' in self.tree.GetLayerInfo(item, key='maplayer').name:
                 return
             try:
-                if type ==  'raster':
+                if type == 'raster':
                     self.LoadRaster(item)
-                elif type ==  'raster_3d':
+                elif type == 'raster_3d':
                     self.LoadRaster3d(item)
-                elif type ==  'vector':
-                    layer = self.tree.GetLayerInfo(item, key = 'maplayer')
+                elif type == 'vector':
+                    layer = self.tree.GetLayerInfo(item, key='maplayer')
                     vInfo = grass.vector_info_topo(layer.GetName())
                     if (vInfo['points']) > 0:
-                        # include vInfo['centroids'] to initially load centroids 
-                        self.LoadVector(item, points = True)
+                        # include vInfo['centroids'] to initially load
+                        # centroids
+                        self.LoadVector(item, points=True)
                     if (vInfo['lines'] + vInfo['boundaries']) > 0:
-                        self.LoadVector(item, points = False)
-                    if vInfo['map3d'] and (vInfo['kernels'] + vInfo['faces']) > 0:
+                        self.LoadVector(item, points=False)
+                    if vInfo['map3d'] and(
+                            vInfo['kernels'] + vInfo['faces']) > 0:
                         self.LoadVector(item, points=None)
-                    
+
             except GException as e:
-                GError(parent = self,
-                       message = e.value)
-        
+                GError(parent=self,
+                       message=e.value)
+
         stop = time.time()
-        
-        Debug.msg(1, "GLWindow.LoadDataLayers(): time = %f" % (stop-start))
-                
-    def UnloadDataLayers(self, force = False):
+
+        Debug.msg(1, "GLWindow.LoadDataLayers(): time = %f" % (stop - start))
+
+    def UnloadDataLayers(self, force=False):
         """Unload any layers that have been deleted from layer tree
 
         :param bool force: True to unload all data layers
         """
         if not self.tree:
             return
-        
+
         listOfItems = []
         if not force:
             item = self.tree.GetFirstChild(self.tree.root)[0]
             self._GetDataLayers(item, listOfItems)
-        
+
         start = time.time()
-        
+
         update = False
         layersTmp = self.layers[:]
         for layer in layersTmp:
             if layer in listOfItems:
                 continue
-            ltype = self.tree.GetLayerInfo(layer, key = 'type')
+            ltype = self.tree.GetLayerInfo(layer, key='type')
             try:
-                if ltype ==  'raster':
+                if ltype == 'raster':
                     self.UnloadRaster(layer)
-                elif ltype ==  'raster_3d':
-                    self.UnloadRaster3d(layer) 
-                elif ltype ==  'vector':
-                    maplayer = self.tree.GetLayerInfo(layer, key = 'maplayer')
+                elif ltype == 'raster_3d':
+                    self.UnloadRaster3d(layer)
+                elif ltype == 'vector':
+                    maplayer = self.tree.GetLayerInfo(layer, key='maplayer')
                     vInfo = grass.vector_info_topo(maplayer.GetName())
                     if (vInfo['points'] + vInfo['centroids']) > 0:
-                        self.UnloadVector(layer, points = True)
-                    if (vInfo['lines'] + vInfo['boundaries']) > 0 or vInfo['map3d']:
-                        self.UnloadVector(layer, points = False)
-                        
+                        self.UnloadVector(layer, points=True)
+                    if (vInfo['lines'] + vInfo['boundaries']
+                        ) > 0 or vInfo['map3d']:
+                        self.UnloadVector(layer, points=False)
+
             except GException as e:
-                GError(parent = self,
-                       message = e.value)
-        
-        if force and self.baseId > 0: # unload base surface when quitting
+                GError(parent=self,
+                       message=e.value)
+
+        if force and self.baseId > 0:  # unload base surface when quitting
             ret = self._display.UnloadSurface(self.baseId)
             self.baseId = -1
         if update:
-            self.lmgr.nviz.UpdateSettings()        
+            self.lmgr.nviz.UpdateSettings()
             self.UpdateView(None)
-        
+
         stop = time.time()
-        
-        Debug.msg(1, "GLWindow.UnloadDataLayers(): time = %f" % (stop-start))        
-        
+
+        Debug.msg(1, "GLWindow.UnloadDataLayers(): time = %f" % (stop - start))
+
     def SetVectorSurface(self, data):
         """Set reference surfaces of vector"""
         data['mode']['surface'] = {}
@@ -1417,14 +1493,14 @@
         for name in self.GetLayerNames('raster'):
             data['mode']['surface']['value'].append(name)
             data['mode']['surface']['show'].append(True)
-        
+
     def SetVectorFromCmd(self, item, data):
         """Set 3D view properties from cmd (d.vect)
 
         :param item: Layer Tree item
         :param nviz: data
         """
-        cmd = self.tree.GetLayerInfo(item, key = 'cmd')
+        cmd = self.tree.GetLayerInfo(item, key='cmd')
         if cmd[0] != 'd.vect':
             return
         for opt in cmd[1:]:
@@ -1440,151 +1516,162 @@
 
     def SetMapObjProperties(self, item, id, nvizType):
         """Set map object properties
-        
+
         Properties must be afterwards updated by
         UpdateMapObjProperties().
-        
+
         :param item: layer item
         :param id: nviz layer id (or -1)
         :param nvizType: nviz data type (surface, points, vector)
         """
         if nvizType != 'constant':
-            mapType = self.tree.GetLayerInfo(item, key = 'maplayer').type
+            mapType = self.tree.GetLayerInfo(item, key='maplayer').type
             # reference to original layer properties (can be None)
-            data = self.tree.GetLayerInfo(item, key = 'nviz')
+            data = self.tree.GetLayerInfo(item, key='nviz')
         else:
             mapType = nvizType
             data = self.constants[item]
-        
+
         if not data:
             # init data structure
             if nvizType != 'constant':
-                self.tree.SetLayerInfo(item, key = 'nviz', value = {})
-                data = self.tree.GetLayerInfo(item, key = 'nviz')
-            
-            if mapType ==  'raster':
+                self.tree.SetLayerInfo(item, key='nviz', value={})
+                data = self.tree.GetLayerInfo(item, key='nviz')
+
+            if mapType == 'raster':
                 # reset to default properties
                 data[nvizType] = self.nvizDefault.SetSurfaceDefaultProp()
-                        
-            elif mapType ==  'vector':
+
+            elif mapType == 'vector':
                 # reset to default properties (lines/points)
                 data['vector'] = self.nvizDefault.SetVectorDefaultProp()
                 self.SetVectorFromCmd(item, data['vector'])
                 self.SetVectorSurface(data['vector']['points'])
                 self.SetVectorSurface(data['vector']['lines'])
-                
-            elif mapType ==  'raster_3d':
-                # reset to default properties 
+
+            elif mapType == 'raster_3d':
+                # reset to default properties
                 data[nvizType] = self.nvizDefault.SetVolumeDefaultProp()
-                
+
             elif mapType == 'constant':
                 data['constant'] = self.nvizDefault.SetConstantDefaultProp()
-        
+
         else:
             # complete data (use default values), not sure if this is necessary
-            if mapType ==  'raster':
+            if mapType == 'raster':
                 if not data['surface']:
                     data['surface'] = self.nvizDefault.SetSurfaceDefaultProp()
-            if mapType ==  'vector':
+            if mapType == 'vector':
                 if not data['vector']['lines']:
-                    self.nvizDefault.SetVectorLinesDefaultProp(data['vector']['lines'])
+                    self.nvizDefault.SetVectorLinesDefaultProp(
+                        data
+                        ['vector']
+                        ['lines'])
                 if not data['vector']['points']:
-                    self.nvizDefault.SetVectorPointsDefaultProp(data['vector']['points'])     
+                    self.nvizDefault.SetVectorPointsDefaultProp(
+                        data
+                        ['vector']
+                        ['points'])
             # set updates
             for sec in data.keys():
                 for sec1 in data[sec].keys():
                     if sec1 == 'position':
                         data[sec][sec1]['update'] = None
                         continue
-                    if type(data[sec][sec1]) == types.DictType:
+                    if isinstance(data[sec][sec1], types.DictType):
                         for sec2 in data[sec][sec1].keys():
                             if sec2 not in ('all', 'init', 'id'):
                                 data[sec][sec1][sec2]['update'] = None
-                    elif type(data[sec][sec1]) == types.ListType:
+                    elif isinstance(data[sec][sec1], types.ListType):
                         for i in range(len(data[sec][sec1])):
                             for sec2 in data[sec][sec1][i].keys():
                                 data[sec][sec1][i][sec2]['update'] = None
-            event = wxUpdateProperties(data = data)
+            event = wxUpdateProperties(data=data)
             wx.PostEvent(self, event)
-        
+
         # set id
         if id > 0:
             if mapType in ('raster', 'raster_3d'):
-                data[nvizType]['object'] = { 'id' : id,
-                                            'init' : False }
-            elif mapType ==  'vector':
-                data['vector'][nvizType]['object'] = { 'id' : id,
-                                                       'init' : False }
-            elif mapType ==  'constant':
-                data[nvizType]['object'] = { 'id' : id,
-                                             'init' : False }
-        
+                data[nvizType]['object'] = {'id': id,
+                                            'init': False}
+            elif mapType == 'vector':
+                data['vector'][nvizType]['object'] = {'id': id,
+                                                      'init': False}
+            elif mapType == 'constant':
+                data[nvizType]['object'] = {'id': id,
+                                            'init': False}
+
         return data
 
     def LoadRaster(self, item):
         """Load 2d raster map and set surface attributes
-        
+
         :param layer: item
         """
         return self._loadRaster(item)
-    
+
     def LoadRaster3d(self, item):
         """Load 3d raster map and set surface attributes
-        
+
         :param layer: item
         """
         return self._loadRaster(item)
-        
+
     def _loadRaster(self, item):
         """Load 2d/3d raster map and set its attributes
-        
+
         :param layer: item
         """
-        layer = self.tree.GetLayerInfo(item, key = 'maplayer')
-        
+        layer = self.tree.GetLayerInfo(item, key='maplayer')
+
         if layer.type not in ('raster', 'raster_3d'):
             return
-        
-        if layer.type ==  'raster':
+
+        if layer.type == 'raster':
             id = self._display.LoadSurface(str(layer.name), None, None)
             nvizType = 'surface'
             errorMsg = _("Loading raster map")
-        elif layer.type ==  'raster_3d':
+        elif layer.type == 'raster_3d':
             id = self._display.LoadVolume(str(layer.name), None, None)
             nvizType = 'volume'
             errorMsg = _("Loading 3d raster map")
         else:
             id = -1
-        
+
         if id < 0:
             if layer.type in ('raster', 'raster_3d'):
-                self.log.WriteError("%s <%s> %s" % (errorMsg, layer.name, _("failed")))
+                self.log.WriteError(
+                    "%s <%s> %s" %
+                    (errorMsg, layer.name, _("failed")))
             else:
-                self.log.WriteError(_("Unsupported layer type '%s'") % layer.type)
-        
+                self.log.WriteError(
+                    _("Unsupported layer type '%s'") %
+                    layer.type)
+
         self.layers.append(item)
-        
+
         # set default/workspace layer properties
         data = self.SetMapObjProperties(item, id, nvizType)
-        
+
         # update properties
-        event = wxUpdateProperties(data = data)
+        event = wxUpdateProperties(data=data)
         wx.PostEvent(self, event)
-        
+
         # update tools window
-        if hasattr(self.lmgr, "nviz") and \
-                item == self.tree.GetSelectedLayer(multi = False, checkedOnly = True):
+        if hasattr(
+                self.lmgr, "nviz") and item == self.tree.GetSelectedLayer(
+                multi=False, checkedOnly=True):
             toolWin = self.lmgr.nviz
-            if layer.type ==  'raster':
-                win = toolWin.FindWindowById( \
+            if layer.type == 'raster':
+                win = toolWin.FindWindowById(
                     toolWin.win['vector']['lines']['surface'])
                 win.SetItems(self.GetLayerNames(layer.type))
-            
-            #toolWin.UpdatePage(nvizType)
-            #toolWin.SetPage(nvizType)
-        
+
+            # toolWin.UpdatePage(nvizType)
+            # toolWin.SetPage(nvizType)
+
         return id
-    
+
     def NewConstant(self):
         """Create new constant"""
         index = len(self.constants)
@@ -1594,27 +1681,31 @@
             name = 1
         data = dict()
         self.constants.append(data)
-        data = self.SetMapObjProperties(item = index, id = -1, nvizType = 'constant')
+        data = self.SetMapObjProperties(item=index, id=-1, nvizType='constant')
         self.AddConstant(data, name)
         return name
-        
+
     def AddConstant(self, data, name):
         """Add new constant"""
-        id = self._display.AddConstant(value = data['constant']['value'], color = data['constant']['color'])
-        self._display.SetSurfaceRes(id, data['constant']['resolution'], data['constant']['resolution'])
-        data['constant']['object'] = { 'id' : id,
-                                       'name': name,
-                                       'init' : False }
-    
+        id = self._display.AddConstant(
+            value=data['constant']['value'],
+            color=data['constant']['color'])
+        self._display.SetSurfaceRes(
+            id, data['constant']['resolution'],
+            data['constant']['resolution'])
+        data['constant']['object'] = {'id': id,
+                                      'name': name,
+                                      'init': False}
+
     def DeleteConstant(self, index):
         """Delete constant layer"""
         id = self.constants[index]['constant']['object']['id']
         self._display.UnloadSurface(id)
         del self.constants[index]
-    
+
     def SelectCPlane(self, index):
         """Select cutting plane"""
-        for plane in range (self._display.GetCPlanesCount()):
+        for plane in range(self._display.GetCPlanesCount()):
             if plane == index:
                 self._display.SelectCPlane(plane)
                 self.cplanes[plane]['on'] = True
@@ -1625,7 +1716,7 @@
                     self.cplanes[plane]['on'] = False
                 except IndexError:
                     pass
-                    
+
     def OnUpdateCPlane(self, event):
         """Change cutting plane settings"""
         self.UpdateCPlane(event.current, event.update)
@@ -1634,42 +1725,44 @@
         """Change cutting plane settings"""
         for each in changes:
             if each == 'rotation':
-                self._display.SetCPlaneRotation(0, self.cplanes[index]['rotation']['tilt'],
-                                                   self.cplanes[index]['rotation']['rot'])
+                self._display.SetCPlaneRotation(
+                    0, self.cplanes[index]['rotation']['tilt'],
+                    self.cplanes[index]['rotation']['rot'])
             if each == 'position':
-                self._display.SetCPlaneTranslation(self.cplanes[index]['position']['x'],
-                                                   self.cplanes[index]['position']['y'],
-                                                   self.cplanes[index]['position']['z'])
+                self._display.SetCPlaneTranslation(
+                    self.cplanes[index]['position']['x'],
+                    self.cplanes[index]['position']['y'],
+                    self.cplanes[index]['position']['z'])
             if each == 'shading':
                 self._display.SetFenceColor(self.cplanes[index]['shading'])
-            
+
     def UnloadRaster(self, item):
         """Unload 2d raster map
-        
+
         :param layer: item
         """
         return self._unloadRaster(item)
-    
+
     def UnloadRaster3d(self, item):
         """Unload 3d raster map
-        
+
         :param layer: item
         """
         return self._unloadRaster(item)
-    
+
     def _unloadRaster(self, item):
         """Unload 2d/3d raster map
-        
+
         :param item: layer item
         """
-        layer = self.tree.GetLayerInfo(item, key = 'maplayer')
-        
+        layer = self.tree.GetLayerInfo(item, key='maplayer')
+
         if layer.type not in ('raster', 'raster_3d'):
             return
-        
-        data = self.tree.GetLayerInfo(item, key = 'nviz')
-        
-        if layer.type ==  'raster':
+
+        data = self.tree.GetLayerInfo(item, key='nviz')
+
+        if layer.type == 'raster':
             nvizType = 'surface'
             unloadFn = self._display.UnloadSurface
             errorMsg = _("Unable to unload raster map")
@@ -1679,48 +1772,51 @@
             unloadFn = self._display.UnloadVolume
             errorMsg = _("Unable to unload 3d raster map")
             successMsg = _("3d raster map")
-        
+
         try:
             id = data[nvizType]['object']['id']
         except KeyError:
             return
-        
-        if unloadFn(id) ==  0:
+
+        if unloadFn(id) == 0:
             self.log.WriteError("%s <%s>" % (errorMsg, layer.name))
         else:
-            self.log.WriteLog("%s <%s> %s" % (successMsg, layer.name, _("unloaded successfully")))
-        
+            self.log.WriteLog(
+                "%s <%s> %s" %
+                (successMsg, layer.name, _("unloaded successfully")))
+
         data[nvizType].pop('object')
-        
+
         self.layers.remove(item)
-        
+
         # update tools window
         if hasattr(self.lmgr, "nviz"):
             toolWin = self.lmgr.nviz
-            if layer.type ==  'raster':
-                win = toolWin.FindWindowById(toolWin.win['vector']['lines']['surface'])
+            if layer.type == 'raster':
+                win = toolWin.FindWindowById(
+                    toolWin.win['vector']['lines']['surface'])
                 win.SetItems(self.GetLayerNames(layer.type))
                 win = toolWin.FindWindowById(toolWin.win['surface']['map'])
                 win.SetValue('')
-            if layer.type ==  'raster_3d':
+            if layer.type == 'raster_3d':
                 win = toolWin.FindWindowById(toolWin.win['volume']['map'])
                 win.SetValue('')
-            if layer.type ==  'vector':
+            if layer.type == 'vector':
                 win = toolWin.FindWindowById(toolWin.win['vector']['map'])
                 win.SetValue('')
-        
-    def LoadVector(self, item, points = None, append = True):
+
+    def LoadVector(self, item, points=None, append=True):
         """Load 2D or 3D vector map overlay
-        
+
         :param item: layer item
         :param points: True to load points, False to load lines, None
                        to load both
         :param bool append: append vector to layer list
         """
-        layer = self.tree.GetLayerInfo(item, key = 'maplayer')
-        if layer.type !=  'vector':
+        layer = self.tree.GetLayerInfo(item, key='maplayer')
+        if layer.type != 'vector':
             return
-        
+
         # set default properties
         if points is None:
             self.SetMapObjProperties(item, -1, 'lines')
@@ -1732,82 +1828,90 @@
         else:
             self.SetMapObjProperties(item, -1, 'lines')
             vecTypes = ('lines', )
-        
+
         id = -1
         for vecType in vecTypes:
             if vecType == 'lines':
-                id, baseId = self._display.LoadVector(str(layer.GetName()), False)
+                id, baseId = self._display.LoadVector(
+                    str(layer.GetName()), False)
             else:
-                id, baseId = self._display.LoadVector(str(layer.GetName()), True)
+                id, baseId = self._display.LoadVector(
+                    str(layer.GetName()), True)
             if id < 0:
-                self.log.WriteError(_("Loading vector map <%(name)s> (%(type)s) failed") % \
-                    { 'name' : layer.name, 'type' : vecType })
+                self.log.WriteError(
+                    _("Loading vector map <%(name)s> (%(type)s) failed") %
+                    {'name': layer.name, 'type': vecType})
             # update layer properties
             self.SetMapObjProperties(item, id, vecType)
         if baseId > 0:
-            self.baseId = baseId # id of base surface (when no surface is loaded)
+            # id of base surface (when no surface is loaded)
+            self.baseId = baseId
         if append:
             self.layers.append(item)
-        
+
         # update properties
-        data = self.tree.GetLayerInfo(item, key = 'nviz')
-        event = wxUpdateProperties(data = data)
+        data = self.tree.GetLayerInfo(item, key='nviz')
+        event = wxUpdateProperties(data=data)
         wx.PostEvent(self, event)
-        
+
         # update tools window
-        if hasattr(self.lmgr, "nviz") and \
-                item ==  self.tree.GetSelectedLayer(multi = False, checkedOnly = True):
+        if hasattr(
+                self.lmgr, "nviz") and item == self.tree.GetSelectedLayer(
+                multi=False, checkedOnly=True):
             toolWin = self.lmgr.nviz
-            
+
             toolWin.UpdatePage('vector')
-            ### toolWin.SetPage('vector')
-        
+            # toolWin.SetPage('vector')
+
         return id
 
-    def UnloadVector(self, item, points = None, remove = True):
+    def UnloadVector(self, item, points=None, remove=True):
         """Unload vector map overlay
-        
+
         :param item: layer item
         :param points, lines: True to unload given feature type
         :param remove: remove layer from list
         :type remove: bool
         """
-        layer = self.tree.GetLayerInfo(item, key = 'maplayer')
-        data = self.tree.GetLayerInfo(item, key = 'nviz')['vector']
-        
+        layer = self.tree.GetLayerInfo(item, key='maplayer')
+        data = self.tree.GetLayerInfo(item, key='nviz')['vector']
+
         # if vecType is None:
         #     vecType = []
         #     for v in ('lines', 'points'):
         #         if UserSettings.Get(group = 'nviz', key = 'vector',
         #                             subkey = [v, 'show']):
         #             vecType.append(v)
-        
+
         if points is None:
             vecTypes = ('points', 'lines')
         elif points:
             vecTypes = ('points', )
         else:
             vecTypes = ('lines', )
-        
+
         for vecType in vecTypes:
             if 'object' not in data[vecType]:
                 continue
 
             id = data[vecType]['object']['id']
-            
-            if vecType ==  'lines':
+
+            if vecType == 'lines':
                 ret = self._display.UnloadVector(id, False)
             else:
                 ret = self._display.UnloadVector(id, True)
-            if ret ==  0:
-                self.log.WriteError(_("Unable to unload vector map <%(name)s> (%(type)s)") % \
-                    { 'name': layer.name, 'type' : vecType })
+            if ret == 0:
+                self.log.WriteError(
+                    _("Unable to unload vector map <%(name)s> (%(type)s)") %
+                    {'name': layer.name, 'type': vecType})
             else:
-                self.log.WriteLog(_("Vector map <%(name)s> (%(type)s) unloaded successfully") % \
-                    { 'name' : layer.name, 'type' : vecType })
-            
+                self.log.WriteLog(
+                    _("Vector map <%(name)s> (%(type)s) unloaded successfully") % {
+                        'name': layer.name,
+                        'type': vecType})
+
             data[vecType].pop('object')
-            
+
         if remove and item in self.layers:
             self.layers.remove(item)
 
@@ -1817,49 +1921,50 @@
             self.iview['height']['value'], \
             self.iview['height']['min'], \
             self.iview['height']['max'] = self._display.SetViewDefault()
-        
-        ## hack for latlon projection
-        ## TODO find more precise way or better rewrite it in OGSF
+
+        # hack for latlon projection
+        # TODO find more precise way or better rewrite it in OGSF
         self.iview['z-exag']['llRatio'] = 1
         if grass.locn_is_latlong():
-            self.iview['z-exag']['llRatio'] = \
-                math.pi / 180 * 6371000 * math.cos((grass.region()['n'] + grass.region()['s']) / 2)
+            self.iview['z-exag']['llRatio'] = math.pi / 180 * 6371000 * math.cos(
+                (grass.region()['n'] + grass.region()['s']) / 2)
 
-        self.view['z-exag']['value'] = round(zexagOriginal * self.iview['z-exag']['llRatio'])
-        self.view['z-exag']['min'] = UserSettings.Get(group = 'nviz', key = 'view',
-                                                      subkey = ('z-exag', 'min'))
-        zexagMax = UserSettings.Get(group = 'nviz', key = 'view',
-                                    subkey = ('z-exag', 'max'))
+        self.view[
+            'z-exag']['value'] = round(zexagOriginal * self.iview['z-exag']['llRatio'])
+        self.view['z-exag']['min'] = UserSettings.Get(group='nviz', key='view',
+                                                      subkey=('z-exag', 'min'))
+        zexagMax = UserSettings.Get(group='nviz', key='view',
+                                    subkey=('z-exag', 'max'))
         if zexagMax <= self.view['z-exag']['value']:
             self.view['z-exag']['max'] = self.view['z-exag']['value'] * 2
         elif self.view['z-exag']['value'] < 1:
             if self.view['z-exag']['value'] == 0:
                 self.view['z-exag']['value'] = 1
-            self.view['z-exag']['max'] = 10 * self.view['z-exag']['value'] 
-        else: 
+            self.view['z-exag']['max'] = 10 * self.view['z-exag']['value']
+        else:
             self.view['z-exag']['max'] = zexagMax
-        
-        self.view['position']['x'] = UserSettings.Get(group = 'nviz', key = 'view',
-                                                 subkey = ('position', 'x'))
-        self.view['position']['y'] = UserSettings.Get(group = 'nviz', key = 'view',
-                                                 subkey = ('position', 'y'))
-        self.view['persp']['value'] = UserSettings.Get(group = 'nviz', key = 'view',
-                                                       subkey = ('persp', 'value'))
-        
-        self.view['twist']['value'] = UserSettings.Get(group = 'nviz', key = 'view',
-                                                       subkey = ('twist', 'value'))
+
+        self.view['position']['x'] = UserSettings.Get(group='nviz', key='view',
+                                                      subkey=('position', 'x'))
+        self.view['position']['y'] = UserSettings.Get(group='nviz', key='view',
+                                                      subkey=('position', 'y'))
+        self.view['persp']['value'] = UserSettings.Get(
+            group='nviz', key='view', subkey=('persp', 'value'))
+
+        self.view['twist']['value'] = UserSettings.Get(
+            group='nviz', key='view', subkey=('twist', 'value'))
         self._display.ResetRotation()
         self.iview['rotation'] = None
         self._display.LookAtCenter()
         focus = self.iview['focus']
         focus['x'], focus['y'], focus['z'] = self._display.GetFocus()
-        
+
         self.PostViewEvent()
-        
+
     def UpdateMapObjProperties(self, event):
         """Generic method to update data layer properties"""
         data = event.data
-        
+
         if 'surface' in data:
             try:
                 id = data['surface']['object']['id']
@@ -1868,19 +1973,19 @@
             self.UpdateSurfaceProperties(id, data['surface'])
             # -> initialized
             data['surface']['object']['init'] = True
-            
+
         elif 'constant' in data:
             id = data['constant']['object']['id']
             self.UpdateConstantProperties(id, data['constant'])
             # -> initialized
-            data['constant']['object']['init'] = True  
-              
+            data['constant']['object']['init'] = True
+
         elif 'volume' in data:
             id = data['volume']['object']['id']
             self.UpdateVolumeProperties(id, data['volume'])
             # -> initialized
             data['volume']['object']['init'] = True
-            
+
         elif 'vector' in data:
             for type in ('lines', 'points'):
                 if 'object' in data['vector'][type]:
@@ -1888,81 +1993,82 @@
                     self.UpdateVectorProperties(id, data['vector'], type)
                     # -> initialized
                     data['vector'][type]['object']['init'] = True
-    
+
     def UpdateConstantProperties(self, id, data):
         """Update surface map object properties"""
-        self._display.SetSurfaceColor(id = id, map = False, value = data['color'])
-        self._display.SetSurfaceTopo(id = id, map = False, value = data['value'])
+        self._display.SetSurfaceColor(id=id, map=False, value=data['color'])
+        self._display.SetSurfaceTopo(id=id, map=False, value=data['value'])
         self._display.SetSurfaceRes(id, data['resolution'], data['resolution'])
         if data['transp'] == 0:
             self._display.UnsetSurfaceTransp(id)
         else:
-            self._display.SetSurfaceTransp(id, map = False, value = data['transp'])
-            
+            self._display.SetSurfaceTransp(id, map=False, value=data['transp'])
+
     def UpdateSurfaceProperties(self, id, data):
         """Update surface map object properties"""
         # surface attributes
         for attrb in ('color', 'mask',
-                     'transp', 'shine'):
+                      'transp', 'shine'):
             if attrb not in data['attribute'] or \
                     'update' not in data['attribute'][attrb]:
                 continue
-            
+
             map = data['attribute'][attrb]['map']
             value = data['attribute'][attrb]['value']
-            
-            if map is None: # unset
+
+            if map is None:  # unset
                 # only optional attributes
-                if attrb ==  'mask':
+                if attrb == 'mask':
                     # TODO: invert mask
                     # TODO: broken in NVIZ
                     self._display.UnsetSurfaceMask(id)
-                elif attrb ==  'transp':
-                    self._display.UnsetSurfaceTransp(id) 
+                elif attrb == 'transp':
+                    self._display.UnsetSurfaceTransp(id)
             else:
-                if type(value) == types.StringType:
+                if isinstance(value, types.StringType):
                     if len(value) == 0:  # ignore empty values (TODO: warning)
                         continue
-                    if map and not grass.find_file(value, element='cell')['fullname']:
+                    if map and not grass.find_file(value, element='cell')[
+                            'fullname']:
                         continue
-                if attrb ==  'color':
+                if attrb == 'color':
                     self._display.SetSurfaceColor(id, map, str(value))
-                elif attrb ==  'mask':
+                elif attrb == 'mask':
                     # TODO: invert mask
                     # TODO: broken in NVIZ
                     self._display.SetSurfaceMask(id, False, str(value))
-                elif attrb ==  'transp':
-                    self._display.SetSurfaceTransp(id, map, str(value)) 
-                elif attrb ==  'shine':
-                    self._display.SetSurfaceShine(id, map, str(value)) 
+                elif attrb == 'transp':
+                    self._display.SetSurfaceTransp(id, map, str(value))
+                elif attrb == 'shine':
+                    self._display.SetSurfaceShine(id, map, str(value))
             data['attribute'][attrb].pop('update')
-        
+
         # draw res
         if 'update' in data['draw']['resolution']:
             coarse = data['draw']['resolution']['coarse']
-            fine   = data['draw']['resolution']['fine']
-            
+            fine = data['draw']['resolution']['fine']
+
             if data['draw']['all']:
                 self._display.SetSurfaceRes(-1, fine, coarse)
             else:
                 self._display.SetSurfaceRes(id, fine, coarse)
             data['draw']['resolution'].pop('update')
-        
+
         # draw style
         if 'update' in data['draw']['mode']:
-            if data['draw']['mode']['value'] < 0: # need to calculate
-                data['draw']['mode']['value'] = \
-                    self.nvizDefault.GetDrawMode(mode = data['draw']['mode']['desc']['mode'],
-                                                 style = data['draw']['mode']['desc']['style'],
-                                                 shade = data['draw']['mode']['desc']['shading'],
-                                                 string = True)
+            if data['draw']['mode']['value'] < 0:  # need to calculate
+                data['draw']['mode']['value'] = self.nvizDefault.GetDrawMode(
+                    mode=data['draw']['mode']['desc']['mode'],
+                    style=data['draw']['mode']['desc']['style'],
+                    shade=data['draw']['mode']['desc']['shading'],
+                    string=True)
             style = data['draw']['mode']['value']
             if data['draw']['all']:
                 self._display.SetSurfaceStyle(-1, style)
             else:
                 self._display.SetSurfaceStyle(id, style)
             data['draw']['mode'].pop('update')
-        
+
         # wire color
         if 'update' in data['draw']['wire-color']:
             color = data['draw']['wire-color']['value']
@@ -1971,7 +2077,7 @@
             else:
                 self._display.SetWireColor(id, str(color))
             data['draw']['wire-color'].pop('update')
-        
+
         # position
         if 'update' in data['position']:
             x = data['position']['x']
@@ -1980,37 +2086,41 @@
             self._display.SetSurfacePosition(id, x, y, z)
             data['position'].pop('update')
         data['draw']['all'] = False
-        
-    def UpdateVolumeProperties(self, id, data, isosurfId = None):
+
+    def UpdateVolumeProperties(self, id, data, isosurfId=None):
         """Update volume (isosurface/slice) map object properties"""
         if 'update' in data['draw']['resolution']:
             if data['draw']['mode']['value'] == 0:
-                self._display.SetIsosurfaceRes(id, data['draw']['resolution']['isosurface']['value'])
+                self._display.SetIsosurfaceRes(
+                    id, data['draw']['resolution']['isosurface']['value'])
             else:
-                self._display.SetSliceRes(id, data['draw']['resolution']['slice']['value'])                
+                self._display.SetSliceRes(
+                    id, data['draw']['resolution']['slice']['value'])
             data['draw']['resolution'].pop('update')
-        
+
         if 'update' in data['draw']['shading']:
             if data['draw']['mode']['value'] == 0:
-                if data['draw']['shading']['isosurface']['value'] < 0: # need to calculate
+                if data['draw']['shading']['isosurface'][
+                        'value'] < 0:  # need to calculate
                     mode = data['draw']['shading']['isosurface']['value'] = \
-                        self.nvizDefault.GetDrawMode(shade = data['draw']['shading']['isosurface'],
-                                                     string = False)
+                        self.nvizDefault.GetDrawMode(shade=data['draw']['shading']['isosurface'],
+                                                     string=False)
                     self._display.SetIsosurfaceMode(id, mode)
             else:
-                if data['draw']['shading']['slice']['value'] < 0: # need to calculate
+                if data['draw']['shading']['slice'][
+                        'value'] < 0:  # need to calculate
                     mode = data['draw']['shading']['slice']['value'] = \
-                        self.nvizDefault.GetDrawMode(shade = data['draw']['shading']['slice'],
-                                                     string = False)
+                        self.nvizDefault.GetDrawMode(shade=data['draw']['shading']['slice'],
+                                                     string=False)
                     self._display.SetSliceMode(id, mode)
             data['draw']['shading'].pop('update')
-        
+
         #
         # isosurface attributes
         #
         isosurfId = 0
         for isosurf in data['isosurface']:
-            self._display.AddIsosurface(id, 0, isosurf_id = isosurfId)
+            self._display.AddIsosurface(id, 0, isosurf_id=isosurfId)
             for attrb in ('topo', 'color', 'mask',
                           'transp', 'shine'):
                 if attrb not in isosurf or \
@@ -2018,52 +2128,64 @@
                     continue
                 map = isosurf[attrb]['map']
                 value = isosurf[attrb]['value']
-                
-                if map is None: # unset
+
+                if map is None:  # unset
                     # only optional attributes
-                    if attrb == 'topo' :
-                        self._display.SetIsosurfaceTopo(id, isosurfId, map, str(value))
-                    elif attrb ==  'mask':
+                    if attrb == 'topo':
+                        self._display.SetIsosurfaceTopo(
+                            id, isosurfId, map, str(value))
+                    elif attrb == 'mask':
                         # TODO: invert mask
                         # TODO: broken in NVIZ
                         self._display.UnsetIsosurfaceMask(id, isosurfId)
-                    elif attrb ==  'transp':
-                        self._display.UnsetIsosurfaceTransp(id, isosurfId) 
+                    elif attrb == 'transp':
+                        self._display.UnsetIsosurfaceTransp(id, isosurfId)
                 else:
-                    if type(value) == types.StringType:
+                    if isinstance(value, types.StringType):
                         if len(value) == 0:  # ignore empty values (TODO: warning)
                             continue
-                        if map and not grass.find_file(value, element='grid3')['fullname']:
+                        if map and not grass.find_file(value, element='grid3')[
+                                'fullname']:
                             continue
-                    if attrb ==  'color':
-                        self._display.SetIsosurfaceColor(id, isosurfId, map, str(value))
-                    elif attrb ==  'mask':
+                    if attrb == 'color':
+                        self._display.SetIsosurfaceColor(
+                            id, isosurfId, map, str(value))
+                    elif attrb == 'mask':
                         # TODO: invert mask
                         # TODO: broken in NVIZ
-                        self._display.SetIsosurfaceMask(id, isosurfId, False, str(value))
-                    elif attrb ==  'transp':
-                        self._display.SetIsosurfaceTransp(id, isosurfId, map, str(value)) 
-                    elif attrb ==  'shine':
-                        self._display.SetIsosurfaceShine(id, isosurfId, map, str(value))  
+                        self._display.SetIsosurfaceMask(
+                            id, isosurfId, False, str(value))
+                    elif attrb == 'transp':
+                        self._display.SetIsosurfaceTransp(
+                            id, isosurfId, map, str(value))
+                    elif attrb == 'shine':
+                        self._display.SetIsosurfaceShine(
+                            id, isosurfId, map, str(value))
                 isosurf[attrb].pop('update')
-            isosurfId +=  1
+            isosurfId += 1
         #
         # slice attributes
         #
         sliceId = 0
         for slice in data['slice']:
-            ret = self._display.AddSlice(id, slice_id = sliceId)
+            ret = self._display.AddSlice(id, slice_id=sliceId)
             if 'update' in slice['position']:
                 pos = slice['position']
-                ret = self._display.SetSlicePosition(id, sliceId, pos['x1'], pos['x2'],
-                                               pos['y1'], pos['y2'], pos['z1'], pos['z2'], pos['axis'])
-                
+                ret = self._display.SetSlicePosition(
+                    id, sliceId, pos['x1'],
+                    pos['x2'],
+                    pos['y1'],
+                    pos['y2'],
+                    pos['z1'],
+                    pos['z2'],
+                    pos['axis'])
+
                 slice['position'].pop('update')
             if 'update' in slice['transp']:
                 tr = slice['transp']['value']
                 self._display.SetSliceTransp(id, sliceId, tr)
             sliceId += 1
-                
+
         # position
         if 'update' in data['position'] and 'x' in data['position']:
             x = data['position']['x']
@@ -2071,19 +2193,19 @@
             z = data['position']['z']
             self._display.SetVolumePosition(id, x, y, z)
             data['position'].pop('update')
-            
+
     def UpdateVectorProperties(self, id, data, type):
         """Update vector layer properties
-        
+
         :param id: layer id
         :param data: properties
         :param type: lines/points
         """
-        if type ==  'points':
+        if type == 'points':
             self.UpdateVectorPointsProperties(id, data[type])
         else:
             self.UpdateVectorLinesProperties(id, data[type])
-        
+
     def UpdateVectorLinesProperties(self, id, data):
         """Update vector line map object properties"""
         # mode
@@ -2092,27 +2214,27 @@
                 'update' in data['mode']:
             width = data['width']['value']
             color = data['color']['value']
-            if data['mode']['type'] ==  '3d':
+            if data['mode']['type'] == '3d':
                 use_3D = True
                 if 'surface' in data['mode']:
                     data['mode'].pop('surface')
             else:
                 use_3D = False
-            
+
             self._display.SetVectorLineMode(id, color,
                                             width, use_3D)
-            
+
             if 'update' in data['color']:
                 data['color'].pop('update')
             if 'update' in data['width']:
                 data['width'].pop('update')
-        
+
         # height
         if 'update' in data['height']:
             self._display.SetVectorLineHeight(id,
                                               data['height']['value'])
             data['height'].pop('update')
-            
+
         # thematic
         if 'update' in data['thematic']:
             color = width = None
@@ -2120,63 +2242,66 @@
             if data['thematic']['usecolor'] or data['thematic']['usewidth']:
                 if data['thematic']['usecolor']:
                     color = data['thematic']['rgbcolumn']
-                    if self._display.CheckColorTable(id = id, type = 'lines'):
+                    if self._display.CheckColorTable(id=id, type='lines'):
                         colorTable = True
                 if data['thematic']['usewidth']:
                     width = data['thematic']['sizecolumn']
-                self._display.SetLinesStyleThematic(id = id, layer = data['thematic']['layer'],
-                                                     color = color,
-                                                     colorTable = colorTable, 
-                                                     width = width)
+                self._display.SetLinesStyleThematic(
+                    id=id, layer=data['thematic']['layer'],
+                    color=color, colorTable=colorTable, width=width)
             else:
-                self._display.UnsetLinesStyleThematic(id = id)
+                self._display.UnsetLinesStyleThematic(id=id)
             data['thematic'].pop('update')
         # surface
         if 'surface' in data['mode'] and 'update' in data['mode']:
             for item in range(len(data['mode']['surface']['value'])):
                 for type in ('raster', 'constant'):
-                    sid = self.GetLayerId(type = type,
-                                          name = data['mode']['surface']['value'][item])
+                    sid = self.GetLayerId(
+                        type=type, name=data['mode']['surface']['value'][item])
                     if sid > -1:
                         if data['mode']['surface']['show'][item]:
                             self._display.SetVectorLineSurface(id, sid)
                         else:
                             self._display.UnsetVectorLineSurface(id, sid)
                         break
-                
+
         if 'update' in data['mode']:
-                data['mode'].pop('update')
-        
+            data['mode'].pop('update')
+
     def UpdateVectorPointsProperties(self, id, data):
         """Update vector point map object properties"""
         if 'update' in data['size'] or \
                 'update' in data['width'] or \
                 'update' in data['marker'] or \
                 'update' in data['color']:
-                
-            ret = self._display.SetVectorPointMode(id, data['color']['value'],
-                                                   data['width']['value'], float(data['size']['value']),
-                                                   data['marker']['value'] + 1)
-            
+
+            ret = self._display.SetVectorPointMode(
+                id, data['color']['value'],
+                data['width']['value'],
+                float(data['size']['value']),
+                data['marker']['value'] + 1)
+
             error = None
-            if ret ==  -1:
+            if ret == -1:
                 error = _("Vector point layer not found (id = %d)") % id
-            elif ret ==  -2:
+            elif ret == -2:
                 error = _("Unable to set data layer properties (id = %d)") % id
 
             if error:
-                raise GException(_("Setting data layer properties failed.\n\n%s") % error)
-            
+                raise GException(
+                    _("Setting data layer properties failed.\n\n%s") %
+                    error)
+
             for prop in ('size', 'width', 'marker', 'color'):
                 if 'update' in data[prop]:
                     data[prop].pop('update')
-        
+
         # height
         if 'update' in data['height']:
             self._display.SetVectorPointHeight(id,
                                                data['height']['value'])
             data['height'].pop('update')
-        
+
         # thematic
         if 'update' in data['thematic']:
             color = size = None
@@ -2184,18 +2309,17 @@
             if data['thematic']['usecolor'] or data['thematic']['usesize']:
                 if data['thematic']['usecolor']:
                     color = data['thematic']['rgbcolumn']
-                    if self._display.CheckColorTable(id = id, type = 'points'):
+                    if self._display.CheckColorTable(id=id, type='points'):
                         colorTable = True
                 if data['thematic']['usesize']:
                     size = data['thematic']['sizecolumn']
-                self._display.SetPointsStyleThematic(id = id, layer = data['thematic']['layer'],
-                                                     color = color,
-                                                     colorTable = colorTable, 
-                                                     size = size)
+                self._display.SetPointsStyleThematic(
+                    id=id, layer=data['thematic']['layer'],
+                    color=color, colorTable=colorTable, size=size)
             else:
-                self._display.UnsetPointsStyleThematic(id = id)
+                self._display.UnsetPointsStyleThematic(id=id)
             data['thematic'].pop('update')
-            
+
         # surface
         if 'update' in data['mode']:
             if data['mode'].get('3d', False):
@@ -2204,98 +2328,105 @@
                 self._display.SetVectorPointZMode(id, False)
                 for item in range(len(data['mode']['surface']['value'])):
                     for type in ('raster', 'constant'):
-                        sid = self.GetLayerId(type=type,
-                                              name=data['mode']['surface']['value'][item])
+                        sid = self.GetLayerId(
+                            type=type, name=data['mode']['surface']['value'][item])
                         if sid > -1:
                             if data['mode']['surface']['show'][item]:
                                 self._display.SetVectorPointSurface(id, sid)
                             else:
-                                self._display.UnsetVectorPointSurface(id, sid)   
+                                self._display.UnsetVectorPointSurface(id, sid)
                             break
             data['mode'].pop('update')
-            
+
     def GetLayerNames(self, type):
         """Return list of map layer names of given type"""
         layerName = []
-        
+
         if type == 'constant':
             for item in self.constants:
-                layerName.append(_("constant#") + str(item['constant']['object']['name']))
-        else:    
+                layerName.append(_("constant#") +
+                                 str(item['constant']['object']['name']))
+        else:
             for item in self.layers:
-                mapLayer = self.tree.GetLayerInfo(item, key = 'maplayer')
-                if type !=  mapLayer.GetType():
+                mapLayer = self.tree.GetLayerInfo(item, key='maplayer')
+                if type != mapLayer.GetType():
                     continue
-                
+
                 layerName.append(mapLayer.GetName())
-        
+
         return layerName
-    
-    def GetLayerId(self, type, name, vsubtyp = None):
+
+    def GetLayerId(self, type, name, vsubtyp=None):
         """Get layer object id or -1"""
         if len(name) < 1:
             return -1
-        
+
         if type == 'constant':
             for item in self.constants:
-                if _("constant#") + str(item['constant']['object']['name']) == name:
+                if _("constant#") + str(item['constant']
+                                        ['object']['name']) == name:
                     return item['constant']['object']['id']
-                
-        
+
         for item in self.layers:
-            mapLayer = self.tree.GetLayerInfo(item, key = 'maplayer')
+            mapLayer = self.tree.GetLayerInfo(item, key='maplayer')
             if type !=  mapLayer.GetType() or \
-                    name !=  mapLayer.GetName():
+                    name != mapLayer.GetName():
                 continue
-            
-            data = self.tree.GetLayerInfo(item, key = 'nviz')
-            
+
+            data = self.tree.GetLayerInfo(item, key='nviz')
+
             try:
-                if type ==  'raster':
+                if type == 'raster':
                     return data['surface']['object']['id']
-                elif type ==  'vector':
+                elif type == 'vector':
                     if vsubtyp == 'vpoint':
                         return data['vector']['points']['object']['id']
-                    elif vsubtyp ==  'vline':
+                    elif vsubtyp == 'vline':
                         return data['vector']['lines']['object']['id']
-                elif type ==  'raster_3d':
+                elif type == 'raster_3d':
                     return data['volume']['object']['id']
             except KeyError:
                 return -1
         return -1
-    
+
     def ReloadLayersData(self):
         """Delete nviz data of all loaded layers and reload them from current settings"""
         for item in self.layers:
-            type = self.tree.GetLayerInfo(item, key = 'type')
-            layer = self.tree.GetLayerInfo(item, key = 'maplayer')
-            data = self.tree.GetLayerInfo(item, key = 'nviz')
-            
+            type = self.tree.GetLayerInfo(item, key='type')
+            layer = self.tree.GetLayerInfo(item, key='maplayer')
+            data = self.tree.GetLayerInfo(item, key='nviz')
+
             if type == 'raster':
                 self.nvizDefault.SetSurfaceDefaultProp(data['surface'])
             if type == 'vector':
                 vInfo = grass.vector_info_topo(layer.GetName())
                 if (vInfo['points'] + vInfo['centroids']) > 0:
-                    self.nvizDefault.SetVectorPointsDefaultProp(data['vector']['points'])
+                    self.nvizDefault.SetVectorPointsDefaultProp(
+                        data
+                        ['vector']
+                        ['points'])
                 if (vInfo['lines'] + vInfo['boundaries']) > 0:
-                    self.nvizDefault.SetVectorLinesDefaultProp(data['vector']['lines'])
-            
+                    self.nvizDefault.SetVectorLinesDefaultProp(
+                        data
+                        ['vector']
+                        ['lines'])
+
     def NvizCmdCommand(self):
         """Generate command for m.nviz.image according to current state"""
         cmd = 'm.nviz.image '
-        
+
         rasters = []
         vectors = []
         volumes = []
         for item in self.layers:
-            if self.tree.GetLayerInfo(item, key = 'type') == 'raster':
+            if self.tree.GetLayerInfo(item, key='type') == 'raster':
                 rasters.append(item)
-            elif self.tree.GetLayerInfo(item, key = 'type') == 'raster_3d':
+            elif self.tree.GetLayerInfo(item, key='type') == 'raster_3d':
                 volumes.append(item)
-            elif self.tree.GetLayerInfo(item, key = 'type') == 'vector':
+            elif self.tree.GetLayerInfo(item, key='type') == 'vector':
                 vectors.append(item)
-        ### if not rasters and not self.constants:
-        ###     return _("At least one raster map required")
+        # if not rasters and not self.constants:
+        # return _("At least one raster map required")
         # elevation_map/elevation_value
         if self.constants:
             subcmd = "elevation_value="
@@ -2306,7 +2437,8 @@
         if rasters:
             subcmd = "elevation_map="
             for item in rasters:
-                subcmd += "%s," % self.tree.GetLayerInfo(item, key = 'maplayer').GetName()
+                subcmd += "%s," % self.tree.GetLayerInfo(
+                    item, key='maplayer').GetName()
             subcmd = subcmd.strip(', ') + ' '
             cmd += subcmd
             #
@@ -2320,15 +2452,18 @@
             cmdWire = "wire_color="
             # test -a flag
             flag_a = "-a "
-            nvizDataFirst = self.tree.GetLayerInfo(rasters[0], key = 'nviz')['surface']['draw']
+            nvizDataFirst = self.tree.GetLayerInfo(
+                rasters[0], key='nviz')['surface']['draw']
             for item in rasters:
-                nvizData = self.tree.GetLayerInfo(item, key = 'nviz')['surface']['draw']
+                nvizData = self.tree.GetLayerInfo(item, key='nviz')[
+                    'surface']['draw']
                 if nvizDataFirst != nvizData:
                     flag_a = ""
             cmd += flag_a
             for item in rasters:
-                nvizData = self.tree.GetLayerInfo(item, key = 'nviz')['surface']['draw']
-                
+                nvizData = self.tree.GetLayerInfo(item, key='nviz')[
+                    'surface']['draw']
+
                 cmdMode += "%s," % nvizData['mode']['desc']['mode']
                 cmdFine += "%s," % nvizData['resolution']['fine']
                 cmdCoarse += "%s," % nvizData['resolution']['coarse']
@@ -2343,18 +2478,19 @@
                 cmdStyle += "surface,"
                 cmdWire += "0:0:0,"
             mode = []
-            for subcmd in (cmdMode, cmdFine, cmdCoarse, cmdShading, cmdStyle, cmdWire):
+            for subcmd in (cmdMode, cmdFine, cmdCoarse,
+                           cmdShading, cmdStyle, cmdWire):
                 if flag_a:
                     mode.append(subcmd.split(',')[0] + ' ')
                 else:
                     subcmd = subcmd.strip(', ') + ' '
                     cmd += subcmd
-            if flag_a:# write only meaningful possibilities
+            if flag_a:  # write only meaningful possibilities
                 cmd += mode[0]
                 if 'fine' in mode[0]:
                     cmd += mode[1]
                 elif 'coarse' in mode[0]:
-                    cmd += mode[2]            
+                    cmd += mode[2]
                 elif 'both' in mode[0]:
                     cmd += mode[2]
                     cmd += mode[1]
@@ -2362,7 +2498,8 @@
                     cmd += mode[3]
                 if 'wire' in mode[4]:
                     cmd += mode[4]
-                if 'coarse' in mode[0] or 'both' in mode[0] and 'wire' in mode[3]:
+                if 'coarse' in mode[0] or 'both' in mode[
+                        0] and 'wire' in mode[3]:
                     cmd += mode[5]
             #
             # attributes
@@ -2370,15 +2507,17 @@
             cmdColorMap = "color_map="
             cmdColorVal = "color="
             for item in rasters:
-                nvizData = self.tree.GetLayerInfo(item, key = 'nviz')['surface']['attribute']
+                nvizData = self.tree.GetLayerInfo(
+                    item, key='nviz')['surface']['attribute']
                 if 'color' not in nvizData:
-                    cmdColorMap += "%s," % self.tree.GetLayerInfo(item, key = 'maplayer').GetName()
+                    cmdColorMap += "%s," % self.tree.GetLayerInfo(
+                        item, key='maplayer').GetName()
                 else:
                     if nvizData['color']['map']:
                         cmdColorMap += "%s," % nvizData['color']['value']
                     else:
                         cmdColorVal += "%s," % nvizData['color']['value']
-                        #TODO
+                        # TODO
                         # transparency, shine, mask
             for item in self.constants:
                 cmdColorVal += "%s," % item['constant']['color']
@@ -2392,27 +2531,32 @@
         #
         if vectors:
             cmdLines = cmdLWidth = cmdLHeight = cmdLColor = cmdLMode = cmdLPos = \
-            cmdPoints = cmdPWidth = cmdPSize = cmdPColor = cmdPMarker = cmdPPos = cmdPLayer = ""
+                cmdPoints = cmdPWidth = cmdPSize = cmdPColor = cmdPMarker = cmdPPos = cmdPLayer = ""
             markers = ['x', 'box', 'sphere', 'cube', 'diamond',
                        'dec_tree', 'con_tree', 'aster', 'gyro', 'histogram']
             for vector in vectors:
-                layerName = self.tree.GetLayerInfo(vector, key = 'maplayer').GetName()
+                layerName = self.tree.GetLayerInfo(
+                    vector, key='maplayer').GetName()
                 vInfo = grass.vector_info_topo(layerName)
-                nvizData = self.tree.GetLayerInfo(vector, key = 'nviz')['vector']
+                nvizData = self.tree.GetLayerInfo(vector, key='nviz')['vector']
                 if (vInfo['lines'] + vInfo['boundaries']) > 0:
-                    cmdLines += "%s," % self.tree.GetLayerInfo(vector, key = 'maplayer').GetName()
+                    cmdLines += "%s," % self.tree.GetLayerInfo(
+                        vector, key='maplayer').GetName()
                     cmdLWidth += "%d," % nvizData['lines']['width']['value']
                     cmdLHeight += "%d," % nvizData['lines']['height']['value']
                     cmdLColor += "%s," % nvizData['lines']['color']['value']
                     cmdLMode += "%s," % nvizData['lines']['mode']['type']
                     cmdLPos += "0,0,%d," % nvizData['lines']['height']['value']
-                if (vInfo['points'] + vInfo['centroids']) > 0:    
-                    cmdPoints += "%s," % self.tree.GetLayerInfo(vector, key = 'maplayer').GetName()
+                if (vInfo['points'] + vInfo['centroids']) > 0:
+                    cmdPoints += "%s," % self.tree.GetLayerInfo(
+                        vector, key='maplayer').GetName()
                     cmdPWidth += "%d," % nvizData['points']['width']['value']
                     cmdPSize += "%d," % nvizData['points']['size']['value']
                     cmdPColor += "%s," % nvizData['points']['color']['value']
-                    cmdPMarker += "%s," % markers[nvizData['points']['marker']['value']]
-                    cmdPPos += "0,0,%d," % nvizData['points']['height']['value']
+                    cmdPMarker += "%s," % markers[
+                        nvizData['points']['marker']['value']]
+                    cmdPPos += "0,0,%d," % nvizData[
+                        'points']['height']['value']
                     cmdPLayer += "1,1,"
             if cmdLines:
                 cmd += "vline=" + cmdLines.strip(',') + ' '
@@ -2430,7 +2574,7 @@
                 cmd += "vpoint_position=" + cmdPPos.strip(',') + ' '
                 cmd += "vpoint_layer=" + cmdPLayer.strip(',') + ' '
             cmd += "\\\n"
-            
+
         #
         # volumes
         #
@@ -2439,13 +2583,18 @@
             cmdIsoColorMap = cmdIsoColorVal = cmdIsoTrMap = cmdIsoTrVal = ""
             cmdSlice = cmdSliceTransp = cmdSlicePos = ""
             for i, volume in enumerate(volumes):
-                nvizData = self.tree.GetLayerInfo(volume, key = 'nviz')['volume']
-                cmdName += "%s," % self.tree.GetLayerInfo(volume, key = 'maplayer').GetName()
-                cmdShade += "%s," % nvizData['draw']['shading']['isosurface']['desc']
-                cmdRes += "%d," % nvizData['draw']['resolution']['isosurface']['value']
+                nvizData = self.tree.GetLayerInfo(volume, key='nviz')['volume']
+                cmdName += "%s," % self.tree.GetLayerInfo(
+                    volume, key='maplayer').GetName()
+                cmdShade += "%s," % nvizData['draw'][
+                    'shading']['isosurface']['desc']
+                cmdRes += "%d," % nvizData['draw'][
+                    'resolution']['isosurface']['value']
                 if nvizData['position']:
-                    cmdPos += "%d,%d,%d," % (nvizData['position']['x'], nvizData['position']['y'],
-                                            nvizData['position']['z'])
+                    cmdPos += "%d,%d,%d," % (
+                        nvizData['position']['x'],
+                        nvizData['position']['y'],
+                        nvizData['position']['z'])
                 for iso in nvizData['isosurface']:
                     level = iso['topo']['value']
                     cmdIso += "%d:%s," % (i + 1, level)
@@ -2457,15 +2606,15 @@
                         if iso['transp']['map']:
                             cmdIsoTrMap += "%s," % iso['transp']['value']
                         else:
-                            cmdIsoTrVal += "%s," % iso['transp']['value']     
-                            
+                            cmdIsoTrVal += "%s," % iso['transp']['value']
+
                 for slice in nvizData['slice']:
-                    axis = ('x','y','z')[slice['position']['axis']]
+                    axis = ('x', 'y', 'z')[slice['position']['axis']]
                     cmdSlice += "%d:%s," % (i + 1, axis)
                     for coord in ('x1', 'x2', 'y1', 'y2', 'z1', 'z2'):
                         cmdSlicePos += "%f," % slice['position'][coord]
                     cmdSliceTransp += "%s," % slice['transp']['value']
-                        
+
             cmd += "volume=" + cmdName.strip(',') + ' '
             cmd += "volume_shading=" + cmdShade.strip(',') + ' '
             cmd += "volume_resolution=" + cmdRes.strip(',') + ' '
@@ -2474,22 +2623,26 @@
             if cmdIso:
                 cmd += "isosurf_level=" + cmdIso.strip(',') + ' '
                 if cmdIsoColorMap:
-                    cmd += "isosurf_color_map=" + cmdIsoColorMap.strip(',') + ' '
+                    cmd += "isosurf_color_map=" + \
+                        cmdIsoColorMap.strip(',') + ' '
                 if cmdIsoColorVal:
-                    cmd += "isosurf_color_value=" + cmdIsoColorVal.strip(',') + ' ' 
+                    cmd += "isosurf_color_value=" + \
+                        cmdIsoColorVal.strip(',') + ' '
                 if cmdIsoTrMap:
                     cmd += "isosurf_transp_map=" + cmdIsoTrMap.strip(',') + ' '
                 if cmdIsoTrVal:
-                    cmd += "isosurf_transp_value=" + cmdIsoTrVal.strip(',') + ' '
+                    cmd += "isosurf_transp_value=" + \
+                        cmdIsoTrVal.strip(',') + ' '
             if cmdSlice:
                 cmd += "slice=" + cmdSlice.strip(',') + ' '
                 cmd += "slice_position=" + cmdSlicePos.strip(',') + ' '
                 cmd += "slice_transparency=" + cmdSliceTransp.strip(',') + ' '
-                
+
         #
         # cutting planes
         #
-        cplane = self.lmgr.nviz.FindWindowById(self.lmgr.nviz.win['cplane']['planes']).GetStringSelection()
+        cplane = self.lmgr.nviz.FindWindowById(
+            self.lmgr.nviz.win['cplane']['planes']).GetStringSelection()
         try:
             planeIndex = int(cplane.split()[-1]) - 1
         except (IndexError, ValueError):
@@ -2497,33 +2650,44 @@
         if planeIndex is not None:
             shading = ['clear', 'top', 'bottom', 'blend', 'shaded']
             cmd += "cplane=%d " % planeIndex
-            cmd += "cplane_rotation=%d " % self.cplanes[planeIndex]['rotation']['rot']
-            cmd += "cplane_tilt=%d " % self.cplanes[planeIndex]['rotation']['tilt']
-            cmd += "cplane_position=%d,%d,%d " % (self.cplanes[planeIndex]['position']['x'],
-                                           self.cplanes[planeIndex]['position']['y'],
-                                           self.cplanes[planeIndex]['position']['z'])
-            cmd += "cplane_shading=%s " % shading[self.cplanes[planeIndex]['shading']]
-            cmd += "\\\n"                                        
-        # 
+            cmd += "cplane_rotation=%d " % self.cplanes[
+                planeIndex]['rotation']['rot']
+            cmd += "cplane_tilt=%d " % self.cplanes[
+                planeIndex]['rotation']['tilt']
+            cmd += "cplane_position=%d,%d,%d " % (
+                self.cplanes[planeIndex]['position']['x'],
+                self.cplanes[planeIndex]['position']['y'],
+                self.cplanes[planeIndex]['position']['z'])
+            cmd += "cplane_shading=%s " % shading[
+                self.cplanes[planeIndex]['shading']]
+            cmd += "\\\n"
+        #
         # viewpoint
         #
-        subcmd  = "position=%.2f,%.2f " % (self.view['position']['x'], self.view['position']['y'])
+        subcmd = "position=%.2f,%.2f " % (
+            self.view['position']['x'],
+            self.view['position']['y'])
         subcmd += "height=%d " % (self.iview['height']['value'])
         subcmd += "perspective=%d " % (self.view['persp']['value'])
         subcmd += "twist=%d " % (self.view['twist']['value'])
-        subcmd += "zexag=%f " % (self.view['z-exag']['value'] / self.iview['z-exag']['llRatio'])
-        subcmd += "focus=%d,%d,%d " % (self.iview['focus']['x'],self.iview['focus']['y'],self.iview['focus']['z'])
+        subcmd += "zexag=%f " % (self.view['z-exag']
+                                 ['value'] / self.iview['z-exag']['llRatio'])
+        subcmd += "focus=%d,%d,%d " % (
+            self.iview['focus']['x'],
+            self.iview['focus']['y'],
+            self.iview['focus']['z'])
         cmd += subcmd
-        
+
         # background
-        subcmd  = "bgcolor=%d:%d:%d " % (self.view['background']['color'][:3])
+        subcmd = "bgcolor=%d:%d:%d " % (self.view['background']['color'][:3])
         if self.view['background']['color'] != (255, 255, 255):
             cmd += subcmd
         cmd += "\\\n"
         # light
-        subcmd  = "light_position=%.2f,%.2f,%.2f " % (self.light['position']['x'],
-                                                      self.light['position']['y'],
-                                                      self.light['position']['z']/100.)
+        subcmd = "light_position=%.2f,%.2f,%.2f " % (
+            self.light['position']['x'],
+            self.light['position']['y'],
+            self.light['position']['z'] / 100.)
         subcmd += "light_brightness=%d " % (self.light['bright'])
         subcmd += "light_ambient=%d " % (self.light['ambient'])
         subcmd += "light_color=%d:%d:%d " % (self.light['color'][:3])
@@ -2533,48 +2697,54 @@
         toolWindow = self.lmgr.nviz
         direction = ''
         for dir in ('nw', 'ne', 'sw', 'se'):
-            if toolWindow.FindWindowById(toolWindow.win['fringe'][dir]).IsChecked():
+            if toolWindow.FindWindowById(
+                    toolWindow.win['fringe'][dir]).IsChecked():
                 direction += "%s," % dir
         if direction:
             subcmd = "fringe=%s " % (direction.strip(','))
-            color = toolWindow.FindWindowById(toolWindow.win['fringe']['color']).GetValue()
+            color = toolWindow.FindWindowById(
+                toolWindow.win['fringe']['color']).GetValue()
             subcmd += "fringe_color=%d:%d:%d " % (color[0], color[1], color[2])
-            subcmd += "fringe_elevation=%d " % (toolWindow.FindWindowById(toolWindow.win['fringe']['elev']).GetValue())
+            subcmd += "fringe_elevation=%d " % (toolWindow.FindWindowById(
+                toolWindow.win['fringe']['elev']).GetValue())
             cmd += subcmd
             cmd += "\\\n"
         # north arrow
         if self.decoration['arrow']['show']:
-            subcmd = "arrow_position=%d,%d " % (self.decoration['arrow']['position']['x'],
-                                                self.decoration['arrow']['position']['y'])
+            subcmd = "arrow_position=%d,%d " % (
+                self.decoration['arrow']['position']['x'],
+                self.decoration['arrow']['position']['y'])
             subcmd += "arrow_color=%s " % self.decoration['arrow']['color']
             subcmd += "arrow_size=%d " % self.decoration['arrow']['size']
             cmd += subcmd
-            
+
         # output
         subcmd = 'output=nviz_output '
         subcmd += 'format=ppm '
         subcmd += 'size=%d,%d ' % self.GetClientSizeTuple()
         cmd += subcmd
-        
+
         return cmd
-    
+
     def OnNvizCmd(self):
         """Generate and write command to command output"""
-        self.log.WriteLog(self.NvizCmdCommand(), notification=Notification.RAISE_WINDOW)
-        
+        self.log.WriteLog(
+            self.NvizCmdCommand(),
+            notification=Notification.RAISE_WINDOW)
+
     def SaveToFile(self, FileName, FileType, width, height):
         """This draws the DC to a buffer that can be saved to a file.
-        
+
         .. todo::
             fix BufferedPaintDC
-        
+
         :param filename: file name
         :param FileType: type of bitmap
         :param width: image width
         :param height: image height
         """
         self._display.SaveToFile(FileName, width, height, FileType)
-                
+
         # pbuffer = wx.EmptyBitmap(max(1, self.Map.width), max(1, self.Map.height))
         # dc = wx.BufferedPaintDC(self, pbuffer)
         # dc.Clear()
@@ -2582,24 +2752,24 @@
         # self._display.Draw(False, -1)
         # pbuffer.SaveFile(FileName, FileType)
         # self.SwapBuffers()
-        
+
     def GetDisplay(self):
         """Get display instance"""
         return self._display
-        
+
     def ZoomToMap(self, layers):
         """Reset view
-        
+
         :param layers: so far unused
         """
         self.lmgr.nviz.OnResetView(None)
-        
+
     def TextBounds(self, textinfo):
         """Return text boundary data
-        
+
         :param textinfo: text metadata (text, font, color, rotation)
         """
-        return self.parent.MapWindow2D.TextBounds(textinfo, relcoords = True)
+        return self.parent.MapWindow2D.TextBounds(textinfo, relcoords=True)
 
     def DisactivateWin(self):
         """Use when the class instance is hidden in MapFrame."""

Modified: grass/trunk/gui/wxpython/nviz/preferences.py
===================================================================
--- grass/trunk/gui/wxpython/nviz/preferences.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/nviz/preferences.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -22,551 +22,636 @@
 import wx
 import wx.lib.colourselect as csel
 
-from core                 import globalvar
-from core.settings        import UserSettings
+from core import globalvar
+from core.settings import UserSettings
 from core.utils import _
 from gui_core.preferences import PreferencesBaseDialog
 
+
 class NvizPreferencesDialog(PreferencesBaseDialog):
     """Nviz preferences dialog"""
-    def __init__(self, parent, giface, title = _("3D view default settings"),
-                 settings = UserSettings):
-        PreferencesBaseDialog.__init__(self, parent = parent, title = title, giface = giface,
-                                       settings = settings)
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass_nviz.ico'), wx.BITMAP_TYPE_ICO))
 
+    def __init__(self, parent, giface, title=_("3D view default settings"),
+                 settings=UserSettings):
+        PreferencesBaseDialog.__init__(
+            self,
+            parent=parent,
+            title=title,
+            giface=giface,
+            settings=settings)
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass_nviz.ico'),
+                wx.BITMAP_TYPE_ICO))
+
         self.toolWin = self.parent.nviz
-        
+
         # create notebook pages
         self._createViewPage(self.notebook)
         self._createFlyPage(self.notebook)
         self._createLightPage(self.notebook)
         self._createSurfacePage(self.notebook)
         self._createVectorPage(self.notebook)
-        
+
         self.SetMinSize(self.GetBestSize())
         self.SetSize(self.size)
-        self.btnDefault.SetToolTipString(_("Revert settings to default, changes are not applied"))
-        
+        self.btnDefault.SetToolTipString(
+            _("Revert settings to default, changes are not applied"))
+
     def _createViewPage(self, notebook):
         """Create notebook page for view settings"""
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY)
-        
-        notebook.AddPage(page = panel,
-                         text = " %s " % _("View"))
-        
+        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
+
+        notebook.AddPage(page=panel,
+                         text=" %s " % _("View"))
+
         pageSizer = wx.BoxSizer(wx.VERTICAL)
-        
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("View")))
+
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("View")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
+        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)
         row = 0
         # perspective
-        pvals = UserSettings.Get(group = 'nviz', key = 'view', subkey = 'persp')
-        ipvals = UserSettings.Get(group='nviz', key='view', subkey='persp', settings_type='internal')
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Perspective:")),
-                      pos = (row, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("value:")),
-                      pos = (row, 1), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
-        
-        pval = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = pvals['value'],
-                           min = ipvals['min'],
-                           max = ipvals['max'])
+        pvals = UserSettings.Get(group='nviz', key='view', subkey='persp')
+        ipvals = UserSettings.Get(
+            group='nviz',
+            key='view',
+            subkey='persp',
+            settings_type='internal')
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Perspective:")),
+                      pos=(row, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel, id=wx.ID_ANY, label=_("value:")), pos=(
+                row, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
+
+        pval = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                           initial=pvals['value'],
+                           min=ipvals['min'],
+                           max=ipvals['max'])
         self.winId['nviz:view:persp:value'] = pval.GetId()
-        gridSizer.Add(item = pval, pos = (row, 2),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("step:")),
-                      pos = (row, 3), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
-        
-        pstep = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = pvals['step'],
-                           min = ipvals['min'],
-                           max = ipvals['max']-1)
+        gridSizer.Add(item=pval, pos=(row, 2),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
+
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel, id=wx.ID_ANY, label=_("step:")), pos=(
+                row, 3), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
+
+        pstep = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                            initial=pvals['step'],
+                            min=ipvals['min'],
+                            max=ipvals['max'] - 1)
         self.winId['nviz:view:persp:step'] = pstep.GetId()
-        gridSizer.Add(item = pstep, pos = (row, 4),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(item=pstep, pos=(row, 4),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
         row += 1
-        
+
         # position
-        posvals = UserSettings.Get(group = 'nviz', key = 'view', subkey = 'position')
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Position:")),
-                      pos = (row, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("x:")),
-                      pos = (row, 1), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
-        
-        px = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = posvals['x'] * 100,
-                           min = 0,
-                           max = 100)
+        posvals = UserSettings.Get(group='nviz', key='view', subkey='position')
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Position:")),
+                      pos=(row, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel, id=wx.ID_ANY, label=_("x:")), pos=(
+                row, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
+
+        px = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                         initial=posvals['x'] * 100,
+                         min=0,
+                         max=100)
         self.winId['nviz:view:position:x'] = px.GetId()
-        gridSizer.Add(item = px, pos = (row, 2),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = "y:"),
-                      pos = (row, 3), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
-        
-        py = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = posvals['y'] * 100,
-                           min = 0,
-                           max = 100)
+        gridSizer.Add(item=px, pos=(row, 2),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
+
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel, id=wx.ID_ANY, label="y:"), pos=(
+                row, 3), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
+
+        py = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                         initial=posvals['y'] * 100,
+                         min=0,
+                         max=100)
         self.winId['nviz:view:position:y'] = py.GetId()
-        gridSizer.Add(item = py, pos = (row, 4),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(item=py, pos=(row, 4),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
         row += 1
-        
+
         # height is computed dynamically
-        
+
         # twist
-        tvals = UserSettings.Get(group = 'nviz', key = 'view', subkey = 'twist')
-        itvals = UserSettings.Get(group='nviz', key='view', subkey='twist', settings_type='internal')
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Twist:")),
-                      pos = (row, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("value:")),
-                      pos = (row, 1), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
-        
-        tval = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = tvals['value'],
-                           min = itvals['min'],
-                           max = itvals['max'])
+        tvals = UserSettings.Get(group='nviz', key='view', subkey='twist')
+        itvals = UserSettings.Get(
+            group='nviz',
+            key='view',
+            subkey='twist',
+            settings_type='internal')
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Twist:")),
+                      pos=(row, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel, id=wx.ID_ANY, label=_("value:")), pos=(
+                row, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
+
+        tval = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                           initial=tvals['value'],
+                           min=itvals['min'],
+                           max=itvals['max'])
         self.winId['nviz:view:twist:value'] = tval.GetId()
-        gridSizer.Add(item = tval, pos = (row, 2),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(item=tval, pos=(row, 2),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
         row += 1
-        
+
         # z-exag
-        zvals = UserSettings.Get(group = 'nviz', key = 'view', subkey = 'z-exag')
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Z-exag:")),
-                      pos = (row, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("value:")),
-                      pos = (row, 1), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
-        
-        zval = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = zvals['value'],
-                           min = -1e6,
-                           max = 1e6)
+        zvals = UserSettings.Get(group='nviz', key='view', subkey='z-exag')
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Z-exag:")),
+                      pos=(row, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel, id=wx.ID_ANY, label=_("value:")), pos=(
+                row, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
+
+        zval = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                           initial=zvals['value'],
+                           min=-1e6,
+                           max=1e6)
         self.winId['nviz:view:z-exag:value'] = zval.GetId()
-        gridSizer.Add(item = zval, pos = (row, 2),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                  flag = wx.ALL | wx.EXPAND, border = 3)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 3)
+        gridSizer.Add(item=zval, pos=(row, 2),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
 
-        box = wx.StaticBox(parent = panel, id = wx.ID_ANY,
-                           label = " %s " % (_("Image Appearance")))
+        boxSizer.Add(item=gridSizer, proportion=1,
+                     flag=wx.ALL | wx.EXPAND, border=3)
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                      border=3)
+
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Image Appearance")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
-        
+        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)
+
         # background color
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Background color:")),
-                      pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        color = csel.ColourSelect(panel, id = wx.ID_ANY,
-                                  colour = UserSettings.Get(group = 'nviz', key = 'view',
-                                                            subkey = ['background', 'color']),
-                                  size = globalvar.DIALOG_COLOR_SIZE)
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Background color:")),
+                      pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+
+        color = csel.ColourSelect(
+            panel,
+            id=wx.ID_ANY,
+            colour=UserSettings.Get(
+                group='nviz',
+                key='view',
+                subkey=[
+                    'background',
+                    'color']),
+            size=globalvar.DIALOG_COLOR_SIZE)
         color.SetName('GetColour')
         self.winId['nviz:view:background:color'] = color.GetId()
-        gridSizer.Add(item = color, pos = (0, 1))
-        
+        gridSizer.Add(item=color, pos=(0, 1))
+
         gridSizer.AddGrowableCol(0)
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                  flag = wx.ALL | wx.EXPAND, border = 5)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL,
-                      border = 5)
-        
+        boxSizer.Add(item=gridSizer, proportion=1,
+                     flag=wx.ALL | wx.EXPAND, border=5)
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALL,
+                      border=5)
+
         panel.SetSizer(pageSizer)
-        
+
         return panel
-        
+
     def _createFlyPage(self, notebook):
         """Create notebook page for view settings"""
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY)
-        
-        notebook.AddPage(page = panel,
-                         text = " %s " % _("Fly-through"))
+        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
+
+        notebook.AddPage(page=panel,
+                         text=" %s " % _("Fly-through"))
         pageSizer = wx.BoxSizer(wx.VERTICAL)
         # fly throuhg mode
-        box = wx.StaticBox(parent = panel, id = wx.ID_ANY,
-                           label = " %s " % (_("Fly-through mode")))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Fly-through mode")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
-        
+        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)
+
         # move exag
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Move exag:")),
-                      pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        moveExag = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 20, 
-                                  initial = UserSettings.Get(group = 'nviz', key = 'fly',
-                                                             subkey = ['exag', 'move']),
-                                  size = (65, -1))
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Move exag:")),
+                      pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+
+        moveExag = wx.SpinCtrl(
+            panel, id=wx.ID_ANY, min=1, max=20, initial=UserSettings.Get(
+                group='nviz', key='fly', subkey=[
+                    'exag', 'move']), size=(
+                65, -1))
         self.winId['nviz:fly:exag:move'] = moveExag.GetId()
-        gridSizer.Add(item = moveExag, pos = (0, 1))
-        
+        gridSizer.Add(item=moveExag, pos=(0, 1))
+
         # turn exag
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Turn exag:")),
-                      pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        turnExag = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 20, 
-                                  initial = UserSettings.Get(group = 'nviz', key = 'fly',
-                                                             subkey = ['exag', 'turn']),
-                                  size = (65, -1))
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Turn exag:")),
+                      pos=(1, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+
+        turnExag = wx.SpinCtrl(
+            panel, id=wx.ID_ANY, min=1, max=20, initial=UserSettings.Get(
+                group='nviz', key='fly', subkey=[
+                    'exag', 'turn']), size=(
+                65, -1))
         self.winId['nviz:fly:exag:turn'] = turnExag.GetId()
-        gridSizer.Add(item = turnExag, pos = (1, 1))
-        
+        gridSizer.Add(item=turnExag, pos=(1, 1))
+
         gridSizer.AddGrowableCol(0)
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                  flag = wx.ALL | wx.EXPAND, border = 5)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL,
-                      border = 5)
-        
+        boxSizer.Add(item=gridSizer, proportion=1,
+                     flag=wx.ALL | wx.EXPAND, border=5)
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALL,
+                      border=5)
+
         panel.SetSizer(pageSizer)
-        
+
         return panel
-        
+
     def _createLightPage(self, notebook):
         """Create notebook page for light settings"""
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY)
-        
-        notebook.AddPage(page = panel,
-                         text = " %s " % _("Lighting"))
-        
+        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
+
+        notebook.AddPage(page=panel,
+                         text=" %s " % _("Lighting"))
+
         pageSizer = wx.BoxSizer(wx.VERTICAL)
-        
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Light")))
+
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Light")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
+        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)
 
-        
         # position
-        posvals = UserSettings.Get(group = 'nviz', key = 'light', subkey = 'position')
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Position:")),
-                      pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("x:")),
-                      pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
-        
-        px = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = posvals['x'] * 100,
-                           min = -100,
-                           max = 100)
+        posvals = UserSettings.Get(
+            group='nviz', key='light', subkey='position')
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Position:")),
+                      pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel, id=wx.ID_ANY, label=_("x:")), pos=(
+                0, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
+
+        px = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                         initial=posvals['x'] * 100,
+                         min=-100,
+                         max=100)
         self.winId['nviz:light:position:x'] = px.GetId()
-        gridSizer.Add(item = px, pos = (0, 2),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = "y:"),
-                      pos = (0, 3), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
-        
-        py = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = posvals['y'] * 100,
-                           min = -100,
-                           max = 100)
+        gridSizer.Add(item=px, pos=(0, 2),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
+
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel, id=wx.ID_ANY, label="y:"), pos=(
+                0, 3), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
+
+        py = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                         initial=posvals['y'] * 100,
+                         min=-100,
+                         max=100)
         self.winId['nviz:light:position:y'] = py.GetId()
-        gridSizer.Add(item = py, pos = (0, 4),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-                    
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("z:")),
-                      pos = (0, 5), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
-        
-        pz = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = posvals['z'],
-                           min = 0,
-                           max = 100)
+        gridSizer.Add(item=py, pos=(0, 4),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
+
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel, id=wx.ID_ANY, label=_("z:")), pos=(
+                0, 5), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
+
+        pz = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                         initial=posvals['z'],
+                         min=0,
+                         max=100)
         self.winId['nviz:light:position:z'] = pz.GetId()
-        gridSizer.Add(item = pz, pos = (0, 6),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-                    
+        gridSizer.Add(item=pz, pos=(0, 6),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
+
         # brightness
-        brightval = UserSettings.Get(group = 'nviz', key = 'light', subkey = 'bright')
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Brightness:")),
-                      pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        bright = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = brightval,
-                           min = 0,
-                           max = 100)
+        brightval = UserSettings.Get(
+            group='nviz', key='light', subkey='bright')
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Brightness:")),
+                      pos=(1, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+
+        bright = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                             initial=brightval,
+                             min=0,
+                             max=100)
         self.winId['nviz:light:bright'] = bright.GetId()
-        gridSizer.Add(item = bright, pos = (1, 2),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-                    
+        gridSizer.Add(item=bright, pos=(1, 2),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
+
         # ambient
-        ambval = UserSettings.Get(group = 'nviz', key = 'light', subkey = 'ambient')
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Ambient:")),
-                      pos = (2, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        amb = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = ambval,
-                           min = 0,
-                           max = 100)
+        ambval = UserSettings.Get(group='nviz', key='light', subkey='ambient')
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Ambient:")),
+                      pos=(2, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+
+        amb = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                          initial=ambval,
+                          min=0,
+                          max=100)
         self.winId['nviz:light:ambient'] = amb.GetId()
-        gridSizer.Add(item = amb, pos = (2, 2),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-                    
+        gridSizer.Add(item=amb, pos=(2, 2),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
+
         # light color
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Color:")),
-                      pos = (3, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        color = csel.ColourSelect(panel, id = wx.ID_ANY,
-                                  colour = UserSettings.Get(group = 'nviz', key = 'light',
-                                                            subkey = 'color'),
-                                  size = globalvar.DIALOG_COLOR_SIZE)
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Color:")),
+                      pos=(3, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+
+        color = csel.ColourSelect(
+            panel, id=wx.ID_ANY, colour=UserSettings.Get(
+                group='nviz', key='light', subkey='color'),
+            size=globalvar.DIALOG_COLOR_SIZE)
         color.SetName('GetColour')
         self.winId['nviz:light:color'] = color.GetId()
-        gridSizer.Add(item = color, pos = (3, 2))
-        
-        
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                  flag = wx.ALL | wx.EXPAND, border = 5)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL,
-                      border = 5)
-        
+        gridSizer.Add(item=color, pos=(3, 2))
+
+        boxSizer.Add(item=gridSizer, proportion=1,
+                     flag=wx.ALL | wx.EXPAND, border=5)
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALL,
+                      border=5)
+
         panel.SetSizer(pageSizer)
-        
+
         return panel
-    
+
     def _createSurfacePage(self, notebook):
         """Create notebook page for surface settings"""
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY)
-        
-        notebook.AddPage(page = panel,
-                         text = " %s " % _("Surface"))
-        
+        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
+
+        notebook.AddPage(page=panel,
+                         text=" %s " % _("Surface"))
+
         pageSizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         # draw
-        
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Draw")))
+
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Draw")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
-        
+        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)
+
         # mode
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                        label = _("Mode:")), flag = wx.ALIGN_CENTER_VERTICAL,
-                        pos = (0, 0))
-        mode = wx.Choice(parent = panel, id = wx.ID_ANY, size = (-1, -1),
-                          choices = [_("coarse"),
-                                     _("fine"),
-                                     _("both")])
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_("Mode:")),
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                0,
+                0))
+        mode = wx.Choice(parent=panel, id=wx.ID_ANY, size=(-1, -1),
+                         choices=[_("coarse"),
+                                  _("fine"),
+                                  _("both")])
         self.winId['nviz:surface:draw:mode'] = mode.GetId()
         mode.SetName('GetSelection')
-        mode.SetSelection(UserSettings.Get(group = 'nviz', key = 'surface',
-                                            subkey = ['draw', 'mode']))
-        gridSizer.Add(item = mode, flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (0, 1))
-                    
+        mode.SetSelection(UserSettings.Get(group='nviz', key='surface',
+                                           subkey=['draw', 'mode']))
+        gridSizer.Add(item=mode, flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(0, 1))
+
         # fine
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                        label = _("Fine mode:")), flag = wx.ALIGN_CENTER_VERTICAL,
-                        pos = (1, 0))
-        res = UserSettings.Get(group = 'nviz', key = 'surface', subkey = ['draw','res-fine'])
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                        label = _("resolution:")), flag = wx.ALIGN_CENTER_VERTICAL,
-                        pos = (1, 1))
-        fine = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = res,
-                           min = 1,
-                           max = 100)
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_("Fine mode:")),
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                1,
+                0))
+        res = UserSettings.Get(
+            group='nviz', key='surface', subkey=[
+                'draw', 'res-fine'])
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_("resolution:")),
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                1,
+                1))
+        fine = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                           initial=res,
+                           min=1,
+                           max=100)
         self.winId['nviz:surface:draw:res-fine'] = fine.GetId()
-        
-        gridSizer.Add(item = fine, flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (1, 2))
-                    
+
+        gridSizer.Add(item=fine, flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(1, 2))
+
         # coarse
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                        label = _("Coarse mode:")), flag = wx.ALIGN_CENTER_VERTICAL,
-                        pos = (2, 0))
-        res = UserSettings.Get(group = 'nviz', key = 'surface', subkey = ['draw','res-coarse'])
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                        label = _("resolution:")), flag = wx.ALIGN_CENTER_VERTICAL,
-                        pos = (2, 1))
-        coarse = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = res,
-                           min = 1,
-                           max = 100)
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_("Coarse mode:")),
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                2,
+                0))
+        res = UserSettings.Get(
+            group='nviz', key='surface', subkey=[
+                'draw', 'res-coarse'])
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_("resolution:")),
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                2,
+                1))
+        coarse = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                             initial=res,
+                             min=1,
+                             max=100)
         self.winId['nviz:surface:draw:res-coarse'] = coarse.GetId()
-        
-        gridSizer.Add(item = coarse, flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (2, 2))
-        #style
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-            label = _("style:")), flag = wx.ALIGN_CENTER_VERTICAL,
-            pos = (3, 1))
-        style = wx.Choice(parent = panel, id = wx.ID_ANY, size = (-1, -1),
-                          choices = [_("wire"),
-                                     _("surface")])
+
+        gridSizer.Add(item=coarse, flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(2, 2))
+        # style
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_("style:")),
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                3,
+                1))
+        style = wx.Choice(parent=panel, id=wx.ID_ANY, size=(-1, -1),
+                          choices=[_("wire"),
+                                   _("surface")])
         self.winId['nviz:surface:draw:style'] = style.GetId()
         style.SetName('GetSelection')
-        style.SetSelection(UserSettings.Get(group = 'nviz', key = 'surface',
-                                            subkey = ['draw', 'style']))
+        style.SetSelection(UserSettings.Get(group='nviz', key='surface',
+                                            subkey=['draw', 'style']))
         self.winId['nviz:surface:draw:style'] = style.GetId()
-        
-        gridSizer.Add(item = style, flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (3, 2))
-        #wire color
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-            label = _("wire color:")), flag = wx.ALIGN_CENTER_VERTICAL,
-            pos = (4, 1))
-        color = csel.ColourSelect(panel, id = wx.ID_ANY,
-                                  colour = UserSettings.Get(group = 'nviz', key = 'surface',
-                                                            subkey = ['draw', 'wire-color']),
-                                  size = globalvar.DIALOG_COLOR_SIZE)
+
+        gridSizer.Add(item=style, flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(3, 2))
+        # wire color
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_("wire color:")),
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                4,
+                1))
+        color = csel.ColourSelect(
+            panel, id=wx.ID_ANY, colour=UserSettings.Get(
+                group='nviz', key='surface', subkey=[
+                    'draw', 'wire-color']), size=globalvar.DIALOG_COLOR_SIZE)
         color.SetName('GetColour')
-        self.winId['nviz:surface:draw:wire-color'] = color.GetId() 
-        gridSizer.Add(item = color, flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (4, 2))
-        
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                  flag = wx.ALL | wx.EXPAND, border = 5)            
-        pageSizer.Add(item = boxSizer, proportion = 0,
-              flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-              border = 5)
-        
+        self.winId['nviz:surface:draw:wire-color'] = color.GetId()
+        gridSizer.Add(item=color, flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(4, 2))
+
+        boxSizer.Add(item=gridSizer, proportion=1,
+                     flag=wx.ALL | wx.EXPAND, border=5)
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                      border=5)
+
         panel.SetSizer(pageSizer)
-        
+
         return panel
-    
+
     def _createVectorPage(self, notebook):
         """Create notebook page for vector settings"""
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY)
-        
-        notebook.AddPage(page = panel,
-                         text = " %s " % _("Vector"))
-        
+        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
+
+        notebook.AddPage(page=panel,
+                         text=" %s " % _("Vector"))
+
         pageSizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         # vector lines
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Vector lines")))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Vector lines")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
-        
+        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)
+
         row = 0
         # icon size
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Width:")),
-                      pos = (row, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        iwidth = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                            initial = 12,
-                            min = 1,
-                            max = 100)
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Width:")),
+                      pos=(row, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+
+        iwidth = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                             initial=12,
+                             min=1,
+                             max=100)
         self.winId['nviz:vector:lines:width'] = iwidth.GetId()
-        iwidth.SetValue(UserSettings.Get(group = 'nviz', key = 'vector',
-                                        subkey = ['lines', 'width']))
-        gridSizer.Add(item = iwidth, pos = (row, 1),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        
+        iwidth.SetValue(UserSettings.Get(group='nviz', key='vector',
+                                         subkey=['lines', 'width']))
+        gridSizer.Add(item=iwidth, pos=(row, 1),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
+
         # icon color
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Color:")),
-                      pos = (row, 4), flag = wx.ALIGN_CENTER_VERTICAL)
-        icolor = csel.ColourSelect(panel, id = wx.ID_ANY,
-                                   size = globalvar.DIALOG_COLOR_SIZE)
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Color:")),
+                      pos=(row, 4), flag=wx.ALIGN_CENTER_VERTICAL)
+        icolor = csel.ColourSelect(panel, id=wx.ID_ANY,
+                                   size=globalvar.DIALOG_COLOR_SIZE)
         icolor.SetName('GetColour')
         self.winId['nviz:vector:lines:color'] = icolor.GetId()
-        icolor.SetColour(UserSettings.Get(group = 'nviz', key = 'vector',
-                                          subkey = ['lines', 'color']))
-        gridSizer.Add(item = icolor, flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 5))
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                  flag = wx.ALL | wx.EXPAND, border = 5)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 5)
-        
+        icolor.SetColour(UserSettings.Get(group='nviz', key='vector',
+                                          subkey=['lines', 'color']))
+        gridSizer.Add(item=icolor, flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(row, 5))
+        boxSizer.Add(item=gridSizer, proportion=1,
+                     flag=wx.ALL | wx.EXPAND, border=5)
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                      border=5)
+
         # vector points
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Vector points")))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Vector points")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 3, hgap = 5)
-        
+        gridSizer = wx.GridBagSizer(vgap=3, hgap=5)
+
         row = 0
         # icon size
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Size:")),
-                      pos = (row, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        isize = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                            initial = 100,
-                            min = 1,
-                            max = 1e6)
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Size:")),
+                      pos=(row, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+
+        isize = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                            initial=100,
+                            min=1,
+                            max=1e6)
         self.winId['nviz:vector:points:size'] = isize.GetId()
-        isize.SetValue(UserSettings.Get(group = 'nviz', key = 'vector',
-                                        subkey = ['points', 'size']))
-        gridSizer.Add(item = isize, pos = (row, 1),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        
+        isize.SetValue(UserSettings.Get(group='nviz', key='vector',
+                                        subkey=['points', 'size']))
+        gridSizer.Add(item=isize, pos=(row, 1),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
+
         # icon symbol
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Marker:")),
-                      pos = (row, 2), flag = wx.ALIGN_CENTER_VERTICAL)
-        isym = wx.Choice (parent = panel, id = wx.ID_ANY, size = (100, -1),
-                          choices = UserSettings.Get(group = 'nviz', key = 'vector',
-                                                   subkey=['points', 'marker'], settings_type='internal'))
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Marker:")),
+                      pos=(row, 2), flag=wx.ALIGN_CENTER_VERTICAL)
+        isym = wx.Choice(
+            parent=panel, id=wx.ID_ANY, size=(100, -1),
+            choices=UserSettings.Get(
+                group='nviz', key='vector', subkey=['points', 'marker'],
+                settings_type='internal'))
         isym.SetName("GetSelection")
         self.winId['nviz:vector:points:marker'] = isym.GetId()
-        isym.SetSelection(UserSettings.Get(group = 'nviz', key = 'vector',
-                                           subkey = ['points', 'marker']))
-        gridSizer.Add(item = isym, flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 3))
-        
+        isym.SetSelection(UserSettings.Get(group='nviz', key='vector',
+                                           subkey=['points', 'marker']))
+        gridSizer.Add(item=isym, flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(row, 3))
+
         # icon color
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Color:")),
-                      pos = (row, 4), flag = wx.ALIGN_CENTER_VERTICAL)
-        icolor = csel.ColourSelect(panel, id = wx.ID_ANY,
-                                   size = globalvar.DIALOG_COLOR_SIZE)
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Color:")),
+                      pos=(row, 4), flag=wx.ALIGN_CENTER_VERTICAL)
+        icolor = csel.ColourSelect(panel, id=wx.ID_ANY,
+                                   size=globalvar.DIALOG_COLOR_SIZE)
         icolor.SetName('GetColour')
         self.winId['nviz:vector:points:color'] = icolor.GetId()
-        icolor.SetColour(UserSettings.Get(group = 'nviz', key = 'vector',
-                                          subkey = ['points', 'color']))
-        gridSizer.Add(item = icolor, flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (row, 5))
-        
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                  flag = wx.ALL | wx.EXPAND, border = 5)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 5)
-        
+        icolor.SetColour(UserSettings.Get(group='nviz', key='vector',
+                                          subkey=['points', 'color']))
+        gridSizer.Add(item=icolor, flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(row, 5))
+
+        boxSizer.Add(item=gridSizer, proportion=1,
+                     flag=wx.ALL | wx.EXPAND, border=5)
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                      border=5)
+
         panel.SetSizer(pageSizer)
-        
+
         return panel
 
     def OnDefault(self, event):
         """Button 'Set to default' pressed"""
-        self.settings.userSettings = copy.deepcopy(self.settings.defaultSettings)
-        
+        self.settings.userSettings = copy.deepcopy(
+            self.settings.defaultSettings)
+
         # update widgets
         for gks in self.winId.keys():
             subkey1 = None
@@ -583,8 +668,8 @@
             if win.GetName() == 'GetSelection':
                 value = win.SetSelection(value)
             else:
-                value = win.SetValue(value)        
-        
+                value = win.SetValue(value)
+
     def OnApply(self, event):
         """Apply Nviz settings for current session"""
         for item in self.winId.keys():
@@ -593,7 +678,7 @@
                 subkey1 = None
             except ValueError:
                 group, key, subkey, subkey1 = item.split(':')
-            
+
             id = self.winId[item]
             win = self.FindWindowById(id)
             if win.GetName() == 'GetSelection':
@@ -602,7 +687,7 @@
                 value = tuple(win.GetValue())
             else:
                 value = win.GetValue()
-            
+
             if subkey == 'position':
                 if subkey1 in ('x', 'y'):
                     value = float(value) / 100
@@ -610,23 +695,21 @@
                 self.settings.Set(group, value, key, [subkey, subkey1])
             else:
                 self.settings.Set(group, value, key, subkey)
-                
+
         self.toolWin.LoadSettings()
-        
-        
+
     def OnSave(self, event):
         """Save button pressed
-        
+
         Apply changes and save settings to configuration file
         """
         self.OnApply(None)
         fileSettings = {}
-        UserSettings.ReadSettingsFile(settings = fileSettings)
-        fileSettings['nviz'] = UserSettings.Get(group = 'nviz')
-        
+        UserSettings.ReadSettingsFile(settings=fileSettings)
+        fileSettings['nviz'] = UserSettings.Get(group='nviz')
+
         UserSettings.SaveToFile(fileSettings)
         self.parent._gconsole.WriteLog(
-                _('3D view settings saved to file <%s>.') % UserSettings.filePath)
-        
+            _('3D view settings saved to file <%s>.') % UserSettings.filePath)
+
         self.Destroy()
-        

Modified: grass/trunk/gui/wxpython/nviz/tools.py
===================================================================
--- grass/trunk/gui/wxpython/nviz/tools.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/nviz/tools.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -25,7 +25,7 @@
 import types
 
 import wx
-import wx.lib.colourselect  as csel
+import wx.lib.colourselect as csel
 import wx.lib.scrolledpanel as SP
 import wx.lib.filebrowsebutton as filebrowse
 try:
@@ -34,38 +34,40 @@
     import wx.lib.flatnotebook as FN
 try:
     from agw import foldpanelbar as fpb
-except ImportError: # if it's not there locally, try the wxPython lib.
+except ImportError:  # if it's not there locally, try the wxPython lib.
     try:
         import wx.lib.agw.foldpanelbar as fpb
     except ImportError:
-        import wx.lib.foldpanelbar as fpb # versions <=2.5.5.1
+        import wx.lib.foldpanelbar as fpb  # versions <=2.5.5.1
 try:
     import wx.lib.agw.floatspin as fs
 except ImportError:
     fs = None
 import grass.script as grass
 
-from core               import globalvar
+from core import globalvar
 from core.utils import _
-from gui_core.gselect   import VectorDBInfo
-from core.gcmd          import GMessage, RunCommand
+from gui_core.gselect import VectorDBInfo
+from core.gcmd import GMessage, RunCommand
 from modules.colorrules import ThematicVectorTable
-from core.settings      import UserSettings
-from gui_core.widgets   import ScrolledPanel, NumTextCtrl, FloatSlider, SymbolButton
-from gui_core.gselect   import Select
-from core.debug         import Debug
+from core.settings import UserSettings
+from gui_core.widgets import ScrolledPanel, NumTextCtrl, FloatSlider, SymbolButton
+from gui_core.gselect import Select
+from core.debug import Debug
 try:
     from nviz.mapwindow import wxUpdateProperties, wxUpdateView,\
-                               wxUpdateLight, wxUpdateCPlane
+        wxUpdateLight, wxUpdateCPlane
     import wxnviz
 except ImportError:
     pass
 
+
 class NvizToolWindow(FN.FlatNotebook):
     """Nviz (3D view) tools panel
     """
+
     def __init__(self, parent, tree, display, id=wx.ID_ANY,
-                 style=globalvar.FNPageStyle|FN.FNB_NO_X_BUTTON,
+                 style=globalvar.FNPageStyle | FN.FNB_NO_X_BUTTON,
                  **kwargs):
         Debug.msg(5, "NvizToolWindow.__init__()")
         self.parent = parent
@@ -73,68 +75,75 @@
         self.mapDisplay = display
         self.mapWindow = display.GetWindow()
         self._display = self.mapWindow.GetDisplay()
-         
+
         if globalvar.hasAgw:
             kwargs['agwStyle'] = style
         else:
             kwargs['style'] = style
         FN.FlatNotebook.__init__(self, parent, id, **kwargs)
         self.SetTabAreaColour(globalvar.FNPageColor)
-        
-        self.win  = {} # window ids
-        self.page = {} # page ids
 
+        self.win = {}  # window ids
+        self.page = {}  # page ids
+
         # view page
-        self.AddPage(page = self._createViewPage(),
-                     text = " %s " % _("View"))
+        self.AddPage(page=self._createViewPage(),
+                     text=" %s " % _("View"))
 
         # data page
-        self.AddPage(page = self._createDataPage(),
-                     text = " %s " % _("Data"))
-        
+        self.AddPage(page=self._createDataPage(),
+                     text=" %s " % _("Data"))
+
         # appearance page
-        self.AddPage(page = self._createAppearancePage(),
-                     text = " %s " % _("Appearance"))
-                    
+        self.AddPage(page=self._createAppearancePage(),
+                     text=" %s " % _("Appearance"))
+
         # analysis page
-        self.AddPage(page = self._createAnalysisPage(),
-                     text = " %s " % _("Analysis"))
+        self.AddPage(page=self._createAnalysisPage(),
+                     text=" %s " % _("Analysis"))
         # view page
-        self.AddPage(page = self._createAnimationPage(),
-                     text = " %s " % _("Animation"))
-        
+        self.AddPage(page=self._createAnimationPage(),
+                     text=" %s " % _("Animation"))
+
         self.UpdateSettings()
-        
+
         self.mapWindow.SetToolWin(self)
-        
+
         self.pageChanging = False
-        self.vetoGSelectEvt = False #when setting map, event is invoked
+        self.vetoGSelectEvt = False  # when setting map, event is invoked
         self.mapWindow.render['quick'] = False
         self.mapWindow.Refresh(False)
-        
+
         # bindings
         self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
         self.Bind(wx.EVT_SIZE, self.OnSize)
-        
+
         self.mapWindow.GetAnimation().animationFinished.connect(self.OnAnimationFinished)
-        self.mapWindow.GetAnimation().animationUpdateIndex.connect(self.OnAnimationUpdateIndex)
-        
+        self.mapWindow.GetAnimation().animationUpdateIndex.connect(
+            self.OnAnimationUpdateIndex)
+
         Debug.msg(3, "NvizToolWindow.__init__()")
-        
+
         self.Update()
         wx.CallAfter(self.SetPage, 'view')
-        wx.CallAfter(self.UpdateScrolling, (self.foldpanelData, self.foldpanelAppear,
-                                            self.foldpanelAnalysis))       
+        wx.CallAfter(
+            self.UpdateScrolling,
+            (self.foldpanelData,
+             self.foldpanelAppear,
+             self.foldpanelAnalysis))
         wx.CallAfter(self.SetInitialMaps)
-        
+
     def SetInitialMaps(self):
         """Set initial raster and vector map"""
         for ltype in ('raster', 'vector', 'raster_3d'):
-            selectedLayer = self.tree.GetSelectedLayer(multi = False, checkedOnly = True)
+            selectedLayer = self.tree.GetSelectedLayer(
+                multi=False, checkedOnly=True)
             if selectedLayer is None:
                 continue
-            selectedLayer = self.tree.GetLayerInfo(selectedLayer, key = 'maplayer')
-            layers = self.mapWindow.Map.GetListOfLayers(ltype = ltype, active = True)
+            selectedLayer = self.tree.GetLayerInfo(
+                selectedLayer, key='maplayer')
+            layers = self.mapWindow.Map.GetListOfLayers(
+                ltype=ltype, active=True)
             if selectedLayer in layers:
                 selection = selectedLayer.GetName()
             else:
@@ -143,1896 +152,2277 @@
                 except:
                     continue
             if ltype == 'raster':
-                self.FindWindowById(self.win['surface']['map']).SetValue(selection)
-                self.FindWindowById(self.win['fringe']['map']).SetValue(selection)
+                self.FindWindowById(
+                    self.win['surface']['map']).SetValue(selection)
+                self.FindWindowById(
+                    self.win['fringe']['map']).SetValue(selection)
             elif ltype == 'vector':
-                self.FindWindowById(self.win['vector']['map']).SetValue(selection)
+                self.FindWindowById(
+                    self.win['vector']['map']).SetValue(selection)
             elif ltype == 'raster_3d':
-                self.FindWindowById(self.win['volume']['map']).SetValue(selection)
-               
+                self.FindWindowById(
+                    self.win['volume']['map']).SetValue(selection)
+
     def UpdateState(self, **kwargs):
         if 'view' in kwargs:
             self.mapWindow.view = kwargs['view']
-            self.FindWindowById(self.win['view']['position']).data = kwargs['view']
+            self.FindWindowById(
+                self.win['view']['position']).data = kwargs['view']
             self.FindWindowById(self.win['view']['position']).PostDraw()
         if 'iview' in kwargs:
             self.mapWindow.iview = kwargs['iview']
         if 'light' in kwargs:
-            self.mapWindow.light = kwargs['light']  
-            self.FindWindowById(self.win['light']['position']).data = kwargs['light']  
+            self.mapWindow.light = kwargs['light']
+            self.FindWindowById(
+                self.win['light']['position']).data = kwargs['light']
             self.FindWindowById(self.win['light']['position']).PostDraw()
         if 'fly' in kwargs:
             self.mapWindow.fly['exag'] = kwargs['fly']['exag']
-    
+
     def LoadSettings(self):
         """Load Nviz settings and apply to current session"""
-        view = copy.deepcopy(UserSettings.Get(group = 'nviz', key = 'view')) # copy
-        light = copy.deepcopy(UserSettings.Get(group = 'nviz', key = 'light')) # copy
-        fly = copy.deepcopy(UserSettings.Get(group = 'nviz', key = 'fly')) # copy
-        self.UpdateState(view = view, light = light, fly = fly)
-        self.PostViewEvent(zExag = True)
+        view = copy.deepcopy(
+            UserSettings.Get(
+                group='nviz',
+                key='view'))  # copy
+        light = copy.deepcopy(
+            UserSettings.Get(
+                group='nviz',
+                key='light'))  # copy
+        fly = copy.deepcopy(UserSettings.Get(group='nviz', key='fly'))  # copy
+        self.UpdateState(view=view, light=light, fly=fly)
+        self.PostViewEvent(zExag=True)
         self.PostLightEvent()
         self.UpdatePage('view')
         self.UpdatePage('light')
-        
+
         self.mapWindow.ReloadLayersData()
         self.UpdatePage('surface')
         self.UpdatePage('vector')
         self.UpdateSettings()
-               
+
     def OnPageChanged(self, event):
         new = event.GetSelection()
         # self.ChangeSelection(new)
-        
-    def PostViewEvent(self, zExag = False):
+
+    def PostViewEvent(self, zExag=False):
         """Change view settings"""
-        event = wxUpdateView(zExag = zExag)
+        event = wxUpdateView(zExag=zExag)
         wx.PostEvent(self.mapWindow, event)
-        
-    def PostLightEvent(self, refresh = False): 
-        """Change light settings""" 
-        event = wxUpdateLight(refresh = refresh)
+
+    def PostLightEvent(self, refresh=False):
+        """Change light settings"""
+        event = wxUpdateLight(refresh=refresh)
         wx.PostEvent(self.mapWindow, event)
-        
+
     def OnSize(self, event):
         """After window is resized, update scrolling"""
         # workaround to resize captionbars of foldpanelbar
-        wx.CallAfter(self.UpdateScrolling, (self.foldpanelData, self.foldpanelAppear,
-                                            self.foldpanelAnalysis)) 
+        wx.CallAfter(
+            self.UpdateScrolling,
+            (self.foldpanelData,
+             self.foldpanelAppear,
+             self.foldpanelAnalysis))
         event.Skip()
-           
+
     def OnPressCaption(self, event):
         """When foldpanel item collapsed/expanded, update scrollbars"""
         foldpanel = event.GetBar().GetGrandParent().GetParent()
         wx.CallAfter(self.UpdateScrolling, (foldpanel,))
         event.Skip()
-        
+
     def UpdateScrolling(self, foldpanels):
         """Update scrollbars in foldpanel"""
         for foldpanel in foldpanels:
-            length = foldpanel.GetPanelsLength(collapsed = 0, expanded = 0)
+            length = foldpanel.GetPanelsLength(collapsed=0, expanded=0)
             # virtual width is set to fixed value to suppress GTK warning
             foldpanel.GetParent().SetVirtualSize((100, length[2]))
             foldpanel.GetParent().Layout()
-        
+
     def _createViewPage(self):
         """Create view settings page"""
-        panel = SP.ScrolledPanel(parent = self, id = wx.ID_ANY)
-        panel.SetupScrolling(scroll_x = False)
-        self.page['view'] = { 'id' : 0,
-                              'notebook' : self.GetId()}
-        
+        panel = SP.ScrolledPanel(parent=self, id=wx.ID_ANY)
+        panel.SetupScrolling(scroll_x=False)
+        self.page['view'] = {'id': 0,
+                             'notebook': self.GetId()}
+
         pageSizer = wx.BoxSizer(wx.VERTICAL)
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Control View")))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Control View")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 5, hgap = 10)
-        
+        gridSizer = wx.GridBagSizer(vgap=5, hgap=10)
+
         self.win['view'] = {}
-        
+
         # position
-        posSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
-        
-        self._createCompass(panel = panel, sizer = posSizer, type = 'view')
-        
-        view = ViewPositionWindow(panel, size = (175, 175),
-                                  mapwindow = self.mapWindow)
+        posSizer = wx.GridBagSizer(vgap=3, hgap=3)
+
+        self._createCompass(panel=panel, sizer=posSizer, type='view')
+
+        view = ViewPositionWindow(panel, size=(175, 175),
+                                  mapwindow=self.mapWindow)
         self.win['view']['position'] = view.GetId()
-        posSizer.Add(item = view,
-                     pos = (1, 1), flag = wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = posSizer, pos = (0, 0))
-                  
+        posSizer.Add(
+            item=view, pos=(1, 1),
+            flag=wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(item=posSizer, pos=(0, 0))
+
         # perspective
         # set initial defaults here (or perhaps in a default values file), not in user settings
-        #todo: consider setting an absolute max at 360 instead of undefined. (leave the default max value at pi)
-        tooltip = _("Adjusts the distance and angular perspective of the image viewpoint")
-        self._createControl(panel, data = self.win['view'], name = 'persp',
-                            tooltip = tooltip, range = (1, 120),
-                            bind = (self.OnViewChange, self.OnViewChanged, self.OnViewChangedText))
-        
-        gridSizer.Add(item = wx.StaticText(panel, id = wx.ID_ANY, label = _("Perspective:")),
-                      pos = (1, 0), flag = wx.ALIGN_CENTER)
-        gridSizer.Add(item = self.FindWindowById(self.win['view']['persp']['slider']), pos = (2, 0),
-                      flag = wx.ALIGN_CENTER)
-        gridSizer.Add(item = self.FindWindowById(self.win['view']['persp']['text']), pos = (3, 0),
-                      flag = wx.ALIGN_CENTER)        
-        
+        # todo: consider setting an absolute max at 360 instead of undefined.
+        # (leave the default max value at pi)
+        tooltip = _(
+            "Adjusts the distance and angular perspective of the image viewpoint")
+        self._createControl(
+            panel,
+            data=self.win['view'],
+            name='persp',
+            tooltip=tooltip,
+            range=(
+                1,
+                120),
+            bind=(
+                self.OnViewChange,
+                self.OnViewChanged,
+                self.OnViewChangedText))
+
+        gridSizer.Add(
+            item=wx.StaticText(
+                panel, id=wx.ID_ANY, label=_("Perspective:")), pos=(
+                1, 0), flag=wx.ALIGN_CENTER)
+        gridSizer.Add(
+            item=self.FindWindowById(
+                self.win['view']['persp']['slider']), pos=(
+                2, 0), flag=wx.ALIGN_CENTER)
+        gridSizer.Add(
+            item=self.FindWindowById(
+                self.win['view']['persp']['text']), pos=(
+                3, 0), flag=wx.ALIGN_CENTER)
+
         # twist
         tooltip = _("Tilts the plane of the surface from the horizontal")
-        self._createControl(panel, data = self.win['view'], name = 'twist',
-                            tooltip = tooltip, range = (-180,180),
-                            bind = (self.OnViewChange, self.OnViewChanged, self.OnViewChangedText))
-        gridSizer.Add(item = wx.StaticText(panel, id = wx.ID_ANY, label = _("Tilt:")),
-                      pos = (1, 1), flag = wx.ALIGN_CENTER)
-        gridSizer.Add(item = self.FindWindowById(self.win['view']['twist']['slider']), pos = (2, 1))
-        gridSizer.Add(item = self.FindWindowById(self.win['view']['twist']['text']), pos = (3, 1),
-                      flag = wx.ALIGN_CENTER)        
-        
+        self._createControl(panel,
+                            data=self.win['view'],
+                            name='twist',
+                            tooltip=tooltip,
+                            range=(-180,
+                                   180),
+                            bind=(self.OnViewChange,
+                                  self.OnViewChanged,
+                                  self.OnViewChangedText))
+        gridSizer.Add(
+            item=wx.StaticText(
+                panel, id=wx.ID_ANY, label=_("Tilt:")), pos=(
+                1, 1), flag=wx.ALIGN_CENTER)
+        gridSizer.Add(
+            item=self.FindWindowById(
+                self.win['view']['twist']['slider']), pos=(
+                2, 1))
+        gridSizer.Add(
+            item=self.FindWindowById(
+                self.win['view']['twist']['text']), pos=(
+                3, 1), flag=wx.ALIGN_CENTER)
+
         # height + z-exag
-        tooltip = _("Adjusts the viewing height above the surface"
-                    " (angle of view automatically adjusts to maintain the same center of view)")
-        self._createControl(panel, data = self.win['view'], name = 'height', sliderHor = False,
-                            tooltip = tooltip, range = (0, 1),
-                            bind = (self.OnViewChange, self.OnViewChanged, self.OnViewChangedText))
-        tooltip = _("Adjusts the relative height of features above the plane of the surface")
-        self._createControl(panel, data = self.win['view'], name = 'z-exag', sliderHor = False,
-                            tooltip = tooltip, range = (0, 10), floatSlider = True,
-                            bind = (self.OnViewChange, self.OnViewChanged, self.OnViewChangedText))
+        tooltip = _(
+            "Adjusts the viewing height above the surface"
+            " (angle of view automatically adjusts to maintain the same center of view)")
+        self._createControl(
+            panel,
+            data=self.win['view'],
+            name='height',
+            sliderHor=False,
+            tooltip=tooltip,
+            range=(
+                0,
+                1),
+            bind=(
+                self.OnViewChange,
+                self.OnViewChanged,
+                self.OnViewChangedText))
+        tooltip = _(
+            "Adjusts the relative height of features above the plane of the surface")
+        self._createControl(
+            panel,
+            data=self.win['view'],
+            name='z-exag',
+            sliderHor=False,
+            tooltip=tooltip,
+            range=(
+                0,
+                10),
+            floatSlider=True,
+            bind=(
+                self.OnViewChange,
+                self.OnViewChanged,
+                self.OnViewChangedText))
         self.FindWindowById(self.win['view']['z-exag']['slider']).SetValue(1)
         self.FindWindowById(self.win['view']['z-exag']['text']).SetValue(1)
-        
-        heightSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
-        heightSizer.Add(item = wx.StaticText(panel, id = wx.ID_ANY, label = _("Height:")),
-                      pos = (0, 0), flag = wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL, span = (1, 2))
-        heightSizer.Add(item = self.FindWindowById(self.win['view']['height']['slider']),
-                        flag = wx.ALIGN_RIGHT, pos = (1, 0))
-        heightSizer.Add(item = self.FindWindowById(self.win['view']['height']['text']),
-                        flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT, pos = (1, 1))
-        heightSizer.Add(item = wx.StaticText(panel, id = wx.ID_ANY, label = _("Z-exag:")),
-                      pos = (0, 2), flag = wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL, span = (1, 2))
-        heightSizer.Add(item = self.FindWindowById(self.win['view']['z-exag']['slider']),
-                        flag = wx.ALIGN_RIGHT, pos = (1, 2))
-        heightSizer.Add(item = self.FindWindowById(self.win['view']['z-exag']['text']),
-                        flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT | wx.TOP |
-                        wx.BOTTOM | wx.RIGHT, pos = (1, 3))
-        
-        gridSizer.Add(item = heightSizer, pos = (0, 1), flag = wx.ALIGN_CENTER)
-        
+
+        heightSizer = wx.GridBagSizer(vgap=3, hgap=3)
+        heightSizer.Add(
+            item=wx.StaticText(
+                panel, id=wx.ID_ANY, label=_("Height:")), pos=(
+                0, 0), flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, span=(
+                1, 2))
+        heightSizer.Add(
+            item=self.FindWindowById(
+                self.win['view']['height']['slider']),
+            flag=wx.ALIGN_RIGHT,
+            pos=(
+                1,
+                0))
+        heightSizer.Add(
+            item=self.FindWindowById(
+                self.win['view']['height']['text']),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT,
+            pos=(
+                1,
+                1))
+        heightSizer.Add(
+            item=wx.StaticText(
+                panel,
+                id=wx.ID_ANY,
+                label=_("Z-exag:")),
+            pos=(
+                0,
+                2),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
+            span=(
+                1,
+                2))
+        heightSizer.Add(
+            item=self.FindWindowById(
+                self.win['view']['z-exag']['slider']),
+            flag=wx.ALIGN_RIGHT,
+            pos=(
+                1,
+                2))
+        heightSizer.Add(item=self.FindWindowById(
+            self.win['view']['z-exag']['text']),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT | wx.TOP |
+            wx.BOTTOM | wx.RIGHT, pos=(1, 3))
+
+        gridSizer.Add(item=heightSizer, pos=(0, 1), flag=wx.ALIGN_CENTER)
+
         # view setup + reset
         viewSizer = wx.BoxSizer(wx.HORIZONTAL)
-        viewSizer.Add(item = wx.StaticText(panel, id = wx.ID_ANY,
-                                           label = _("Look:")),
-                      flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL,
-                      border = 5)
-        here = wx.ToggleButton(panel, id = wx.ID_ANY, label = _("here"))
+        viewSizer.Add(item=wx.StaticText(panel, id=wx.ID_ANY,
+                                         label=_("Look:")),
+                      flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL,
+                      border=5)
+        here = wx.ToggleButton(panel, id=wx.ID_ANY, label=_("here"))
         here.Bind(wx.EVT_TOGGLEBUTTON, self.OnLookAt)
         here.SetName('here')
         here.SetToolTipString(_("Allows you to select a point on the surface "
                                 "that becomes the new center of view. "
                                 "Click on the button and then on the surface."))
-        viewSizer.Add(item = here, flag = wx.TOP|wx.BOTTOM|wx.LEFT|wx.ALIGN_CENTER_VERTICAL,
-                      border = 5)
-                    
-        center = wx.Button(panel, id = wx.ID_ANY, label = _("center"))
+        viewSizer.Add(item=here, flag=wx.TOP | wx.BOTTOM |
+                      wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border=5)
+
+        center = wx.Button(panel, id=wx.ID_ANY, label=_("center"))
         center.Bind(wx.EVT_BUTTON, self.OnLookAt)
         center.SetName('center')
-        center.SetToolTipString(_("Resets the view to the original default center of view"))
-        viewSizer.Add(item = center, flag = wx.TOP|wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL,
-                      border = 5)
-                    
-        top = wx.Button(panel, id = wx.ID_ANY, label = _("top"))
+        center.SetToolTipString(
+            _("Resets the view to the original default center of view"))
+        viewSizer.Add(item=center, flag=wx.TOP | wx.BOTTOM |
+                      wx.ALIGN_CENTER_VERTICAL, border=5)
+
+        top = wx.Button(panel, id=wx.ID_ANY, label=_("top"))
         top.Bind(wx.EVT_BUTTON, self.OnLookAt)
         top.SetName('top')
-        top.SetToolTipString(_("Sets the viewer directly over the scene's center position. This top view orients approximately north south."))
-        viewSizer.Add(item = top, flag = wx.TOP|wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL,
-                      border = 5)
-                    
-        reset = wx.Button(panel, id = wx.ID_ANY, label = _("reset"))
+        top.SetToolTipString(
+            _("Sets the viewer directly over the scene's center position. This top view orients approximately north south."))
+        viewSizer.Add(item=top, flag=wx.TOP | wx.BOTTOM |
+                      wx.ALIGN_CENTER_VERTICAL, border=5)
+
+        reset = wx.Button(panel, id=wx.ID_ANY, label=_("reset"))
         reset.SetToolTipString(_("Reset to default view"))
         reset.Bind(wx.EVT_BUTTON, self.OnResetView)
-        viewSizer.Add(item = reset, proportion = 0,
-                      flag = wx.TOP|wx.BOTTOM|wx.RIGHT| wx.ALIGN_RIGHT,
-                      border = 5)
-        
-        gridSizer.Add(item = viewSizer, pos = (4, 0), span = (1, 3),
-                      flag = wx.EXPAND)
-        
+        viewSizer.Add(item=reset, proportion=0,
+                      flag=wx.TOP | wx.BOTTOM | wx.RIGHT | wx.ALIGN_RIGHT,
+                      border=5)
+
+        gridSizer.Add(item=viewSizer, pos=(4, 0), span=(1, 3),
+                      flag=wx.EXPAND)
+
         # body
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                  flag = wx.ALL | wx.EXPAND, border = 2)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL,
-                      border = 3)
-        
-        box = wx.StaticBox(parent = panel, id = wx.ID_ANY,
-                           label = " %s " % (_("Image Appearance")))
+        boxSizer.Add(item=gridSizer, proportion=1,
+                     flag=wx.ALL | wx.EXPAND, border=2)
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALL,
+                      border=3)
+
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Image Appearance")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
-        
+        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)
+
         # background color
         self.win['view']['background'] = {}
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Background color:")),
-                      pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        color = csel.ColourSelect(panel, id = wx.ID_ANY,
-                                  colour = UserSettings.Get(group = 'nviz', key = 'view',
-                                                            subkey = ['background', 'color']),
-                                  size = globalvar.DIALOG_COLOR_SIZE)
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Background color:")),
+                      pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+
+        color = csel.ColourSelect(
+            panel,
+            id=wx.ID_ANY,
+            colour=UserSettings.Get(
+                group='nviz',
+                key='view',
+                subkey=[
+                    'background',
+                    'color']),
+            size=globalvar.DIALOG_COLOR_SIZE)
         self.win['view']['background']['color'] = color.GetId()
         color.Bind(csel.EVT_COLOURSELECT, self.OnBgColor)
-        gridSizer.Add(item = color, pos = (0, 1))
+        gridSizer.Add(item=color, pos=(0, 1))
         gridSizer.AddGrowableCol(0)
-        
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                  flag = wx.ALL | wx.EXPAND, border = 3)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT,
-                      border = 3)
-        
+
+        boxSizer.Add(item=gridSizer, proportion=1,
+                     flag=wx.ALL | wx.EXPAND, border=3)
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT,
+                      border=3)
+
         panel.SetSizer(pageSizer)
-        
+
         return panel
-        
+
     def _createAnimationPage(self):
         """Create view settings page"""
-        panel = SP.ScrolledPanel(parent = self, id = wx.ID_ANY)
-        panel.SetupScrolling(scroll_x = False)
-        self.page['animation'] = { 'id' : 0,
-                                   'notebook' : self.GetId()}
-        
+        panel = SP.ScrolledPanel(parent=self, id=wx.ID_ANY)
+        panel.SetupScrolling(scroll_x=False)
+        self.page['animation'] = {'id': 0,
+                                  'notebook': self.GetId()}
+
         pageSizer = wx.BoxSizer(wx.VERTICAL)
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Animation")))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Animation")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
         hSizer = wx.BoxSizer(wx.HORIZONTAL)
-        
+
         self.win['anim'] = {}
         # animation help text
-        help = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                             label = _("Press 'Record' button and start changing the view. "
-                                       "It is recommended to use fly-through mode "
-                                       "(Map Display toolbar) to achieve smooth motion."))
+        help = wx.StaticText(
+            parent=panel, id=wx.ID_ANY, label=_(
+                "Press 'Record' button and start changing the view. "
+                "It is recommended to use fly-through mode "
+                "(Map Display toolbar) to achieve smooth motion."))
         self.win['anim']['help'] = help.GetId()
-        hSizer.Add(item = help, proportion = 0)
-        boxSizer.Add(item = hSizer, proportion = 1,
-                     flag = wx.ALL | wx.EXPAND, border = 5)
-                     
+        hSizer.Add(item=help, proportion=0)
+        boxSizer.Add(item=hSizer, proportion=1,
+                     flag=wx.ALL | wx.EXPAND, border=5)
+
         # animation controls
         hSizer = wx.BoxSizer(wx.HORIZONTAL)
-        record = SymbolButton(parent = panel, id = wx.ID_ANY,
-                              usage = "record", label = _("Record"))
-        play = SymbolButton(parent = panel, id = wx.ID_ANY,
-                            usage = "play", label = _("Play"))
-        pause = SymbolButton(parent = panel, id = wx.ID_ANY,
-                             usage = "pause", label = _("Pause"))
-        stop = SymbolButton(parent = panel, id = wx.ID_ANY,
-                            usage = "stop", label = _("Stop"))
-        
+        record = SymbolButton(parent=panel, id=wx.ID_ANY,
+                              usage="record", label=_("Record"))
+        play = SymbolButton(parent=panel, id=wx.ID_ANY,
+                            usage="play", label=_("Play"))
+        pause = SymbolButton(parent=panel, id=wx.ID_ANY,
+                             usage="pause", label=_("Pause"))
+        stop = SymbolButton(parent=panel, id=wx.ID_ANY,
+                            usage="stop", label=_("Stop"))
+
         self.win['anim']['record'] = record.GetId()
         self.win['anim']['play'] = play.GetId()
         self.win['anim']['pause'] = pause.GetId()
         self.win['anim']['stop'] = stop.GetId()
-                            
-        self._createControl(panel, data = self.win['anim'], name = 'frameIndex',
-                            range = (0, 1), floatSlider = False,
-                            bind = (self.OnFrameIndex, None, self.OnFrameIndexText))
-        frameSlider = self.FindWindowById(self.win['anim']['frameIndex']['slider'])
+
+        self._createControl(
+            panel, data=self.win['anim'], name='frameIndex', range=(
+                0, 1), floatSlider=False, bind=(
+                self.OnFrameIndex, None, self.OnFrameIndexText))
+        frameSlider = self.FindWindowById(
+            self.win['anim']['frameIndex']['slider'])
         frameText = self.FindWindowById(self.win['anim']['frameIndex']['text'])
-        infoLabel = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Total number of frames :"))
-        info = wx.StaticText(parent = panel, id = wx.ID_ANY)
+        infoLabel = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Total number of frames :"))
+        info = wx.StaticText(parent=panel, id=wx.ID_ANY)
         self.win['anim']['info'] = info.GetId()
-        
-        fpsLabel = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Frame rate (FPS):"))
-        fps = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = UserSettings.Get(group = 'nviz', key = 'animation', subkey = 'fps'),
-                           min = 1,
-                           max = 50)
+
+        fpsLabel = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Frame rate (FPS):"))
+        fps = wx.SpinCtrl(
+            parent=panel, id=wx.ID_ANY, size=(65, -1),
+            initial=UserSettings.Get(
+                group='nviz', key='animation', subkey='fps'),
+            min=1, max=50)
         self.win['anim']['fps'] = fps.GetId()
-        fps.SetToolTipString(_("Frames are recorded with given frequency (FPS). "))
-                            
+        fps.SetToolTipString(
+            _("Frames are recorded with given frequency (FPS). "))
+
         record.Bind(wx.EVT_BUTTON, self.OnRecord)
         play.Bind(wx.EVT_BUTTON, self.OnPlay)
         stop.Bind(wx.EVT_BUTTON, self.OnStop)
         pause.Bind(wx.EVT_BUTTON, self.OnPause)
         fps.Bind(wx.EVT_SPINCTRL, self.OnFPS)
-        
-        hSizer.Add(item = record, proportion = 0)
-        hSizer.Add(item = play, proportion = 0)
-        hSizer.Add(item = pause, proportion = 0)
-        hSizer.Add(item = stop, proportion = 0)
-        boxSizer.Add(item = hSizer, proportion = 0,
-                     flag = wx.ALL | wx.EXPAND, border = 3)
-        
+
+        hSizer.Add(item=record, proportion=0)
+        hSizer.Add(item=play, proportion=0)
+        hSizer.Add(item=pause, proportion=0)
+        hSizer.Add(item=stop, proportion=0)
+        boxSizer.Add(item=hSizer, proportion=0,
+                     flag=wx.ALL | wx.EXPAND, border=3)
+
         sliderBox = wx.BoxSizer(wx.HORIZONTAL)
-        sliderBox.Add(item = frameSlider, proportion = 1, border = 5, flag = wx.EXPAND | wx.RIGHT)
-        sliderBox.Add(item = frameText, proportion = 0, border = 5, flag = wx.EXPAND| wx.RIGHT | wx.LEFT)
-        boxSizer.Add(item = sliderBox, proportion = 0, flag = wx.EXPAND)
-        
+        sliderBox.Add(
+            item=frameSlider,
+            proportion=1,
+            border=5,
+            flag=wx.EXPAND | wx.RIGHT)
+        sliderBox.Add(
+            item=frameText,
+            proportion=0,
+            border=5,
+            flag=wx.EXPAND | wx.RIGHT | wx.LEFT)
+        boxSizer.Add(item=sliderBox, proportion=0, flag=wx.EXPAND)
+
         # total number of frames
         hSizer = wx.BoxSizer(wx.HORIZONTAL)
-        hSizer.Add(item = infoLabel, proportion = 0, flag = wx.RIGHT, border = 5)
-        hSizer.Add(item = info, proportion = 0, flag = wx.LEFT, border = 5)
-        
-        boxSizer.Add(item = hSizer, proportion = 0,
-                     flag = wx.ALL | wx.EXPAND, border = 5)
-                     
+        hSizer.Add(item=infoLabel, proportion=0, flag=wx.RIGHT, border=5)
+        hSizer.Add(item=info, proportion=0, flag=wx.LEFT, border=5)
+
+        boxSizer.Add(item=hSizer, proportion=0,
+                     flag=wx.ALL | wx.EXPAND, border=5)
+
         # frames per second
         hSizer = wx.BoxSizer(wx.HORIZONTAL)
-        hSizer.Add(item = fpsLabel, proportion = 0, flag = wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, border = 5)
-        hSizer.Add(item = fps, proportion = 0, flag = wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border = 5)
-        
-        boxSizer.Add(item = hSizer, proportion = 0,
-                     flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 3)
-                      
+        hSizer.Add(
+            item=fpsLabel,
+            proportion=0,
+            flag=wx.RIGHT | wx.ALIGN_CENTER_VERTICAL,
+            border=5)
+        hSizer.Add(item=fps, proportion=0, flag=wx.LEFT |
+                   wx.ALIGN_CENTER_VERTICAL, border=5)
+
+        boxSizer.Add(item=hSizer, proportion=0,
+                     flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=5)
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                      border=3)
+
         # save animation
         self.win['anim']['save'] = {}
         self.win['anim']['save']['image'] = {}
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Save image sequence")))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Save image sequence")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
         vSizer = wx.BoxSizer(wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 5, hgap = 10)
-        
+        gridSizer = wx.GridBagSizer(vgap=5, hgap=10)
+
         pwd = os.getcwd()
-        dir = filebrowse.DirBrowseButton(parent = panel, id = wx.ID_ANY,
-                                         labelText = _("Choose a directory:"),
-                                         dialogTitle = _("Choose a directory for images"),
-                                         buttonText = _('Browse'),
-                                         startDirectory = pwd)
+        dir = filebrowse.DirBrowseButton(
+            parent=panel,
+            id=wx.ID_ANY,
+            labelText=_("Choose a directory:"),
+            dialogTitle=_("Choose a directory for images"),
+            buttonText=_('Browse'),
+            startDirectory=pwd)
         dir.SetValue(pwd)
-        prefixLabel = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("File prefix:"))
-        prefixCtrl = wx.TextCtrl(parent = panel, id = wx.ID_ANY, size = (100, -1),
-                                 value = UserSettings.Get(group = 'nviz',
-                                                          key = 'animation', subkey = 'prefix'))
-        prefixCtrl.SetToolTipString(_("Generated files names will look like this: prefix_1.ppm, prefix_2.ppm, ..."))
-        fileTypeLabel = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("File format:"))
-        fileTypeCtrl = wx.Choice(parent = panel, id = wx.ID_ANY, choices = ["TIF", "PPM"])
-        
-        save = wx.Button(parent = panel, id = wx.ID_ANY,
-                         label = "Save")
-                         
+        prefixLabel = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("File prefix:"))
+        prefixCtrl = wx.TextCtrl(
+            parent=panel, id=wx.ID_ANY, size=(100, -1),
+            value=UserSettings.Get(
+                group='nviz', key='animation', subkey='prefix'))
+        prefixCtrl.SetToolTipString(
+            _("Generated files names will look like this: prefix_1.ppm, prefix_2.ppm, ..."))
+        fileTypeLabel = wx.StaticText(
+            parent=panel, id=wx.ID_ANY, label=_("File format:"))
+        fileTypeCtrl = wx.Choice(
+            parent=panel, id=wx.ID_ANY, choices=[
+                "TIF", "PPM"])
+
+        save = wx.Button(parent=panel, id=wx.ID_ANY,
+                         label="Save")
+
         self.win['anim']['save']['image']['dir'] = dir.GetId()
         self.win['anim']['save']['image']['prefix'] = prefixCtrl.GetId()
         self.win['anim']['save']['image']['format'] = fileTypeCtrl.GetId()
         self.win['anim']['save']['image']['confirm'] = save.GetId()
-        
-        boxSizer.Add(item = dir, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 3)
-        
-        gridSizer.Add(item = prefixLabel, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
-        gridSizer.Add(item = prefixCtrl, pos = (0, 1), flag = wx.EXPAND )
-        gridSizer.Add(item = fileTypeLabel, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
-        gridSizer.Add(item = fileTypeCtrl, pos = (1, 1), flag = wx.EXPAND )
-        
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                     flag = wx.ALL | wx.EXPAND, border = 5)
-        boxSizer.Add(item = save, proportion = 0, flag = wx.ALL | wx.ALIGN_RIGHT, border = 5)
-        
+
+        boxSizer.Add(item=dir, proportion=0, flag=wx.ALL | wx.EXPAND, border=3)
+
+        gridSizer.Add(
+            item=prefixLabel, pos=(0, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
+        gridSizer.Add(item=prefixCtrl, pos=(0, 1), flag=wx.EXPAND)
+        gridSizer.Add(
+            item=fileTypeLabel, pos=(1, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
+        gridSizer.Add(item=fileTypeCtrl, pos=(1, 1), flag=wx.EXPAND)
+
+        boxSizer.Add(item=gridSizer, proportion=1,
+                     flag=wx.ALL | wx.EXPAND, border=5)
+        boxSizer.Add(
+            item=save,
+            proportion=0,
+            flag=wx.ALL | wx.ALIGN_RIGHT,
+            border=5)
+
         save.Bind(wx.EVT_BUTTON, self.OnSaveAnimation)
-        
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 
-                      border = 3)
-        
+
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                      border=3)
+
         panel.SetSizer(pageSizer)
-        
+
         return panel
-        
+
     def _createDataPage(self):
         """Create data (surface, vector, volume) settings page"""
 
-        self.mainPanelData = ScrolledPanel(parent = self)
-        self.mainPanelData.SetupScrolling(scroll_x = False)
-        try:# wxpython <= 2.8.10
-            self.foldpanelData = fpb.FoldPanelBar(parent = self.mainPanelData, id = wx.ID_ANY,
-                                                  style = fpb.FPB_DEFAULT_STYLE,
-                                                  extraStyle = fpb.FPB_SINGLE_FOLD)
+        self.mainPanelData = ScrolledPanel(parent=self)
+        self.mainPanelData.SetupScrolling(scroll_x=False)
+        try:  # wxpython <= 2.8.10
+            self.foldpanelData = fpb.FoldPanelBar(
+                parent=self.mainPanelData, id=wx.ID_ANY,
+                style=fpb.FPB_DEFAULT_STYLE, extraStyle=fpb.FPB_SINGLE_FOLD)
         except:
-            try:# wxpython >= 2.8.11
-                self.foldpanelData = fpb.FoldPanelBar(parent = self.mainPanelData, id = wx.ID_ANY,                               
-                                                      agwStyle = fpb.FPB_SINGLE_FOLD)
-            except: # to be sure
-                self.foldpanelData = fpb.FoldPanelBar(parent = self.mainPanelData, id = wx.ID_ANY,                               
-                                                      style = fpb.FPB_SINGLE_FOLD)
-            
-                     
+            try:  # wxpython >= 2.8.11
+                self.foldpanelData = fpb.FoldPanelBar(
+                    parent=self.mainPanelData, id=wx.ID_ANY,
+                    agwStyle=fpb.FPB_SINGLE_FOLD)
+            except:  # to be sure
+                self.foldpanelData = fpb.FoldPanelBar(
+                    parent=self.mainPanelData, id=wx.ID_ANY,
+                    style=fpb.FPB_SINGLE_FOLD)
+
         self.foldpanelData.Bind(fpb.EVT_CAPTIONBAR, self.OnPressCaption)
 
+        # # surface page
+        surfacePanel = self.foldpanelData.AddFoldPanel(
+            _("Surface"), collapsed=False)
+        self.foldpanelData.AddFoldPanelWindow(
+            surfacePanel, window=self._createSurfacePage(
+                parent=surfacePanel), flags=fpb.FPB_ALIGN_WIDTH)
+        self.EnablePage("surface", enabled=False)
 
-        
-        # # surface page
-        surfacePanel = self.foldpanelData.AddFoldPanel(_("Surface"), collapsed = False)
-        self.foldpanelData.AddFoldPanelWindow(surfacePanel, 
-            window = self._createSurfacePage(parent = surfacePanel), flags = fpb.FPB_ALIGN_WIDTH)
-        self.EnablePage("surface", enabled = False)
-        
         # constant page
-        constantPanel = self.foldpanelData.AddFoldPanel(_("Constant surface"), collapsed = True)
-        self.foldpanelData.AddFoldPanelWindow(constantPanel,
-            window = self._createConstantPage(parent = constantPanel), flags = fpb.FPB_ALIGN_WIDTH)
-        self.EnablePage("constant", enabled = False)
+        constantPanel = self.foldpanelData.AddFoldPanel(
+            _("Constant surface"), collapsed=True)
+        self.foldpanelData.AddFoldPanelWindow(
+            constantPanel, window=self._createConstantPage(
+                parent=constantPanel), flags=fpb.FPB_ALIGN_WIDTH)
+        self.EnablePage("constant", enabled=False)
         # vector page
-        vectorPanel = self.foldpanelData.AddFoldPanel(_("Vector"), collapsed = True)
-        self.foldpanelData.AddFoldPanelWindow(vectorPanel, 
-            window = self._createVectorPage(parent = vectorPanel), flags = fpb.FPB_ALIGN_WIDTH)
-        self.EnablePage("vector", enabled = False)
-        
+        vectorPanel = self.foldpanelData.AddFoldPanel(
+            _("Vector"), collapsed=True)
+        self.foldpanelData.AddFoldPanelWindow(
+            vectorPanel, window=self._createVectorPage(
+                parent=vectorPanel), flags=fpb.FPB_ALIGN_WIDTH)
+        self.EnablePage("vector", enabled=False)
+
         # volume page
-        volumePanel = self.foldpanelData.AddFoldPanel(_("3D raster"), collapsed=True)
-        self.foldpanelData.AddFoldPanelWindow(volumePanel,
-            window = self._createVolumePage(parent = volumePanel), flags = fpb.FPB_ALIGN_WIDTH)
-        self.EnablePage("volume", enabled = False)
-        
-##        self.foldpanelData.ApplyCaptionStyleAll(style)
-        
+        volumePanel = self.foldpanelData.AddFoldPanel(
+            _("3D raster"), collapsed=True)
+        self.foldpanelData.AddFoldPanelWindow(
+            volumePanel, window=self._createVolumePage(
+                parent=volumePanel), flags=fpb.FPB_ALIGN_WIDTH)
+        self.EnablePage("volume", enabled=False)
+
+# self.foldpanelData.ApplyCaptionStyleAll(style)
+
         sizer = wx.BoxSizer(wx.VERTICAL)
-        sizer.Add(self.foldpanelData, proportion = 1, flag = wx.EXPAND)
+        sizer.Add(self.foldpanelData, proportion=1, flag=wx.EXPAND)
         self.mainPanelData.SetSizer(sizer)
         self.mainPanelData.Layout()
         self.mainPanelData.Fit()
-        
+
         return self.mainPanelData
-        
-        
+
     def _createAppearancePage(self):
         """Create data (surface, vector, volume) settings page"""
-        self.mainPanelAppear = ScrolledPanel(parent = self)
-        self.mainPanelAppear.SetupScrolling(scroll_x = False)
-        
-        try:# wxpython <= 2.8.10
-            self.foldpanelAppear = fpb.FoldPanelBar(parent = self.mainPanelAppear, id = wx.ID_ANY,
-                                                  style = fpb.FPB_DEFAULT_STYLE,
-                                                  extraStyle = fpb.FPB_SINGLE_FOLD)
+        self.mainPanelAppear = ScrolledPanel(parent=self)
+        self.mainPanelAppear.SetupScrolling(scroll_x=False)
+
+        try:  # wxpython <= 2.8.10
+            self.foldpanelAppear = fpb.FoldPanelBar(
+                parent=self.mainPanelAppear, id=wx.ID_ANY,
+                style=fpb.FPB_DEFAULT_STYLE, extraStyle=fpb.FPB_SINGLE_FOLD)
         except:
-            try:# wxpython >= 2.8.11
-                self.foldpanelAppear = fpb.FoldPanelBar(parent = self.mainPanelAppear, id = wx.ID_ANY,                               
-                                                      agwStyle = fpb.FPB_SINGLE_FOLD)
-            except: # to be sure
-                self.foldpanelAppear = fpb.FoldPanelBar(parent = self.mainPanelAppear, id = wx.ID_ANY,                               
-                                                      style = fpb.FPB_SINGLE_FOLD)
-            
+            try:  # wxpython >= 2.8.11
+                self.foldpanelAppear = fpb.FoldPanelBar(
+                    parent=self.mainPanelAppear, id=wx.ID_ANY,
+                    agwStyle=fpb.FPB_SINGLE_FOLD)
+            except:  # to be sure
+                self.foldpanelAppear = fpb.FoldPanelBar(
+                    parent=self.mainPanelAppear, id=wx.ID_ANY,
+                    style=fpb.FPB_SINGLE_FOLD)
+
         self.foldpanelAppear.Bind(fpb.EVT_CAPTIONBAR, self.OnPressCaption)
         # light page
-        lightPanel = self.foldpanelAppear.AddFoldPanel(_("Lighting"), collapsed = False)
-        self.foldpanelAppear.AddFoldPanelWindow(lightPanel, 
-            window = self._createLightPage(parent = lightPanel), flags = fpb.FPB_ALIGN_WIDTH)
-    
+        lightPanel = self.foldpanelAppear.AddFoldPanel(
+            _("Lighting"), collapsed=False)
+        self.foldpanelAppear.AddFoldPanelWindow(
+            lightPanel, window=self._createLightPage(
+                parent=lightPanel), flags=fpb.FPB_ALIGN_WIDTH)
+
         # fringe page
-        fringePanel = self.foldpanelAppear.AddFoldPanel(_("Fringe"), collapsed = True)
-        self.foldpanelAppear.AddFoldPanelWindow(fringePanel, 
-            window = self._createFringePage(parent = fringePanel), flags = fpb.FPB_ALIGN_WIDTH)
-        
+        fringePanel = self.foldpanelAppear.AddFoldPanel(
+            _("Fringe"), collapsed=True)
+        self.foldpanelAppear.AddFoldPanelWindow(
+            fringePanel, window=self._createFringePage(
+                parent=fringePanel), flags=fpb.FPB_ALIGN_WIDTH)
+
         self.EnablePage('fringe', False)
-        
+
         # decoration page
-        decorationPanel = self.foldpanelAppear.AddFoldPanel(_("Decorations"), collapsed = True)
-        self.foldpanelAppear.AddFoldPanelWindow(decorationPanel, 
-            window = self._createDecorationPage(parent = decorationPanel), flags = fpb.FPB_ALIGN_WIDTH)
-        
-        
+        decorationPanel = self.foldpanelAppear.AddFoldPanel(
+            _("Decorations"), collapsed=True)
+        self.foldpanelAppear.AddFoldPanelWindow(
+            decorationPanel, window=self._createDecorationPage(
+                parent=decorationPanel), flags=fpb.FPB_ALIGN_WIDTH)
+
         sizer = wx.BoxSizer(wx.VERTICAL)
-        sizer.Add(self.foldpanelAppear, proportion = 1, flag = wx.EXPAND)
+        sizer.Add(self.foldpanelAppear, proportion=1, flag=wx.EXPAND)
         self.mainPanelAppear.SetSizer(sizer)
         self.mainPanelAppear.Layout()
         self.mainPanelAppear.Fit()
         return self.mainPanelAppear
-    
+
     def _createAnalysisPage(self):
         """Create data analysis (cutting planes, ...) page"""
-        self.mainPanelAnalysis = ScrolledPanel(parent = self)
-        self.mainPanelAnalysis.SetupScrolling(scroll_x = False)
-        self.foldpanelAnalysis = fpb.FoldPanelBar(parent = self.mainPanelAnalysis, id = wx.ID_ANY,
-                                                  style = fpb.FPB_SINGLE_FOLD)
+        self.mainPanelAnalysis = ScrolledPanel(parent=self)
+        self.mainPanelAnalysis.SetupScrolling(scroll_x=False)
+        self.foldpanelAnalysis = fpb.FoldPanelBar(
+            parent=self.mainPanelAnalysis, id=wx.ID_ANY,
+            style=fpb.FPB_SINGLE_FOLD)
         self.foldpanelAnalysis.Bind(fpb.EVT_CAPTIONBAR, self.OnPressCaption)
         # cutting planes page
-        cplanePanel = self.foldpanelAnalysis.AddFoldPanel(_("Cutting planes"), collapsed = False)
-        self.foldpanelAnalysis.AddFoldPanelWindow(cplanePanel, 
-            window = self._createCPlanePage(parent = cplanePanel), flags = fpb.FPB_ALIGN_WIDTH)
-        
+        cplanePanel = self.foldpanelAnalysis.AddFoldPanel(
+            _("Cutting planes"), collapsed=False)
+        self.foldpanelAnalysis.AddFoldPanelWindow(
+            cplanePanel, window=self._createCPlanePage(
+                parent=cplanePanel), flags=fpb.FPB_ALIGN_WIDTH)
+
         sizer = wx.BoxSizer(wx.VERTICAL)
-        sizer.Add(self.foldpanelAnalysis, proportion = 1, flag = wx.EXPAND)
+        sizer.Add(self.foldpanelAnalysis, proportion=1, flag=wx.EXPAND)
         self.mainPanelAnalysis.SetSizer(sizer)
         self.mainPanelAnalysis.Layout()
         self.mainPanelAnalysis.Fit()
         return self.mainPanelAnalysis
-        
+
     def _createSurfacePage(self, parent):
         """Create view settings page"""
-        panel = wx.Panel(parent = parent, id = wx.ID_ANY)
-        self.page['surface'] = { 'id' : 0,
-                                 'notebook' : self.foldpanelData.GetId() }
+        panel = wx.Panel(parent=parent, id=wx.ID_ANY)
+        self.page['surface'] = {'id': 0,
+                                'notebook': self.foldpanelData.GetId()}
         pageSizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         self.win['surface'] = {}
-        
+
         # selection
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Raster map")))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Raster map")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        rmaps = Select(parent = panel, type = 'raster',
-                       onPopup = self.GselectOnPopup)
+        rmaps = Select(parent=panel, type='raster',
+                       onPopup=self.GselectOnPopup)
         rmaps.GetChildren()[0].Bind(wx.EVT_TEXT, self.OnSetRaster)
         self.win['surface']['map'] = rmaps.GetId()
-        desc = wx.StaticText(parent = panel, id = wx.ID_ANY)
+        desc = wx.StaticText(parent=panel, id=wx.ID_ANY)
         self.win['surface']['desc'] = desc.GetId()
-        boxSizer.Add(item = rmaps, proportion = 0,
-                     flag = wx.ALL,
-                     border = 3)
-        boxSizer.Add(item = desc, proportion = 0,
-                     flag = wx.ALL,
-                     border = 3)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 3)
-        
+        boxSizer.Add(item=rmaps, proportion=0,
+                     flag=wx.ALL,
+                     border=3)
+        boxSizer.Add(item=desc, proportion=0,
+                     flag=wx.ALL,
+                     border=3)
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                      border=3)
+
         #
         # draw
         #
         self.win['surface']['draw'] = {}
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Draw")))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Draw")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
-        
+        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)
+
         # mode
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Mode:")),
-                      pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        mode = wx.Choice (parent = panel, id = wx.ID_ANY, size = (-1, -1),
-                          choices = [_("coarse"),
-                                     _("fine"),
-                                     _("both")])
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Mode:")),
+                      pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+        mode = wx.Choice(parent=panel, id=wx.ID_ANY, size=(-1, -1),
+                         choices=[_("coarse"),
+                                  _("fine"),
+                                  _("both")])
         mode.SetName("selection")
         mode.Bind(wx.EVT_CHOICE, self.OnSurfaceMode)
         self.win['surface']['draw']['mode'] = mode.GetId()
-        gridSizer.Add(item = mode, flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND,
-                      pos = (0, 1),span = (1, 2))
-        
+        gridSizer.Add(item=mode, flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+                      pos=(0, 1), span=(1, 2))
+
         # shading
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Shading:")),
-                      pos = (0, 3), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT)
-        shade = wx.Choice (parent = panel, id = wx.ID_ANY, size = (-1, -1),
-                           choices = [_("flat"),
-                                      _("gouraud")])
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel, id=wx.ID_ANY, label=_("Shading:")), pos=(
+                0, 3), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
+        shade = wx.Choice(parent=panel, id=wx.ID_ANY, size=(-1, -1),
+                          choices=[_("flat"),
+                                   _("gouraud")])
         shade.SetName("selection")
         self.win['surface']['draw']['shading'] = shade.GetId()
         shade.Bind(wx.EVT_CHOICE, self.OnSurfaceMode)
-        gridSizer.Add(item = shade, flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (0, 4))
-        
+        gridSizer.Add(item=shade, flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(0, 4))
+
         # set to all
-        all = wx.Button(panel, id = wx.ID_ANY, label = _("Set to all"))
+        all = wx.Button(panel, id=wx.ID_ANY, label=_("Set to all"))
         all.SetToolTipString(_("Use draw settings for all loaded surfaces"))
         all.Bind(wx.EVT_BUTTON, self.OnSurfaceModeAll)
-        gridSizer.Add(item = all, flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
-                      pos = (3, 4))
+        gridSizer.Add(
+            item=all,
+            flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+            pos=(
+                3,
+                4))
         self.win['surface']['all'] = all.GetId()
-        
+
         # resolution coarse
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Coarse mode:")),
-                      pos = (2, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                        label = _("resolution:")),
-                     pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL)
-        resC = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = 6,
-                           min = 1,
-                           max = 100)
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Coarse mode:")),
+                      pos=(2, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("resolution:")),
+                      pos=(2, 1), flag=wx.ALIGN_CENTER_VERTICAL)
+        resC = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                           initial=6,
+                           min=1,
+                           max=100)
         resC.SetName("value")
         self.win['surface']['draw']['res-coarse'] = resC.GetId()
         resC.Bind(wx.EVT_SPINCTRL, self.OnSurfaceResolution)
-        gridSizer.Add(item = resC, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT)
-        
+        gridSizer.Add(
+            item=resC, pos=(2, 2),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
+
         # Coarse style
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("style:")),
-                      pos = (3, 1), flag = wx.ALIGN_CENTER_VERTICAL)
-        style = wx.Choice (parent = panel, id = wx.ID_ANY, size = (100, -1),
-                          choices = [_("wire"),
-                                     _("surface")])
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("style:")),
+                      pos=(3, 1), flag=wx.ALIGN_CENTER_VERTICAL)
+        style = wx.Choice(parent=panel, id=wx.ID_ANY, size=(100, -1),
+                          choices=[_("wire"),
+                                   _("surface")])
         style.SetName("selection")
         self.win['surface']['draw']['style'] = style.GetId()
         style.Bind(wx.EVT_CHOICE, self.OnSurfaceMode)
-        gridSizer.Add(item = style, flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (3, 2))
-        
+        gridSizer.Add(item=style, flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(3, 2))
+
         # color
-        color = csel.ColourSelect(panel, id = wx.ID_ANY,
-                                  size = globalvar.DIALOG_COLOR_SIZE)
+        color = csel.ColourSelect(panel, id=wx.ID_ANY,
+                                  size=globalvar.DIALOG_COLOR_SIZE)
         color.SetName("colour")
         color.Bind(csel.EVT_COLOURSELECT, self.OnSurfaceWireColor)
         color.SetToolTipString(_("Change wire color"))
         self.win['surface']['draw']['wire-color'] = color.GetId()
-        gridSizer.Add(item = color, flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT,
-                      pos = (3, 3))
-        
+        gridSizer.Add(
+            item=color,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT,
+            pos=(
+                3,
+                3))
+
         # resolution fine
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Fine mode:")),
-                      pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                        label = _("resolution:")),
-                     pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL)
-        resF = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = 3,
-                           min = 1,
-                           max = 100)
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Fine mode:")),
+                      pos=(1, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("resolution:")),
+                      pos=(1, 1), flag=wx.ALIGN_CENTER_VERTICAL)
+        resF = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                           initial=3,
+                           min=1,
+                           max=100)
         resF.SetName("value")
         self.win['surface']['draw']['res-fine'] = resF.GetId()
         resF.Bind(wx.EVT_SPINCTRL, self.OnSurfaceResolution)
-        gridSizer.Add(item = resF, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT)
+        gridSizer.Add(
+            item=resF, pos=(1, 2),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
         gridSizer.AddGrowableCol(3)
-        
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                  flag = wx.ALL | wx.EXPAND, border = 3)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 3)
-        
+
+        boxSizer.Add(item=gridSizer, proportion=1,
+                     flag=wx.ALL | wx.EXPAND, border=3)
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                      border=3)
+
         #
         # surface attributes
         #
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Surface attributes")))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Surface attributes")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
-        
-        # type 
+        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)
+
+        # type
         self.win['surface']['attr'] = {}
         row = 0
         for code, attrb in (('color', _("Color")),
-                           ('mask', _("Mask")),
-                           ('transp', _("Transparency")),
-                           ('shine', _("Shininess"))):
-            self.win['surface'][code] = {} 
-            gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                             label = attrb + ':'),
-                          pos = (row, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-            use = wx.Choice (parent = panel, id = wx.ID_ANY, size = (100, -1),
-                             choices = [_("map")])
-            
+                            ('mask', _("Mask")),
+                            ('transp', _("Transparency")),
+                            ('shine', _("Shininess"))):
+            self.win['surface'][code] = {}
+            gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                             label=attrb + ':'),
+                          pos=(row, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+            use = wx.Choice(parent=panel, id=wx.ID_ANY, size=(100, -1),
+                            choices=[_("map")])
+
             if code not in ('color', 'shine'):
-                use.Insert(item = _("unset"), pos = 0)
+                use.Insert(item=_("unset"), pos=0)
                 self.win['surface'][code]['required'] = False
             else:
                 self.win['surface'][code]['required'] = True
             if code != 'mask':
-                use.Append(item = _('constant'))
+                use.Append(item=_('constant'))
             self.win['surface'][code]['use'] = use.GetId()
             use.Bind(wx.EVT_CHOICE, self.OnMapObjUse)
-            gridSizer.Add(item = use, flag = wx.ALIGN_CENTER_VERTICAL,
-                          pos = (row, 1))
-            
-            map = Select(parent = panel, id = wx.ID_ANY,
+            gridSizer.Add(item=use, flag=wx.ALIGN_CENTER_VERTICAL,
+                          pos=(row, 1))
+
+            map = Select(parent=panel, id=wx.ID_ANY,
                          # size = globalvar.DIALOG_GSELECT_SIZE,
-                         size = (-1, -1),
-                         type = "raster")
+                         size=(-1, -1),
+                         type="raster")
             if globalvar.CheckWxVersion([3]):
                 self.win['surface'][code]['map'] = map.GetId()
             else:
                 self.win['surface'][code]['map'] = map.GetTextCtrl().GetId()
             map.Bind(wx.EVT_TEXT, self.OnSurfaceMap)
-            gridSizer.Add(item = map, flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND,
-                          pos = (row, 2))
-            
+            gridSizer.Add(item=map, flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+                          pos=(row, 2))
+
             if code == 'color':
-                color = UserSettings.Get(group = 'nviz', key = 'surface', subkey = ['color', 'value'])
-                value = csel.ColourSelect(panel, id = wx.ID_ANY,
-                                          colour = color,
-                                          size = globalvar.DIALOG_COLOR_SIZE)
+                color = UserSettings.Get(
+                    group='nviz', key='surface', subkey=[
+                        'color', 'value'])
+                value = csel.ColourSelect(panel, id=wx.ID_ANY,
+                                          colour=color,
+                                          size=globalvar.DIALOG_COLOR_SIZE)
                 value.Bind(csel.EVT_COLOURSELECT, self.OnSurfaceMap)
             elif code == 'mask':
                 value = None
             else:
-                value = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                                    initial = 0)
-                value.SetRange(minVal = 0, maxVal = 100)
+                value = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                                    initial=0)
+                value.SetRange(minVal=0, maxVal=100)
                 value.Bind(wx.EVT_TEXT, self.OnSurfaceMap)
-            
+
             if value:
                 self.win['surface'][code]['const'] = value.GetId()
                 value.Enable(False)
-                gridSizer.Add(item = value, flag = wx.ALIGN_CENTER_VERTICAL,
-                              pos = (row, 3))
+                gridSizer.Add(item=value, flag=wx.ALIGN_CENTER_VERTICAL,
+                              pos=(row, 3))
             else:
                 self.win['surface'][code]['const'] = None
-            
-            self.SetMapObjUseMap(nvizType = 'surface',
-                                 attrb = code) # -> enable map / disable constant
-                
+
+            # -> enable map / disable constant
+            self.SetMapObjUseMap(nvizType='surface', attrb=code)
+
             row += 1
         gridSizer.AddGrowableCol(2)
-        boxSizer.Add(item = gridSizer, proportion = 0,
-                  flag = wx.ALL | wx.EXPAND, border = 3)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL,
-                      border = 3)
+        boxSizer.Add(item=gridSizer, proportion=0,
+                     flag=wx.ALL | wx.EXPAND, border=3)
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALL,
+                      border=3)
         #
         # position
         #
         self.win['surface']['position'] = {}
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Position")))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Position")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
-        
+        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)
+
         # position
         tooltip = _("Changes the x, y, and z position of the current surface")
-        self._createControl(panel, data = self.win['surface'], name = 'position',
-                            tooltip = tooltip, range = (-10000, 10000), floatSlider = True,
-                            bind = (self.OnSurfacePosition, self.OnSurfacePositionChanged, self.OnSurfacePositionText))
-        
-        axis = wx.Choice (parent = panel, id = wx.ID_ANY, size = (75, -1),
-                          choices = ["X",
-                                     "Y",
-                                     "Z"])
-                                    
-        reset = wx.Button(panel, id = wx.ID_ANY, label = _("Reset"))
+        self._createControl(panel,
+                            data=self.win['surface'],
+                            name='position',
+                            tooltip=tooltip,
+                            range=(-10000,
+                                   10000),
+                            floatSlider=True,
+                            bind=(self.OnSurfacePosition,
+                                  self.OnSurfacePositionChanged,
+                                  self.OnSurfacePositionText))
+
+        axis = wx.Choice(parent=panel, id=wx.ID_ANY, size=(75, -1),
+                         choices=["X",
+                                  "Y",
+                                  "Z"])
+
+        reset = wx.Button(panel, id=wx.ID_ANY, label=_("Reset"))
         reset.SetToolTipString(_("Reset to default position"))
         reset.Bind(wx.EVT_BUTTON, self.OnResetSurfacePosition)
         self.win['surface']['position']['reset'] = reset.GetId()
-        
+
         self.win['surface']['position']['axis'] = axis.GetId()
         axis.SetSelection(2)
         axis.Bind(wx.EVT_CHOICE, self.OnSurfaceAxis)
-        
+
         pslide = self.FindWindowById(self.win['surface']['position']['slider'])
         ptext = self.FindWindowById(self.win['surface']['position']['text'])
         ptext.SetValue('0')
-        
-        gridSizer.Add(item = axis, flag = wx.ALIGN_CENTER_VERTICAL, pos = (0, 0))
-        gridSizer.Add(item = pslide, flag = wx.ALIGN_CENTER_VERTICAL, pos = (0, 1))
-        gridSizer.Add(item = ptext, flag = wx.ALIGN_CENTER_VERTICAL, pos = (0, 2))
-        gridSizer.Add(item = reset, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, pos = (0, 3))
+
+        gridSizer.Add(item=axis, flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 0))
+        gridSizer.Add(item=pslide, flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 1))
+        gridSizer.Add(item=ptext, flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 2))
+        gridSizer.Add(
+            item=reset,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT,
+            pos=(
+                0,
+                3))
         gridSizer.AddGrowableCol(3)
-        
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                  flag = wx.ALL | wx.EXPAND, border = 3)
-        
-        pageSizer.Add(item = boxSizer, proportion = 1,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 3)
+
+        boxSizer.Add(item=gridSizer, proportion=1,
+                     flag=wx.ALL | wx.EXPAND, border=3)
+
+        pageSizer.Add(item=boxSizer, proportion=1,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                      border=3)
         #
         # mask
         #
-##        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-##                            label = " %s " % (_("Mask")))
+# box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
+# label = " %s " % (_("Mask")))
 ##        boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
 ##        gridSizer = wx.GridBagSizer(vgap = 5, hgap = 5)
-##        
-##        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-##                                         label = _("Mask zeros:")),
-##                      pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-##        
-##        elev = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-##                           label = _("by elevation"))
-##        elev.Enable(False) # TODO: not implemented yet
+##
+# gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
+# label = _("Mask zeros:")),
+# pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
+##
+# elev = wx.CheckBox(parent = panel, id = wx.ID_ANY,
+# label = _("by elevation"))
+# elev.Enable(False) # TODO: not implemented yet
 ##        gridSizer.Add(item = elev, pos = (0, 1))
-##        
-##        color = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-##                           label = _("by color"))
-##        color.Enable(False) # TODO: not implemented yet
+##
+# color = wx.CheckBox(parent = panel, id = wx.ID_ANY,
+# label = _("by color"))
+# color.Enable(False) # TODO: not implemented yet
 ##        gridSizer.Add(item = color, pos = (0, 2))
-##        
-##        boxSizer.Add(item = gridSizer, proportion = 1,
-##                  flag = wx.ALL | wx.EXPAND, border = 3)
-##        pageSizer.Add(item = boxSizer, proportion = 0,
+##
+# boxSizer.Add(item = gridSizer, proportion = 1,
+# flag = wx.ALL | wx.EXPAND, border = 3)
+# pageSizer.Add(item = boxSizer, proportion = 0,
 ##                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-##                      border = 3)
-        
-        
+# border = 3)
+
         panel.SetSizer(pageSizer)
 
         panel.Layout()
         panel.Fit()
-        
+
         return panel
+
     def _createCPlanePage(self, parent):
         """Create cutting planes page"""
-        panel = wx.Panel(parent = parent, id = wx.ID_ANY)
-        self.page['cplane'] = { 'id' : 4, 
-                                'notebook' : self.foldpanelData.GetId() }
+        panel = wx.Panel(parent=parent, id=wx.ID_ANY)
+        self.page['cplane'] = {'id': 4,
+                               'notebook': self.foldpanelData.GetId()}
         self.win['cplane'] = {}
-        
+
         pageSizer = wx.BoxSizer(wx.VERTICAL)
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Cutting planes")))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Cutting planes")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
         horSizer = wx.BoxSizer(wx.HORIZONTAL)
-        
+
         # planes
-        horSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Active cutting plane:")),
-                     flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
-        choice = wx.Choice(parent = panel, id = wx.ID_ANY, choices = [])
+        horSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                        label=_("Active cutting plane:")),
+                     flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
+        choice = wx.Choice(parent=panel, id=wx.ID_ANY, choices=[])
         self.win['cplane']['planes'] = choice.GetId()
         choice.Bind(wx.EVT_CHOICE, self.OnCPlaneSelection)
-        horSizer.Add(item = choice, flag = wx.ALL, border = 5)
-        
+        horSizer.Add(item=choice, flag=wx.ALL, border=5)
+
         # shading
-        horSizer.Add(item = wx.Size(-1, -1), proportion = 1)
-        horSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Shading:")),
-                     flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
+        horSizer.Add(item=wx.Size(-1, -1), proportion=1)
+        horSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                        label=_("Shading:")),
+                     flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
         choices = [_("clear"),
                    _("top color"),
                    _("bottom color"),
                    _("blend"),
                    _("shaded")]
-        choice = wx.Choice(parent = panel, id = wx.ID_ANY, choices = choices)
+        choice = wx.Choice(parent=panel, id=wx.ID_ANY, choices=choices)
         self.win['cplane']['shading'] = choice.GetId()
         choice.Bind(wx.EVT_CHOICE, self.OnCPlaneShading)
-        horSizer.Add(item = choice, flag = wx.ALL, border = 5)
-        boxSizer.Add(item = horSizer, flag = wx.EXPAND)
-        
-        gridSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
-        
+        horSizer.Add(item=choice, flag=wx.ALL, border=5)
+        boxSizer.Add(item=horSizer, flag=wx.EXPAND)
+
+        gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
+
         # cutting plane horizontal x position
         self.win['cplane']['position'] = {}
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Horizontal X:")),
-                      pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Horizontal X:")),
+                      pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL)
         tooltip = _("Sets the X coordinate of the current cutting plane")
-        self._createControl(panel, data = self.win['cplane']['position'], name = 'x', size = 250,
-                            range = (-1000, 1000), sliderHor = True, floatSlider = True, tooltip = tooltip,
-                            bind = (self.OnCPlaneChanging, self.OnCPlaneChangeDone, self.OnCPlaneChangeText))
-        self.FindWindowById(self.win['cplane']['position']['x']['slider']).SetValue(0)
-        self.FindWindowById(self.win['cplane']['position']['x']['text']).SetValue(0)
-        gridSizer.Add(item = self.FindWindowById(self.win['cplane']['position']['x']['slider']),
-                      pos = (0, 1),  flag = wx.EXPAND|wx.ALIGN_RIGHT)
-        gridSizer.Add(item = self.FindWindowById(self.win['cplane']['position']['x']['text']),
-                      pos = (0, 2),
-                      flag = wx.ALIGN_CENTER)   
-        
+        self._createControl(panel,
+                            data=self.win['cplane']['position'],
+                            name='x',
+                            size=250,
+                            range=(-1000,
+                                   1000),
+                            sliderHor=True,
+                            floatSlider=True,
+                            tooltip=tooltip,
+                            bind=(self.OnCPlaneChanging,
+                                  self.OnCPlaneChangeDone,
+                                  self.OnCPlaneChangeText))
+        self.FindWindowById(self.win['cplane']['position'][
+                            'x']['slider']).SetValue(0)
+        self.FindWindowById(self.win['cplane']['position'][
+                            'x']['text']).SetValue(0)
+        gridSizer.Add(
+            item=self.FindWindowById(
+                self.win['cplane']['position']['x']['slider']), pos=(
+                0, 1), flag=wx.EXPAND | wx.ALIGN_RIGHT)
+        gridSizer.Add(
+            item=self.FindWindowById(
+                self.win['cplane']['position']['x']['text']), pos=(
+                0, 2), flag=wx.ALIGN_CENTER)
+
         # cutting plane horizontal y position
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Horizontal Y:")),
-                      pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Horizontal Y:")),
+                      pos=(1, 0), flag=wx.ALIGN_CENTER_VERTICAL)
         tooltip = _("Sets the Y coordinate of the current cutting plane")
-        self._createControl(panel, data = self.win['cplane']['position'], name = 'y', size = 250,
-                            range = (-1000, 1000), sliderHor = True, floatSlider = True, tooltip = tooltip,
-                            bind = (self.OnCPlaneChanging, self.OnCPlaneChangeDone, self.OnCPlaneChangeText))
-        self.FindWindowById(self.win['cplane']['position']['y']['slider']).SetValue(0)
-        self.FindWindowById(self.win['cplane']['position']['y']['text']).SetValue(0)
-        gridSizer.Add(item = self.FindWindowById(self.win['cplane']['position']['y']['slider']),
-                      pos = (1, 1),  flag = wx.EXPAND|wx.ALIGN_RIGHT)
-        gridSizer.Add(item = self.FindWindowById(self.win['cplane']['position']['y']['text']),
-                      pos = (1, 2),
-                      flag = wx.ALIGN_CENTER)                         
-        
+        self._createControl(panel,
+                            data=self.win['cplane']['position'],
+                            name='y',
+                            size=250,
+                            range=(-1000,
+                                   1000),
+                            sliderHor=True,
+                            floatSlider=True,
+                            tooltip=tooltip,
+                            bind=(self.OnCPlaneChanging,
+                                  self.OnCPlaneChangeDone,
+                                  self.OnCPlaneChangeText))
+        self.FindWindowById(self.win['cplane']['position'][
+                            'y']['slider']).SetValue(0)
+        self.FindWindowById(self.win['cplane']['position'][
+                            'y']['text']).SetValue(0)
+        gridSizer.Add(
+            item=self.FindWindowById(
+                self.win['cplane']['position']['y']['slider']), pos=(
+                1, 1), flag=wx.EXPAND | wx.ALIGN_RIGHT)
+        gridSizer.Add(
+            item=self.FindWindowById(
+                self.win['cplane']['position']['y']['text']), pos=(
+                1, 2), flag=wx.ALIGN_CENTER)
+
         # cutting plane rotation
         self.win['cplane']['rotation'] = {}
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Rotation:")),
-                      pos = (2, 0), flag = wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Rotation:")),
+                      pos=(2, 0), flag=wx.ALIGN_CENTER_VERTICAL)
         tooltip = _("Rotates the current cutting plane about vertical axis")
-        self._createControl(panel, data = self.win['cplane']['rotation'], name = 'rot', size = 250,
-                            range = (0, 360), sliderHor = True, tooltip = tooltip,
-                            bind = (self.OnCPlaneChanging, self.OnCPlaneChangeDone, self.OnCPlaneChangeText))
-        self.FindWindowById(self.win['cplane']['rotation']['rot']['slider']).SetValue(180)
-        self.FindWindowById(self.win['cplane']['rotation']['rot']['text']).SetValue(180)
-        gridSizer.Add(item = self.FindWindowById(self.win['cplane']['rotation']['rot']['slider']),
-                      pos = (2, 1),  flag = wx.EXPAND|wx.ALIGN_RIGHT)
-        gridSizer.Add(item = self.FindWindowById(self.win['cplane']['rotation']['rot']['text']),
-                      pos = (2, 2),
-                      flag = wx.ALIGN_CENTER)
+        self._createControl(
+            panel, data=self.win['cplane']['rotation'], name='rot', size=250, range=(
+                0, 360), sliderHor=True, tooltip=tooltip, bind=(
+                self.OnCPlaneChanging, self.OnCPlaneChangeDone, self.OnCPlaneChangeText))
+        self.FindWindowById(self.win['cplane']['rotation'][
+                            'rot']['slider']).SetValue(180)
+        self.FindWindowById(self.win['cplane']['rotation'][
+                            'rot']['text']).SetValue(180)
+        gridSizer.Add(
+            item=self.FindWindowById(
+                self.win['cplane']['rotation']['rot']['slider']), pos=(
+                2, 1), flag=wx.EXPAND | wx.ALIGN_RIGHT)
+        gridSizer.Add(
+            item=self.FindWindowById(
+                self.win['cplane']['rotation']['rot']['text']), pos=(
+                2, 2), flag=wx.ALIGN_CENTER)
 
-        # cutting plane tilt        
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Tilt:")),
-                      pos = (3, 0), flag = wx.ALIGN_CENTER_VERTICAL)
+        # cutting plane tilt
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Tilt:")),
+                      pos=(3, 0), flag=wx.ALIGN_CENTER_VERTICAL)
         tooltip = _("Rotates the current cutting plane about horizontal axis")
-        self._createControl(panel, data = self.win['cplane']['rotation'], name = 'tilt', size = 250,
-                            range = (0, 360), sliderHor = True, tooltip = tooltip,
-                            bind = (self.OnCPlaneChanging, self.OnCPlaneChangeDone, self.OnCPlaneChangeText))
-        self.FindWindowById(self.win['cplane']['rotation']['tilt']['slider']).SetValue(0)
-        self.FindWindowById(self.win['cplane']['rotation']['tilt']['text']).SetValue(0)
-        gridSizer.Add(item = self.FindWindowById(self.win['cplane']['rotation']['tilt']['slider']),
-                      pos = (3, 1),  flag = wx.EXPAND|wx.ALIGN_RIGHT)
-        gridSizer.Add(item = self.FindWindowById(self.win['cplane']['rotation']['tilt']['text']),
-                      pos = (3, 2),
-                      flag = wx.ALIGN_CENTER)          
-        
+        self._createControl(
+            panel, data=self.win['cplane']['rotation'], name='tilt', size=250, range=(
+                0, 360), sliderHor=True, tooltip=tooltip, bind=(
+                self.OnCPlaneChanging, self.OnCPlaneChangeDone, self.OnCPlaneChangeText))
+        self.FindWindowById(self.win['cplane']['rotation'][
+                            'tilt']['slider']).SetValue(0)
+        self.FindWindowById(self.win['cplane']['rotation'][
+                            'tilt']['text']).SetValue(0)
+        gridSizer.Add(
+            item=self.FindWindowById(
+                self.win['cplane']['rotation']['tilt']['slider']), pos=(
+                3, 1), flag=wx.EXPAND | wx.ALIGN_RIGHT)
+        gridSizer.Add(
+            item=self.FindWindowById(
+                self.win['cplane']['rotation']['tilt']['text']), pos=(
+                3, 2), flag=wx.ALIGN_CENTER)
+
         # cutting pland height
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Height:")),
-                      pos = (4, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        tooltip = _("Sets the Z coordinate of the current cutting plane (only meaningful when tilt is not 0)")
-        self._createControl(panel, data = self.win['cplane']['position'], name = 'z', size = 250,
-                            range = (-1000, 1000), sliderHor = True, tooltip = tooltip,
-                            bind = (self.OnCPlaneChanging, self.OnCPlaneChangeDone, self.OnCPlaneChangeText))
-        self.FindWindowById(self.win['cplane']['position']['z']['slider']).SetValue(0)
-        self.FindWindowById(self.win['cplane']['position']['z']['text']).SetValue(0)
-        gridSizer.Add(item = self.FindWindowById(self.win['cplane']['position']['z']['slider']),
-                      pos = (4, 1),  flag = wx.EXPAND|wx.ALIGN_RIGHT)
-        gridSizer.Add(item = self.FindWindowById(self.win['cplane']['position']['z']['text']),
-                      pos = (4, 2),
-                      flag = wx.ALIGN_CENTER)
-        
-        boxSizer.Add(gridSizer, proportion = 0, flag = wx.EXPAND|wx.ALL, border = 5)
-                    
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Height:")),
+                      pos=(4, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+        tooltip = _(
+            "Sets the Z coordinate of the current cutting plane (only meaningful when tilt is not 0)")
+        self._createControl(panel,
+                            data=self.win['cplane']['position'],
+                            name='z',
+                            size=250,
+                            range=(-1000,
+                                   1000),
+                            sliderHor=True,
+                            tooltip=tooltip,
+                            bind=(self.OnCPlaneChanging,
+                                  self.OnCPlaneChangeDone,
+                                  self.OnCPlaneChangeText))
+        self.FindWindowById(self.win['cplane']['position'][
+                            'z']['slider']).SetValue(0)
+        self.FindWindowById(self.win['cplane']['position'][
+                            'z']['text']).SetValue(0)
+        gridSizer.Add(
+            item=self.FindWindowById(
+                self.win['cplane']['position']['z']['slider']), pos=(
+                4, 1), flag=wx.EXPAND | wx.ALIGN_RIGHT)
+        gridSizer.Add(
+            item=self.FindWindowById(
+                self.win['cplane']['position']['z']['text']), pos=(
+                4, 2), flag=wx.ALIGN_CENTER)
+
+        boxSizer.Add(
+            gridSizer,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+
         horSizer = wx.BoxSizer(wx.HORIZONTAL)
-        horSizer.Add(item = wx.Size(-1, -1), proportion = 1, flag = wx.ALL, border = 5)  
+        horSizer.Add(item=wx.Size(-1, -1), proportion=1, flag=wx.ALL, border=5)
         # reset
-        reset = wx.Button(parent = panel, id = wx.ID_ANY, label = _("Reset"))
+        reset = wx.Button(parent=panel, id=wx.ID_ANY, label=_("Reset"))
         self.win['cplane']['reset'] = reset.GetId()
         reset.Bind(wx.EVT_BUTTON, self.OnCPlaneReset)
-        horSizer.Add(item = reset, flag = wx.ALL, border = 5)
-        boxSizer.Add(horSizer, proportion = 0, flag = wx.EXPAND)            
-        
-        
-        pageSizer.Add(boxSizer, proportion = 0, flag = wx.EXPAND)
-        
+        horSizer.Add(item=reset, flag=wx.ALL, border=5)
+        boxSizer.Add(horSizer, proportion=0, flag=wx.EXPAND)
+
+        pageSizer.Add(boxSizer, proportion=0, flag=wx.EXPAND)
+
         panel.SetSizer(pageSizer)
-        panel.Fit()    
-        
+        panel.Fit()
+
         return panel
-        
+
     def _createConstantPage(self, parent):
         """Create constant page"""
-        panel = wx.Panel(parent = parent, id = wx.ID_ANY)
-        self.page['constant'] = { 'id' : 1, 
-                                'notebook' : self.foldpanelData.GetId() }
+        panel = wx.Panel(parent=parent, id=wx.ID_ANY)
+        self.page['constant'] = {'id': 1,
+                                 'notebook': self.foldpanelData.GetId()}
         self.win['constant'] = {}
-        
+
         pageSizer = wx.BoxSizer(wx.VERTICAL)
-        
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Constant surface")))
+
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Constant surface")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
         horsizer = wx.BoxSizer(wx.HORIZONTAL)
-        
-        surface = wx.ComboBox(parent = panel, id = wx.ID_ANY, 
-                              style = wx.CB_SIMPLE | wx.CB_READONLY,
-                              choices = [])
+
+        surface = wx.ComboBox(parent=panel, id=wx.ID_ANY,
+                              style=wx.CB_SIMPLE | wx.CB_READONLY,
+                              choices=[])
         self.win['constant']['surface'] = surface.GetId()
         surface.Bind(wx.EVT_COMBOBOX, self.OnConstantSelection)
-        horsizer.Add(surface, proportion = 1, flag = wx.EXPAND|wx.RIGHT, border = 20)
+        horsizer.Add(
+            surface,
+            proportion=1,
+            flag=wx.EXPAND | wx.RIGHT,
+            border=20)
 
-        addNew = wx.Button(panel, id = wx.ID_ANY, label = _("New"))
+        addNew = wx.Button(panel, id=wx.ID_ANY, label=_("New"))
         addNew.Bind(wx.EVT_BUTTON, self.OnNewConstant)
         self.win['constant']['new'] = addNew.GetId()
 
-        delete = wx.Button(panel, id = wx.ID_ANY, label = _("Delete"))
+        delete = wx.Button(panel, id=wx.ID_ANY, label=_("Delete"))
         delete.Bind(wx.EVT_BUTTON, self.OnDeleteConstant)
         self.win['constant']['delete'] = delete.GetId()
-        
-        horsizer.Add(item = addNew, proportion = 0, flag = wx.RIGHT|wx.LEFT, border = 3)
-        horsizer.Add(item = delete, proportion = 0, flag = wx.RIGHT|wx.LEFT, border = 3)
-    
-        boxSizer.Add(item = horsizer, proportion = 0, flag = wx.ALL|wx.EXPAND,
-                      border = 5)
-        
-        gridSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
+
+        horsizer.Add(
+            item=addNew,
+            proportion=0,
+            flag=wx.RIGHT | wx.LEFT,
+            border=3)
+        horsizer.Add(
+            item=delete,
+            proportion=0,
+            flag=wx.RIGHT | wx.LEFT,
+            border=3)
+
+        boxSizer.Add(item=horsizer, proportion=0, flag=wx.ALL | wx.EXPAND,
+                     border=5)
+
+        gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
         # fine resolution
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Fine resolution:")),
-                      pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        resF = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           initial = 3,
-                           min = 1,
-                           max = 100)
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Fine resolution:")),
+                      pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+        resF = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                           initial=3,
+                           min=1,
+                           max=100)
         resF.SetName("value")
         self.win['constant']['resolution'] = resF.GetId()
         resF.Bind(wx.EVT_SPINCTRL, self.OnSetConstantProp)
-        gridSizer.Add(item = resF, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT)
-        # value 
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Value:")), pos = (1, 0),
-                                         flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        value = wx.SpinCtrl(panel, id = wx.ID_ANY,
-                                  min = -1e9, max = 1e9,
-                                  size = (65, -1))
+        gridSizer.Add(
+            item=resF, pos=(0, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
+        # value
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Value:")), pos=(1, 0),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
+
+        value = wx.SpinCtrl(panel, id=wx.ID_ANY,
+                            min=-1e9, max=1e9,
+                            size=(65, -1))
         self.win['constant']['value'] = value.GetId()
         value.Bind(wx.EVT_SPINCTRL, self.OnSetConstantProp)
-        gridSizer.Add(item = value, pos = (1, 1))
-        
-        # transparency 
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Transparency:")), pos = (2, 0),
-                                         flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        transp = wx.SpinCtrl(panel, id = wx.ID_ANY,
-                                  min = 0, max = 100,
-                                  size = (65, -1))
+        gridSizer.Add(item=value, pos=(1, 1))
+
+        # transparency
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Transparency:")), pos=(2, 0),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
+
+        transp = wx.SpinCtrl(panel, id=wx.ID_ANY,
+                             min=0, max=100,
+                             size=(65, -1))
         self.win['constant']['transp'] = transp.GetId()
         transp.Bind(wx.EVT_SPINCTRL, self.OnSetConstantProp)
-        gridSizer.Add(item = transp, pos = (2, 1))
-        
+        gridSizer.Add(item=transp, pos=(2, 1))
+
         # color
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Color:")), pos = (3, 0),
-                                         flag = wx.ALIGN_CENTER_VERTICAL)
-        color = csel.ColourSelect(panel, id = wx.ID_ANY,
-                                  colour = (0,0,0),
-                                  size = globalvar.DIALOG_COLOR_SIZE)
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Color:")), pos=(3, 0),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
+        color = csel.ColourSelect(panel, id=wx.ID_ANY,
+                                  colour=(0, 0, 0),
+                                  size=globalvar.DIALOG_COLOR_SIZE)
         self.win['constant']['color'] = color.GetId()
         color.Bind(csel.EVT_COLOURSELECT, self.OnSetConstantProp)
-        gridSizer.Add(item = color, pos = (3, 1))
-        boxSizer.Add(item = gridSizer, proportion = 0, flag = wx.ALL,
-                      border = 5)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL,
-                      border = 3)
-        
+        gridSizer.Add(item=color, pos=(3, 1))
+        boxSizer.Add(item=gridSizer, proportion=0, flag=wx.ALL,
+                     border=5)
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALL,
+                      border=3)
+
         panel.SetSizer(pageSizer)
-        panel.Fit()    
-        
+        panel.Fit()
+
         return panel
-        
+
     def _createVectorPage(self, parent):
         """Create view settings page"""
-        panel = wx.Panel(parent = parent, id = wx.ID_ANY)
-        self.page['vector'] = { 'id' : 2,
-                                'notebook' : self.foldpanelData.GetId() }
+        panel = wx.Panel(parent=parent, id=wx.ID_ANY)
+        self.page['vector'] = {'id': 2,
+                               'notebook': self.foldpanelData.GetId()}
         pageSizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         self.win['vector'] = {}
-        
+
         # selection
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Vector map")))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Vector map")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        vmaps = Select(parent = panel, type = 'vector',
-                       onPopup = self.GselectOnPopup)
+        vmaps = Select(parent=panel, type='vector',
+                       onPopup=self.GselectOnPopup)
         vmaps.GetChildren()[0].Bind(wx.EVT_TEXT, self.OnSetVector)
         self.win['vector']['map'] = vmaps.GetId()
-        desc = wx.StaticText(parent = panel, id = wx.ID_ANY)
+        desc = wx.StaticText(parent=panel, id=wx.ID_ANY)
         self.win['vector']['desc'] = desc.GetId()
-        boxSizer.Add(item = vmaps, proportion = 0,
-                     flag = wx.ALL,
-                     border = 3)
-        boxSizer.Add(item = desc, proportion = 0,
-                     flag = wx.ALL,
-                     border = 3)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 3)
-        
+        boxSizer.Add(item=vmaps, proportion=0,
+                     flag=wx.ALL,
+                     border=3)
+        boxSizer.Add(item=desc, proportion=0,
+                     flag=wx.ALL,
+                     border=3)
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                      border=3)
+
         #
         # vector lines
         #
         self.win['vector']['lines'] = {}
-        
-        showLines = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                label = _("Show vector lines"))
+
+        showLines = wx.CheckBox(parent=panel, id=wx.ID_ANY,
+                                label=_("Show vector lines"))
         showLines.SetValue(True)
-        
+
         self.win['vector']['lines']['show'] = showLines.GetId()
         showLines.Bind(wx.EVT_CHECKBOX, self.OnVectorShow)
-        
-        pageSizer.Add(item = showLines, proportion = 0,
-                      flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
-        
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Vector lines")))
+
+        pageSizer.Add(item=showLines, proportion=0, flag=wx.LEFT |
+                      wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=5)
+
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Vector lines")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 5, hgap = 5)
-        
+        gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
+
         # width
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Line:")),
-                      pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("width:")),
-                      pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL | 
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Line:")),
+                      pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("width:")),
+                      pos=(0, 1), flag=wx.ALIGN_CENTER_VERTICAL |
                       wx.ALIGN_RIGHT)
-        
-        width = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                            initial = 1,
-                            min = 1,
-                            max = 100)
+
+        width = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                            initial=1,
+                            min=1,
+                            max=100)
         width.SetValue(1)
         self.win['vector']['lines']['width'] = width.GetId()
         width.Bind(wx.EVT_SPINCTRL, self.OnVectorLines)
-        gridSizer.Add(item = width, pos = (0, 2),
-                      flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
-        
+        gridSizer.Add(item=width, pos=(0, 2),
+                      flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
+
         # color
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("color:")),
-                      pos = (0, 3), flag = wx.ALIGN_CENTER_VERTICAL |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("color:")),
+                      pos=(0, 3), flag=wx.ALIGN_CENTER_VERTICAL |
                       wx.ALIGN_RIGHT)
-        
-        color = csel.ColourSelect(panel, id = wx.ID_ANY,
-                                  colour = (0,0,0),
-                                  size = globalvar.DIALOG_COLOR_SIZE)
+
+        color = csel.ColourSelect(panel, id=wx.ID_ANY,
+                                  colour=(0, 0, 0),
+                                  size=globalvar.DIALOG_COLOR_SIZE)
         self.win['vector']['lines']['color'] = color.GetId()
         color.Bind(csel.EVT_COLOURSELECT, self.OnVectorLines)
 
-        gridSizer.Add(item = color, pos = (0, 4), flag = wx.ALIGN_CENTER_VERTICAL |
+        gridSizer.Add(item=color, pos=(0, 4), flag=wx.ALIGN_CENTER_VERTICAL |
                       wx.ALIGN_LEFT)
-        
+
         # thematic mapping
         self.win['vector']['lines']['thematic'] = {}
-        checkThematicColor = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                         label = _("use color for thematic mapping"))
-        checkThematicWidth = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                         label = _("use width for thematic mapping"))
-        self.win['vector']['lines']['thematic']['checkcolor'] = checkThematicColor.GetId()
-        self.win['vector']['lines']['thematic']['checkwidth'] = checkThematicWidth.GetId()
+        checkThematicColor = wx.CheckBox(
+            parent=panel, id=wx.ID_ANY,
+            label=_("use color for thematic mapping"))
+        checkThematicWidth = wx.CheckBox(
+            parent=panel, id=wx.ID_ANY,
+            label=_("use width for thematic mapping"))
+        self.win['vector']['lines']['thematic'][
+            'checkcolor'] = checkThematicColor.GetId()
+        self.win['vector']['lines']['thematic'][
+            'checkwidth'] = checkThematicWidth.GetId()
         checkThematicColor.Bind(wx.EVT_CHECKBOX, self.OnCheckThematic)
         checkThematicWidth.Bind(wx.EVT_CHECKBOX, self.OnCheckThematic)
         checkThematicColor.SetValue(False)
         checkThematicWidth.SetValue(False)
-        
+
         vSizer = wx.BoxSizer(wx.VERTICAL)
         hSizer = wx.BoxSizer(wx.HORIZONTAL)
-        hSizer.Add(item = checkThematicColor, flag = wx.ALIGN_CENTER_VERTICAL,
-                    border = 5)
-        setThematic = wx.Button(parent = panel, id = wx.ID_ANY,
-                                         label = _("Set options..."))
-        self.win['vector']['lines']['thematic']['buttoncolor'] = setThematic.GetId()
+        hSizer.Add(item=checkThematicColor, flag=wx.ALIGN_CENTER_VERTICAL,
+                   border=5)
+        setThematic = wx.Button(parent=panel, id=wx.ID_ANY,
+                                label=_("Set options..."))
+        self.win['vector']['lines']['thematic'][
+            'buttoncolor'] = setThematic.GetId()
         setThematic.Bind(wx.EVT_BUTTON, self.OnSetThematic)
-        hSizer.Add(item = wx.Size(-1, -1), proportion = 1)
-        hSizer.Add(item = setThematic, flag = wx.ALIGN_CENTER_VERTICAL|wx.LEFT,
-                    border = 5, proportion = 0)
-        vSizer.Add(hSizer, flag = wx.EXPAND)
-                    
+        hSizer.Add(item=wx.Size(-1, -1), proportion=1)
+        hSizer.Add(item=setThematic, flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
+                   border=5, proportion=0)
+        vSizer.Add(hSizer, flag=wx.EXPAND)
+
         hSizer = wx.BoxSizer(wx.HORIZONTAL)
-        hSizer.Add(item = checkThematicWidth, flag = wx.ALIGN_CENTER_VERTICAL,
-                    border = 5)
-        setThematic = wx.Button(parent = panel, id = wx.ID_ANY,
-                                         label = _("Set options..."))
-        self.win['vector']['lines']['thematic']['buttonwidth'] = setThematic.GetId()
+        hSizer.Add(item=checkThematicWidth, flag=wx.ALIGN_CENTER_VERTICAL,
+                   border=5)
+        setThematic = wx.Button(parent=panel, id=wx.ID_ANY,
+                                label=_("Set options..."))
+        self.win['vector']['lines']['thematic'][
+            'buttonwidth'] = setThematic.GetId()
         setThematic.Bind(wx.EVT_BUTTON, self.OnSetThematic)
-        hSizer.Add(item = wx.Size(-1, -1), proportion = 1)
-        hSizer.Add(item = setThematic, flag = wx.ALIGN_CENTER_VERTICAL|wx.LEFT,
-                    border = 5, proportion = 0)
-        
-        vSizer.Add(hSizer, flag = wx.EXPAND)
-        gridSizer.Add(item = vSizer, flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
-                      pos = (1, 1), span = (1, 5))
-        
+        hSizer.Add(item=wx.Size(-1, -1), proportion=1)
+        hSizer.Add(item=setThematic, flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
+                   border=5, proportion=0)
+
+        vSizer.Add(hSizer, flag=wx.EXPAND)
+        gridSizer.Add(item=vSizer, flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+                      pos=(1, 1), span=(1, 5))
+
         # display
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Display")),
-                      pos = (2, 0), flag = wx.ALIGN_CENTER_VERTICAL |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Display")),
+                      pos=(2, 0), flag=wx.ALIGN_CENTER_VERTICAL |
                       wx.ALIGN_LEFT)
-        
-        display = wx.Choice (parent = panel, id = wx.ID_ANY, size = (-1, -1),
-                             choices = [_("on surface(s):"),
-                                        _("as 3D")])
+
+        display = wx.Choice(parent=panel, id=wx.ID_ANY, size=(-1, -1),
+                            choices=[_("on surface(s):"),
+                                     _("as 3D")])
         self.win['vector']['lines']['3d'] = display.GetId()
         display.Bind(wx.EVT_CHOICE, self.OnVectorLinesMode)
-        
-        gridSizer.Add(item = display, flag = wx.ALIGN_CENTER_VERTICAL | 
-                      wx.ALIGN_LEFT|wx.EXPAND, pos = (2, 1), span = (1,4))
-        
+
+        gridSizer.Add(item=display, flag=wx.ALIGN_CENTER_VERTICAL |
+                      wx.ALIGN_LEFT | wx.EXPAND, pos=(2, 1), span=(1, 4))
+
         # height
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Height above surface:")),
-                      pos = (3, 5), flag = wx.ALIGN_BOTTOM|wx.EXPAND)
-        
-        surface = wx.CheckListBox(parent = panel, id = wx.ID_ANY, size = (-1, 60),
-                                  choices = [], style = wx.LB_NEEDED_SB)
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Height above surface:")),
+                      pos=(3, 5), flag=wx.ALIGN_BOTTOM | wx.EXPAND)
+
+        surface = wx.CheckListBox(parent=panel, id=wx.ID_ANY, size=(-1, 60),
+                                  choices=[], style=wx.LB_NEEDED_SB)
         surface.Bind(wx.EVT_CHECKLISTBOX, self.OnVectorSurface)
-        
+
         self.win['vector']['lines']['surface'] = surface.GetId()
-        gridSizer.Add(item = surface, 
-                      pos = (3, 0), span = (3, 5),
-                      flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)
-        
-        self._createControl(panel, data = self.win['vector']['lines'], name = 'height', size = -1,
-                            range = (0, 500), sliderHor = True,
-                            bind = (self.OnVectorHeight, self.OnVectorHeightFull, self.OnVectorHeightText))
-        self.FindWindowById(self.win['vector']['lines']['height']['slider']).SetValue(0)
-        self.FindWindowById(self.win['vector']['lines']['height']['text']).SetValue(0)
-        gridSizer.Add(item = self.FindWindowById(self.win['vector']['lines']['height']['slider']),
-                      pos = (4, 5),  flag = wx.EXPAND|wx.ALIGN_RIGHT)
-        gridSizer.Add(item = self.FindWindowById(self.win['vector']['lines']['height']['text']),
-                      pos = (5, 5),
-                      flag = wx.ALIGN_CENTER)
+        gridSizer.Add(item=surface,
+                      pos=(3, 0), span=(3, 5),
+                      flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
+
+        self._createControl(
+            panel,
+            data=self.win['vector']['lines'],
+            name='height',
+            size=-1,
+            range=(
+                0,
+                500),
+            sliderHor=True,
+            bind=(
+                self.OnVectorHeight,
+                self.OnVectorHeightFull,
+                self.OnVectorHeightText))
+        self.FindWindowById(self.win['vector']['lines'][
+                            'height']['slider']).SetValue(0)
+        self.FindWindowById(self.win['vector']['lines'][
+                            'height']['text']).SetValue(0)
+        gridSizer.Add(
+            item=self.FindWindowById(
+                self.win['vector']['lines']['height']['slider']), pos=(
+                4, 5), flag=wx.EXPAND | wx.ALIGN_RIGHT)
+        gridSizer.Add(
+            item=self.FindWindowById(
+                self.win['vector']['lines']['height']['text']), pos=(
+                5, 5), flag=wx.ALIGN_CENTER)
         gridSizer.AddGrowableCol(5)
-        
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                     flag = wx.ALL | wx.EXPAND, border = 3)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 3)
-        
+
+        boxSizer.Add(item=gridSizer, proportion=1,
+                     flag=wx.ALL | wx.EXPAND, border=3)
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                      border=3)
+
         #
         # vector points
         #
         self.win['vector']['points'] = {}
-        
-        showPoints = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                 label = _("Show vector points"))
+
+        showPoints = wx.CheckBox(parent=panel, id=wx.ID_ANY,
+                                 label=_("Show vector points"))
         showPoints.SetValue(True)
         self.win['vector']['points']['show'] = showPoints.GetId()
         showPoints.Bind(wx.EVT_CHECKBOX, self.OnVectorShow)
-        
-        pageSizer.Add(item = showPoints, proportion = 0,
-                      flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
-        
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Vector points")))
+
+        pageSizer.Add(item=showPoints, proportion=0, flag=wx.LEFT |
+                      wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=5)
+
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Vector points")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
         vertSizer = wx.BoxSizer(wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 5, hgap = 5)
-        
+        gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
+
         # icon size
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Icon:")),
-                      pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("size:")),
-                      pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Icon:")),
+                      pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("size:")),
+                      pos=(0, 1), flag=wx.ALIGN_CENTER_VERTICAL |
                       wx.ALIGN_RIGHT)
-        
+
         if fs:
-            isize = fs.FloatSpin(parent = panel, id = wx.ID_ANY,
-                                 min_val = 0, max_val = 1e6,
-                                 increment = 1, value = 1, style = fs.FS_RIGHT)
+            isize = fs.FloatSpin(parent=panel, id=wx.ID_ANY,
+                                 min_val=0, max_val=1e6,
+                                 increment=1, value=1, style=fs.FS_RIGHT)
             isize.SetFormat("%f")
             isize.SetDigits(1)
             isize.Bind(fs.EVT_FLOATSPIN, self.OnVectorPoints)
         else:
-            isize = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                                initial = 1,
-                                min = 1,
-                                max = 1e6)
+            isize = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                                initial=1,
+                                min=1,
+                                max=1e6)
             isize.Bind(wx.EVT_SPINCTRL, self.OnVectorPoints)
         isize.SetName('value')
         isize.SetValue(100)
         self.win['vector']['points']['size'] = isize.GetId()
-        gridSizer.Add(item = isize, pos = (0, 2),
-                      flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
-        
+        gridSizer.Add(item=isize, pos=(0, 2),
+                      flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
+
         # icon color
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("color:")),
-                      pos = (0, 3), flag = wx.ALIGN_CENTER_VERTICAL |
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("color:")),
+                      pos=(0, 3), flag=wx.ALIGN_CENTER_VERTICAL |
                       wx.ALIGN_RIGHT)
-        icolor = csel.ColourSelect(panel, id = wx.ID_ANY,
-                                   size = globalvar.DIALOG_COLOR_SIZE)
+        icolor = csel.ColourSelect(panel, id=wx.ID_ANY,
+                                   size=globalvar.DIALOG_COLOR_SIZE)
         icolor.SetName("color")
-        icolor.SetColour((0,0,255))
+        icolor.SetColour((0, 0, 255))
         self.win['vector']['points']['color'] = icolor.GetId()
         icolor.Bind(csel.EVT_COLOURSELECT, self.OnVectorPoints)
-        gridSizer.Add(item = icolor, flag = wx.ALIGN_CENTER_VERTICAL | 
+        gridSizer.Add(item=icolor, flag=wx.ALIGN_CENTER_VERTICAL |
                       wx.ALIGN_LEFT,
-                      pos = (0, 4))
+                      pos=(0, 4))
 
         # icon width - seems to do nothing
-##        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-##                                           label = _("width")),
-##                      pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL |
-##                      wx.ALIGN_RIGHT)
-##        
-##        iwidth = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
+# gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
+# label = _("width")),
+# pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL |
+# wx.ALIGN_RIGHT)
+##
+# iwidth = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
 ##                             initial = 1,
 ##                             min = 1,
-##                             max = 1e6)
-##        iwidth.SetName('value')
-##        iwidth.SetValue(100)
+# max = 1e6)
+# iwidth.SetName('value')
+# iwidth.SetValue(100)
 ##        self.win['vector']['points']['width'] = iwidth.GetId()
 ##        iwidth.Bind(wx.EVT_SPINCTRL, self.OnVectorPoints)
 ##        iwidth.Bind(wx.EVT_TEXT, self.OnVectorPoints)
-##        gridSizer.Add(item = iwidth, pos = (1, 2),
-##                      flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
+# gridSizer.Add(item = iwidth, pos = (1, 2),
+# flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
         # icon symbol
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("symbol:")),
-                      pos = (0, 5), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
-        isym = wx.Choice (parent = panel, id = wx.ID_ANY, size = (100, -1),
-                          choices = UserSettings.Get(group = 'nviz', key = 'vector',
-                                                   subkey=['points', 'marker'], settings_type='internal'))
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel, id=wx.ID_ANY, label=_("symbol:")), pos=(
+                0, 5), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
+        isym = wx.Choice(
+            parent=panel, id=wx.ID_ANY, size=(100, -1),
+            choices=UserSettings.Get(
+                group='nviz', key='vector', subkey=['points', 'marker'],
+                settings_type='internal'))
         isym.SetName("selection")
         self.win['vector']['points']['marker'] = isym.GetId()
         isym.Bind(wx.EVT_CHOICE, self.OnVectorPoints)
-        gridSizer.Add(item = isym, flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT,
-                      pos = (0, 6))
+        gridSizer.Add(item=isym, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT,
+                      pos=(0, 6))
         # thematic mapping
         self.win['vector']['points']['thematic'] = {}
-        checkThematicColor = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                         label = _("use color for thematic mapping"))
-        checkThematicSize = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                         label = _("use size for thematic mapping"))
-        self.win['vector']['points']['thematic']['checkcolor'] = checkThematicColor.GetId()
-        self.win['vector']['points']['thematic']['checksize'] = checkThematicSize.GetId()
+        checkThematicColor = wx.CheckBox(
+            parent=panel, id=wx.ID_ANY,
+            label=_("use color for thematic mapping"))
+        checkThematicSize = wx.CheckBox(
+            parent=panel, id=wx.ID_ANY,
+            label=_("use size for thematic mapping"))
+        self.win['vector']['points']['thematic'][
+            'checkcolor'] = checkThematicColor.GetId()
+        self.win['vector']['points']['thematic'][
+            'checksize'] = checkThematicSize.GetId()
         checkThematicColor.Bind(wx.EVT_CHECKBOX, self.OnCheckThematic)
         checkThematicSize.Bind(wx.EVT_CHECKBOX, self.OnCheckThematic)
         checkThematicColor.SetValue(False)
         checkThematicSize.SetValue(False)
-        
-        gridSizer.Add(item = checkThematicColor, flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT,
-                      pos = (1, 1), span = (1, 5))
-        setThematic = wx.Button(parent = panel, id = wx.ID_ANY,
-                                         label = _("Set options..."))
-        self.win['vector']['points']['thematic']['buttoncolor'] = setThematic.GetId()
+
+        gridSizer.Add(
+            item=checkThematicColor,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT,
+            pos=(
+                1,
+                1),
+            span=(
+                1,
+                5))
+        setThematic = wx.Button(parent=panel, id=wx.ID_ANY,
+                                label=_("Set options..."))
+        self.win['vector']['points']['thematic'][
+            'buttoncolor'] = setThematic.GetId()
         setThematic.Bind(wx.EVT_BUTTON, self.OnSetThematic)
-        gridSizer.Add(item = setThematic, flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (1, 6))
-                    
-        gridSizer.Add(item = checkThematicSize, flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT,
-                      pos = (2, 1), span = (1, 5))
-        setThematic = wx.Button(parent = panel, id = wx.ID_ANY,
-                                         label = _("Set options..."))
-        self.win['vector']['points']['thematic']['buttonsize'] = setThematic.GetId()
+        gridSizer.Add(item=setThematic, flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(1, 6))
+
+        gridSizer.Add(
+            item=checkThematicSize,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT,
+            pos=(
+                2,
+                1),
+            span=(
+                1,
+                5))
+        setThematic = wx.Button(parent=panel, id=wx.ID_ANY,
+                                label=_("Set options..."))
+        self.win['vector']['points']['thematic'][
+            'buttonsize'] = setThematic.GetId()
         setThematic.Bind(wx.EVT_BUTTON, self.OnSetThematic)
-        gridSizer.Add(item = setThematic, flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (2, 6))                   
+        gridSizer.Add(item=setThematic, flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(2, 6))
         gridSizer.AddGrowableCol(0)
         gridSizer.AddGrowableCol(2)
         gridSizer.AddGrowableCol(4)
         gridSizer.AddGrowableCol(6)
-        vertSizer.Add(gridSizer, proportion = 0, flag = wx.EXPAND, border = 0)
+        vertSizer.Add(gridSizer, proportion=0, flag=wx.EXPAND, border=0)
         # high
-        gridSizer = wx.GridBagSizer(vgap = 5, hgap = 5)
-        gridSizer.Add(item=wx.StaticText(parent=panel, label=_("Display")),
-                      pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
+        gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel, label=_("Display")), pos=(
+                0, 0), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
         display = wx.Choice(parent=panel)
         self.win['vector']['points']['3d'] = display.GetId()
         display.Bind(wx.EVT_CHOICE, self.OnVectorPointsMode)
         gridSizer.Add(item=display,
                       pos=(0, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Height above surface:")),
-                      pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        surface = wx.CheckListBox(parent = panel, id = wx.ID_ANY, size = (-1, 60),
-                                  choices = [], style = wx.LB_NEEDED_SB)
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Height above surface:")),
+                      pos=(1, 2), flag=wx.ALIGN_CENTER_VERTICAL)
+
+        surface = wx.CheckListBox(parent=panel, id=wx.ID_ANY, size=(-1, 60),
+                                  choices=[], style=wx.LB_NEEDED_SB)
         surface.Bind(wx.EVT_CHECKLISTBOX, self.OnVectorSurface)
         self.win['vector']['points']['surface'] = surface.GetId()
-        gridSizer.Add(item = surface, 
-                      pos = (1, 0), span = (3, 2),
-                      flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)
-        
-        self._createControl(panel, data = self.win['vector']['points'], name = 'height', size = -1,
-                            range = (0, 500),
-                            bind = (self.OnVectorHeight, self.OnVectorHeightFull, self.OnVectorHeightText))
-        
-        self.FindWindowById(self.win['vector']['points']['height']['slider']).SetValue(0)
-        self.FindWindowById(self.win['vector']['points']['height']['text']).SetValue(0)
-        
-        gridSizer.Add(item = self.FindWindowById(self.win['vector']['points']['height']['slider']),
-                      pos = (2, 2),flag = wx.EXPAND|wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = self.FindWindowById(self.win['vector']['points']['height']['text']),
-                      pos = (3, 2),
-                      flag = wx.ALIGN_CENTER)
+        gridSizer.Add(item=surface,
+                      pos=(1, 0), span=(3, 2),
+                      flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
+
+        self._createControl(
+            panel,
+            data=self.win['vector']['points'],
+            name='height',
+            size=-1,
+            range=(
+                0,
+                500),
+            bind=(
+                self.OnVectorHeight,
+                self.OnVectorHeightFull,
+                self.OnVectorHeightText))
+
+        self.FindWindowById(self.win['vector']['points'][
+                            'height']['slider']).SetValue(0)
+        self.FindWindowById(self.win['vector']['points'][
+                            'height']['text']).SetValue(0)
+
+        gridSizer.Add(
+            item=self.FindWindowById(
+                self.win['vector']['points']['height']['slider']), pos=(
+                2, 2), flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=self.FindWindowById(
+                self.win['vector']['points']['height']['text']), pos=(
+                3, 2), flag=wx.ALIGN_CENTER)
         gridSizer.AddGrowableCol(2)
-                    
-        vertSizer.Add(gridSizer, proportion = 0, flag = wx.EXPAND, border = 0)
-        boxSizer.Add(item = vertSizer, proportion = 1,
-                     flag = wx.ALL | wx.EXPAND, border = 3)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 3)
-        
+
+        vertSizer.Add(gridSizer, proportion=0, flag=wx.EXPAND, border=0)
+        boxSizer.Add(item=vertSizer, proportion=1,
+                     flag=wx.ALL | wx.EXPAND, border=3)
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                      border=3)
+
         panel.SetSizer(pageSizer)
         panel.Fit()
 
         return panel
 
-    def GselectOnPopup(self, ltype, exclude = False):
+    def GselectOnPopup(self, ltype, exclude=False):
         """Update gselect.Select() items"""
         maps = list()
-        for layer in self.mapWindow.Map.GetListOfLayers(ltype = ltype, active = True):
+        for layer in self.mapWindow.Map.GetListOfLayers(
+                ltype=ltype, active=True):
             maps.append(layer.GetName())
         return maps, exclude
-    
+
     def _createVolumePage(self, parent):
         """Create view settings page"""
-        panel = wx.Panel(parent = parent, id = wx.ID_ANY)
-        self.page['volume'] = { 'id' : 3,
-                                'notebook' : self.foldpanelData.GetId() }
+        panel = wx.Panel(parent=parent, id=wx.ID_ANY)
+        self.page['volume'] = {'id': 3,
+                               'notebook': self.foldpanelData.GetId()}
         pageSizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         self.win['volume'] = {}
-        
+
         # selection
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("3D raster map")))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("3D raster map")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        rmaps = Select(parent = panel, type = 'raster_3d',
-                       onPopup = self.GselectOnPopup)
+        rmaps = Select(parent=panel, type='raster_3d',
+                       onPopup=self.GselectOnPopup)
         rmaps.GetChildren()[0].Bind(wx.EVT_TEXT, self.OnSetRaster3D)
         self.win['volume']['map'] = rmaps.GetId()
-        desc = wx.StaticText(parent = panel, id = wx.ID_ANY)
+        desc = wx.StaticText(parent=panel, id=wx.ID_ANY)
         self.win['volume']['desc'] = desc.GetId()
-        boxSizer.Add(item = rmaps, proportion = 0,
-                     flag = wx.ALL,
-                     border = 3)
-        boxSizer.Add(item = desc, proportion = 0,
-                     flag = wx.ALL,
-                     border = 3)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 3)
-                
+        boxSizer.Add(item=rmaps, proportion=0,
+                     flag=wx.ALL,
+                     border=3)
+        boxSizer.Add(item=desc, proportion=0,
+                     flag=wx.ALL,
+                     border=3)
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                      border=3)
+
         #
         # draw
         #
         self.win['volume']['draw'] = {}
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Draw")))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Draw")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 5, hgap = 5)
-##        gridSizer.AddGrowableCol(4)
-        
+        gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
+# gridSizer.AddGrowableCol(4)
+
         # mode
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Mode:")),
-                      pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        mode = wx.Choice (parent = panel, id = wx.ID_ANY, size = (-1, -1),
-                          choices = [_("isosurfaces"),
-                                     _("slices")])
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Mode:")),
+                      pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+        mode = wx.Choice(parent=panel, id=wx.ID_ANY, size=(-1, -1),
+                         choices=[_("isosurfaces"),
+                                  _("slices")])
         mode.SetSelection(0)
         mode.SetName("selection")
         mode.Bind(wx.EVT_CHOICE, self.OnVolumeMode)
         self.win['volume']['draw']['mode'] = mode.GetId()
-        gridSizer.Add(item = mode, flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (0, 1))
-        
+        gridSizer.Add(item=mode, flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(0, 1))
+
         # shading
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Shading:")),
-                      pos = (0, 2), flag = wx.ALIGN_CENTER_VERTICAL)
-        shade = wx.Choice (parent = panel, id = wx.ID_ANY, size = (100, -1),
-                           choices = [_("flat"),
-                                      _("gouraud")])
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Shading:")),
+                      pos=(0, 2), flag=wx.ALIGN_CENTER_VERTICAL)
+        shade = wx.Choice(parent=panel, id=wx.ID_ANY, size=(100, -1),
+                          choices=[_("flat"),
+                                   _("gouraud")])
         shade.SetName("selection")
         self.win['volume']['draw']['shading'] = shade.GetId()
         shade.Bind(wx.EVT_CHOICE, self.OnVolumeDrawMode)
-        gridSizer.Add(item = shade, flag = wx.ALIGN_CENTER_VERTICAL,
-                      pos = (0, 3))
-        
+        gridSizer.Add(item=shade, flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(0, 3))
+
         # resolution (mode)
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                         label = _("Resolution:")),
-                      pos = (0, 4), flag = wx.ALIGN_CENTER_VERTICAL)
-        resol = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                            initial = 1,
-                            min = 1,
-                            max = 100)
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Resolution:")),
+                      pos=(0, 4), flag=wx.ALIGN_CENTER_VERTICAL)
+        resol = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                            initial=1,
+                            min=1,
+                            max=100)
         resol.SetName("value")
         self.win['volume']['draw']['resolution'] = resol.GetId()
         resol.Bind(wx.EVT_SPINCTRL, self.OnVolumeResolution)
         resol.Bind(wx.EVT_TEXT, self.OnVolumeResolution)
-        gridSizer.Add(item = resol, pos = (0, 5))
-        
+        gridSizer.Add(item=resol, pos=(0, 5))
+
         # draw wire box
-        box = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                            label = _("Draw wire box"))
+        box = wx.CheckBox(parent=panel, id=wx.ID_ANY,
+                          label=_("Draw wire box"))
         box.SetName("value")
         self.win['volume']['draw']['box'] = box.GetId()
         box.Bind(wx.EVT_CHECKBOX, self.OnVolumeDrawBox)
-        gridSizer.Add(item = box, pos = (1, 0), span = (1, 6))
+        gridSizer.Add(item=box, pos=(1, 0), span=(1, 6))
 
-        boxSizer.Add(item = gridSizer, proportion = 0,
-                     flag = wx.ALL | wx.EXPAND, border = 3)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL,
-                      border = 3)
-        
+        boxSizer.Add(item=gridSizer, proportion=0,
+                     flag=wx.ALL | wx.EXPAND, border=3)
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALL,
+                      border=3)
+
         #
         # manage isosurfaces
         #
-        box = wx.StaticBox(parent = panel, id = wx.ID_ANY, 
-                           label = " %s " % (_("List of isosurfaces")))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("List of isosurfaces")))
         box.SetName('listStaticBox')
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
-        
+        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)
+
         # list
-        isolevel = wx.CheckListBox(parent = panel, id = wx.ID_ANY,
-                                   size = (300, 150))
+        isolevel = wx.CheckListBox(parent=panel, id=wx.ID_ANY,
+                                   size=(300, 150))
         self.Bind(wx.EVT_CHECKLISTBOX, self.OnVolumeCheck, isolevel)
         self.Bind(wx.EVT_LISTBOX, self.OnVolumeSelect, isolevel)
-        
+
         self.win['volume']['isosurfs'] = isolevel.GetId()
         self.win['volume']['slices'] = isolevel.GetId()
-        gridSizer.Add(item = isolevel, pos = (0, 0), span = (4, 1))
-        
+        gridSizer.Add(item=isolevel, pos=(0, 0), span=(4, 1))
+
         # buttons (add, delete, move up, move down)
-        btnAdd = wx.Button(parent = panel, id = wx.ID_ADD)
+        btnAdd = wx.Button(parent=panel, id=wx.ID_ADD)
         self.win['volume']['btnAdd'] = btnAdd.GetId()
         btnAdd.Bind(wx.EVT_BUTTON, self.OnVolumeAdd)
-        gridSizer.Add(item = btnAdd,
-                      pos = (0, 1))
-        btnDelete = wx.Button(parent = panel, id = wx.ID_DELETE)
+        gridSizer.Add(item=btnAdd,
+                      pos=(0, 1))
+        btnDelete = wx.Button(parent=panel, id=wx.ID_DELETE)
         self.win['volume']['btnDelete'] = btnDelete.GetId()
         btnDelete.Bind(wx.EVT_BUTTON, self.OnVolumeDelete)
         btnDelete.Enable(False)
-        gridSizer.Add(item = btnDelete,
-                      pos = (1, 1))
-        btnMoveUp = wx.Button(parent = panel, id = wx.ID_UP)
+        gridSizer.Add(item=btnDelete,
+                      pos=(1, 1))
+        btnMoveUp = wx.Button(parent=panel, id=wx.ID_UP)
         self.win['volume']['btnMoveUp'] = btnMoveUp.GetId()
         btnMoveUp.Bind(wx.EVT_BUTTON, self.OnVolumeMoveUp)
         btnMoveUp.Enable(False)
-        gridSizer.Add(item = btnMoveUp,
-                      pos = (2, 1))
-        btnMoveDown = wx.Button(parent = panel, id = wx.ID_DOWN)
+        gridSizer.Add(item=btnMoveUp,
+                      pos=(2, 1))
+        btnMoveDown = wx.Button(parent=panel, id=wx.ID_DOWN)
         self.win['volume']['btnMoveDown'] = btnMoveDown.GetId()
         btnMoveDown.Bind(wx.EVT_BUTTON, self.OnVolumeMoveDown)
         btnMoveDown.Enable(False)
-        gridSizer.Add(item = btnMoveDown,
-                      pos = (3, 1))
-        
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                     flag = wx.ALL | wx.EXPAND, border = 3)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 3)
-        # isosurface/slice 
+        gridSizer.Add(item=btnMoveDown,
+                      pos=(3, 1))
+
+        boxSizer.Add(item=gridSizer, proportion=1,
+                     flag=wx.ALL | wx.EXPAND, border=3)
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                      border=3)
+        # isosurface/slice
         sizer = wx.BoxSizer()
         self.isoPanel = self._createIsosurfacePanel(panel)
         self.slicePanel = self._createSlicePanel(panel)
-        sizer.Add(self.isoPanel, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 0)
-        sizer.Add(self.slicePanel, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 0)
+        sizer.Add(
+            self.isoPanel,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=0)
+        sizer.Add(
+            self.slicePanel,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=0)
         sizer.Hide(self.slicePanel)
-        pageSizer.Add(item = sizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL,
-                      border = 3)
+        pageSizer.Add(item=sizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALL,
+                      border=3)
         #
         # position
         #
         self.win['volume']['position'] = {}
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Position")))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Position")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
-        
+        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)
+
         # position
-        self._createControl(panel, data = self.win['volume'], name = 'position',
-                            range = (-10000, 10000), floatSlider = True,
-                            bind = (self.OnVolumePosition, self.OnVolumePositionChanged, self.OnVolumePositionText))
-        
-        axis = wx.Choice (parent = panel, id = wx.ID_ANY, size = (75, -1),
-                          choices = ["X",
-                                     "Y",
-                                     "Z"])
-                                    
-        reset = wx.Button(panel, id = wx.ID_ANY, label = _("Reset"))
+        self._createControl(panel,
+                            data=self.win['volume'],
+                            name='position',
+                            range=(-10000,
+                                   10000),
+                            floatSlider=True,
+                            bind=(self.OnVolumePosition,
+                                  self.OnVolumePositionChanged,
+                                  self.OnVolumePositionText))
+
+        axis = wx.Choice(parent=panel, id=wx.ID_ANY, size=(75, -1),
+                         choices=["X",
+                                  "Y",
+                                  "Z"])
+
+        reset = wx.Button(panel, id=wx.ID_ANY, label=_("Reset"))
         reset.SetToolTipString(_("Reset to default position"))
         reset.Bind(wx.EVT_BUTTON, self.OnResetVolumePosition)
         self.win['volume']['position']['reset'] = reset.GetId()
-        
+
         self.win['volume']['position']['axis'] = axis.GetId()
-        axis.SetSelection(2) # Z
+        axis.SetSelection(2)  # Z
         axis.Bind(wx.EVT_CHOICE, self.OnVolumeAxis)
-        
+
         pslide = self.FindWindowById(self.win['volume']['position']['slider'])
         ptext = self.FindWindowById(self.win['volume']['position']['text'])
         ptext.SetValue('0')
-        
-        gridSizer.Add(item = axis, flag = wx.ALIGN_CENTER_VERTICAL, pos = (0, 0))
-        gridSizer.Add(item = pslide, flag = wx.ALIGN_CENTER_VERTICAL, pos = (0, 1))
-        gridSizer.Add(item = ptext, flag = wx.ALIGN_CENTER_VERTICAL, pos = (0, 2))
-        gridSizer.Add(item = reset, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, pos = (0, 3))
+
+        gridSizer.Add(item=axis, flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 0))
+        gridSizer.Add(item=pslide, flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 1))
+        gridSizer.Add(item=ptext, flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 2))
+        gridSizer.Add(
+            item=reset,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT,
+            pos=(
+                0,
+                3))
         gridSizer.AddGrowableCol(3)
-        
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                  flag = wx.ALL | wx.EXPAND, border = 3)
-        
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 3)
+
+        boxSizer.Add(item=gridSizer, proportion=1,
+                     flag=wx.ALL | wx.EXPAND, border=3)
+
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                      border=3)
         panel.SetSizer(pageSizer)
         panel.Fit()
-        
+
         return panel
-       
-        
+
     def _createLightPage(self, parent):
         """Create light page"""
-        panel = wx.Panel(parent = parent, id = wx.ID_ANY)
-        
-        self.page['light'] = { 'id' : 0, 
-                               'notebook' : self.foldpanelAppear.GetId() }
+        panel = wx.Panel(parent=parent, id=wx.ID_ANY)
+
+        self.page['light'] = {'id': 0,
+                              'notebook': self.foldpanelAppear.GetId()}
         self.win['light'] = {}
-        
+
         pageSizer = wx.BoxSizer(wx.VERTICAL)
-        
-        show = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                           label = _("Show light model"))
+
+        show = wx.CheckBox(parent=panel, id=wx.ID_ANY,
+                           label=_("Show light model"))
         show.Bind(wx.EVT_CHECKBOX, self.OnShowLightModel)
         show.SetValue(True)
         self._display.showLight = True
-        pageSizer.Add(item = show, proportion = 0,
-                      flag = wx.ALL, border = 3)
-##        surface = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-##                              label = _("Follow source viewpoint"))
-##        pageSizer.Add(item = surface, proportion = 0,
-##                      flag = wx.ALL, border = 3)
-        
+        pageSizer.Add(item=show, proportion=0,
+                      flag=wx.ALL, border=3)
+# surface = wx.CheckBox(parent = panel, id = wx.ID_ANY,
+# label = _("Follow source viewpoint"))
+# pageSizer.Add(item = surface, proportion = 0,
+# flag = wx.ALL, border = 3)
+
         # position
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Light source position")))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Light source position")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
-        gridSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
-        posSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
-        
-        self._createCompass(panel = panel, sizer = posSizer, type = 'light')
-        
-        pos = LightPositionWindow(panel, id = wx.ID_ANY, size = (175, 175),
-                                  mapwindow = self.mapWindow)
+
+        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)
+        posSizer = wx.GridBagSizer(vgap=3, hgap=3)
+
+        self._createCompass(panel=panel, sizer=posSizer, type='light')
+
+        pos = LightPositionWindow(panel, id=wx.ID_ANY, size=(175, 175),
+                                  mapwindow=self.mapWindow)
         self.win['light']['position'] = pos.GetId()
-        posSizer.Add(item = pos,
-                     pos = (1, 1), flag = wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = posSizer, pos = (0, 0))
-        
+        posSizer.Add(
+            item=pos, pos=(1, 1),
+            flag=wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(item=posSizer, pos=(0, 0))
+
         # height
         tooltip = _("Adjusts the light height")
-        self._createControl(panel, data = self.win['light'], name = 'z', sliderHor = False,
-                            range = (0, 100), tooltip = tooltip,
-                            bind = (self.OnLightChange, self.OnLightChanged, self.OnLightChange))
-        
-        heightSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
-        heightSizer.Add(item = wx.StaticText(panel, id = wx.ID_ANY, label = _("Height:")),
-                      pos = (0, 0), flag = wx.ALIGN_LEFT, span = (1, 2))
-        heightSizer.Add(item = self.FindWindowById(self.win['light']['z']['slider']),
-                        flag = wx.ALIGN_RIGHT, pos = (1, 0))
-        heightSizer.Add(item = self.FindWindowById(self.win['light']['z']['text']),
-                        flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT | wx.TOP |
-                        wx.BOTTOM | wx.RIGHT, pos = (1, 1))
-        
-        gridSizer.Add(item = heightSizer, pos = (0, 2), flag = wx.ALIGN_RIGHT)
-        
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                     flag = wx.ALL | wx.EXPAND, border = 2)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 3)
-        
+        self._createControl(
+            panel, data=self.win['light'], name='z', sliderHor=False, range=(
+                0, 100), tooltip=tooltip, bind=(
+                self.OnLightChange, self.OnLightChanged, self.OnLightChange))
+
+        heightSizer = wx.GridBagSizer(vgap=3, hgap=3)
+        heightSizer.Add(
+            item=wx.StaticText(
+                panel, id=wx.ID_ANY, label=_("Height:")), pos=(
+                0, 0), flag=wx.ALIGN_LEFT, span=(
+                1, 2))
+        heightSizer.Add(
+            item=self.FindWindowById(
+                self.win['light']['z']['slider']), flag=wx.ALIGN_RIGHT, pos=(
+                1, 0))
+        heightSizer.Add(item=self.FindWindowById(
+            self.win['light']['z']['text']),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT | wx.TOP |
+            wx.BOTTOM | wx.RIGHT, pos=(1, 1))
+
+        gridSizer.Add(item=heightSizer, pos=(0, 2), flag=wx.ALIGN_RIGHT)
+
+        boxSizer.Add(item=gridSizer, proportion=1,
+                     flag=wx.ALL | wx.EXPAND, border=2)
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                      border=3)
+
         # position
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Light color and intensity")))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Light color and intensity")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
+        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)
 
-        gridSizer.Add(item = wx.StaticText(panel, id = wx.ID_ANY, label = _("Color:")),
-                      pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        color = csel.ColourSelect(panel, id = wx.ID_ANY,
-                                  colour = UserSettings.Get(group = 'nviz', key = 'light',
-                                                            subkey = 'color'),
-                                  size = globalvar.DIALOG_COLOR_SIZE)
+        gridSizer.Add(
+            item=wx.StaticText(
+                panel, id=wx.ID_ANY, label=_("Color:")), pos=(
+                0, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+        color = csel.ColourSelect(
+            panel, id=wx.ID_ANY, colour=UserSettings.Get(
+                group='nviz', key='light', subkey='color'),
+            size=globalvar.DIALOG_COLOR_SIZE)
         self.win['light']['color'] = color.GetId()
         color.Bind(csel.EVT_COLOURSELECT, self.OnLightColor)
-        gridSizer.Add(item = color, pos = (0, 2))
+        gridSizer.Add(item=color, pos=(0, 2))
 
-        gridSizer.Add(item = wx.StaticText(panel, id = wx.ID_ANY, label = _("Brightness:")),
-                      pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=wx.StaticText(
+                panel, id=wx.ID_ANY, label=_("Brightness:")), pos=(
+                1, 0), flag=wx.ALIGN_CENTER_VERTICAL)
         tooltip = _("Adjusts the brightness of the light")
-        self._createControl(panel, data = self.win['light'], name = 'bright', size = 300,
-                            range = (0, 100), tooltip = tooltip, 
-                            bind = (self.OnLightValue, self.OnLightChanged, self.OnLightValue))
-        gridSizer.Add(item = self.FindWindowById(self.win['light']['bright']['slider']),
-                      pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = self.FindWindowById(self.win['light']['bright']['text']),
-                      pos = (1, 2),
-                      flag = wx.ALIGN_CENTER)
-        gridSizer.Add(item = wx.StaticText(panel, id = wx.ID_ANY, label = _("Ambient:")),
-                      pos = (2, 0), flag = wx.ALIGN_CENTER_VERTICAL)
+        self._createControl(
+            panel, data=self.win['light'], name='bright', size=300, range=(
+                0, 100), tooltip=tooltip, bind=(
+                self.OnLightValue, self.OnLightChanged, self.OnLightValue))
+        gridSizer.Add(
+            item=self.FindWindowById(
+                self.win['light']['bright']['slider']), pos=(
+                1, 1), flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=self.FindWindowById(
+                self.win['light']['bright']['text']), pos=(
+                1, 2), flag=wx.ALIGN_CENTER)
+        gridSizer.Add(
+            item=wx.StaticText(
+                panel, id=wx.ID_ANY, label=_("Ambient:")), pos=(
+                2, 0), flag=wx.ALIGN_CENTER_VERTICAL)
         tooltip = _("Adjusts the ambient light")
-        self._createControl(panel, data = self.win['light'], name = 'ambient', size = 300,
-                            range = (0, 100), tooltip = tooltip,
-                            bind = (self.OnLightValue, self.OnLightChanged, self.OnLightValue))
-        gridSizer.Add(item = self.FindWindowById(self.win['light']['ambient']['slider']),
-                      pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = self.FindWindowById(self.win['light']['ambient']['text']),
-                      pos = (2, 2),
-                      flag = wx.ALIGN_CENTER)
+        self._createControl(
+            panel, data=self.win['light'], name='ambient', size=300, range=(
+                0, 100), tooltip=tooltip, bind=(
+                self.OnLightValue, self.OnLightChanged, self.OnLightValue))
+        gridSizer.Add(
+            item=self.FindWindowById(
+                self.win['light']['ambient']['slider']), pos=(
+                2, 1), flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=self.FindWindowById(
+                self.win['light']['ambient']['text']), pos=(
+                2, 2), flag=wx.ALIGN_CENTER)
 
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                     flag = wx.ALL | wx.EXPAND, border = 2)
-        pageSizer.Add(item = boxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 3)
-        
+        boxSizer.Add(item=gridSizer, proportion=1,
+                     flag=wx.ALL | wx.EXPAND, border=2)
+        pageSizer.Add(item=boxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                      border=3)
+
         # reset = wx.Button(panel, id = wx.ID_ANY, label = _("Reset"))
         # reset.SetToolTipString(_("Reset to default view"))
         # # self.win['reset'] = reset.GetId()
         # reset.Bind(wx.EVT_BUTTON, self.OnResetView)
-        
+
         # viewSizer.Add(item = reset, proportion = 1,
         #               flag = wx.EXPAND | wx.ALL | wx.ALIGN_RIGHT,
         #               border = 5)
-        
+
         # gridSizer.AddGrowableCol(3)
         # gridSizer.Add(item = viewSizer, pos = (4, 0), span = (1, 2),
         #               flag = wx.EXPAND)
-        
+
         panel.SetSizer(pageSizer)
         panel.Layout()
         panel.Fit()
-        
+
         return panel
 
     def _createFringePage(self, parent):
         """Create fringe page"""
-        panel = wx.Panel(parent = parent, id = wx.ID_ANY)
-        
-        self.page['fringe'] = { 'id' : 1,
-                                'notebook' : self.foldpanelAppear.GetId() }
+        panel = wx.Panel(parent=parent, id=wx.ID_ANY)
+
+        self.page['fringe'] = {'id': 1,
+                               'notebook': self.foldpanelAppear.GetId()}
         self.win['fringe'] = {}
 
         pageSizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         # selection
-        rbox = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                             label = " %s " % (_("Surface")))
+        rbox = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                            label=" %s " % (_("Surface")))
         rboxSizer = wx.StaticBoxSizer(rbox, wx.VERTICAL)
-        rmaps = Select(parent = panel, type = 'raster',
-                       onPopup = self.GselectOnPopup)
+        rmaps = Select(parent=panel, type='raster',
+                       onPopup=self.GselectOnPopup)
         rmaps.GetChildren()[0].Bind(wx.EVT_TEXT, self.OnSetSurface)
         self.win['fringe']['map'] = rmaps.GetId()
-        rboxSizer.Add(item = rmaps, proportion = 0,
-                      flag = wx.ALL,
-                      border = 3)
-        pageSizer.Add(item = rboxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 3)
-        
-        ebox = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                             label = " %s " % (_("Edges with fringe")))
+        rboxSizer.Add(item=rmaps, proportion=0,
+                      flag=wx.ALL,
+                      border=3)
+        pageSizer.Add(item=rboxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                      border=3)
+
+        ebox = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                            label=" %s " % (_("Edges with fringe")))
         eboxSizer = wx.StaticBoxSizer(ebox, wx.HORIZONTAL)
         for edge in [(_("N && W"), "nw"),
                      (_("N && E"), "ne"),
                      (_("S && W"), "sw"),
                      (_("S && E"), "se")]:
-            chkbox = wx.CheckBox(parent = panel,
-                                 label = edge[0],
-                                 name = edge[1])
+            chkbox = wx.CheckBox(parent=panel,
+                                 label=edge[0],
+                                 name=edge[1])
             self.win['fringe'][edge[1]] = chkbox.GetId()
-            eboxSizer.Add(item = chkbox, proportion = 0,
-                         flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT, border = 5)
+            eboxSizer.Add(
+                item=chkbox,
+                proportion=0,
+                flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT,
+                border=5)
             chkbox.Bind(wx.EVT_CHECKBOX, self.OnFringe)
-        
-        pageSizer.Add(item = eboxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 3)
 
-        sbox = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                             label = " %s " % (_("Settings")))
+        pageSizer.Add(item=eboxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                      border=3)
+
+        sbox = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                            label=" %s " % (_("Settings")))
         sboxSizer = wx.StaticBoxSizer(sbox, wx.HORIZONTAL)
-        gridSizer = wx.GridBagSizer(vgap = 5, hgap = 5)
-        
+        gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
+
         # elevation
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                           label = _("Elevation of fringe from bottom:")),
-                      pos = (0, 0),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        spin = wx.SpinCtrl(parent = panel, id = wx.ID_ANY,
-                           size = (65, -1), min = -1e6, max = 1e6)
-        spin.SetValue(UserSettings.Get(group = 'nviz', key = 'fringe', subkey = 'elev'))
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel, id=wx.ID_ANY,
+                label=_("Elevation of fringe from bottom:")),
+            pos=(0, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL)
+        spin = wx.SpinCtrl(parent=panel, id=wx.ID_ANY,
+                           size=(65, -1), min=-1e6, max=1e6)
+        spin.SetValue(
+            UserSettings.Get(
+                group='nviz',
+                key='fringe',
+                subkey='elev'))
         spin.Bind(wx.EVT_SPINCTRL, self.OnFringe)
         self.win['fringe']['elev'] = spin.GetId()
-        gridSizer.Add(item = spin, pos = (0, 1))
-        
+        gridSizer.Add(item=spin, pos=(0, 1))
+
         # color
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                           label = _("Color:")),
-                      pos = (1, 0),
-                      flag = wx.ALIGN_CENTER_VERTICAL)
-        color = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
-                                  size = globalvar.DIALOG_COLOR_SIZE)
-        color.SetColour(UserSettings.Get(group = 'nviz', key = 'fringe',
-                                         subkey = 'color'))
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Color:")),
+                      pos=(1, 0),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
+        color = csel.ColourSelect(parent=panel, id=wx.ID_ANY,
+                                  size=globalvar.DIALOG_COLOR_SIZE)
+        color.SetColour(UserSettings.Get(group='nviz', key='fringe',
+                                         subkey='color'))
         color.Bind(csel.EVT_COLOURSELECT, self.OnFringe)
         self.win['fringe']['color'] = color.GetId()
-        gridSizer.Add(item = color, pos = (1, 1))
-        
-        sboxSizer.Add(item = gridSizer, proportion = 1,
-                      flag = wx.ALL | wx.EXPAND, border = 3)
-        pageSizer.Add(item = sboxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 3)
-        
+        gridSizer.Add(item=color, pos=(1, 1))
+
+        sboxSizer.Add(item=gridSizer, proportion=1,
+                      flag=wx.ALL | wx.EXPAND, border=3)
+        pageSizer.Add(item=sboxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                      border=3)
+
         panel.SetSizer(pageSizer)
         panel.Layout()
         panel.Fit()
 
         return panel
-    
+
     def _createDecorationPage(self, parent):
         """Create decoration (north arrow, scalebar, legend) page"""
-        panel = wx.Panel(parent = parent, id = wx.ID_ANY)
-        
-        self.page['decoration'] = { 'id' : 2,
-                                    'notebook' : self.foldpanelAppear.GetId()}
+        panel = wx.Panel(parent=parent, id=wx.ID_ANY)
+
+        self.page['decoration'] = {'id': 2,
+                                   'notebook': self.foldpanelAppear.GetId()}
         self.win['decoration'] = {}
 
         pageSizer = wx.BoxSizer(wx.VERTICAL)
-        
+
         # north arrow
         self.win['decoration']['arrow'] = {}
-        nabox = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                             label = " %s " % (_("North Arrow")))
+        nabox = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                             label=" %s " % (_("North Arrow")))
         naboxSizer = wx.StaticBoxSizer(nabox, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
+        gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
         # size
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                           label = _("Arrow length (in map units):")),
-                      pos = (0,0), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL)
-        sizeCtrl = NumTextCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1), style = wx.TE_PROCESS_ENTER)
-        gridSizer.Add(sizeCtrl, pos = (0, 2))
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Arrow length (in map units):")),
+                      pos=(0, 0), span=(1, 2), flag=wx.ALIGN_CENTER_VERTICAL)
+        sizeCtrl = NumTextCtrl(
+            parent=panel, id=wx.ID_ANY, size=(
+                65, -1), style=wx.TE_PROCESS_ENTER)
+        gridSizer.Add(sizeCtrl, pos=(0, 2))
         self.win['decoration']['arrow']['size'] = sizeCtrl.GetId()
         sizeCtrl.Bind(wx.EVT_TEXT_ENTER, self.OnDecorationProp)
         sizeCtrl.Bind(wx.EVT_KILL_FOCUS, self.OnDecorationProp)
-        
+
         # color
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                           label = _("Arrow color:")),
-                      pos = (1,0), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL)
-        color = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
-                                  size = globalvar.DIALOG_COLOR_SIZE)
-        gridSizer.Add(color, pos = (1, 2))
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Arrow color:")),
+                      pos=(1, 0), span=(1, 2), flag=wx.ALIGN_CENTER_VERTICAL)
+        color = csel.ColourSelect(parent=panel, id=wx.ID_ANY,
+                                  size=globalvar.DIALOG_COLOR_SIZE)
+        gridSizer.Add(color, pos=(1, 2))
         self.win['decoration']['arrow']['color'] = color.GetId()
         color.Bind(csel.EVT_COLOURSELECT, self.OnDecorationProp)
-        
+
         # control
-        toggle = wx.ToggleButton(parent = panel, id = wx.ID_ANY, label = _("Place arrow"))
-        gridSizer.Add(item = toggle, pos = (2, 0))
+        toggle = wx.ToggleButton(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Place arrow"))
+        gridSizer.Add(item=toggle, pos=(2, 0))
         toggle.Bind(wx.EVT_TOGGLEBUTTON, self.OnDecorationPlacement)
         self.win['decoration']['arrow']['place'] = toggle.GetId()
         toggle.SetName('placeArrow')
 
-        delete = wx.Button(parent = panel, id = wx.ID_ANY, label = _("Delete"))
+        delete = wx.Button(parent=panel, id=wx.ID_ANY, label=_("Delete"))
         self.win['decoration']['arrow']['delete'] = delete.GetId()
-        gridSizer.Add(item = delete, pos = (2, 1))
+        gridSizer.Add(item=delete, pos=(2, 1))
         delete.Bind(wx.EVT_BUTTON, self.OnArrowDelete)
         shown = self.mapWindow.decoration['arrow']['show']
         delete.Enable(shown)
-        naboxSizer.Add(item = gridSizer, proportion = 0, flag = wx.EXPAND, border = 3)
-        pageSizer.Add(item = naboxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 3)
-        
-        
+        naboxSizer.Add(item=gridSizer, proportion=0, flag=wx.EXPAND, border=3)
+        pageSizer.Add(item=naboxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                      border=3)
+
         # scale bars
         self.win['decoration']['scalebar'] = {}
-        nabox = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                             label = " %s " % (_("Scale bar")))
+        nabox = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                             label=" %s " % (_("Scale bar")))
         naboxSizer = wx.StaticBoxSizer(nabox, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
+        gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
         # size
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                           label = _("Scale bar length (in map units):")),
-                      pos = (0,0), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL)
-        sizeCtrl = NumTextCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1), style = wx.TE_PROCESS_ENTER)
-        gridSizer.Add(sizeCtrl, pos = (0, 2))
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Scale bar length (in map units):")),
+                      pos=(0, 0), span=(1, 2), flag=wx.ALIGN_CENTER_VERTICAL)
+        sizeCtrl = NumTextCtrl(
+            parent=panel, id=wx.ID_ANY, size=(
+                65, -1), style=wx.TE_PROCESS_ENTER)
+        gridSizer.Add(sizeCtrl, pos=(0, 2))
         self.win['decoration']['scalebar']['size'] = sizeCtrl.GetId()
         sizeCtrl.Bind(wx.EVT_TEXT_ENTER, self.OnDecorationProp)
         sizeCtrl.Bind(wx.EVT_KILL_FOCUS, self.OnDecorationProp)
-        
+
         # color
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                           label = _("Scale bar color:")),
-                      pos = (1,0), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL)
-        color = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
-                                  size = globalvar.DIALOG_COLOR_SIZE)
-        gridSizer.Add(color, pos = (1, 2))
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=_("Scale bar color:")),
+                      pos=(1, 0), span=(1, 2), flag=wx.ALIGN_CENTER_VERTICAL)
+        color = csel.ColourSelect(parent=panel, id=wx.ID_ANY,
+                                  size=globalvar.DIALOG_COLOR_SIZE)
+        gridSizer.Add(color, pos=(1, 2))
         self.win['decoration']['scalebar']['color'] = color.GetId()
         color.Bind(csel.EVT_COLOURSELECT, self.OnDecorationProp)
-        
+
         # control
-        toggle = wx.ToggleButton(parent = panel, id = wx.ID_ANY, label = _("Place new scale bar"))
-        gridSizer.Add(item = toggle, pos = (2, 0))
+        toggle = wx.ToggleButton(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Place new scale bar"))
+        gridSizer.Add(item=toggle, pos=(2, 0))
         toggle.Bind(wx.EVT_TOGGLEBUTTON, self.OnDecorationPlacement)
         self.win['decoration']['scalebar']['place'] = toggle.GetId()
         toggle.SetName('placeScalebar')
 
-        scalebarChoice = wx.Choice(parent = panel, id = wx.ID_ANY, choices = [])
+        scalebarChoice = wx.Choice(parent=panel, id=wx.ID_ANY, choices=[])
         self.win['decoration']['scalebar']['choice'] = scalebarChoice.GetId()
-        gridSizer.Add(item = scalebarChoice, pos = (3, 0), flag = wx.EXPAND)
-        delete = wx.Button(parent = panel, id = wx.ID_ANY, label = _("Delete"))
+        gridSizer.Add(item=scalebarChoice, pos=(3, 0), flag=wx.EXPAND)
+        delete = wx.Button(parent=panel, id=wx.ID_ANY, label=_("Delete"))
         self.win['decoration']['scalebar']['delete'] = delete.GetId()
-        gridSizer.Add(item = delete, pos = (3, 1))
+        gridSizer.Add(item=delete, pos=(3, 1))
         delete.Bind(wx.EVT_BUTTON, self.OnScalebarDelete)
-        naboxSizer.Add(item = gridSizer, proportion = 0, flag = wx.EXPAND, border = 3)
-        pageSizer.Add(item = naboxSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
-                      border = 3)      
+        naboxSizer.Add(item=gridSizer, proportion=0, flag=wx.EXPAND, border=3)
+        pageSizer.Add(item=naboxSizer, proportion=0,
+                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+                      border=3)
 
         self.DisableScalebarControls()
 
@@ -2041,20 +2431,20 @@
         panel.Fit()
 
         return panel
-    
-    def GetLayerData(self, nvizType, nameOnly = False):
+
+    def GetLayerData(self, nvizType, nameOnly=False):
         """Get nviz data"""
         name = self.FindWindowById(self.win[nvizType]['map']).GetValue()
         if nameOnly:
             return name
-        
+
         if nvizType == 'surface' or nvizType == 'fringe':
-            return self._getLayerPropertiesByName(name, mapType = 'raster')
+            return self._getLayerPropertiesByName(name, mapType='raster')
         elif nvizType == 'vector':
-            return self._getLayerPropertiesByName(name, mapType = 'vector')
+            return self._getLayerPropertiesByName(name, mapType='vector')
         elif nvizType == 'volume':
-            return self._getLayerPropertiesByName(name, mapType = 'raster_3d')
-        
+            return self._getLayerPropertiesByName(name, mapType='raster_3d')
+
         return None
 
     def _getMapLayerByName(self, name, mapType):
@@ -2063,7 +2453,7 @@
         :param name: layer name
         :param mapType: map type (raster, vector, raster_3d)
         """
-        layers = self.mapWindow.Map.GetListOfLayers(ltype = mapType, name = name)
+        layers = self.mapWindow.Map.GetListOfLayers(ltype=mapType, name=name)
         if layers:
             return layers[0]
         return None
@@ -2074,12 +2464,12 @@
         :param name: layer name
         :param mapType: map type (raster, vector, raster_3d)
         """
-        items = self.tree.FindItemByData(key = 'name', value = name)
+        items = self.tree.FindItemByData(key='name', value=name)
         if not items:
             return None
         for item in items:
-            if self.tree.GetLayerInfo(item, key = 'type') == mapType:
-                return self.tree.GetLayerInfo(item, key = 'nviz')
+            if self.tree.GetLayerInfo(item, key='type') == mapType:
+                return self.tree.GetLayerInfo(item, key='nviz')
         return None
 
     def OnRecord(self, event):
@@ -2087,45 +2477,45 @@
         anim = self.mapWindow.GetAnimation()
         if not anim.IsPaused():
             if anim.Exists() and not anim.IsSaved():
-                msg = _("Do you want to record new animation without saving the previous one?")
-                dlg = wx.MessageDialog(parent = self,
-                                       message = msg,
-                                       caption =_("Animation already axists"),
-                                       style = wx.YES_NO | wx.CENTRE)
+                msg = _(
+                    "Do you want to record new animation without saving the previous one?")
+                dlg = wx.MessageDialog(parent=self,
+                                       message=msg,
+                                       caption=_("Animation already axists"),
+                                       style=wx.YES_NO | wx.CENTRE)
                 if dlg.ShowModal() == wx.ID_NO:
                     dlg.Destroy()
                     return
-                
-        
+
             anim.Clear()
             self.UpdateFrameIndex(0)
             self.UpdateFrameCount()
-            
+
         anim.SetPause(False)
-        anim.SetMode(mode = 'record')
+        anim.SetMode(mode='record')
         anim.Start()
-        
+
         self.FindWindowById(self.win['anim']['play']).Disable()
         self.FindWindowById(self.win['anim']['record']).Disable()
         self.FindWindowById(self.win['anim']['pause']).Enable()
         self.FindWindowById(self.win['anim']['stop']).Enable()
         self.FindWindowById(self.win['anim']['frameIndex']['slider']).Disable()
         self.FindWindowById(self.win['anim']['frameIndex']['text']).Disable()
-        
+
     def OnPlay(self, event):
         """Animation: replay"""
         anim = self.mapWindow.GetAnimation()
         anim.SetPause(False)
-        anim.SetMode(mode = 'play')
+        anim.SetMode(mode='play')
         anim.Start()
-        
+
         self.FindWindowById(self.win['anim']['play']).Disable()
         self.FindWindowById(self.win['anim']['record']).Disable()
         self.FindWindowById(self.win['anim']['pause']).Enable()
         self.FindWindowById(self.win['anim']['stop']).Enable()
         self.FindWindowById(self.win['anim']['frameIndex']['slider']).Enable()
         self.FindWindowById(self.win['anim']['frameIndex']['text']).Enable()
-        
+
     def OnStop(self, event):
         """Animation: stop recording/replaying"""
         anim = self.mapWindow.GetAnimation()
@@ -2134,190 +2524,204 @@
             anim.StopSaving()
         if anim.IsRunning():
             anim.Stop()
-        
+
         self.UpdateFrameIndex(0)
-        
+
         self.FindWindowById(self.win['anim']['play']).Enable()
         self.FindWindowById(self.win['anim']['record']).Enable()
         self.FindWindowById(self.win['anim']['pause']).Disable()
         self.FindWindowById(self.win['anim']['stop']).Disable()
         self.FindWindowById(self.win['anim']['frameIndex']['slider']).Disable()
         self.FindWindowById(self.win['anim']['frameIndex']['text']).Disable()
-        
+
     def OnPause(self, event):
         """Pause animation"""
         anim = self.mapWindow.GetAnimation()
-        
+
         anim.SetPause(True)
         mode = anim.GetMode()
         if anim.IsRunning():
             anim.Pause()
-            
+
         if mode == "record":
             self.FindWindowById(self.win['anim']['play']).Disable()
             self.FindWindowById(self.win['anim']['record']).Enable()
-            self.FindWindowById(self.win['anim']['frameIndex']['slider']).Disable()
-            self.FindWindowById(self.win['anim']['frameIndex']['text']).Disable()
+            self.FindWindowById(
+                self.win['anim']['frameIndex']['slider']).Disable()
+            self.FindWindowById(
+                self.win['anim']['frameIndex']['text']).Disable()
         elif mode == 'play':
             self.FindWindowById(self.win['anim']['record']).Disable()
             self.FindWindowById(self.win['anim']['play']).Enable()
-            self.FindWindowById(self.win['anim']['frameIndex']['slider']).Enable()
-            self.FindWindowById(self.win['anim']['frameIndex']['text']).Enable()
-        
+            self.FindWindowById(
+                self.win['anim']['frameIndex']['slider']).Enable()
+            self.FindWindowById(
+                self.win['anim']['frameIndex']['text']).Enable()
+
         self.FindWindowById(self.win['anim']['pause']).Disable()
         self.FindWindowById(self.win['anim']['stop']).Enable()
 
-        
     def OnFrameIndex(self, event):
         """Frame index changed (by slider)"""
         index = event.GetInt()
-        self.UpdateFrameIndex(index = index, sliderWidget = False)
-        
+        self.UpdateFrameIndex(index=index, sliderWidget=False)
+
     def OnFrameIndexText(self, event):
         """Frame index changed by (textCtrl)"""
         index = event.GetValue()
-        self.UpdateFrameIndex(index = index, textWidget = False)
-        
+        self.UpdateFrameIndex(index=index, textWidget=False)
+
     def OnFPS(self, event):
         """Frames per second changed"""
         anim = self.mapWindow.GetAnimation()
         anim.SetFPS(event.GetInt())
-        
-    def UpdateFrameIndex(self, index, sliderWidget = True, textWidget = True, goToFrame = True):
+
+    def UpdateFrameIndex(self, index, sliderWidget=True,
+                         textWidget=True, goToFrame=True):
         """Update frame index"""
         anim = self.mapWindow.GetAnimation()
-        
+
         # check index
         frameCount = anim.GetFrameCount()
         if index >= frameCount:
             index = frameCount - 1
         if index < 0:
             index = 0
-            
+
         if sliderWidget:
-            slider = self.FindWindowById(self.win['anim']['frameIndex']['slider'])
+            slider = self.FindWindowById(
+                self.win['anim']['frameIndex']['slider'])
             slider.SetValue(index)
         if textWidget:
             text = self.FindWindowById(self.win['anim']['frameIndex']['text'])
             text.SetValue(int(index))
-        
+
         # if called from tool window, update frame
         if goToFrame:
             anim.GoToFrame(int(index))
-            
+
     def UpdateFrameCount(self):
         """Update frame count label"""
         anim = self.mapWindow.GetAnimation()
         count = anim.GetFrameCount()
         self.FindWindowById(self.win['anim']['info']).SetLabel(str(count))
-        
+
     def OnAnimationFinished(self, mode):
         """Animation finished"""
         anim = self.mapWindow.GetAnimation()
-        self.UpdateFrameIndex(index = 0)
-        
+        self.UpdateFrameIndex(index=0)
+
         slider = self.FindWindowById(self.win['anim']['frameIndex']['slider'])
         text = self.FindWindowById(self.win['anim']['frameIndex']['text'])
-        
+
         if mode == 'record':
             count = anim.GetFrameCount()
             slider.SetMax(count)
             self.UpdateFrameCount()
-            
+
         self.FindWindowById(self.win['anim']['pause']).Disable()
         self.FindWindowById(self.win['anim']['stop']).Disable()
         self.FindWindowById(self.win['anim']['record']).Enable()
         self.FindWindowById(self.win['anim']['play']).Enable()
         self.FindWindowById(self.win['anim']['frameIndex']['slider']).Disable()
         self.FindWindowById(self.win['anim']['frameIndex']['text']).Disable()
-        self.FindWindowById(self.win['anim']['save']['image']['confirm']).Enable()
-        
+        self.FindWindowById(self.win['anim']['save'][
+                            'image']['confirm']).Enable()
+
         self.mapWindow.render['quick'] = False
         self.mapWindow.Refresh(False)
-        
+
     def OnAnimationUpdateIndex(self, index, mode):
         """Animation: frame index changed"""
         if mode == 'record':
             self.UpdateFrameCount()
         elif mode == 'play':
-            self.UpdateFrameIndex(index = index, goToFrame = False)
-        
+            self.UpdateFrameIndex(index=index, goToFrame=False)
+
     def OnSaveAnimation(self, event):
         """Save animation as a sequence of images"""
         anim = self.mapWindow.GetAnimation()
-        
-        prefix = self.FindWindowById(self.win['anim']['save']['image']['prefix']).GetValue()
-        format = self.FindWindowById(self.win['anim']['save']['image']['format']).GetSelection()
-        dir = self.FindWindowById(self.win['anim']['save']['image']['dir']).GetValue()
-        
+
+        prefix = self.FindWindowById(
+            self.win['anim']['save']['image']['prefix']).GetValue()
+        format = self.FindWindowById(
+            self.win['anim']['save']['image']['format']).GetSelection()
+        dir = self.FindWindowById(
+            self.win['anim']['save']['image']['dir']).GetValue()
+
         if not prefix:
-            GMessage(parent = self,
-                          message = _("No file prefix given."))
+            GMessage(parent=self,
+                     message=_("No file prefix given."))
             return
         elif not os.path.exists(dir):
-            GMessage(parent = self,
-                          message = _("Directory %s does not exist.") % dir)
+            GMessage(parent=self,
+                     message=_("Directory %s does not exist.") % dir)
             return
-            
+
         self.FindWindowById(self.win['anim']['pause']).Disable()
         self.FindWindowById(self.win['anim']['stop']).Enable()
         self.FindWindowById(self.win['anim']['record']).Disable()
         self.FindWindowById(self.win['anim']['play']).Disable()
         self.FindWindowById(self.win['anim']['frameIndex']['slider']).Disable()
         self.FindWindowById(self.win['anim']['frameIndex']['text']).Disable()
-        
-        self.FindWindowById(self.win['anim']['save']['image']['confirm']).Disable()
-        
-        anim.SaveAnimationFile(path = dir, prefix = prefix, format = format)
-        
+
+        self.FindWindowById(self.win['anim']['save'][
+                            'image']['confirm']).Disable()
+
+        anim.SaveAnimationFile(path=dir, prefix=prefix, format=format)
+
     def OnNewConstant(self, event):
         """Create new surface with constant value"""
-        #TODO settings
+        # TODO settings
         name = self.mapWindow.NewConstant()
         win = self.FindWindowById(self.win['constant']['surface'])
         name = _("constant#") + str(name)
         win.Append(name)
         win.SetStringSelection(name)
         self.OnConstantSelection(None)
-        self.EnablePage(name = 'constant', enabled = True)
-        
-        self.mapWindow.Refresh(eraseBackground = False)
-        
+        self.EnablePage(name='constant', enabled=True)
+
+        self.mapWindow.Refresh(eraseBackground=False)
+
         # need to update list of surfaces in vector page
         for vtype in ('points', 'lines'):
-            checklist = self.FindWindowById(self.win['vector'][vtype]['surface'])
+            checklist = self.FindWindowById(
+                self.win['vector'][vtype]['surface'])
             checklist.Append(name)
         win = self.FindWindowById(self.win['vector']['map'])
         win.SetValue(win.GetValue())
-                
 
     def OnDeleteConstant(self, event):
         """Delete selected constant surface"""
-        layerIdx = self.FindWindowById(self.win['constant']['surface']).GetSelection()
+        layerIdx = self.FindWindowById(
+            self.win['constant']['surface']).GetSelection()
         if layerIdx == wx.NOT_FOUND:
             return
-        name = self.FindWindowById(self.win['constant']['surface']).GetStringSelection()
+        name = self.FindWindowById(
+            self.win['constant']['surface']).GetStringSelection()
         self.mapWindow.DeleteConstant(layerIdx)
         win = self.FindWindowById(self.win['constant']['surface'])
         win.Delete(layerIdx)
         if win.IsEmpty():
             win.SetValue("")
-            self.EnablePage(name = 'constant', enabled = False)
+            self.EnablePage(name='constant', enabled=False)
         else:
             win.SetSelection(0)
             self.OnConstantSelection(None)
-            
+
         # need to update list of surfaces in vector page
         for vtype in ('points', 'lines'):
-            checklist = self.FindWindowById(self.win['vector'][vtype]['surface'])
+            checklist = self.FindWindowById(
+                self.win['vector'][vtype]['surface'])
             checklist.Delete(checklist.FindString(name))
-            
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-    
+
     def OnConstantSelection(self, event):
         """Constant selected"""
-        layerIdx = self.FindWindowById(self.win['constant']['surface']).GetSelection()
+        layerIdx = self.FindWindowById(
+            self.win['constant']['surface']).GetSelection()
         if layerIdx == wx.NOT_FOUND:
             return
         name = _("constant#") + str(layerIdx + 1)
@@ -2327,43 +2731,49 @@
                 value = self._getColorFromString(value)
             if attr in ('color', 'value', 'resolution', 'transp'):
                 if attr == 'transp':
-                    self.FindWindowById(self.win['constant'][attr]).SetValue(self._getPercent(value))
+                    self.FindWindowById(
+                        self.win['constant'][attr]).SetValue(
+                        self._getPercent(value))
                 self.FindWindowById(self.win['constant'][attr]).SetValue(value)
-        
+
     def OnSetConstantProp(self, event):
         """Change properties (color, value, resolution)
             of currently selected constant surface"""
-        layerIdx = self.FindWindowById(self.win['constant']['surface']).GetSelection()
+        layerIdx = self.FindWindowById(
+            self.win['constant']['surface']).GetSelection()
         if layerIdx == wx.NOT_FOUND:
             return
         data = self.mapWindow.constants[layerIdx]
         for attr in ('resolution', 'value', 'transp'):
-            data['constant'][attr] = self.FindWindowById(self.win['constant'][attr]).GetValue()
+            data['constant'][attr] = self.FindWindowById(
+                self.win['constant'][attr]).GetValue()
         data['constant']['color'] = self._getColorString(
-                self.FindWindowById(self.win['constant']['color']).GetValue())
-        data['constant']['transp'] = self._getPercent(data['constant']['transp'], toPercent = False)
-        
+            self.FindWindowById(self.win['constant']['color']).GetValue())
+        data['constant']['transp'] = self._getPercent(
+            data['constant']['transp'], toPercent=False)
+
        # update properties
-        event = wxUpdateProperties(data = data)
-        wx.PostEvent(self.mapWindow, event) 
+        event = wxUpdateProperties(data=data)
+        wx.PostEvent(self.mapWindow, event)
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-        
+
     def OnFringe(self, event):
         """Show/hide fringe"""
         data = self.GetLayerData('fringe')['surface']
-        
+
         sid = data['object']['id']
         elev = self.FindWindowById(self.win['fringe']['elev']).GetValue()
         color = self.FindWindowById(self.win['fringe']['color']).GetValue()
-        
-        self._display.SetFringe(sid, color, elev,
-                                self.FindWindowById(self.win['fringe']['nw']).IsChecked(),
-                                self.FindWindowById(self.win['fringe']['ne']).IsChecked(),
-                                self.FindWindowById(self.win['fringe']['sw']).IsChecked(),
-                                self.FindWindowById(self.win['fringe']['se']).IsChecked())
+
+        self._display.SetFringe(
+            sid, color, elev, self.FindWindowById(
+                self.win['fringe']['nw']).IsChecked(), self.FindWindowById(
+                self.win['fringe']['ne']).IsChecked(), self.FindWindowById(
+                self.win['fringe']['sw']).IsChecked(), self.FindWindowById(
+                    self.win['fringe']['se']).IsChecked())
         self.mapWindow.Refresh(False)
-        
+
     def OnScroll(self, event, win, data):
         """Generic scrolling handler"""
         winName = self.__GetWindowName(win, event.GetId())
@@ -2372,233 +2782,275 @@
         data[winName] = self.FindWindowById(event.GetId()).GetValue()
         for w in win[winName].itervalues():
             self.FindWindowById(w).SetValue(data[winName])
-        
+
         event.Skip()
-        
+
     def AdjustSliderRange(self, slider, value):
         minim, maxim = slider.GetRange()
         if not (minim <= value <= maxim):
             slider.SetRange(min(minim, value), max(maxim, value))
-    
+
     def _createIsosurfacePanel(self, parent):
-        panel = wx.Panel(parent = parent, id = wx.ID_ANY)
-        
+        panel = wx.Panel(parent=parent, id=wx.ID_ANY)
+
         vSizer = wx.BoxSizer(wx.HORIZONTAL)
-        
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Isosurface attributes")))
+
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Isosurface attributes")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
-        
+        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)
+
         self.win['volume']['attr'] = {}
-        inout = wx.CheckBox(parent = panel, id = wx.ID_ANY, 
-                            label = _("toggle normal direction"))
-        gridSizer.Add(item = inout, pos = (0,0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL)
+        inout = wx.CheckBox(parent=panel, id=wx.ID_ANY,
+                            label=_("toggle normal direction"))
+        gridSizer.Add(
+            item=inout, pos=(
+                0, 0), span=(
+                1, 2), flag=wx.ALIGN_CENTER_VERTICAL)
         inout.Bind(wx.EVT_CHECKBOX, self.OnInOutMode)
         self.win['volume']['inout'] = inout.GetId()
-        
+
         row = 1
         for code, attrb in (('topo', _("Isosurface value")),
                             ('color', _("Color")),
                             ('mask', _("Mask")),
                             ('transp', _("Transparency")),
                             ('shine', _("Shininess"))):
-            self.win['volume'][code] = {} 
+            self.win['volume'][code] = {}
             # label
             colspan = 1
             if code == 'topo':
                 colspan = 2
-            gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                             label = attrb + ':'),
-                          pos = (row, 0), span = (1, colspan),flag = wx.ALIGN_CENTER_VERTICAL)
+            gridSizer.Add(
+                item=wx.StaticText(
+                    parent=panel,
+                    id=wx.ID_ANY,
+                    label=attrb + ':'),
+                pos=(
+                    row,
+                    0),
+                span=(
+                    1,
+                    colspan),
+                flag=wx.ALIGN_CENTER_VERTICAL)
             if code != 'topo':
-                use = wx.Choice (parent = panel, id = wx.ID_ANY, size = (100, -1),
-                                 choices = [_("map")])
+                use = wx.Choice(parent=panel, id=wx.ID_ANY, size=(100, -1),
+                                choices=[_("map")])
             else:
                 use = None
             # check for required properties
             if code not in ('topo', 'color', 'shine'):
-                use.Insert(item = _("unset"), pos = 0)
+                use.Insert(item=_("unset"), pos=0)
                 self.win['volume'][code]['required'] = False
             else:
                 self.win['volume'][code]['required'] = True
             if use and code != 'mask':
-                use.Append(item = _('constant'))
+                use.Append(item=_('constant'))
             if use:
                 self.win['volume'][code]['use'] = use.GetId()
                 use.Bind(wx.EVT_CHOICE, self.OnMapObjUse)
-                gridSizer.Add(item = use, flag = wx.ALIGN_CENTER_VERTICAL,
-                              pos = (row, 1))
-                    
+                gridSizer.Add(item=use, flag=wx.ALIGN_CENTER_VERTICAL,
+                              pos=(row, 1))
+
             if code != 'topo':
-                map = Select(parent = panel, id = wx.ID_ANY,
+                map = Select(parent=panel, id=wx.ID_ANY,
                              # size = globalvar.DIALOG_GSELECT_SIZE,
-                             size = (200, -1),
-                             type = "grid3")
+                             size=(200, -1),
+                             type="grid3")
                 if globalvar.CheckWxVersion([3]):
                     self.win['volume'][code]['map'] = map.GetId()
                 else:
                     self.win['volume'][code]['map'] = map.GetTextCtrl().GetId()
                 map.Bind(wx.EVT_TEXT, self.OnVolumeIsosurfMap)
-                gridSizer.Add(item = map, flag = wx.ALIGN_CENTER_VERTICAL,
-                              pos = (row, 2))
+                gridSizer.Add(item=map, flag=wx.ALIGN_CENTER_VERTICAL,
+                              pos=(row, 2))
             else:
                 map = None
-            
+
             if code == 'color':
-                color = UserSettings.Get(group = 'nviz', key = 'volume', subkey = ['color', 'value'])
-                value = csel.ColourSelect(panel, id = wx.ID_ANY,
-                                          colour = color,
-                                          size = globalvar.DIALOG_COLOR_SIZE)
+                color = UserSettings.Get(
+                    group='nviz', key='volume', subkey=[
+                        'color', 'value'])
+                value = csel.ColourSelect(panel, id=wx.ID_ANY,
+                                          colour=color,
+                                          size=globalvar.DIALOG_COLOR_SIZE)
                 value.Bind(csel.EVT_COLOURSELECT, self.OnVolumeIsosurfMap)
                 value.SetName('color')
             elif code == 'mask':
                 value = None
             elif code == 'topo':
-                value = NumTextCtrl(parent = panel, id = wx.ID_ANY, size = (200, -1),
-                            style = wx.TE_PROCESS_ENTER)
+                value = NumTextCtrl(parent=panel, id=wx.ID_ANY, size=(200, -1),
+                                    style=wx.TE_PROCESS_ENTER)
                 value.Bind(wx.EVT_TEXT_ENTER, self.OnVolumeIsosurfMap)
                 value.Bind(wx.EVT_KILL_FOCUS, self.OnVolumeIsosurfMap)
 ##                value.Bind(wx.EVT_TEXT, self.OnVolumeIsosurfMap)
             else:
                 size = (65, -1)
-                value = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = size,
-                                    initial = 0)
+                value = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=size,
+                                    initial=0)
                 if code == 'topo':
-                    value.SetRange(minVal = -1e9, maxVal = 1e9)
+                    value.SetRange(minVal=-1e9, maxVal=1e9)
                 elif code in ('shine', 'transp'):
-                    value.SetRange(minVal = 0, maxVal = 100)
-                
+                    value.SetRange(minVal=0, maxVal=100)
+
                 value.Bind(wx.EVT_SPINCTRL, self.OnVolumeIsosurfMap)
                 value.Bind(wx.EVT_TEXT, self.OnVolumeIsosurfMap)
-            
+
             if value:
                 self.win['volume'][code]['const'] = value.GetId()
                 if code == 'topo':
-                    gridSizer.Add(item = value, flag = wx.ALIGN_CENTER_VERTICAL,
-                                  pos = (row, 2))
+                    gridSizer.Add(item=value, flag=wx.ALIGN_CENTER_VERTICAL,
+                                  pos=(row, 2))
                 else:
                     value.Enable(False)
-                    gridSizer.Add(item = value, flag = wx.ALIGN_CENTER_VERTICAL,
-                                  pos = (row, 3))
+                    gridSizer.Add(item=value, flag=wx.ALIGN_CENTER_VERTICAL,
+                                  pos=(row, 3))
             else:
                 self.win['volume'][code]['const'] = None
-            
+
             if code != 'topo':
-                self.SetMapObjUseMap(nvizType = 'volume',
-                                     attrb = code) # -> enable map / disable constant
-            
+                # -> enable map / disable constant
+                self.SetMapObjUseMap(nvizType='volume', attrb=code)
+
             row += 1
-        
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                     flag = wx.ALL | wx.EXPAND, border = 3)
-        vSizer.Add(item = boxSizer, proportion = 1,
-                     flag = wx.EXPAND, border = 0)
+
+        boxSizer.Add(item=gridSizer, proportion=1,
+                     flag=wx.ALL | wx.EXPAND, border=3)
+        vSizer.Add(item=boxSizer, proportion=1,
+                   flag=wx.EXPAND, border=0)
         panel.SetSizer(vSizer)
-        
+
         return panel
-    
+
     def _createSlicePanel(self, parent):
-        panel = wx.Panel(parent = parent, id = wx.ID_ANY)
-        
+        panel = wx.Panel(parent=parent, id=wx.ID_ANY)
+
         vSizer = wx.BoxSizer(wx.HORIZONTAL)
-        
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                            label = " %s " % (_("Slice attributes")))
+
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % (_("Slice attributes")))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
         hSizer = wx.BoxSizer()
-        
+
         self.win['volume']['slice'] = {}
-        hSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                      label = _("Slice parallel to axis:")), proportion = 0,
-                      flag = wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, border = 3)
-        axes = wx.Choice(parent = panel, id = wx.ID_ANY, size = (65, -1), choices = ("X", "Y", "Z"))
-        hSizer.Add(axes, proportion = 0, flag = wx.ALIGN_LEFT|wx.LEFT, border = 3)
+        hSizer.Add(
+            item=wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_("Slice parallel to axis:")),
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT,
+            border=3)
+        axes = wx.Choice(
+            parent=panel, id=wx.ID_ANY, size=(65, -1),
+            choices=("X", "Y", "Z"))
+        hSizer.Add(axes, proportion=0, flag=wx.ALIGN_LEFT | wx.LEFT, border=3)
         self.win['volume']['slice']['axes'] = axes.GetId()
         axes.Bind(wx.EVT_CHOICE, self.OnVolumeSliceAxes)
-        boxSizer.Add(hSizer, proportion = 0, flag = wx.ALL|wx.EXPAND, border = 3)
-        
-        gridSizer = wx.GridBagSizer(vgap = 3, hgap = 3)
-        
+        boxSizer.Add(hSizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=3)
+
+        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)
+
         # text labels
         for i in range(2):
-            label = wx.StaticText(parent = panel, id = wx.ID_ANY)
+            label = wx.StaticText(parent=panel, id=wx.ID_ANY)
             label.SetName('label_edge_' + str(i))
-            gridSizer.Add(item = label, pos = (0, i + 1),
-                          flag = wx.ALIGN_CENTER)
-        for i in range(2,4):
-            label = wx.StaticText(parent = panel, id = wx.ID_ANY)
+            gridSizer.Add(item=label, pos=(0, i + 1),
+                          flag=wx.ALIGN_CENTER)
+        for i in range(2, 4):
+            label = wx.StaticText(parent=panel, id=wx.ID_ANY)
             label.SetName('label_edge_' + str(i))
-            gridSizer.Add(item = label, pos = (3, i -1),
-                          flag = wx.ALIGN_CENTER)
+            gridSizer.Add(item=label, pos=(3, i - 1),
+                          flag=wx.ALIGN_CENTER)
         for i in range(2):
-            label = wx.StaticText(parent = panel, id = wx.ID_ANY)
+            label = wx.StaticText(parent=panel, id=wx.ID_ANY)
             label.SetName('label_coord_' + str(i))
-            gridSizer.Add(item = label, pos = (i + 1, 0),
-                          flag = wx.ALIGN_CENTER_VERTICAL)
-        label = wx.StaticText(parent = panel, id = wx.ID_ANY)
+            gridSizer.Add(item=label, pos=(i + 1, 0),
+                          flag=wx.ALIGN_CENTER_VERTICAL)
+        label = wx.StaticText(parent=panel, id=wx.ID_ANY)
         label.SetName('label_coord_2')
-        gridSizer.Add(item = label, pos = (4, 0), 
-                          flag = wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(item=label, pos=(4, 0),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
         # sliders
         for i, coord in enumerate(('x1', 'x2')):
-            slider = wx.Slider(parent = panel, id = wx.ID_ANY, minValue = 0, maxValue = 100, value = 0)
+            slider = wx.Slider(
+                parent=panel,
+                id=wx.ID_ANY,
+                minValue=0,
+                maxValue=100,
+                value=0)
             self.win['volume']['slice']['slider_' + coord] = slider.GetId()
             slider.Bind(wx.EVT_SPIN, self.OnSlicePositionChange)
-            slider.Bind(wx.EVT_SCROLL_THUMBRELEASE, self.OnSlicePositionChanged)
-            gridSizer.Add(item = slider, pos = (1, i + 1), 
-                          flag = wx.ALIGN_CENTER|wx.EXPAND)
-                        
+            slider.Bind(
+                wx.EVT_SCROLL_THUMBRELEASE,
+                self.OnSlicePositionChanged)
+            gridSizer.Add(item=slider, pos=(1, i + 1),
+                          flag=wx.ALIGN_CENTER | wx.EXPAND)
+
         for i, coord in enumerate(('y1', 'y2')):
-            slider = wx.Slider(parent = panel, id = wx.ID_ANY, minValue = 0, maxValue = 100, value = 0)
+            slider = wx.Slider(
+                parent=panel,
+                id=wx.ID_ANY,
+                minValue=0,
+                maxValue=100,
+                value=0)
             self.win['volume']['slice']['slider_' + coord] = slider.GetId()
             slider.Bind(wx.EVT_SPIN, self.OnSlicePositionChange)
-            slider.Bind(wx.EVT_SCROLL_THUMBRELEASE, self.OnSlicePositionChanged)
-            gridSizer.Add(item = slider, pos = (2, i + 1), 
-                          flag = wx.ALIGN_CENTER|wx.EXPAND)
-        
+            slider.Bind(
+                wx.EVT_SCROLL_THUMBRELEASE,
+                self.OnSlicePositionChanged)
+            gridSizer.Add(item=slider, pos=(2, i + 1),
+                          flag=wx.ALIGN_CENTER | wx.EXPAND)
+
         for i, coord in enumerate(('z1', 'z2')):
-            slider = wx.Slider(parent = panel, id = wx.ID_ANY, minValue = 0, maxValue = 100, value = 0)
+            slider = wx.Slider(
+                parent=panel,
+                id=wx.ID_ANY,
+                minValue=0,
+                maxValue=100,
+                value=0)
             self.win['volume']['slice']['slider_' + coord] = slider.GetId()
             slider.Bind(wx.EVT_SPIN, self.OnSlicePositionChange)
-            slider.Bind(wx.EVT_SCROLL_THUMBRELEASE, self.OnSlicePositionChanged)
-            gridSizer.Add(item = slider, pos = (4,i+1), 
-                          flag = wx.ALIGN_CENTER|wx.EXPAND)
-                        
-        gridSizer.AddGrowableCol(0,1)
-        gridSizer.AddGrowableCol(1,2)
-        gridSizer.AddGrowableCol(2,2)
-        
-        boxSizer.Add(item = gridSizer, proportion = 1,
-                     flag = wx.ALL | wx.EXPAND, border = 3)
-        
+            slider.Bind(
+                wx.EVT_SCROLL_THUMBRELEASE,
+                self.OnSlicePositionChanged)
+            gridSizer.Add(item=slider, pos=(4, i + 1),
+                          flag=wx.ALIGN_CENTER | wx.EXPAND)
+
+        gridSizer.AddGrowableCol(0, 1)
+        gridSizer.AddGrowableCol(1, 2)
+        gridSizer.AddGrowableCol(2, 2)
+
+        boxSizer.Add(item=gridSizer, proportion=1,
+                     flag=wx.ALL | wx.EXPAND, border=3)
+
         # transparency, reset
         hSizer = wx.BoxSizer()
-        hSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                      label = _("Transparency:")), proportion = 0,
-                      flag = wx.ALIGN_CENTER_VERTICAL|wx.RIGHT|wx.TOP, border = 7)
-        spin = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
-                           min = 0, max = 100, initial = 0)
+        hSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                      label=_("Transparency:")), proportion=0,
+                   flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT | wx.TOP, border=7)
+        spin = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+                           min=0, max=100, initial=0)
         spin.Bind(wx.EVT_SPINCTRL, self.OnSliceTransparency)
         self.win['volume']['slice']['transp'] = spin.GetId()
-        hSizer.Add(item = spin, proportion = 0,
-                      flag = wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.TOP, border = 7)
-                    
-        hSizer.Add(item = wx.Size(-1, -1), proportion = 1,
-                      flag = wx.EXPAND)
-        reset = wx.Button(parent = panel, id = wx.ID_ANY, label = _("Reset"))
+        hSizer.Add(item=spin, proportion=0,
+                   flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.TOP, border=7)
+
+        hSizer.Add(item=wx.Size(-1, -1), proportion=1,
+                   flag=wx.EXPAND)
+        reset = wx.Button(parent=panel, id=wx.ID_ANY, label=_("Reset"))
         reset.Bind(wx.EVT_BUTTON, self.OnSliceReset)
         self.win['volume']['slice']['reset'] = reset.GetId()
-        hSizer.Add(item = reset, proportion = 0,
-                      flag = wx.ALIGN_CENTER_VERTICAL|wx.TOP, border = 7)
-        
-        boxSizer.Add(hSizer, proportion = 0, flag = wx.ALL|wx.EXPAND, border = 3)
+        hSizer.Add(item=reset, proportion=0,
+                   flag=wx.ALIGN_CENTER_VERTICAL | wx.TOP, border=7)
+
+        boxSizer.Add(hSizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=3)
         panel.SetSizer(boxSizer)
-        
+
         return panel
-    
-    def _createControl(self, parent, data, name, range, tooltip = None, bind = (None, None, None),
-                       sliderHor = True, size = 200, floatSlider = False):
+
+    def _createControl(self, parent, data, name, range, tooltip=None, bind=(
+            None, None, None), sliderHor=True, size=200, floatSlider=False):
         """Add control (Slider + TextCtrl)"""
         data[name] = dict()
         if sliderHor:
@@ -2609,88 +3061,86 @@
             style = wx.SL_VERTICAL | wx.SL_AUTOTICKS | \
                 wx.SL_INVERSE
             sizeW = (-1, size)
-        
-        kwargs = dict(parent = parent, id = wx.ID_ANY,
-                           minValue = range[0],
-                           maxValue = range[1],
-                           style = style,
-                           size = sizeW)
+
+        kwargs = dict(parent=parent, id=wx.ID_ANY,
+                      minValue=range[0],
+                      maxValue=range[1],
+                      style=style,
+                      size=sizeW)
         if floatSlider:
             slider = FloatSlider(**kwargs)
         else:
             slider = wx.Slider(**kwargs)
-            
+
         slider.SetName('slider')
         if bind[0]:
-            #EVT_SCROLL emits event after slider is released, EVT_SPIN not
+            # EVT_SCROLL emits event after slider is released, EVT_SPIN not
             slider.Bind(wx.EVT_SPIN, bind[0])
-        
+
         if bind[1]:
-            slider.Bind(wx.EVT_SCROLL_THUMBRELEASE, bind[1]) 
+            slider.Bind(wx.EVT_SCROLL_THUMBRELEASE, bind[1])
         data[name]['slider'] = slider.GetId()
-        
-        text = NumTextCtrl(parent = parent, id = wx.ID_ANY, size = (65, -1),
-                            style = wx.TE_PROCESS_ENTER)
-        
+
+        text = NumTextCtrl(parent=parent, id=wx.ID_ANY, size=(65, -1),
+                           style=wx.TE_PROCESS_ENTER)
+
         text.SetName('text')
         if tooltip:
             text.SetToolTipString(tooltip)
         if bind[2]:
             text.Bind(wx.EVT_TEXT_ENTER, bind[2])
             text.Bind(wx.EVT_KILL_FOCUS, bind[2])
-        
+
         data[name]['text'] = text.GetId()
-        
+
     def _createCompass(self, panel, sizer, type):
         """Create 'compass' widget for light and view page"""
-        w = wx.Button(panel, id = wx.ID_ANY, label = _("W"))
-        n = wx.Button(panel, id = wx.ID_ANY, label = _("N"))
-        s = wx.Button(panel, id = wx.ID_ANY, label = _("S"))
-        e = wx.Button(panel, id = wx.ID_ANY, label = _("E"))
-        nw = wx.Button(panel, id = wx.ID_ANY, label = _("NW"))
-        ne = wx.Button(panel, id = wx.ID_ANY, label = _("NE"))
-        se = wx.Button(panel, id = wx.ID_ANY, label = _("SE"))
-        sw = wx.Button(panel, id = wx.ID_ANY, label = _("SW"))
+        w = wx.Button(panel, id=wx.ID_ANY, label=_("W"))
+        n = wx.Button(panel, id=wx.ID_ANY, label=_("N"))
+        s = wx.Button(panel, id=wx.ID_ANY, label=_("S"))
+        e = wx.Button(panel, id=wx.ID_ANY, label=_("E"))
+        nw = wx.Button(panel, id=wx.ID_ANY, label=_("NW"))
+        ne = wx.Button(panel, id=wx.ID_ANY, label=_("NE"))
+        se = wx.Button(panel, id=wx.ID_ANY, label=_("SE"))
+        sw = wx.Button(panel, id=wx.ID_ANY, label=_("SW"))
         padding = 15
         if sys.platform == 'darwin':
             padding = 20
         minWidth = sw.GetTextExtent(sw.GetLabel())[0] + padding
         for win, name in zip((w, n, s, e, nw, ne, se, sw),
-                        ('w', 'n', 's', 'e', 'nw', 'ne', 'se', 'sw')):
+                             ('w', 'n', 's', 'e', 'nw', 'ne', 'se', 'sw')):
             win.SetMinSize((minWidth, -1))
             win.Bind(wx.EVT_BUTTON, self.OnLookFrom)
             win.SetName(type + '_' + name)
-        sizer.Add(item = nw, pos = (0, 0), flag = wx.ALIGN_CENTER)
-        sizer.Add(item = n, pos = (0, 1), flag = wx.ALIGN_CENTER)
-        sizer.Add(item = ne, pos = (0, 2), flag = wx.ALIGN_CENTER)
-        sizer.Add(item = e, pos = (1, 2), flag = wx.ALIGN_CENTER)
-        sizer.Add(item = se, pos = (2, 2), flag = wx.ALIGN_CENTER)
-        sizer.Add(item = s, pos = (2, 1), flag = wx.ALIGN_CENTER)
-        sizer.Add(item = sw, pos = (2, 0), flag = wx.ALIGN_CENTER)
-        sizer.Add(item = w, pos = (1, 0), flag = wx.ALIGN_CENTER)
-        
-        
-        
+        sizer.Add(item=nw, pos=(0, 0), flag=wx.ALIGN_CENTER)
+        sizer.Add(item=n, pos=(0, 1), flag=wx.ALIGN_CENTER)
+        sizer.Add(item=ne, pos=(0, 2), flag=wx.ALIGN_CENTER)
+        sizer.Add(item=e, pos=(1, 2), flag=wx.ALIGN_CENTER)
+        sizer.Add(item=se, pos=(2, 2), flag=wx.ALIGN_CENTER)
+        sizer.Add(item=s, pos=(2, 1), flag=wx.ALIGN_CENTER)
+        sizer.Add(item=sw, pos=(2, 0), flag=wx.ALIGN_CENTER)
+        sizer.Add(item=w, pos=(1, 0), flag=wx.ALIGN_CENTER)
+
     def __GetWindowName(self, data, id):
         for name in data.iterkeys():
-            if type(data[name]) is type({}):
+            if isinstance(data[name], type({})):
                 for win in data[name].itervalues():
                     if win == id:
                         return name
             else:
                 if data[name] == id:
                     return name
-        
+
         return None
 
     def UpdateSettings(self):
-        """Update view from settings values 
+        """Update view from settings values
         stored in self.mapWindow.view dictionary"""
         for control in ('height',
                         'persp',
                         'twist',
                         'z-exag'):
-            for win in self.win['view'][control].itervalues():             
+            for win in self.win['view'][control].itervalues():
                 try:
                     if control == 'height':
                         value = int(self.mapWindow.iview[control]['value'])
@@ -2698,157 +3148,162 @@
                         value = self.mapWindow.view[control]['value']
                 except KeyError:
                     value = -1
-                        
+
                 self.FindWindowById(win).SetValue(value)
-        
+
         viewWin = self.FindWindowById(self.win['view']['position'])
         x, y = viewWin.UpdatePos(self.mapWindow.view['position']['x'],
                                  self.mapWindow.view['position']['y'])
-        viewWin.Draw(pos = (x, y), scale = True)
+        viewWin.Draw(pos=(x, y), scale=True)
         viewWin.Refresh(False)
-        
-        color = self._getColorString(self.mapWindow.view['background']['color'])
+
+        color = self._getColorString(
+            self.mapWindow.view['background']['color'])
         self._display.SetBgColor(str(color))
-        
+
         self.Update()
-        
-        self.mapWindow.Refresh(eraseBackground = False)
+
+        self.mapWindow.Refresh(eraseBackground=False)
         self.mapWindow.render['quick'] = False
         self.mapWindow.Refresh(True)
-        
+
     def OnShowLightModel(self, event):
         """Show light model"""
         self._display.showLight = event.IsChecked()
         self._display.DrawLightingModel()
-        
+
     def OnLightChange(self, event):
         """Position of the light changing"""
         winName = self.__GetWindowName(self.win['light'], event.GetId())
         if not winName:
             return
-        
+
         value = self.FindWindowById(event.GetId()).GetValue()
-        
+
         self.mapWindow.light['position']['z'] = value
         for win in self.win['light'][winName].itervalues():
             self.FindWindowById(win).SetValue(value)
-            
+
         self.PostLightEvent()
-        
+
         event.Skip()
-        
+
     def OnLightChanged(self, event):
         """Light changed"""
-        self.PostLightEvent(refresh = True)
-        
+        self.PostLightEvent(refresh=True)
+
     def OnLightColor(self, event):
         """Color of the light changed"""
         self.mapWindow.light['color'] = tuple(event.GetValue())
-        
-        self.PostLightEvent(refresh = True)
-        
+
+        self.PostLightEvent(refresh=True)
+
         event.Skip()
-        
+
     def OnLightValue(self, event):
         """Light brightness/ambient changing"""
         data = self.mapWindow.light
         self.OnScroll(event, self.win['light'], data)
-        
+
         self.PostLightEvent()
         event.Skip()
-        
+
     def OnBgColor(self, event):
         """Background color changed"""
         color = event.GetValue()
         self.mapWindow.view['background']['color'] = tuple(color)
         color = str(color[0]) + ':' + str(color[1]) + ':' + str(color[2])
         self._display.SetBgColor(str(color))
-        
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-        
+
     def OnSetSurface(self, event):
         """Surface selected, currently used for fringes"""
         name = event.GetString()
         try:
-            data = self._getLayerPropertiesByName(name, mapType = 'raster')['surface']
+            data = self._getLayerPropertiesByName(
+                name, mapType='raster')['surface']
         except:
             self.EnablePage('fringe', False)
             return
-        
-        layer = self._getMapLayerByName(name, mapType = 'raster')
+
+        layer = self._getMapLayerByName(name, mapType='raster')
         self.EnablePage('fringe', True)
-        
+
     def OnSetRaster(self, event):
         """Raster map selected, update surface page"""
         name = event.GetString()
         try:
-            data = self._getLayerPropertiesByName(name, mapType = 'raster')['surface']
+            data = self._getLayerPropertiesByName(
+                name, mapType='raster')['surface']
         except TypeError as e:
             self.EnablePage('surface', False)
             return
 
-        layer = self._getMapLayerByName(name, mapType = 'raster')
+        layer = self._getMapLayerByName(name, mapType='raster')
         self.EnablePage('surface', True)
-        self.UpdateSurfacePage(layer, data, updateName = False)
-        
+        self.UpdateSurfacePage(layer, data, updateName=False)
+
     def OnSetVector(self, event):
         """Vector map selected, update properties page"""
         name = event.GetString()
         try:
-            data = self._getLayerPropertiesByName(name, mapType = 'vector')['vector']
+            data = self._getLayerPropertiesByName(
+                name, mapType='vector')['vector']
         except:
             self.EnablePage('vector', False)
             return
-        layer = self._getMapLayerByName(name, mapType = 'vector')
+        layer = self._getMapLayerByName(name, mapType='vector')
         self.EnablePage('vector', True)
-        self.UpdateVectorPage(layer, data, updateName = False)
+        self.UpdateVectorPage(layer, data, updateName=False)
 
     def OnSetRaster3D(self, event):
         """3D Raster map selected, update surface page"""
         name = event.GetString()
         try:
-            data = self._getLayerPropertiesByName(name, mapType = 'raster_3d')['volume']
+            data = self._getLayerPropertiesByName(
+                name, mapType='raster_3d')['volume']
         except:
             self.EnablePage('volume', False)
             return
-        
-        layer = self._getMapLayerByName(name, mapType = 'raster_3d')
+
+        layer = self._getMapLayerByName(name, mapType='raster_3d')
         self.EnablePage('volume', True)
-        self.UpdateVolumePage(layer, data, updateName = False)
-        
+        self.UpdateVolumePage(layer, data, updateName=False)
+
     def OnViewChange(self, event):
         """Change view, render in quick mode"""
         # find control
         winName = self.__GetWindowName(self.win['view'], event.GetId())
         if not winName:
             return
-        
+
         value = self.FindWindowById(event.GetId()).GetValue()
         slider = self.FindWindowById(self.win['view'][winName]['slider'])
 
         if winName == 'persp' and not (0 <= value <= 180):
             return
 
-        self.AdjustSliderRange(slider = slider, value = value)
-        
+        self.AdjustSliderRange(slider=slider, value=value)
+
         if winName == 'height':
-            view = self.mapWindow.iview # internal
+            view = self.mapWindow.iview  # internal
         else:
             view = self.mapWindow.view
-        
+
         if winName == 'z-exag' and value >= 0:
-            self.PostViewEvent(zExag = True)
+            self.PostViewEvent(zExag=True)
         else:
-            self.PostViewEvent(zExag = False)
-        
+            self.PostViewEvent(zExag=False)
+
         if winName in ('persp', 'twist'):
             convert = int
         else:
             convert = float
-        
+
         view[winName]['value'] = convert(value)
-            
+
         for win in self.win['view'][winName].itervalues():
             self.FindWindowById(win).SetValue(value)
 
@@ -2856,28 +3311,28 @@
         self.mapWindow.render['quick'] = True
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-        
+
         event.Skip()
-        
+
     def OnViewChanged(self, event):
         """View changed, render in full resolution"""
         self.mapWindow.render['quick'] = False
         self.mapWindow.Refresh(False)
         self.UpdateSettings()
-        try:# when calling event = None
+        try:  # when calling event = None
             event.Skip()
         except AttributeError:
             pass
-            
+
     def OnViewChangedText(self, event):
         """View changed, render in full resolution"""
         self.mapWindow.render['quick'] = False
         self.OnViewChange(event)
         self.OnViewChanged(None)
         self.Update()
-        
+
         event.Skip()
-    
+
     def OnLookAt(self, event):
         """Look here/center"""
         name = self.FindWindowById(event.GetId()).GetName()
@@ -2890,10 +3345,10 @@
         elif name == 'top':
             self.mapWindow.view['position']['x'] = 0.5
             self.mapWindow.view['position']['y'] = 0.5
-            self.PostViewEvent(zExag = True)
+            self.PostViewEvent(zExag=True)
             self.UpdateSettings()
             self.mapWindow.Refresh(False)
-        else: # here
+        else:  # here
             if self.FindWindowById(event.GetId()).GetValue():
                 self.mapDisplay.Raise()
                 self.mapWindow.mouse['use'] = 'lookHere'
@@ -2901,36 +3356,36 @@
             else:
                 self.mapWindow.mouse['use'] = 'default'
                 self.mapWindow.SetNamedCursor('default')
-            
+
     def OnResetView(self, event):
         """Reset to default view (view page)"""
         self.mapWindow.ResetView()
         self.UpdateSettings()
         self.mapWindow.Refresh(False)
-        
+
     def OnResetSurfacePosition(self, event):
         """Reset position of surface"""
-        
+
         for win in self.win['surface']['position'].itervalues():
             if win == self.win['surface']['position']['axis']:
-                self.FindWindowById(win).SetSelection(2) # Z
+                self.FindWindowById(win).SetSelection(2)  # Z
             elif win == self.win['surface']['position']['reset']:
                 continue
             else:
                 self.FindWindowById(win).SetValue(0)
-                
+
         data = self.GetLayerData('surface')
         data['surface']['position']['x'] = 0
         data['surface']['position']['y'] = 0
         data['surface']['position']['z'] = 0
         data['surface']['position']['update'] = None
         # update properties
-        event = wxUpdateProperties(data = data)
+        event = wxUpdateProperties(data=data)
         wx.PostEvent(self.mapWindow, event)
-        
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-            
+
     def OnLookFrom(self, event):
         """Position of view/light changed by buttons"""
         name = self.FindWindowById(event.GetId()).GetName()
@@ -2941,40 +3396,40 @@
         else:
             type = 'light'
             data = self.mapWindow.light
-        if buttonName == 'n': # north
+        if buttonName == 'n':  # north
             data['position']['x'] = 0.5
             data['position']['y'] = 0.0
-        elif buttonName == 's': # south
+        elif buttonName == 's':  # south
             data['position']['x'] = 0.5
             data['position']['y'] = 1.0
-        elif buttonName == 'e': # east
+        elif buttonName == 'e':  # east
             data['position']['x'] = 1.0
             data['position']['y'] = 0.5
-        elif buttonName =='w': # west
+        elif buttonName == 'w':  # west
             data['position']['x'] = 0.0
             data['position']['y'] = 0.5
-        elif buttonName == 'nw': # north-west
+        elif buttonName == 'nw':  # north-west
             data['position']['x'] = 0.0
             data['position']['y'] = 0.0
-        elif buttonName == 'ne': # north-east
+        elif buttonName == 'ne':  # north-east
             data['position']['x'] = 1.0
             data['position']['y'] = 0.0
-        elif buttonName == 'se': # south-east
+        elif buttonName == 'se':  # south-east
             data['position']['x'] = 1.0
             data['position']['y'] = 1.0
-        elif buttonName == 'sw': # south-west
+        elif buttonName == 'sw':  # south-west
             data['position']['x'] = 0.0
             data['position']['y'] = 1.0
-        if type == 'view':    
-            self.PostViewEvent(zExag = True)
-            
+        if type == 'view':
+            self.PostViewEvent(zExag=True)
+
             self.UpdateSettings()
         else:
             self.PostLightEvent()
             lightWin = self.FindWindowById(self.win['light']['position'])
             x, y = lightWin.UpdatePos(self.mapWindow.light['position']['x'],
-                                     self.mapWindow.light['position']['y'])
-            lightWin.Draw(pos = (x, y), scale = True)
+                                      self.mapWindow.light['position']['y'])
+            lightWin.Draw(pos=(x, y), scale=True)
             lightWin.Refresh(False)
         self.mapWindow.render['quick'] = False
         self.mapWindow.Refresh(False)
@@ -2983,9 +3438,9 @@
         """Set surface attribute -- use -- map/constant"""
         if not self.mapWindow.init:
             return
-        
+
         wx.Yield()
-        
+
         # find attribute row
         attrb = self.__GetWindowName(self.win['surface'], event.GetId())
         if not attrb:
@@ -2993,256 +3448,287 @@
             nvizType = 'volume'
         else:
             nvizType = 'surface'
-        
+
         selection = event.GetSelection()
-        if self.win[nvizType][attrb]['required']: # no 'unset'
+        if self.win[nvizType][attrb]['required']:  # no 'unset'
             selection += 1
-        if selection == 0: # unset
+        if selection == 0:  # unset
             useMap = None
             value = ''
-        elif selection == 1: # map
+        elif selection == 1:  # map
             useMap = True
-            value = self.FindWindowById(self.win[nvizType][attrb]['map']).GetValue()
-        elif selection == 2: # constant
+            value = self.FindWindowById(
+                self.win[nvizType][attrb]['map']).GetValue()
+        elif selection == 2:  # constant
             useMap = False
             if attrb == 'color':
-                value = self.FindWindowById(self.win[nvizType][attrb]['const']).GetColour()
+                value = self.FindWindowById(
+                    self.win[nvizType][attrb]['const']).GetColour()
                 value = self._getColorString(value)
             else:
-                value = self._getPercent(self.FindWindowById(self.win[nvizType][attrb]['const']).GetValue(), toPercent = False)
-        
-        self.SetMapObjUseMap(nvizType = nvizType,
-                             attrb = attrb, map = useMap)
-        
+                value = self._getPercent(
+                    self.FindWindowById(
+                        self.win[nvizType][attrb]['const']).GetValue(),
+                    toPercent=False)
+
+        self.SetMapObjUseMap(nvizType=nvizType,
+                             attrb=attrb, map=useMap)
+
         name = self.FindWindowById(self.win[nvizType]['map']).GetValue()
         if nvizType == 'surface':
-            data = self._getLayerPropertiesByName(name, mapType = 'raster')
-            data[nvizType]['attribute'][attrb] = { 'map' : useMap,
-                                                   'value' : str(value),
-                                                   'update' : None }
-        else: # volume / isosurface
-            data = self._getLayerPropertiesByName(name, mapType = 'raster_3d')
+            data = self._getLayerPropertiesByName(name, mapType='raster')
+            data[nvizType]['attribute'][attrb] = {'map': useMap,
+                                                  'value': str(value),
+                                                  'update': None}
+        else:  # volume / isosurface
+            data = self._getLayerPropertiesByName(name, mapType='raster_3d')
             list = self.FindWindowById(self.win['volume']['isosurfs'])
             id = list.GetSelection()
             if id != -1:
-                data[nvizType]['isosurface'][id][attrb] = { 'map' : useMap,
-                                                            'value' : str(value),
-                                                            'update' : None }
-        
+                data[nvizType]['isosurface'][id][attrb] = {'map': useMap,
+                                                           'value': str(value),
+                                                           'update': None}
+
         # update properties
-        event = wxUpdateProperties(data = data)
+        event = wxUpdateProperties(data=data)
         wx.PostEvent(self.mapWindow, event)
-        
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
- 
-    def EnablePage(self, name, enabled = True):
+
+    def EnablePage(self, name, enabled=True):
         """Enable/disable all widgets on page"""
         for key, item in self.win[name].iteritems():
-            if key in ('map', 'surface', 'new','planes'):
+            if key in ('map', 'surface', 'new', 'planes'):
                 continue
-            if type(item) == types.DictType:
+            if isinstance(item, types.DictType):
                 for skey, sitem in self.win[name][key].iteritems():
-                    if type(sitem) == types.DictType:
+                    if isinstance(sitem, types.DictType):
                         for ssitem in self.win[name][key][skey].itervalues():
-                            if type(ssitem) == types.IntType:
+                            if isinstance(ssitem, types.IntType):
                                 self.FindWindowById(ssitem).Enable(enabled)
                     else:
-                        if type(sitem) == types.IntType:
+                        if isinstance(sitem, types.IntType):
                             self.FindWindowById(sitem).Enable(enabled)
             else:
-                if type(item) == types.IntType:
+                if isinstance(item, types.IntType):
                     self.FindWindowById(item).Enable(enabled)
-        
-    def SetMapObjUseMap(self, nvizType, attrb, map = None):
+
+    def SetMapObjUseMap(self, nvizType, attrb, map=None):
         """Update dialog widgets when attribute type changed"""
         if attrb in ('topo', 'color', 'shine'):
-            incSel = -1 # decrement selection (no 'unset')
+            incSel = -1  # decrement selection (no 'unset')
         else:
             incSel = 0
         if nvizType == 'volume' and attrb == 'topo':
             return
-        if map is True: # map
-            if attrb != 'topo': # changing map topography not allowed
-                # not sure why, but here must be disabled both ids, should be fixed!
-                self.FindWindowById(self.win[nvizType][attrb]['map']).Enable(True)
+        if map is True:  # map
+            if attrb != 'topo':  # changing map topography not allowed
+                # not sure why, but here must be disabled both ids, should be
+                # fixed!
+                self.FindWindowById(
+                    self.win[nvizType][attrb]['map']).Enable(True)
             if self.win[nvizType][attrb]['const']:
-                self.FindWindowById(self.win[nvizType][attrb]['const']).Enable(False)
-            self.FindWindowById(self.win[nvizType][attrb]['use']).SetSelection(1 + incSel)
-        elif map is False: # const
+                self.FindWindowById(
+                    self.win[nvizType][attrb]['const']).Enable(False)
+            self.FindWindowById(
+                self.win[nvizType][attrb]['use']).SetSelection(
+                1 + incSel)
+        elif map is False:  # const
             self.FindWindowById(self.win[nvizType][attrb]['map']).Enable(False)
             if self.win[nvizType][attrb]['const']:
-                self.FindWindowById(self.win[nvizType][attrb]['const']).Enable(True)
-            self.FindWindowById(self.win[nvizType][attrb]['use']).SetSelection(2 + incSel)
-        else: # unset
-            self.FindWindowById(self.win[nvizType][attrb]['use']).SetSelection(0)
+                self.FindWindowById(
+                    self.win[nvizType][attrb]['const']).Enable(True)
+            self.FindWindowById(
+                self.win[nvizType][attrb]['use']).SetSelection(
+                2 + incSel)
+        else:  # unset
+            self.FindWindowById(
+                self.win[nvizType][attrb]['use']).SetSelection(0)
             self.FindWindowById(self.win[nvizType][attrb]['map']).Enable(False)
             if self.win[nvizType][attrb]['const']:
-                self.FindWindowById(self.win[nvizType][attrb]['const']).Enable(False)
-            
-        
+                self.FindWindowById(
+                    self.win[nvizType][attrb]['const']).Enable(False)
+
     def OnSurfaceMap(self, event):
         """Set surface attribute"""
         if self.vetoGSelectEvt:
             self.vetoGSelectEvt = False
             return
-        self.SetMapObjAttrb(nvizType = 'surface', winId = event.GetId())
-        
+        self.SetMapObjAttrb(nvizType='surface', winId=event.GetId())
+
     def SetMapObjAttrb(self, nvizType, winId):
         """Set map object (surface/isosurface) attribute (map/constant)"""
         if not self.mapWindow.init:
             return
-        
+
         attrb = self.__GetWindowName(self.win[nvizType], winId)
         if not attrb:
             return
-        
+
         if not (nvizType == 'volume' and attrb == 'topo'):
-            selection = self.FindWindowById(self.win[nvizType][attrb]['use']).GetSelection()
+            selection = self.FindWindowById(
+                self.win[nvizType][attrb]['use']).GetSelection()
             if self.win[nvizType][attrb]['required']:
                 selection += 1
 
-            if selection == 0: # unset
+            if selection == 0:  # unset
                 useMap = None
                 value = ''
-            elif selection == 1: # map
-                value = self.FindWindowById(self.win[nvizType][attrb]['map']).GetValue()
+            elif selection == 1:  # map
+                value = self.FindWindowById(
+                    self.win[nvizType][attrb]['map']).GetValue()
                 useMap = True
-            else: # constant
+            else:  # constant
                 if attrb == 'color':
-                    value = self.FindWindowById(self.win[nvizType][attrb]['const']).GetColour()
+                    value = self.FindWindowById(
+                        self.win[nvizType][attrb]['const']).GetColour()
                     # tuple to string
                     value = self._getColorString(value)
                 else:
                     value = self._getPercent(
-                        self.FindWindowById(self.win[nvizType][attrb]['const']).GetValue(), toPercent = False)
-                    
+                        self.FindWindowById(
+                            self.win[nvizType][attrb]['const']).GetValue(),
+                        toPercent=False)
+
                 useMap = False
         else:
             useMap = None
-            value = self.FindWindowById(self.win[nvizType][attrb]['const']).GetValue()
+            value = self.FindWindowById(
+                self.win[nvizType][attrb]['const']).GetValue()
         if not self.pageChanging:
             name = self.FindWindowById(self.win[nvizType]['map']).GetValue()
             if nvizType == 'surface':
-                data = self._getLayerPropertiesByName(name, mapType = 'raster')
-                data[nvizType]['attribute'][attrb] = { 'map' : useMap,
-                                                       'value' : str(value),
-                                                       'update' : None }
+                data = self._getLayerPropertiesByName(name, mapType='raster')
+                data[nvizType]['attribute'][attrb] = {'map': useMap,
+                                                      'value': str(value),
+                                                      'update': None}
             else:
-                data = self._getLayerPropertiesByName(name, mapType = 'raster_3d')
+                data = self._getLayerPropertiesByName(
+                    name, mapType='raster_3d')
                 list = self.FindWindowById(self.win['volume']['isosurfs'])
                 id = list.GetSelection()
                 if id > -1:
-                    data[nvizType]['isosurface'][id][attrb] = { 'map' : useMap,
-                                                                'value' : str(value),
-                                                                'update' : None }
+                    data[nvizType]['isosurface'][id][attrb] = {
+                        'map': useMap, 'value': str(value), 'update': None}
                     if attrb == 'topo':
-                        list = self.FindWindowById(self.win['volume']['isosurfs'])
+                        list = self.FindWindowById(
+                            self.win['volume']['isosurfs'])
                         sel = list.GetSelection()
                         list.SetString(sel, "%s %s" % (_("Level"), str(value)))
                         list.Check(sel)
-            
+
             # update properties
-            event = wxUpdateProperties(data = data)
+            event = wxUpdateProperties(data=data)
             wx.PostEvent(self.mapWindow, event)
-            
+
             if self.mapDisplay.IsAutoRendered():
                 self.mapWindow.Refresh(False)
-        
+
     def OnSurfaceResolution(self, event):
         """Draw resolution changed"""
         self.SetSurfaceResolution()
-        
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-    
 
     def SetSurfaceResolution(self):
         """Set draw resolution"""
-        coarse = self.FindWindowById(self.win['surface']['draw']['res-coarse']).GetValue()
-        fine = self.FindWindowById(self.win['surface']['draw']['res-fine']).GetValue()
-        
+        coarse = self.FindWindowById(
+            self.win['surface']['draw']['res-coarse']).GetValue()
+        fine = self.FindWindowById(
+            self.win['surface']['draw']['res-fine']).GetValue()
+
         data = self.GetLayerData('surface')
-        data['surface']['draw']['resolution'] = { 'coarse' : coarse,
-                                                  'fine' : fine,
-                                                  'update' : None }
-        
+        data['surface']['draw']['resolution'] = {'coarse': coarse,
+                                                 'fine': fine,
+                                                 'update': None}
+
         # update properties
-        event = wxUpdateProperties(data = data)
+        event = wxUpdateProperties(data=data)
         wx.PostEvent(self.mapWindow, event)
-        
+
     def SetSurfaceMode(self):
         """Set draw mode"""
-        mode = self.FindWindowById(self.win['surface']['draw']['mode']).GetSelection()
-        style = self.FindWindowById(self.win['surface']['draw']['style']).GetSelection()
-        if style == 0: # wire
-            self.FindWindowById(self.win['surface']['draw']['wire-color']).Enable(True)
-        elif style == 1: # surface
-            self.FindWindowById(self.win['surface']['draw']['wire-color']).Enable(False)
-        
-        shade = self.FindWindowById(self.win['surface']['draw']['shading']).GetSelection()
-        
-        value, desc = self.mapWindow.nvizDefault.GetDrawMode(mode, style, shade)
-        
+        mode = self.FindWindowById(
+            self.win['surface']['draw']['mode']).GetSelection()
+        style = self.FindWindowById(
+            self.win['surface']['draw']['style']).GetSelection()
+        if style == 0:  # wire
+            self.FindWindowById(self.win['surface']['draw'][
+                                'wire-color']).Enable(True)
+        elif style == 1:  # surface
+            self.FindWindowById(self.win['surface']['draw'][
+                                'wire-color']).Enable(False)
+
+        shade = self.FindWindowById(
+            self.win['surface']['draw']['shading']).GetSelection()
+
+        value, desc = self.mapWindow.nvizDefault.GetDrawMode(
+            mode, style, shade)
+
         return value, desc
 
     def OnSurfaceMode(self, event):
         """Set draw mode"""
         value, desc = self.SetSurfaceMode()
-        
+
         data = self.GetLayerData('surface')
-        data['surface']['draw']['mode'] = { 'value' : value,
-                                            'desc' : desc,
-                                            'update' : None }
-        
+        data['surface']['draw']['mode'] = {'value': value,
+                                           'desc': desc,
+                                           'update': None}
+
         # update properties
-        event = wxUpdateProperties(data = data)
+        event = wxUpdateProperties(data=data)
         wx.PostEvent(self.mapWindow, event)
-        
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
 
     def OnSurfaceModeAll(self, event):
         """Set draw mode (including wire color) for all loaded surfaces"""
         value, desc = self.SetSurfaceMode()
-        coarse = self.FindWindowById(self.win['surface']['draw']['res-coarse']).GetValue()
-        fine = self.FindWindowById(self.win['surface']['draw']['res-fine']).GetValue()
-        color = self.FindWindowById(self.win['surface']['draw']['wire-color']).GetColour()
+        coarse = self.FindWindowById(
+            self.win['surface']['draw']['res-coarse']).GetValue()
+        fine = self.FindWindowById(
+            self.win['surface']['draw']['res-fine']).GetValue()
+        color = self.FindWindowById(
+            self.win['surface']['draw']['wire-color']).GetColour()
         cvalue = self._getColorString(color)
-        
-        for name in self.mapWindow.GetLayerNames(type = 'raster'):
-            
-            data = self._getLayerPropertiesByName(name, mapType = 'raster')
+
+        for name in self.mapWindow.GetLayerNames(type='raster'):
+
+            data = self._getLayerPropertiesByName(name, mapType='raster')
             if not data:
-                continue # shouldy no happen
-            
+                continue  # shouldy no happen
+
             data['surface']['draw']['all'] = True
-            data['surface']['draw']['mode'] = { 'value' : value,
-                                                'desc' : desc,
-                                                'update' : None }
-            data['surface']['draw']['resolution'] = { 'coarse' : coarse,
-                                                      'fine' : fine,
-                                                      'update' : None }
-            data['surface']['draw']['wire-color'] = { 'value' : cvalue,
-                                                      'update' : None }
-            
+            data['surface']['draw']['mode'] = {'value': value,
+                                               'desc': desc,
+                                               'update': None}
+            data['surface']['draw']['resolution'] = {'coarse': coarse,
+                                                     'fine': fine,
+                                                     'update': None}
+            data['surface']['draw']['wire-color'] = {'value': cvalue,
+                                                     'update': None}
+
             # update properties
-            event = wxUpdateProperties(data = data)
+            event = wxUpdateProperties(data=data)
             wx.PostEvent(self.mapWindow, event)
-            
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-        
+
     def _getColorString(self, color):
         """Convert color tuple to R:G:B format
 
         :param color: tuple
-        
+
         :return: string R:G:B
         """
         return str(color[0]) + ':' + str(color[1]) + ':' + str(color[2])
-    
-    def _getColorFromString(self, color, delim = ':'):
+
+    def _getColorFromString(self, color, delim=':'):
         """Convert color string (R:G:B) to wx.Colour
 
         :param color: string
@@ -3251,111 +3737,113 @@
         :return: wx.Colour instance
         """
         return wx.Colour(*map(int, color.split(delim)))
-    
+
     def _get3dRange(self, name):
         """Gelper func for getting range of 3d map"""
-        ret = RunCommand('r3.info', read = True, flags = 'r', map = name)
+        ret = RunCommand('r3.info', read=True, flags='r', map=name)
         if ret:
             range = []
             for value in ret.strip('\n').split('\n'):
                 range.append(float(value.split('=')[1]))
             return range
-        
+
         return -1e6, 1e6
-    
-    def _getPercent(self, value, toPercent = True):
+
+    def _getPercent(self, value, toPercent=True):
         """Convert values 0 - 255 to percents and vice versa"""
         value = int(value)
         if toPercent:
-            value = int(value/255. * 100)
+            value = int(value / 255. * 100)
         else:
-            value = int(value/100. * 255)
+            value = int(value / 100. * 255)
         return value
-    
+
     def OnSurfaceWireColor(self, event):
         """Set wire color"""
         data = self.GetLayerData('surface')
         value = self._getColorString(event.GetValue())
-        data['surface']['draw']['wire-color'] = { 'value' : value,
-                                                  'update' : None }
-        
+        data['surface']['draw']['wire-color'] = {'value': value,
+                                                 'update': None}
+
         # update properties
-        event = wxUpdateProperties(data = data)
+        event = wxUpdateProperties(data=data)
         wx.PostEvent(self.mapWindow, event)
-        
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-        
+
     def OnSurfaceAxis(self, event):
         """Surface position, axis changed"""
         data = self.GetLayerData('surface')
         id = data['surface']['object']['id']
-        
-        axis = self.FindWindowById(self.win['surface']['position']['axis']).GetSelection()
+
+        axis = self.FindWindowById(
+            self.win['surface']['position']['axis']).GetSelection()
         slider = self.FindWindowById(self.win['surface']['position']['slider'])
         text = self.FindWindowById(self.win['surface']['position']['text'])
         xydim = self._display.GetLongDim()
         zdim = self._display.GetZRange()
         zdim = zdim[1] - zdim[0]
-        
+
         x, y, z = self._display.GetSurfacePosition(id)
-        
-        if axis == 0: # x
+
+        if axis == 0:  # x
             slider.SetRange(-3 * xydim, 3 * xydim)
             slider.SetValue(x)
             text.SetValue(x)
-        elif axis == 1: # y
+        elif axis == 1:  # y
             slider.SetRange(-3 * xydim, 3 * xydim)
             slider.SetValue(y)
             text.SetValue(y)
-        else: # z
+        else:  # z
             slider.SetRange(-3 * zdim, 3 * zdim)
             slider.SetValue(z)
             text.SetValue(z)
-        
+
     def OnSurfacePosition(self, event):
         """Surface position"""
         winName = self.__GetWindowName(self.win['surface'], event.GetId())
         if not winName:
             return
-        axis = self.FindWindowById(self.win['surface']['position']['axis']).GetSelection()
-        
+        axis = self.FindWindowById(
+            self.win['surface']['position']['axis']).GetSelection()
+
         value = self.FindWindowById(event.GetId()).GetValue()
         slider = self.FindWindowById(self.win['surface'][winName]['slider'])
-        self.AdjustSliderRange(slider = slider, value = value)
-        
+        self.AdjustSliderRange(slider=slider, value=value)
+
         for win in self.win['surface']['position'].itervalues():
             if win in (self.win['surface']['position']['axis'],
                        self.win['surface']['position']['reset']):
                 continue
             else:
                 self.FindWindowById(win).SetValue(value)
-        
+
         data = self.GetLayerData('surface')
         id = data['surface']['object']['id']
         x, y, z = self._display.GetSurfacePosition(id)
-        
-        if axis == 0: # x
+
+        if axis == 0:  # x
             x = value
-        elif axis == 1: # y
+        elif axis == 1:  # y
             y = value
-        else: # z
+        else:  # z
             z = value
-        
+
         data['surface']['position']['x'] = x
         data['surface']['position']['y'] = y
         data['surface']['position']['z'] = z
         data['surface']['position']['update'] = None
         # update properties
-        
-        event = wxUpdateProperties(data = data)
+
+        event = wxUpdateProperties(data=data)
         wx.PostEvent(self.mapWindow, event)
-        
+
         self.mapWindow.render['quick'] = True
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
         #        self.UpdatePage('surface')
-        
+
     def OnSurfacePositionChanged(self, event):
         """Surface position changed"""
         self.mapWindow.render['quick'] = False
@@ -3365,158 +3853,176 @@
         """Surface position changed by textctrl"""
         self.OnSurfacePosition(event)
         self.OnSurfacePositionChanged(None)
-        
+
     def UpdateVectorShow(self, vecType, enabled):
         """Enable/disable lines/points widgets
-        
+
         :param vecType: vector type (lines, points)
         """
         if vecType != 'lines' and vecType != 'points':
             return False
-        
+
         for win in self.win['vector'][vecType].keys():
             if win == 'show':
                 continue
-            if type(self.win['vector'][vecType][win]) == type({}):
+            if isinstance(self.win['vector'][vecType][win], type({})):
                 for swin in self.win['vector'][vecType][win].keys():
                     if enabled:
-                        self.FindWindowById(self.win['vector'][vecType][win][swin]).Enable(True)
+                        self.FindWindowById(
+                            self.win['vector'][vecType][win][swin]).Enable(True)
                     else:
-                        self.FindWindowById(self.win['vector'][vecType][win][swin]).Enable(False)
+                        self.FindWindowById(
+                            self.win['vector'][vecType][win][swin]).Enable(False)
             else:
                 if enabled:
-                    self.FindWindowById(self.win['vector'][vecType][win]).Enable(True)
+                    self.FindWindowById(
+                        self.win['vector'][vecType][win]).Enable(True)
                 else:
-                    self.FindWindowById(self.win['vector'][vecType][win]).Enable(False)
-        
+                    self.FindWindowById(
+                        self.win['vector'][vecType][win]).Enable(False)
+
         return True
-    
+
     def OnVectorShow(self, event):
         """Show vector lines/points"""
         winId = event.GetId()
         if winId == self.win['vector']['lines']['show']:
             vecType = 'lines'
             points = False
-        else: # points
-            vecType = 'points' 
+        else:  # points
+            vecType = 'points'
             points = True
-       
+
         checked = event.IsChecked()
         name = self.FindWindowById(self.win['vector']['map']).GetValue()
-        items = self.tree.FindItemByData(key = 'name', value = name)
+        items = self.tree.FindItemByData(key='name', value=name)
         for item in items:
-            if self.tree.GetLayerInfo(item, key = 'type') == 'vector':
+            if self.tree.GetLayerInfo(item, key='type') == 'vector':
                 break
         data = self.GetLayerData('vector')['vector']
-        
+
         if checked:
-            self.mapWindow.LoadVector(item, points = points, append = False)
+            self.mapWindow.LoadVector(item, points=points, append=False)
         else:
-            self.mapWindow.UnloadVector(item, points = points, remove = False)
-        
+            self.mapWindow.UnloadVector(item, points=points, remove=False)
+
         self.UpdateVectorShow(vecType, checked)
-        
+
         if checked:
             try:
                 id = data[vecType]['object']['id']
             except KeyError:
                 id = -1
-            
+
             if id > 0:
                 self.mapWindow.SetMapObjProperties(item, id, vecType)
-                
+
                 # update properties
-                event = wxUpdateProperties(data = data)
+                event = wxUpdateProperties(data=data)
                 wx.PostEvent(self.mapWindow, event)
-        
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-        
+
         event.Skip()
-    
+
     def OnVectorLinesMode(self, event):
         """Display vector lines on surface/3d"""
         rasters = self.mapWindow.GetLayerNames('raster')
-        if event.GetSelection() == 0: # surface
+        if event.GetSelection() == 0:  # surface
             if len(rasters) < 1:
-                self.FindWindowById(self.win['vector']['lines']['surface']).Enable(False)
-                self.FindWindowById(self.win['vector']['lines']['3d']).SetSelection(1)
+                self.FindWindowById(
+                    self.win['vector']['lines']['surface']).Enable(False)
+                self.FindWindowById(
+                    self.win['vector']['lines']['3d']).SetSelection(1)
                 return
-            
-            self.FindWindowById(self.win['vector']['lines']['surface']).Enable(True)
+
+            self.FindWindowById(
+                self.win['vector']['lines']['surface']).Enable(True)
             # set first found surface
             data = self.GetLayerData('vector')
             data['vector']['lines']['mode']['surface'] = rasters[0]
-            self.FindWindowById(self.win['vector']['lines']['surface']).SetStringSelection( \
+            self.FindWindowById(
+                self.win['vector']['lines']['surface']).SetStringSelection(
                 rasters[0])
-        else: # 3D
-            self.FindWindowById(self.win['vector']['lines']['surface']).Enable(False)
-        
+        else:  # 3D
+            self.FindWindowById(self.win['vector']['lines'][
+                                'surface']).Enable(False)
+
         self.OnVectorLines(event)
-        
+
         event.Skip()
 
     def OnVectorLines(self, event):
         """Set vector lines mode, apply changes if auto-rendering is enabled"""
         data = self.GetLayerData('vector')
-        width = self.FindWindowById(self.win['vector']['lines']['width']).GetValue()
-        
+        width = self.FindWindowById(
+            self.win['vector']['lines']['width']).GetValue()
+
         mode = {}
-        if self.FindWindowById(self.win['vector']['lines']['3d']).GetSelection() == 0:
+        if self.FindWindowById(self.win['vector']['lines'][
+                               '3d']).GetSelection() == 0:
             mode['type'] = 'surface'
             mode['surface'] = {}
-            checklist = self.FindWindowById(self.win['vector']['lines']['surface'])
+            checklist = self.FindWindowById(
+                self.win['vector']['lines']['surface'])
             value = list()
             checked = list()
             for surface in range(checklist.GetCount()):
                 value.append(checklist.GetString(surface))
                 checked.append(checklist.IsChecked(surface))
-                    
+
             mode['surface']['value'] = value
             mode['surface']['show'] = checked
         else:
             mode['type'] = '3d'
-        
+
         for attrb in ('width', 'mode'):
             data['vector']['lines'][attrb]['update'] = None
         data['vector']['lines']['width']['value'] = width
         data['vector']['lines']['mode'] = mode
-        
-        color = self.FindWindowById(self.win['vector']['lines']['color']).GetColour()
-        
+
+        color = self.FindWindowById(
+            self.win['vector']['lines']['color']).GetColour()
+
         if isinstance(color, csel.ColourSelect):
-            pass #color picker not yet instantiated
+            pass  # color picker not yet instantiated
         else:
             color = str(color[0]) + ':' + str(color[1]) + ':' + str(color[2])
             data['vector']['lines']['color']['update'] = None
             data['vector']['lines']['color']['value'] = color
-        
+
         # update properties
-        event = wxUpdateProperties(data = data)
+        event = wxUpdateProperties(data=data)
         wx.PostEvent(self.mapWindow, event)
-                        
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
 
     def OnVectorPointsMode(self, event):
         rasters = self.mapWindow.GetLayerNames('raster')
-        if event.GetSelection() == 0: # surface
+        if event.GetSelection() == 0:  # surface
             if len(rasters) < 1:
-                self.FindWindowById(self.win['vector']['points']['surface']).Enable(False)
-                self.FindWindowById(self.win['vector']['points']['3d']).SetSelection(1)
+                self.FindWindowById(
+                    self.win['vector']['points']['surface']).Enable(False)
+                self.FindWindowById(
+                    self.win['vector']['points']['3d']).SetSelection(1)
                 return
 
-            self.FindWindowById(self.win['vector']['points']['surface']).Enable(True)
+            self.FindWindowById(
+                self.win['vector']['points']['surface']).Enable(True)
             # set first found surface
             data = self.GetLayerData('vector')
             data['vector']['points']['mode']['surface']['value'] = rasters
             data['vector']['points']['mode']['3d'] = False
-            self.FindWindowById(self.win['vector']['points']['surface']).SetStringSelection( \
+            self.FindWindowById(
+                self.win['vector']['points']['surface']).SetStringSelection(
                 rasters[0])
-        else: # use z coordinate if 3d
+        else:  # use z coordinate if 3d
             data = self.GetLayerData('vector')
             data['vector']['points']['mode']['3d'] = True
-            self.FindWindowById(self.win['vector']['points']['surface']).Enable(False)
+            self.FindWindowById(self.win['vector']['points'][
+                                'surface']).Enable(False)
         data['vector']['points']['mode']['update'] = None
 
         self.OnVectorPoints(event)
@@ -3529,51 +4035,52 @@
             vtype = 'lines'
         else:
             vtype = 'points'
-        
+
         value = self.FindWindowById(id).GetValue()
-        slider = self.FindWindowById(self.win['vector'][vtype]['height']['slider'])
-        self.AdjustSliderRange(slider = slider, value = value)
-        
+        slider = self.FindWindowById(
+            self.win['vector'][vtype]['height']['slider'])
+        self.AdjustSliderRange(slider=slider, value=value)
+
         for win in self.win['vector'][vtype]['height'].itervalues():
             self.FindWindowById(win).SetValue(value)
-        
+
         data = self.GetLayerData('vector')
-        data['vector'][vtype]['height'] = { 'value' : value,
-                                            'update' : None }
-        
+        data['vector'][vtype]['height'] = {'value': value,
+                                           'update': None}
+
         # update properties
-        
-        event = wxUpdateProperties(data = data)
+
+        event = wxUpdateProperties(data=data)
         wx.PostEvent(self.mapWindow, event)
-        
+
         self.mapWindow.render['quick'] = True
         self.mapWindow.render['v' + vtype] = True
         self.mapWindow.Refresh(False)
-        
+
         event.Skip()
-    
+
     def OnVectorHeightFull(self, event):
         """Vector height changed, render in full resolution"""
         self.OnVectorHeight(event)
-##        self.OnVectorSurface(event)
+# self.OnVectorSurface(event)
         id = event.GetId()
         if id in self.win['vector']['lines']['height'].values():
             vtype = 'lines'
         else:
             vtype = 'points'
-        
+
         self.mapWindow.render['quick'] = False
         self.mapWindow.render['v' + vtype] = False
         self.mapWindow.Refresh(False)
 
     def OnVectorHeightText(self, event):
         """Vector height changed, render in full resolution"""
-        
+
         #        self.OnVectorHeight(event)
         self.OnVectorHeightFull(event)
-    
+
     def OnVectorSurface(self, event):
-        """Reference surface for vector map (lines/points)""" 
+        """Reference surface for vector map (lines/points)"""
         id = event.GetId()
         if id == self.win['vector']['lines']['surface']:
             vtype = 'lines'
@@ -3585,46 +4092,48 @@
         for items in range(checkList.GetCount()):
             checked.append(checkList.IsChecked(items))
             surfaces.append(checkList.GetString(items))
-        
+
         data = self.GetLayerData('vector')
-        data['vector'][vtype]['mode']['surface'] = { 'value' : surfaces,
-                                                     'show'  : checked}
-        data['vector'][vtype]['mode']['update'] = None 
-        
+        data['vector'][vtype]['mode']['surface'] = {'value': surfaces,
+                                                    'show': checked}
+        data['vector'][vtype]['mode']['update'] = None
+
         # update properties
-        event = wxUpdateProperties(data = data)
+        event = wxUpdateProperties(data=data)
         wx.PostEvent(self.mapWindow, event)
-        
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-            
-        
+
     def OnVectorPoints(self, event):
         """Set vector points mode, apply changes if auto-rendering is enabled"""
         data = self.GetLayerData('vector')
-        
-        size  = self.FindWindowById(self.win['vector']['points']['size']).GetValue()
-        marker = self.FindWindowById(self.win['vector']['points']['marker']).GetSelection()
+
+        size = self.FindWindowById(
+            self.win['vector']['points']['size']).GetValue()
+        marker = self.FindWindowById(
+            self.win['vector']['points']['marker']).GetSelection()
         #        width = self.FindWindowById(self.win['vector']['points']['width']).GetValue()
-        
+
         for attrb in ('size', 'marker'):
             data['vector']['points'][attrb]['update'] = None
         data['vector']['points']['size']['value'] = size
         #        data['vector']['points']['width']['value'] = width
         data['vector']['points']['marker']['value'] = marker
-        
-        color = self.FindWindowById(self.win['vector']['points']['color']).GetColour()
+
+        color = self.FindWindowById(
+            self.win['vector']['points']['color']).GetColour()
         if isinstance(color, csel.ColourSelect):
-            pass #color picker not yet instantiated
+            pass  # color picker not yet instantiated
         else:
             color = str(color[0]) + ':' + str(color[1]) + ':' + str(color[2])
             data['vector']['points']['color']['update'] = None
             data['vector']['points']['color']['value'] = color
-        
+
         # update properties
-        event = wxUpdateProperties(data = data)
+        event = wxUpdateProperties(data=data)
         wx.PostEvent(self.mapWindow, event)
-        
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
 
@@ -3633,9 +4142,9 @@
         # can be called with no event to enable/disable button
         if not event:
             ids = (self.win['vector']['points']['thematic']['checkcolor'],
-                  self.win['vector']['lines']['thematic']['checkcolor'],
-                  self.win['vector']['points']['thematic']['checksize'],
-                  self.win['vector']['lines']['thematic']['checkwidth'])
+                   self.win['vector']['lines']['thematic']['checkcolor'],
+                   self.win['vector']['points']['thematic']['checksize'],
+                   self.win['vector']['lines']['thematic']['checkwidth'])
         else:
             ids = (event.GetId(),)
         for id in ids:
@@ -3651,7 +4160,7 @@
                     attrType = 'color'
                 else:
                     attrType = 'width'
-                
+
             check = self.win['vector'][vtype]['thematic']['check' + attrType]
             button = self.win['vector'][vtype]['thematic']['button' + attrType]
             if self.FindWindowById(check).GetValue():
@@ -3659,61 +4168,64 @@
             else:
                 checked = False
             self.FindWindowById(button).Enable(checked)
-            
+
             data = self.GetLayerData('vector')
-            
+
             # decide if use GRASSRGB column
             if attrType == 'color':
-                name = self.FindWindowById(self.win['vector']['map']).GetValue()
+                name = self.FindWindowById(
+                    self.win['vector']['map']).GetValue()
                 if not data['vector'][vtype]['thematic']['rgbcolumn']:
                     try:
-                        id =  data['vector'][vtype]['object']['id']
-                    
+                        id = data['vector'][vtype]['object']['id']
+
                         # if GRASSRGB exists and color table doesn't, use GRGB
                         if self.HasGRASSRGB(name)  and \
-                            not self._display.CheckColorTable(id = id, type = vtype):
-                            data['vector'][vtype]['thematic']['rgbcolumn'] = 'GRASSRGB'
+                                not self._display.CheckColorTable(id=id, type=vtype):
+                            data['vector'][vtype]['thematic'][
+                                'rgbcolumn'] = 'GRASSRGB'
                     except KeyError:
                         pass
-                        
+
             data['vector'][vtype]['thematic']['use' + attrType] = checked
             data['vector'][vtype]['thematic']['update'] = None
-        
+
         # update properties
-        event = wxUpdateProperties(data = data)
+        event = wxUpdateProperties(data=data)
         wx.PostEvent(self.mapWindow, event)
-        
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-            
+
     def HasGRASSRGB(self, name):
         """Check if GRASSRGB column exist."""
         column = False
-        
+
         dbInfo = VectorDBInfo(name)
         if len(dbInfo.layers):
             table = dbInfo.layers[1]['table']
             if 'GRASSRGB' in dbInfo.GetTableDesc(table):
                 column = True
-                
+
         return column
-        
+
     def OnSetThematic(self, event):
         """Set options for thematic points"""
         if event.GetId() in self.win['vector']['points']['thematic'].values():
             vtype = 'points'
         else:
             vtype = 'lines'
-        if event.GetId() == self.win['vector'][vtype]['thematic']['buttoncolor']:
+        if event.GetId() == self.win['vector'][vtype][
+                'thematic']['buttoncolor']:
             attrType = 'color'
         elif vtype == 'points':
             attrType = 'size'
         else:
             attrType = 'width'
-        ctable = ThematicVectorTable(self, vtype, attributeType = attrType)
+        ctable = ThematicVectorTable(self, vtype, attributeType=attrType)
         ctable.CentreOnScreen()
         ctable.Show()
-        
+
     def UpdateIsosurfButtons(self, list):
         """Enable/disable buttons 'add', 'delete',
         'move up', 'move down'"""
@@ -3727,30 +4239,31 @@
             add.Enable(False)
         else:
             add.Enable(True)
-        
+
         if nitems < 1:
             # disable 'delete' if only one item in the lis
             delete.Enable(False)
         else:
             delete.Enable(True)
-        
+
         if list.GetSelection() >= nitems - 1:
             # disable 'move-down' if last
             moveDown.Enable(False)
         else:
             moveDown.Enable(True)
-        
+
         if list.GetSelection() < 1:
             # disable 'move-up' if first
             moveUp.Enable(False)
         else:
             moveUp.Enable(True)
-            
+
     def OnVolumeMode(self, event):
         """Change mode isosurfaces/slices"""
-        mode = self.FindWindowById(self.win['volume']['draw']['mode']).GetSelection()
+        mode = self.FindWindowById(
+            self.win['volume']['draw']['mode']).GetSelection()
         data = self.GetLayerData('volume')['volume']
-        
+
         sizer = self.isoPanel.GetContainingSizer()
         sizer = self.slicePanel.GetContainingSizer()
         listBox = self.FindWindowByName('listStaticBox')
@@ -3766,24 +4279,25 @@
             listBox.SetLabel(" %s " % _("List of slices"))
             data['draw']['mode']['value'] = 1
             data['draw']['mode']['desc'] = 'slice'
-        
+
         if event:
             name = self.FindWindowById(self.win['volume']['map']).GetValue()
-            layer = self._getMapLayerByName(name, mapType = 'raster_3d')
-            self.UpdateVolumePage(layer, data, updateName = False)
-            
+            layer = self._getMapLayerByName(name, mapType='raster_3d')
+            self.UpdateVolumePage(layer, data, updateName=False)
+
         sizer.Layout()
         listBox.GetParent().Fit()
-            
+
     def OnVolumeDrawMode(self, event):
         """Set isosurface/slice draw mode"""
         self.SetVolumeDrawMode(event.GetSelection())
-        
+
     def OnVolumeDrawBox(self, event):
         """Set wire box drawing"""
         data = self.GetLayerData('volume')['volume']
         vid = data['object']['id']
-        checked = self.FindWindowById(self.win['volume']['draw']['box']).GetValue()
+        checked = self.FindWindowById(
+            self.win['volume']['draw']['box']).GetValue()
         self._display.SetVolumeDrawBox(vid, checked)
         data['draw']['box']['enabled'] = checked
 
@@ -3794,14 +4308,15 @@
         """Set isosurface draw mode"""
         data = self.GetLayerData('volume')['volume']
         id = data['object']['id']
-        
+
         mode = 0
         if selection == 0:
             mode |= wxnviz.DM_FLAT
         else:
             mode |= wxnviz.DM_GOURAUD
-            
-        if self.FindWindowById(self.win['volume']['draw']['mode']).GetSelection() == 0:
+
+        if self.FindWindowById(self.win['volume']['draw'][
+                               'mode']).GetSelection() == 0:
             self._display.SetIsosurfaceMode(id, mode)
             data['draw']['shading']['isosurface']['desc'] = 'gouraud'
             data['draw']['shading']['isosurface']['value'] = mode
@@ -3809,68 +4324,70 @@
             self._display.SetSliceMode(id, mode)
             data['draw']['shading']['slice']['desc'] = 'flat'
             data['draw']['shading']['slice']['value'] = mode
-        
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-        
+
     def OnVolumeResolution(self, event):
         """Set isosurface/slice draw resolution"""
         self.SetVolumeResolution(event.GetInt())
-        
+
     def SetVolumeResolution(self, res):
         """Set isosurface draw resolution"""
         data = self.GetLayerData('volume')['volume']
         id = data['object']['id']
-        
-        if self.FindWindowById(self.win['volume']['draw']['mode']).GetSelection() == 0:
+
+        if self.FindWindowById(self.win['volume']['draw'][
+                               'mode']).GetSelection() == 0:
             self._display.SetIsosurfaceRes(id, res)
             data['draw']['resolution']['isosurface']['value'] = res
         else:
             self._display.SetSliceRes(id, res)
             data['draw']['resolution']['slice']['value'] = res
-        
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-    
+
     def OnInOutMode(self, event):
         """Change isosurfaces mode inout"""
         data = self.GetLayerData('volume')['volume']
         id = data['object']['id']
-        isosurfId = self.FindWindowById(self.win['volume']['isosurfs']).GetSelection()
-        
+        isosurfId = self.FindWindowById(
+            self.win['volume']['isosurfs']).GetSelection()
+
         ret = self._display.SetIsosurfaceInOut(id, isosurfId, event.GetInt())
         if ret == 1:
             data['isosurface'][isosurfId]['inout']['value'] = event.GetInt()
-            
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-    
-        
+
     def OnVolumeIsosurfMap(self, event):
         """Set surface attribute"""
         if self.vetoGSelectEvt:
             self.vetoGSelectEvt = False
             return
-        self.SetMapObjAttrb(nvizType = 'volume', winId = event.GetId())
-        
+        self.SetMapObjAttrb(nvizType='volume', winId=event.GetId())
+
     def OnVolumeCheck(self, event):
         """Isosurface/slice checked (->load) or unchecked (->unload)"""
-        if self.FindWindowById(self.win['volume']['draw']['mode']).GetSelection() == 0:
+        if self.FindWindowById(self.win['volume']['draw'][
+                               'mode']).GetSelection() == 0:
             mode = 'isosurf'
         else:
             mode = 'slice'
         index = event.GetSelection()
         list = self.FindWindowById(self.win['volume'][mode + 's'])
-        
+
         data = self.GetLayerData('volume')['volume']
         vid = data['object']['id']
-        
+
         id = event.GetSelection()
-        
+
         if mode == 'isosurf':
             if list.IsChecked(index):
                 if 'transp' in data['isosurface'][id] and\
-                    data['isosurface'][id]['transp']['map'] is not None:
+                        data['isosurface'][id]['transp']['map'] is not None:
                     if data['isosurface'][id]['transp']['map']:
                         map = True
                         value = data['isosurface'][id]['transp']['value']
@@ -3890,17 +4407,18 @@
             else:
                 # disable -> make transparent
                 self._display.SetSliceTransp(vid, id, 255)
-                
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-        
+
     def OnVolumeSelect(self, event):
         """Isosurface/Slice item selected"""
-        if self.FindWindowById(self.win['volume']['draw']['mode']).GetSelection() == 0:
+        if self.FindWindowById(self.win['volume']['draw'][
+                               'mode']).GetSelection() == 0:
             mode = 'isosurf'
         else:
             mode = 'slice'
-            
+
         winUp = self.FindWindowById(self.win['volume']['btnMoveUp'])
         winDown = self.FindWindowById(self.win['volume']['btnMoveDown'])
         selection = event.GetSelection()
@@ -3919,109 +4437,118 @@
                 winDown.Enable()
             if not winUp.IsEnabled():
                 winUp.Enable()
-        
+
         # update dialog
         name = self.FindWindowById(self.win['volume']['map']).GetValue()
-        layer = self._getMapLayerByName(name, mapType = 'raster_3d')
-        
+        layer = self._getMapLayerByName(name, mapType='raster_3d')
+
         if mode == 'isosurf':
-            data = self.GetLayerData('volume')['volume']['isosurface'][selection]
+            data = self.GetLayerData('volume')['volume'][
+                'isosurface'][selection]
             self.UpdateVolumeIsosurfPage(data)
         else:
             data = self.GetLayerData('volume')['volume']['slice'][selection]
             self.UpdateVolumeSlicePage(data)
-        
-        
-        
+
     def OnVolumeAdd(self, event):
         """Add new isosurface/slice to the list"""
-        if self.FindWindowById(self.win['volume']['draw']['mode']).GetSelection() == 0:
+        if self.FindWindowById(self.win['volume']['draw'][
+                               'mode']).GetSelection() == 0:
             mode = 'isosurf'
         else:
             mode = 'slice'
         list = self.FindWindowById(self.win['volume'][mode + 's'])
-        
+
         name = self.FindWindowById(self.win['volume']['map']).GetValue()
-        layer = self._getMapLayerByName(name, mapType = 'raster_3d')
+        layer = self._getMapLayerByName(name, mapType='raster_3d')
         data = self.GetLayerData('volume')['volume']
         id = data['object']['id']
-        
+
         sel = list.GetSelection()
         if mode == 'isosurf':
             isosurfData = self.mapWindow.nvizDefault.SetIsosurfaceDefaultProp()
             if isosurfData['color']['map']:
                 isosurfData['color']['value'] = layer.name
 
-            level = isosurfData['topo']['value'] = round(self._get3dRange(name = layer.name)[0], 2)
-        
+            level = isosurfData['topo']['value'] = round(
+                self._get3dRange(name=layer.name)[0], 2)
+
             if sel < 0 or sel >= list.GetCount() - 1:
                 item = list.Append(item=_("Level {level}").format(level=level))
             else:
                 list.Insert(item=_("Level {level}").format(level=level),
-                            pos=sel+1) # append
+                            pos=sel + 1)  # append
                 item = sel + 1
         else:
             sliceData = self.mapWindow.nvizDefault.SetSliceDefaultProp()
             axis = ("X", "Y", "Z")[sliceData['position']['axis']]
             if sel < 0 or sel >= list.GetCount() - 1:
-                item = list.Append(item=_("Slice parallel to {axis}").format(axis=axis))
+                item = list.Append(
+                    item=_("Slice parallel to {axis}").format(
+                        axis=axis))
             else:
-                list.Insert(item=_("Slice parallel to {axis}").format(axis=axis),
-                            pos=sel+1) # append
+                list.Insert(
+                    item=_("Slice parallel to {axis}").format(
+                        axis=axis), pos=sel + 1)  # append
                 item = sel + 1
-        
+
         list.Check(item)
         list.SetSelection(item)
-        
+
         if mode == 'isosurf':
             data['isosurface'].insert(item, isosurfData)
-            # add isosurface        
+            # add isosurface
             self._display.AddIsosurface(id, float(level))
         else:
             data['slice'].insert(item, sliceData)
-            # add isosurface        
+            # add isosurface
             nslice = self._display.AddSlice(id)
-            self._display.SetSlicePosition(id, nslice -1, sliceData['position']['x1'], sliceData['position']['x2'],
-                                               sliceData['position']['y1'], sliceData['position']['y2'],
-                                               sliceData['position']['z1'], sliceData['position']['z2'],
-                                               sliceData['position']['axis'])
+            self._display.SetSlicePosition(
+                id, nslice - 1, sliceData['position']['x1'],
+                sliceData['position']['x2'],
+                sliceData['position']['y1'],
+                sliceData['position']['y2'],
+                sliceData['position']['z1'],
+                sliceData['position']['z2'],
+                sliceData['position']['axis'])
         # update properties
-        event = wxUpdateProperties(data = data)
+        event = wxUpdateProperties(data=data)
         wx.PostEvent(self.mapWindow, event)
-        
+
         # update buttons
         self.UpdateIsosurfButtons(list)
         if mode == 'isosurf':
             self.UpdateVolumeIsosurfPage(isosurfData)
         else:
             self.UpdateVolumeSlicePage(sliceData)
-        
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-        
+
         event.Skip()
-        
+
     def OnVolumeDelete(self, event):
         """Remove isosurface/slice from list"""
-        if self.FindWindowById(self.win['volume']['draw']['mode']).GetSelection() == 0:
+        if self.FindWindowById(self.win['volume']['draw'][
+                               'mode']).GetSelection() == 0:
             mode = 'isosurf'
         else:
             mode = 'slice'
         list = self.FindWindowById(self.win['volume'][mode + 's'])
-        
+
         # remove item from list
         id = list.GetSelection()
         list.Delete(id)
         # select last item
         if list.GetCount() > 0:
-            list.SetSelection(list.GetCount()-1)
-        
+            list.SetSelection(list.GetCount() - 1)
+
         name = self.FindWindowById(self.win['volume']['map']).GetValue()
-        layer = self._getMapLayerByName(name, mapType = 'raster_3d')
+        layer = self._getMapLayerByName(name, mapType='raster_3d')
         data = self.GetLayerData('volume')['volume']
 
         vid = data['object']['id']
-        
+
         # delete isosurface
         if mode == 'isosurf':
             del data['isosurface'][id]
@@ -4029,11 +4556,12 @@
         else:
             del data['slice'][id]
             self._display.DeleteSlice(vid, id)
-        
+
         # update buttons
         if list.GetCount() > 0:
             if mode == 'isosurf':
-                self.UpdateVolumeIsosurfPage(data['isosurface'][list.GetSelection()])
+                self.UpdateVolumeIsosurfPage(
+                    data['isosurface'][list.GetSelection()])
             else:
                 self.UpdateVolumeSlicePage(data['slice'][list.GetSelection()])
         else:
@@ -4042,194 +4570,198 @@
             else:
                 self.UpdateVolumeSlicePage(None)
         self.UpdateIsosurfButtons(list)
-        
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-        
+
         event.Skip()
-        
+
     def OnVolumeMoveUp(self, event):
         """Move isosurface/slice up in the list"""
-        if self.FindWindowById(self.win['volume']['draw']['mode']).GetSelection() == 0:
+        if self.FindWindowById(self.win['volume']['draw'][
+                               'mode']).GetSelection() == 0:
             mode = 'isosurf'
         else:
             mode = 'slice'
         list = self.FindWindowById(self.win['volume'][mode + 's'])
         sel = list.GetSelection()
-        
+
         if sel < 1:
-            return # this should not happen
-        
+            return  # this should not happen
+
         name = self.FindWindowById(self.win['volume']['map']).GetValue()
-        layer = self._getMapLayerByName(name, mapType = 'raster_3d')
+        layer = self._getMapLayerByName(name, mapType='raster_3d')
         data = self.GetLayerData('volume')['volume']
-        
+
         id = data['object']['id']
-        
+
         # move item up
         text = list.GetStringSelection()
-        list.Insert(item = text, pos = sel-1)
-        list.Check(sel-1)
-        list.SetSelection(sel-1)
-        list.Delete(sel+1)
+        list.Insert(item=text, pos=sel - 1)
+        list.Check(sel - 1)
+        list.SetSelection(sel - 1)
+        list.Delete(sel + 1)
         if mode == 'isosurf':
-            data['isosurface'].insert(sel-1, data['isosurface'][sel])
-            del data['isosurface'][sel+1]
+            data['isosurface'].insert(sel - 1, data['isosurface'][sel])
+            del data['isosurface'][sel + 1]
             self._display.MoveIsosurface(id, sel, True)
         else:
-            data['slice'].insert(sel-1, data['slice'][sel])
-            del data['slice'][sel+1]
+            data['slice'].insert(sel - 1, data['slice'][sel])
+            del data['slice'][sel + 1]
             self._display.MoveSlice(id, sel, True)
-        
+
         # update buttons
         self.UpdateIsosurfButtons(list)
-        
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-        
+
         event.Skip()
-        
+
     def OnVolumeMoveDown(self, event):
         """Move isosurface/slice down in the list"""
-        if self.FindWindowById(self.win['volume']['draw']['mode']).GetSelection() == 0:
+        if self.FindWindowById(self.win['volume']['draw'][
+                               'mode']).GetSelection() == 0:
             mode = 'isosurf'
         else:
             mode = 'slice'
         list = self.FindWindowById(self.win['volume'][mode + 's'])
         sel = list.GetSelection()
-        
+
         if sel >= list.GetCount() - 1:
-            return # this should not happen
-        
+            return  # this should not happen
+
         name = self.FindWindowById(self.win['volume']['map']).GetValue()
-        layer = self._getMapLayerByName(name, mapType = 'raster_3d')
+        layer = self._getMapLayerByName(name, mapType='raster_3d')
         data = self.GetLayerData('volume')['volume']
-        
+
         id = data['object']['id']
-        
+
         # move item up
         text = list.GetStringSelection()
-        list.Insert(item = text, pos = sel+2)
-        list.Check(sel+2)
-        list.SetSelection(sel+2)
+        list.Insert(item=text, pos=sel + 2)
+        list.Check(sel + 2)
+        list.SetSelection(sel + 2)
         list.Delete(sel)
         if mode == 'isosurf':
-            data['isosurface'].insert(sel+2, data['isosurface'][sel])
+            data['isosurface'].insert(sel + 2, data['isosurface'][sel])
             del data['isosurface'][sel]
             self._display.MoveIsosurface(id, sel, False)
         else:
-            data['slice'].insert(sel+2, data['slice'][sel])
+            data['slice'].insert(sel + 2, data['slice'][sel])
             del data['slice'][sel]
             self._display.MoveSlice(id, sel, False)
-        
+
         # update buttons
         self.UpdateIsosurfButtons(list)
-        
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-        
+
         event.Skip()
-    
+
     def OnVolumePositionChanged(self, event):
         """Volume position changed"""
         self.mapWindow.render['quick'] = False
         self.mapWindow.Refresh(False)
-        
+
     def OnVolumePosition(self, event):
         """Volume position"""
         winName = self.__GetWindowName(self.win['volume'], event.GetId())
         if not winName:
             return
-        axis = self.FindWindowById(self.win['volume']['position']['axis']).GetSelection()
-        
+        axis = self.FindWindowById(
+            self.win['volume']['position']['axis']).GetSelection()
+
         value = self.FindWindowById(event.GetId()).GetValue()
         slider = self.FindWindowById(self.win['volume'][winName]['slider'])
-        self.AdjustSliderRange(slider = slider, value = value)
-        
+        self.AdjustSliderRange(slider=slider, value=value)
+
         for win in self.win['volume']['position'].itervalues():
             if win in (self.win['volume']['position']['axis'],
                        self.win['volume']['position']['reset']):
                 continue
             else:
                 self.FindWindowById(win).SetValue(value)
-        
+
         data = self.GetLayerData('volume')
         id = data['volume']['object']['id']
         x, y, z = self._display.GetVolumePosition(id)
-        
-        if axis == 0: # x
+
+        if axis == 0:  # x
             x = value
-        elif axis == 1: # y
+        elif axis == 1:  # y
             y = value
-        else: # z
+        else:  # z
             z = value
-        
+
         data['volume']['position']['x'] = x
         data['volume']['position']['y'] = y
         data['volume']['position']['z'] = z
         data['volume']['position']['update'] = None
         # update properties
-        
-        event = wxUpdateProperties(data = data)
+
+        event = wxUpdateProperties(data=data)
         wx.PostEvent(self.mapWindow, event)
-        
+
         self.mapWindow.render['quick'] = True
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-        
+
     def OnVolumeAxis(self, event):
         """Volume position, axis changed"""
         data = self.GetLayerData('volume')
         id = data['volume']['object']['id']
-        
-        axis = self.FindWindowById(self.win['volume']['position']['axis']).GetSelection()
+
+        axis = self.FindWindowById(
+            self.win['volume']['position']['axis']).GetSelection()
         slider = self.FindWindowById(self.win['volume']['position']['slider'])
         text = self.FindWindowById(self.win['volume']['position']['text'])
         xydim = self._display.GetLongDim()
         zdim = self._display.GetZRange()
         zdim = zdim[1] - zdim[0]
         x, y, z = self._display.GetVolumePosition(id)
-        
-        if axis == 0: # x
+
+        if axis == 0:  # x
             slider.SetRange(-3 * xydim, 3 * xydim)
             slider.SetValue(x)
             text.SetValue(x)
-        elif axis == 1: # y
+        elif axis == 1:  # y
             slider.SetRange(-3 * xydim, 3 * xydim)
             slider.SetValue(y)
             text.SetValue(y)
-        else: # z
+        else:  # z
             slider.SetRange(-3 * zdim, 3 * zdim)
             slider.SetValue(z)
             text.SetValue(z)
-            
+
     def OnVolumePositionText(self, event):
         """Volume position changed by textctrl"""
         self.OnVolumePosition(event)
         self.OnVolumePositionChanged(None)
-        
+
     def OnResetVolumePosition(self, event):
         """Reset position of volume"""
         for win in self.win['volume']['position'].itervalues():
             if win == self.win['volume']['position']['axis']:
-                self.FindWindowById(win).SetSelection(2) # Z
+                self.FindWindowById(win).SetSelection(2)  # Z
             elif win == self.win['volume']['position']['reset']:
                 continue
             else:
                 self.FindWindowById(win).SetValue(0)
-                
+
         data = self.GetLayerData('volume')
         data['volume']['position']['x'] = 0
         data['volume']['position']['y'] = 0
         data['volume']['position']['z'] = 0
         data['volume']['position']['update'] = None
         # update properties
-        event = wxUpdateProperties(data = data)
+        event = wxUpdateProperties(data=data)
         wx.PostEvent(self.mapWindow, event)
-        
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-        
+
     def OnVolumeSliceAxes(self, event):
         """Slice axis changed"""
         self.UpdateSliceLabels()
@@ -4238,62 +4770,67 @@
         sel = list.GetSelection()
         if sel < 0:
             return
-        axis = self.FindWindowById(self.win['volume']['slice']['axes']).GetSelection()
+        axis = self.FindWindowById(
+            self.win['volume']['slice']['axes']).GetSelection()
         data['volume']['slice'][sel]['position']['axis'] = axis
         data['volume']['slice'][sel]['position']['update'] = None
-        
+
         axis = ("X", "Y", "Z")[axis]
         list.SetString(sel, "%s %s" % (_("Slice parallel to"), axis))
         list.Check(sel)
-        
+
         # update properties
-        event = wxUpdateProperties(data = data)
-        wx.PostEvent(self.mapWindow, event) 
-        
+        event = wxUpdateProperties(data=data)
+        wx.PostEvent(self.mapWindow, event)
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-    
+
     def OnSliceTransparency(self, event):
         """Slice transparency changed"""
         data = self.GetLayerData('volume')
-        
+
         list = self.FindWindowById(self.win['volume']['slices'])
         sel = list.GetSelection()
         if sel < 0:
             return
-        
-        val = self.FindWindowById(self.win['volume']['slice']['transp']).GetValue()
-        data['volume']['slice'][sel]['transp']['value'] = self._getPercent(val, toPercent = False)
+
+        val = self.FindWindowById(
+            self.win['volume']['slice']['transp']).GetValue()
+        data['volume']['slice'][sel]['transp'][
+            'value'] = self._getPercent(val, toPercent=False)
         data['volume']['slice'][sel]['transp']['update'] = None
-        
+
         # update properties
-        event = wxUpdateProperties(data = data)
+        event = wxUpdateProperties(data=data)
         wx.PostEvent(self.mapWindow, event)
-        
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-        
+
     def OnSliceReset(self, event):
         """Slice position reset"""
         data = self.GetLayerData('volume')
-        
+
         list = self.FindWindowById(self.win['volume']['slices'])
         sel = list.GetSelection()
         if sel < 0:
             return
-        
-        for coord, val in zip(('x1', 'x2', 'y1', 'y2', 'z1', 'z2'),(0, 1, 0, 1, 0, 1, 0)):
+
+        for coord, val in zip(
+                ('x1', 'x2', 'y1', 'y2', 'z1', 'z2'),
+                (0, 1, 0, 1, 0, 1, 0)):
             data['volume']['slice'][sel]['position'][coord] = val
         data['volume']['slice'][sel]['position']['update'] = None
-        
+
         self.UpdateVolumeSlicePage(data['volume']['slice'][sel])
         # update properties
-        event = wxUpdateProperties(data = data)
+        event = wxUpdateProperties(data=data)
         wx.PostEvent(self.mapWindow, event)
-        
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-        
+
     def OnSlicePositionChange(self, event):
         """Slice position is changing"""
         data = self.GetLayerData('volume')
@@ -4303,8 +4840,8 @@
             return
         win = self.win['volume']['slice']
         winId = event.GetId()
-        value = event.GetInt()/100.
-        
+        value = event.GetInt() / 100.
+
         for coord in ('x1', 'x2', 'y1', 'y2', 'z1', 'z2'):
             if win['slider_' + coord] == winId:
                 data['volume']['slice'][sel]['position'][coord] = value
@@ -4312,55 +4849,59 @@
                 break
         self.mapWindow.render['quick'] = True
         # update properties
-        event = wxUpdateProperties(data = data)
-        wx.PostEvent(self.mapWindow, event) 
-        
+        event = wxUpdateProperties(data=data)
+        wx.PostEvent(self.mapWindow, event)
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-               
+
     def OnSlicePositionChanged(self, event):
         """Slice position is changed"""
         self.mapWindow.render['quick'] = False
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-                
+
     def OnCPlaneSelection(self, event):
         """Cutting plane selected"""
-        plane = self.FindWindowById(self.win['cplane']['planes']).GetStringSelection()
+        plane = self.FindWindowById(
+            self.win['cplane']['planes']).GetStringSelection()
         try:
             planeIndex = int(plane.split()[-1]) - 1
-            self.EnablePage("cplane", enabled = True)
+            self.EnablePage("cplane", enabled=True)
         except:
             planeIndex = -1
-            self.EnablePage("cplane", enabled = False)
+            self.EnablePage("cplane", enabled=False)
         self.mapWindow.SelectCPlane(planeIndex)
         if planeIndex >= 0:
-            self.mapWindow.UpdateCPlane(planeIndex, changes = ['rotation', 'position', 'shading'])
+            self.mapWindow.UpdateCPlane(
+                planeIndex, changes=[
+                    'rotation', 'position', 'shading'])
 
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
         self.UpdateCPlanePage(planeIndex)
-        
+
     def OnCPlaneChanging(self, event):
         """Cutting plane is changing"""
-        plane = self.FindWindowById(self.win['cplane']['planes']).GetStringSelection()
+        plane = self.FindWindowById(
+            self.win['cplane']['planes']).GetStringSelection()
         try:
             planeIndex = int(plane.split()[-1]) - 1
-        except:#TODO disabled page
+        except:  # TODO disabled page
             planeIndex = -1
-    
+
         if event.GetId() in (self.win['cplane']['rotation']['rot'].values() +
-                            self.win['cplane']['rotation']['tilt'].values()):
+                             self.win['cplane']['rotation']['tilt'].values()):
             action = 'rotation'
         else:
             action = 'position'
         data = self.mapWindow.cplanes[planeIndex][action]
         self.OnScroll(event, self.win['cplane'][action], data)
-        
+
         self.mapWindow.render['quick'] = True
-        event = wxUpdateCPlane(update = (action,), current = planeIndex)
+        event = wxUpdateCPlane(update=(action,), current=planeIndex)
         wx.PostEvent(self.mapWindow, event)
-        
+
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
 
@@ -4369,57 +4910,67 @@
         self.mapWindow.render['quick'] = False
         if self.mapDisplay.IsAutoRendered():
             self.mapWindow.Refresh(False)
-            
+
     def OnCPlaneChangeText(self, event):
         """Cutting plane changed by textctrl"""
         for axis in ('x', 'y', 'z'):
             if event.GetId() == self.win['cplane']['position'][axis]['text']:
                 value = self.FindWindowById(event.GetId()).GetValue()
-                slider = self.FindWindowById(self.win['cplane']['position'][axis]['slider'])
-                self.AdjustSliderRange(slider = slider, value = value)
-        self.OnCPlaneChanging(event = event)
-        self.OnCPlaneChangeDone(None)   
-        
+                slider = self.FindWindowById(
+                    self.win['cplane']['position'][axis]['slider'])
+                self.AdjustSliderRange(slider=slider, value=value)
+        self.OnCPlaneChanging(event=event)
+        self.OnCPlaneChangeDone(None)
+
     def OnCPlaneShading(self, event):
         """Cutting plane shading changed"""
-        shading = self.FindWindowById(self.win['cplane']['shading']).GetSelection()
-        plane = self.FindWindowById(self.win['cplane']['planes']).GetStringSelection()
+        shading = self.FindWindowById(
+            self.win['cplane']['shading']).GetSelection()
+        plane = self.FindWindowById(
+            self.win['cplane']['planes']).GetStringSelection()
         try:
             planeIndex = int(plane.split()[-1]) - 1
-        except:#TODO disabled page
+        except:  # TODO disabled page
             planeIndex = -1
-            
+
         self.mapWindow.cplanes[planeIndex]['shading'] = shading
-        
-        event = wxUpdateCPlane(update = ('shading',), current = planeIndex)
+
+        event = wxUpdateCPlane(update=('shading',), current=planeIndex)
         wx.PostEvent(self.mapWindow, event)
-        
+
         self.OnCPlaneChangeDone(None)
-        
+
     def OnCPlaneReset(self, event):
         """Reset current cutting plane"""
-        plane = self.FindWindowById(self.win['cplane']['planes']).GetStringSelection()
+        plane = self.FindWindowById(
+            self.win['cplane']['planes']).GetStringSelection()
         try:
             planeIndex = int(plane.split()[-1]) - 1
-        except:#TODO disabled page
+        except:  # TODO disabled page
             planeIndex = -1
 
-        self.mapWindow.cplanes[planeIndex] = copy.deepcopy(UserSettings.Get(group = 'nviz',
-                                                                            key = 'cplane'))
+        self.mapWindow.cplanes[planeIndex] = copy.deepcopy(
+            UserSettings.Get(group='nviz', key='cplane'))
         self.mapWindow.cplanes[planeIndex]['on'] = True
-        event = wxUpdateCPlane(update = ('position','rotation','shading'), current = planeIndex)
+        event = wxUpdateCPlane(
+            update=(
+                'position',
+                'rotation',
+                'shading'),
+            current=planeIndex)
         wx.PostEvent(self.mapWindow, event)
         self.OnCPlaneChangeDone(None)
         self.UpdateCPlanePage(planeIndex)
-    
+
     def OnDecorationPlacement(self, event):
         """Place an arrow/scalebar by clicking on display"""
         if event.GetId() == self.win['decoration']['arrow']['place']:
             type = 'arrow'
         elif event.GetId() == self.win['decoration']['scalebar']['place']:
             type = 'scalebar'
-        else: return
-        
+        else:
+            return
+
         if event.GetInt():
             self.mapDisplay.Raise()
             self.mapWindow.mouse['use'] = type
@@ -4427,43 +4978,52 @@
         else:
             self.mapWindow.mouse['use'] = 'default'
             self.mapWindow.SetNamedCursor('default')
-    
+
     def OnArrowDelete(self, event):
         """Delete arrow"""
         self._display.DeleteArrow()
         self.mapWindow.decoration['arrow']['show'] = False
-        self.FindWindowById( self.win['decoration']['arrow']['delete']).Disable()
+        self.FindWindowById(self.win['decoration'][
+                            'arrow']['delete']).Disable()
         self.mapWindow.Refresh(False)
-    
+
     def OnScalebarDelete(self, event):
         """Delete scalebar"""
-        choice = self.FindWindowById(self.win['decoration']['scalebar']['choice'])
+        choice = self.FindWindowById(
+            self.win['decoration']['scalebar']['choice'])
         choiceIndex = choice.GetSelection()
         index = choice.GetClientData(choiceIndex)
         if index == wx.NOT_FOUND:
             return
-        self._display.DeleteScalebar(id = index)
-        
-        self.FindWindowById(self.win['decoration']['scalebar']['choice']).Delete(choiceIndex)
+        self._display.DeleteScalebar(id=index)
+
+        self.FindWindowById(self.win['decoration']['scalebar'][
+                            'choice']).Delete(choiceIndex)
         if not choice.IsEmpty():
             choice.SetSelection(choice.GetCount() - 1)
         self.DisableScalebarControls()
 
         self.mapWindow.Refresh(False)
-         
+
     def AddScalebar(self, scalebarNum):
-        choice = self.FindWindowById(self.win['decoration']['scalebar']['choice'])
+        choice = self.FindWindowById(
+            self.win['decoration']['scalebar']['choice'])
         choice.Append(_("Scalebar %d") % (scalebarNum + 1), scalebarNum)
         choice.SetSelection(choice.GetCount() - 1)
         self.DisableScalebarControls()
 
     def AddArrow(self):
-        self.FindWindowById( self.win['decoration']['arrow']['delete']).Enable()
+        self.FindWindowById(self.win['decoration']['arrow']['delete']).Enable()
 
     def DisableScalebarControls(self):
-        choice = self.FindWindowById(self.win['decoration']['scalebar']['choice'])
-        self.FindWindowById(self.win['decoration']['scalebar']['delete']).Enable(not choice.IsEmpty())
-        self.FindWindowById(self.win['decoration']['scalebar']['choice']).Enable(not choice.IsEmpty())
+        choice = self.FindWindowById(
+            self.win['decoration']['scalebar']['choice'])
+        self.FindWindowById(
+            self.win['decoration']['scalebar']['delete']).Enable(
+            not choice.IsEmpty())
+        self.FindWindowById(
+            self.win['decoration']['scalebar']['choice']).Enable(
+            not choice.IsEmpty())
 
     def OnDecorationProp(self, event):
         """Set arrow/scalebar properties"""
@@ -4471,27 +5031,33 @@
             type = 'arrow'
         elif event.GetId() in self.win['decoration']['scalebar'].values():
             type = 'scalebar'
-        else: return
-        
-        color = self.FindWindowById(self.win['decoration'][type]['color']).GetValue()
-        size = self.FindWindowById(self.win['decoration'][type]['size']).GetValue()
+        else:
+            return
+
+        color = self.FindWindowById(
+            self.win['decoration'][type]['color']).GetValue()
+        size = self.FindWindowById(
+            self.win['decoration'][type]['size']).GetValue()
         if type == 'arrow':
-            self.mapWindow.decoration[type]['color'] = self._getColorString(color)
+            self.mapWindow.decoration[type][
+                'color'] = self._getColorString(color)
             self.mapWindow.decoration[type]['size'] = size
         elif type == 'scalebar'and self.mapWindow.decoration['scalebar']:
             for scalebar in self.mapWindow.decoration[type]:
                 scalebar['color'] = self._getColorString(color)
                 scalebar['size'] = size
-        
+
         if type == 'arrow' and self.mapWindow.decoration['arrow']['show']:
-            self._display.SetArrow(self.mapWindow.decoration['arrow']['position']['x'],
-                                   self.mapWindow.decoration['arrow']['position']['y'],
-                                   self.mapWindow.decoration['arrow']['size'],
-                                   self.mapWindow.decoration['arrow']['color'])
+            self._display.SetArrow(
+                self.mapWindow.decoration['arrow']['position']['x'],
+                self.mapWindow.decoration['arrow']['position']['y'],
+                self.mapWindow.decoration['arrow']['size'],
+                self.mapWindow.decoration['arrow']['color'])
             self._display.DrawArrow()
         elif type == 'scalebar' and self.mapWindow.decoration['scalebar']:
             ids = []
-            choice = self.FindWindowById(self.win['decoration']['scalebar']['choice'])
+            choice = self.FindWindowById(
+                self.win['decoration']['scalebar']['choice'])
             for index in range(choice.GetCount()):
                 ids.append(choice.GetClientData(index))
             for scalebar in self.mapWindow.decoration[type]:
@@ -4503,12 +5069,12 @@
                                               scalebar['color'])
             self._display.DrawScalebar()
             self.mapWindow.Refresh(False)
-        
+
     def UpdatePage(self, pageId):
         """Update dialog (selected page)"""
         self.pageChanging = True
         Debug.msg(1, "NvizToolWindow.UpdatePage(): %s", pageId)
-        
+
         if pageId == 'view':
             self.SetPage('view')
             hmin = self.mapWindow.iview['height']['min']
@@ -4518,104 +5084,127 @@
             zmax = self.mapWindow.view['z-exag']['max']
             zval = self.mapWindow.view['z-exag']['value']
 
-            for control in ('slider','text'):
+            for control in ('slider', 'text'):
                 try:
-                    self.FindWindowById(self.win['view']['height'][control]).SetRange(
-                                                                             hmin, hmax)
+                    self.FindWindowById(
+                        self.win['view']['height'][control]).SetRange(
+                        hmin, hmax)
                 except OverflowError:
                     hmin = self.mapWindow.iview['height']['min'] = 0
                     hmax = self.mapWindow.iview['height']['max'] = 10000
                     hval = self.mapWindow.iview['height']['value'] = 5000
-                    self.FindWindowById(self.win['view']['height'][control]).SetRange(hmin, hmax)
-                self.FindWindowById(self.win['view']['z-exag'][control]).SetRange(
-                                                                        zmin, zmax) 
-                self.FindWindowById(self.win['view']['height'][control]).SetValue(hval)                                      
-                
-                self.FindWindowById(self.win['view']['z-exag'][control]).SetValue(zval)                                      
-        
-            self.FindWindowById(self.win['view']['background']['color']).SetColour(\
-                            self.mapWindow.view['background']['color'])
-                            
+                    self.FindWindowById(
+                        self.win['view']['height'][control]).SetRange(
+                        hmin, hmax)
+                self.FindWindowById(
+                    self.win['view']['z-exag'][control]).SetRange(zmin, zmax)
+                self.FindWindowById(
+                    self.win['view']['height'][control]).SetValue(hval)
+
+                self.FindWindowById(
+                    self.win['view']['z-exag'][control]).SetValue(zval)
+
+            self.FindWindowById(
+                self.win['view']['background']['color']).SetColour(
+                self.mapWindow.view['background']['color'])
+
             tval = self.mapWindow.view['twist']['value']
             pval = self.mapWindow.view['persp']['value']
-            for control in ('slider','text'):
-                self.FindWindowById(self.win['view']['twist'][control]).SetValue(tval)                                      
-                
-                self.FindWindowById(self.win['view']['persp'][control]).SetValue(pval)
-            
-            
+            for control in ('slider', 'text'):
+                self.FindWindowById(
+                    self.win['view']['twist'][control]).SetValue(tval)
+
+                self.FindWindowById(
+                    self.win['view']['persp'][control]).SetValue(pval)
+
         elif pageId in ('surface', 'vector', 'volume'):
             name = self.FindWindowById(self.win[pageId]['map']).GetValue()
             data = self.GetLayerData(pageId)
             if data:
                 if pageId == 'surface':
-                    layer = self._getMapLayerByName(name, mapType = 'raster')
+                    layer = self._getMapLayerByName(name, mapType='raster')
                     if layer:
                         self.UpdateSurfacePage(layer, data['surface'])
                 elif pageId == 'vector':
-                    layer = self._getMapLayerByName(name, mapType = 'vector')
+                    layer = self._getMapLayerByName(name, mapType='vector')
                     if layer:
                         self.UpdateVectorPage(layer, data['vector'])
                 elif pageId == 'volume':
-                    layer = self._getMapLayerByName(name, mapType = 'raster_3d')
+                    layer = self._getMapLayerByName(name, mapType='raster_3d')
                     if layer:
                         self.UpdateVolumePage(layer, data['volume'])
         elif pageId == 'light':
             zval = self.mapWindow.light['position']['z']
             bval = self.mapWindow.light['bright']
             aval = self.mapWindow.light['ambient']
-            for control in ('slider','text'):
-                self.FindWindowById(self.win['light']['z'][control]).SetValue(zval)
-                self.FindWindowById(self.win['light']['bright'][control]).SetValue(bval)
-                self.FindWindowById(self.win['light']['ambient'][control]).SetValue(aval)
-            self.FindWindowById(self.win['light']['color']).SetColour(self.mapWindow.light['color'])
+            for control in ('slider', 'text'):
+                self.FindWindowById(
+                    self.win['light']['z'][control]).SetValue(zval)
+                self.FindWindowById(
+                    self.win['light']['bright'][control]).SetValue(bval)
+                self.FindWindowById(
+                    self.win['light']['ambient'][control]).SetValue(aval)
+            self.FindWindowById(
+                self.win['light']['color']).SetColour(
+                self.mapWindow.light['color'])
             self.FindWindowById(self.win['light']['position']).PostDraw()
         elif pageId == 'fringe':
             win = self.FindWindowById(self.win['fringe']['map'])
-            win.SetValue(self.FindWindowById(self.win['surface']['map']).GetValue())
+            win.SetValue(
+                self.FindWindowById(
+                    self.win['surface']['map']).GetValue())
         elif pageId == 'decoration':
             win = self.FindWindowById(self.win['decoration']['arrow']['size'])
             win.SetValue(self.mapWindow.decoration['arrow']['size'])
-            win = self.FindWindowById(self.win['decoration']['scalebar']['size'])
+            win = self.FindWindowById(
+                self.win['decoration']['scalebar']['size'])
             win.SetValue(self.mapWindow._getDecorationSize())
         elif pageId == 'constant':
             if self.mapWindow.constants:
                 surface = self.FindWindowById(self.win['constant']['surface'])
                 for item in self.mapWindow.constants:
-                    surface.Append(_("constant#") + str(item['constant']['object']['name']))
+                    surface.Append(_("constant#") +
+                                   str(item['constant']['object']['name']))
                 surface.SetSelection(0)
                 self.OnConstantSelection(None)
                 self.EnablePage('constant', True)
         elif pageId == 'cplane':
             count = self._display.GetCPlanesCount()
-            choices = [_("None"),]
+            choices = [_("None"), ]
             for plane in range(count):
-                choices.append("%s %i" % (_("Plane"), plane+1))
+                choices.append("%s %i" % (_("Plane"), plane + 1))
             self.FindWindowById(self.win['cplane']['planes']).SetItems(choices)
             current = 0
             for i, cplane in enumerate(self.mapWindow.cplanes):
                 if cplane['on']:
                     current = i + 1
-            self.FindWindowById(self.win['cplane']['planes']).SetSelection(current)
-            
+            self.FindWindowById(
+                self.win['cplane']['planes']).SetSelection(current)
+
             xyRange, zRange = self._display.GetXYRange(), self._display.GetZRange()
-            if xyRange > 0: # GTK warning
-                self.FindWindowById(self.win['cplane']['position']['x']['slider']).SetRange(
-                                                                    -xyRange/2., xyRange/2.)
-                self.FindWindowById(self.win['cplane']['position']['y']['slider']).SetRange(
-                                                                    -xyRange/2., xyRange/2.)
+            if xyRange > 0:  # GTK warning
+                self.FindWindowById(self.win['cplane']['position']['x'][
+                                    'slider']).SetRange(-xyRange / 2., xyRange / 2.)
+                self.FindWindowById(self.win['cplane']['position']['y'][
+                                    'slider']).SetRange(-xyRange / 2., xyRange / 2.)
             if zRange[1] - zRange[0] > 1:
-                self.FindWindowById(self.win['cplane']['position']['z']['slider']).SetRange(zRange[0], zRange[1])
-            self.FindWindowById(self.win['cplane']['position']['z']['slider']).SetValue(zRange[0])
-            self.FindWindowById(self.win['cplane']['position']['z']['text']).SetValue(zRange[0])
+                self.FindWindowById(
+                    self.win['cplane']['position']['z']['slider']).SetRange(
+                    zRange[0], zRange[1])
+            self.FindWindowById(
+                self.win['cplane']['position']['z']['slider']).SetValue(
+                zRange[0])
+            self.FindWindowById(
+                self.win['cplane']['position']['z']['text']).SetValue(
+                zRange[0])
             self.OnCPlaneSelection(None)
-            
+
         elif pageId == 'animation':
             self.UpdateAnimationPage()
-            
+
         self.Update()
         self.pageChanging = False
-        
+
     def UpdateAnimationPage(self):
         """Update animation page"""
         # wrap help text according to tool window
@@ -4626,109 +5215,142 @@
         if anim.Exists():
             self.FindWindowById(self.win['anim']['play']).Enable()
         else:
-            self.UpdateFrameIndex(index = 0)
-            
+            self.UpdateFrameIndex(index=0)
+
         self.UpdateFrameCount()
-        
+
         self.FindWindowById(self.win['anim']['play']).Disable()
         self.FindWindowById(self.win['anim']['record']).Enable()
         self.FindWindowById(self.win['anim']['pause']).Disable()
         self.FindWindowById(self.win['anim']['stop']).Disable()
         self.FindWindowById(self.win['anim']['frameIndex']['slider']).Disable()
         self.FindWindowById(self.win['anim']['frameIndex']['text']).Disable()
-        
+
     def UpdateCPlanePage(self, index):
         """Update widgets according to selected clip plane"""
-        if index == -1:   
+        if index == -1:
             return
         data = self.mapWindow.cplanes[index]
         for widget in ('text', 'slider'):
             for axes in ('x', 'y', 'z'):
-                self.FindWindowById(self.win['cplane']['position'][axes][widget]).SetValue(data['position'][axes])
+                self.FindWindowById(
+                    self.win['cplane']['position'][axes][widget]).SetValue(
+                    data['position'][axes])
             for each in ('tilt', 'rot'):
-                self.FindWindowById(self.win['cplane']['rotation'][each][widget]).SetValue(data['rotation'][each])
-        self.FindWindowById(self.win['cplane']['shading']).SetSelection(data['shading'])
-                
-    def UpdateSurfacePage(self, layer, data, updateName = True):
+                self.FindWindowById(
+                    self.win['cplane']['rotation'][each][widget]).SetValue(
+                    data['rotation'][each])
+        self.FindWindowById(
+            self.win['cplane']['shading']).SetSelection(
+            data['shading'])
+
+    def UpdateSurfacePage(self, layer, data, updateName=True):
         """Update surface page"""
         desc = grass.raster_info(layer.name)['title']
         if updateName:
-            self.FindWindowById(self.win['surface']['map']).SetValue(layer.name)
+            self.FindWindowById(
+                self.win['surface']['map']).SetValue(
+                layer.name)
         self.FindWindowById(self.win['surface']['desc']).SetLabel(desc)
-        
+
         # attributes
         if layer and layer.type == 'raster':
             self.vetoGSelectEvt = True
-            self.FindWindowById(self.win['surface']['color']['map']).SetValue(layer.name)
+            self.FindWindowById(
+                self.win['surface']['color']['map']).SetValue(
+                layer.name)
         else:
-            self.FindWindowById(self.win['surface']['color']['map']).SetValue('')
+            self.FindWindowById(
+                self.win['surface']['color']['map']).SetValue('')
 
-        self.SetMapObjUseMap(nvizType = 'surface',
-                             attrb = 'color', map = True) # -> map
-                                
+        self.SetMapObjUseMap(nvizType='surface',
+                             attrb='color', map=True)  # -> map
+
         if 'color' in data['attribute']:
             value = data['attribute']['color']['value']
 
             if data['attribute']['color']['map']:
-                self.FindWindowById(self.win['surface']['color']['map']).SetValue(value)
-            else: # constant
+                self.FindWindowById(
+                    self.win['surface']['color']['map']).SetValue(value)
+            else:  # constant
                 color = map(int, value.split(':'))
-                self.FindWindowById(self.win['surface']['color']['const']).SetColour(color)
-            self.SetMapObjUseMap(nvizType = 'surface',
-                                 attrb = 'color', map = data['attribute']['color']['map'])
+                self.FindWindowById(
+                    self.win['surface']['color']['const']).SetColour(color)
+            self.SetMapObjUseMap(
+                nvizType='surface', attrb='color',
+                map=data['attribute']['color']['map'])
 
-        self.SetMapObjUseMap(nvizType = 'surface',
-                             attrb = 'shine', map = data['attribute']['shine']['map'])
+        self.SetMapObjUseMap(
+            nvizType='surface', attrb='shine',
+            map=data['attribute']['shine']['map'])
         value = data['attribute']['shine']['value']
         if data['attribute']['shine']['map']:
-            self.FindWindowById(self.win['surface']['shine']['map']).SetValue(value)
+            self.FindWindowById(
+                self.win['surface']['shine']['map']).SetValue(value)
         else:
-            self.FindWindowById(self.win['surface']['shine']['const']).SetValue(self._getPercent(value))
-        if 'transp' in data['attribute']:  
-            value = data['attribute']['transp']['value']  
+            self.FindWindowById(
+                self.win['surface']['shine']['const']).SetValue(
+                self._getPercent(value))
+        if 'transp' in data['attribute']:
+            value = data['attribute']['transp']['value']
             if data['attribute']['transp']['map']:
-                self.FindWindowById(self.win['surface']['color']['map']).SetValue(value)
+                self.FindWindowById(
+                    self.win['surface']['color']['map']).SetValue(value)
             else:
-                self.FindWindowById(self.win['surface']['transp']['const']).SetValue(self._getPercent(value))
-            self.SetMapObjUseMap(nvizType = 'surface', attrb = 'transp', map = data['attribute']['transp']['map'])
+                self.FindWindowById(
+                    self.win['surface']['transp']['const']).SetValue(
+                    self._getPercent(value))
+            self.SetMapObjUseMap(
+                nvizType='surface',
+                attrb='transp',
+                map=data['attribute']['transp']['map'])
         else:
-            self.SetMapObjUseMap(nvizType = 'surface', attrb = 'transp', map = None)
+            self.SetMapObjUseMap(nvizType='surface', attrb='transp', map=None)
         #
         # draw
         #
         for control, drawData in data['draw'].iteritems():
-            if control == 'all': # skip 'all' property
+            if control == 'all':  # skip 'all' property
                 continue
             if control == 'resolution':
-                self.FindWindowById(self.win['surface']['draw']['res-coarse']).SetValue(drawData['coarse'])
-                self.FindWindowById(self.win['surface']['draw']['res-fine']).SetValue(drawData['fine'])
+                self.FindWindowById(self.win['surface']['draw'][
+                                    'res-coarse']).SetValue(drawData['coarse'])
+                self.FindWindowById(self.win['surface']['draw'][
+                                    'res-fine']).SetValue(drawData['fine'])
                 continue
-            
+
             if control == 'mode':
                 if drawData['desc']['mode'] == 'coarse':
-                    self.FindWindowById(self.win['surface']['draw']['mode']).SetSelection(0)
+                    self.FindWindowById(
+                        self.win['surface']['draw']['mode']).SetSelection(0)
                 elif drawData['desc']['mode'] == 'fine':
-                    self.FindWindowById(self.win['surface']['draw']['mode']).SetSelection(1)
-                else: # both
-                    self.FindWindowById(self.win['surface']['draw']['mode']).SetSelection(2)
-                
+                    self.FindWindowById(
+                        self.win['surface']['draw']['mode']).SetSelection(1)
+                else:  # both
+                    self.FindWindowById(
+                        self.win['surface']['draw']['mode']).SetSelection(2)
+
                 if drawData['desc']['style'] == 'wire':
-                    self.FindWindowById(self.win['surface']['draw']['style']).SetSelection(0)
-                else: # surface
-                    self.FindWindowById(self.win['surface']['draw']['style']).SetSelection(1)
-                
+                    self.FindWindowById(
+                        self.win['surface']['draw']['style']).SetSelection(0)
+                else:  # surface
+                    self.FindWindowById(
+                        self.win['surface']['draw']['style']).SetSelection(1)
+
                 if drawData['desc']['shading'] == 'flat':
-                    self.FindWindowById(self.win['surface']['draw']['shading']).SetSelection(0)
-                else: # gouraud
-                    self.FindWindowById(self.win['surface']['draw']['shading']).SetSelection(1)
-                
+                    self.FindWindowById(
+                        self.win['surface']['draw']['shading']).SetSelection(0)
+                else:  # gouraud
+                    self.FindWindowById(
+                        self.win['surface']['draw']['shading']).SetSelection(1)
+
                 continue
-            
+
             value = drawData['value']
             win = self.FindWindowById(self.win['surface']['draw'][control])
-            
+
             name = win.GetName()
-            
+
             if name == "selection":
                 win.SetSelection(value)
             elif name == "colour":
@@ -4742,9 +5364,9 @@
         self.OnSurfaceAxis(None)
 
         # enable/disable res widget + set draw mode
-        self.OnSurfaceMode(event = None)
-        
-    def UpdateVectorPage(self, layer, data, updateName = True):
+        self.OnSurfaceMode(event=None)
+
+    def UpdateVectorPage(self, layer, data, updateName=True):
         """Update vector page"""
         vInfo = grass.vector_info_topo(layer.GetName())
         if not vInfo:
@@ -4756,26 +5378,33 @@
             desc = _("Vector map is 2D")
             enable = True
         desc += " - " + _("%(features)d features (%(points)d points)") % \
-            { 'features' : vInfo['primitives'], 'points' : vInfo['points']}
-        
+            {'features': vInfo['primitives'], 'points': vInfo['points']}
+
         if updateName:
             self.FindWindowById(self.win['vector']['map']).SetValue(layer.name)
         self.FindWindowById(self.win['vector']['desc']).SetLabel(desc)
-        
+
         self.FindWindowById(self.win['vector']['lines']['3d']).Enable(enable)
         for v in ('lines', 'points'):
-            self.FindWindowById(self.win['vector'][v]['surface']).Enable(enable)
-            self.FindWindowById(self.win['vector'][v]['height']['slider']).Enable(enable)
-            self.FindWindowById(self.win['vector'][v]['height']['text']).Enable(enable)
-            
+            self.FindWindowById(
+                self.win['vector'][v]['surface']).Enable(enable)
+            self.FindWindowById(self.win['vector'][v]['height'][
+                                'slider']).Enable(enable)
+            self.FindWindowById(
+                self.win['vector'][v]['height']['text']).Enable(enable)
+
             if data[v]['thematic']['usecolor']:
-                check = self.FindWindowById(self.win['vector'][v]['thematic']['checkcolor'])
+                check = self.FindWindowById(
+                    self.win['vector'][v]['thematic']['checkcolor'])
                 check.SetValue(data[v]['thematic']['usecolor'])
-            if 'usesize' in data[v]['thematic'] and data[v]['thematic']['usesize']:
-                check = self.FindWindowById(self.win['vector'][v]['thematic']['checksize'])
+            if 'usesize' in data[v]['thematic'] and data[
+                    v]['thematic']['usesize']:
+                check = self.FindWindowById(
+                    self.win['vector'][v]['thematic']['checksize'])
                 check.SetValue(data[v]['thematic']['usesize'])
             elif 'usewidth' in data[v]['thematic'] and data[v]['thematic']['usewidth']:
-                check = self.FindWindowById(self.win['vector'][v]['thematic']['checkwidth'])
+                check = self.FindWindowById(
+                    self.win['vector'][v]['thematic']['checkwidth'])
                 check.SetValue(data[v]['thematic']['usewidth'])
             self.OnCheckThematic(None)
         #
@@ -4790,23 +5419,24 @@
             showLines.Enable(True)
         else:
             showLines.Enable(False)
-        
+
         self.UpdateVectorShow('lines', showLines.IsChecked())
-        
+
         width = self.FindWindowById(self.win['vector']['lines']['width'])
         width.SetValue(data['lines']['width']['value'])
-        
+
         color = self.FindWindowById(self.win['vector']['lines']['color'])
         color.SetValue(map(int, data['lines']['color']['value'].split(':')))
-        
+
         for vtype in ('lines', 'points'):
             if vtype == 'lines':
-                display = self.FindWindowById(self.win['vector']['lines']['3d'])
+                display = self.FindWindowById(
+                    self.win['vector']['lines']['3d'])
                 if vInfo['map3d']:
                     items = [_("on surface(s):"), _("as 3D")]
                 else:
                     items = [_("on surface")]
-                display.SetItems(items)               
+                display.SetItems(items)
                 if data[vtype]['mode']['type'] == '3d':
                     display.SetSelection(1)
                 else:
@@ -4815,24 +5445,26 @@
                 rasters = self.mapWindow.GetLayerNames('raster')
                 constants = self.mapWindow.GetLayerNames('constant')
                 surfaces = rasters + constants
-                surfaceWin = self.FindWindowById(self.win['vector'][vtype]['surface'])
+                surfaceWin = self.FindWindowById(
+                    self.win['vector'][vtype]['surface'])
                 surfaceWin.SetItems(surfaces)
                 for idx, surface in enumerate(surfaces):
-                    try:# TODO fix this mess
+                    try:  # TODO fix this mess
                         selected = data[vtype]['mode']['surface']['show'][idx]
                     except (TypeError, IndexError, KeyError):
                         selected = False
                     surfaceWin.Check(idx, selected)
 
         for type in ('slider', 'text'):
-            win = self.FindWindowById(self.win['vector']['lines']['height'][type])
+            win = self.FindWindowById(
+                self.win['vector']['lines']['height'][type])
             win.SetValue(data['lines']['height']['value'])
-        
+
         #
         # points
         #
         showPoints = self.FindWindowById(self.win['vector']['points']['show'])
-        
+
         if 'object' in data['points']:
             showPoints.SetValue(True)
         else:
@@ -4841,7 +5473,7 @@
             showPoints.Enable(True)
         else:
             showPoints.Enable(False)
-        
+
         self.UpdateVectorShow('points', showPoints.IsChecked())
         # size, width, marker, color
         for prop in ('size', 'marker', 'color'):
@@ -4865,27 +5497,29 @@
         else:
             win.SetSelection(0)
 
-##        self.OnCheckThematic(None)
+# self.OnCheckThematic(None)
         # height
         for type in ('slider', 'text'):
-            win = self.FindWindowById(self.win['vector']['points']['height'][type])
+            win = self.FindWindowById(
+                self.win['vector']['points']['height'][type])
             win.SetValue(data['points']['height']['value'])
-        
-    def UpdateVolumePage(self, layer, data, updateName = True):
+
+    def UpdateVolumePage(self, layer, data, updateName=True):
         """Update volume page"""
         if updateName:
             self.FindWindowById(self.win['volume']['map']).SetValue(layer.name)
-        
+
         # draw
         for control, idata in data['draw'].iteritems():
-            if control == 'all': # skip 'all' property
+            if control == 'all':  # skip 'all' property
                 continue
-                
+
             win = self.FindWindowById(self.win['volume']['draw'][control])
             if control == 'mode':
                 value = data['draw']['mode']['value']
             if control == 'shading':
-                if data['draw']['shading'][data['draw']['mode']['desc']]['desc'] == 'flat':
+                if data['draw']['shading'][data['draw']
+                                           ['mode']['desc']]['desc'] == 'flat':
                     value = 0
                 else:
                     value = 1
@@ -4893,22 +5527,26 @@
                 value = idata[data['draw']['mode']['desc']]['value']
             if control == 'box':
                 value = idata['enabled']
-            
+
             if win.GetName() == "selection":
                 win.SetSelection(value)
             else:
                 win.SetValue(value)
-                
+
         self.OnVolumeMode(None)
         id = data['object']['id']
         if data['draw']['mode']['desc'] == 'isosurface':
-            self._display.SetIsosurfaceMode(id, data['draw']['shading']['isosurface']['value'])
-            self._display.SetIsosurfaceRes(id, data['draw']['resolution']['isosurface']['value'])
+            self._display.SetIsosurfaceMode(
+                id, data['draw']['shading']['isosurface']['value'])
+            self._display.SetIsosurfaceRes(
+                id, data['draw']['resolution']['isosurface']['value'])
         else:
-            self._display.SetSliceMode(id, data['draw']['shading']['slice']['value'])
-            self._display.SetSliceRes(id, data['draw']['resolution']['slice']['value'])
+            self._display.SetSliceMode(
+                id, data['draw']['shading']['slice']['value'])
+            self._display.SetSliceRes(
+                id, data['draw']['resolution']['slice']['value'])
         box = self.FindWindowById(self.win['volume']['isosurfs'])
-        
+
         if data['draw']['mode']['desc'] == 'isosurface':
             isosurfaces = []
             for iso in data['isosurface']:
@@ -4940,33 +5578,39 @@
         #
         if 'z' in data['position']:
             zval = data['position']['z']
-            self.FindWindowById(self.win['volume']['position']['axis']).SetSelection(2)
-            for control in ('slider','text'):
-                    self.FindWindowById(self.win['volume']['position'][control]).SetValue(zval)
+            self.FindWindowById(
+                self.win['volume']['position']['axis']).SetSelection(2)
+            for control in ('slider', 'text'):
+                self.FindWindowById(
+                    self.win['volume']['position'][control]).SetValue(zval)
         # set topo range
-        mapRange = self._get3dRange(name = layer.name)
+        mapRange = self._get3dRange(name=layer.name)
         desc = self.FindWindowById(self.win['volume']['desc'])
-        desc.SetLabel("%s %.2f - %.2f" % (_("range:"), mapRange[0], mapRange[1]))
-        
+        desc.SetLabel(
+            "%s %.2f - %.2f" %
+            (_("range:"), mapRange[0], mapRange[1]))
+
     def UpdateVolumeIsosurfPage(self, data):
         """Update dialog -- isosurface attributes"""
         #
         # isosurface attributes
         #
         for attrb in ('topo', 'color', 'mask',
-                     'transp', 'shine'):
+                      'transp', 'shine'):
             # skip empty attributes
             if attrb not in data:
-                self.SetMapObjUseMap(nvizType = 'volume', attrb = attrb, map = None)
-                continue     
-            
+                self.SetMapObjUseMap(nvizType='volume', attrb=attrb, map=None)
+                continue
+
             value = data[attrb]['value']
             if attrb == 'color':
                 if data[attrb]['map']:
-                    self.FindWindowById(self.win['volume'][attrb]['map']).SetValue(value)
-                else: # constant
+                    self.FindWindowById(
+                        self.win['volume'][attrb]['map']).SetValue(value)
+                else:  # constant
                     color = map(int, value.split(':'))
-                    self.FindWindowById(self.win['volume'][attrb]['const']).SetColour(color)
+                    self.FindWindowById(
+                        self.win['volume'][attrb]['const']).SetColour(color)
             else:
                 if data[attrb]['map']:
                     self.vetoGSelectEvt = True
@@ -4974,51 +5618,60 @@
                     win.SetValue(value)
                 else:
                     if value:
-                        win = self.FindWindowById(self.win['volume'][attrb]['const'])
+                        win = self.FindWindowById(
+                            self.win['volume'][attrb]['const'])
                         if attrb == 'topo':
                             win.SetValue(float(value))
                         else:
                             win.SetValue(self._getPercent(value))
-                    
-            self.SetMapObjUseMap(nvizType = 'volume',
-                                 attrb = attrb, map = data[attrb]['map'])
+
+            self.SetMapObjUseMap(nvizType='volume',
+                                 attrb=attrb, map=data[attrb]['map'])
         # set inout
         if 'inout' in data:
-            self.FindWindowById(self.win['volume']['inout']).SetValue(data['inout']['value'])
-            
+            self.FindWindowById(
+                self.win['volume']['inout']).SetValue(
+                data['inout']['value'])
+
     def UpdateVolumeSlicePage(self, data):
         """Update dialog -- slice attributes"""
         if data:
             for coord in ('x1', 'x2', 'y1', 'y2', 'z1', 'z2'):
-                win = self.FindWindowById(self.win['volume']['slice']['slider_' + coord])
+                win = self.FindWindowById(
+                    self.win['volume']['slice'][
+                        'slider_' + coord])
                 win.Enable()
                 win.SetValue(data['position'][coord] * 100)
             win = self.FindWindowById(self.win['volume']['slice']['axes'])
             win.SetSelection(data['position']['axis'])
             win.Enable()
-            
+
             win = self.FindWindowById(self.win['volume']['slice']['transp'])
             win.SetValue(self._getPercent(data['transp']['value']))
             win.Enable()
             self.FindWindowById(self.win['volume']['slice']['reset']).Enable()
         else:
             for coord in ('x1', 'x2', 'y1', 'y2', 'z1', 'z2'):
-                self.FindWindowById(self.win['volume']['slice']['slider_' + coord]).Disable()
+                self.FindWindowById(
+                    self.win['volume']['slice'][
+                        'slider_' + coord]).Disable()
             self.FindWindowById(self.win['volume']['slice']['axes']).Disable()
-            self.FindWindowById(self.win['volume']['slice']['transp']).Disable()
+            self.FindWindowById(
+                self.win['volume']['slice']['transp']).Disable()
             self.FindWindowById(self.win['volume']['slice']['reset']).Disable()
-        
+
         self.UpdateSliceLabels()
-        
+
     def UpdateSliceLabels(self):
         """Update text labels of slice controls according to axis"""
-        sel = self.FindWindowById(self.win['volume']['slice']['axes']).GetSelection()
+        sel = self.FindWindowById(
+            self.win['volume']['slice']['axes']).GetSelection()
         if sel == 0:
             self.FindWindowByName('label_edge_0').SetLabel(_("North edge:"))
             self.FindWindowByName('label_edge_1').SetLabel(_("South edge:"))
             self.FindWindowByName('label_edge_2').SetLabel(_("West edge:"))
             self.FindWindowByName('label_edge_3').SetLabel(_("East edge:"))
-            
+
             self.FindWindowByName('label_coord_0').SetLabel(_("Northing (Y):"))
             self.FindWindowByName('label_coord_1').SetLabel(_("Height (Z):"))
             self.FindWindowByName('label_coord_2').SetLabel(_("Easting (X):"))
@@ -5027,7 +5680,7 @@
             self.FindWindowByName('label_edge_1').SetLabel(_("East edge:"))
             self.FindWindowByName('label_edge_2').SetLabel(_("North edge:"))
             self.FindWindowByName('label_edge_3').SetLabel(_("South edge:"))
-            
+
             self.FindWindowByName('label_coord_0').SetLabel(_("Easting (X):"))
             self.FindWindowByName('label_coord_1').SetLabel(_("Height (Z):"))
             self.FindWindowByName('label_coord_2').SetLabel(_("Northing (Y):"))
@@ -5035,12 +5688,12 @@
             self.FindWindowByName('label_edge_0').SetLabel(_("West edge:"))
             self.FindWindowByName('label_edge_1').SetLabel(_("East edge:"))
             self.FindWindowByName('label_edge_2').SetLabel(_("Bottom edge:"))
-            self.FindWindowByName('label_edge_3').SetLabel(_("Top edge:"))  
-            
+            self.FindWindowByName('label_edge_3').SetLabel(_("Top edge:"))
+
             self.FindWindowByName('label_coord_0').SetLabel(_("Easting (X):"))
             self.FindWindowByName('label_coord_1').SetLabel(_("Northing (Y):"))
-            self.FindWindowByName('label_coord_2').SetLabel(_("Height (Z):")) 
-        
+            self.FindWindowByName('label_coord_2').SetLabel(_("Height (Z):"))
+
     def SetPage(self, name):
         """Get named page"""
         if name == 'view':
@@ -5053,33 +5706,36 @@
         win = self.FindWindowById(self.page[name]['notebook'])
         try:
             win.Expand(win.GetFoldPanel(self.page[name]['id']))
-            self.UpdateScrolling((win.GetFoldPanel(self.page[name]['id']).GetGrandParent(),))
+            self.UpdateScrolling(
+                (win.GetFoldPanel(self.page[name]['id']).GetGrandParent(),))
         except AttributeError:
             win.SetSelection(self.page[name]['id'])
 
+
 class PositionWindow(wx.Window):
     """Abstract position control window, see subclasses
     ViewPostionWindow and LightPositionWindow"""
-    def __init__(self, parent, mapwindow, id = wx.ID_ANY,
+
+    def __init__(self, parent, mapwindow, id=wx.ID_ANY,
                  **kwargs):
         self.mapWindow = mapwindow
         self.quick = True
-        
+
         wx.Window.__init__(self, parent, id, **kwargs)
-        
+
         self.SetBackgroundColour("WHITE")
-        
+
         self.pdc = wx.PseudoDC()
-        
-        self.pdc.SetBrush(wx.Brush(colour = 'dark green', style = wx.SOLID))
-        self.pdc.SetPen(wx.Pen(colour = 'dark green', width = 2, style = wx.SOLID))
 
+        self.pdc.SetBrush(wx.Brush(colour='dark green', style=wx.SOLID))
+        self.pdc.SetPen(wx.Pen(colour='dark green', width=2, style=wx.SOLID))
+
         self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
         self.Bind(wx.EVT_PAINT, self.OnPaint)
         # self.Bind(wx.EVT_MOTION,       self.OnMouse)
         self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
-        
-    def Draw(self, pos, scale = False):
+
+    def Draw(self, pos, scale=False):
         w, h = self.GetClientSize()
         x, y = pos
         if scale:
@@ -5090,16 +5746,16 @@
         self.pdc.DrawLine(w / 2, h / 2, x, y)
         self.pdc.DrawCircle(x, y, 5)
         self.pdc.EndDrawing()
-        
+
     def OnPaint(self, event):
         dc = wx.BufferedPaintDC(self)
         dc.SetBackground(wx.Brush("White"))
         dc.Clear()
-        
+
         # probably does nothing, removed from wxPython 2.9
         # self.PrepareDC(dc)
         self.pdc.DrawToDC(dc)
-        
+
     def UpdatePos(self, xcoord, ycoord):
         """Update position coordinates (origin: UL)"""
         if xcoord < 0.0:
@@ -5110,102 +5766,108 @@
             ycoord = 0.0
         elif ycoord > 1.0:
             ycoord = 1.0
-        
+
         x, y = self.TransformCoordinates(xcoord, ycoord)
-        self.data['position']['x'] = x        
+        self.data['position']['x'] = x
         self.data['position']['y'] = y
-        
+
         return xcoord, ycoord
-    
+
     def OnMouse(self, event):
         if event.LeftIsDown():
             x, y = event.GetPosition()
-            self.Draw(pos = (x, y))
+            self.Draw(pos=(x, y))
             w, h = self.GetClientSize()
             x = float(x) / w
             y = float(y) / h
             self.UpdatePos(x, y)
             self.Refresh(False)
-        
+
         event.Skip()
-        
+
     def PostDraw(self):
         x, y = self.UpdatePos(self.data['position']['x'],
                               self.data['position']['y'])
-        
-        self.Draw(pos = (x,y), scale = True)
 
+        self.Draw(pos=(x, y), scale=True)
+
+
 class ViewPositionWindow(PositionWindow):
     """View position control widget"""
-    def __init__(self, parent, mapwindow, id = wx.ID_ANY,
+
+    def __init__(self, parent, mapwindow, id=wx.ID_ANY,
                  **kwargs):
         PositionWindow.__init__(self, parent, mapwindow, id, **kwargs)
-        self.SetToolTipString(_("Adjusts the distance and direction of the image viewpoint"))
+        self.SetToolTipString(
+            _("Adjusts the distance and direction of the image viewpoint"))
         self.data = self.mapWindow.view
         self.PostDraw()
-        
+
     def UpdatePos(self, xcoord, ycoord):
         x, y = PositionWindow.UpdatePos(self, xcoord, ycoord)
-        
-        event = wxUpdateView(zExag = True)
+
+        event = wxUpdateView(zExag=True)
         wx.PostEvent(self.mapWindow, event)
 
         return x, y
-    
-    def TransformCoordinates(self, x, y, toLight = True):
+
+    def TransformCoordinates(self, x, y, toLight=True):
         return x, y
-        
+
     def OnMouse(self, event):
-        self.mapWindow.iview['dir']['use'] = False # use focus instead of viewdir
+        # use focus instead of viewdir
+        self.mapWindow.iview['dir']['use'] = False
         PositionWindow.OnMouse(self, event)
         if event.LeftIsDown():
             self.mapWindow.render['quick'] = self.quick
-            self.mapWindow.Refresh(eraseBackground = False)
+            self.mapWindow.Refresh(eraseBackground=False)
         elif event.LeftUp():
             self.mapWindow.render['quick'] = False
-            self.mapWindow.Refresh(eraseBackground = False)
-        
+            self.mapWindow.Refresh(eraseBackground=False)
+
         event.Skip()
-    
+
+
 class LightPositionWindow(PositionWindow):
     """Light position control widget"""
-    def __init__(self, parent, mapwindow, id = wx.ID_ANY,
+
+    def __init__(self, parent, mapwindow, id=wx.ID_ANY,
                  **kwargs):
         PositionWindow.__init__(self, parent, mapwindow, id, **kwargs)
         self.SetToolTipString(_("Adjusts the light direction. "
                                 "Click and drag the puck to change the light direction."))
-        
+
         self.data = self.mapWindow.light
         self.quick = False
         self.PostDraw()
 
     def UpdatePos(self, xcoord, ycoord):
         x, y = PositionWindow.UpdatePos(self, xcoord, ycoord)
-        
-        event = wxUpdateLight(refresh = False)
+
+        event = wxUpdateLight(refresh=False)
         wx.PostEvent(self.mapWindow, event)
-        
+
         return x, y
-    
-    def TransformCoordinates(self, x, y, toLight = True):
+
+    def TransformCoordinates(self, x, y, toLight=True):
         if toLight:
             x = 2 * x - 1
             y = -2 * y + 1
         else:
-            x = (x + 1)/2
-            y = (1 - y)/2
+            x = (x + 1) / 2
+            y = (1 - y) / 2
         return x, y
-    
+
     def PostDraw(self):
-        event = wxUpdateLight(refresh = True)
+        event = wxUpdateLight(refresh=True)
         wx.PostEvent(self.mapWindow, event)
         x, y = self.data['position']['x'], self.data['position']['y']
-        x, y = self.TransformCoordinates(x, y, toLight = False)
-        
-        self.Draw(pos = (x,y), scale = True)
-        
+        x, y = self.TransformCoordinates(x, y, toLight=False)
+
+        self.Draw(pos=(x, y), scale=True)
+
     def OnMouse(self, event):
         PositionWindow.OnMouse(self, event)
         if event.LeftUp():
             self.mapWindow.render['quick'] = False
-            self.mapWindow.Refresh(eraseBackground = False)
+            self.mapWindow.Refresh(eraseBackground=False)

Modified: grass/trunk/gui/wxpython/nviz/workspace.py
===================================================================
--- grass/trunk/gui/wxpython/nviz/workspace.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/nviz/workspace.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -26,15 +26,18 @@
 
 
 class NvizSettings(object):
+
     def __init__(self):
         pass
 
     def SetConstantDefaultProp(self):
         """Set default constant data properties"""
         data = dict()
-        for key, value in UserSettings.Get(group='nviz', key='constant').iteritems():
+        for key, value in UserSettings.Get(
+                group='nviz', key='constant').iteritems():
             data[key] = value
-        color = str(data['color'][0]) + ':' + str(data['color'][1]) + ':' + str(data['color'][2])
+        color = str(data['color'][0]) + ':' + str(data['color']
+                                                  [1]) + ':' + str(data['color'][2])
         data['color'] = color
 
         return data
@@ -59,7 +62,7 @@
         #
         # draw
         #
-        data['draw']['all'] = False # apply only for current surface
+        data['draw']['all'] = False  # apply only for current surface
         for control, value in UserSettings.Get(group='nviz', key='surface',
                                                subkey='draw').iteritems():
             if control[:3] == 'res':
@@ -71,25 +74,32 @@
                 continue
 
             if control == 'wire-color':
-                value = str(value[0]) + ':' + str(value[1]) + ':' + str(value[2])
+                value = str(value[0]) + ':' + str(value[1]
+                                                  ) + ':' + str(value[2])
             elif control in ('mode', 'style', 'shading'):
                 if 'mode' not in data['draw']:
                     data['draw']['mode'] = {}
                 continue
 
-            data['draw'][control] = { 'value' : value }
+            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']))
+        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,
-                                 'update': None }
+        data['draw']['mode'] = {'value': value,
+                                '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'][coord] = UserSettings.Get(
+                group='nviz', key='surface', subkey=['position', coord])
         data['position']['update'] = None
 
         return data
@@ -100,37 +110,44 @@
         for sec in ('attribute', 'draw', 'position'):
             data[sec] = dict()
             for sec in ('isosurface', 'slice'):
-                    data[sec] = list()
+                data[sec] = list()
 
         #
         # draw
         #
-        for control, value in UserSettings.Get(group='nviz', key='volume', subkey='draw').iteritems():
+        for control, value in UserSettings.Get(
+                group='nviz', key='volume', subkey='draw').iteritems():
             if control == 'shading':
-                sel = UserSettings.Get(group='nviz', key='volume', subkey=['draw', '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'] }
-                data['draw']['shading']['slice'] = { 'value' : value,
-                                                     'desc' : desc['shading'] }
+                data['draw']['shading']['isosurface'] = {
+                    'value': value, 'desc': desc['shading']}
+                data['draw']['shading']['slice'] = {'value': value,
+                                                    'desc': desc['shading']}
             elif control == 'mode':
-                sel = UserSettings.Get(group='nviz', key='volume', subkey=['draw', 'mode'])
+                sel = UserSettings.Get(
+                    group='nviz', key='volume', subkey=[
+                        'draw', 'mode'])
                 if sel == 0:
                     desc = 'isosurface'
                 else:
                     desc = 'slice'
-                data['draw']['mode'] = { 'value' : sel,
-                                         'desc' : desc, }
+                data['draw']['mode'] = {'value': sel,
+                                        'desc': desc, }
             elif control == 'box':
-                box = UserSettings.Get(group = 'nviz', key = 'volume', subkey = ['draw', 'box'])
+                box = UserSettings.Get(
+                    group='nviz', key='volume', subkey=[
+                        'draw', 'box'])
                 data['draw']['box'] = {'enabled': box}
 
             else:
                 data['draw'][control] = {}
-                data['draw'][control]['isosurface'] = { 'value' : value }
-                data['draw'][control]['slice'] = { 'value' : value }
+                data['draw'][control]['isosurface'] = {'value': value}
+                data['draw'][control]['slice'] = {'value': value}
 
             if 'update' not in data['draw'][control]:
                 data['draw'][control]['update'] = None
@@ -155,20 +172,26 @@
             if attr == 'inout':
                 data[attr]['value'] = 0
                 continue
-            for key, value in UserSettings.Get(group = 'nviz', key = 'volume',
-                                               subkey = attr).iteritems():
+            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',
-                                               subkey = 'slice_position'))
+        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):
@@ -208,16 +231,21 @@
         data['mode']['update'] = None
 
         # height
-        data['height'] = { 'value' : UserSettings.Get(group='nviz', key='vector',
-                                                      subkey=['lines', 'height']) }
+        data['height'] = {
+            'value': UserSettings.Get(
+                group='nviz',
+                key='vector',
+                subkey=[
+                    'lines',
+                    'height'])}
         # thematic
-        data['thematic'] = {'rgbcolumn' : UserSettings.Get(group='nviz', key='vector',
-                                                      subkey=['lines', 'rgbcolumn']),
-                            'sizecolumn' : UserSettings.Get(group='nviz', key='vector',
-                                                      subkey=['lines', 'sizecolumn']),
+        data['thematic'] = {'rgbcolumn': UserSettings.Get(group='nviz', key='vector',
+                                                          subkey=['lines', 'rgbcolumn']),
+                            'sizecolumn': UserSettings.Get(group='nviz', key='vector',
+                                                           subkey=['lines', 'sizecolumn']),
                             'layer': 1,
-                            'usecolor' : False,
-                            'usewidth' : False}
+                            'usecolor': False,
+                            'usewidth': False}
         if 'object' in data:
             for attrb in ('color', 'width', 'mode', 'height', 'thematic'):
                 data[attrb]['update'] = None
@@ -225,38 +253,57 @@
     def SetVectorPointsDefaultProp(self, data):
         """Set default vector properties -- points"""
         # size
-        data['size'] = { 'value' : UserSettings.Get(group='nviz', key='vector',
-                                                    subkey=['points', 'size']) }
+        data['size'] = {'value': UserSettings.Get(group='nviz', key='vector',
+                                                  subkey=['points', 'size'])}
 
         # width
-        data['width'] = { 'value' : UserSettings.Get(group='nviz', key='vector',
-                                                     subkey=['points', 'width']) }
+        data['width'] = {'value': UserSettings.Get(group='nviz', key='vector',
+                                                   subkey=['points', 'width'])}
 
         # marker
-        data['marker'] = { 'value' : UserSettings.Get(group='nviz', key='vector',
-                                                      subkey=['points', 'marker']) }
+        data['marker'] = {
+            'value': UserSettings.Get(
+                group='nviz',
+                key='vector',
+                subkey=[
+                    'points',
+                    'marker'])}
 
         # color
         value = UserSettings.Get(group='nviz', key='vector',
                                  subkey=['points', 'color'])
         color = str(value[0]) + ':' + str(value[1]) + ':' + str(value[2])
-        data['color'] = { 'value' : color }
+        data['color'] = {'value': color}
 
         # mode
-        data['mode'] = { 'type' : 'surface'}
-##                         'surface' : '', }
+        data['mode'] = {'type': 'surface'}
+# 'surface' : '', }
 
         # height
-        data['height'] = { 'value' : UserSettings.Get(group='nviz', key='vector',
-                                                      subkey=['points', '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',
-                                                      subkey=['points', 'sizecolumn']),
-                            'layer': 1,
-                            'usecolor' : False,
-                            'usesize' : False}
+        data['thematic'] = {
+            'rgbcolumn': UserSettings.Get(
+                group='nviz',
+                key='vector',
+                subkey=[
+                    'points',
+                    'rgbcolumn']),
+            'sizecolumn': UserSettings.Get(
+                group='nviz',
+                key='vector',
+                subkey=[
+                    'points',
+                    'sizecolumn']),
+            'layer': 1,
+            'usecolor': False,
+            'usesize': False}
         if 'object' in data:
             for attrb in ('size', 'width', 'marker',
                           'color', 'height', 'thematic'):
@@ -283,40 +330,40 @@
                     value |= wxnviz.DM_WIRE
                 elif mode == 'fine':
                     value |= wxnviz.DM_POLY
-                else: # both
+                else:  # both
                     value |= wxnviz.DM_WIRE_POLY
 
             if style is not None:
                 if style == 'wire':
                     value |= wxnviz.DM_GRID_WIRE
-                else: # surface
+                else:  # surface
                     value |= wxnviz.DM_GRID_SURF
 
             if shade is not None:
                 if shade == 'flat':
                     value |= wxnviz.DM_FLAT
-                else: # surface
+                else:  # surface
                     value |= wxnviz.DM_GOURAUD
 
             return value
 
         # -> string is False
         if mode is not None:
-            if mode == 0: # coarse
+            if mode == 0:  # coarse
                 value |= wxnviz.DM_WIRE
                 desc['mode'] = 'coarse'
-            elif mode == 1: # fine
+            elif mode == 1:  # fine
                 value |= wxnviz.DM_POLY
                 desc['mode'] = 'fine'
-            else: # both
+            else:  # both
                 value |= wxnviz.DM_WIRE_POLY
                 desc['mode'] = 'both'
 
         if style is not None:
-            if style == 0: # wire
+            if style == 0:  # wire
                 value |= wxnviz.DM_GRID_WIRE
                 desc['style'] = 'wire'
-            else: # surface
+            else:  # surface
                 value |= wxnviz.DM_GRID_SURF
                 desc['style'] = 'surface'
 
@@ -324,7 +371,7 @@
             if shade == 0:
                 value |= wxnviz.DM_FLAT
                 desc['shading'] = 'flat'
-            else: # surface
+            else:  # surface
                 value |= wxnviz.DM_GOURAUD
                 desc['shading'] = 'gouraud'
 
@@ -342,9 +389,12 @@
             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',
-                                                                settings_type='internal')))
+            data['arrow'].update(
+                copy.deepcopy(
+                    UserSettings.Get(
+                        group='nviz',
+                        key='arrow',
+                        settings_type='internal')))
             data['arrow']['show'] = False
 
         # arrow
@@ -354,8 +404,11 @@
             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',
-                                                                   settings_type='internal')))
+            data['scalebar'].update(
+                copy.deepcopy(
+                    UserSettings.Get(
+                        group='nviz',
+                        key='scalebar',
+                        settings_type='internal')))
             data['scalebar']['id'] = 0
         return data

Modified: grass/trunk/gui/wxpython/nviz/wxnviz.py
===================================================================
--- grass/trunk/gui/wxpython/nviz/wxnviz.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/nviz/wxnviz.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -25,35 +25,37 @@
 import sys
 import locale
 import struct
-from math  import sqrt
+from math import sqrt
 try:
     from numpy import matrix
 except ImportError:
-    msg = _("This module requires the NumPy module, which could not be "
-            "imported. It probably is not installed (it's not part of the "
-            "standard Python distribution). See the Numeric Python site "
-            "(http://numpy.scipy.org) for information on downloading source or "
-            "binaries.")
+    msg = _(
+        "This module requires the NumPy module, which could not be "
+        "imported. It probably is not installed (it's not part of the "
+        "standard Python distribution). See the Numeric Python site "
+        "(http://numpy.scipy.org) for information on downloading source or "
+        "binaries.")
     print >> sys.stderr, "wxnviz.py: " + msg
 
 import wx
 
 from ctypes import *
 
-from grass.lib.gis      import *
+from grass.lib.gis import *
 from grass.lib.raster3d import *
-from grass.lib.vector   import *
-from grass.lib.ogsf     import *
-from grass.lib.nviz     import *
-from grass.lib.raster   import *
+from grass.lib.vector import *
+from grass.lib.ogsf import *
+from grass.lib.nviz import *
+from grass.lib.raster import *
 
 from core.debug import Debug
 from core.utils import _
 import grass.script as grass
 
-log      = None
+log = None
 progress = None
 
+
 def print_error(msg, type):
     """Redirect stderr"""
     global log
@@ -61,9 +63,10 @@
         log.write(msg)
     else:
         print msg
-    
+
     return 0
 
+
 def print_progress(value):
     """Redirect progress info"""
     global progress
@@ -73,7 +76,7 @@
         progress.SetValue(value)
     else:
         print value
-    
+
     return 0
 
 try:
@@ -84,34 +87,36 @@
 except NameError:
     pass
 
+
 class Nviz(object):
+
     def __init__(self, glog, gprogress):
         """Initialize Nviz class instance
-        
+
         :param glog: logging area
         :param gprogress: progressbar
         """
         global errfunc, perfunc, log, progress
         log = glog
         progress = gprogress
-        
+
         G_gisinit("wxnviz")
         # gislib is already initialized (where?)
-        G_set_error_routine(errfunc) 
+        G_set_error_routine(errfunc)
         G_set_percent_routine(perfunc)
-        
+
         self.Init()
-        
+
         self.data_obj = nv_data()
         self.data = pointer(self.data_obj)
         self.color_obj = Colors()
         self.color = pointer(self.color_obj)
-        
+
         self.width = self.height = -1
         self.showLight = False
-        
+
         Debug.msg(1, "Nviz::Nviz()")
-        
+
     def __del__(self):
         """Destroy Nviz class instance"""
         G_unset_error_routine()
@@ -129,46 +134,46 @@
         GS_libinit()
         GVL_libinit()
         GVL_init_region()
-    
+
     def ResizeWindow(self, width, height):
         """GL canvas resized
-        
+
         :param width: window width
         :param height: window height
-        
+
         :return: 1 on success
         :return: 0 on failure (window resized by default to 20x20 px)
         """
-        self.width  = width
+        self.width = width
         self.height = height
         Debug.msg(3, "Nviz::ResizeWindow(): width=%d height=%d",
                   width, height)
         return Nviz_resize_window(width, height)
-    
+
     def GetLongDim(self):
         """Get longest dimension, used for initial size of north arrow"""
         return Nviz_get_longdim(self.data)
-    
+
     def SetViewDefault(self):
         """Set default view (based on loaded data)
-        
+
         :return: z-exag value, default, min and max height
         """
         # determine z-exag
         z_exag = Nviz_get_exag()
         Nviz_change_exag(self.data, z_exag)
-        
+
         # determine height
         hdef = c_double()
         hmin = c_double()
         hmax = c_double()
         Nviz_get_exag_height(byref(hdef), byref(hmin), byref(hmax))
-        
+
         Debug.msg(1, "Nviz::SetViewDefault(): hdef=%f, hmin=%f, hmax=%f",
                   hdef.value, hmin.value, hmax.value)
-        
+
         return (z_exag, hdef.value, hmin.value, hmax.value)
-    
+
     def SetView(self, x, y, height, persp, twist):
         """Change view settings
         :param x,y: position
@@ -180,32 +185,38 @@
         Nviz_set_viewpoint_position(x, y)
         Nviz_set_viewpoint_twist(twist)
         Nviz_set_viewpoint_persp(persp)
-        
-        Debug.msg(3, "Nviz::SetView(): x=%f, y=%f, height=%f, persp=%f, twist=%f",
-                  x, y, height, persp, twist)
-                
+
+        Debug.msg(
+            3,
+            "Nviz::SetView(): x=%f, y=%f, height=%f, persp=%f, twist=%f",
+            x,
+            y,
+            height,
+            persp,
+            twist)
+
     def GetViewpointPosition(self):
         x = c_double()
         y = c_double()
         h = c_double()
         Nviz_get_viewpoint_height(byref(h))
         Nviz_get_viewpoint_position(byref(x), byref(y))
-        
+
         return (x.value, y.value, h.value)
-        
+
     def LookHere(self, x, y):
-        """Look here feature 
+        """Look here feature
         :param x,y: screen coordinates
         """
-        
+
         Nviz_look_here(x, y)
         Debug.msg(3, "Nviz::LookHere(): x=%f, y=%f", x, y)
-    
+
     def LookAtCenter(self):
         """Center view at center of displayed surface"""
         Nviz_set_focus_map(MAP_OBJ_UNDEFINED, -1)
         Debug.msg(3, "Nviz::LookAtCenter()")
-    
+
     def GetFocus(self):
         """Get focus"""
         Debug.msg(3, "Nviz::GetFocus()")
@@ -217,20 +228,20 @@
             return x.value, y.value, z.value
         else:
             return -1, -1, -1
-        
+
     def SetFocus(self, x, y, z):
         """Set focus"""
         Debug.msg(3, "Nviz::SetFocus()")
         Nviz_set_focus(self.data, x, y, z)
-        
+
     def GetViewdir(self):
         """Get viewdir"""
         Debug.msg(3, "Nviz::GetViewdir()")
         dir = (c_float * 3)()
         GS_get_viewdir(byref(dir))
-        
+
         return dir[0], dir[1], dir[2]
-        
+
     def SetViewdir(self, x, y, z):
         """Set viewdir"""
         Debug.msg(3, "Nviz::SetViewdir(): x=%f, y=%f, z=%f" % (x, y, z))
@@ -238,70 +249,70 @@
         for i, coord in enumerate((x, y, z)):
             dir[i] = coord
         GS_set_viewdir(byref(dir))
-                
+
     def SetZExag(self, z_exag):
         """Set z-exag value
-        
+
         :param z_exag: value
-        
+
         :return: 1
         """
         Debug.msg(3, "Nviz::SetZExag(): z_exag=%f", z_exag)
         return Nviz_change_exag(self.data, z_exag)
-    
+
     def Draw(self, quick, quick_mode):
         """Draw canvas
-        
+
         Draw quick mode:
          - DRAW_QUICK_SURFACE
          - DRAW_QUICK_VLINES
          - DRAW_QUICK_VPOINTS
          - DRAW_QUICK_VOLUME
-        
+
         :param quick: if true draw in wiremode
         :param quick_mode: quick mode
         """
         Debug.msg(3, "Nviz::Draw(): quick=%d", quick)
-        
-        Nviz_draw_cplane(self.data, -1, -1) # ?
-        
+
+        Nviz_draw_cplane(self.data, -1, -1)  # ?
+
         if quick:
             Nviz_draw_quick(self.data, quick_mode)
         else:
             Nviz_draw_all(self.data)
-        
+
     def EraseMap(self):
         """Erase map display (with background color)
         """
         Debug.msg(1, "Nviz::EraseMap()")
         GS_clear(Nviz_get_bgcolor(self.data))
-        
+
     def InitView(self):
         """Initialize view"""
         # initialize nviz data
         Nviz_init_data(self.data)
-        
+
         # define default attributes for map objects
         Nviz_set_surface_attr_default()
         # set background color
         Nviz_set_bgcolor(self.data, Nviz_color_from_str("white"))
-        
-        GS_clear(Nviz_get_bgcolor(self.data))        
+
+        GS_clear(Nviz_get_bgcolor(self.data))
         # initialize view, lights
         Nviz_init_view(self.data)
-        
+
         Debug.msg(1, "Nviz::InitView()")
-        
+
     def SetBgColor(self, color_str):
         """Set background color
-        
+
         :param str color_str: color string
         """
         Nviz_set_bgcolor(self.data, Nviz_color_from_str(color_str))
-        
-    def SetLight(self, x, y, z, color, bright, ambient, w = 0, lid = 1):
+
+    def SetLight(self, x, y, z, color, bright, ambient, w=0, lid=1):
         """Change lighting settings
-        
+
         :param x,y,z: position
         :param color: light color (as string)
         :param bright: light brightness
@@ -311,16 +322,20 @@
         """
         Nviz_set_light_position(self.data, lid, x, y, z, w)
         Nviz_set_light_bright(self.data, lid, bright)
-        Nviz_set_light_color(self.data, lid, int(color[0]), int(color[1]), int(color[2]))
+        Nviz_set_light_color(
+            self.data, lid, int(
+                color[0]), int(
+                color[1]), int(
+                color[2]))
         Nviz_set_light_ambient(self.data, lid, ambient)
-                             
+
     def LoadSurface(self, name, color_name, color_value):
         """Load raster map (surface)
-        
+
         :param name: raster map name
         :param color_name: raster map for color (None for color_value)
         :param color_value: color string (named color or RGB triptet)
-        
+
         :return: object id
         :return: -1 on failure
         """
@@ -328,95 +343,95 @@
         if mapset is None:
             G_warning(_("Raster map <%s> not found"), name)
             return -1
-        
+
         # topography
         id = Nviz_new_map_obj(MAP_OBJ_SURF,
                               G_fully_qualified_name(name, mapset), 0.0,
                               self.data)
-        
+
         if color_name:      # check for color map
             mapset = G_find_raster2(color_name, "")
             if mapset is None:
                 G_warning(_("Raster map <%s> not found"), color_name)
                 GS_delete_surface(id)
                 return -1
-            
+
             Nviz_set_attr(id, MAP_OBJ_SURF, ATT_COLOR, MAP_ATT,
                           G_fully_qualified_name(color_name, mapset), -1.0,
                           self.data)
-        
+
         elif color_value:   # check for color value
             Nviz_set_attr(id, MAP_OBJ_SURF, ATT_COLOR, CONST_ATT,
                           None, Nviz_color_from_str(color_value),
                           self.data)
-        
+
         else:               # use by default elevation map for coloring
             Nviz_set_attr(id, MAP_OBJ_SURF, ATT_COLOR, MAP_ATT,
                           G_fully_qualified_name(name, mapset), -1.0,
                           self.data)
-        
+
         # if (i > 1)
         #     set_default_wirecolors(self.data, i)
-        
+
         # focus on loaded self.data
         Nviz_set_focus_map(MAP_OBJ_UNDEFINED, -1)
-        
+
         Debug.msg(1, "Nviz::LoadRaster(): name=%s -> id=%d", name, id)
-        
+
         return id
-    
+
     def AddConstant(self, value, color):
         """Add new constant surface"""
         id = Nviz_new_map_obj(MAP_OBJ_SURF, None, value, self.data)
-        
+
         Nviz_set_attr(id, MAP_OBJ_SURF, ATT_COLOR, CONST_ATT,
-                        None, Nviz_color_from_str(color),
-                        self.data)
+                      None, Nviz_color_from_str(color),
+                      self.data)
         Nviz_set_focus_map(MAP_OBJ_UNDEFINED, -1)
-        
+
         Debug.msg(1, "Nviz::AddConstant(): id=%d", id)
         return id
-        
+
     def UnloadSurface(self, id):
         """Unload surface
-        
+
         :param id: surface id
-        
+
         :return: 1 on success
         :return: 0 on failure
         """
         if not GS_surf_exists(id):
             return 0
-        
+
         Debug.msg(1, "Nviz::UnloadSurface(): id=%d", id)
-        
+
         if GS_delete_surface(id) < 0:
             return 0
-        
+
         return 1
-    
+
     def LoadVector(self, name, points):
         """Load vector map overlay
-        
+
         :param name: vector map name
         :param points: if true load 2d points rather then 2d lines
-        
+
         :return: object id, id of base surface (or -1 if it is not loaded)
         :return: -1 on failure
         """
         baseId = -1
         if GS_num_surfs() == 0:     # load base surface if no loaded
             baseId = Nviz_new_map_obj(MAP_OBJ_SURF, None, 0.0, self.data)
-            
+
             nsurf = c_int()
             surf_list = GS_get_surf_list(byref(nsurf))
             GS_set_att_const(surf_list[0], ATT_TRANSP, 255)
-            
-        mapset = G_find_vector2 (name, "")
+
+        mapset = G_find_vector2(name, "")
         if mapset is None:
             G_warning(_("Vector map <%s> not found"),
                       name)
-        
+
         if points:
             id = Nviz_new_map_obj(MAP_OBJ_SITE,
                                   G_fully_qualified_name(name, mapset), 0.0,
@@ -425,22 +440,22 @@
             id = Nviz_new_map_obj(MAP_OBJ_VECT,
                                   G_fully_qualified_name(name, mapset), 0.0,
                                   self.data)
-        
+
         Debug.msg(1, "Nviz::LoadVector(): name=%s -> id=%d", name, id)
-        
+
         return id, baseId
-    
+
     def UnloadVector(self, id, points):
         """Unload vector set
-        
+
         :param id: vector set id
         :param points: vector points or lines set
-        
+
         :return: 1 on success
         :return: 0 on failure
         """
         Debug.msg(1, "Nviz::UnloadVector(): id=%d", id)
-        
+
         if points:
             if not GP_site_exists(id):
                 return 0
@@ -451,29 +466,34 @@
                 return 0
             if GV_delete_vector(id) < 0:
                 return 0
-        
+
         return 1
 
     def VectorSurfaceSelected(self, vid, sid):
         """Check if surface is selected (currently unused)
-        
+
         :param vid: vector id
         :param sid: surface id
-        
+
         :return: True if selected
         :return: False if not selected
         """
         selected = GV_surf_is_selected(vid, sid)
-        Debug.msg(1, "Nviz::VectorSurfaceSelected(): vid=%s, sid=%d -> selected=%d", vid, sid, selected)
+        Debug.msg(
+            1,
+            "Nviz::VectorSurfaceSelected(): vid=%s, sid=%d -> selected=%d",
+            vid,
+            sid,
+            selected)
         return selected
-    
+
     def LoadVolume(self, name, color_name, color_value):
         """Load 3d raster map (volume)
-        
+
         :param name: 3d raster map name
         :param color_name: 3d raster map for color (None for color_value)
         :param color_value: color string (named color or RGB triptet)
-        
+
         :return: object id
         :return: -1 on failure
         """
@@ -482,12 +502,12 @@
             G_warning(_("3d raster map <%s> not found"),
                       name)
             return -1
-        
+
         # topography
         id = Nviz_new_map_obj(MAP_OBJ_VOL,
                               G_fully_qualified_name(name, mapset), 0.0,
                               self.data)
-        
+
         if color_name:      # check for color map
             mapset = G_find_raster3d(color_name, "")
             if mapset is None:
@@ -495,7 +515,7 @@
                           color_name)
                 GVL_delete_vol(id)
                 return -1
-            
+
             Nviz_set_attr(id, MAP_OBJ_VOL, ATT_COLOR, MAP_ATT,
                           G_fully_qualified_name(color_name, mapset), -1.0,
                           self.data)
@@ -507,128 +527,128 @@
             Nviz_set_attr(id, MAP_OBJ_VOL, ATT_COLOR, MAP_ATT,
                           G_fully_qualified_name(name, mapset), -1.0,
                           self.data)
-        
+
         Debug.msg(1, "Nviz::LoadVolume(): name=%s -> id=%d", name, id)
-        
+
         return id
 
     def UnloadVolume(self, id):
         """Unload volume
-        
+
         :param id: volume id
-        
+
         :return: 1 on success
         :return: 0 on failure
         """
         if not GVL_vol_exists(id):
             return 0
-        
+
         Debug.msg(1, "Nviz::UnloadVolume(): id=%d", id)
-        
+
         if GVL_delete_vol(id) < 0:
-          return 0
-        
+            return 0
+
         return 1
-    
+
     def SetSurfaceTopo(self, id, map, value):
         """Set surface topography
-        
+
         :param id: surface id
         :param map: if true use map otherwise constant
         :param value: map name of value
-        
+
         :return: 1 on success
         :return: -1 surface not found
         :return: -2 setting attributes failed
         """
         return self.SetSurfaceAttr(id, ATT_TOPO, map, value)
-    
+
     def SetSurfaceColor(self, id, map, value):
         """Set surface color
-        
+
         :param id: surface id
         :param map: if true use map otherwise constant
         :param value: map name or value
-        
+
         :return: 1 on success
         :return: -1 surface not found
         :return: -2 setting attributes failed
         """
         return self.SetSurfaceAttr(id, ATT_COLOR, map, value)
-    
+
     def SetSurfaceMask(self, id, invert, value):
         """Set surface mask
-        
+
         .. todo::
             invert
-        
+
         :param id: surface id
-        :param invert: if true invert mask 
+        :param invert: if true invert mask
         :param value: map name of value
-        
+
         :return: 1 on success
         :return: -1 surface not found
         :return: -2 setting attributes failed
         """
         return self.SetSurfaceAttr(id, ATT_MASK, True, value)
-    
+
     def SetSurfaceTransp(self, id, map, value):
         """Set surface mask
-        
+
         ..todo::
             invert
-        
+
         :param id: surface id
         :param map: if true use map otherwise constant
         :param value: map name of value
-        
+
         :return: 1 on success
         :return: -1 surface not found
         :return: -2 setting attributes failed
         """
         return self.SetSurfaceAttr(id, ATT_TRANSP, map, value)
-    
+
     def SetSurfaceShine(self, id, map, value):
         """Set surface shininess
-        
+
         :param id: surface id
         :param map: if true use map otherwise constant
         :param value: map name of value
-        
+
         :return: 1 on success
         :return: -1 surface not found
         :return: -2 setting attributes failed
         """
         return self.SetSurfaceAttr(id, ATT_SHINE, map, value)
-    
+
     def SetSurfaceEmit(self, id, map, value):
         """Set surface emission (currently unused)
-        
+
         :param id: surface id
         :param map: if true use map otherwise constant
         :param value: map name of value
-        
+
         :return: 1 on success
         :return: -1 surface not found
         :return: -2 setting attributes failed
         """
         return self.SetSurfaceAttr(id, ATT_EMIT, map, value)
-    
+
     def SetSurfaceAttr(self, id, attr, map, value):
         """Set surface attribute
-        
+
         :param id: surface id
         :param attr: attribute desc
         :param map: if true use map otherwise constant
         :param value: map name of value
-        
+
         :return: 1 on success
         :return: -1 surface not found
         :return: -2 setting attributes failed
         """
         if not GS_surf_exists(id):
             return -1
-        
+
         if map:
             ret = Nviz_set_attr(id, MAP_OBJ_SURF, attr, MAP_ATT,
                                 value, -1.0, self.data)
@@ -637,103 +657,108 @@
                 val = Nviz_color_from_str(value)
             else:
                 val = float(value)
-            
+
             ret = Nviz_set_attr(id, MAP_OBJ_SURF, attr, CONST_ATT,
                                 None, val, self.data)
-        
-        Debug.msg(3, "Nviz::SetSurfaceAttr(): id=%d, attr=%d, map=%d, value=%s",
-                  id, attr, map, value)
-        
+
+        Debug.msg(
+            3,
+            "Nviz::SetSurfaceAttr(): id=%d, attr=%d, map=%d, value=%s",
+            id,
+            attr,
+            map,
+            value)
+
         if ret < 0:
             return -2
-        
+
         return 1
-    
+
     def UnsetSurfaceMask(self, id):
         """Unset surface mask
-        
+
         :param id: surface id
-        
+
         :return: 1 on success
         :return: -1 surface not found
         :return: -2 setting attributes failed
         :return: -1 on failure
         """
         return self.UnsetSurfaceAttr(id, ATT_MASK)
-    
+
     def UnsetSurfaceTransp(self, id):
         """Unset surface transparency
-        
+
         :param id: surface id
-        
+
         :return: 1 on success
         :return: -1 surface not found
         :return: -2 setting attributes failed
         """
         return self.UnsetSurfaceAttr(id, ATT_TRANSP)
-    
+
     def UnsetSurfaceEmit(self, id):
         """Unset surface emission (currently unused)
-        
+
         :param id: surface id
-        
+
         :return: 1 on success
         :return: -1 surface not found
         :return: -2 setting attributes failed
         """
         return self.UnsetSurfaceAttr(id, ATT_EMIT)
-    
+
     def UnsetSurfaceAttr(self, id, attr):
         """Unset surface attribute
-        
+
         :param id: surface id
         :param attr: attribute descriptor
-        
+
         :return: 1 on success
         :return: -1 surface not found
         :return: -2 setting attributes failed
         """
         if not GS_surf_exists(id):
             return -1
-        
+
         Debug.msg(3, "Nviz::UnsetSurfaceAttr(): id=%d, attr=%d",
                   id, attr)
-        
+
         ret = Nviz_unset_attr(id, MAP_OBJ_SURF, attr)
-        
+
         if ret < 0:
             return -2
-        
+
         return 1
 
     def SetSurfaceRes(self, id, fine, coarse):
         """Set surface resolution
-        
+
         :param id: surface id
         :param fine: x/y fine resolution
         :param coarse: x/y coarse resolution
-        
+
         :return: 1 on success
         :return: -1 surface not found
         :return: -2 setting attributes failed
         """
         Debug.msg(3, "Nviz::SetSurfaceRes(): id=%d, fine=%d, coarse=%d",
                   id, fine, coarse)
-        
+
         if id > 0:
             if not GS_surf_exists(id):
                 return -1
-            
+
             if GS_set_drawres(id, fine, fine, coarse, coarse) < 0:
                 return -2
         else:
             GS_setall_drawres(fine, fine, coarse, coarse)
-        
+
         return 1
 
     def SetSurfaceStyle(self, id, style):
         """Set draw style
-        
+
         Draw styles:
          - DM_GOURAUD
          - DM_FLAT
@@ -744,40 +769,40 @@
          - DM_WIRE_POLY
          - DM_GRID_WIRE
          - DM_GRID_SURF
-         
+
         :param id: surface id (<= 0 for all)
         :param style: draw style
-        
+
         :return: 1 on success
         :return: -1 surface not found
         :return: -2 setting attributes failed
         """
         Debug.msg(3, "Nviz::SetSurfaceStyle(): id=%d, style=%d",
                   id, style)
-        
+
         if id > 0:
             if not GS_surf_exists(id):
                 return -1
-            
+
             if GS_set_drawmode(id, style) < 0:
                 return -2
-            
+
             return 1
-        
+
         if GS_setall_drawmode(style) < 0:
             return -2
-        
+
         return 1
-    
+
     def SetWireColor(self, id, color_str):
         """Set color of wire
-        
+
         .. todo::
             all
-         
+
         :param id: surface id (< 0 for all)
         :param color_str: color string (R:G:B)
-        
+
         :return: 1 on success
         :return: -1 surface not found
         :return: -2 setting attributes failed
@@ -786,13 +811,13 @@
         """
         Debug.msg(3, "Nviz::SetWireColor(): id=%d, color=%s",
                   id, color_str)
-        
+
         color = Nviz_color_from_str(color_str)
-        
+
         if id > 0:
             if not GS_surf_exists(id):
                 return -1
-            
+
             GS_set_wire_color(id, color)
         else:
             nsurfs = c_int()
@@ -800,102 +825,107 @@
             for i in xrange(nsurfs.value):
                 id = surf_list[i]
                 GS_set_wire_color(id, color)
-            
+
             G_free(surf_list)
             surf_list = None
-        
+
         return 1
-    
+
     def GetSurfacePosition(self, id):
         """Get surface position
-        
+
         :param id: surface id
-        
+
         :return: x,y,z
         :return: zero-length vector on error
         """
         if not GS_surf_exists(id):
             return []
-        
+
         x, y, z = c_float(), c_float(), c_float()
         GS_get_trans(id, byref(x), byref(y), byref(z))
-        
+
         Debug.msg(3, "Nviz::GetSurfacePosition(): id=%d, x=%f, y=%f, z=%f",
                   id, x.value, y.value, z.value)
-        
+
         return [x.value, y.value, z.value]
 
     def SetSurfacePosition(self, id, x, y, z):
         """Set surface position
-        
+
         :param id: surface id
         :param x,y,z: translation values
-        
+
         :return: 1 on success
         :return: -1 surface not found
         :return: -2 setting position failed
         """
         if not GS_surf_exists(id):
             return -1
-        
+
         Debug.msg(3, "Nviz::SetSurfacePosition(): id=%d, x=%f, y=%f, z=%f",
                   id, x, y, z)
-        
+
         GS_set_trans(id, x, y, z)
-        
+
         return 1
 
     def SetVectorLineMode(self, id, color_str, width, use_z):
         """Set mode of vector line overlay
-        
+
         :param id: vector id
         :param color_str: color string
         :param width: line width
         :param use_z: display 3d or on surface
-        
+
         :return: -1 vector set not found
         :return: -2 on failure
         :return: 1 on success
         """
         if not GV_vect_exists(id):
             return -1
-        
-        Debug.msg(3, "Nviz::SetVectorMode(): id=%d, color=%s, width=%d, use_z=%d",
-                  id, color_str, width, use_z)
-        
+
+        Debug.msg(
+            3,
+            "Nviz::SetVectorMode(): id=%d, color=%s, width=%d, use_z=%d",
+            id,
+            color_str,
+            width,
+            use_z)
+
         color = Nviz_color_from_str(color_str)
-        
+
         # use memory by default
         if GV_set_style(id, 1, color, width, use_z) < 0:
             return -2
-        
+
         return 1
 
     def SetVectorLineHeight(self, id, height):
         """Set vector height above surface (lines)
-        
+
         :param id: vector set id
         :param height:
-        
+
         :return: -1 vector set not found
         :return: 1 on success
         """
         if not GV_vect_exists(id):
             return -1
-        
+
         Debug.msg(3, "Nviz::SetVectorLineHeight(): id=%d, height=%f",
                   id, height)
-        
+
         GV_set_trans(id, 0.0, 0.0, height)
-        
+
         return 1
 
     def SetVectorLineSurface(self, id, surf_id):
         """Set reference surface of vector set (lines)
-        
+
         :param id: vector set id
         :param surf_id: surface id
-        
+
         :return: 1 on success
         :return: -1 vector set not found
         :return: -2 surface not found
@@ -903,21 +933,21 @@
         """
         if not GV_vect_exists(id):
             return -1
-        
+
         if not GS_surf_exists(surf_id):
             return -2
-        
+
         if GV_select_surf(id, surf_id) < 0:
             return -3
-        
+
         return 1
 
     def UnsetVectorLineSurface(self, id, surf_id):
         """Unset reference surface of vector set (lines)
-        
+
         :param id: vector set id
         :param surf_id: surface id
-        
+
         :return: 1 on success
         :return: -1 vector set not found
         :return: -2 surface not found
@@ -925,69 +955,69 @@
         """
         if not GV_vect_exists(id):
             return -1
-        
+
         if not GS_surf_exists(surf_id):
             return -2
-        
+
         if GV_unselect_surf(id, surf_id) < 0:
             return -3
-        
+
         return 1
-        
+
     def SetVectorPointMode(self, id, color_str, width, size, marker):
         """Set mode of vector point overlay
-        
+
         :param id: vector id
         :param color_str: color string
         :param width: line width
         :param size: size of the symbol
         :param marker: type of the symbol
-        
+
         :return: -1 vector set not found
         """
         if not GP_site_exists(id):
             return -1
-        
+
         # dtree and ctree defined but not used
         if marker > 5:
             marker += 2
-        
+
         Debug.msg(3, "Nviz::SetVectorPointMode(): id=%d, color=%s, "
                   "width=%d, size=%f, marker=%d",
                   id, color_str, width, size, marker)
-        
+
         color = Nviz_color_from_str(color_str)
-        
+
         if GP_set_style(id, color, width, size, marker) < 0:
             return -2
-        
+
         return 1
 
     def SetVectorPointHeight(self, id, height):
         """Set vector height above surface (points)
-        
+
         :param id: vector set id
         :param height:
-        
+
         :return: -1 vector set not found
         :return: 1 on success
         """
         if not GP_site_exists(id):
             return -1
-        
+
         Debug.msg(3, "Nviz::SetVectorPointHeight(): id=%d, height=%f",
                   id, height)
-        
+
         GP_set_trans(id, 0.0, 0.0, height)
-        
+
         return 1
 
     def SetVectorPointSurface(self, id, surf_id):
         """Set reference surface of vector set (points)
-        
+
         :param id: vector set id
         :param surf_id: surface id
-        
+
         :return: 1 on success
         :return: -1 vector set not found
         :return: -2 surface not found
@@ -995,113 +1025,115 @@
         """
         if not GP_site_exists(id):
             return -1
-        
+
         if not GS_surf_exists(surf_id):
             return -2
-        
+
         if GP_select_surf(id, surf_id) < 0:
             return -3
-        
+
         return 1
 
     def ReadVectorColors(self, name, mapset):
         """Read vector colors
-        
+
         :param name: vector map name
         :param mapset: mapset name (empty string (\c "") for search path)
-        
-        :return: -1 on error 
-        :return: 0 if color table missing 
-        :return: 1 on success (color table found) 
+
+        :return: -1 on error
+        :return: 0 if color table missing
+        :return: 1 on success (color table found)
         """
         return Vect_read_colors(name, mapset, self.color)
-        
+
     def CheckColorTable(self, id, type):
         """Check if color table exists.
-        
+
         :param id: vector set id
         :param type: vector set type (lines/points)
-        
+
         :return: 1 color table exists
         :return: 0 no color table found
         :return: -1 on error
         :return: -2 vector set not found
         """
         file = c_char_p()
-        
+
         if type == 'points':
             ret = GP_get_sitename(id, byref(file))
         elif type == 'lines':
             ret = GV_get_vectname(id, byref(file))
-            
+
         if ret < 0:
             return -2
-        
+
         return self.ReadVectorColors(file, "")
-        
-    def SetPointsStyleThematic(self, id, layer, color = None, colorTable = False, 
-                               width = None, size = None, symbol = None):
+
+    def SetPointsStyleThematic(self, id, layer, color=None, colorTable=False,
+                               width=None, size=None, symbol=None):
         """Set thematic style for vector points
-        
+
         :param id: vector set id
         :param layer: layer number for thematic mapping
-        :param colorTable: use color table 
-        :param color: color column name 
-        :param width: width column name 
-        :param size: size column name 
-        :param symbol: symbol column name 
+        :param colorTable: use color table
+        :param color: color column name
+        :param width: width column name
+        :param size: size column name
+        :param symbol: symbol column name
         """
         file = c_char_p()
         ret = GP_get_sitename(id, byref(file))
         if ret < 0:
             return -1
-        
+
         ret = self.ReadVectorColors(file, "")
         if ret < 0:
             return -1
-        
+
         if colorTable:
-            GP_set_style_thematic(id, layer, color, width, size, symbol, self.color)
+            GP_set_style_thematic(
+                id, layer, color, width, size, symbol, self.color)
         else:
             GP_set_style_thematic(id, layer, color, width, size, symbol, None)
 
-    def SetLinesStyleThematic(self, id, layer, color = None, colorTable = False, width = None):
+    def SetLinesStyleThematic(
+            self, id, layer, color=None, colorTable=False, width=None):
         """Set thematic style for vector lines
-        
+
         :param id: vector set id
         :param layer: layer number for thematic mapping
-        :param color: color column name 
-        :param colorTable: use color table 
-        :param width: width column name 
+        :param color: color column name
+        :param colorTable: use color table
+        :param width: width column name
         """
         file = c_char_p()
         ret = GV_get_vectname(id, byref(file))
         if ret < 0:
             return -1
-        
+
         ret = self.ReadVectorColors(file, "")
         if ret < 0:
             return -1
-        
+
         if colorTable:
             GV_set_style_thematic(id, layer, color, width, self.color)
         else:
             GV_set_style_thematic(id, layer, color, width, None)
-        
+
     def UnsetLinesStyleThematic(self, id):
         """Unset thematic style for vector points"""
-        GV_unset_style_thematic(id)      
-         
+        GV_unset_style_thematic(id)
+
     def UnsetPointsStyleThematic(self, id):
         """Unset thematic style for vector lines"""
         GP_unset_style_thematic(id)
-        
+
     def UnsetVectorPointSurface(self, id, surf_id):
         """Unset reference surface of vector set (points)
-        
+
         :param id: vector set id
         :param surf_id: surface id
-        
+
         :return: 1 on success
         :return: -1 vector set not found
         :return: -2 surface not found
@@ -1109,18 +1141,18 @@
         """
         if not GP_site_exists(id):
             return -1
-        
+
         if not GS_surf_exists(surf_id):
             return -2
-        
+
         if GP_unselect_surf(id, surf_id) < 0:
             return -3
-        
+
         return 1
-        
+
     def SetVectorPointZMode(self, id, zMode):
         """Set z mode (use z coordinate or not)
-        
+
         :param id: volume id
         :param zMode: bool
 
@@ -1130,63 +1162,63 @@
         """
         if not GP_site_exists(id):
             return -1
-            
+
         return GP_set_zmode(id, int(zMode))
 
-    def AddIsosurface(self, id, level, isosurf_id = None):
+    def AddIsosurface(self, id, level, isosurf_id=None):
         """Add new isosurface
-        
+
         :param id: volume id
         :param level: isosurface level (topography)
         :param isosurf_id: isosurface id
-        
+
         :return: -1 on failure
         :return: 1 on success
         """
         if not GVL_vol_exists(id):
             return -1
-        
+
         if isosurf_id is not None:
             num = GVL_isosurf_num_isosurfs(id)
             if num < 0 or isosurf_id != num:
                 return -1
-                
+
         if GVL_isosurf_add(id) < 0:
             return -1
-        
+
         # set topography level
         nisosurfs = GVL_isosurf_num_isosurfs(id)
-        
+
         return GVL_isosurf_set_att_const(id, nisosurfs - 1, ATT_TOPO, level)
-    
-    def AddSlice(self, id, slice_id = None):
+
+    def AddSlice(self, id, slice_id=None):
         """Add new slice
-        
+
         :param id: volume id
         :param slice_id: slice id
-        
+
         :return: -1 on failure
         :return: number of slices
         """
         if not GVL_vol_exists(id):
             return -1
-        
+
         if slice_id is not None:
             num = GVL_slice_num_slices(id)
             if num < 0 or slice_id != num:
                 return -1
-                
+
         if GVL_slice_add(id) < 0:
             return -1
-        
+
         return GVL_slice_num_slices(id)
-    
+
     def DeleteIsosurface(self, id, isosurf_id):
         """Delete isosurface
-        
+
         :param id: volume id
         :param isosurf_id: isosurface id
-        
+
         :return: 1 on success
         :return: -1 volume not found
         :return: -2 isosurface not found
@@ -1194,23 +1226,23 @@
         """
         if not GVL_vol_exists(id):
             return -1
-        
+
         if isosurf_id > GVL_isosurf_num_isosurfs(id):
             return -2
-        
+
         ret = GVL_isosurf_del(id, isosurf_id)
-        
+
         if ret < 0:
             return -3
 
         return 1
-    
+
     def DeleteSlice(self, id, slice_id):
         """Delete slice
-        
+
         :param id: volume id
         :param slice_id: slice id
-        
+
         :return: 1 on success
         :return: -1 volume not found
         :return: -2 slice not found
@@ -1218,24 +1250,24 @@
         """
         if not GVL_vol_exists(id):
             return -1
-        
+
         if slice_id > GVL_slice_num_slices(id):
             return -2
-        
+
         ret = GVL_slice_del(id, slice_id)
-        
+
         if ret < 0:
             return -3
 
         return 1
-    
+
     def MoveIsosurface(self, id, isosurf_id, up):
         """Move isosurface up/down in the list
-        
+
         :param id: volume id
         :param isosurf_id: isosurface id
         :param up: if true move up otherwise down
-        
+
         :return: 1 on success
         :return: -1 volume not found
         :return: -2 isosurface not found
@@ -1243,15 +1275,15 @@
         """
         if not GVL_vol_exists(id):
             return -1
-        
+
         if isosurf_id > GVL_isosurf_num_isosurfs(id):
             return -2
-        
+
         if up:
             ret = GVL_isosurf_move_up(id, isosurf_id)
         else:
             ret = GVL_isosurf_move_down(id, isosurf_id)
-        
+
         if ret < 0:
             return -3
 
@@ -1259,11 +1291,11 @@
 
     def MoveSlice(self, id, slice_id, up):
         """Move slice up/down in the list
-        
+
         :param id: volume id
         :param slice_id: slice id
         :param up: if true move up otherwise down
-        
+
         :return: 1 on success
         :return: -1 volume not found
         :return: -2 slice not found
@@ -1271,122 +1303,122 @@
         """
         if not GVL_vol_exists(id):
             return -1
-        
+
         if slice_id > GVL_slice_num_slices(id):
             return -2
-        
+
         if up:
             ret = GVL_slice_move_up(id, slice_id)
         else:
             ret = GVL_slice_move_down(id, slice_id)
-        
+
         if ret < 0:
             return -3
 
         return 1
-    
+
     def SetIsosurfaceTopo(self, id, isosurf_id, map, value):
         """Set isosurface level
-        
+
         :param id: volume id
         :param isosurf_id: isosurface id (0 - MAX_ISOSURFS)
         :param map: if true use map otherwise constant
         :param value: map name of value
-        
+
         :return: 1 on success
         :return: -1 volume not found
         :return: -2 isosurface not found
         :return: -3 on failure
         """
         return self.SetIsosurfaceAttr(id, isosurf_id, ATT_TOPO, map, value)
-    
+
     def SetIsosurfaceColor(self, id, isosurf_id, map, value):
         """Set isosurface color
-        
+
         :param id: volume id
         :param isosurf_id: isosurface id (0 - MAX_ISOSURFS)
         :param map: if true use map otherwise constant
         :param value: map name of value
-        
+
         :return: 1 on success
         :return: -1 volume not found
         :return: -2 isosurface not found
         :return: -3 on failure
         """
         return self.SetIsosurfaceAttr(id, isosurf_id, ATT_COLOR, map, value)
-    
+
     def SetIsosurfaceMask(self, id, isosurf_id, invert, value):
         """Set isosurface mask
-        
+
         .. todo::
             invert
-        
+
         :param id: volume id
         :param isosurf_id: isosurface id (0 - MAX_ISOSURFS)
         :param invert: true for invert mask
         :param value: map name to be used for mask
-        
+
         :return: 1 on success
         :return: -1 volume not found
         :return: -2 isosurface not found
         :return: -3 on failure
         """
         return self.SetIsosurfaceAttr(id, isosurf_id, ATT_MASK, True, value)
-    
+
     def SetIsosurfaceTransp(self, id, isosurf_id, map, value):
         """Set isosurface transparency
-        
+
         :param id: volume id
         :param isosurf_id: isosurface id (0 - MAX_ISOSURFS)
         :param map: if true use map otherwise constant
         :param value: map name of value
-        
+
         :return: 1 on success
         :return: -1 volume not found
         :return: -2 isosurface not found
         :return: -3 on failure
         """
         return self.SetIsosurfaceAttr(id, isosurf_id, ATT_TRANSP, map, value)
-    
+
     def SetIsosurfaceShine(self, id, isosurf_id, map, value):
         """Set isosurface shininess
-        
+
         :param id: volume id
         :param isosurf_id: isosurface id (0 - MAX_ISOSURFS)
         :param map: if true use map otherwise constant
         :param value: map name of value
-        
+
         :return: 1 on success
         :return: -1 volume not found
         :return: -2 isosurface not found
         :return: -3 on failure
         """
         return self.SetIsosurfaceAttr(id, isosurf_id, ATT_SHINE, map, value)
-    
+
     def SetIsosurfaceEmit(self, id, isosurf_id, map, value):
         """Set isosurface emission (currently unused)
-        
+
         :param id: volume id
         :param isosurf_id: isosurface id (0 - MAX_ISOSURFS)
         :param map: if true use map otherwise constant
         :param value: map name of value
-        
+
         :return: 1 on success
         :return: -1 volume not found
         :return: -2 isosurface not found
         :return: -3 on failure
         """
         return self.SetIsosurfaceAttr(id, isosurf_id, ATT_EMIT, map, value)
-    
+
     def SetIsosurfaceAttr(self, id, isosurf_id, attr, map, value):
         """Set isosurface attribute
-        
+
         :param id: volume id
         :param isosurf_id: isosurface id (0 - MAX_ISOSURFS)
         :param attr: attribute desc
         :param map: if true use map otherwise constant
         :param value: map name of value
-        
+
         :return: 1 on success
         :return: -1 volume not found
         :return: -2 isosurface not found
@@ -1394,10 +1426,10 @@
         """
         if not GVL_vol_exists(id):
             return -1
-        
+
         if isosurf_id > GVL_isosurf_num_isosurfs(id) - 1:
             return -2
-        
+
         if map:
             ret = GVL_isosurf_set_att_map(id, isosurf_id, attr, value)
         else:
@@ -1405,64 +1437,64 @@
                 val = Nviz_color_from_str(value)
             else:
                 val = float(value)
-            
+
             ret = GVL_isosurf_set_att_const(id, isosurf_id, attr, val)
-        
+
         Debug.msg(3, "Nviz::SetIsosurfaceAttr(): id=%d, isosurf=%d, "
                   "attr=%d, map=%s, value=%s",
                   id, isosurf_id, attr, map, value)
-        
+
         if ret < 0:
             return -2
-        
+
         return 1
-    
+
     def UnsetIsosurfaceMask(self, id, isosurf_id):
         """Unset isosurface mask
-        
+
         :param id: volume id
         :param isosurf_id: isosurface id (0 - MAX_ISOSURFS)
-        
+
         :return: 1 on success
         :return: -1 volume not found
         :return: -2 isosurface not found
         :return: -3 setting attributes failed
         """
         return self.UnsetIsosurfaceAttr(id, isosurf_id, ATT_MASK)
-    
+
     def UnsetIsosurfaceTransp(self, id, isosurf_id):
         """Unset isosurface transparency
-        
+
         :param id: volume id
         :param isosurf_id: isosurface id (0 - MAX_ISOSURFS)
-        
+
         :return: 1 on success
         :return: -1 volume not found
         :return: -2 isosurface not found
         :return: -3 setting attributes failed
         """
         return self.UnsetIsosurfaceAttr(id, isosurf_id, ATT_TRANSP)
-    
+
     def UnsetIsosurfaceEmit(self, id, isosurf_id):
         """Unset isosurface emission (currently unused)
-        
+
         :param id: volume id
         :param isosurf_id: isosurface id (0 - MAX_ISOSURFS)
-        
+
         :return: 1 on success
         :return: -1 volume not found
         :return: -2 isosurface not found
         :return: -3 setting attributes failed
         """
         return self.UnsetIsosurfaceAttr(id, isosurf_id, ATT_EMIT)
-    
+
     def UnsetIsosurfaceAttr(self, id, isosurf_id, attr):
         """Unset surface attribute
-        
+
         :param id: surface id
         :param isosurf_id: isosurface id (0 - MAX_ISOSURFS)
         :param attr: attribute descriptor
-        
+
         :return: 1 on success
         :return: -1 volume not found
         :return: -2 isosurface not found
@@ -1470,108 +1502,108 @@
         """
         if not GVL_vol_exists(id):
             return -1
-        
+
         if isosurf_id > GVL_isosurf_num_isosurfs(id) - 1:
             return -2
-        
+
         Debug.msg(3, "Nviz::UnsetSurfaceAttr(): id=%d, isosurf_id=%d, attr=%d",
                   id, isosurf_id, attr)
-        
+
         ret = GVL_isosurf_unset_att(id, isosurf_id, attr)
-        
+
         if ret < 0:
             return -2
-        
+
         return 1
 
     def SetIsosurfaceMode(self, id, mode):
         """Set draw mode for isosurfaces
-        
+
         :param id: isosurface id
         :param mode: isosurface draw mode
-        
+
         :return: 1 on success
         :return: -1 volume set not found
         :return: -2 on failure
         """
         if not GVL_vol_exists(id):
             return -1
-        
+
         ret = GVL_isosurf_set_drawmode(id, mode)
-        
+
         if ret < 0:
             return -2
-        
+
         return 1
-    
+
     def SetSliceMode(self, id, mode):
         """Set draw mode for slices
-        
+
         :param id: slice id
         :param mode: slice draw mode
-        
+
         :return: 1 on success
         :return: -1 volume set not found
         :return: -2 on failure
         """
         if not GVL_vol_exists(id):
             return -1
-        
+
         ret = GVL_slice_set_drawmode(id, mode)
-        
+
         if ret < 0:
             return -2
-        
+
         return 1
-    
+
     def SetIsosurfaceRes(self, id, res):
         """Set draw resolution for isosurfaces
-        
+
         :param id: isosurface id
         :param res: resolution value
-        
+
         :return: 1 on success
         :return: -1 volume set not found
         :return: -2 on failure
         """
         if not GVL_vol_exists(id):
             return -1
-        
+
         ret = GVL_isosurf_set_drawres(id, res, res, res)
-        
+
         if ret < 0:
             return -2
-        
+
         return 1
-    
+
     def SetSliceRes(self, id, res):
         """Set draw resolution for slices
-        
+
         :param id: slice id
         :param res: resolution value
-        
+
         :return: 1 on success
         :return: -1 volume set not found
         :return: -2 on failure
         """
         if not GVL_vol_exists(id):
             return -1
-        
+
         ret = GVL_slice_set_drawres(id, res, res, res)
-        
+
         if ret < 0:
             return -2
-        
+
         return 1
-    
+
     def SetSlicePosition(self, id, slice_id, x1, x2, y1, y2, z1, z2, dir):
         """Set slice position
-        
+
         :param id: volume id
         :param slice_id: slice id
         :param x1,x2,y1,y2,z1,z2: slice coordinates
         :param dir: axis
-        
+
         :return: 1 on success
         :return: -1 volume not found
         :return: -2 slice not found
@@ -1579,50 +1611,50 @@
         """
         if not GVL_vol_exists(id):
             return -1
-        
+
         if slice_id > GVL_slice_num_slices(id):
             return -2
-        
+
         ret = GVL_slice_set_pos(id, slice_id, x1, x2, y1, y2, z1, z2, dir)
-        
+
         if ret < 0:
             return -2
-        
+
         return 1
-    
+
     def SetSliceTransp(self, id, slice_id, value):
         """Set slice transparency
-        
+
         :param id: volume id
         :param slice_id: slice id
         :param value: transparency value (0 - 255)
-        
+
         :return: 1 on success
         :return: -1 volume not found
         :return: -2 slice not found
         :return: -3 on failure
         """
-        
+
         if not GVL_vol_exists(id):
             return -1
-        
+
         if slice_id > GVL_slice_num_slices(id):
             return -2
-        
+
         ret = GVL_slice_set_transp(id, slice_id, value)
-        
+
         if ret < 0:
             return -2
-        
+
         return 1
-    
+
     def SetIsosurfaceInOut(self, id, isosurf_id, inout):
         """Set inout mode
-        
+
         :param id: volume id
         :param isosurf_id: isosurface id
         :param inout: mode true/false
-        
+
         :return: 1 on success
         :return: -1 volume set not found
         :return: -2 isosurface not found
@@ -1630,59 +1662,59 @@
         """
         if not GVL_vol_exists(id):
             return -1
-        
+
         if isosurf_id > GVL_isosurf_num_isosurfs(id) - 1:
             return -2
-        
+
         ret = GVL_isosurf_set_flags(id, isosurf_id, inout)
-        
+
         if ret < 0:
             return -3
-        
+
         return 1
-    
+
     def GetVolumePosition(self, id):
         """Get volume position
-        
+
         :param id: volume id
-        
+
         :return: x,y,z
         :return: zero-length vector on error
         """
         if not GVL_vol_exists(id):
             return []
-        
+
         x, y, z = c_float(), c_float(), c_float()
         GVL_get_trans(id, byref(x), byref(y), byref(z))
-        
+
         Debug.msg(3, "Nviz::GetVolumePosition(): id=%d, x=%f, y=%f, z=%f",
                   id, x.value, y.value, z.value)
-        
+
         return [x.value, y.value, z.value]
-    
+
     def SetVolumePosition(self, id, x, y, z):
         """Set volume position
-        
+
         :param id: volume id
         :param x,y,z: translation values
-        
+
         :return: 1 on success
         :return: -1 volume not found
         :return: -2 setting position failed
         """
         if not GVL_vol_exists(id):
             return -1
-        
+
         Debug.msg(3, "Nviz::SetVolumePosition(): id=%d, x=%f, y=%f, z=%f",
                   id, x, y, z)
-        
+
         GVL_set_trans(id, x, y, z)
-        
+
         return 1
 
     def SetVolumeDrawBox(self, id, ifBox):
         """Display volume wire box
-        
+
         :param id: volume id
         :param ifBox: True to draw wire box, False otherwise
         :type ifBox: bool
@@ -1693,56 +1725,62 @@
             return -1
 
         Debug.msg(3, "Nviz::SetVolumeDrawBox(): id=%d, ifBox=%d", id, ifBox)
-        
+
         GVL_set_draw_wire(id, int(ifBox))
 
         return 1
 
     def GetCPlaneCurrent(self):
         return Nviz_get_current_cplane(self.data)
-    
+
     def GetCPlanesCount(self):
         """Returns number of cutting planes"""
-        return Nviz_num_cplanes(self.data) 
-    
+        return Nviz_num_cplanes(self.data)
+
     def GetCPlaneRotation(self):
         """Returns rotation parameters of current cutting plane"""
         x, y, z = c_float(), c_float(), c_float()
-        
+
         current = Nviz_get_current_cplane(self.data)
-        Nviz_get_cplane_rotation(self.data, current, byref(x), byref(y), byref(z))
-        
+        Nviz_get_cplane_rotation(
+            self.data,
+            current,
+            byref(x),
+            byref(y),
+            byref(z))
+
         return x.value, y.value, z.value
-    
+
     def GetCPlaneTranslation(self):
         """Returns translation parameters of current cutting plane"""
         x, y, z = c_float(), c_float(), c_float()
-        
+
         current = Nviz_get_current_cplane(self.data)
-        Nviz_get_cplane_translation(self.data, current, byref(x), byref(y), byref(z))
-        
+        Nviz_get_cplane_translation(
+            self.data, current, byref(x), byref(y), byref(z))
+
         return x.value, y.value, z.value
-    
+
     def SetCPlaneRotation(self, x, y, z):
         """Set current clip plane rotation
-        
+
         :param x,y,z: rotation parameters
         """
         current = Nviz_get_current_cplane(self.data)
         Nviz_set_cplane_rotation(self.data, current, x, y, z)
         Nviz_draw_cplane(self.data, -1, -1)
-    
+
     def SetCPlaneTranslation(self, x, y, z):
         """Set current clip plane translation
-        
+
         :param x,y,z: translation parameters
         """
         current = Nviz_get_current_cplane(self.data)
         Nviz_set_cplane_translation(self.data, current, x, y, z)
-        Nviz_draw_cplane(self.data, -1, -1) 
+        Nviz_draw_cplane(self.data, -1, -1)
         Debug.msg(3, "Nviz::SetCPlaneTranslation(): id=%d, x=%f, y=%f, z=%f",
                   current, x, y, z)
-                
+
     def SetCPlaneInteractively(self, x, y):
         current = Nviz_get_current_cplane(self.data)
         ret = Nviz_set_cplane_here(self.data, current, x, y)
@@ -1752,40 +1790,39 @@
             return x, y, z
         else:
             return None, None, None
-        
-        
+
     def SelectCPlane(self, index):
         """Select cutting plane
-        
+
         :param index: index of cutting plane
         """
         Nviz_on_cplane(self.data, index)
-    
+
     def UnselectCPlane(self, index):
         """Unselect cutting plane
-        
+
         :param index: index of cutting plane
         """
         Nviz_off_cplane(self.data, index)
-        
+
     def SetFenceColor(self, index):
         """Select current cutting plane
-        
+
         :param index: type of fence - from 0 (off) to 4
-        """  
+        """
         Nviz_set_fence_color(self.data, index)
-            
+
     def GetXYRange(self):
         """Get xy range"""
         return Nviz_get_xyrange(self.data)
-    
+
     def GetZRange(self):
         """Get z range"""
         min, max = c_float(), c_float()
         Nviz_get_zrange(self.data, byref(min), byref(max))
         return min.value, max.value
-    
-    def SaveToFile(self, filename, width = 20, height = 20, itype = 'ppm'):
+
+    def SaveToFile(self, filename, width=20, height=20, itype='ppm'):
         """Save current GL screen to ppm/tif file
 
         :param filename: file name
@@ -1793,9 +1830,9 @@
         :param height: image height
         :param itype: image type ('ppm' or 'tif')
         """
-        widthOrig  = self.width
+        widthOrig = self.width
         heightOrig = self.height
-        
+
         self.ResizeWindow(width, height)
         GS_clear(Nviz_get_bgcolor(self.data))
         self.Draw(False, -1)
@@ -1803,7 +1840,7 @@
             GS_write_ppm(filename)
         else:
             GS_write_tif(filename)
-        
+
         self.ResizeWindow(widthOrig, heightOrig)
 
     def DrawLightingModel(self):
@@ -1814,8 +1851,9 @@
     def DrawFringe(self):
         """Draw fringe"""
         Nviz_draw_fringe(self.data)
-        
-    def SetFringe(self, sid, color, elev, nw = False, ne = False, sw = False, se = False):
+
+    def SetFringe(self, sid, color, elev, nw=False,
+                  ne=False, sw=False, se=False):
         """Set fringe
 
         :param sid: surface id
@@ -1827,60 +1865,63 @@
         Nviz_set_fringe(self.data,
                         sid, Nviz_color_from_str(scolor),
                         elev, int(nw), int(ne), int(sw), int(se))
-    
+
     def DrawArrow(self):
         """Draw north arrow
         """
         return Nviz_draw_arrow(self.data)
-        
+
     def SetArrow(self, sx, sy, size, color):
         """Set north arrow from canvas coordinates
-        
+
         :param sx,sy: canvas coordinates
         :param size: arrow length
         :param color: arrow color
         """
-        return Nviz_set_arrow(self.data, sx, sy, size, Nviz_color_from_str(color))       
-        
+        return Nviz_set_arrow(self.data, sx, sy, size,
+                              Nviz_color_from_str(color))
+
     def DeleteArrow(self):
         """Delete north arrow
         """
         Nviz_delete_arrow(self.data)
-    
+
     def SetScalebar(self, id, sx, sy, size, color):
         """Set scale bar from canvas coordinates
-        
+
         :param sx,sy: canvas coordinates
         :param id: scale bar id
         :param size: scale bar length
         :param color: scale bar color
         """
-        return Nviz_set_scalebar(self.data, id, sx, sy, size, Nviz_color_from_str(color))
-    
+        return Nviz_set_scalebar(
+            self.data, id, sx, sy, size, Nviz_color_from_str(color))
+
     def DrawScalebar(self):
         """Draw scale bar
         """
         return Nviz_draw_scalebar(self.data)
-    
+
     def DeleteScalebar(self, id):
         """Delete scalebar
         """
         Nviz_delete_scalebar(self.data, id)
-        
+
     def GetPointOnSurface(self, sx, sy):
         """Get point on surface
 
         :param sx,sy: canvas coordinates (LL)
         """
         sid = c_int()
-        x   = c_float()
-        y   = c_float()
-        z   = c_float()
+        x = c_float()
+        y = c_float()
+        z = c_float()
         Debug.msg(5, "Nviz::GetPointOnSurface(): sx=%d sy=%d" % (sx, sy))
-        num = GS_get_selected_point_on_surface(sx, sy, byref(sid), byref(x), byref(y), byref(z))
+        num = GS_get_selected_point_on_surface(
+            sx, sy, byref(sid), byref(x), byref(y), byref(z))
         if num == 0:
             return (None, None, None, None)
-        
+
         return (sid.value, x.value, y.value, z.value)
 
     def QueryMap(self, sx, sy):
@@ -1891,52 +1932,52 @@
         sid, x, y, z = self.GetPointOnSurface(sx, sy)
         if not sid:
             return None
-        
+
         catstr = create_string_buffer(256)
         valstr = create_string_buffer(256)
         GS_get_cat_at_xy(sid, ATT_TOPO, catstr, x, y)
         GS_get_val_at_xy(sid, ATT_COLOR, valstr, x, y)
-        
-        return { 'id' : sid,
-                 'x'  : x,
-                 'y'  : y,
-                 'z'  : z,
-                 'elevation' : catstr.value.replace('(', '').replace(')', ''),
-                 'color'     : valstr.value }
-    
-    def GetDistanceAlongSurface(self, sid, p1, p2, useExag = True):
+
+        return {'id': sid,
+                'x': x,
+                'y': y,
+                'z': z,
+                'elevation': catstr.value.replace('(', '').replace(')', ''),
+                'color': valstr.value}
+
+    def GetDistanceAlongSurface(self, sid, p1, p2, useExag=True):
         """Get distance measured along surface"""
         d = c_float()
-        
+
         GS_get_distance_alongsurf(sid, p1[0], p1[1], p2[0], p2[1],
                                   byref(d), int(useExag))
-        
+
         return d.value
 
     def GetRotationParameters(self, dx, dy):
         """Get rotation parameters (angle, x, y, z axes)
-        
+
         :param dx,dy: difference from previous mouse drag event
         """
         modelview = (c_double * 16)()
         Nviz_get_modelview(byref(modelview))
-        
-        angle = sqrt(dx*dx+dy*dy)/float(self.width+1)*180.0
+
+        angle = sqrt(dx * dx + dy * dy) / float(self.width + 1) * 180.0
         m = []
         row = []
         for i, item in enumerate(modelview):
             row.append(item)
-            if (i+1) % 4 == 0:
+            if (i + 1) % 4 == 0:
                 m.append(row)
                 row = []
         inv = matrix(m).I
         ax, ay, az = dy, dx, 0.
-        x = inv[0,0]*ax + inv[1,0]*ay + inv[2,0]*az
-        y = inv[0,1]*ax + inv[1,1]*ay + inv[2,1]*az
-        z = inv[0,2]*ax + inv[1,2]*ay + inv[2,2]*az
-        
-        return angle, x, y, z 
-       
+        x = inv[0, 0] * ax + inv[1, 0] * ay + inv[2, 0] * az
+        y = inv[0, 1] * ax + inv[1, 1] * ay + inv[2, 1] * az
+        z = inv[0, 2] * ax + inv[1, 2] * ay + inv[2, 2] * az
+
+        return angle, x, y, z
+
     def Rotate(self, angle, x, y, z):
         """Set rotation parameters
         Rotate scene (difference from current state).
@@ -1945,15 +1986,15 @@
         :param x,y,z: axis coordinate
         """
         Nviz_set_rotation(angle, x, y, z)
-        
+
     def UnsetRotation(self):
         """Stop rotating the scene"""
         Nviz_unset_rotation()
-        
+
     def ResetRotation(self):
         """Reset scene rotation"""
         Nviz_init_rotation()
-        
+
     def GetRotationMatrix(self):
         """Get rotation matrix"""
         matrix = (c_double * 16)()
@@ -1962,20 +2003,20 @@
         for item in matrix:
             returnMatrix.append(item)
         return returnMatrix
-        
+
     def SetRotationMatrix(self, matrix):
         """Set rotation matrix"""
         mtrx = (c_double * 16)()
         for i in range(len(matrix)):
             mtrx[i] = matrix[i]
         GS_set_rotation_matrix(byref(mtrx))
-    
+
     def Start2D(self):
         Nviz_set_2D(self.width, self.height)
-        
+
     def FlyThrough(self, flyInfo, mode, exagInfo):
         """Fly through the scene
-        
+
         :param flyInfo: fly parameters
         :param mode: 0 or 1 for different fly behaviour
         :param exagInfo: parameters changing fly speed
@@ -1987,9 +2028,11 @@
         exag[0] = int(exagInfo['move'])
         exag[1] = int(exagInfo['turn'])
         Nviz_flythrough(self.data, fly, exag, mode)
-        
+
+
 class Texture(object):
     """Class representing OpenGL texture"""
+
     def __init__(self, filepath, overlayId, coords):
         """Load image to texture
 
@@ -2005,41 +2048,41 @@
         self.coords = [0, 0]
         self.bounds = wx.Rect()
         self.active = True
-        
+
         # alpha needs to be initialized
         if not self.image.HasAlpha():
             self.image.InitAlpha()
-    
+
         # resize image to match 2^n
         self.Resize()
-        
+
         # check max texture size
         maxSize = c_int()
         Nviz_get_max_texture(byref(maxSize))
         self.maxSize = maxSize.value
         if self.maxSize < self.width or self.maxSize < self.height:
-            # TODO: split up image 
+            # TODO: split up image
             self.textureId = None
         else:
             self.textureId = self.Load()
-            
+
     def __del__(self):
         """Delete texture"""
         if self.textureId:
             Nviz_del_texture(self.textureId)
         grass.try_remove(self.path)
-            
-    def Resize(self):    
+
+    def Resize(self):
         """Resize image to match 2^n"""
         n = m = 1
-        while self.width > pow(2,n):
+        while self.width > pow(2, n):
             n += 1
-        while self.height > pow(2,m):
+        while self.height > pow(2, m):
             m += 1
-        self.image.Resize(size = (pow(2,n), pow(2,m)), pos = (0, 0))
+        self.image.Resize(size=(pow(2, n), pow(2, m)), pos=(0, 0))
         self.width = self.image.GetWidth()
         self.height = self.image.GetHeight()
-        
+
     def Load(self):
         """Load image to texture"""
         if self.image.HasAlpha():
@@ -2053,105 +2096,129 @@
         bytes1 = self.width * self.height
         imageData = struct.unpack(str(bytes3) + 'B', self.image.GetData())
         if self.image.HasAlpha():
-            alphaData = struct.unpack(str(bytes1) + 'B', self.image.GetAlphaData())
-        
+            alphaData = struct.unpack(
+                str(bytes1) + 'B', self.image.GetAlphaData())
+
         # this takes too much time
         wx.BeginBusyCursor()
         for i in range(self.height):
             for j in range(self.width):
-                im[(j + i * self.width) * bytesPerPixel + 0] = imageData[( j + (rev_val - i) * self.width) * 3 + 0]
-                im[(j + i * self.width) * bytesPerPixel + 1] = imageData[( j + (rev_val - i) * self.width) * 3 + 1]
-                im[(j + i * self.width) * bytesPerPixel + 2] = imageData[( j + (rev_val - i) * self.width) * 3 + 2]
+                im[(j + i * self.width) * bytesPerPixel + 0] = imageData[(j +
+                                                                          (rev_val - i) * self.width) * 3 + 0]
+                im[(j + i * self.width) * bytesPerPixel + 1] = imageData[(j +
+                                                                          (rev_val - i) * self.width) * 3 + 1]
+                im[(j + i * self.width) * bytesPerPixel + 2] = imageData[(j +
+                                                                          (rev_val - i) * self.width) * 3 + 2]
                 if self.image.HasAlpha():
-                    im[(j + i * self.width) * bytesPerPixel + 3] = alphaData[( j + (rev_val - i) * self.width)]
+                    im[(j + i * self.width) * bytesPerPixel + 3] = alphaData[(j +
+                                                                              (rev_val - i) * self.width)]
         wx.EndBusyCursor()
-        
-        id = Nviz_load_image(im, self.width, self.height, self.image.HasAlpha())
-        
+
+        id = Nviz_load_image(
+            im,
+            self.width,
+            self.height,
+            self.image.HasAlpha())
+
         return id
-        
+
     def Draw(self):
         """Draw texture as an image"""
-        Nviz_draw_image(self.coords[0], self.coords[1], self.width, self.height, self.textureId)
-    
-        
+        Nviz_draw_image(
+            self.coords[0],
+            self.coords[1],
+            self.width,
+            self.height,
+            self.textureId)
+
     def SetBounds(self, rect):
         """Set Bounding Rectangle"""
         self.bounds = rect
-        
+
     def HitTest(self, x, y, radius):
         copy = wx.Rect(*self.bounds)
         copy.Inflate(radius, radius)
         return copy.ContainsXY(x, y)
-    
+
     def MoveTexture(self, dx, dy):
         """Move texture on the screen"""
         self.coords[0] += dx
         self.coords[1] += dy
         self.bounds.OffsetXY(dx, dy)
-    
+
     def SetCoords(self, coords):
         """Set coordinates"""
         dx = coords[0] - self.coords[0]
         dy = coords[1] - self.coords[1]
         self.MoveTexture(dx, dy)
-        
+
     def GetId(self):
         """Returns image id."""
         return self.id
-    
-    def SetActive(self, active = True):
+
+    def SetActive(self, active=True):
         self.active = active
-        
+
     def IsActive(self):
         return self.active
-        
+
+
 class ImageTexture(Texture):
     """Class representing OpenGL texture as an overlay image"""
+
     def __init__(self, filepath, overlayId, coords, cmd):
         """Load image to texture
 
         :param filepath: path to image file
         :param overlayId: id of overlay (1 for legend)
         :param coords: image coordinates
-        :param cmd: d.legend command      
+        :param cmd: d.legend command
         """
-        Texture.__init__(self, filepath = filepath, overlayId = overlayId, coords = coords)
-        
+        Texture.__init__(
+            self,
+            filepath=filepath,
+            overlayId=overlayId,
+            coords=coords)
+
         self.cmd = cmd
-        
+
     def GetCmd(self):
         """Returns overlay command."""
         return self.cmd
-        
+
     def Corresponds(self, item):
         return sorted(self.GetCmd()) == sorted(item.GetCmd())
-        
+
+
 class TextTexture(Texture):
     """Class representing OpenGL texture as a text label"""
+
     def __init__(self, filepath, overlayId, coords, textDict):
         """Load image to texture
 
         :param filepath: path to image file
         :param overlayId: id of overlay (101 and more for text)
         :param coords: text coordinates
-        :param textDict: text properties      
+        :param textDict: text properties
         """
-        Texture.__init__(self, filepath = filepath, overlayId = overlayId, coords = coords)
-        
+        Texture.__init__(
+            self,
+            filepath=filepath,
+            overlayId=overlayId,
+            coords=coords)
+
         self.textDict = textDict
-        
+
     def GetTextDict(self):
         """Returns text properties."""
         return self.textDict
-        
-        
+
     def Corresponds(self, item):
         t = self.GetTextDict()
         for prop in t.keys():
-            if prop in ('coords','bbox'): continue
+            if prop in ('coords', 'bbox'):
+                continue
             if t[prop] != item[prop]:
                 return False
-                
+
         return True
-    

Modified: grass/trunk/gui/wxpython/psmap/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/psmap/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/psmap/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -6,4 +6,4 @@
     'toolbars',
     'utils',
     'frame',
-    ]
+]

Modified: grass/trunk/gui/wxpython/psmap/dialogs.py
===================================================================
--- grass/trunk/gui/wxpython/psmap/dialogs.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/psmap/dialogs.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -40,10 +40,10 @@
 from copy import deepcopy
 
 import wx
-import wx.lib.scrolledpanel    as scrolled
+import wx.lib.scrolledpanel as scrolled
 import wx.lib.filebrowsebutton as filebrowse
 from wx.lib.mixins.listctrl import CheckListCtrlMixin, ListCtrlAutoWidthMixin
-from wx.lib.expando         import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED
+from wx.lib.expando import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED
 try:
     import wx.lib.agw.floatspin as fs
 except ImportError:
@@ -51,24 +51,40 @@
 
 import grass.script as grass
 
-from core               import globalvar
+from core import globalvar
 from core.utils import _, PilImageToWxImage
-from dbmgr.vinfo        import VectorDBInfo
-from gui_core.gselect   import Select
-from core.gcmd          import RunCommand, GError, GMessage
-from gui_core.dialogs   import SymbolDialog
-from psmap.utils        import *
+from dbmgr.vinfo import VectorDBInfo
+from gui_core.gselect import Select
+from core.gcmd import RunCommand, GError, GMessage
+from gui_core.dialogs import SymbolDialog
+from psmap.utils import *
 from psmap.instructions import *
 
 # grass.set_raise_on_error(True)
 
-PSMAP_COLORS = ['aqua', 'black', 'blue', 'brown', 'cyan', 'gray', 'grey', 'green', 'indigo',
-                'magenta','orange', 'purple', 'red', 'violet', 'white', 'yellow']
+PSMAP_COLORS = [
+    'aqua',
+    'black',
+    'blue',
+    'brown',
+    'cyan',
+    'gray',
+    'grey',
+    'green',
+    'indigo',
+    'magenta',
+    'orange',
+    'purple',
+    'red',
+    'violet',
+    'white',
+    'yellow']
 
-    
+
 class TCValidator(wx.PyValidator):
     """validates input in textctrls, combobox, 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)
@@ -77,7 +93,7 @@
         return TCValidator(self.flag)
 
     def Validate(self, win):
-        
+
         tc = self.GetWindow()
         val = tc.GetValue()
 
@@ -95,9 +111,9 @@
         if self.flag == 'DIGIT_ONLY' and chr(key) in string.digits + '.-':
             event.Skip()
             return
-##        if self.flag == 'SCALE' and chr(key) in string.digits + ':':
-##            event.Skip()
-##            return
+# if self.flag == 'SCALE' and chr(key) in string.digits + ':':
+# event.Skip()
+# return
         if self.flag == 'ZERO_AND_ONE_ONLY' and chr(key) in '01':
             event.Skip()
             return
@@ -105,7 +121,7 @@
             wx.Bell()
         # Returning without calling even.Skip eats the event before it
         # gets to the text control
-        return  
+        return
 
 
 class PenStyleComboBox(wx.combo.OwnerDrawnComboBox):
@@ -133,13 +149,13 @@
         dc.SetPen(pen)
 
         # for painting the items in the popup
-        dc.DrawText(self.GetString(item ),
+        dc.DrawText(self.GetString(item),
                     r.x + 3,
-                    (r.y + 0) + ((r.height/2) - dc.GetCharHeight() )/2
+                    (r.y + 0) + ((r.height / 2) - dc.GetCharHeight()) / 2
                     )
-        dc.DrawLine(r.x+5, r.y+((r.height/4)*3)+1, r.x+r.width - 5, r.y+((r.height/4)*3)+1 )
+        dc.DrawLine(r.x + 5, r.y + ((r.height / 4) * 3) + 1,
+                    r.x + r.width - 5, r.y + ((r.height / 4) * 3) + 1)
 
-        
     def OnDrawBackground(self, dc, rect, item, flags):
         """Overridden from OwnerDrawnComboBox, called for drawing the
         background area of each item."""
@@ -147,14 +163,15 @@
         # combo control itself, then use the default rendering.
         if (item & 1 == 0 or flags & (wx.combo.ODCB_PAINTING_CONTROL |
                                       wx.combo.ODCB_PAINTING_SELECTED)):
-            wx.combo.OwnerDrawnComboBox.OnDrawBackground(self, dc, rect, item, flags)
+            wx.combo.OwnerDrawnComboBox.OnDrawBackground(
+                self, dc, rect, item, flags)
             return
 
         # Otherwise, draw every other background with different colour.
-        bgCol = wx.Colour(240,240,250)
+        bgCol = wx.Colour(240, 240, 250)
         dc.SetBrush(wx.Brush(bgCol))
         dc.SetPen(wx.Pen(bgCol))
-        dc.DrawRectangleRect(rect);
+        dc.DrawRectangleRect(rect)
 
     def OnMeasureItem(self, item):
         """Overridden from OwnerDrawnComboBox, should return the height
@@ -164,23 +181,26 @@
     def OnMeasureItemWidth(self, item):
         """Overridden from OwnerDrawnComboBox.  Callback for item width, or
         -1 for default/undetermined"""
-        return -1; # default - will be measured from text width  
-    
-    
+        return -1  # default - will be measured from text width
+
+
 class CheckListCtrl(wx.ListCtrl, CheckListCtrlMixin, ListCtrlAutoWidthMixin):
     """List control for managing order and labels of vector maps in legend"""
+
     def __init__(self, parent):
-        wx.ListCtrl.__init__(self, parent, id = wx.ID_ANY, 
-                             style = wx.LC_REPORT|wx.LC_SINGLE_SEL|wx.BORDER_SUNKEN|wx.LC_VRULES|wx.LC_HRULES)
-        CheckListCtrlMixin.__init__(self) 
+        wx.ListCtrl.__init__(
+            self, parent, id=wx.ID_ANY, style=wx.LC_REPORT | wx.LC_SINGLE_SEL |
+            wx.BORDER_SUNKEN | wx.LC_VRULES | wx.LC_HRULES)
+        CheckListCtrlMixin.__init__(self)
         ListCtrlAutoWidthMixin.__init__(self)
-        
 
+
 class PsmapDialog(wx.Dialog):
-    def __init__(self, parent, id,  title, settings, apply = True):
-        wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY, 
-                            title = title, size = wx.DefaultSize,
-                            style = wx.CAPTION|wx.MINIMIZE_BOX|wx.CLOSE_BOX)
+
+    def __init__(self, parent, id, title, settings, apply=True):
+        wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY,
+                           title=title, size=wx.DefaultSize,
+                           style=wx.CAPTION | wx.MINIMIZE_BOX | wx.CLOSE_BOX)
         self.apply = apply
         self.id = id
         self.parent = parent
@@ -188,144 +208,231 @@
         self.objectType = None
         self.unitConv = UnitConversion(self)
         self.spinCtrlSize = (65, -1)
-        
+
         self.Bind(wx.EVT_CLOSE, self.OnClose)
-        
-    
-        
+
     def AddUnits(self, parent, dialogDict):
         parent.units = dict()
-        parent.units['unitsLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Units:"))
+        parent.units['unitsLabel'] = wx.StaticText(
+            parent, id=wx.ID_ANY, label=_("Units:"))
         choices = self.unitConv.getPageUnitsNames()
-        parent.units['unitsCtrl'] = wx.Choice(parent, id = wx.ID_ANY, choices = choices)  
-        parent.units['unitsCtrl'].SetStringSelection(self.unitConv.findName(dialogDict['unit']))
-          
+        parent.units['unitsCtrl'] = wx.Choice(
+            parent, id=wx.ID_ANY, choices=choices)
+        parent.units['unitsCtrl'].SetStringSelection(
+            self.unitConv.findName(dialogDict['unit']))
+
     def AddPosition(self, parent, dialogDict):
         if not hasattr(parent, "position"):
             parent.position = dict()
-        parent.position['comment'] = wx.StaticText(parent, id = wx.ID_ANY,\
-                    label = _("Position of the top left corner\nfrom the top left edge of the paper"))
-        parent.position['xLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("X:"))
-        parent.position['yLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Y:"))
-        parent.position['xCtrl'] = wx.TextCtrl(parent, id = wx.ID_ANY, value = str(dialogDict['where'][0]), validator = TCValidator(flag = 'DIGIT_ONLY'))
-        parent.position['yCtrl'] = wx.TextCtrl(parent, id = wx.ID_ANY, value = str(dialogDict['where'][1]), validator = TCValidator(flag = 'DIGIT_ONLY'))
-        if dialogDict.has_key('unit'):
-            x = self.unitConv.convert(value = dialogDict['where'][0], fromUnit = 'inch', toUnit = dialogDict['unit'])
-            y = self.unitConv.convert(value = dialogDict['where'][1], fromUnit = 'inch', toUnit = dialogDict['unit'])
+        parent.position['comment'] = wx.StaticText(parent, id=wx.ID_ANY, label=_(
+            "Position of the top left corner\nfrom the top left edge of the paper"))
+        parent.position['xLabel'] = wx.StaticText(
+            parent, id=wx.ID_ANY, label=_("X:"))
+        parent.position['yLabel'] = wx.StaticText(
+            parent, id=wx.ID_ANY, label=_("Y:"))
+        parent.position['xCtrl'] = wx.TextCtrl(
+            parent, id=wx.ID_ANY, value=str(
+                dialogDict['where'][0]), validator=TCValidator(
+                flag='DIGIT_ONLY'))
+        parent.position['yCtrl'] = wx.TextCtrl(
+            parent, id=wx.ID_ANY, value=str(
+                dialogDict['where'][1]), validator=TCValidator(
+                flag='DIGIT_ONLY'))
+        if 'unit' in dialogDict:
+            x = self.unitConv.convert(
+                value=dialogDict['where'][0],
+                fromUnit='inch',
+                toUnit=dialogDict['unit'])
+            y = self.unitConv.convert(
+                value=dialogDict['where'][1],
+                fromUnit='inch',
+                toUnit=dialogDict['unit'])
             parent.position['xCtrl'].SetValue("%5.3f" % x)
             parent.position['yCtrl'].SetValue("%5.3f" % y)
-        
+
     def AddExtendedPosition(self, panel, gridBagSizer, dialogDict):
         """Add widgets for setting position relative to paper and to map"""
         panel.position = dict()
-        positionLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("Position is given:"))
-        panel.position['toPaper'] = wx.RadioButton(panel, id = wx.ID_ANY, label = _("relative to paper"), style = wx.RB_GROUP)
-        panel.position['toMap'] = wx.RadioButton(panel, id = wx.ID_ANY, label = _("by map coordinates"))
+        positionLabel = wx.StaticText(
+            panel, id=wx.ID_ANY, label=_("Position is given:"))
+        panel.position['toPaper'] = wx.RadioButton(
+            panel, id=wx.ID_ANY, label=_("relative to paper"), style=wx.RB_GROUP)
+        panel.position['toMap'] = wx.RadioButton(
+            panel, id=wx.ID_ANY, label=_("by map coordinates"))
         panel.position['toPaper'].SetValue(dialogDict['XY'])
         panel.position['toMap'].SetValue(not dialogDict['XY'])
-        
-        gridBagSizer.Add(positionLabel, pos = (0,0), span = (1,3), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT, border = 0)
-        gridBagSizer.Add(panel.position['toPaper'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT, border = 0)
-        gridBagSizer.Add(panel.position['toMap'], pos = (1,1),flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT, border = 0)
-        
+
+        gridBagSizer.Add(
+            positionLabel, pos=(
+                0, 0), span=(
+                1, 3), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT, border=0)
+        gridBagSizer.Add(
+            panel.position['toPaper'],
+            pos=(
+                1,
+                0),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT,
+            border=0)
+        gridBagSizer.Add(
+            panel.position['toMap'],
+            pos=(
+                1,
+                1),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT,
+            border=0)
+
         # first box - paper coordinates
-        box1   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = "")
+        box1 = wx.StaticBox(parent=panel, id=wx.ID_ANY, label="")
         sizerP = wx.StaticBoxSizer(box1, wx.VERTICAL)
-        self.gridBagSizerP = wx.GridBagSizer (hgap = 5, vgap = 5)
-        
-        self.AddPosition(parent = panel, dialogDict = dialogDict)
-        panel.position['comment'].SetLabel(_("Position from the top left\nedge of the paper"))
-        self.AddUnits(parent = panel, dialogDict = dialogDict)
-        self.gridBagSizerP.Add(panel.units['unitsLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        self.gridBagSizerP.Add(panel.units['unitsCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        self.gridBagSizerP.Add(panel.position['xLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        self.gridBagSizerP.Add(panel.position['xCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        self.gridBagSizerP.Add(panel.position['yLabel'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        self.gridBagSizerP.Add(panel.position['yCtrl'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        self.gridBagSizerP.Add(panel.position['comment'], pos = (3,0), span = (1,2), flag = wx.ALIGN_BOTTOM, border = 0)
-        
+        self.gridBagSizerP = wx.GridBagSizer(hgap=5, vgap=5)
+
+        self.AddPosition(parent=panel, dialogDict=dialogDict)
+        panel.position['comment'].SetLabel(
+            _("Position from the top left\nedge of the paper"))
+        self.AddUnits(parent=panel, dialogDict=dialogDict)
+        self.gridBagSizerP.Add(
+            panel.units['unitsLabel'], pos=(
+                0, 0), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerP.Add(
+            panel.units['unitsCtrl'], pos=(
+                0, 1), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerP.Add(
+            panel.position['xLabel'], pos=(
+                1, 0), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerP.Add(panel.position['xCtrl'], pos=(
+            1, 1), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerP.Add(
+            panel.position['yLabel'], pos=(
+                2, 0), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerP.Add(panel.position['yCtrl'], pos=(
+            2, 1), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerP.Add(
+            panel.position['comment'], pos=(
+                3, 0), span=(
+                1, 2), flag=wx.ALIGN_BOTTOM, border=0)
+
         self.gridBagSizerP.AddGrowableCol(1)
         self.gridBagSizerP.AddGrowableRow(3)
-        sizerP.Add(self.gridBagSizerP, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        gridBagSizer.Add(sizerP, pos = (2,0),span = (1,1), flag = wx.ALIGN_CENTER_HORIZONTAL|wx.EXPAND, border = 0)
-        
+        sizerP.Add(
+            self.gridBagSizerP,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        gridBagSizer.Add(
+            sizerP, pos=(
+                2, 0), span=(
+                1, 1), flag=wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND, border=0)
+
         # second box - map coordinates
-        box2   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = "")
+        box2 = wx.StaticBox(parent=panel, id=wx.ID_ANY, label="")
         sizerM = wx.StaticBoxSizer(box2, wx.VERTICAL)
-        self.gridBagSizerM = wx.GridBagSizer (hgap = 5, vgap = 5)
-        
-        eastingLabel  = wx.StaticText(panel, id = wx.ID_ANY, label = "E:")
-        northingLabel  = wx.StaticText(panel, id = wx.ID_ANY, label = "N:")
-        panel.position['eCtrl'] = wx.TextCtrl(panel, id = wx.ID_ANY, value = "")
-        panel.position['nCtrl'] = wx.TextCtrl(panel, id = wx.ID_ANY, value = "")
-        east, north = PaperMapCoordinates(mapInstr = self.instruction[self.mapId], x = dialogDict['where'][0], y = dialogDict['where'][1], paperToMap = True)
+        self.gridBagSizerM = wx.GridBagSizer(hgap=5, vgap=5)
+
+        eastingLabel = wx.StaticText(panel, id=wx.ID_ANY, label="E:")
+        northingLabel = wx.StaticText(panel, id=wx.ID_ANY, label="N:")
+        panel.position['eCtrl'] = wx.TextCtrl(panel, id=wx.ID_ANY, value="")
+        panel.position['nCtrl'] = wx.TextCtrl(panel, id=wx.ID_ANY, value="")
+        east, north = PaperMapCoordinates(
+            mapInstr=self.instruction[self.mapId],
+            x=dialogDict['where'][0],
+            y=dialogDict['where'][1],
+            paperToMap=True)
         panel.position['eCtrl'].SetValue(str(east))
         panel.position['nCtrl'].SetValue(str(north))
-        
-        self.gridBagSizerM.Add(eastingLabel, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        self.gridBagSizerM.Add(northingLabel, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        self.gridBagSizerM.Add(panel.position['eCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        self.gridBagSizerM.Add(panel.position['nCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        
+
+        self.gridBagSizerM.Add(
+            eastingLabel, pos=(0, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerM.Add(
+            northingLabel, pos=(1, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerM.Add(panel.position['eCtrl'], pos=(
+            0, 1), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerM.Add(panel.position['nCtrl'], pos=(
+            1, 1), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+
         self.gridBagSizerM.AddGrowableCol(0)
         self.gridBagSizerM.AddGrowableCol(1)
-        sizerM.Add(self.gridBagSizerM, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        gridBagSizer.Add(sizerM, pos = (2,1), flag = wx.ALIGN_LEFT|wx.EXPAND, border = 0)
-        
-    def AddFont(self, parent, dialogDict, color = True):
+        sizerM.Add(
+            self.gridBagSizerM,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        gridBagSizer.Add(
+            sizerM, pos=(2, 1),
+            flag=wx.ALIGN_LEFT | wx.EXPAND, border=0)
+
+    def AddFont(self, parent, dialogDict, color=True):
         parent.font = dict()
 ##        parent.font['fontLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Choose font:"))
 ##        parent.font['fontCtrl'] = wx.FontPickerCtrl(parent, id = wx.ID_ANY)
-##        
-##        parent.font['fontCtrl'].SetSelectedFont(
-##                        wx.FontFromNativeInfoString(dialogDict['font'] + " " + str(dialogDict['fontsize'])))
-##        parent.font['fontCtrl'].SetMaxPointSize(50)
-##        
-##        if color:
+##
+# parent.font['fontCtrl'].SetSelectedFont(
+# wx.FontFromNativeInfoString(dialogDict['font'] + " " + str(dialogDict['fontsize'])))
+# parent.font['fontCtrl'].SetMaxPointSize(50)
+##
+# if color:
 ##            parent.font['colorLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Choose color:"))
 ##            parent.font['colorCtrl'] = wx.ColourPickerCtrl(parent, id = wx.ID_ANY, style=wx.FNTP_FONTDESC_AS_LABEL)
-##            parent.font['colorCtrl'].SetColour(dialogDict['color'])
-           
-##        parent.font['colorCtrl'].SetColour(convertRGB(dialogDict['color'])) 
-           
-        parent.font['fontLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Font:"))
-        parent.font['fontSizeLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Font size:"))
-        fontChoices = [ 'Times-Roman', 'Times-Italic', 'Times-Bold', 'Times-BoldItalic', 'Helvetica',\
-                        'Helvetica-Oblique', 'Helvetica-Bold', 'Helvetica-BoldOblique', 'Courier',\
-                        'Courier-Oblique', 'Courier-Bold', 'Courier-BoldOblique'] 
-        parent.font['fontCtrl'] = wx.Choice(parent, id = wx.ID_ANY, choices = fontChoices)
+# parent.font['colorCtrl'].SetColour(dialogDict['color'])
+
+# parent.font['colorCtrl'].SetColour(convertRGB(dialogDict['color']))
+
+        parent.font['fontLabel'] = wx.StaticText(
+            parent, id=wx.ID_ANY, label=_("Font:"))
+        parent.font['fontSizeLabel'] = wx.StaticText(
+            parent, id=wx.ID_ANY, label=_("Font size:"))
+        fontChoices = [
+            'Times-Roman',
+            'Times-Italic',
+            'Times-Bold',
+            'Times-BoldItalic',
+            'Helvetica',
+            'Helvetica-Oblique',
+            'Helvetica-Bold',
+            'Helvetica-BoldOblique',
+            'Courier',
+            'Courier-Oblique',
+            'Courier-Bold',
+            'Courier-BoldOblique']
+        parent.font['fontCtrl'] = wx.Choice(
+            parent, id=wx.ID_ANY, choices=fontChoices)
         if dialogDict['font'] in fontChoices:
             parent.font['fontCtrl'].SetStringSelection(dialogDict['font'])
         else:
             parent.font['fontCtrl'].SetStringSelection('Helvetica')
-        parent.font['fontSizeCtrl'] = wx.SpinCtrl(parent, id = wx.ID_ANY, min = 4, max = 50, initial = 10)
+        parent.font['fontSizeCtrl'] = wx.SpinCtrl(
+            parent, id=wx.ID_ANY, min=4, max=50, initial=10)
         parent.font['fontSizeCtrl'].SetValue(dialogDict['fontsize'])
-         
+
         if color:
-            parent.font['colorLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Choose color:"))
-            parent.font['colorCtrl'] = wx.ColourPickerCtrl(parent, id = wx.ID_ANY)
+            parent.font['colorLabel'] = wx.StaticText(
+                parent, id=wx.ID_ANY, label=_("Choose color:"))
+            parent.font['colorCtrl'] = wx.ColourPickerCtrl(
+                parent, id=wx.ID_ANY)
             parent.font['colorCtrl'].SetColour(convertRGB(dialogDict['color']))
 ##            parent.font['colorLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Color:"))
-##            colorChoices = [  'aqua', 'black', 'blue', 'brown', 'cyan', 'gray', 'green', 'indigo', 'magenta',\
-##                                'orange', 'purple', 'red', 'violet', 'white', 'yellow']
+# colorChoices = [  'aqua', 'black', 'blue', 'brown', 'cyan', 'gray', 'green', 'indigo', 'magenta',\
+# 'orange', 'purple', 'red', 'violet', 'white', 'yellow']
 ##            parent.colorCtrl = wx.Choice(parent, id = wx.ID_ANY, choices = colorChoices)
-##            parent.colorCtrl.SetStringSelection(parent.rLegendDict['color'])
+# parent.colorCtrl.SetStringSelection(parent.rLegendDict['color'])
 ##            parent.font['colorCtrl'] = wx.ColourPickerCtrl(parent, id = wx.ID_ANY)
-##            parent.font['colorCtrl'].SetColour(dialogDict['color'])   
+# parent.font['colorCtrl'].SetColour(dialogDict['color'])
+
     def OnApply(self, event):
         ok = self.update()
         if ok:
-            self.parent.DialogDataChanged(id = self.id)
-            return True 
+            self.parent.DialogDataChanged(id=self.id)
+            return True
         else:
             return False
-        
+
     def OnOK(self, event):
         """Apply changes, close dialog"""
         ok = self.OnApply(event)
         if ok:
             self.Close()
-    
+
     def OnCancel(self, event):
         """Close dialog"""
         self.Close()
@@ -333,20 +440,19 @@
     def OnClose(self, event):
         """Destroy dialog and delete it from open dialogs"""
         if self.objectType:
-            for each in  self.objectType:
+            for each in self.objectType:
                 if each in self.parent.openDialogs:
                     del self.parent.openDialogs[each]
         event.Skip()
         self.Destroy()
-        
+
     def _layout(self, panel):
-        #buttons
+        # buttons
         btnCancel = wx.Button(self, wx.ID_CANCEL)
         btnOK = wx.Button(self, wx.ID_OK)
         btnOK.SetDefault()
         if self.apply:
             btnApply = wx.Button(self, wx.ID_APPLY)
-        
 
         # bindigs
         btnOK.Bind(wx.EVT_BUTTON, self.OnOK)
@@ -357,7 +463,7 @@
         if self.apply:
             btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
             btnApply.SetToolTipString(_("Apply changes"))
-        
+
         # sizers
         btnSizer = wx.StdDialogButtonSizer()
         btnSizer.AddButton(btnCancel)
@@ -365,50 +471,82 @@
             btnSizer.AddButton(btnApply)
         btnSizer.AddButton(btnOK)
         btnSizer.Realize()
-        
+
         mainSizer = wx.BoxSizer(wx.VERTICAL)
-        mainSizer.Add(item = panel, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
-        mainSizer.Add(item = btnSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
-        
-        
+        mainSizer.Add(
+            item=panel,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        mainSizer.Add(item=btnSizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
+
         self.SetSizer(mainSizer)
         mainSizer.Layout()
-        mainSizer.Fit(self) 
-            
+        mainSizer.Fit(self)
+
+
 class PageSetupDialog(PsmapDialog):
+
     def __init__(self, parent, id, settings):
-        PsmapDialog.__init__(self, parent = parent, id = id, title = "Page setup",  settings = settings)
-        
-        self.cat = ['Units', 'Format', 'Orientation', 'Width', 'Height', 'Left', 'Right', 'Top', 'Bottom']
-        labels = [_('Units'), _('Format'), _('Orientation'), _('Width'), _('Height'),
-                  _('Left'), _('Right'), _('Top'), _('Bottom')]
+        PsmapDialog.__init__(
+            self,
+            parent=parent,
+            id=id,
+            title="Page setup",
+            settings=settings)
+
+        self.cat = [
+            'Units',
+            'Format',
+            'Orientation',
+            'Width',
+            'Height',
+            'Left',
+            'Right',
+            'Top',
+            'Bottom']
+        labels = [
+            _('Units'),
+            _('Format'),
+            _('Orientation'),
+            _('Width'),
+            _('Height'),
+            _('Left'),
+            _('Right'),
+            _('Top'),
+            _('Bottom')]
         self.catsLabels = dict(zip(self.cat, labels))
-        paperString = RunCommand('ps.map', flags = 'p', read = True, quiet = True)
-        self.paperTable = self._toList(paperString) 
+        paperString = RunCommand('ps.map', flags='p', read=True, quiet=True)
+        self.paperTable = self._toList(paperString)
         self.unitsList = self.unitConv.getPageUnitsNames()
         self.pageSetupDict = settings[id].GetInstruction()
 
         self._layout()
-        
+
         if self.pageSetupDict:
-            self.getCtrl('Units').SetStringSelection(self.unitConv.findName(self.pageSetupDict['Units']))
+            self.getCtrl('Units').SetStringSelection(
+                self.unitConv.findName(self.pageSetupDict['Units']))
             if self.pageSetupDict['Format'] == 'custom':
-                self.getCtrl('Format').SetSelection(self.getCtrl('Format').GetCount() - 1)
+                self.getCtrl('Format').SetSelection(
+                    self.getCtrl('Format').GetCount() - 1)
             else:
-                self.getCtrl('Format').SetStringSelection(self.pageSetupDict['Format'])
+                self.getCtrl('Format').SetStringSelection(
+                    self.pageSetupDict['Format'])
             if self.pageSetupDict['Orientation'] == 'Portrait':
                 self.getCtrl('Orientation').SetSelection(0)
             else:
                 self.getCtrl('Orientation').SetSelection(1)
-                
+
             for item in self.cat[3:]:
-                val = self.unitConv.convert(value = self.pageSetupDict[item],
-                                            fromUnit = 'inch', toUnit = self.pageSetupDict['Units'])
+                val = self.unitConv.convert(
+                    value=self.pageSetupDict[item],
+                    fromUnit='inch',
+                    toUnit=self.pageSetupDict['Units'])
                 self.getCtrl(item).SetValue("%4.3f" % val)
 
-       
-        if self.getCtrl('Format').GetSelection() != self.getCtrl('Format').GetCount() - 1: # custom
+        if self.getCtrl('Format').GetSelection() != self.getCtrl(
+                'Format').GetCount() - 1:  # custom
             self.getCtrl('Width').Disable()
             self.getCtrl('Height').Disable()
         else:
@@ -419,65 +557,97 @@
         self.getCtrl('Orientation').Bind(wx.EVT_CHOICE, self.OnChoice)
         self.btnOk.Bind(wx.EVT_BUTTON, self.OnOK)
 
-    
     def update(self):
-        self.pageSetupDict['Units'] = self.unitConv.findUnit(self.getCtrl('Units').GetStringSelection())
-        self.pageSetupDict['Format'] = self.paperTable[self.getCtrl('Format').GetSelection()]['Format']
+        self.pageSetupDict['Units'] = self.unitConv.findUnit(
+            self.getCtrl('Units').GetStringSelection())
+        self.pageSetupDict['Format'] = self.paperTable[
+            self.getCtrl('Format').GetSelection()]['Format']
         if self.getCtrl('Orientation').GetSelection() == 0:
             self.pageSetupDict['Orientation'] = 'Portrait'
         else:
             self.pageSetupDict['Orientation'] = 'Landscape'
         for item in self.cat[3:]:
-            self.pageSetupDict[item] = self.unitConv.convert(value = float(self.getCtrl(item).GetValue()),
-                                        fromUnit = self.pageSetupDict['Units'], toUnit = 'inch')
-            
+            self.pageSetupDict[item] = self.unitConv.convert(
+                value=float(self.getCtrl(item).GetValue()),
+                fromUnit=self.pageSetupDict['Units'],
+                toUnit='inch')
 
-            
     def OnOK(self, event):
         try:
             self.update()
         except ValueError:
-                wx.MessageBox(message = _("Literal is not allowed!"), caption = _('Invalid input'),
-                                    style = wx.OK|wx.ICON_ERROR)
+            wx.MessageBox(
+                message=_("Literal is not allowed!"),
+                caption=_('Invalid input'),
+                style=wx.OK | wx.ICON_ERROR)
         else:
             event.Skip()
-        
+
     def _layout(self):
-        size = (110,-1)
-        #sizers
+        size = (110, -1)
+        # sizers
         mainSizer = wx.BoxSizer(wx.VERTICAL)
-        pageBox = wx.StaticBox(self, id = wx.ID_ANY, label = " %s " % _("Page size"))
+        pageBox = wx.StaticBox(
+            self,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Page size"))
         pageSizer = wx.StaticBoxSizer(pageBox, wx.VERTICAL)
-        marginBox = wx.StaticBox(self, id = wx.ID_ANY, label = " %s " % _("Margins"))
+        marginBox = wx.StaticBox(
+            self, id=wx.ID_ANY, label=" %s " %
+            _("Margins"))
         marginSizer = wx.StaticBoxSizer(marginBox, wx.VERTICAL)
-        horSizer = wx.BoxSizer(wx.HORIZONTAL) 
+        horSizer = wx.BoxSizer(wx.HORIZONTAL)
         #staticText + choice
-        choices = [self.unitsList, [item['Format'] for item in self.paperTable], [_('Portrait'), _('Landscape')]]
-        propor = [0,1,1]
-        border = [5,3,3]
-        self.hBoxDict={}
+        choices = [
+            self.unitsList, [
+                item['Format'] for item in self.paperTable], [
+                _('Portrait'), _('Landscape')]]
+        propor = [0, 1, 1]
+        border = [5, 3, 3]
+        self.hBoxDict = {}
         for i, item in enumerate(self.cat[:3]):
             hBox = wx.BoxSizer(wx.HORIZONTAL)
-            stText = wx.StaticText(self, id = wx.ID_ANY, label = self.catsLabels[item] + ':')
-            choice = wx.Choice(self, id = wx.ID_ANY, choices = choices[i], size = size)
-            hBox.Add(stText, proportion = propor[i], flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = border[i])
-            hBox.Add(choice, proportion = 0, flag = wx.ALL, border = border[i])
+            stText = wx.StaticText(
+                self, id=wx.ID_ANY, label=self.catsLabels[item] + ':')
+            choice = wx.Choice(
+                self,
+                id=wx.ID_ANY,
+                choices=choices[i],
+                size=size)
+            hBox.Add(
+                stText,
+                proportion=propor[i],
+                flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+                border=border[i])
+            hBox.Add(choice, proportion=0, flag=wx.ALL, border=border[i])
             if item == 'Units':
-                hBox.Add(size,1) 
-            self.hBoxDict[item] = hBox    
+                hBox.Add(size, 1)
+            self.hBoxDict[item] = hBox
 
         #staticText + TextCtrl
         for item in self.cat[3:]:
             hBox = wx.BoxSizer(wx.HORIZONTAL)
-            label = wx.StaticText(self, id = wx.ID_ANY, label = self.catsLabels[item] + ':')
-            textctrl = wx.TextCtrl(self, id = wx.ID_ANY, size = size, value = '')
-            hBox.Add(label, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 3)
-            hBox.Add(textctrl, proportion = 0, flag = wx.ALIGN_CENTRE|wx.ALL, border = 3)
+            label = wx.StaticText(
+                self, id=wx.ID_ANY, label=self.catsLabels[item] + ':')
+            textctrl = wx.TextCtrl(self, id=wx.ID_ANY, size=size, value='')
+            hBox.Add(
+                label,
+                proportion=1,
+                flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+                border=3)
+            hBox.Add(
+                textctrl,
+                proportion=0,
+                flag=wx.ALIGN_CENTRE | wx.ALL,
+                border=3)
             self.hBoxDict[item] = hBox
-         
-        sizer = list([mainSizer] + [pageSizer]*4 + [marginSizer]*4)
+
+        sizer = list([mainSizer] + [pageSizer] * 4 + [marginSizer] * 4)
         for i, item in enumerate(self.cat):
-                sizer[i].Add(self.hBoxDict[item], 0, wx.GROW|wx.RIGHT|wx.LEFT,5)
+            sizer[i].Add(
+                self.hBoxDict[item],
+                0, wx.GROW | wx.RIGHT | wx.LEFT, 5)
         # OK button
         btnSizer = wx.StdDialogButtonSizer()
         self.btnOk = wx.Button(self, wx.ID_OK)
@@ -486,27 +656,39 @@
         btn = wx.Button(self, wx.ID_CANCEL)
         btnSizer.AddButton(btn)
         btnSizer.Realize()
-    
-    
-        horSizer.Add(pageSizer, proportion = 0, flag = wx.LEFT|wx.RIGHT|wx.BOTTOM, border = 10)
-        horSizer.Add(marginSizer, proportion = 0, flag = wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, border = 10)
-        mainSizer.Add(horSizer, proportion = 0, border = 10)  
-        mainSizer.Add(btnSizer, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT|wx.ALL,  border = 10)      
+
+        horSizer.Add(
+            pageSizer,
+            proportion=0,
+            flag=wx.LEFT | wx.RIGHT | wx.BOTTOM,
+            border=10)
+        horSizer.Add(marginSizer, proportion=0, flag=wx.LEFT |
+                     wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=10)
+        mainSizer.Add(horSizer, proportion=0, border=10)
+        mainSizer.Add(
+            btnSizer,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL,
+            border=10)
         self.SetSizer(mainSizer)
         mainSizer.Fit(self)
-    
+
     def OnChoice(self, event):
         currPaper = self.paperTable[self.getCtrl('Format').GetSelection()]
-        currUnit = self.unitConv.findUnit(self.getCtrl('Units').GetStringSelection())
+        currUnit = self.unitConv.findUnit(
+            self.getCtrl('Units').GetStringSelection())
         currOrientIdx = self.getCtrl('Orientation').GetSelection()
         newSize = dict()
         for item in self.cat[3:]:
-            newSize[item] = self.unitConv.convert(float(currPaper[item]), fromUnit = 'inch', toUnit = currUnit)
+            newSize[item] = self.unitConv.convert(
+                float(currPaper[item]),
+                fromUnit='inch', toUnit=currUnit)
 
         enable = True
         if currPaper['Format'] != _('custom'):
-            if currOrientIdx == 1: # portrait
-                newSize['Width'], newSize['Height'] = newSize['Height'], newSize['Width']
+            if currOrientIdx == 1:  # portrait
+                newSize['Width'], newSize['Height'] = newSize[
+                    'Height'], newSize['Width']
             for item in self.cat[3:]:
                 self.getCtrl(item).ChangeValue("%4.3f" % newSize[item])
             enable = False
@@ -514,80 +696,95 @@
         self.getCtrl('Height').Enable(enable)
         self.getCtrl('Orientation').Enable(not enable)
 
+    def getCtrl(self, item):
+        return self.hBoxDict[item].GetItem(1).GetWindow()
 
-    def getCtrl(self, item):
-         return self.hBoxDict[item].GetItem(1).GetWindow()
-        
     def _toList(self, paperStr):
-        
+
         sizeList = list()
         for line in paperStr.strip().split('\n'):
-            d = dict(zip([self.cat[1]]+ self.cat[3:],line.split()))
+            d = dict(zip([self.cat[1]] + self.cat[3:], line.split()))
             sizeList.append(d)
-        d = {}.fromkeys([self.cat[1]]+ self.cat[3:], 100)
-        d.update(Format = _('custom'))
+        d = {}.fromkeys([self.cat[1]] + self.cat[3:], 100)
+        d.update(Format=_('custom'))
         sizeList.append(d)
         return sizeList
-    
+
+
 class MapDialog(PsmapDialog):
     """Dialog for map frame settings and optionally  raster and vector map selection"""
-    def __init__(self, parent, id, settings,  rect = None, notebook = False):
-        PsmapDialog.__init__(self, parent = parent, id = id, title = "", settings = settings)
- 
+
+    def __init__(self, parent, id, settings, rect=None, notebook=False):
+        PsmapDialog.__init__(
+            self,
+            parent=parent,
+            id=id,
+            title="",
+            settings=settings)
+
         self.isNotebook = notebook
         if self.isNotebook:
-            self.objectType = ('mapNotebook',) 
+            self.objectType = ('mapNotebook',)
         else:
             self.objectType = ('map',)
 
-        
-        #notebook
+        # notebook
         if self.isNotebook:
-            self.notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
-            self.mPanel = MapFramePanel(parent = self.notebook, id = self.id[0], settings = self.instruction, 
-                                        rect = rect, notebook = True)
+            self.notebook = wx.Notebook(
+                parent=self, id=wx.ID_ANY, style=wx.BK_DEFAULT)
+            self.mPanel = MapFramePanel(
+                parent=self.notebook,
+                id=self.id[0],
+                settings=self.instruction,
+                rect=rect,
+                notebook=True)
             self.id[0] = self.mPanel.getId()
-            self.rPanel = RasterPanel(parent = self.notebook, id = self.id[1], settings = self.instruction, 
-                                        notebook = True)
+            self.rPanel = RasterPanel(
+                parent=self.notebook, id=self.id[1],
+                settings=self.instruction, notebook=True)
             self.id[1] = self.rPanel.getId()
-            self.vPanel = VectorPanel(parent = self.notebook, id = self.id[2], settings = self.instruction,
-                                        notebook = True)
+            self.vPanel = VectorPanel(
+                parent=self.notebook, id=self.id[2],
+                settings=self.instruction, notebook=True)
             self.id[2] = self.vPanel.getId()
             self._layout(self.notebook)
             self.SetTitle(_("Map settings"))
         else:
-            self.mPanel = MapFramePanel(parent = self, id = self.id[0], settings = self.instruction, 
-                                        rect = rect, notebook = False)
+            self.mPanel = MapFramePanel(
+                parent=self,
+                id=self.id[0],
+                settings=self.instruction,
+                rect=rect,
+                notebook=False)
             self.id[0] = self.mPanel.getId()
             self._layout(self.mPanel)
             self.SetTitle(_("Map frame settings"))
-        
-        
+
     def OnApply(self, event):
         """Apply changes"""
         if self.isNotebook:
             okV = self.vPanel.update()
             okR = self.rPanel.update()
             if okV and self.id[2] in self.instruction:
-                self.parent.DialogDataChanged(id = self.id[2])
+                self.parent.DialogDataChanged(id=self.id[2])
             if okR and self.id[1] in self.instruction:
-                self.parent.DialogDataChanged(id = self.id[1])
+                self.parent.DialogDataChanged(id=self.id[1])
             if not okR or not okV:
                 return False
 
         ok = self.mPanel.update()
         if ok:
-            self.parent.DialogDataChanged(id = self.id[0])
-            return True 
-        
+            self.parent.DialogDataChanged(id=self.id[0])
+            return True
+
         return False
-    
+
     def OnCancel(self, event):
         """Close dialog and remove tmp red box"""
         self.parent.canvas.pdcTmp.RemoveId(self.parent.canvas.idZoomBoxTmp)
-        self.parent.canvas.Refresh() 
+        self.parent.canvas.Refresh()
         self.Close()
-        
+
     def updateDialog(self):
         """Update raster and vector information"""
         if self.mPanel.scaleChoice.GetSelection() == 0:
@@ -595,48 +792,48 @@
                 if 'raster' in self.parent.openDialogs:
                     if self.parent.openDialogs['raster'].rPanel.rasterYesRadio.GetValue() and \
                             self.parent.openDialogs['raster'].rPanel.rasterSelect.GetValue() == self.mPanel.select.GetValue():
-                            self.mPanel.drawMap.SetValue(True)
+                        self.mPanel.drawMap.SetValue(True)
                     else:
                         self.mPanel.drawMap.SetValue(False)
             else:
                 if 'vector' in self.parent.openDialogs:
                     found = False
-                    for each in self.parent.openDialogs['vector'].vPanel.vectorList:
+                    for each in self.parent.openDialogs[
+                            'vector'].vPanel.vectorList:
                         if each[0] == self.mPanel.select.GetValue():
                             found = True
-                    self.mPanel.drawMap.SetValue(found)    
-                        
+                    self.mPanel.drawMap.SetValue(found)
+
+
 class MapFramePanel(wx.Panel):
     """wx.Panel with map (scale, region, border) settings"""
-    def __init__(self, parent, id, settings, rect, notebook = True):
-        wx.Panel.__init__(self, parent, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL)
 
+    def __init__(self, parent, id, settings, rect, notebook=True):
+        wx.Panel.__init__(self, parent, id=wx.ID_ANY, style=wx.TAB_TRAVERSAL)
+
         self.id = id
         self.instruction = settings
-        
+
         if notebook:
             self.book = parent
-            self.book.AddPage(page = self, text = _("Map frame"))
+            self.book.AddPage(page=self, text=_("Map frame"))
             self.mapDialog = self.book.GetParent()
         else:
             self.mapDialog = parent
-            
+
         if self.id is not None:
-            self.mapFrameDict = self.instruction[self.id].GetInstruction() 
+            self.mapFrameDict = self.instruction[self.id].GetInstruction()
         else:
             self.id = wx.NewId()
             mapFrame = MapFrame(self.id)
             self.mapFrameDict = mapFrame.GetInstruction()
             self.mapFrameDict['rect'] = rect
 
-            
         self._layout()
 
-        self.scale = [None]*4
-        self.center = [None]*4
-        
-        
-        
+        self.scale = [None] * 4
+        self.center = [None] * 4
+
         self.selectedMap = self.mapFrameDict['map']
         self.selectedRegion = self.mapFrameDict['region']
         self.scaleType = self.mapFrameDict['scaleType']
@@ -656,203 +853,355 @@
                 self.vectorTypeRadio.SetValue(True)
         elif self.mapFrameDict['scaleType'] == 1 and self.mapFrameDict['region']:
             self.select.SetValue(self.mapFrameDict['region'])
-        
-        
+
         self.OnMap(None)
         self.scale[self.mapFrameDict['scaleType']] = self.mapFrameDict['scale']
-        self.center[self.mapFrameDict['scaleType']] = self.mapFrameDict['center']
+        self.center[self.mapFrameDict['scaleType']
+                    ] = self.mapFrameDict['center']
         self.OnScaleChoice(None)
         self.OnElementType(None)
         self.OnBorder(None)
-        
-        
-        
+
     def _layout(self):
         """Do layout"""
         border = wx.BoxSizer(wx.VERTICAL)
-        
-        box   = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Map frame"))
+
+        box = wx.StaticBox(
+            parent=self,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Map frame"))
         sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
-        gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
 
-
-        #scale options
-        frameText = wx.StaticText(self, id = wx.ID_ANY, label = _("Map frame options:"))
+        # scale options
+        frameText = wx.StaticText(
+            self, id=wx.ID_ANY, label=_("Map frame options:"))
         scaleChoices = [_("fit frame to match selected map"),
                         _("fit frame to match saved region"),
                         _("fit frame to match current computational region"),
                         _("fixed scale and map center")]
-        self.scaleChoice = wx.Choice(self, id = wx.ID_ANY, choices = scaleChoices)
-        
-        
-        gridBagSizer.Add(frameText, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.scaleChoice, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        
-        #map and region selection
-        self.staticBox = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Map selection"))
+        self.scaleChoice = wx.Choice(self, id=wx.ID_ANY, choices=scaleChoices)
+
+        gridBagSizer.Add(
+            frameText, pos=(0, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.scaleChoice,
+            pos=(
+                1,
+                0),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+            border=0)
+
+        # map and region selection
+        self.staticBox = wx.StaticBox(
+            parent=self, id=wx.ID_ANY, label=" %s " %
+            _("Map selection"))
         sizerM = wx.StaticBoxSizer(self.staticBox, wx.HORIZONTAL)
-        self.mapSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
+        self.mapSizer = wx.GridBagSizer(hgap=5, vgap=5)
 
-        self.rasterTypeRadio = wx.RadioButton(self, id = wx.ID_ANY, label = " %s " % _("raster"), style = wx.RB_GROUP)
-        self.vectorTypeRadio = wx.RadioButton(self, id = wx.ID_ANY, label = " %s " % _("vector"))
-        self.drawMap = wx.CheckBox(self, id = wx.ID_ANY, label = "add selected map")
-        
-        self.mapOrRegionText = [_("Map:"), _("Region:")] 
-        dc = wx.ClientDC(self)# determine size of labels
-        width = max(dc.GetTextExtent(self.mapOrRegionText[0])[0], dc.GetTextExtent(self.mapOrRegionText[1])[0])
-        self.mapText = wx.StaticText(self, id = wx.ID_ANY, label = self.mapOrRegionText[0], size = (width, -1))
-        self.select = Select(self, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
-                             type = 'raster', multiple = False,
-                             updateOnPopup = True, onPopup = None)
-                            
-        self.mapSizer.Add(self.rasterTypeRadio, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        self.mapSizer.Add(self.vectorTypeRadio, pos = (0, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        self.mapSizer.Add(self.drawMap, pos = (0, 3), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
-        self.mapSizer.Add(self.mapText, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        self.mapSizer.Add(self.select, pos = (1, 1), span = (1, 3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-                 
-        sizerM.Add(self.mapSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        gridBagSizer.Add(sizerM, pos = (2, 0), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        
+        self.rasterTypeRadio = wx.RadioButton(
+            self, id=wx.ID_ANY, label=" %s " %
+            _("raster"), style=wx.RB_GROUP)
+        self.vectorTypeRadio = wx.RadioButton(
+            self, id=wx.ID_ANY, label=" %s " %
+            _("vector"))
+        self.drawMap = wx.CheckBox(
+            self, id=wx.ID_ANY, label="add selected map")
 
-        #map scale and center
-        boxC   = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Map scale and center"))
+        self.mapOrRegionText = [_("Map:"), _("Region:")]
+        dc = wx.ClientDC(self)  # determine size of labels
+        width = max(
+            dc.GetTextExtent(
+                self.mapOrRegionText[0])[0], dc.GetTextExtent(
+                self.mapOrRegionText[1])[0])
+        self.mapText = wx.StaticText(
+            self, id=wx.ID_ANY, label=self.mapOrRegionText[0],
+            size=(width, -1))
+        self.select = Select(
+            self,
+            id=wx.ID_ANY,
+            size=globalvar.DIALOG_GSELECT_SIZE,
+            type='raster',
+            multiple=False,
+            updateOnPopup=True,
+            onPopup=None)
+
+        self.mapSizer.Add(
+            self.rasterTypeRadio, pos=(0, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.mapSizer.Add(
+            self.vectorTypeRadio, pos=(0, 2),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.mapSizer.Add(
+            self.drawMap,
+            pos=(
+                0,
+                3),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT,
+            border=0)
+        self.mapSizer.Add(
+            self.mapText, pos=(1, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.mapSizer.Add(
+            self.select, pos=(
+                1, 1), span=(
+                1, 3), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+
+        sizerM.Add(
+            self.mapSizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        gridBagSizer.Add(
+            sizerM,
+            pos=(
+                2,
+                0),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+            border=0)
+
+        # map scale and center
+        boxC = wx.StaticBox(
+            parent=self,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Map scale and center"))
         sizerC = wx.StaticBoxSizer(boxC, wx.HORIZONTAL)
-        self.centerSizer = wx.FlexGridSizer(rows = 2, cols = 5, hgap = 5, vgap = 5)        
-                
-                           
-        centerText = wx.StaticText(self, id = wx.ID_ANY, label = _("Center:"))
-        self.eastingText = wx.StaticText(self, id = wx.ID_ANY, label = _("E:"))
-        self.northingText = wx.StaticText(self, id = wx.ID_ANY, label = _("N:"))
-        self.eastingTextCtrl = wx.TextCtrl(self, id = wx.ID_ANY, style = wx.TE_RIGHT, validator = TCValidator(flag = 'DIGIT_ONLY'))
-        self.northingTextCtrl = wx.TextCtrl(self, id = wx.ID_ANY, style = wx.TE_RIGHT, validator = TCValidator(flag = 'DIGIT_ONLY'))
-        scaleText = wx.StaticText(self, id = wx.ID_ANY, label = _("Scale:"))
-        scalePrefixText = wx.StaticText(self, id = wx.ID_ANY, label = _("1 :"))
-        self.scaleTextCtrl = wx.TextCtrl(self, id = wx.ID_ANY, value = "", style = wx.TE_RIGHT, validator = TCValidator('DIGIT_ONLY'))
-        
-        self.centerSizer.Add(centerText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, border = 10)
-        self.centerSizer.Add(self.eastingText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
-        self.centerSizer.Add(self.eastingTextCtrl, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        self.centerSizer.Add(self.northingText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
-        self.centerSizer.Add(self.northingTextCtrl, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        
-        self.centerSizer.Add(scaleText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, border = 10)
-        self.centerSizer.Add(scalePrefixText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
-        self.centerSizer.Add(self.scaleTextCtrl, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        
-        sizerC.Add(self.centerSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        gridBagSizer.Add(sizerC, pos = (3, 0), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        
-        
-        #resolution
-        flexSizer = wx.FlexGridSizer(rows = 1, cols = 2, hgap = 5, vgap = 5)
-        
-        resolutionText = wx.StaticText(self, id = wx.ID_ANY, label = _("Map max resolution (dpi):"))
-        self.resolutionSpin = wx.SpinCtrl(self, id = wx.ID_ANY, min = 1, max = 1000, initial = 300)
-        
-        flexSizer.Add(resolutionText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        flexSizer.Add(self.resolutionSpin, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
+        self.centerSizer = wx.FlexGridSizer(rows=2, cols=5, hgap=5, vgap=5)
+
+        centerText = wx.StaticText(self, id=wx.ID_ANY, label=_("Center:"))
+        self.eastingText = wx.StaticText(self, id=wx.ID_ANY, label=_("E:"))
+        self.northingText = wx.StaticText(self, id=wx.ID_ANY, label=_("N:"))
+        self.eastingTextCtrl = wx.TextCtrl(
+            self, id=wx.ID_ANY, style=wx.TE_RIGHT,
+            validator=TCValidator(flag='DIGIT_ONLY'))
+        self.northingTextCtrl = wx.TextCtrl(
+            self, id=wx.ID_ANY, style=wx.TE_RIGHT,
+            validator=TCValidator(flag='DIGIT_ONLY'))
+        scaleText = wx.StaticText(self, id=wx.ID_ANY, label=_("Scale:"))
+        scalePrefixText = wx.StaticText(self, id=wx.ID_ANY, label=_("1 :"))
+        self.scaleTextCtrl = wx.TextCtrl(
+            self, id=wx.ID_ANY, value="", style=wx.TE_RIGHT,
+            validator=TCValidator('DIGIT_ONLY'))
+
+        self.centerSizer.Add(
+            centerText,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT,
+            border=10)
+        self.centerSizer.Add(
+            self.eastingText,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT,
+            border=0)
+        self.centerSizer.Add(
+            self.eastingTextCtrl,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+        self.centerSizer.Add(
+            self.northingText,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT,
+            border=0)
+        self.centerSizer.Add(
+            self.northingTextCtrl,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+
+        self.centerSizer.Add(
+            scaleText,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT,
+            border=10)
+        self.centerSizer.Add(
+            scalePrefixText,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT,
+            border=0)
+        self.centerSizer.Add(
+            self.scaleTextCtrl,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+
+        sizerC.Add(
+            self.centerSizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        gridBagSizer.Add(
+            sizerC,
+            pos=(
+                3,
+                0),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+            border=0)
+
+        # resolution
+        flexSizer = wx.FlexGridSizer(rows=1, cols=2, hgap=5, vgap=5)
+
+        resolutionText = wx.StaticText(
+            self, id=wx.ID_ANY, label=_("Map max resolution (dpi):"))
+        self.resolutionSpin = wx.SpinCtrl(
+            self, id=wx.ID_ANY, min=1, max=1000, initial=300)
+
+        flexSizer.Add(
+            resolutionText,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+        flexSizer.Add(
+            self.resolutionSpin,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
         self.resolutionSpin.SetValue(self.mapFrameDict['resolution'])
-        
-        gridBagSizer.Add(flexSizer, pos = (4, 0), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        
-        sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+
+        gridBagSizer.Add(
+            flexSizer,
+            pos=(
+                4,
+                0),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+            border=0)
+
+        sizer.Add(
+            gridBagSizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         # border
         # GTC Line around legend or map frame
-        box   = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Border"))        
+        box = wx.StaticBox(
+            parent=self,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Border"))
         sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
-        gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
-        
-        self.borderCheck = wx.CheckBox(self, id = wx.ID_ANY, label = (_("draw border around map frame")))
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
+
+        self.borderCheck = wx.CheckBox(
+            self, id=wx.ID_ANY, label=(
+                _("draw border around map frame")))
         if self.mapFrameDict['border'] == 'y':
             self.borderCheck.SetValue(True)
-        else: 
+        else:
             self.borderCheck.SetValue(False)
-        
-        self.borderColorText = wx.StaticText(self, id = wx.ID_ANY, label = _("border color:"))
-        self.borderWidthText = wx.StaticText(self, id = wx.ID_ANY, label = _("border width (pts):"))
-        self.borderColourPicker = wx.ColourPickerCtrl(self, id = wx.ID_ANY)
-        self.borderWidthCtrl = wx.SpinCtrl(self, id = wx.ID_ANY, min = 1, max = 100, initial = 1)
-        
+
+        self.borderColorText = wx.StaticText(
+            self, id=wx.ID_ANY, label=_("border color:"))
+        self.borderWidthText = wx.StaticText(
+            self, id=wx.ID_ANY, label=_("border width (pts):"))
+        self.borderColourPicker = wx.ColourPickerCtrl(self, id=wx.ID_ANY)
+        self.borderWidthCtrl = wx.SpinCtrl(
+            self, id=wx.ID_ANY, min=1, max=100, initial=1)
+
         if self.mapFrameDict['border'] == 'y':
             self.borderWidthCtrl.SetValue(int(self.mapFrameDict['width']))
-            self.borderColourPicker.SetColour(convertRGB(self.mapFrameDict['color']))
-        
-        
-        gridBagSizer.Add(self.borderCheck, pos = (0, 0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        gridBagSizer.Add(self.borderColorText, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.borderWidthText, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.borderColourPicker, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        gridBagSizer.Add(self.borderWidthCtrl, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        
-        sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+            self.borderColourPicker.SetColour(
+                convertRGB(self.mapFrameDict['color']))
+
+        gridBagSizer.Add(
+            self.borderCheck, pos=(
+                0, 0), span=(
+                1, 2), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+        gridBagSizer.Add(
+            self.borderColorText, pos=(1, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.borderWidthText, pos=(2, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.borderColourPicker,
+            pos=(
+                1,
+                2),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+            border=0)
+        gridBagSizer.Add(
+            self.borderWidthCtrl,
+            pos=(
+                2,
+                2),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+            border=0)
+
+        sizer.Add(
+            gridBagSizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         self.SetSizer(border)
         self.Fit()
-        
-        
+
         if projInfo()['proj'] == 'll':
             self.scaleChoice.SetItems(self.scaleChoice.GetItems()[0:3])
             boxC.Hide()
             for each in self.centerSizer.GetChildren():
                 each.GetWindow().Hide()
 
-            
         # bindings
         self.scaleChoice.Bind(wx.EVT_CHOICE, self.OnScaleChoice)
         self.select.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnMap)
         self.Bind(wx.EVT_RADIOBUTTON, self.OnElementType, self.vectorTypeRadio)
         self.Bind(wx.EVT_RADIOBUTTON, self.OnElementType, self.rasterTypeRadio)
         self.Bind(wx.EVT_CHECKBOX, self.OnBorder, self.borderCheck)
-        
-        
-     
+
     def OnMap(self, event):
         """Selected map or region changing"""
-        
+
         if self.select.GetValue():
-            self.selected = self.select.GetValue() 
+            self.selected = self.select.GetValue()
         else:
             self.selected = None
 
         if self.scaleChoice.GetSelection() == 0:
             self.selectedMap = self.selected
             if self.rasterTypeRadio.GetValue():
-                mapType = 'raster' 
+                mapType = 'raster'
             else:
                 mapType = 'vector'
 
-            self.scale[0], self.center[0], foo = AutoAdjust(self, scaleType = 0, map = self.selected,
-                                                mapType = mapType, rect = self.mapFrameDict['rect'])
+            self.scale[0], self.center[0], foo = AutoAdjust(
+                self, scaleType=0, map=self.selected, mapType=mapType,
+                rect=self.mapFrameDict['rect'])
             #self.center[0] = self.RegionCenter(self.RegionDict(scaleType = 0))
 
         elif self.scaleChoice.GetSelection() == 1:
             self.selectedRegion = self.selected
-            self.scale[1], self.center[1],  foo = AutoAdjust(self, scaleType = 1, region = self.selected, rect = self.mapFrameDict['rect'])
+            self.scale[1], self.center[1], foo = AutoAdjust(
+                self, scaleType=1, region=self.selected,
+                rect=self.mapFrameDict['rect'])
             #self.center[1] = self.RegionCenter(self.RegionDict(scaleType = 1))
         elif self.scaleChoice.GetSelection() == 2:
-            self.scale[2], self.center[2], foo = AutoAdjust(self, scaleType = 2, rect = self.mapFrameDict['rect'])
+            self.scale[2], self.center[2], foo = AutoAdjust(
+                self, scaleType=2, rect=self.mapFrameDict['rect'])
             #self.center[2] = self.RegionCenter(self.RegionDict(scaleType = 2))
-            
+
         else:
-            self.scale[3] = None        
+            self.scale[3] = None
             self.center[3] = None
-            
+
         self.OnScaleChoice(None)
-        
-            
+
     def OnScaleChoice(self, event):
         """Selected scale type changing"""
-        
+
         scaleType = self.scaleChoice.GetSelection()
         if self.scaleType != scaleType:
             self.scaleType = scaleType
             self.select.SetValue("")
-        
-        if scaleType in (0, 1): # automatic - region from raster map, saved region
+
+        if scaleType in (
+                0, 1):  # automatic - region from raster map, saved region
             if scaleType == 0:
                 # set map selection
                 self.rasterTypeRadio.Show()
@@ -860,14 +1209,15 @@
                 self.drawMap.Show()
                 self.staticBox.SetLabel(" %s " % _("Map selection"))
                 if self.rasterTypeRadio.GetValue():
-                    stype = 'raster' 
+                    stype = 'raster'
                 else:
                     stype = 'vector'
 
-                self.select.SetElementList(type = stype)
+                self.select.SetElementList(type=stype)
                 self.mapText.SetLabel(self.mapOrRegionText[0])
-                self.select.SetToolTipString(_("Region is set to match this map,\nraster or vector map must be added later"))
-                    
+                self.select.SetToolTipString(
+                    _("Region is set to match this map,\nraster or vector map must be added later"))
+
             if scaleType == 1:
                 # set region selection
                 self.rasterTypeRadio.Hide()
@@ -875,7 +1225,7 @@
                 self.drawMap.Hide()
                 self.staticBox.SetLabel(" %s " % _("Region selection"))
                 stype = 'region'
-                self.select.SetElementList(type = stype)
+                self.select.SetElementList(type=stype)
                 self.mapText.SetLabel(self.mapOrRegionText[1])
                 self.select.SetToolTipString("")
 
@@ -883,10 +1233,11 @@
                 each.GetWindow().Enable()
             for each in self.centerSizer.GetChildren():
                 each.GetWindow().Disable()
-                    
+
             if self.scale[scaleType]:
-                
-                self.scaleTextCtrl.SetValue("%.0f" % (1/self.scale[scaleType]))
+
+                self.scaleTextCtrl.SetValue(
+                    "%.0f" % (1 / self.scale[scaleType]))
             if self.center[scaleType]:
                 self.eastingTextCtrl.SetValue(str(self.center[scaleType][0]))
                 self.northingTextCtrl.SetValue(str(self.center[scaleType][1]))
@@ -895,69 +1246,77 @@
                 each.GetWindow().Disable()
             for each in self.centerSizer.GetChildren():
                 each.GetWindow().Disable()
-                
+
             if self.scale[scaleType]:
-                self.scaleTextCtrl.SetValue("%.0f" % (1/self.scale[scaleType]))
+                self.scaleTextCtrl.SetValue(
+                    "%.0f" % (1 / self.scale[scaleType]))
             if self.center[scaleType]:
                 self.eastingTextCtrl.SetValue(str(self.center[scaleType][0]))
                 self.northingTextCtrl.SetValue(str(self.center[scaleType][1]))
-        else: # fixed
+        else:  # fixed
             for each in self.mapSizer.GetChildren():
                 each.GetWindow().Disable()
             for each in self.centerSizer.GetChildren():
                 each.GetWindow().Enable()
-                    
+
             if self.scale[scaleType]:
-                self.scaleTextCtrl.SetValue("%.0f" % (1/self.scale[scaleType]))
+                self.scaleTextCtrl.SetValue(
+                    "%.0f" % (1 / self.scale[scaleType]))
             if self.center[scaleType]:
                 self.eastingTextCtrl.SetValue(str(self.center[scaleType][0]))
                 self.northingTextCtrl.SetValue(str(self.center[scaleType][1]))
-                
+
     def OnElementType(self, event):
         """Changes data in map selection tree ctrl popup"""
         if self.rasterTypeRadio.GetValue():
             mapType = 'raster'
         else:
             mapType = 'vector'
-        self.select.SetElementList(type  = mapType)
+        self.select.SetElementList(type=mapType)
         if self.mapType != mapType and event is not None:
             self.mapType = mapType
             self.select.SetValue('')
-        self.mapType = mapType    
-        
+        self.mapType = mapType
+
     def OnBorder(self, event):
         """Enables/disable the part relating to border of map frame"""
-        for each in (self.borderColorText, self.borderWidthText, self.borderColourPicker, self.borderWidthCtrl):
+        for each in (self.borderColorText, self.borderWidthText,
+                     self.borderColourPicker, self.borderWidthCtrl):
             each.Enable(self.borderCheck.GetValue())
-            
+
     def getId(self):
         """Returns id of raster map"""
         return self.id
-            
+
     def update(self):
         """Save changes"""
         mapFrameDict = dict(self.mapFrameDict)
         # resolution
         mapFrameDict['resolution'] = self.resolutionSpin.GetValue()
-        #scale
+        # scale
         scaleType = self.scaleType
         mapFrameDict['scaleType'] = scaleType
-        
+
         if mapFrameDict['scaleType'] == 0:
             if self.select.GetValue():
                 mapFrameDict['drawMap'] = self.drawMap.GetValue()
                 mapFrameDict['map'] = self.select.GetValue()
                 mapFrameDict['mapType'] = self.mapType
                 mapFrameDict['region'] = None
-                
+
                 if mapFrameDict['drawMap']:
 
                     if mapFrameDict['mapType'] == 'raster':
-                        mapFile = grass.find_file(mapFrameDict['map'], element = 'cell')
+                        mapFile = grass.find_file(
+                            mapFrameDict['map'],
+                            element='cell')
                         if mapFile['file'] == '':
-                            GMessage("Raster %s not found" % mapFrameDict['map'])
+                            GMessage(
+                                "Raster %s not found" %
+                                mapFrameDict['map'])
                             return False
-                        raster = self.instruction.FindInstructionByType('raster')
+                        raster = self.instruction.FindInstructionByType(
+                            'raster')
                         if raster:
                             raster['raster'] = mapFrameDict['map']
                         else:
@@ -967,20 +1326,26 @@
                             self.instruction.AddInstruction(raster)
 
                     elif mapFrameDict['mapType'] == 'vector':
-                        
-                        mapFile = grass.find_file(mapFrameDict['map'], element = 'vector')
+
+                        mapFile = grass.find_file(
+                            mapFrameDict['map'],
+                            element='vector')
                         if mapFile['file'] == '':
-                            GMessage("Vector %s not found" % mapFrameDict['map'])
+                            GMessage(
+                                "Vector %s not found" %
+                                mapFrameDict['map'])
                             return False
-                        
-                        vector = self.instruction.FindInstructionByType('vector')
+
+                        vector = self.instruction.FindInstructionByType(
+                            'vector')
                         isAdded = False
                         if vector:
                             for each in vector['list']:
                                 if each[0] == mapFrameDict['map']:
                                     isAdded = True
                         if not isAdded:
-                            topoInfo = grass.vector_info_topo(map = mapFrameDict['map'])
+                            topoInfo = grass.vector_info_topo(
+                                map=mapFrameDict['map'])
                             if topoInfo:
                                 if bool(topoInfo['areas']):
                                     topoType = 'areas'
@@ -988,104 +1353,119 @@
                                     topoType = 'lines'
                                 else:
                                     topoType = 'points'
-                                label = '('.join(mapFrameDict['map'].split('@')) + ')'
-                           
+                                label = '('.join(
+                                    mapFrameDict['map'].split('@')) + ')'
+
                                 if not vector:
                                     vector = Vector(wx.NewId())
                                     vector['list'] = []
                                     self.instruction.AddInstruction(vector)
                                 id = wx.NewId()
-                                vector['list'].insert(0, [mapFrameDict['map'], topoType, id, 1, label])
+                                vector['list'].insert(
+                                    0, [mapFrameDict['map'], topoType, id, 1, label])
                                 vProp = VProperties(id, topoType)
-                                vProp['name'], vProp['label'], vProp['lpos'] = mapFrameDict['map'], label, 1
+                                vProp['name'], vProp['label'], vProp[
+                                    'lpos'] = mapFrameDict['map'], label, 1
                                 self.instruction.AddInstruction(vProp)
                             else:
                                 return False
-                            
-                self.scale[0], self.center[0], self.rectAdjusted = AutoAdjust(self, scaleType = 0, map = mapFrameDict['map'],
-                                                                   mapType = self.mapType, rect = self.mapFrameDict['rect'])
-                                               
+
+                self.scale[0], self.center[0], self.rectAdjusted = AutoAdjust(
+                    self, scaleType=0, map=mapFrameDict['map'],
+                    mapType=self.mapType, rect=self.mapFrameDict['rect'])
+
                 if self.rectAdjusted:
-                    mapFrameDict['rect'] = self.rectAdjusted 
+                    mapFrameDict['rect'] = self.rectAdjusted
                 else:
                     mapFrameDict['rect'] = self.mapFrameDict['rect']
 
                 mapFrameDict['scale'] = self.scale[0]
-                
+
                 mapFrameDict['center'] = self.center[0]
                 # set region
                 if self.mapType == 'raster':
-                    RunCommand('g.region', raster = mapFrameDict['map'])
+                    RunCommand('g.region', raster=mapFrameDict['map'])
                 if self.mapType == 'vector':
                     raster = self.instruction.FindInstructionByType('raster')
                     if raster:
-                        rasterId = raster.id 
+                        rasterId = raster.id
                     else:
                         rasterId = None
 
                     if rasterId:
-                        
-                        RunCommand('g.region', vector = mapFrameDict['map'], raster = self.instruction[rasterId]['raster'])
+
+                        RunCommand(
+                            'g.region',
+                            vector=mapFrameDict['map'],
+                            raster=self.instruction[rasterId]['raster'])
                     else:
-                        RunCommand('g.region', vector = mapFrameDict['map'])
-                
-                    
-                
+                        RunCommand('g.region', vector=mapFrameDict['map'])
+
             else:
-                wx.MessageBox(message = _("No map selected!"),
-                                    caption = _('Invalid input'), style = wx.OK|wx.ICON_ERROR)
-                return False    
-            
+                wx.MessageBox(
+                    message=_("No map selected!"),
+                    caption=_('Invalid input'),
+                    style=wx.OK | wx.ICON_ERROR)
+                return False
+
         elif mapFrameDict['scaleType'] == 1:
             if self.select.GetValue():
                 mapFrameDict['drawMap'] = False
                 mapFrameDict['map'] = None
                 mapFrameDict['mapType'] = None
                 mapFrameDict['region'] = self.select.GetValue()
-                self.scale[1], self.center[1], self.rectAdjusted = AutoAdjust(self, scaleType = 1, region = mapFrameDict['region'],
-                                                                                rect = self.mapFrameDict['rect'])
+                self.scale[1], self.center[1], self.rectAdjusted = AutoAdjust(
+                    self, scaleType=1, region=mapFrameDict['region'], rect=self.mapFrameDict['rect'])
                 if self.rectAdjusted:
-                    mapFrameDict['rect'] = self.rectAdjusted 
+                    mapFrameDict['rect'] = self.rectAdjusted
                 else:
                     mapFrameDict['rect'] = self.mapFrameDict['rect']
 
                 mapFrameDict['scale'] = self.scale[1]
                 mapFrameDict['center'] = self.center[1]
                 # set region
-                RunCommand('g.region', region = mapFrameDict['region'])
+                RunCommand('g.region', region=mapFrameDict['region'])
             else:
-                wx.MessageBox(message = _("No region selected!"),
-                                    caption = _('Invalid input'), style = wx.OK|wx.ICON_ERROR)
-                return False 
-                               
+                wx.MessageBox(
+                    message=_("No region selected!"),
+                    caption=_('Invalid input'),
+                    style=wx.OK | wx.ICON_ERROR)
+                return False
+
         elif scaleType == 2:
             mapFrameDict['drawMap'] = False
             mapFrameDict['map'] = None
             mapFrameDict['mapType'] = None
             mapFrameDict['region'] = None
-            self.scale[2], self.center[2], self.rectAdjusted = AutoAdjust(self, scaleType = 2, rect = self.mapFrameDict['rect'])
+            self.scale[2], self.center[2], self.rectAdjusted = AutoAdjust(
+                self, scaleType=2, rect=self.mapFrameDict['rect'])
             if self.rectAdjusted:
-                mapFrameDict['rect'] = self.rectAdjusted 
+                mapFrameDict['rect'] = self.rectAdjusted
             else:
                 mapFrameDict['rect'] = self.mapFrameDict['rect']
 
             mapFrameDict['scale'] = self.scale[2]
             mapFrameDict['center'] = self.center[2]
             region = grass.region()
-            
+
             raster = self.instruction.FindInstructionByType('raster')
             if raster:
-                rasterId = raster.id 
+                rasterId = raster.id
             else:
                 rasterId = None
 
-            if rasterId: # because of resolution
-                RunCommand('g.region', n=region['n'], s=region['s'],
-                            e=region['e'], w=region['w'], rast=self.instruction[rasterId]['raster'])
+            if rasterId:  # because of resolution
+                RunCommand(
+                    'g.region',
+                    n=region['n'],
+                    s=region['s'],
+                    e=region['e'],
+                    w=region['w'],
+                    rast=self.instruction[rasterId]['raster'])
             else:
                 RunCommand('g.region', n=region['n'], s=region['s'],
                            e=region['e'], w=region['w'])
-            
+
         elif scaleType == 3:
             mapFrameDict['drawMap'] = False
             mapFrameDict['map'] = None
@@ -1094,48 +1474,56 @@
             mapFrameDict['rect'] = self.mapFrameDict['rect']
             try:
                 scaleNumber = float(self.scaleTextCtrl.GetValue())
-                centerE = float(self.eastingTextCtrl.GetValue()) 
+                centerE = float(self.eastingTextCtrl.GetValue())
                 centerN = float(self.northingTextCtrl.GetValue())
             except (ValueError, SyntaxError):
-                wx.MessageBox(message = _("Invalid scale or map center!"),
-                                    caption = _('Invalid input'), style = wx.OK|wx.ICON_ERROR)
-                return False  
-            mapFrameDict['scale'] = 1/scaleNumber
+                wx.MessageBox(
+                    message=_("Invalid scale or map center!"),
+                    caption=_('Invalid input'),
+                    style=wx.OK | wx.ICON_ERROR)
+                return False
+            mapFrameDict['scale'] = 1 / scaleNumber
             mapFrameDict['center'] = centerE, centerN
-        
-            ComputeSetRegion(self, mapDict = mapFrameDict)
-        
+
+            ComputeSetRegion(self, mapDict=mapFrameDict)
+
         # check resolution
-        SetResolution(dpi = mapFrameDict['resolution'], width = mapFrameDict['rect'].width,
-                                                        height = mapFrameDict['rect'].height)
+        SetResolution(
+            dpi=mapFrameDict['resolution'],
+            width=mapFrameDict['rect'].width,
+            height=mapFrameDict['rect'].height)
         # border
         if self.borderCheck.GetValue():
-            mapFrameDict['border'] = 'y' 
+            mapFrameDict['border'] = 'y'
         else:
             mapFrameDict['border'] = 'n'
 
         if mapFrameDict['border'] == 'y':
             mapFrameDict['width'] = self.borderWidthCtrl.GetValue()
-            mapFrameDict['color'] = convertRGB(self.borderColourPicker.GetColour())
-            
+            mapFrameDict['color'] = convertRGB(
+                self.borderColourPicker.GetColour())
+
         if self.id not in self.instruction:
             mapFrame = MapFrame(self.id)
             self.instruction.AddInstruction(mapFrame)
         self.instruction[self.id].SetInstruction(mapFrameDict)
 
         if self.id not in self.mapDialog.parent.objectId:
-            self.mapDialog.parent.objectId.insert(0, self.id)# map frame is drawn first
+            self.mapDialog.parent.objectId.insert(
+                0, self.id)  # map frame is drawn first
         return True
-        
+
+
 class RasterPanel(wx.Panel):
     """Panel for raster map settings"""
-    def __init__(self, parent, id, settings,  notebook = True):
-        wx.Panel.__init__(self, parent, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL)
+
+    def __init__(self, parent, id, settings, notebook=True):
+        wx.Panel.__init__(self, parent, id=wx.ID_ANY, style=wx.TAB_TRAVERSAL)
         self.instruction = settings
-        
+
         if notebook:
             self.book = parent
-            self.book.AddPage(page = self, text = _("Raster map"))
+            self.book.AddPage(page=self, text=_("Raster map"))
             self.mainDialog = self.book.GetParent()
         else:
             self.mainDialog = parent
@@ -1146,27 +1534,38 @@
             self.id = wx.NewId()
             raster = Raster(self.id)
             self.rasterDict = raster.GetInstruction()
-            
-            
+
         self._layout()
         self.OnRaster(None)
-            
+
     def _layout(self):
         """Do layout"""
         border = wx.BoxSizer(wx.VERTICAL)
-        
+
         # choose raster map
-        
-        box   = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Choose raster map"))
+
+        box = wx.StaticBox(
+            parent=self,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Choose raster map"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
-        
-        self.rasterNoRadio = wx.RadioButton(self, id = wx.ID_ANY, label = _("no raster map"), style = wx.RB_GROUP)
-        self.rasterYesRadio = wx.RadioButton(self, id = wx.ID_ANY, label = _("raster:"))
-        
-        self.rasterSelect = Select(self, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
-                             type = 'raster', multiple = False,
-                             updateOnPopup = True, onPopup = None)
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
+
+        self.rasterNoRadio = wx.RadioButton(
+            self, id=wx.ID_ANY, label=_("no raster map"),
+            style=wx.RB_GROUP)
+        self.rasterYesRadio = wx.RadioButton(
+            self, id=wx.ID_ANY, label=_("raster:"))
+
+        self.rasterSelect = Select(
+            self,
+            id=wx.ID_ANY,
+            size=globalvar.DIALOG_GSELECT_SIZE,
+            type='raster',
+            multiple=False,
+            updateOnPopup=True,
+            onPopup=None)
         if self.rasterDict['isRaster']:
             self.rasterYesRadio.SetValue(True)
             self.rasterNoRadio.SetValue(False)
@@ -1176,35 +1575,52 @@
             self.rasterNoRadio.SetValue(True)
             mapId = self.instruction.FindInstructionByType('map').id
 
-            if self.instruction[mapId]['map'] and self.instruction[mapId]['mapType'] == 'raster':
-                self.rasterSelect.SetValue(self.instruction[mapId]['map'])# raster map from map frame dialog if possible
+            if self.instruction[mapId]['map'] and self.instruction[
+                    mapId]['mapType'] == 'raster':
+                # raster map from map frame dialog if possible
+                self.rasterSelect.SetValue(self.instruction[mapId]['map'])
             else:
-                self.rasterSelect.SetValue('')                
-        gridBagSizer.Add(self.rasterNoRadio, pos = (0, 0), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)            
-        gridBagSizer.Add(self.rasterYesRadio, pos = (1, 0),  flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.rasterSelect, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        
-        sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+                self.rasterSelect.SetValue('')
+        gridBagSizer.Add(
+            self.rasterNoRadio, pos=(
+                0, 0), span=(
+                1, 2), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.rasterYesRadio, pos=(1, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.rasterSelect,
+            pos=(
+                1,
+                1),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+            border=0)
+
+        sizer.Add(
+            gridBagSizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         #self.rasterSelect.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnRaster)
         self.Bind(wx.EVT_RADIOBUTTON, self.OnRaster, self.rasterNoRadio)
         self.Bind(wx.EVT_RADIOBUTTON, self.OnRaster, self.rasterYesRadio)
-        
+
         self.SetSizer(border)
         self.Fit()
-        
+
     def OnRaster(self, event):
         """Enable/disable raster selection"""
         self.rasterSelect.Enable(self.rasterYesRadio.GetValue())
-        
+
     def update(self):
-        #draw raster
+        # draw raster
         mapInstr = self.instruction.FindInstructionByType('map')
-        if not mapInstr: # no map frame
-            GMessage(message = _("Please, create map frame first."))
+        if not mapInstr:  # no map frame
+            GMessage(message=_("Please, create map frame first."))
             return
-            
+
         if self.rasterNoRadio.GetValue() or not self.rasterSelect.GetValue():
             self.rasterDict['isRaster'] = False
             self.rasterDict['raster'] = None
@@ -1225,26 +1641,30 @@
                 self.instruction[self.id].SetInstruction(self.rasterDict)
             else:
                 self.instruction[raster.id].SetInstruction(self.rasterDict)
-            
+
         if 'map' in self.mainDialog.parent.openDialogs:
             self.mainDialog.parent.openDialogs['map'].updateDialog()
         return True
-        
+
     def getId(self):
         return self.id
-  
+
+
 class VectorPanel(wx.Panel):
     """Panel for vector maps settings"""
-    def __init__(self, parent, id, settings, notebook = True):
-        wx.Panel.__init__(self, parent, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL)
-        
+
+    def __init__(self, parent, id, settings, notebook=True):
+        wx.Panel.__init__(self, parent, id=wx.ID_ANY, style=wx.TAB_TRAVERSAL)
+
         self.parent = parent
         self.instruction = settings
         self.tmpDialogDict = {}
-        vectors = self.instruction.FindInstructionByType('vProperties', list = True)
+        vectors = self.instruction.FindInstructionByType(
+            'vProperties', list=True)
         for vector in vectors:
-            self.tmpDialogDict[vector.id] = dict(self.instruction[vector.id].GetInstruction())
-        
+            self.tmpDialogDict[vector.id] = dict(
+                self.instruction[vector.id].GetInstruction())
+
         if id:
             self.id = id
             self.vectorList = deepcopy(self.instruction[id]['list'])
@@ -1254,107 +1674,168 @@
 
         vLegend = self.instruction.FindInstructionByType('vectorLegend')
         if vLegend:
-            self.vLegendId = vLegend.id 
+            self.vLegendId = vLegend.id
         else:
             self.vLegendId = None
 
-         
         self._layout()
-        
+
         if notebook:
-            self.parent.AddPage(page = self, text = _("Vector maps"))
+            self.parent.AddPage(page=self, text=_("Vector maps"))
             self.parent = self.parent.GetParent()
-            
+
     def _layout(self):
         """Do layout"""
         border = wx.BoxSizer(wx.VERTICAL)
-        
+
         # choose vector map
-        
-        box   = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Add map"))
+
+        box = wx.StaticBox(
+            parent=self,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Add map"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
-        
-        text = wx.StaticText(self, id = wx.ID_ANY, label = _("Map:"))
-        self.select = Select(self, id = wx.ID_ANY,# size = globalvar.DIALOG_GSELECT_SIZE,
-                             type = 'vector', multiple = False,
-                             updateOnPopup = True, onPopup = None)
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
+
+        text = wx.StaticText(self, id=wx.ID_ANY, label=_("Map:"))
+        self.select = Select(self, id=wx.ID_ANY,  # size = globalvar.DIALOG_GSELECT_SIZE,
+                             type='vector', multiple=False,
+                             updateOnPopup=True, onPopup=None)
         topologyTypeTr = [_("points"), _("lines"), _("areas")]
         self.topologyTypeList = ["points", "lines", "areas"]
-        self.vectorType = wx.RadioBox(self, id = wx.ID_ANY, label = " %s " % _("Data Type"), choices = topologyTypeTr,
-                                      majorDimension = 3, style = wx.RA_SPECIFY_COLS)
-            
-        self.AddVector = wx.Button(self, id = wx.ID_ANY, label = _("Add"))
-        
-        gridBagSizer.Add(text, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.select, pos = (0,1), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.vectorType, pos = (1,1), flag = wx.ALIGN_CENTER, border = 0)
-        gridBagSizer.Add(self.AddVector, pos = (1,2), flag = wx.ALIGN_BOTTOM|wx.ALIGN_RIGHT, border = 0)
-        
-        sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+        self.vectorType = wx.RadioBox(
+            self,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Data Type"),
+            choices=topologyTypeTr,
+            majorDimension=3,
+            style=wx.RA_SPECIFY_COLS)
+
+        self.AddVector = wx.Button(self, id=wx.ID_ANY, label=_("Add"))
+
+        gridBagSizer.Add(
+            text, pos=(0, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.select, pos=(
+                0, 1), span=(
+                1, 2), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.vectorType, pos=(1, 1),
+            flag=wx.ALIGN_CENTER, border=0)
+        gridBagSizer.Add(
+            self.AddVector, pos=(1, 2),
+            flag=wx.ALIGN_BOTTOM | wx.ALIGN_RIGHT, border=0)
+
+        sizer.Add(
+            gridBagSizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         # manage vector layers
-        
-        box   = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Manage vector maps"))
+
+        box = wx.StaticBox(
+            parent=self,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Manage vector maps"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
 
-        
-        
-        text = wx.StaticText(self, id = wx.ID_ANY, label = _("The topmost vector map overlaps the others"))
-        self.listbox = wx.ListBox(self, id = wx.ID_ANY, choices = [], style = wx.LB_SINGLE|wx.LB_NEEDED_SB)
-        self.btnUp = wx.Button(self, id = wx.ID_ANY, label = _("Up"))
-        self.btnDown = wx.Button(self, id = wx.ID_ANY, label = _("Down"))
-        self.btnDel = wx.Button(self, id = wx.ID_ANY, label = _("Delete"))
-        self.btnProp = wx.Button(self, id = wx.ID_ANY, label = _("Properties..."))
-        
+        text = wx.StaticText(self, id=wx.ID_ANY, label=_(
+            "The topmost vector map overlaps the others"))
+        self.listbox = wx.ListBox(
+            self, id=wx.ID_ANY, choices=[],
+            style=wx.LB_SINGLE | wx.LB_NEEDED_SB)
+        self.btnUp = wx.Button(self, id=wx.ID_ANY, label=_("Up"))
+        self.btnDown = wx.Button(self, id=wx.ID_ANY, label=_("Down"))
+        self.btnDel = wx.Button(self, id=wx.ID_ANY, label=_("Delete"))
+        self.btnProp = wx.Button(self, id=wx.ID_ANY, label=_("Properties..."))
+
         self.updateListBox(selected=0)
-        
-        
-        gridBagSizer.Add(text, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.listbox, pos = (1,0), span = (4, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        gridBagSizer.Add(self.btnUp, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        gridBagSizer.Add(self.btnDown, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        gridBagSizer.Add(self.btnDel, pos = (3,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        gridBagSizer.Add(self.btnProp, pos = (4,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        
-        gridBagSizer.AddGrowableCol(0,2)
-        gridBagSizer.AddGrowableCol(1,1)
-        sizer.Add(gridBagSizer, proportion = 0, flag = wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+
+        gridBagSizer.Add(
+            text, pos=(0, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.listbox, pos=(
+                1, 0), span=(
+                4, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+        gridBagSizer.Add(
+            self.btnUp,
+            pos=(
+                1,
+                1),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+            border=0)
+        gridBagSizer.Add(
+            self.btnDown,
+            pos=(
+                2,
+                1),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+            border=0)
+        gridBagSizer.Add(
+            self.btnDel,
+            pos=(
+                3,
+                1),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+            border=0)
+        gridBagSizer.Add(
+            self.btnProp,
+            pos=(
+                4,
+                1),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+            border=0)
+
+        gridBagSizer.AddGrowableCol(0, 2)
+        gridBagSizer.AddGrowableCol(1, 1)
+        sizer.Add(gridBagSizer, proportion=0, flag=wx.ALL, border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         self.Bind(wx.EVT_BUTTON, self.OnAddVector, self.AddVector)
         self.Bind(wx.EVT_BUTTON, self.OnDelete, self.btnDel)
         self.Bind(wx.EVT_BUTTON, self.OnUp, self.btnUp)
         self.Bind(wx.EVT_BUTTON, self.OnDown, self.btnDown)
         self.Bind(wx.EVT_BUTTON, self.OnProperties, self.btnProp)
         self.select.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnVector)
-        
+
         self.SetSizer(border)
         self.Fit()
-        
+
         self.Bind(wx.EVT_LISTBOX_DCLICK, self.OnProperties, self.listbox)
 
     def OnVector(self, event):
         """Gets info about toplogy and enables/disables choices point/line/area"""
-        vmap = self.select.GetValue()   
-        try:     
-            topoInfo = grass.vector_info_topo(map = vmap)
+        vmap = self.select.GetValue()
+        try:
+            topoInfo = grass.vector_info_topo(map=vmap)
         except grass.ScriptError:
             return
-        
+
         if topoInfo:
             self.vectorType.EnableItem(2, bool(topoInfo['areas']))
-            self.vectorType.EnableItem(1, bool(topoInfo['boundaries']) or bool(topoInfo['lines']))
-            self.vectorType.EnableItem(0, bool(topoInfo['centroids'] or bool(topoInfo['points']) ))
-            for item in range(2,-1,-1):
+            self.vectorType.EnableItem(
+                1, bool(
+                    topoInfo['boundaries']) or bool(
+                    topoInfo['lines']))
+            self.vectorType.EnableItem(
+                0, bool(
+                    topoInfo['centroids'] or bool(
+                        topoInfo['points'])))
+            for item in range(2, -1, -1):
                 if self.vectorType.IsItemEnabled(item):
                     self.vectorType.SetSelection(item)
                     break
-            
-            self.AddVector.SetFocus()        
-            
+
+            self.AddVector.SetFocus()
+
     def OnAddVector(self, event):
         """Adds vector map to list"""
         vmap = self.select.GetValue()
@@ -1369,21 +1850,20 @@
             record = "%s - %s" % (vmap, ttype)
             id = wx.NewId()
             lpos = 1
-            label = mapname + mapset 
+            label = mapname + mapset
             self.vectorList.insert(0, [vmap, ttype, id, lpos, label])
             self.reposition()
             self.listbox.InsertItems([record], 0)
-            
+
             vector = VProperties(id, ttype)
             self.tmpDialogDict[id] = vector.GetInstruction()
             self.tmpDialogDict[id]['name'] = vmap
 
-            
-            self.listbox.SetSelection(0)  
+            self.listbox.SetSelection(0)
             self.listbox.EnsureVisible(0)
             self.btnProp.SetFocus()
             self.enableButtons()
-            
+
     def OnDelete(self, event):
         """Deletes vector map from the list"""
         if self.listbox.GetSelections():
@@ -1391,20 +1871,19 @@
             id = self.vectorList[pos][2]
             del self.vectorList[pos]
             del self.tmpDialogDict[id]
-            
+
             for i in range(pos, len(self.vectorList)):
-                if self.vectorList[i][3]:# can be 0
+                if self.vectorList[i][3]:  # can be 0
                     self.vectorList[i][3] -= 1
-            
-            if pos < len(self.vectorList) -1:
+
+            if pos < len(self.vectorList) - 1:
                 selected = pos
             else:
-                selected = len(self.vectorList) -1
-            self.updateListBox(selected = selected)
+                selected = len(self.vectorList) - 1
+            self.updateListBox(selected=selected)
             if self.listbox.IsEmpty():
                 self.enableButtons(False)
-            
-            
+
     def OnUp(self, event):
         """Moves selected map to top"""
         if self.listbox.GetSelections():
@@ -1413,13 +1892,12 @@
                 self.vectorList.insert(pos - 1, self.vectorList.pop(pos))
             if not self.vLegendId:
                 self.reposition()
-                
+
             if pos > 0:
-                self.updateListBox(selected = (pos - 1)) 
+                self.updateListBox(selected=(pos - 1))
             else:
-                self.updateListBox(selected = 0)
+                self.updateListBox(selected=0)
 
-            
     def OnDown(self, event):
         """Moves selected map to bottom"""
         if self.listbox.GetSelections():
@@ -1428,32 +1906,35 @@
                 self.vectorList.insert(pos + 1, self.vectorList.pop(pos))
                 if not self.vLegendId:
                     self.reposition()
-            if pos < len(self.vectorList) -1:
-                self.updateListBox(selected = (pos + 1)) 
+            if pos < len(self.vectorList) - 1:
+                self.updateListBox(selected=(pos + 1))
             else:
-                self.updateListBox(selected = len(self.vectorList) -1)
+                self.updateListBox(selected=len(self.vectorList) - 1)
 
-    
     def OnProperties(self, event):
         """Opens vector map properties dialog"""
         if self.listbox.GetSelections():
             pos = self.listbox.GetSelection()
             id = self.vectorList[pos][2]
 
-            dlg = VPropertiesDialog(self, id = id, settings = self.instruction, 
-                                    vectors = self.vectorList, tmpSettings = self.tmpDialogDict[id])
+            dlg = VPropertiesDialog(
+                self,
+                id=id,
+                settings=self.instruction,
+                vectors=self.vectorList,
+                tmpSettings=self.tmpDialogDict[id])
             dlg.ShowModal()
-            
+
             self.parent.FindWindowById(wx.ID_OK).SetFocus()
-           
-    def enableButtons(self, enable = True):
+
+    def enableButtons(self, enable=True):
         """Enable/disable up, down, properties, delete buttons"""
         self.btnUp.Enable(enable)
         self.btnDown.Enable(enable)
         self.btnProp.Enable(enable)
         self.btnDel.Enable(enable)
-    
-    def updateListBox(self, selected = None):
+
+    def updateListBox(self, selected=None):
         mapList = ["%s - %s" % (item[0], item[1]) for item in self.vectorList]
         self.listbox.Set(mapList)
         if self.listbox.IsEmpty():
@@ -1461,32 +1942,33 @@
         else:
             self.enableButtons(True)
             if selected is not None:
-                self.listbox.SetSelection(selected)  
-                self.listbox.EnsureVisible(selected)  
-              
+                self.listbox.SetSelection(selected)
+                self.listbox.EnsureVisible(selected)
+
     def reposition(self):
         """Update position in legend, used only if there is no vlegend yet"""
         for i in range(len(self.vectorList)):
             if self.vectorList[i][3]:
                 self.vectorList[i][3] = i + 1
-                
+
     def getId(self):
         return self.id
-        
+
     def update(self):
-        vectors = self.instruction.FindInstructionByType('vProperties', list = True)
-        
+        vectors = self.instruction.FindInstructionByType(
+            'vProperties', list=True)
+
         for vector in vectors:
             del self.instruction[vector.id]
         if self.id in self.instruction:
-            del self.instruction[self.id] 
+            del self.instruction[self.id]
 
         if len(self.vectorList) > 0:
             vector = Vector(self.id)
             self.instruction.AddInstruction(vector)
 
             vector.SetInstruction({'list': deepcopy(self.vectorList)})
-            
+
             # save new vectors
             for item in self.vectorList:
                 id = item[2]
@@ -1497,93 +1979,123 @@
                 vLayer['name'] = item[0]
                 vLayer['label'] = item[4]
                 vLayer['lpos'] = item[3]
-            
+
         else:
             if self.id in self.instruction:
                 del self.instruction[self.id]
-                
+
         if 'map' in self.parent.parent.openDialogs:
             self.parent.parent.openDialogs['map'].updateDialog()
 
         return True
-    
+
+
 class RasterDialog(PsmapDialog):
+
     def __init__(self, parent, id, settings):
-        PsmapDialog.__init__(self, parent = parent, id = id, title = _("Raster map settings"), settings = settings)
+        PsmapDialog.__init__(
+            self,
+            parent=parent,
+            id=id,
+            title=_("Raster map settings"),
+            settings=settings)
         self.objectType = ('raster',)
-        
-        self.rPanel = RasterPanel(parent = self, id = self.id, settings = self.instruction, notebook = False)
 
+        self.rPanel = RasterPanel(
+            parent=self,
+            id=self.id,
+            settings=self.instruction,
+            notebook=False)
+
         self.id = self.rPanel.getId()
         self._layout(self.rPanel)
-    
+
     def update(self):
         ok = self.rPanel.update()
         if ok:
             return True
         return False
-    
+
     def OnApply(self, event):
         ok = self.update()
         if not ok:
             return False
 
         if self.id in self.instruction:
-            self.parent.DialogDataChanged(id = self.id)
+            self.parent.DialogDataChanged(id=self.id)
         else:
             mapId = self.instruction.FindInstructionByType('map').id
-            self.parent.DialogDataChanged(id = mapId)
+            self.parent.DialogDataChanged(id=mapId)
         return True
-    
+
     def updateDialog(self):
         """Update information (not used)"""
         pass
-##        if 'map' in self.parent.openDialogs:
-##            if self.parent.openDialogs['map'].mPanel.rasterTypeRadio.GetValue()\
-##                    and self.parent.openDialogs['map'].mPanel.select.GetValue():
-##                if self.parent.openDialogs['map'].mPanel.drawMap.IsChecked():
-##                    self.rPanel.rasterSelect.SetValue(self.parent.openDialogs['map'].mPanel.select.GetValue())   
-                
+# if 'map' in self.parent.openDialogs:
+# if self.parent.openDialogs['map'].mPanel.rasterTypeRadio.GetValue()\
+# and self.parent.openDialogs['map'].mPanel.select.GetValue():
+# if self.parent.openDialogs['map'].mPanel.drawMap.IsChecked():
+# self.rPanel.rasterSelect.SetValue(self.parent.openDialogs['map'].mPanel.select.GetValue())
+
+
 class MainVectorDialog(PsmapDialog):
+
     def __init__(self, parent, id, settings):
-        PsmapDialog.__init__(self, parent = parent, id = id, title = _("Vector maps settings"), settings = settings)
+        PsmapDialog.__init__(
+            self,
+            parent=parent,
+            id=id,
+            title=_("Vector maps settings"),
+            settings=settings)
         self.objectType = ('vector',)
-        self.vPanel = VectorPanel(parent = self, id = self.id, settings = self.instruction, notebook = False)
+        self.vPanel = VectorPanel(
+            parent=self,
+            id=self.id,
+            settings=self.instruction,
+            notebook=False)
 
         self.id = self.vPanel.getId()
         self._layout(self.vPanel)
-    
+
     def update(self):
         self.vPanel.update()
-        
+
     def OnApply(self, event):
         self.update()
         if self.id in self.instruction:
-            self.parent.DialogDataChanged(id = self.id)
+            self.parent.DialogDataChanged(id=self.id)
         else:
             mapId = self.instruction.FindInstructionByType('map').id
-            self.parent.DialogDataChanged(id = mapId)
+            self.parent.DialogDataChanged(id=mapId)
         return True
-        
+
     def updateDialog(self):
         """Update information (not used)"""
         pass
-        
+
+
 class VPropertiesDialog(PsmapDialog):
+
     def __init__(self, parent, id, settings, vectors, tmpSettings):
-        PsmapDialog.__init__(self, parent = parent, id = id, title = "", settings = settings, apply = False)
-        
+        PsmapDialog.__init__(
+            self,
+            parent=parent,
+            id=id,
+            title="",
+            settings=settings,
+            apply=False)
+
         vectorList = vectors
         self.vPropertiesDict = tmpSettings
-        
+
         # determine map and its type
         for item in vectorList:
             if id == item[2]:
                 self.vectorName = item[0]
                 self.type = item[1]
         self.SetTitle(_("%s properties") % self.vectorName)
-        
-        #vector map info
+
+        # vector map info
         self.connection = True
         try:
             self.mapDBInfo = VectorDBInfo(self.vectorName)
@@ -1594,10 +2106,10 @@
         if not self.layers:
             self.connection = False
             self.layers = []
-            
+
         self.currLayer = self.vPropertiesDict['layer']
-        
-        #path to symbols, patterns
+
+        # path to symbols, patterns
         gisbase = os.getenv("GISBASE")
         self.symbolPath = os.path.join(gisbase, 'etc', 'symbol')
         self.symbols = []
@@ -1606,20 +2118,22 @@
                 self.symbols.append(os.path.join(dir, symbol))
         self.patternPath = os.path.join(gisbase, 'etc', 'paint', 'patterns')
 
-        #notebook
-        notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
+        # notebook
+        notebook = wx.Notebook(parent=self, id=wx.ID_ANY, style=wx.BK_DEFAULT)
         self.DSpanel = self._DataSelectionPanel(notebook)
-        self.EnableLayerSelection(enable = self.connection)
-        selectPanel = { 'points': [self._ColorsPointAreaPanel, self._StylePointPanel], 
-                        'lines': [self._ColorsLinePanel, self._StyleLinePanel], 
-                        'areas': [self._ColorsPointAreaPanel, self._StyleAreaPanel]}
+        self.EnableLayerSelection(enable=self.connection)
+        selectPanel = {
+            'points': [
+                self._ColorsPointAreaPanel, self._StylePointPanel], 'lines': [
+                self._ColorsLinePanel, self._StyleLinePanel], 'areas': [
+                self._ColorsPointAreaPanel, self._StyleAreaPanel]}
         self.ColorsPanel = selectPanel[self.type][0](notebook)
-        
+
         self.OnOutline(None)
         if self.type in ('points', 'areas'):
             self.OnFill(None)
         self.OnColor(None)
-        
+
         self.StylePanel = selectPanel[self.type][1](notebook)
         if self.type == 'points':
             self.OnSize(None)
@@ -1627,558 +2141,920 @@
             self.OnSymbology(None)
         if self.type == 'areas':
             self.OnPattern(None)
-        
+
         self._layout(notebook)
-        
+
     def _DataSelectionPanel(self, notebook):
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
-        notebook.AddPage(page = panel, text = _("Data selection"))
-        
+        panel = wx.Panel(
+            parent=notebook, id=wx.ID_ANY, size=(-1, -1),
+            style=wx.TAB_TRAVERSAL)
+        notebook.AddPage(page=panel, text=_("Data selection"))
+
         border = wx.BoxSizer(wx.VERTICAL)
-        
+
         # data type
         self.checkType1 = self.checkType2 = None
         if self.type in ('lines', 'points'):
-            box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Feature type"))
+            box = wx.StaticBox(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=" %s " %
+                _("Feature type"))
             sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
-            gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
+            gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
             if self.type == 'points':
                 label = (_("points"), _("centroids"))
-            else: 
+            else:
                 label = (_("lines"), _("boundaries"))
             if self.type == 'points':
                 name = ("point", "centroid")
             else:
                 name = ("line", "boundary")
-            self.checkType1 = wx.CheckBox(panel, id = wx.ID_ANY, label = label[0], name = name[0])
-            self.checkType2 = wx.CheckBox(panel, id = wx.ID_ANY, label = label[1], name = name[1])
-            self.checkType1.SetValue(self.vPropertiesDict['type'].find(name[0]) >= 0)
-            self.checkType2.SetValue(self.vPropertiesDict['type'].find(name[1]) >= 0)
-            
-            gridBagSizer.Add(self.checkType1, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-            gridBagSizer.Add(self.checkType2, pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-            sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-            border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+            self.checkType1 = wx.CheckBox(
+                panel, id=wx.ID_ANY, label=label[0], name=name[0])
+            self.checkType2 = wx.CheckBox(
+                panel, id=wx.ID_ANY, label=label[1], name=name[1])
+            self.checkType1.SetValue(
+                self.vPropertiesDict['type'].find(
+                    name[0]) >= 0)
+            self.checkType2.SetValue(
+                self.vPropertiesDict['type'].find(
+                    name[1]) >= 0)
+
+            gridBagSizer.Add(
+                self.checkType1, pos=(0, 0),
+                flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+            gridBagSizer.Add(
+                self.checkType2, pos=(0, 1),
+                flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+            sizer.Add(
+                gridBagSizer,
+                proportion=1,
+                flag=wx.EXPAND | wx.ALL,
+                border=5)
+            border.Add(
+                item=sizer,
+                proportion=0,
+                flag=wx.ALL | wx.EXPAND,
+                border=5)
+
         # layer selection
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Layer selection"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Layer selection"))
         sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
-        self.gridBagSizerL = wx.GridBagSizer(hgap = 5, vgap = 5)
-        
-        self.warning =  wx.StaticText(panel, id = wx.ID_ANY, label = "")
+        self.gridBagSizerL = wx.GridBagSizer(hgap=5, vgap=5)
+
+        self.warning = wx.StaticText(panel, id=wx.ID_ANY, label="")
         if not self.connection:
-            self.warning = wx.StaticText(panel, id = wx.ID_ANY, label = _("Database connection is not defined in DB file."))
-        text = wx.StaticText(panel, id = wx.ID_ANY, label = _("Select layer:"))
-        self.layerChoice = wx.Choice(panel, id = wx.ID_ANY, choices = map(str, self.layers), size = self.spinCtrlSize)
-        
+            self.warning = wx.StaticText(panel, id=wx.ID_ANY, label=_(
+                "Database connection is not defined in DB file."))
+        text = wx.StaticText(panel, id=wx.ID_ANY, label=_("Select layer:"))
+        self.layerChoice = wx.Choice(
+            panel, id=wx.ID_ANY, choices=map(
+                str, self.layers), size=self.spinCtrlSize)
+
         self.layerChoice.SetStringSelection(self.currLayer)
-                
+
         if self.connection:
-            table = self.mapDBInfo.layers[int(self.currLayer)]['table'] 
+            table = self.mapDBInfo.layers[int(self.currLayer)]['table']
         else:
             table = ""
 
-        self.radioWhere = wx.RadioButton(panel, id = wx.ID_ANY, label = "SELECT * FROM %s WHERE" % table, style = wx.RB_GROUP)
-        self.textCtrlWhere = wx.TextCtrl(panel, id = wx.ID_ANY, value = "")
-        
-        
+        self.radioWhere = wx.RadioButton(
+            panel, id=wx.ID_ANY, label="SELECT * FROM %s WHERE" %
+            table, style=wx.RB_GROUP)
+        self.textCtrlWhere = wx.TextCtrl(panel, id=wx.ID_ANY, value="")
+
         if self.connection:
-            cols = self.mapDBInfo.GetColumns(self.mapDBInfo.layers[int(self.currLayer)]['table']) 
+            cols = self.mapDBInfo.GetColumns(
+                self.mapDBInfo.layers[int(self.currLayer)]['table'])
         else:
             cols = []
 
-        self.choiceColumns = wx.Choice(panel, id = wx.ID_ANY, choices = cols)
-        
-        self.radioCats = wx.RadioButton(panel, id = wx.ID_ANY, label = "Choose categories ")
-        self.textCtrlCats = wx.TextCtrl(panel, id = wx.ID_ANY, value = "")
-        self.textCtrlCats.SetToolTipString(_("list of categories (e.g. 1,3,5-7)"))
-        
-        if self.vPropertiesDict.has_key('cats'):
+        self.choiceColumns = wx.Choice(panel, id=wx.ID_ANY, choices=cols)
+
+        self.radioCats = wx.RadioButton(
+            panel, id=wx.ID_ANY, label="Choose categories ")
+        self.textCtrlCats = wx.TextCtrl(panel, id=wx.ID_ANY, value="")
+        self.textCtrlCats.SetToolTipString(
+            _("list of categories (e.g. 1,3,5-7)"))
+
+        if 'cats' in self.vPropertiesDict:
             self.radioCats.SetValue(True)
             self.textCtrlCats.SetValue(self.vPropertiesDict['cats'])
-        if self.vPropertiesDict.has_key('where'):
+        if 'where' in self.vPropertiesDict:
             self.radioWhere.SetValue(True)
-            where = self.vPropertiesDict['where'].strip().split(" ",1)
+            where = self.vPropertiesDict['where'].strip().split(" ", 1)
             self.choiceColumns.SetStringSelection(where[0])
             self.textCtrlWhere.SetValue(where[1])
-            
+
         row = 0
         if not self.connection:
-            self.gridBagSizerL.Add(self.warning, pos = (0,0), span = (1,3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
+            self.gridBagSizerL.Add(
+                self.warning, pos=(
+                    0, 0), span=(
+                    1, 3), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
             row = 1
-        self.gridBagSizerL.Add(text, pos = (0 + row,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        self.gridBagSizerL.Add(self.layerChoice, pos = (0 + row,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        self.gridBagSizerL.Add(self.radioWhere, pos = (1 + row,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        self.gridBagSizerL.Add(self.choiceColumns, pos = (1 + row,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)        
-        self.gridBagSizerL.Add(self.textCtrlWhere, pos = (1 + row,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        self.gridBagSizerL.Add(self.radioCats, pos = (2 + row,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        self.gridBagSizerL.Add(self.textCtrlCats, pos = (2 + row,1), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        
-        sizer.Add(self.gridBagSizerL, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
-        #mask
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Mask"))
+        self.gridBagSizerL.Add(
+            text, pos=(0 + row, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerL.Add(
+            self.layerChoice, pos=(0 + row, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+        self.gridBagSizerL.Add(
+            self.radioWhere, pos=(1 + row, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerL.Add(
+            self.choiceColumns, pos=(1 + row, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerL.Add(
+            self.textCtrlWhere, pos=(1 + row, 2),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerL.Add(
+            self.radioCats, pos=(2 + row, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerL.Add(
+            self.textCtrlCats, pos=(2 + row, 1),
+            span=(1, 2),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+
+        sizer.Add(
+            self.gridBagSizerL,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
+        # mask
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Mask"))
         sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
-        
-        self.mask = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Use current mask"))
+
+        self.mask = wx.CheckBox(
+            panel, id=wx.ID_ANY, label=_("Use current mask"))
         if self.vPropertiesDict['masked'] == 'y':
-            self.mask.SetValue(True) 
+            self.mask.SetValue(True)
         else:
             self.mask.SetValue(False)
-        
-        sizer.Add(self.mask, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
 
+        sizer.Add(self.mask, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         self.Bind(wx.EVT_CHOICE, self.OnLayer, self.layerChoice)
-        
+
         panel.SetSizer(border)
         panel.Fit()
         return panel
-    
+
     def _ColorsPointAreaPanel(self, notebook):
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
-        notebook.AddPage(page = panel, text = _("Colors"))
-        
+        panel = wx.Panel(
+            parent=notebook, id=wx.ID_ANY, size=(-1, -1),
+            style=wx.TAB_TRAVERSAL)
+        notebook.AddPage(page=panel, text=_("Colors"))
+
         border = wx.BoxSizer(wx.VERTICAL)
-        
+
         #colors - outline
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Outline"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Outline"))
         sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
-        self.gridBagSizerO = wx.GridBagSizer(hgap = 5, vgap = 2)
-        
-        self.outlineCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("draw outline"))
+        self.gridBagSizerO = wx.GridBagSizer(hgap=5, vgap=2)
+
+        self.outlineCheck = wx.CheckBox(
+            panel, id=wx.ID_ANY, label=_("draw outline"))
         self.outlineCheck.SetValue(self.vPropertiesDict['color'] != 'none')
-        
-        widthText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width (pts):"))
+
+        widthText = wx.StaticText(panel, id=wx.ID_ANY, label=_("Width (pts):"))
         if fs:
-            self.widthSpin = fs.FloatSpin(panel, id = wx.ID_ANY, min_val = 0, max_val = 30,
-                                          increment = 0.5, value = 1, style = fs.FS_RIGHT)
+            self.widthSpin = fs.FloatSpin(
+                panel,
+                id=wx.ID_ANY,
+                min_val=0,
+                max_val=30,
+                increment=0.5,
+                value=1,
+                style=fs.FS_RIGHT)
             self.widthSpin.SetFormat("%f")
             self.widthSpin.SetDigits(2)
         else:
-            self.widthSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 25, initial = 1,
-                                         size = self.spinCtrlSize)
-                                        
-        if self.vPropertiesDict['color'] == None:
+            self.widthSpin = wx.SpinCtrl(
+                panel, id=wx.ID_ANY, min=1, max=25, initial=1,
+                size=self.spinCtrlSize)
+
+        if self.vPropertiesDict['color'] is None:
             self.vPropertiesDict['color'] = 'none'
- 
+
         if self.vPropertiesDict['color'] != 'none':
-            self.widthSpin.SetValue(self.vPropertiesDict['width'] )
+            self.widthSpin.SetValue(self.vPropertiesDict['width'])
         else:
             self.widthSpin.SetValue(1)
 
-        colorText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Color:"))
-        self.colorPicker = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
+        colorText = wx.StaticText(panel, id=wx.ID_ANY, label=_("Color:"))
+        self.colorPicker = wx.ColourPickerCtrl(panel, id=wx.ID_ANY)
         if self.vPropertiesDict['color'] != 'none':
-            self.colorPicker.SetColour(convertRGB(self.vPropertiesDict['color'])) 
+            self.colorPicker.SetColour(
+                convertRGB(self.vPropertiesDict['color']))
         else:
             self.colorPicker.SetColour(convertRGB('black'))
 
-        self.gridBagSizerO.Add(self.outlineCheck, pos = (0, 0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)        
-        self.gridBagSizerO.Add(widthText, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)        
-        self.gridBagSizerO.Add(self.widthSpin, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)        
-        self.gridBagSizerO.Add(colorText, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)                
-        self.gridBagSizerO.Add(self.colorPicker, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)        
-        
-        sizer.Add(self.gridBagSizerO, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+        self.gridBagSizerO.Add(
+            self.outlineCheck, pos=(
+                0, 0), span=(
+                1, 2), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerO.Add(
+            widthText, pos=(1, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerO.Add(
+            self.widthSpin, pos=(1, 2),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+        self.gridBagSizerO.Add(
+            colorText, pos=(2, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerO.Add(
+            self.colorPicker, pos=(2, 2),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+
+        sizer.Add(
+            self.gridBagSizerO,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         self.Bind(wx.EVT_CHECKBOX, self.OnOutline, self.outlineCheck)
-        
+
         #colors - fill
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Fill")) 
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Fill"))
         sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
-        self.gridBagSizerF = wx.GridBagSizer(hgap = 5, vgap = 2)
-       
-        self.fillCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("fill color"))
-        self.fillCheck.SetValue(self.vPropertiesDict['fcolor'] != 'none' or self.vPropertiesDict['rgbcolumn'] is not None)
+        self.gridBagSizerF = wx.GridBagSizer(hgap=5, vgap=2)
 
-        self.colorPickerRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("choose color:"), style = wx.RB_GROUP)
-        #set choose color option if there is no db connection
+        self.fillCheck = wx.CheckBox(
+            panel, id=wx.ID_ANY, label=_("fill color"))
+        self.fillCheck.SetValue(
+            self.vPropertiesDict['fcolor'] !=
+            'none' or self.vPropertiesDict['rgbcolumn'] is not None)
+
+        self.colorPickerRadio = wx.RadioButton(
+            panel, id=wx.ID_ANY, label=_("choose color:"), style=wx.RB_GROUP)
+        # set choose color option if there is no db connection
         if self.connection:
-            self.colorPickerRadio.SetValue(not self.vPropertiesDict['rgbcolumn'])
+            self.colorPickerRadio.SetValue(
+                not self.vPropertiesDict['rgbcolumn'])
         else:
-            self.colorPickerRadio.SetValue(False)            
-        self.fillColorPicker = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
+            self.colorPickerRadio.SetValue(False)
+        self.fillColorPicker = wx.ColourPickerCtrl(panel, id=wx.ID_ANY)
         if self.vPropertiesDict['fcolor'] != 'none':
-            self.fillColorPicker.SetColour(convertRGB(self.vPropertiesDict['fcolor'])) 
+            self.fillColorPicker.SetColour(
+                convertRGB(self.vPropertiesDict['fcolor']))
         else:
-            self.fillColorPicker.SetColour(convertRGB('red'))        
-        
-        self.colorColRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("color from map table column:"))
-        self.colorColChoice = self.getColsChoice(parent = panel)
+            self.fillColorPicker.SetColour(convertRGB('red'))
+
+        self.colorColRadio = wx.RadioButton(
+            panel, id=wx.ID_ANY, label=_("color from map table column:"))
+        self.colorColChoice = self.getColsChoice(parent=panel)
         if self.connection:
             if self.vPropertiesDict['rgbcolumn']:
                 self.colorColRadio.SetValue(True)
-                self.colorColChoice.SetStringSelection(self.vPropertiesDict['rgbcolumn'])
+                self.colorColChoice.SetStringSelection(
+                    self.vPropertiesDict['rgbcolumn'])
             else:
                 self.colorColRadio.SetValue(False)
                 self.colorColChoice.SetSelection(0)
         self.colorColChoice.Enable(self.connection)
         self.colorColRadio.Enable(self.connection)
-        
-        self.gridBagSizerF.Add(self.fillCheck, pos = (0, 0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        self.gridBagSizerF.Add(self.colorPickerRadio, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)        
-        self.gridBagSizerF.Add(self.fillColorPicker, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)        
-        self.gridBagSizerF.Add(self.colorColRadio, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)        
-        self.gridBagSizerF.Add(self.colorColChoice, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)        
-        
-        sizer.Add(self.gridBagSizerF, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
 
+        self.gridBagSizerF.Add(
+            self.fillCheck, pos=(
+                0, 0), span=(
+                1, 2), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerF.Add(
+            self.colorPickerRadio, pos=(1, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerF.Add(
+            self.fillColorPicker, pos=(1, 2),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerF.Add(
+            self.colorColRadio, pos=(2, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerF.Add(
+            self.colorColChoice, pos=(2, 2),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+
+        sizer.Add(
+            self.gridBagSizerF,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         self.Bind(wx.EVT_CHECKBOX, self.OnFill, self.fillCheck)
         self.Bind(wx.EVT_RADIOBUTTON, self.OnColor, self.colorColRadio)
         self.Bind(wx.EVT_RADIOBUTTON, self.OnColor, self.colorPickerRadio)
-        
+
         panel.SetSizer(border)
         panel.Fit()
         return panel
-    
+
     def _ColorsLinePanel(self, notebook):
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
-        notebook.AddPage(page = panel, text = _("Colors"))
-        
+        panel = wx.Panel(
+            parent=notebook, id=wx.ID_ANY, size=(-1, -1),
+            style=wx.TAB_TRAVERSAL)
+        notebook.AddPage(page=panel, text=_("Colors"))
+
         border = wx.BoxSizer(wx.VERTICAL)
-        
+
         #colors - outline
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Outline"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Outline"))
         sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
-        self.gridBagSizerO = wx.GridBagSizer(hgap = 5, vgap = 2)
-        
-        if self.vPropertiesDict['hcolor'] == None:
+        self.gridBagSizerO = wx.GridBagSizer(hgap=5, vgap=2)
+
+        if self.vPropertiesDict['hcolor'] is None:
             self.vPropertiesDict['hcolor'] = 'none'
-        if self.vPropertiesDict['color'] == None:
+        if self.vPropertiesDict['color'] is None:
             self.vPropertiesDict['color'] = 'none'
-        
-        self.outlineCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("draw outline"))
+
+        self.outlineCheck = wx.CheckBox(
+            panel, id=wx.ID_ANY, label=_("draw outline"))
         self.outlineCheck.SetValue(self.vPropertiesDict['hcolor'] != 'none')
-        self.outlineCheck.SetToolTipString(_("No effect for fill color from table column"))
-        
-        widthText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width (pts):"))
-        
+        self.outlineCheck.SetToolTipString(
+            _("No effect for fill color from table column"))
+
+        widthText = wx.StaticText(panel, id=wx.ID_ANY, label=_("Width (pts):"))
+
         if fs:
-            self.outWidthSpin = fs.FloatSpin(panel, id = wx.ID_ANY, min_val = 0, max_val = 30,
-                                             increment = 0.5, value = 1, style = fs.FS_RIGHT)
+            self.outWidthSpin = fs.FloatSpin(
+                panel,
+                id=wx.ID_ANY,
+                min_val=0,
+                max_val=30,
+                increment=0.5,
+                value=1,
+                style=fs.FS_RIGHT)
             self.outWidthSpin.SetFormat("%f")
             self.outWidthSpin.SetDigits(1)
         else:
-            self.outWidthSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 30, initial = 1,
-                                         size = self.spinCtrlSize)
-        
+            self.outWidthSpin = wx.SpinCtrl(
+                panel, id=wx.ID_ANY, min=1, max=30, initial=1,
+                size=self.spinCtrlSize)
+
         if self.vPropertiesDict['hcolor'] != 'none':
-            self.outWidthSpin.SetValue(self.vPropertiesDict['hwidth'] )
+            self.outWidthSpin.SetValue(self.vPropertiesDict['hwidth'])
         else:
             self.outWidthSpin.SetValue(1)
 
-        colorText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Color:"))
-        self.colorPicker = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
+        colorText = wx.StaticText(panel, id=wx.ID_ANY, label=_("Color:"))
+        self.colorPicker = wx.ColourPickerCtrl(panel, id=wx.ID_ANY)
         if self.vPropertiesDict['hcolor'] != 'none':
-            self.colorPicker.SetColour(convertRGB(self.vPropertiesDict['hcolor']) )
+            self.colorPicker.SetColour(
+                convertRGB(self.vPropertiesDict['hcolor']))
         else:
             self.colorPicker.SetColour(convertRGB('black'))
 
-        
-        self.gridBagSizerO.Add(self.outlineCheck, pos = (0, 0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)        
-        self.gridBagSizerO.Add(widthText, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)        
-        self.gridBagSizerO.Add(self.outWidthSpin, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)        
-        self.gridBagSizerO.Add(colorText, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)                
-        self.gridBagSizerO.Add(self.colorPicker, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)        
-        
-        sizer.Add(self.gridBagSizerO, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+        self.gridBagSizerO.Add(
+            self.outlineCheck, pos=(
+                0, 0), span=(
+                1, 2), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerO.Add(
+            widthText, pos=(1, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerO.Add(
+            self.outWidthSpin, pos=(1, 2),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+        self.gridBagSizerO.Add(
+            colorText, pos=(2, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerO.Add(
+            self.colorPicker, pos=(2, 2),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+
+        sizer.Add(
+            self.gridBagSizerO,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         self.Bind(wx.EVT_CHECKBOX, self.OnOutline, self.outlineCheck)
-        
+
         #colors - fill
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Fill"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Fill"))
         sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
-        self.gridBagSizerF = wx.GridBagSizer(hgap = 5, vgap = 2)
-       
-        fillText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Color of lines:"))
+        self.gridBagSizerF = wx.GridBagSizer(hgap=5, vgap=2)
 
-        self.colorPickerRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("choose color:"), style = wx.RB_GROUP)
+        fillText = wx.StaticText(
+            panel, id=wx.ID_ANY, label=_("Color of lines:"))
 
-        #set choose color option if there is no db connection
+        self.colorPickerRadio = wx.RadioButton(
+            panel, id=wx.ID_ANY, label=_("choose color:"), style=wx.RB_GROUP)
+
+        # set choose color option if there is no db connection
         if self.connection:
-            self.colorPickerRadio.SetValue(not self.vPropertiesDict['rgbcolumn'])
+            self.colorPickerRadio.SetValue(
+                not self.vPropertiesDict['rgbcolumn'])
         else:
-            self.colorPickerRadio.SetValue(False)            
-        self.fillColorPicker = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
+            self.colorPickerRadio.SetValue(False)
+        self.fillColorPicker = wx.ColourPickerCtrl(panel, id=wx.ID_ANY)
         if self.vPropertiesDict['color'] != 'none':
-            self.fillColorPicker.SetColour(convertRGB(self.vPropertiesDict['color']) )
+            self.fillColorPicker.SetColour(
+                convertRGB(self.vPropertiesDict['color']))
         else:
             self.fillColorPicker.SetColour(convertRGB('black'))
-        
-        self.colorColRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("color from map table column:"))
-        self.colorColChoice = self.getColsChoice(parent = panel)
+
+        self.colorColRadio = wx.RadioButton(
+            panel, id=wx.ID_ANY, label=_("color from map table column:"))
+        self.colorColChoice = self.getColsChoice(parent=panel)
         if self.connection:
             if self.vPropertiesDict['rgbcolumn']:
                 self.colorColRadio.SetValue(True)
-                self.colorColChoice.SetStringSelection(self.vPropertiesDict['rgbcolumn'])
+                self.colorColChoice.SetStringSelection(
+                    self.vPropertiesDict['rgbcolumn'])
             else:
                 self.colorColRadio.SetValue(False)
                 self.colorColChoice.SetSelection(0)
         self.colorColChoice.Enable(self.connection)
         self.colorColRadio.Enable(self.connection)
-        
-        self.gridBagSizerF.Add(fillText, pos = (0, 0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        self.gridBagSizerF.Add(self.colorPickerRadio, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)        
-        self.gridBagSizerF.Add(self.fillColorPicker, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)        
-        self.gridBagSizerF.Add(self.colorColRadio, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)        
-        self.gridBagSizerF.Add(self.colorColChoice, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)        
-        
-        sizer.Add(self.gridBagSizerF, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
 
+        self.gridBagSizerF.Add(
+            fillText, pos=(
+                0, 0), span=(
+                1, 2), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerF.Add(
+            self.colorPickerRadio, pos=(1, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerF.Add(
+            self.fillColorPicker, pos=(1, 2),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerF.Add(
+            self.colorColRadio, pos=(2, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        self.gridBagSizerF.Add(
+            self.colorColChoice, pos=(2, 2),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+
+        sizer.Add(
+            self.gridBagSizerF,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         self.Bind(wx.EVT_RADIOBUTTON, self.OnColor, self.colorColRadio)
         self.Bind(wx.EVT_RADIOBUTTON, self.OnColor, self.colorPickerRadio)
 
         panel.SetSizer(border)
         panel.Fit()
         return panel
-    
+
     def _StylePointPanel(self, notebook):
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
-        notebook.AddPage(page = panel, text = _("Size and style"))
-        
+        panel = wx.Panel(
+            parent=notebook, id=wx.ID_ANY, size=(-1, -1),
+            style=wx.TAB_TRAVERSAL)
+        notebook.AddPage(page=panel, text=_("Size and style"))
+
         border = wx.BoxSizer(wx.VERTICAL)
-        
-        #symbology
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Symbology"))        
+
+        # symbology
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Symbology"))
         sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
-        gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
-    
-        self.symbolRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("symbol:"), style = wx.RB_GROUP)
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
+
+        self.symbolRadio = wx.RadioButton(
+            panel, id=wx.ID_ANY, label=_("symbol:"),
+            style=wx.RB_GROUP)
         self.symbolRadio.SetValue(bool(self.vPropertiesDict['symbol']))
-            
-        self.symbolName = wx.StaticText(panel, id = wx.ID_ANY)
+
+        self.symbolName = wx.StaticText(panel, id=wx.ID_ANY)
         self.symbolName.SetLabel(self.vPropertiesDict['symbol'])
-        bitmap = wx.Bitmap(os.path.join(globalvar.SYMBDIR,
-                                        self.vPropertiesDict['symbol']) + '.png')
-        self.symbolButton = wx.BitmapButton(panel, id = wx.ID_ANY, bitmap = bitmap)
-            
-        self.epsRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("eps file:"))
+        bitmap = wx.Bitmap(
+            os.path.join(
+                globalvar.SYMBDIR,
+                self.vPropertiesDict['symbol']) +
+            '.png')
+        self.symbolButton = wx.BitmapButton(panel, id=wx.ID_ANY, bitmap=bitmap)
+
+        self.epsRadio = wx.RadioButton(
+            panel, id=wx.ID_ANY, label=_("eps file:"))
         self.epsRadio.SetValue(bool(self.vPropertiesDict['eps']))
-        
-        self.epsFileCtrl = filebrowse.FileBrowseButton(panel, id = wx.ID_ANY, labelText = '',
-                                buttonText =  _("Browse"), toolTip = _("Type filename or click browse to choose file"), 
-                                dialogTitle = _("Choose a file"), startDirectory = '', initialValue = '',
-                                fileMask = "Encapsulated PostScript (*.eps)|*.eps|All files (*.*)|*.*", fileMode = wx.FD_OPEN)
+
+        self.epsFileCtrl = filebrowse.FileBrowseButton(
+            panel, id=wx.ID_ANY, labelText='', buttonText=_("Browse"),
+            toolTip=_("Type filename or click browse to choose file"),
+            dialogTitle=_("Choose a file"),
+            startDirectory='', initialValue='',
+            fileMask="Encapsulated PostScript (*.eps)|*.eps|All files (*.*)|*.*",
+            fileMode=wx.FD_OPEN)
         if not self.vPropertiesDict['eps']:
             self.epsFileCtrl.SetValue('')
-        else: #eps chosen
+        else:  # eps chosen
             self.epsFileCtrl.SetValue(self.vPropertiesDict['eps'])
-            
-        gridBagSizer.Add(self.symbolRadio, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.symbolName, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT, border = 10)
-        gridBagSizer.Add(self.symbolButton, pos = (0, 2), flag = wx.ALIGN_RIGHT , border = 0)
-        gridBagSizer.Add(self.epsRadio, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.epsFileCtrl, pos = (1, 1), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        
+
+        gridBagSizer.Add(
+            self.symbolRadio, pos=(0, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.symbolName,
+            pos=(
+                0,
+                1),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
+            border=10)
+        gridBagSizer.Add(
+            self.symbolButton, pos=(0, 2),
+            flag=wx.ALIGN_RIGHT, border=0)
+        gridBagSizer.Add(
+            self.epsRadio, pos=(1, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.epsFileCtrl, pos=(
+                1, 1), span=(
+                1, 2), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+
         gridBagSizer.AddGrowableCol(1)
         gridBagSizer.AddGrowableCol(2)
-        sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+        sizer.Add(
+            gridBagSizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         self.Bind(wx.EVT_BUTTON, self.OnSymbolSelection, self.symbolButton)
         self.Bind(wx.EVT_RADIOBUTTON, self.OnSymbology, self.symbolRadio)
         self.Bind(wx.EVT_RADIOBUTTON, self.OnSymbology, self.epsRadio)
-        
-        #size
-        
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Size"))
+
+        # size
+
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Size"))
         sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
-        gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
-        
-        self.sizeRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("size:"), style = wx.RB_GROUP)
-        self.sizeSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 50, initial = 1)
-        self.sizecolumnRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("size from map table column:"))
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
+
+        self.sizeRadio = wx.RadioButton(
+            panel, id=wx.ID_ANY, label=_("size:"),
+            style=wx.RB_GROUP)
+        self.sizeSpin = wx.SpinCtrl(
+            panel, id=wx.ID_ANY, min=1, max=50, initial=1)
+        self.sizecolumnRadio = wx.RadioButton(
+            panel, id=wx.ID_ANY, label=_("size from map table column:"))
         self.sizeColChoice = self.getColsChoice(panel)
-        self.scaleText = wx.StaticText(panel, id = wx.ID_ANY, label = _("scale:"))
-        self.scaleSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 25, initial = 1)
-        
+        self.scaleText = wx.StaticText(panel, id=wx.ID_ANY, label=_("scale:"))
+        self.scaleSpin = wx.SpinCtrl(
+            panel, id=wx.ID_ANY, min=1, max=25, initial=1)
+
         self.sizeRadio.SetValue(self.vPropertiesDict['size'] is not None)
         self.sizecolumnRadio.SetValue(bool(self.vPropertiesDict['sizecolumn']))
         if self.vPropertiesDict['size']:
             self.sizeSpin.SetValue(self.vPropertiesDict['size'])
-        else: self.sizeSpin.SetValue(5)
+        else:
+            self.sizeSpin.SetValue(5)
         if self.vPropertiesDict['sizecolumn']:
             self.scaleSpin.SetValue(self.vPropertiesDict['scale'])
-            self.sizeColChoice.SetStringSelection(self.vPropertiesDict['sizecolumn'])
+            self.sizeColChoice.SetStringSelection(
+                self.vPropertiesDict['sizecolumn'])
         else:
             self.scaleSpin.SetValue(1)
             self.sizeColChoice.SetSelection(0)
-        if not self.connection:   
-            for each in (self.sizecolumnRadio, self.sizeColChoice, self.scaleSpin, self.scaleText):
+        if not self.connection:
+            for each in (self.sizecolumnRadio, self.sizeColChoice,
+                         self.scaleSpin, self.scaleText):
                 each.Disable()
-            
-        gridBagSizer.Add(self.sizeRadio, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.sizeSpin, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.sizecolumnRadio, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.sizeColChoice, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        gridBagSizer.Add(self.scaleText, pos = (2, 0), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
-        gridBagSizer.Add(self.scaleSpin, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        
+
+        gridBagSizer.Add(
+            self.sizeRadio, pos=(0, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.sizeSpin, pos=(0, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.sizecolumnRadio, pos=(1, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.sizeColChoice,
+            pos=(
+                1,
+                1),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+            border=0)
+        gridBagSizer.Add(
+            self.scaleText,
+            pos=(
+                2,
+                0),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT,
+            border=0)
+        gridBagSizer.Add(
+            self.scaleSpin, pos=(2, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+
         gridBagSizer.AddGrowableCol(0)
-        sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+        sizer.Add(
+            gridBagSizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         self.Bind(wx.EVT_RADIOBUTTON, self.OnSize, self.sizeRadio)
         self.Bind(wx.EVT_RADIOBUTTON, self.OnSize, self.sizecolumnRadio)
-        
-        #rotation
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Rotation"))
+
+        # rotation
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Rotation"))
         sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
-        gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
 
-        
-        self.rotateCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("rotate symbols:"))
-        self.rotateRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("counterclockwise in degrees:"), style = wx.RB_GROUP)
-        self.rotateSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 0, max = 360, initial = 0)
-        self.rotatecolumnRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("from map table column:"))
+        self.rotateCheck = wx.CheckBox(
+            panel, id=wx.ID_ANY, label=_("rotate symbols:"))
+        self.rotateRadio = wx.RadioButton(panel, id=wx.ID_ANY, label=_(
+            "counterclockwise in degrees:"), style=wx.RB_GROUP)
+        self.rotateSpin = wx.SpinCtrl(
+            panel, id=wx.ID_ANY, min=0, max=360, initial=0)
+        self.rotatecolumnRadio = wx.RadioButton(
+            panel, id=wx.ID_ANY, label=_("from map table column:"))
         self.rotateColChoice = self.getColsChoice(panel)
-        
+
         self.rotateCheck.SetValue(self.vPropertiesDict['rotation'])
         self.rotateRadio.SetValue(self.vPropertiesDict['rotate'] is not None)
-        self.rotatecolumnRadio.SetValue(bool(self.vPropertiesDict['rotatecolumn']))
+        self.rotatecolumnRadio.SetValue(
+            bool(self.vPropertiesDict['rotatecolumn']))
         if self.vPropertiesDict['rotate']:
             self.rotateSpin.SetValue(self.vPropertiesDict['rotate'])
         else:
             self.rotateSpin.SetValue(0)
         if self.vPropertiesDict['rotatecolumn']:
-            self.rotateColChoice.SetStringSelection(self.vPropertiesDict['rotatecolumn'])
+            self.rotateColChoice.SetStringSelection(
+                self.vPropertiesDict['rotatecolumn'])
         else:
             self.rotateColChoice.SetSelection(0)
-            
-        gridBagSizer.Add(self.rotateCheck, pos = (0, 0), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.rotateRadio, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.rotateSpin, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.rotatecolumnRadio, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.rotateColChoice, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        
+
+        gridBagSizer.Add(
+            self.rotateCheck, pos=(
+                0, 0), span=(
+                1, 2), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.rotateRadio, pos=(1, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.rotateSpin, pos=(1, 2),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.rotatecolumnRadio, pos=(2, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.rotateColChoice,
+            pos=(
+                2,
+                2),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+            border=0)
+
         gridBagSizer.AddGrowableCol(1)
-        sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+        sizer.Add(
+            gridBagSizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         self.Bind(wx.EVT_CHECKBOX, self.OnRotation, self.rotateCheck)
         self.Bind(wx.EVT_RADIOBUTTON, self.OnRotationType, self.rotateRadio)
-        self.Bind(wx.EVT_RADIOBUTTON, self.OnRotationType, self.rotatecolumnRadio)
-        
+        self.Bind(
+            wx.EVT_RADIOBUTTON,
+            self.OnRotationType,
+            self.rotatecolumnRadio)
+
         panel.SetSizer(border)
         panel.Fit()
         return panel
-    
+
     def _StyleLinePanel(self, notebook):
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
-        notebook.AddPage(page = panel, text = _("Size and style"))
-        
+        panel = wx.Panel(
+            parent=notebook, id=wx.ID_ANY, size=(-1, -1),
+            style=wx.TAB_TRAVERSAL)
+        notebook.AddPage(page=panel, text=_("Size and style"))
+
         border = wx.BoxSizer(wx.VERTICAL)
-        
-        #width
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Width"))       
+
+        # width
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Width"))
         sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
-        gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
-        
-        widthText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Set width (pts):"))
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
+
+        widthText = wx.StaticText(
+            panel, id=wx.ID_ANY, label=_("Set width (pts):"))
         if fs:
-            self.widthSpin = fs.FloatSpin(panel, id = wx.ID_ANY, min_val = 0, max_val = 30,
-                                        increment = 0.5, value = 1, style = fs.FS_RIGHT)
+            self.widthSpin = fs.FloatSpin(
+                panel,
+                id=wx.ID_ANY,
+                min_val=0,
+                max_val=30,
+                increment=0.5,
+                value=1,
+                style=fs.FS_RIGHT)
             self.widthSpin.SetFormat("%f")
             self.widthSpin.SetDigits(1)
         else:
-            self.widthSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 30, initial = 1)
-            
-        self.cwidthCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("multiply width by category value"))
-        
+            self.widthSpin = wx.SpinCtrl(
+                panel, id=wx.ID_ANY, min=1, max=30, initial=1)
+
+        self.cwidthCheck = wx.CheckBox(
+            panel, id=wx.ID_ANY, label=_("multiply width by category value"))
+
         if self.vPropertiesDict['width']:
             self.widthSpin.SetValue(self.vPropertiesDict['width'])
             self.cwidthCheck.SetValue(False)
         else:
             self.widthSpin.SetValue(self.vPropertiesDict['cwidth'])
             self.cwidthCheck.SetValue(True)
-        
-        gridBagSizer.Add(widthText, pos = (0, 0),  flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.widthSpin, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.cwidthCheck, pos = (1, 0), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        
-        sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
-        #style
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Line style"))
+
+        gridBagSizer.Add(
+            widthText, pos=(0, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.widthSpin, pos=(0, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.cwidthCheck, pos=(
+                1, 0), span=(
+                1, 2), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+
+        sizer.Add(
+            gridBagSizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
+        # style
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Line style"))
         sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
-        gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
-        
-        styleText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Choose line style:"))
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
+
+        styleText = wx.StaticText(
+            panel, id=wx.ID_ANY, label=_("Choose line style:"))
         penStyles = ["solid", "dashed", "dotted", "dashdotted"]
-        self.styleCombo = PenStyleComboBox(panel, choices = penStyles, validator = TCValidator(flag = 'ZERO_AND_ONE_ONLY'))
-##        self.styleCombo = wx.ComboBox(panel, id = wx.ID_ANY,
+        self.styleCombo = PenStyleComboBox(
+            panel, choices=penStyles, validator=TCValidator(
+                flag='ZERO_AND_ONE_ONLY'))
+# self.styleCombo = wx.ComboBox(panel, id = wx.ID_ANY,
 ##                            choices = ["solid", "dashed", "dotted", "dashdotted"],
-##                            validator = TCValidator(flag = 'ZERO_AND_ONE_ONLY'))
-##        self.styleCombo.SetToolTipString(_("It's possible to enter a series of 0's and 1's too. "\
+# validator = TCValidator(flag = 'ZERO_AND_ONE_ONLY'))
+# self.styleCombo.SetToolTipString(_("It's possible to enter a series of 0's and 1's too. "\
 ##                                    "The first block of repeated zeros or ones represents 'draw', "\
 ##                                    "the second block represents 'blank'. An even number of blocks "\
-##                                    "will repeat the pattern, an odd number of blocks will alternate the pattern."))
-        linecapText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Choose linecap:"))
-        self.linecapChoice = wx.Choice(panel, id = wx.ID_ANY, choices = ["butt", "round", "extended_butt"])
-        
+# "will repeat the pattern, an odd number of blocks will alternate the pattern."))
+        linecapText = wx.StaticText(
+            panel, id=wx.ID_ANY, label=_("Choose linecap:"))
+        self.linecapChoice = wx.Choice(
+            panel, id=wx.ID_ANY, choices=[
+                "butt", "round", "extended_butt"])
+
         self.styleCombo.SetValue(self.vPropertiesDict['style'])
         self.linecapChoice.SetStringSelection(self.vPropertiesDict['linecap'])
-        
-        gridBagSizer.Add(styleText, pos = (0, 0),  flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.styleCombo, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        gridBagSizer.Add(linecapText, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.linecapChoice, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        
-        sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+
+        gridBagSizer.Add(
+            styleText, pos=(0, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.styleCombo,
+            pos=(
+                0,
+                1),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+            border=0)
+        gridBagSizer.Add(
+            linecapText, pos=(1, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.linecapChoice,
+            pos=(
+                1,
+                1),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+            border=0)
+
+        sizer.Add(
+            gridBagSizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         panel.SetSizer(border)
         panel.Fit()
         return panel
-        
+
     def _StyleAreaPanel(self, notebook):
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
-        notebook.AddPage(page = panel, text = _("Size and style"))
-        
+        panel = wx.Panel(
+            parent=notebook, id=wx.ID_ANY, size=(-1, -1),
+            style=wx.TAB_TRAVERSAL)
+        notebook.AddPage(page=panel, text=_("Size and style"))
+
         border = wx.BoxSizer(wx.VERTICAL)
-        
-        #pattern
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Pattern"))
+
+        # pattern
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Pattern"))
         sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
-        gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
-        
-        self.patternCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("use pattern:"))
-        self.patFileCtrl = filebrowse.FileBrowseButton(panel, id = wx.ID_ANY, labelText = _("Choose pattern file:"),
-                                buttonText =  _("Browse"), toolTip = _("Type filename or click browse to choose file"), 
-                                dialogTitle = _("Choose a file"), startDirectory = self.patternPath, initialValue = '',
-                                fileMask = "Encapsulated PostScript (*.eps)|*.eps|All files (*.*)|*.*", fileMode = wx.FD_OPEN)
-        self.patWidthText = wx.StaticText(panel, id = wx.ID_ANY, label = _("pattern line width (pts):"))
-        self.patWidthSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 25, initial = 1)
-        self.patScaleText = wx.StaticText(panel, id = wx.ID_ANY, label = _("pattern scale factor:"))
-        self.patScaleSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 25, initial = 1)
-        
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
+
+        self.patternCheck = wx.CheckBox(
+            panel, id=wx.ID_ANY, label=_("use pattern:"))
+        self.patFileCtrl = filebrowse.FileBrowseButton(
+            panel, id=wx.ID_ANY, labelText=_("Choose pattern file:"),
+            buttonText=_("Browse"),
+            toolTip=_("Type filename or click browse to choose file"),
+            dialogTitle=_("Choose a file"),
+            startDirectory=self.patternPath, initialValue='',
+            fileMask="Encapsulated PostScript (*.eps)|*.eps|All files (*.*)|*.*",
+            fileMode=wx.FD_OPEN)
+        self.patWidthText = wx.StaticText(
+            panel, id=wx.ID_ANY, label=_("pattern line width (pts):"))
+        self.patWidthSpin = wx.SpinCtrl(
+            panel, id=wx.ID_ANY, min=1, max=25, initial=1)
+        self.patScaleText = wx.StaticText(
+            panel, id=wx.ID_ANY, label=_("pattern scale factor:"))
+        self.patScaleSpin = wx.SpinCtrl(
+            panel, id=wx.ID_ANY, min=1, max=25, initial=1)
+
         self.patternCheck.SetValue(bool(self.vPropertiesDict['pat']))
         if self.patternCheck.GetValue():
             self.patFileCtrl.SetValue(self.vPropertiesDict['pat'])
             self.patWidthSpin.SetValue(self.vPropertiesDict['pwidth'])
             self.patScaleSpin.SetValue(self.vPropertiesDict['scale'])
-        
-        gridBagSizer.Add(self.patternCheck, pos = (0, 0),  flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.patFileCtrl, pos = (1, 0), span = (1, 2),flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        gridBagSizer.Add(self.patWidthText, pos = (2, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.patWidthSpin, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.patScaleText, pos = (3, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.patScaleSpin, pos = (3, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        
-        
+
+        gridBagSizer.Add(
+            self.patternCheck, pos=(0, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.patFileCtrl, pos=(
+                1, 0), span=(
+                1, 2), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+        gridBagSizer.Add(
+            self.patWidthText, pos=(2, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.patWidthSpin, pos=(2, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.patScaleText, pos=(3, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.patScaleSpin, pos=(3, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+
         gridBagSizer.AddGrowableCol(1)
-        sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+        sizer.Add(
+            gridBagSizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         self.Bind(wx.EVT_CHECKBOX, self.OnPattern, self.patternCheck)
-        
+
         panel.SetSizer(border)
         panel.Fit()
         return panel
@@ -2189,7 +3065,8 @@
             return
         self.currLayer = self.layerChoice.GetStringSelection()
         if self.connection:
-            cols = self.mapDBInfo.GetColumns(self.mapDBInfo.layers[int(self.currLayer)]['table']) 
+            cols = self.mapDBInfo.GetColumns(
+                self.mapDBInfo.layers[int(self.currLayer)]['table'])
         else:
             cols = []
 
@@ -2199,15 +3076,15 @@
         if self.type in ('points', 'lines'):
             self.colorColChoice.SetItems(cols)
             self.colorColChoice.SetSelection(0)
-            
+
     def OnOutline(self, event):
         for widget in self.gridBagSizerO.GetChildren():
             if widget.GetWindow() != self.outlineCheck:
                 widget.GetWindow().Enable(self.outlineCheck.GetValue())
-                
+
     def OnFill(self, event):
         enable = self.fillCheck.GetValue()
-        
+
         self.colorColChoice.Enable(enable)
         self.colorColRadio.Enable(enable)
         self.fillColorPicker.Enable(enable)
@@ -2217,68 +3094,71 @@
         if not self.connection:
             self.colorColChoice.Disable()
             self.colorColRadio.Disable()
-            
+
     def OnColor(self, event):
         self.colorColChoice.Enable(self.colorColRadio.GetValue())
         self.fillColorPicker.Enable(self.colorPickerRadio.GetValue())
-            
+
     def OnSize(self, event):
         self.sizeSpin.Enable(self.sizeRadio.GetValue())
         self.sizeColChoice.Enable(self.sizecolumnRadio.GetValue())
         self.scaleText.Enable(self.sizecolumnRadio.GetValue())
         self.scaleSpin.Enable(self.sizecolumnRadio.GetValue())
-        
+
     def OnRotation(self, event):
-        for each in (self.rotateRadio, self.rotatecolumnRadio, self.rotateColChoice, self.rotateSpin):
+        for each in (self.rotateRadio, self.rotatecolumnRadio,
+                     self.rotateColChoice, self.rotateSpin):
             if self.rotateCheck.GetValue():
                 each.Enable()
-                self.OnRotationType(event = None)     
+                self.OnRotationType(event=None)
             else:
                 each.Disable()
-           
+
     def OnRotationType(self, event):
         self.rotateSpin.Enable(self.rotateRadio.GetValue())
         self.rotateColChoice.Enable(self.rotatecolumnRadio.GetValue())
-        
+
     def OnPattern(self, event):
-        for each in (self.patFileCtrl, self.patWidthText, self.patWidthSpin, self.patScaleText, self.patScaleSpin):
+        for each in (self.patFileCtrl, self.patWidthText,
+                     self.patWidthSpin, self.patScaleText, self.patScaleSpin):
             each.Enable(self.patternCheck.GetValue())
-            
+
     def OnSymbology(self, event):
         useSymbol = self.symbolRadio.GetValue()
-        
+
         self.symbolButton.Enable(useSymbol)
         self.symbolName.Enable(useSymbol)
         self.epsFileCtrl.Enable(not useSymbol)
-            
+
     def OnSymbolSelection(self, event):
-        dlg = SymbolDialog(self, symbolPath = globalvar.SYMBDIR,
-                           currentSymbol = self.symbolName.GetLabel())
+        dlg = SymbolDialog(self, symbolPath=globalvar.SYMBDIR,
+                           currentSymbol=self.symbolName.GetLabel())
         if dlg.ShowModal() == wx.ID_OK:
             img = dlg.GetSelectedSymbolPath()
             name = dlg.GetSelectedSymbolName()
             self.symbolButton.SetBitmapLabel(wx.Bitmap(img + '.png'))
             self.symbolName.SetLabel(name)
-            
+
         dlg.Destroy()
-                
-    def EnableLayerSelection(self, enable = True):
+
+    def EnableLayerSelection(self, enable=True):
         for widget in self.gridBagSizerL.GetChildren():
             if widget.GetWindow() != self.warning:
                 widget.GetWindow().Enable(enable)
-                
+
     def getColsChoice(self, parent):
         """Returns a wx.Choice with table columns"""
         if self.connection:
-            cols = self.mapDBInfo.GetColumns(self.mapDBInfo.layers[int(self.currLayer)]['table']) 
+            cols = self.mapDBInfo.GetColumns(
+                self.mapDBInfo.layers[int(self.currLayer)]['table'])
         else:
             cols = []
 
-        choice = wx.Choice(parent = parent, id = wx.ID_ANY, choices = cols)
+        choice = wx.Choice(parent=parent, id=wx.ID_ANY, choices=cols)
         return choice
-        
+
     def update(self):
-        #feature type
+        # feature type
         if self.type in ('lines', 'points'):
             featureType = None
             if self.checkType1.GetValue():
@@ -2289,77 +3169,88 @@
                 featureType = self.checkType2.GetName()
             if featureType:
                 self.vPropertiesDict['type'] = featureType
-            
+
         # is connection
         self.vPropertiesDict['connection'] = self.connection
         if self.connection:
-            self.vPropertiesDict['layer'] = self.layerChoice.GetStringSelection()
+            self.vPropertiesDict[
+                'layer'] = self.layerChoice.GetStringSelection()
             if self.radioCats.GetValue() and not self.textCtrlCats.IsEmpty():
                 self.vPropertiesDict['cats'] = self.textCtrlCats.GetValue()
             elif self.radioWhere.GetValue() and not self.textCtrlWhere.IsEmpty():
-                self.vPropertiesDict['where'] = self.choiceColumns.GetStringSelection() + " " \
-                                                                + self.textCtrlWhere.GetValue()
-        #mask
+                self.vPropertiesDict['where'] = self.choiceColumns.GetStringSelection(
+                ) + " " + self.textCtrlWhere.GetValue()
+        # mask
         if self.mask.GetValue():
-            self.vPropertiesDict['masked'] = 'y' 
+            self.vPropertiesDict['masked'] = 'y'
         else:
             self.vPropertiesDict['masked'] = 'n'
 
-        #colors
+        # colors
         if self.type in ('points', 'areas'):
             if self.outlineCheck.GetValue():
-                self.vPropertiesDict['color'] = convertRGB(self.colorPicker.GetColour())
+                self.vPropertiesDict['color'] = convertRGB(
+                    self.colorPicker.GetColour())
                 self.vPropertiesDict['width'] = self.widthSpin.GetValue()
             else:
                 self.vPropertiesDict['color'] = 'none'
-                
+
             if self.fillCheck.GetValue():
                 if self.colorPickerRadio.GetValue():
-                    self.vPropertiesDict['fcolor'] = convertRGB(self.fillColorPicker.GetColour())
+                    self.vPropertiesDict['fcolor'] = convertRGB(
+                        self.fillColorPicker.GetColour())
                     self.vPropertiesDict['rgbcolumn'] = None
                 if self.colorColRadio.GetValue():
-                    self.vPropertiesDict['fcolor'] = 'none'# this color is taken in case of no record in rgb column
-                    self.vPropertiesDict['rgbcolumn'] = self.colorColChoice.GetStringSelection()
+                    # this color is taken in case of no record in rgb column
+                    self.vPropertiesDict['fcolor'] = 'none'
+                    self.vPropertiesDict[
+                        'rgbcolumn'] = self.colorColChoice.GetStringSelection()
             else:
-                self.vPropertiesDict['fcolor'] = 'none'    
-                
+                self.vPropertiesDict['fcolor'] = 'none'
+
         if self.type == 'lines':
-                #hcolor only when no rgbcolumn
-            if self.outlineCheck.GetValue():# and self.fillCheck.GetValue() and self.colorColRadio.GetValue():
-                self.vPropertiesDict['hcolor'] = convertRGB(self.colorPicker.GetColour())
+                # hcolor only when no rgbcolumn
+            # and self.fillCheck.GetValue() and self.colorColRadio.GetValue():
+            if self.outlineCheck.GetValue():
+                self.vPropertiesDict['hcolor'] = convertRGB(
+                    self.colorPicker.GetColour())
                 self.vPropertiesDict['hwidth'] = self.outWidthSpin.GetValue()
-                
+
             else:
                 self.vPropertiesDict['hcolor'] = 'none'
-                
+
             if self.colorPickerRadio.GetValue():
-                self.vPropertiesDict['color'] = convertRGB(self.fillColorPicker.GetColour())
+                self.vPropertiesDict['color'] = convertRGB(
+                    self.fillColorPicker.GetColour())
                 self.vPropertiesDict['rgbcolumn'] = None
             if self.colorColRadio.GetValue():
-                self.vPropertiesDict['color'] = 'none'# this color is taken in case of no record in rgb column
-                self.vPropertiesDict['rgbcolumn'] = self.colorColChoice.GetStringSelection()
+                # this color is taken in case of no record in rgb column
+                self.vPropertiesDict['color'] = 'none'
+                self.vPropertiesDict[
+                    'rgbcolumn'] = self.colorColChoice.GetStringSelection()
         #
         #size and style
         #
-        
+
         if self.type == 'points':
-            #symbols
+            # symbols
             if self.symbolRadio.GetValue():
                 self.vPropertiesDict['symbol'] = self.symbolName.GetLabel()
                 self.vPropertiesDict['eps'] = None
             else:
                 self.vPropertiesDict['eps'] = self.epsFileCtrl.GetValue()
-            #size
+            # size
             if self.sizeRadio.GetValue():
                 self.vPropertiesDict['size'] = self.sizeSpin.GetValue()
                 self.vPropertiesDict['sizecolumn'] = None
                 self.vPropertiesDict['scale'] = None
             else:
-                self.vPropertiesDict['sizecolumn'] = self.sizeColChoice.GetStringSelection()
+                self.vPropertiesDict[
+                    'sizecolumn'] = self.sizeColChoice.GetStringSelection()
                 self.vPropertiesDict['scale'] = self.scaleSpin.GetValue()
                 self.vPropertiesDict['size'] = None
-            
-            #rotation
+
+            # rotation
             self.vPropertiesDict['rotate'] = None
             self.vPropertiesDict['rotatecolumn'] = None
             self.vPropertiesDict['rotation'] = False
@@ -2368,62 +3259,71 @@
             if self.rotateRadio.GetValue():
                 self.vPropertiesDict['rotate'] = self.rotateSpin.GetValue()
             else:
-                self.vPropertiesDict['rotatecolumn'] = self.rotateColChoice.GetStringSelection()
-                
+                self.vPropertiesDict[
+                    'rotatecolumn'] = self.rotateColChoice.GetStringSelection()
+
         if self.type == 'areas':
-            #pattern
-            self.vPropertiesDict['pat'] = None 
+            # pattern
+            self.vPropertiesDict['pat'] = None
             if self.patternCheck.GetValue() and bool(self.patFileCtrl.GetValue()):
                 self.vPropertiesDict['pat'] = self.patFileCtrl.GetValue()
                 self.vPropertiesDict['pwidth'] = self.patWidthSpin.GetValue()
                 self.vPropertiesDict['scale'] = self.patScaleSpin.GetValue()
-                
+
         if self.type == 'lines':
-            #width
+            # width
             if self.cwidthCheck.GetValue():
                 self.vPropertiesDict['cwidth'] = self.widthSpin.GetValue()
                 self.vPropertiesDict['width'] = None
             else:
                 self.vPropertiesDict['width'] = self.widthSpin.GetValue()
                 self.vPropertiesDict['cwidth'] = None
-            #line style
+            # line style
             if self.styleCombo.GetValue():
-                self.vPropertiesDict['style'] = self.styleCombo.GetValue() 
+                self.vPropertiesDict['style'] = self.styleCombo.GetValue()
             else:
                 self.vPropertiesDict['style'] = 'solid'
 
-            self.vPropertiesDict['linecap'] = self.linecapChoice.GetStringSelection()
-            
+            self.vPropertiesDict[
+                'linecap'] = self.linecapChoice.GetStringSelection()
+
     def OnOK(self, event):
         self.update()
         event.Skip()
-        
+
+
 class LegendDialog(PsmapDialog):
+
     def __init__(self, parent, id, settings, page):
-        PsmapDialog.__init__(self, parent = parent, id = id, title = "Legend settings", settings = settings)
+        PsmapDialog.__init__(
+            self,
+            parent=parent,
+            id=id,
+            title="Legend settings",
+            settings=settings)
         self.objectType = ('rasterLegend', 'vectorLegend')
         self.instruction = settings
         map = self.instruction.FindInstructionByType('map')
         if map:
-            self.mapId = map.id 
+            self.mapId = map.id
         else:
             self.mapId = None
 
         vector = self.instruction.FindInstructionByType('vector')
         if vector:
-            self.vectorId = vector.id 
+            self.vectorId = vector.id
         else:
             self.vectorId = None
 
         raster = self.instruction.FindInstructionByType('raster')
         if raster:
-            self.rasterId = raster.id 
+            self.rasterId = raster.id
         else:
             self.rasterId = None
 
         self.pageId = self.instruction.FindInstructionByType('page').id
         currPage = self.instruction[self.pageId].GetInstruction()
-        #raster legend
+        # raster legend
         if self.id[0] is not None:
             self.rasterLegend = self.instruction[self.id[0]]
             self.rLegendDict = self.rasterLegend.GetInstruction()
@@ -2432,9 +3332,8 @@
             self.rasterLegend = RasterLegend(self.id[0])
             self.rLegendDict = self.rasterLegend.GetInstruction()
             self.rLegendDict['where'] = currPage['Left'], currPage['Top']
-            
-            
-        #vector legend    
+
+        # vector legend
         if self.id[1] is not None:
             self.vLegendDict = self.instruction[self.id[1]].GetInstruction()
         else:
@@ -2442,138 +3341,246 @@
             vectorLegend = VectorLegend(self.id[1])
             self.vLegendDict = vectorLegend.GetInstruction()
             self.vLegendDict['where'] = currPage['Left'], currPage['Top']
-            
+
         if self.rasterId:
-            self.currRaster = self.instruction[self.rasterId]['raster'] 
+            self.currRaster = self.instruction[self.rasterId]['raster']
         else:
             self.currRaster = None
 
-        #notebook
-        self.notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
+        # notebook
+        self.notebook = wx.Notebook(
+            parent=self, id=wx.ID_ANY, style=wx.BK_DEFAULT)
         self.panelRaster = self._rasterLegend(self.notebook)
-        self.panelVector = self._vectorLegend(self.notebook)  
+        self.panelVector = self._vectorLegend(self.notebook)
         self.OnRaster(None)
         self.OnRange(None)
         self.OnIsLegend(None)
         self.OnSpan(None)
         self.OnBorder(None)
-                
+
         self._layout(self.notebook)
         self.notebook.ChangeSelection(page)
         self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGING, self.OnPageChanging)
-        
+
     def OnPageChanging(self, event):
         """Workaround to scroll up to see the checkbox"""
         wx.CallAfter(self.FindWindowByName('rasterPanel').ScrollChildIntoView,
-                                            self.FindWindowByName('showRLegend'))
+                     self.FindWindowByName('showRLegend'))
         wx.CallAfter(self.FindWindowByName('vectorPanel').ScrollChildIntoView,
-                                            self.FindWindowByName('showVLegend'))
-                                            
+                     self.FindWindowByName('showVLegend'))
+
     def _rasterLegend(self, notebook):
-        panel = scrolled.ScrolledPanel(parent = notebook, id = wx.ID_ANY, size = (-1, 500), style = wx.TAB_TRAVERSAL)
-        panel.SetupScrolling(scroll_x = False, scroll_y = True)
+        panel = scrolled.ScrolledPanel(
+            parent=notebook, id=wx.ID_ANY, size=(-1, 500),
+            style=wx.TAB_TRAVERSAL)
+        panel.SetupScrolling(scroll_x=False, scroll_y=True)
         panel.SetName('rasterPanel')
-        notebook.AddPage(page = panel, text = _("Raster legend"))
+        notebook.AddPage(page=panel, text=_("Raster legend"))
 
         border = wx.BoxSizer(wx.VERTICAL)
         # is legend
-        self.isRLegend = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Show raster legend"))
+        self.isRLegend = wx.CheckBox(
+            panel, id=wx.ID_ANY, label=_("Show raster legend"))
         self.isRLegend.SetValue(self.rLegendDict['rLegend'])
         self.isRLegend.SetName("showRLegend")
-        border.Add(item = self.isRLegend, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
+        border.Add(
+            item=self.isRLegend,
+            proportion=0,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
 
         # choose raster
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Source raster"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Source raster"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        flexSizer = wx.FlexGridSizer (cols = 2, hgap = 5, vgap = 5)
-        
-        self.rasterDefault = wx.RadioButton(panel, id = wx.ID_ANY, label = _("current raster"), style = wx.RB_GROUP)
-        self.rasterOther = wx.RadioButton(panel, id = wx.ID_ANY, label = _("select raster"))
-        self.rasterDefault.SetValue(self.rLegendDict['rasterDefault'])#
-        self.rasterOther.SetValue(not self.rLegendDict['rasterDefault'])#
+        flexSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
 
-        rasterType = getRasterType(map = self.currRaster)
+        self.rasterDefault = wx.RadioButton(
+            panel, id=wx.ID_ANY, label=_("current raster"),
+            style=wx.RB_GROUP)
+        self.rasterOther = wx.RadioButton(
+            panel, id=wx.ID_ANY, label=_("select raster"))
+        self.rasterDefault.SetValue(self.rLegendDict['rasterDefault'])
+        self.rasterOther.SetValue(not self.rLegendDict['rasterDefault'])
 
-        self.rasterCurrent = wx.StaticText(panel, id = wx.ID_ANY,
-                                label = _("%(rast)s: type %(type)s") % { 'rast' : self.currRaster,
-                                                                         'type' : rasterType })
-        self.rasterSelect = Select(panel, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
-                                    type = 'raster', multiple = False,
-                                    updateOnPopup = True, onPopup = None)
+        rasterType = getRasterType(map=self.currRaster)
+
+        self.rasterCurrent = wx.StaticText(
+            panel, id=wx.ID_ANY, label=_("%(rast)s: type %(type)s") %
+            {'rast': self.currRaster, 'type': rasterType})
+        self.rasterSelect = Select(
+            panel,
+            id=wx.ID_ANY,
+            size=globalvar.DIALOG_GSELECT_SIZE,
+            type='raster',
+            multiple=False,
+            updateOnPopup=True,
+            onPopup=None)
         if not self.rLegendDict['rasterDefault']:
             self.rasterSelect.SetValue(self.rLegendDict['raster'])
         else:
             self.rasterSelect.SetValue('')
-        flexSizer.Add(self.rasterDefault, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        flexSizer.Add(self.rasterCurrent, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.LEFT, border = 10)
-        flexSizer.Add(self.rasterOther, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        flexSizer.Add(self.rasterSelect, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
+        flexSizer.Add(
+            self.rasterDefault,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+        flexSizer.Add(
+            self.rasterCurrent,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
+            border=10)
+        flexSizer.Add(
+            self.rasterOther,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+        flexSizer.Add(
+            self.rasterSelect,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT,
+            border=0)
         flexSizer.AddGrowableCol(1)
-        
-        sizer.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+
+        sizer.Add(
+            item=flexSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=1)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         # type of legend
-        
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Type of legend"))        
+
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Type of legend"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
         vbox = wx.BoxSizer(wx.VERTICAL)
-        self.discrete = wx.RadioButton(parent = panel, id = wx.ID_ANY, 
-                        label = " %s " % _("discrete legend (categorical maps)"), style = wx.RB_GROUP)
-        self.continuous = wx.RadioButton(parent = panel, id = wx.ID_ANY, 
-                        label = " %s " % _("continuous color gradient legend (floating point map)"))
-        
-        vbox.Add(self.discrete, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 0)
-        vbox.Add(self.continuous, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 0)
-        sizer.Add(item = vbox, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+        self.discrete = wx.RadioButton(
+            parent=panel, id=wx.ID_ANY, label=" %s " %
+            _("discrete legend (categorical maps)"),
+            style=wx.RB_GROUP)
+        self.continuous = wx.RadioButton(
+            parent=panel, id=wx.ID_ANY, label=" %s " %
+            _("continuous color gradient legend (floating point map)"))
+
+        vbox.Add(
+            self.discrete,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=0)
+        vbox.Add(
+            self.continuous,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=0)
+        sizer.Add(item=vbox, proportion=1, flag=wx.ALL | wx.EXPAND, border=1)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         # size, position and font
-        self.sizePositionFont(legendType = 'raster', parent = panel, mainSizer = border)
-        
+        self.sizePositionFont(
+            legendType='raster',
+            parent=panel,
+            mainSizer=border)
+
         # advanced settings
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Advanced legend settings"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Advanced legend settings"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
         # no data
-        self.nodata = wx.CheckBox(panel, id = wx.ID_ANY, label = _('draw "no data" box'))
+        self.nodata = wx.CheckBox(
+            panel, id=wx.ID_ANY, label=_('draw "no data" box'))
         if self.rLegendDict['nodata'] == 'y':
             self.nodata.SetValue(True)
-        else: 
+        else:
             self.nodata.SetValue(False)
-        #tickbar
-        self.ticks = wx.CheckBox(panel, id = wx.ID_ANY, label = _("draw ticks across color table"))
+        # tickbar
+        self.ticks = wx.CheckBox(
+            panel,
+            id=wx.ID_ANY,
+            label=_("draw ticks across color table"))
         if self.rLegendDict['tickbar'] == 'y':
             self.ticks.SetValue(True)
         else:
             self.ticks.SetValue(False)
         # range
         if self.rasterId and self.instruction[self.rasterId]['raster']:
-            rinfo = grass.raster_info(self.instruction[self.rasterId]['raster'])
+            rinfo = grass.raster_info(
+                self.instruction[
+                    self.rasterId]['raster'])
             self.minim, self.maxim = rinfo['min'], rinfo['max']
         else:
-            self.minim, self.maxim = 0,0
-        self.range = wx.CheckBox(panel, id = wx.ID_ANY, label = _("range"))
+            self.minim, self.maxim = 0, 0
+        self.range = wx.CheckBox(panel, id=wx.ID_ANY, label=_("range"))
         self.range.SetValue(self.rLegendDict['range'])
-        self.minText =  wx.StaticText(panel, id = wx.ID_ANY, label = "min (%s)" % self.minim)
-        self.maxText =  wx.StaticText(panel, id = wx.ID_ANY, label = "max (%s)" % self.maxim)       
-        self.min = wx.TextCtrl(panel, id = wx.ID_ANY, value = str(self.rLegendDict['min']))
-        self.max = wx.TextCtrl(panel, id = wx.ID_ANY, value = str(self.rLegendDict['max']))
-        
-        gridBagSizer.Add(self.nodata, pos = (0,0), span = (1,5), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.ticks, pos = (1,0), span = (1,5), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.range, pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.minText, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
-        gridBagSizer.Add(self.min, pos = (2,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.maxText, pos = (2,3), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
-        gridBagSizer.Add(self.max, pos = (2,4), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        
-        sizer.Add(gridBagSizer, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-   
+        self.minText = wx.StaticText(
+            panel,
+            id=wx.ID_ANY,
+            label="min (%s)" %
+            self.minim)
+        self.maxText = wx.StaticText(
+            panel,
+            id=wx.ID_ANY,
+            label="max (%s)" %
+            self.maxim)
+        self.min = wx.TextCtrl(
+            panel, id=wx.ID_ANY, value=str(
+                self.rLegendDict['min']))
+        self.max = wx.TextCtrl(
+            panel, id=wx.ID_ANY, value=str(
+                self.rLegendDict['max']))
+
+        gridBagSizer.Add(
+            self.nodata, pos=(
+                0, 0), span=(
+                1, 5), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.ticks, pos=(
+                1, 0), span=(
+                1, 5), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.range, pos=(2, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.minText,
+            pos=(
+                2,
+                1),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT,
+            border=0)
+        gridBagSizer.Add(
+            self.min, pos=(2, 2),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.maxText,
+            pos=(
+                2,
+                3),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT,
+            border=0)
+        gridBagSizer.Add(
+            self.max, pos=(2, 4),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+
+        sizer.Add(
+            gridBagSizer,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         panel.SetSizer(border)
         panel.Fit()
-        
+
         # bindings
         self.Bind(wx.EVT_RADIOBUTTON, self.OnRaster, self.rasterDefault)
         self.Bind(wx.EVT_RADIOBUTTON, self.OnRaster, self.rasterOther)
@@ -2583,38 +3590,54 @@
 ##        self.Bind(wx.EVT_CHECKBOX, self.OnDefaultSize, panel.defaultSize)
         self.Bind(wx.EVT_CHECKBOX, self.OnRange, self.range)
         self.rasterSelect.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnRaster)
-        
+
         return panel
-    
+
     def _vectorLegend(self, notebook):
-        panel = scrolled.ScrolledPanel(parent = notebook, id = wx.ID_ANY, size = (-1, 500), style = wx.TAB_TRAVERSAL)
-        panel.SetupScrolling(scroll_x = False, scroll_y = True)
+        panel = scrolled.ScrolledPanel(
+            parent=notebook, id=wx.ID_ANY, size=(-1, 500),
+            style=wx.TAB_TRAVERSAL)
+        panel.SetupScrolling(scroll_x=False, scroll_y=True)
         panel.SetName('vectorPanel')
-        notebook.AddPage(page = panel, text = _("Vector legend"))
+        notebook.AddPage(page=panel, text=_("Vector legend"))
 
         border = wx.BoxSizer(wx.VERTICAL)
         # is legend
-        self.isVLegend = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Show vector legend"))
+        self.isVLegend = wx.CheckBox(
+            panel, id=wx.ID_ANY, label=_("Show vector legend"))
         self.isVLegend.SetValue(self.vLegendDict['vLegend'])
         self.isVLegend.SetName("showVLegend")
-        border.Add(item = self.isVLegend, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
-        #vector maps, their order, labels
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Source vector maps"))
+        border.Add(
+            item=self.isVLegend,
+            proportion=0,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+
+        # vector maps, their order, labels
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Source vector maps"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
-        
-        vectorText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Choose vector maps and their order in legend"))
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
 
+        vectorText = wx.StaticText(panel, id=wx.ID_ANY, label=_(
+            "Choose vector maps and their order in legend"))
+
         self.vectorListCtrl = CheckListCtrl(panel)
-        
+
         self.vectorListCtrl.InsertColumn(0, _("Vector map"))
         self.vectorListCtrl.InsertColumn(1, _("Label"))
         if self.vectorId:
-            vectors = sorted(self.instruction[self.vectorId]['list'], key = lambda x: x[3])
-            
+            vectors = sorted(
+                self.instruction[
+                    self.vectorId]['list'],
+                key=lambda x: x[3])
+
             for vector in vectors:
-                index = self.vectorListCtrl.InsertStringItem(sys.maxint, vector[0].split('@')[0])
+                index = self.vectorListCtrl.InsertStringItem(
+                    sys.maxsize, vector[0].split('@')[0])
                 self.vectorListCtrl.SetStringItem(index, 1, vector[4])
                 self.vectorListCtrl.SetItemData(index, index)
                 self.vectorListCtrl.CheckItem(index, True)
@@ -2625,191 +3648,350 @@
         else:
             self.vectorListCtrl.SetColumnWidth(0, wx.LIST_AUTOSIZE)
         self.vectorListCtrl.SetColumnWidth(1, wx.LIST_AUTOSIZE)
-        
-        self.btnUp = wx.Button(panel, id = wx.ID_ANY, label = _("Up"))
-        self.btnDown = wx.Button(panel, id = wx.ID_ANY, label = _("Down"))
-        self.btnLabel = wx.Button(panel, id = wx.ID_ANY, label = _("Edit label"))
-      
-        gridBagSizer.Add(vectorText, pos = (0,0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.vectorListCtrl, pos = (1,0), span = (3,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        gridBagSizer.Add(self.btnUp, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.btnDown, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.btnLabel, pos = (3,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        
-        gridBagSizer.AddGrowableCol(0,3)
-        gridBagSizer.AddGrowableCol(1,1)
-        sizer.Add(gridBagSizer, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+
+        self.btnUp = wx.Button(panel, id=wx.ID_ANY, label=_("Up"))
+        self.btnDown = wx.Button(panel, id=wx.ID_ANY, label=_("Down"))
+        self.btnLabel = wx.Button(panel, id=wx.ID_ANY, label=_("Edit label"))
+
+        gridBagSizer.Add(
+            vectorText, pos=(
+                0, 0), span=(
+                1, 2), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.vectorListCtrl, pos=(
+                1, 0), span=(
+                3, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+        gridBagSizer.Add(
+            self.btnUp, pos=(1, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.btnDown, pos=(2, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.btnLabel, pos=(3, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+
+        gridBagSizer.AddGrowableCol(0, 3)
+        gridBagSizer.AddGrowableCol(1, 1)
+        sizer.Add(
+            gridBagSizer,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+            border=0)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         # size, position and font
-        self.sizePositionFont(legendType = 'vector', parent = panel, mainSizer = border)
-         
+        self.sizePositionFont(
+            legendType='vector',
+            parent=panel,
+            mainSizer=border)
+
         # border
         # GTC  Line around legend or map frame
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Border"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Border"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        flexGridSizer = wx.FlexGridSizer(cols = 2, hgap = 5, vgap = 5)
-        
-        self.borderCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("draw border around legend"))
-        self.borderColorCtrl = wx.ColourPickerCtrl(panel, id = wx.ID_ANY, style = wx.FNTP_FONTDESC_AS_LABEL)
+        flexGridSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
+
+        self.borderCheck = wx.CheckBox(
+            panel, id=wx.ID_ANY, label=_("draw border around legend"))
+        self.borderColorCtrl = wx.ColourPickerCtrl(
+            panel, id=wx.ID_ANY, style=wx.FNTP_FONTDESC_AS_LABEL)
         if self.vLegendDict['border'] == 'none':
             self.borderColorCtrl.SetColour(wx.BLACK)
             self.borderCheck.SetValue(False)
         else:
-            self.borderColorCtrl.SetColour(convertRGB(self.vLegendDict['border']))
+            self.borderColorCtrl.SetColour(
+                convertRGB(self.vLegendDict['border']))
             self.borderCheck.SetValue(True)
-            
-        flexGridSizer.Add(self.borderCheck, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)    
-        flexGridSizer.Add(self.borderColorCtrl, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        sizer.Add(item = flexGridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+
+        flexGridSizer.Add(
+            self.borderCheck,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+        flexGridSizer.Add(
+            self.borderColorCtrl,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+        sizer.Add(
+            item=flexGridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=1)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         self.Bind(wx.EVT_BUTTON, self.OnUp, self.btnUp)
-        self.Bind(wx.EVT_BUTTON, self.OnDown, self.btnDown)  
+        self.Bind(wx.EVT_BUTTON, self.OnDown, self.btnDown)
         self.Bind(wx.EVT_BUTTON, self.OnEditLabel, self.btnLabel)
-        self.Bind(wx.EVT_CHECKBOX, self.OnIsLegend, self.isVLegend)    
-        self.Bind(wx.EVT_CHECKBOX, self.OnSpan, panel.spanRadio)  
+        self.Bind(wx.EVT_CHECKBOX, self.OnIsLegend, self.isVLegend)
+        self.Bind(wx.EVT_CHECKBOX, self.OnSpan, panel.spanRadio)
         self.Bind(wx.EVT_CHECKBOX, self.OnBorder, self.borderCheck)
-        self.Bind(wx.EVT_FONTPICKER_CHANGED, self.OnFont, panel.font['fontCtrl']) 
-        
+        self.Bind(
+            wx.EVT_FONTPICKER_CHANGED,
+            self.OnFont,
+            panel.font['fontCtrl'])
+
         panel.SetSizer(border)
-        
+
         panel.Fit()
         return panel
-    
+
     def sizePositionFont(self, legendType, parent, mainSizer):
         """Insert widgets for size, position and font control"""
         if legendType == 'raster':
-            legendDict = self.rLegendDict  
+            legendDict = self.rLegendDict
         else:
             legendDict = self.vLegendDict
         panel = parent
         border = mainSizer
-        
-        # size and position        
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Size and position"))
+
+        # size and position
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Size and position"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        #unit
-        self.AddUnits(parent = panel, dialogDict = legendDict)
+        # unit
+        self.AddUnits(parent=panel, dialogDict=legendDict)
         unitBox = wx.BoxSizer(wx.HORIZONTAL)
-        unitBox.Add(panel.units['unitsLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.LEFT, border = 10)
-        unitBox.Add(panel.units['unitsCtrl'], proportion = 1, flag = wx.ALL, border = 5)
-        sizer.Add(unitBox, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        
+        unitBox.Add(
+            panel.units['unitsLabel'],
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
+            border=10)
+        unitBox.Add(
+            panel.units['unitsCtrl'],
+            proportion=1,
+            flag=wx.ALL,
+            border=5)
+        sizer.Add(
+            unitBox,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+
         hBox = wx.BoxSizer(wx.HORIZONTAL)
-        posBox = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " %_("Position"))
-        posSizer = wx.StaticBoxSizer(posBox, wx.VERTICAL)       
-        sizeBox = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Size"))
-        sizeSizer = wx.StaticBoxSizer(sizeBox, wx.VERTICAL) 
-        posGridBagSizer = wx.GridBagSizer(hgap = 10, vgap = 5)
-        
-        #position
-        self.AddPosition(parent = panel, dialogDict = legendDict)
-        
-        posGridBagSizer.Add(panel.position['xLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        posGridBagSizer.Add(panel.position['xCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        posGridBagSizer.Add(panel.position['yLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        posGridBagSizer.Add(panel.position['yCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        posGridBagSizer.Add(panel.position['comment'], pos = (2,0), span = (1,2), flag =wx.ALIGN_BOTTOM, border = 0)
+        posBox = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Position"))
+        posSizer = wx.StaticBoxSizer(posBox, wx.VERTICAL)
+        sizeBox = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Size"))
+        sizeSizer = wx.StaticBoxSizer(sizeBox, wx.VERTICAL)
+        posGridBagSizer = wx.GridBagSizer(hgap=10, vgap=5)
+
+        # position
+        self.AddPosition(parent=panel, dialogDict=legendDict)
+
+        posGridBagSizer.Add(panel.position['xLabel'], pos=(
+            0, 0), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        posGridBagSizer.Add(panel.position['xCtrl'], pos=(
+            0, 1), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        posGridBagSizer.Add(panel.position['yLabel'], pos=(
+            1, 0), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        posGridBagSizer.Add(panel.position['yCtrl'], pos=(
+            1, 1), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        posGridBagSizer.Add(
+            panel.position['comment'], pos=(
+                2, 0), span=(
+                1, 2), flag=wx.ALIGN_BOTTOM, border=0)
         posGridBagSizer.AddGrowableRow(2)
-        posSizer.Add(posGridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        
-        #size
-        width = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width:"))
+        posSizer.Add(
+            posGridBagSizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+
+        # size
+        width = wx.StaticText(panel, id=wx.ID_ANY, label=_("Width:"))
         if legendDict['width']:
-            w = self.unitConv.convert(value = float(legendDict['width']), fromUnit = 'inch', toUnit = legendDict['unit'])
-        else: 
+            w = self.unitConv.convert(
+                value=float(legendDict['width']),
+                fromUnit='inch', toUnit=legendDict['unit'])
+        else:
             w = ''
-        panel.widthCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = str(w), validator = TCValidator("DIGIT_ONLY"))
-        panel.widthCtrl.SetToolTipString(_("Leave the edit field empty, to use default values."))
-        
+        panel.widthCtrl = wx.TextCtrl(
+            panel, id=wx.ID_ANY, value=str(w),
+            validator=TCValidator("DIGIT_ONLY"))
+        panel.widthCtrl.SetToolTipString(
+            _("Leave the edit field empty, to use default values."))
+
         if legendType == 'raster':
-##            panel.defaultSize = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Use default size"))
-##            panel.defaultSize.SetValue(legendDict['defaultSize'])
-            
-            panel.heightOrColumnsLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("Height:"))
+            ##            panel.defaultSize = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Use default size"))
+            # panel.defaultSize.SetValue(legendDict['defaultSize'])
+
+            panel.heightOrColumnsLabel = wx.StaticText(
+                panel, id=wx.ID_ANY, label=_("Height:"))
             if legendDict['height']:
-                h = self.unitConv.convert(value = float(legendDict['height']), fromUnit = 'inch', toUnit = legendDict['unit'])
+                h = self.unitConv.convert(
+                    value=float(legendDict['height']),
+                    fromUnit='inch', toUnit=legendDict['unit'])
             else:
                 h = ''
-            panel.heightOrColumnsCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = str(h), validator = TCValidator("DIGIT_ONLY"))
-            
-            self.rSizeGBSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
+            panel.heightOrColumnsCtrl = wx.TextCtrl(
+                panel, id=wx.ID_ANY, value=str(h),
+                validator=TCValidator("DIGIT_ONLY"))
+
+            self.rSizeGBSizer = wx.GridBagSizer(hgap=5, vgap=5)
 ##            self.rSizeGBSizer.Add(panel.defaultSize, pos = (0,0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-            self.rSizeGBSizer.Add(width, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-            self.rSizeGBSizer.Add(panel.widthCtrl, pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-            self.rSizeGBSizer.Add(panel.heightOrColumnsLabel, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-            self.rSizeGBSizer.Add(panel.heightOrColumnsCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-            sizeSizer.Add(self.rSizeGBSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-            
+            self.rSizeGBSizer.Add(
+                width, pos=(0, 0),
+                flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+            self.rSizeGBSizer.Add(
+                panel.widthCtrl, pos=(0, 1),
+                flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+            self.rSizeGBSizer.Add(
+                panel.heightOrColumnsLabel, pos=(
+                    1, 0), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+            self.rSizeGBSizer.Add(
+                panel.heightOrColumnsCtrl, pos=(
+                    1, 1), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+            sizeSizer.Add(
+                self.rSizeGBSizer,
+                proportion=1,
+                flag=wx.EXPAND | wx.ALL,
+                border=5)
+
         if legendType == 'vector':
-            panel.widthCtrl.SetToolTipString(_("Width of the color symbol (for lines)\nin front of the legend text")) 
-            #columns
+            panel.widthCtrl.SetToolTipString(
+                _("Width of the color symbol (for lines)\nin front of the legend text"))
+            # columns
             minVect, maxVect = 0, 0
             if self.vectorId:
                 minVect = 1
                 maxVect = min(10, len(self.instruction[self.vectorId]['list']))
-            cols = wx.StaticText(panel, id = wx.ID_ANY, label = _("Columns:"))
-            panel.colsCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, value = "",
-                                        min = minVect, max = maxVect, initial = legendDict['cols'])
-            #span
-            panel.spanRadio = wx.CheckBox(panel, id = wx.ID_ANY, label = _("column span:"))
-            panel.spanTextCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = '')
-            panel.spanTextCtrl.SetToolTipString(_("Column separation distance between the left edges\n"\
-                                                "of two columns in a multicolumn legend"))
+            cols = wx.StaticText(panel, id=wx.ID_ANY, label=_("Columns:"))
+            panel.colsCtrl = wx.SpinCtrl(
+                panel,
+                id=wx.ID_ANY,
+                value="",
+                min=minVect,
+                max=maxVect,
+                initial=legendDict['cols'])
+            # span
+            panel.spanRadio = wx.CheckBox(
+                panel, id=wx.ID_ANY, label=_("column span:"))
+            panel.spanTextCtrl = wx.TextCtrl(panel, id=wx.ID_ANY, value='')
+            panel.spanTextCtrl.SetToolTipString(_("Column separation distance between the left edges\n"
+                                                  "of two columns in a multicolumn legend"))
             if legendDict['span']:
                 panel.spanRadio.SetValue(True)
-                s = self.unitConv.convert(value = float(legendDict['span']), fromUnit = 'inch', toUnit = legendDict['unit'])    
+                s = self.unitConv.convert(
+                    value=float(legendDict['span']),
+                    fromUnit='inch', toUnit=legendDict['unit'])
                 panel.spanTextCtrl.SetValue(str(s))
             else:
                 panel.spanRadio.SetValue(False)
-                
-            self.vSizeGBSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
-            self.vSizeGBSizer.Add(width, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-            self.vSizeGBSizer.Add(panel.widthCtrl, pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-            self.vSizeGBSizer.Add(cols, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-            self.vSizeGBSizer.Add(panel.colsCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-            self.vSizeGBSizer.Add(panel.spanRadio, pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-            self.vSizeGBSizer.Add(panel.spanTextCtrl, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
+
+            self.vSizeGBSizer = wx.GridBagSizer(hgap=5, vgap=5)
+            self.vSizeGBSizer.Add(
+                width, pos=(0, 0),
+                flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+            self.vSizeGBSizer.Add(
+                panel.widthCtrl, pos=(0, 1),
+                flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+            self.vSizeGBSizer.Add(
+                cols, pos=(1, 0),
+                flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+            self.vSizeGBSizer.Add(
+                panel.colsCtrl, pos=(1, 1),
+                flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+            self.vSizeGBSizer.Add(
+                panel.spanRadio, pos=(2, 0),
+                flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+            self.vSizeGBSizer.Add(
+                panel.spanTextCtrl, pos=(2, 1),
+                flag=wx.ALIGN_CENTER_VERTICAL, border=0)
             self.vSizeGBSizer.AddGrowableCol(1)
-            sizeSizer.Add(self.vSizeGBSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)        
-        
-        hBox.Add(posSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 3)
-        hBox.Add(sizeSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 3)
-        sizer.Add(hBox, proportion = 0, flag = wx.EXPAND, border = 0)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-              
-        # font        
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Font settings"))
+            sizeSizer.Add(
+                self.vSizeGBSizer,
+                proportion=1,
+                flag=wx.EXPAND | wx.ALL,
+                border=5)
+
+        hBox.Add(posSizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=3)
+        hBox.Add(sizeSizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=3)
+        sizer.Add(hBox, proportion=0, flag=wx.EXPAND, border=0)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
+        # font
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Font settings"))
         fontSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        flexSizer = wx.FlexGridSizer (cols = 2, hgap = 5, vgap = 5)
-        
+        flexSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
+
         if legendType == 'raster':
-            self.AddFont(parent = panel, dialogDict = legendDict, color = True)
+            self.AddFont(parent=panel, dialogDict=legendDict, color=True)
         else:
-            self.AddFont(parent = panel, dialogDict = legendDict, color = False)            
-        flexSizer.Add(panel.font['fontLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        flexSizer.Add(panel.font['fontCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        flexSizer.Add(panel.font['fontSizeLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        flexSizer.Add(panel.font['fontSizeCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
+            self.AddFont(parent=panel, dialogDict=legendDict, color=False)
+        flexSizer.Add(
+            panel.font['fontLabel'],
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+        flexSizer.Add(
+            panel.font['fontCtrl'],
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+        flexSizer.Add(
+            panel.font['fontSizeLabel'],
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+        flexSizer.Add(
+            panel.font['fontSizeCtrl'],
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
         if legendType == 'raster':
-            flexSizer.Add(panel.font['colorLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)        
-            flexSizer.Add(panel.font['colorCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
+            flexSizer.Add(
+                panel.font['colorLabel'],
+                proportion=0,
+                flag=wx.ALIGN_CENTER_VERTICAL,
+                border=0)
+            flexSizer.Add(
+                panel.font['colorCtrl'],
+                proportion=0,
+                flag=wx.ALIGN_CENTER_VERTICAL,
+                border=0)
         flexSizer.AddGrowableCol(1)
-        
-        fontSizer.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
-        border.Add(item = fontSizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)    
 
-    #   some enable/disable methods  
-        
+        fontSizer.Add(
+            item=flexSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=1)
+        border.Add(
+            item=fontSizer,
+            proportion=0,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
+
+    #   some enable/disable methods
+
     def OnIsLegend(self, event):
         """Enables and disables controls, it depends if raster or vector legend is checked"""
         page = self.notebook.GetSelection()
         if page == 0 or event is None:
             children = self.panelRaster.GetChildren()
             if self.isRLegend.GetValue():
-                for i,widget in enumerate(children):
-                        widget.Enable()
+                for i, widget in enumerate(children):
+                    widget.Enable()
                 self.OnRaster(None)
                 self.OnRange(None)
                 self.OnDiscrete(None)
@@ -2821,23 +4003,23 @@
             children = self.panelVector.GetChildren()
             if self.isVLegend.GetValue():
                 for i, widget in enumerate(children):
-                        widget.Enable()
+                    widget.Enable()
                 self.OnSpan(None)
                 self.OnBorder(None)
             else:
                 for widget in children:
                     if widget.GetName() != 'showVLegend':
                         widget.Disable()
-                    
+
     def OnRaster(self, event):
-        if self.rasterDefault.GetValue():#default
+        if self.rasterDefault.GetValue():  # default
             self.rasterSelect.Disable()
             type = getRasterType(self.currRaster)
-        else:#select raster
+        else:  # select raster
             self.rasterSelect.Enable()
             map = self.rasterSelect.GetValue()
             type = getRasterType(map)
-  
+
         if type == 'CELL':
             self.discrete.SetValue(True)
         elif type in ('FCELL', 'DCELL'):
@@ -2848,14 +4030,16 @@
             elif self.rLegendDict['discrete'] == 'n':
                 self.continuous.SetValue(True)
         self.OnDiscrete(None)
-        
+
     def OnDiscrete(self, event):
         """Change control according to the type of legend"""
         enabledSize = self.panelRaster.heightOrColumnsCtrl.IsEnabled()
         self.panelRaster.heightOrColumnsCtrl.Destroy()
         if self.discrete.GetValue():
             self.panelRaster.heightOrColumnsLabel.SetLabel(_("Columns:"))
-            self.panelRaster.heightOrColumnsCtrl = wx.SpinCtrl(self.panelRaster, id = wx.ID_ANY, value = "", min = 1, max = 10, initial = self.rLegendDict['cols'])
+            self.panelRaster.heightOrColumnsCtrl = wx.SpinCtrl(
+                self.panelRaster, id=wx.ID_ANY, value="", min=1, max=10,
+                initial=self.rLegendDict['cols'])
             self.panelRaster.heightOrColumnsCtrl.Enable(enabledSize)
             self.nodata.Enable()
             self.range.Disable()
@@ -2867,11 +4051,16 @@
         else:
             self.panelRaster.heightOrColumnsLabel.SetLabel(_("Height:"))
             if self.rLegendDict['height']:
-                h = self.unitConv.convert(value = float(self.rLegendDict['height']), fromUnit = 'inch', toUnit = self.rLegendDict['unit'])
+                h = self.unitConv.convert(
+                    value=float(
+                        self.rLegendDict['height']),
+                    fromUnit='inch',
+                    toUnit=self.rLegendDict['unit'])
             else:
                 h = ''
-            self.panelRaster.heightOrColumnsCtrl = wx.TextCtrl(self.panelRaster, id = wx.ID_ANY,
-                                                    value = str(h), validator = TCValidator("DIGIT_ONLY"))
+            self.panelRaster.heightOrColumnsCtrl = wx.TextCtrl(
+                self.panelRaster, id=wx.ID_ANY, value=str(h),
+                validator=TCValidator("DIGIT_ONLY"))
             self.panelRaster.heightOrColumnsCtrl.Enable(enabledSize)
             self.nodata.Disable()
             self.range.Enable()
@@ -2881,23 +4070,25 @@
                 self.min.Enable()
                 self.max.Enable()
             self.ticks.Enable()
-        
-        self.rSizeGBSizer.Add(self.panelRaster.heightOrColumnsCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
+
+        self.rSizeGBSizer.Add(
+            self.panelRaster.heightOrColumnsCtrl, pos=(
+                1, 1), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
         self.panelRaster.Layout()
-        self.panelRaster.Fit()   
-        
+        self.panelRaster.Fit()
+
     def OnRange(self, event):
         if not self.range.GetValue():
-            self.min.Disable()        
+            self.min.Disable()
             self.max.Disable()
             self.minText.Disable()
             self.maxText.Disable()
         else:
-            self.min.Enable()        
-            self.max.Enable() 
+            self.min.Enable()
+            self.max.Enable()
             self.minText.Enable()
-            self.maxText.Enable()           
-     
+            self.maxText.Enable()
+
     def OnUp(self, event):
         """Moves selected map up, changes order in vector legend"""
         if self.vectorListCtrl.GetFirstSelected() != -1:
@@ -2905,16 +4096,16 @@
             if pos:
                 idx1 = self.vectorListCtrl.GetItemData(pos) - 1
                 idx2 = self.vectorListCtrl.GetItemData(pos - 1) + 1
-                self.vectorListCtrl.SetItemData(pos, idx1) 
-                self.vectorListCtrl.SetItemData(pos - 1, idx2) 
+                self.vectorListCtrl.SetItemData(pos, idx1)
+                self.vectorListCtrl.SetItemData(pos - 1, idx2)
                 self.vectorListCtrl.SortItems(cmp)
                 if pos > 0:
-                    selected = (pos - 1) 
+                    selected = (pos - 1)
                 else:
                     selected = 0
 
                 self.vectorListCtrl.Select(selected)
-       
+
     def OnDown(self, event):
         """Moves selected map down, changes order in vector legend"""
         if self.vectorListCtrl.GetFirstSelected() != -1:
@@ -2922,53 +4113,61 @@
             if pos != self.vectorListCtrl.GetItemCount() - 1:
                 idx1 = self.vectorListCtrl.GetItemData(pos) + 1
                 idx2 = self.vectorListCtrl.GetItemData(pos + 1) - 1
-                self.vectorListCtrl.SetItemData(pos, idx1) 
-                self.vectorListCtrl.SetItemData(pos + 1, idx2) 
+                self.vectorListCtrl.SetItemData(pos, idx1)
+                self.vectorListCtrl.SetItemData(pos + 1, idx2)
                 self.vectorListCtrl.SortItems(cmp)
-                if pos < self.vectorListCtrl.GetItemCount() -1:
-                    selected = (pos + 1) 
+                if pos < self.vectorListCtrl.GetItemCount() - 1:
+                    selected = (pos + 1)
                 else:
-                    selected = self.vectorListCtrl.GetItemCount() -1
+                    selected = self.vectorListCtrl.GetItemCount() - 1
 
                 self.vectorListCtrl.Select(selected)
-                
+
     def OnEditLabel(self, event):
         """Change legend label of vector map"""
         if self.vectorListCtrl.GetFirstSelected() != -1:
             idx = self.vectorListCtrl.GetFirstSelected()
             default = self.vectorListCtrl.GetItem(idx, 1).GetText()
-            dlg = wx.TextEntryDialog(self, message = _("Edit legend label:"), caption = _("Edit label"),
-                                    defaultValue = default, style = wx.OK|wx.CANCEL|wx.CENTRE)
+            dlg = wx.TextEntryDialog(
+                self,
+                message=_("Edit legend label:"),
+                caption=_("Edit label"),
+                defaultValue=default,
+                style=wx.OK | wx.CANCEL | wx.CENTRE)
             if dlg.ShowModal() == wx.ID_OK:
                 new = dlg.GetValue()
                 self.vectorListCtrl.SetStringItem(idx, 1, new)
             dlg.Destroy()
-        
+
     def OnSpan(self, event):
-        self.panelVector.spanTextCtrl.Enable(self.panelVector.spanRadio.GetValue())
+        self.panelVector.spanTextCtrl.Enable(
+            self.panelVector.spanRadio.GetValue())
+
     def OnFont(self, event):
-        """Changes default width according to fontsize, width [inch] = fontsize[pt]/24""" 
-##        fontsize = self.panelVector.font['fontCtrl'].GetSelectedFont().GetPointSize() 
+        """Changes default width according to fontsize, width [inch] = fontsize[pt]/24"""
+##        fontsize = self.panelVector.font['fontCtrl'].GetSelectedFont().GetPointSize()
         fontsize = self.panelVector.font['fontSizeCtrl'].GetValue()
-        unit = self.unitConv.findUnit(self.panelVector.units['unitsCtrl'].GetStringSelection())
-        w = fontsize/24.
-        width = self.unitConv.convert(value = w, fromUnit = 'inch', toUnit = unit)
+        unit = self.unitConv.findUnit(
+            self.panelVector.units['unitsCtrl'].GetStringSelection())
+        w = fontsize / 24.
+        width = self.unitConv.convert(value=w, fromUnit='inch', toUnit=unit)
         self.panelVector.widthCtrl.SetValue("%3.2f" % width)
-        
+
     def OnBorder(self, event):
-        """Enables/disables colorPickerCtrl for border"""  
+        """Enables/disables colorPickerCtrl for border"""
         self.borderColorCtrl.Enable(self.borderCheck.GetValue())
-    
+
     def updateRasterLegend(self):
         """Save information from raster legend dialog to dictionary"""
 
-        #is raster legend
+        # is raster legend
         if not self.isRLegend.GetValue():
             self.rLegendDict['rLegend'] = False
         else:
             self.rLegendDict['rLegend'] = True
-        #units
-        currUnit = self.unitConv.findUnit(self.panelRaster.units['unitsCtrl'].GetStringSelection())
+        # units
+        currUnit = self.unitConv.findUnit(
+            self.panelRaster.units['unitsCtrl'].GetStringSelection())
         self.rLegendDict['unit'] = currUnit
         # raster
         if self.rasterDefault.GetValue():
@@ -2978,61 +4177,80 @@
             self.rLegendDict['rasterDefault'] = False
             self.rLegendDict['raster'] = self.rasterSelect.GetValue()
         if self.rLegendDict['rLegend'] and not self.rLegendDict['raster']:
-            wx.MessageBox(message = _("No raster map selected!"),
-                                    caption = _('No raster'), style = wx.OK|wx.ICON_ERROR)
+            wx.MessageBox(message=_("No raster map selected!"),
+                          caption=_('No raster'), style=wx.OK | wx.ICON_ERROR)
             return False
-            
+
         if self.rLegendDict['raster']:
             # type and range of map
             rasterType = getRasterType(self.rLegendDict['raster'])
             if rasterType is None:
                 return False
             self.rLegendDict['type'] = rasterType
-            
-            
-            #discrete
+
+            # discrete
             if self.discrete.GetValue():
                 self.rLegendDict['discrete'] = 'y'
             else:
-                self.rLegendDict['discrete'] = 'n'   
-                    
-            # font 
-            self.rLegendDict['font'] = self.panelRaster.font['fontCtrl'].GetStringSelection()
-            self.rLegendDict['fontsize'] = self.panelRaster.font['fontSizeCtrl'].GetValue()
+                self.rLegendDict['discrete'] = 'n'
+
+            # font
+            self.rLegendDict['font'] = self.panelRaster.font[
+                'fontCtrl'].GetStringSelection()
+            self.rLegendDict['fontsize'] = self.panelRaster.font[
+                'fontSizeCtrl'].GetValue()
             color = self.panelRaster.font['colorCtrl'].GetColour()
             self.rLegendDict['color'] = convertRGB(color)
 
             # position
-            x = self.unitConv.convert(value = float(self.panelRaster.position['xCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
-            y = self.unitConv.convert(value = float(self.panelRaster.position['yCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
+            x = self.unitConv.convert(
+                value=float(
+                    self.panelRaster.position
+                    ['xCtrl'].GetValue()),
+                fromUnit=currUnit, toUnit='inch')
+            y = self.unitConv.convert(
+                value=float(
+                    self.panelRaster.position
+                    ['yCtrl'].GetValue()),
+                fromUnit=currUnit, toUnit='inch')
             self.rLegendDict['where'] = (x, y)
             # estimated size
             width = self.panelRaster.widthCtrl.GetValue()
             try:
                 width = float(width)
-                width = self.unitConv.convert(value = width, fromUnit = currUnit, toUnit = 'inch')
+                width = self.unitConv.convert(
+                    value=width, fromUnit=currUnit, toUnit='inch')
             except ValueError:
                 width = None
             self.rLegendDict['width'] = width
             if self.rLegendDict['discrete'] == 'n':
-                height = self.panelRaster.heightOrColumnsCtrl.GetValue()    
+                height = self.panelRaster.heightOrColumnsCtrl.GetValue()
                 try:
                     height = float(height)
-                    height = self.unitConv.convert(value = height, fromUnit = currUnit, toUnit = 'inch')
+                    height = self.unitConv.convert(
+                        value=height, fromUnit=currUnit, toUnit='inch')
                 except ValueError:
                     height = None
                 self.rLegendDict['height'] = height
             else:
                 cols = self.panelRaster.heightOrColumnsCtrl.GetValue()
                 self.rLegendDict['cols'] = cols
-            drawHeight = self.rasterLegend.EstimateHeight(raster = self.rLegendDict['raster'], discrete = self.rLegendDict['discrete'],
-                                            fontsize = self.rLegendDict['fontsize'], cols = self.rLegendDict['cols'],
-                                            height = self.rLegendDict['height'])
-            drawWidth = self.rasterLegend.EstimateWidth(raster = self.rLegendDict['raster'], discrete = self.rLegendDict['discrete'],
-                                            fontsize = self.rLegendDict['fontsize'], cols = self.rLegendDict['cols'],
-                                            width = self.rLegendDict['width'], paperInstr = self.instruction[self.pageId])
-            self.rLegendDict['rect'] = Rect2D(x = x, y = y, width = drawWidth, height = drawHeight)
-                        
+            drawHeight = self.rasterLegend.EstimateHeight(
+                raster=self.rLegendDict['raster'],
+                discrete=self.rLegendDict['discrete'],
+                fontsize=self.rLegendDict['fontsize'],
+                cols=self.rLegendDict['cols'],
+                height=self.rLegendDict['height'])
+            drawWidth = self.rasterLegend.EstimateWidth(
+                raster=self.rLegendDict['raster'],
+                discrete=self.rLegendDict['discrete'],
+                fontsize=self.rLegendDict['fontsize'],
+                cols=self.rLegendDict['cols'],
+                width=self.rLegendDict['width'],
+                paperInstr=self.instruction[self.pageId])
+            self.rLegendDict['rect'] = Rect2D(
+                x=x, y=y, width=drawWidth, height=drawHeight)
+
             # no data
             if self.rLegendDict['discrete'] == 'y':
                 if self.nodata.GetValue():
@@ -3052,7 +4270,7 @@
                     self.rLegendDict['max'] = self.max.GetValue()
                 else:
                     self.rLegendDict['range'] = False
-         
+
         if not self.id[0] in self.instruction:
             rasterLegend = RasterLegend(self.id[0])
             self.instruction.AddInstruction(rasterLegend)
@@ -3061,24 +4279,24 @@
         if self.id[0] not in self.parent.objectId:
             self.parent.objectId.append(self.id[0])
         return True
-    
+
     def updateVectorLegend(self):
         """Save information from vector legend dialog to dictionary"""
 
         vector = self.instruction.FindInstructionByType('vector')
         if vector:
-            self.vectorId = vector.id 
+            self.vectorId = vector.id
         else:
             self.vectorId = None
 
-        #is vector legend
+        # is vector legend
         if not self.isVLegend.GetValue():
             self.vLegendDict['vLegend'] = False
         else:
-            self.vLegendDict['vLegend'] = True   
+            self.vLegendDict['vLegend'] = True
         if self.vLegendDict['vLegend'] == True and self.vectorId is not None:
             # labels
-            #reindex order
+            # reindex order
             idx = 1
             for item in range(self.vectorListCtrl.GetItemCount()):
                 if self.vectorListCtrl.IsChecked(item):
@@ -3086,63 +4304,83 @@
                     idx += 1
                 else:
                     self.vectorListCtrl.SetItemData(item, 0)
-            if idx == 1: 
-                self.vLegendDict['vLegend'] = False     
+            if idx == 1:
+                self.vLegendDict['vLegend'] = False
             else:
                 vList = self.instruction[self.vectorId]['list']
                 for i, vector in enumerate(vList):
-                    item = self.vectorListCtrl.FindItem(start = -1, str = vector[0].split('@')[0])
+                    item = self.vectorListCtrl.FindItem(
+                        start=-1, str=vector[0].split('@')[0])
                     vList[i][3] = self.vectorListCtrl.GetItemData(item)
-                    vList[i][4] = self.vectorListCtrl.GetItem(item, 1).GetText()
-                vmaps = self.instruction.FindInstructionByType('vProperties', list = True)
+                    vList[i][4] = self.vectorListCtrl.GetItem(
+                        item, 1).GetText()
+                vmaps = self.instruction.FindInstructionByType(
+                    'vProperties', list=True)
                 for vmap, vector in zip(vmaps, vList):
                     self.instruction[vmap.id]['lpos'] = vector[3]
                     self.instruction[vmap.id]['label'] = vector[4]
-                #units
-                currUnit = self.unitConv.findUnit(self.panelVector.units['unitsCtrl'].GetStringSelection())
+                # units
+                currUnit = self.unitConv.findUnit(
+                    self.panelVector.units['unitsCtrl'].GetStringSelection())
                 self.vLegendDict['unit'] = currUnit
                 # position
-                x = self.unitConv.convert(value = float(self.panelVector.position['xCtrl'].GetValue()),
-                                                                fromUnit = currUnit, toUnit = 'inch')
-                y = self.unitConv.convert(value = float(self.panelVector.position['yCtrl'].GetValue()),
-                                                                fromUnit = currUnit, toUnit = 'inch')
+                x = self.unitConv.convert(
+                    value=float(
+                        self.panelVector.position['xCtrl'].GetValue()),
+                    fromUnit=currUnit,
+                    toUnit='inch')
+                y = self.unitConv.convert(
+                    value=float(
+                        self.panelVector.position['yCtrl'].GetValue()),
+                    fromUnit=currUnit,
+                    toUnit='inch')
                 self.vLegendDict['where'] = (x, y)
-                
-                # font 
-                self.vLegendDict['font'] = self.panelVector.font['fontCtrl'].GetStringSelection()
-                self.vLegendDict['fontsize'] = self.panelVector.font['fontSizeCtrl'].GetValue()
+
+                # font
+                self.vLegendDict['font'] = self.panelVector.font[
+                    'fontCtrl'].GetStringSelection()
+                self.vLegendDict['fontsize'] = self.panelVector.font[
+                    'fontSizeCtrl'].GetValue()
                 dc = wx.ClientDC(self)
-                dc.SetFont(wx.Font(pointSize = self.vLegendDict['fontsize'], family = wx.FONTFAMILY_DEFAULT,
-                                   style = wx.FONTSTYLE_NORMAL, weight = wx.FONTWEIGHT_NORMAL))
-                #size
-                width = self.unitConv.convert(value = float(self.panelVector.widthCtrl.GetValue()),
-                                              fromUnit = currUnit, toUnit = 'inch')
+                dc.SetFont(
+                    wx.Font(
+                        pointSize=self.vLegendDict['fontsize'],
+                        family=wx.FONTFAMILY_DEFAULT,
+                        style=wx.FONTSTYLE_NORMAL,
+                        weight=wx.FONTWEIGHT_NORMAL))
+                # size
+                width = self.unitConv.convert(
+                    value=float(self.panelVector.widthCtrl.GetValue()),
+                    fromUnit=currUnit, toUnit='inch')
                 self.vLegendDict['width'] = width
                 self.vLegendDict['cols'] = self.panelVector.colsCtrl.GetValue()
                 if self.panelVector.spanRadio.GetValue() and self.panelVector.spanTextCtrl.GetValue():
-                    self.vLegendDict['span'] = self.panelVector.spanTextCtrl.GetValue()
+                    self.vLegendDict[
+                        'span'] = self.panelVector.spanTextCtrl.GetValue()
                 else:
                     self.vLegendDict['span'] = None
-                    
+
                 # size estimation
                 vectors = self.instruction[self.vectorId]['list']
                 labels = [vector[4] for vector in vectors if vector[3] != 0]
-                extent = dc.GetTextExtent(max(labels, key = len))
-                wExtent = self.unitConv.convert(value = extent[0], fromUnit = 'pixel', toUnit = 'inch')
-                hExtent = self.unitConv.convert(value = extent[1], fromUnit = 'pixel', toUnit = 'inch')
+                extent = dc.GetTextExtent(max(labels, key=len))
+                wExtent = self.unitConv.convert(
+                    value=extent[0], fromUnit='pixel', toUnit='inch')
+                hExtent = self.unitConv.convert(
+                    value=extent[1], fromUnit='pixel', toUnit='inch')
                 w = (width + wExtent) * self.vLegendDict['cols']
                 h = len(labels) * hExtent / self.vLegendDict['cols']
                 h *= 1.1
                 self.vLegendDict['rect'] = Rect2D(x, y, w, h)
-                
-                #border
+
+                # border
                 if self.borderCheck.GetValue():
                     color = self.borderColorCtrl.GetColour()
                     self.vLegendDict['border'] = convertRGB(color)
-                    
+
                 else:
                     self.vLegendDict['border'] = 'none'
-                                 
+
         if not self.id[1] in self.instruction:
             vectorLegend = VectorLegend(self.id[1])
             self.instruction.AddInstruction(vectorLegend)
@@ -3150,71 +4388,89 @@
         if self.id[1] not in self.parent.objectId:
             self.parent.objectId.append(self.id[1])
         return True
-    
+
     def update(self):
         okR = self.updateRasterLegend()
         okV = self.updateVectorLegend()
         if okR and okV:
             return True
         return False
-        
+
     def updateDialog(self):
         """Update legend coordinates after moving"""
-        
-        # raster legend    
+
+        # raster legend
         if 'rect' in self.rLegendDict:
             x, y = self.rLegendDict['rect'][:2]
-            currUnit = self.unitConv.findUnit(self.panelRaster.units['unitsCtrl'].GetStringSelection())
-            x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
-            y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
+            currUnit = self.unitConv.findUnit(
+                self.panelRaster.units['unitsCtrl'].GetStringSelection())
+            x = self.unitConv.convert(
+                value=x, fromUnit='inch', toUnit=currUnit)
+            y = self.unitConv.convert(
+                value=y, fromUnit='inch', toUnit=currUnit)
             self.panelRaster.position['xCtrl'].SetValue("%5.3f" % x)
             self.panelRaster.position['yCtrl'].SetValue("%5.3f" % y)
-        #update name and type of raster
+        # update name and type of raster
         raster = self.instruction.FindInstructionByType('raster')
         if raster:
-            self.rasterId = raster.id 
+            self.rasterId = raster.id
         else:
-            self.rasterId = None 
+            self.rasterId = None
 
         if raster:
-            currRaster = raster['raster'] 
+            currRaster = raster['raster']
         else:
             currRaster = None
-            
-        rasterType = getRasterType(map = currRaster)
-        self.rasterCurrent.SetLabel(_("%(rast)s: type %(type)s") % \
-                                        { 'rast' : currRaster, 'type' : str(rasterType) })
-        
-        # vector legend       
+
+        rasterType = getRasterType(map=currRaster)
+        self.rasterCurrent.SetLabel(
+            _("%(rast)s: type %(type)s") %
+            {'rast': currRaster, 'type': str(rasterType)})
+
+        # vector legend
         if 'rect' in self.vLegendDict:
             x, y = self.vLegendDict['rect'][:2]
-            currUnit = self.unitConv.findUnit(self.panelVector.units['unitsCtrl'].GetStringSelection())
-            x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
-            y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
+            currUnit = self.unitConv.findUnit(
+                self.panelVector.units['unitsCtrl'].GetStringSelection())
+            x = self.unitConv.convert(
+                value=x, fromUnit='inch', toUnit=currUnit)
+            y = self.unitConv.convert(
+                value=y, fromUnit='inch', toUnit=currUnit)
             self.panelVector.position['xCtrl'].SetValue("%5.3f" % x)
             self.panelVector.position['yCtrl'].SetValue("%5.3f" % y)
         # update vector maps
         if self.instruction.FindInstructionByType('vector'):
-            vectors = sorted(self.instruction.FindInstructionByType('vector')['list'], key = lambda x: x[3])
+            vectors = sorted(
+                self.instruction.FindInstructionByType('vector')['list'],
+                key=lambda x: x[3])
             self.vectorListCtrl.DeleteAllItems()
             for vector in vectors:
-                index = self.vectorListCtrl.InsertStringItem(sys.maxint, vector[0].split('@')[0])
+                index = self.vectorListCtrl.InsertStringItem(
+                    sys.maxsize, vector[0].split('@')[0])
                 self.vectorListCtrl.SetStringItem(index, 1, vector[4])
                 self.vectorListCtrl.SetItemData(index, index)
                 self.vectorListCtrl.CheckItem(index, True)
                 if vector[3] == 0:
                     self.vectorListCtrl.CheckItem(index, False)
-            self.panelVector.colsCtrl.SetRange(1, min(10, len(self.instruction.FindInstructionByType('vector')['list'])))
+            self.panelVector.colsCtrl.SetRange(
+                1, min(10, len(self.instruction.FindInstructionByType('vector')['list'])))
             self.panelVector.colsCtrl.SetValue(1)
         else:
             self.vectorListCtrl.DeleteAllItems()
-            self.panelVector.colsCtrl.SetRange(0,0)
+            self.panelVector.colsCtrl.SetRange(0, 0)
             self.panelVector.colsCtrl.SetValue(0)
-             
+
+
 class MapinfoDialog(PsmapDialog):
+
     def __init__(self, parent, id, settings):
-        PsmapDialog.__init__(self, parent = parent, id = id, title = _("Mapinfo settings"), settings = settings)
-        
+        PsmapDialog.__init__(
+            self,
+            parent=parent,
+            id=id,
+            title=_("Mapinfo settings"),
+            settings=settings)
+
         self.objectType = ('mapinfo',)
         if self.id is not None:
             self.mapinfo = self.instruction[self.id]
@@ -3223,186 +4479,274 @@
             self.id = wx.NewId()
             self.mapinfo = Mapinfo(self.id)
             self.mapinfoDict = self.mapinfo.GetInstruction()
-            page = self.instruction.FindInstructionByType('page').GetInstruction()
+            page = self.instruction.FindInstructionByType(
+                'page').GetInstruction()
             self.mapinfoDict['where'] = page['Left'], page['Top']
 
         self.panel = self._mapinfoPanel()
-        
+
         self._layout(self.panel)
         self.OnIsBackground(None)
         self.OnIsBorder(None)
 
     def _mapinfoPanel(self):
-        panel = wx.Panel(parent = self, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
+        panel = wx.Panel(
+            parent=self, id=wx.ID_ANY, size=(-1, -1),
+            style=wx.TAB_TRAVERSAL)
         #panel.SetupScrolling(scroll_x = False, scroll_y = True)
         border = wx.BoxSizer(wx.VERTICAL)
-                
-        # position     
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Position"))
+
+        # position
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Position"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
-        
-        self.AddPosition(parent = panel, dialogDict = self.mapinfoDict)
-        self.AddUnits(parent = panel, dialogDict = self.mapinfoDict)
-        gridBagSizer.Add(panel.units['unitsLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(panel.units['unitsCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(panel.position['xLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(panel.position['xCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(panel.position['yLabel'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(panel.position['yCtrl'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(panel.position['comment'], pos = (3,0), span = (1,2), flag =wx.ALIGN_BOTTOM, border = 0)
-        
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
+
+        self.AddPosition(parent=panel, dialogDict=self.mapinfoDict)
+        self.AddUnits(parent=panel, dialogDict=self.mapinfoDict)
+        gridBagSizer.Add(panel.units['unitsLabel'], pos=(
+            0, 0), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(panel.units['unitsCtrl'], pos=(
+            0, 1), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(panel.position['xLabel'], pos=(
+            1, 0), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(panel.position['xCtrl'], pos=(
+            1, 1), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(panel.position['yLabel'], pos=(
+            2, 0), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(panel.position['yCtrl'], pos=(
+            2, 1), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            panel.position['comment'], pos=(
+                3, 0), span=(
+                1, 2), flag=wx.ALIGN_BOTTOM, border=0)
+
         gridBagSizer.AddGrowableCol(1)
-        sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+        sizer.Add(
+            gridBagSizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         # font
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Font settings"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Font settings"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
-        
-        self.AddFont(parent = panel, dialogDict = self.mapinfoDict)#creates font color too, used below
-        
-        gridBagSizer.Add(panel.font['fontLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(panel.font['fontCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(panel.font['fontSizeLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(panel.font['fontSizeCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(panel.font['colorLabel'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)        
-        gridBagSizer.Add(panel.font['colorCtrl'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
+
+        # creates font color too, used below
+        self.AddFont(parent=panel, dialogDict=self.mapinfoDict)
+
+        gridBagSizer.Add(panel.font['fontLabel'], pos=(
+            0, 0), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            panel.font['fontCtrl'],
+            pos=(0, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(panel.font['fontSizeLabel'], pos=(
+            1, 0), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(panel.font['fontSizeCtrl'], pos=(
+            1, 1), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(panel.font['colorLabel'], pos=(
+            2, 0), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(panel.font['colorCtrl'], pos=(
+            2, 1), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+
         gridBagSizer.AddGrowableCol(1)
-        sizer.Add(item = gridBagSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+        sizer.Add(
+            item=gridBagSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=1)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         # colors
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " %_("Color settings"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Color settings"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        flexSizer = wx.FlexGridSizer (cols = 2, hgap = 5, vgap = 5)
-        
+        flexSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
+
         self.colors = {}
-        self.colors['borderCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("use border color:"))
-        self.colors['backgroundCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("use background color:"))
-        self.colors['borderColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
-        self.colors['backgroundColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
-        
-        if self.mapinfoDict['border'] == None:
+        self.colors['borderCtrl'] = wx.CheckBox(
+            panel, id=wx.ID_ANY, label=_("use border color:"))
+        self.colors['backgroundCtrl'] = wx.CheckBox(
+            panel, id=wx.ID_ANY, label=_("use background color:"))
+        self.colors['borderColor'] = wx.ColourPickerCtrl(panel, id=wx.ID_ANY)
+        self.colors['backgroundColor'] = wx.ColourPickerCtrl(
+            panel, id=wx.ID_ANY)
+
+        if self.mapinfoDict['border'] is None:
             self.mapinfoDict['border'] = 'none'
         if self.mapinfoDict['border'] != 'none':
-            self.colors['borderCtrl'].SetValue(True) 
-            self.colors['borderColor'].SetColour(convertRGB(self.mapinfoDict['border']))
+            self.colors['borderCtrl'].SetValue(True)
+            self.colors['borderColor'].SetColour(
+                convertRGB(self.mapinfoDict['border']))
         else:
             self.colors['borderCtrl'].SetValue(False)
             self.colors['borderColor'].SetColour(convertRGB('black'))
-            
-        if self.mapinfoDict['background'] == None:
+
+        if self.mapinfoDict['background'] is None:
             self.mapinfoDict['background'] == 'none'
         if self.mapinfoDict['background'] != 'none':
-            self.colors['backgroundCtrl'].SetValue(True) 
-            self.colors['backgroundColor'].SetColour(convertRGB(self.mapinfoDict['background']))
+            self.colors['backgroundCtrl'].SetValue(True)
+            self.colors['backgroundColor'].SetColour(
+                convertRGB(self.mapinfoDict['background']))
         else:
             self.colors['backgroundCtrl'].SetValue(False)
             self.colors['backgroundColor'].SetColour(convertRGB('white'))
-                    
-        flexSizer.Add(self.colors['borderCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        flexSizer.Add(self.colors['borderColor'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        flexSizer.Add(self.colors['backgroundCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        flexSizer.Add(self.colors['backgroundColor'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
+
+        flexSizer.Add(
+            self.colors['borderCtrl'],
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+        flexSizer.Add(
+            self.colors['borderColor'],
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+        flexSizer.Add(
+            self.colors['backgroundCtrl'],
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+        flexSizer.Add(
+            self.colors['backgroundColor'],
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
         flexSizer.AddGrowableCol(1)
-        
-        sizer.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+
+        sizer.Add(
+            item=flexSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=1)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         panel.SetSizer(border)
-        
+
         self.Bind(wx.EVT_CHECKBOX, self.OnIsBorder, self.colors['borderCtrl'])
-        self.Bind(wx.EVT_CHECKBOX, self.OnIsBackground, self.colors['backgroundCtrl'])
-        
+        self.Bind(
+            wx.EVT_CHECKBOX,
+            self.OnIsBackground,
+            self.colors['backgroundCtrl'])
+
         return panel
-    
+
     def OnIsBackground(self, event):
         if self.colors['backgroundCtrl'].GetValue():
             self.colors['backgroundColor'].Enable()
             self.update()
         else:
             self.colors['backgroundColor'].Disable()
-                        
+
     def OnIsBorder(self, event):
         if self.colors['borderCtrl'].GetValue():
             self.colors['borderColor'].Enable()
             self.update()
         else:
-            self.colors['borderColor'].Disable() 
-                                           
+            self.colors['borderColor'].Disable()
+
     def update(self):
 
-        #units
-        currUnit = self.unitConv.findUnit(self.panel.units['unitsCtrl'].GetStringSelection())
+        # units
+        currUnit = self.unitConv.findUnit(
+            self.panel.units['unitsCtrl'].GetStringSelection())
         self.mapinfoDict['unit'] = currUnit
-        
+
         # position
         if self.panel.position['xCtrl'].GetValue():
-            x = self.panel.position['xCtrl'].GetValue() 
+            x = self.panel.position['xCtrl'].GetValue()
         else:
             x = self.mapinfoDict['where'][0]
 
         if self.panel.position['yCtrl'].GetValue():
-            y = self.panel.position['yCtrl'].GetValue() 
+            y = self.panel.position['yCtrl'].GetValue()
         else:
             y = self.mapinfoDict['where'][1]
 
-        x = self.unitConv.convert(value = float(self.panel.position['xCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
-        y = self.unitConv.convert(value = float(self.panel.position['yCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
+        x = self.unitConv.convert(
+            value=float(
+                self.panel.position['xCtrl'].GetValue()),
+            fromUnit=currUnit,
+            toUnit='inch')
+        y = self.unitConv.convert(
+            value=float(
+                self.panel.position['yCtrl'].GetValue()),
+            fromUnit=currUnit,
+            toUnit='inch')
         self.mapinfoDict['where'] = (x, y)
-        
+
         # font
-        self.mapinfoDict['font'] =  self.panel.font['fontCtrl'].GetStringSelection()
-        self.mapinfoDict['fontsize'] = self.panel.font['fontSizeCtrl'].GetValue()
+        self.mapinfoDict['font'] = self.panel.font[
+            'fontCtrl'].GetStringSelection()
+        self.mapinfoDict['fontsize'] = self.panel.font[
+            'fontSizeCtrl'].GetValue()
 
-        #colors
+        # colors
         color = self.panel.font['colorCtrl'].GetColour()
         self.mapinfoDict['color'] = convertRGB(color)
-        
-        if self.colors['backgroundCtrl'].GetValue():    
+
+        if self.colors['backgroundCtrl'].GetValue():
             background = self.colors['backgroundColor'].GetColour()
             self.mapinfoDict['background'] = convertRGB(background)
         else:
             self.mapinfoDict['background'] = 'none'
 
-        if self.colors['borderCtrl'].GetValue():    
+        if self.colors['borderCtrl'].GetValue():
             border = self.colors['borderColor'].GetColour()
             self.mapinfoDict['border'] = convertRGB(border)
         else:
             self.mapinfoDict['border'] = 'none'
-        
+
         # estimation of size
         self.mapinfoDict['rect'] = self.mapinfo.EstimateRect(self.mapinfoDict)
 
         if self.id not in self.instruction:
             mapinfo = Mapinfo(self.id)
             self.instruction.AddInstruction(mapinfo)
-            
+
         self.instruction[self.id].SetInstruction(self.mapinfoDict)
 
         if self.id not in self.parent.objectId:
             self.parent.objectId.append(self.id)
-            
+
         self.updateDialog()
 
         return True
-    
+
     def updateDialog(self):
         """Update mapinfo coordinates, after moving"""
         x, y = self.mapinfoDict['where']
-        currUnit = self.unitConv.findUnit(self.panel.units['unitsCtrl'].GetStringSelection())
-        x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
-        y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
+        currUnit = self.unitConv.findUnit(
+            self.panel.units['unitsCtrl'].GetStringSelection())
+        x = self.unitConv.convert(value=x, fromUnit='inch', toUnit=currUnit)
+        y = self.unitConv.convert(value=y, fromUnit='inch', toUnit=currUnit)
         self.panel.position['xCtrl'].SetValue("%5.3f" % x)
         self.panel.position['yCtrl'].SetValue("%5.3f" % y)
-             
+
+
 class ScalebarDialog(PsmapDialog):
     """Dialog for scale bar"""
+
     def __init__(self, parent, id, settings):
-        PsmapDialog.__init__(self, parent = parent, id = id, title = "Scale bar settings", settings = settings)
+        PsmapDialog.__init__(
+            self,
+            parent=parent,
+            id=id,
+            title="Scale bar settings",
+            settings=settings)
         self.objectType = ('scalebar',)
         if self.id is not None:
             self.scalebar = self.instruction[id]
@@ -3411,280 +4755,412 @@
             self.id = wx.NewId()
             self.scalebar = Scalebar(self.id)
             self.scalebarDict = self.scalebar.GetInstruction()
-            page = self.instruction.FindInstructionByType('page').GetInstruction()
+            page = self.instruction.FindInstructionByType(
+                'page').GetInstruction()
             self.scalebarDict['where'] = page['Left'], page['Top']
 
         self.panel = self._scalebarPanel()
-        
+
         self._layout(self.panel)
-        
+
         self.mapUnit = projInfo()['units'].lower()
         if projInfo()['proj'] == 'xy':
             self.mapUnit = 'meters'
         if self.mapUnit not in self.unitConv.getAllUnits():
-            wx.MessageBox(message = _("Units of current projection are not supported,\n meters will be used!"),
-                            caption = _('Unsupported units'),
-                                    style = wx.OK|wx.ICON_ERROR)
+            wx.MessageBox(
+                message=_(
+                    "Units of current projection are not supported,\n meters will be used!"),
+                caption=_('Unsupported units'),
+                style=wx.OK | wx.ICON_ERROR)
             self.mapUnit = 'meters'
-            
+
     def _scalebarPanel(self):
-        panel = wx.Panel(parent = self, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL)
+        panel = wx.Panel(parent=self, id=wx.ID_ANY, style=wx.TAB_TRAVERSAL)
         border = wx.BoxSizer(wx.VERTICAL)
-        #        
+        #
         # position
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Position"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Position"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
-        
-        self.AddUnits(parent = panel, dialogDict = self.scalebarDict)
-        self.AddPosition(parent = panel, dialogDict = self.scalebarDict)
-        
-        if self.scalebarDict['rect']: # set position, ref point is center and not left top corner
-            
-            x = self.unitConv.convert(value = self.scalebarDict['where'][0] - self.scalebarDict['rect'].Get()[2]/2,
-                                                    fromUnit = 'inch', toUnit = self.scalebarDict['unit'])
-            y = self.unitConv.convert(value = self.scalebarDict['where'][1] - self.scalebarDict['rect'].Get()[3]/2,
-                                                    fromUnit = 'inch', toUnit = self.scalebarDict['unit'])
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
+
+        self.AddUnits(parent=panel, dialogDict=self.scalebarDict)
+        self.AddPosition(parent=panel, dialogDict=self.scalebarDict)
+
+        if self.scalebarDict[
+                'rect']:  # set position, ref point is center and not left top corner
+
+            x = self.unitConv.convert(
+                value=self.scalebarDict['where'][0] -
+                self.scalebarDict['rect'].Get()[2] /
+                2,
+                fromUnit='inch',
+                toUnit=self.scalebarDict['unit'])
+            y = self.unitConv.convert(
+                value=self.scalebarDict['where'][1] -
+                self.scalebarDict['rect'].Get()[3] /
+                2,
+                fromUnit='inch',
+                toUnit=self.scalebarDict['unit'])
             panel.position['xCtrl'].SetValue("%5.3f" % x)
             panel.position['yCtrl'].SetValue("%5.3f" % y)
-        
-        gridBagSizer.Add(panel.units['unitsLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(panel.units['unitsCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(panel.position['xLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(panel.position['xCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(panel.position['yLabel'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(panel.position['yCtrl'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(panel.position['comment'], pos = (3,0), span = (1,2), flag =wx.ALIGN_BOTTOM, border = 0)
-        
+
+        gridBagSizer.Add(panel.units['unitsLabel'], pos=(
+            0, 0), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(panel.units['unitsCtrl'], pos=(
+            0, 1), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(panel.position['xLabel'], pos=(
+            1, 0), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(panel.position['xCtrl'], pos=(
+            1, 1), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(panel.position['yLabel'], pos=(
+            2, 0), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(panel.position['yCtrl'], pos=(
+            2, 1), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            panel.position['comment'], pos=(
+                3, 0), span=(
+                1, 2), flag=wx.ALIGN_BOTTOM, border=0)
+
         gridBagSizer.AddGrowableCol(1)
-        sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
+        sizer.Add(
+            gridBagSizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
         #
         # size
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Size"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Size"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
-        
-        lengthText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Length:"))
-        heightText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Height:"))
-        
-        self.lengthTextCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, validator = TCValidator('DIGIT_ONLY'))
-        self.lengthTextCtrl.SetToolTipString(_("Scalebar length is given in map units"))
-        
-        self.heightTextCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, validator = TCValidator('DIGIT_ONLY'))
-        self.heightTextCtrl.SetToolTipString(_("Scalebar height is real height on paper"))
-        
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
+
+        lengthText = wx.StaticText(panel, id=wx.ID_ANY, label=_("Length:"))
+        heightText = wx.StaticText(panel, id=wx.ID_ANY, label=_("Height:"))
+
+        self.lengthTextCtrl = wx.TextCtrl(
+            panel, id=wx.ID_ANY, validator=TCValidator('DIGIT_ONLY'))
+        self.lengthTextCtrl.SetToolTipString(
+            _("Scalebar length is given in map units"))
+
+        self.heightTextCtrl = wx.TextCtrl(
+            panel, id=wx.ID_ANY, validator=TCValidator('DIGIT_ONLY'))
+        self.heightTextCtrl.SetToolTipString(
+            _("Scalebar height is real height on paper"))
+
         choices = [_('default')] + self.unitConv.getMapUnitsNames()
-        self.unitsLength = wx.Choice(panel, id = wx.ID_ANY, choices = choices)
+        self.unitsLength = wx.Choice(panel, id=wx.ID_ANY, choices=choices)
         choices = self.unitConv.getPageUnitsNames()
-        self.unitsHeight = wx.Choice(panel, id = wx.ID_ANY, choices = choices)
-        
+        self.unitsHeight = wx.Choice(panel, id=wx.ID_ANY, choices=choices)
+
         # set values
         unitName = self.unitConv.findName(self.scalebarDict['unitsLength'])
         if unitName:
             self.unitsLength.SetStringSelection(unitName)
         else:
             if self.scalebarDict['unitsLength'] == 'auto':
-                 self.unitsLength.SetSelection(0)
+                self.unitsLength.SetSelection(0)
             elif self.scalebarDict['unitsLength'] == 'nautmiles':
-                 self.unitsLength.SetStringSelection(self.unitConv.findName("nautical miles"))
-        self.unitsHeight.SetStringSelection(self.unitConv.findName(self.scalebarDict['unitsHeight']))
+                self.unitsLength.SetStringSelection(
+                    self.unitConv.findName("nautical miles"))
+        self.unitsHeight.SetStringSelection(
+            self.unitConv.findName(
+                self.scalebarDict['unitsHeight']))
         if self.scalebarDict['length']:
             self.lengthTextCtrl.SetValue(str(self.scalebarDict['length']))
-        else: #estimate default
+        else:  # estimate default
             reg = grass.region()
-            w = int((reg['e'] - reg['w'])/3)
-            w = round(w, -len(str(w)) + 2) #12345 -> 12000
+            w = int((reg['e'] - reg['w']) / 3)
+            w = round(w, -len(str(w)) + 2)  # 12345 -> 12000
             self.lengthTextCtrl.SetValue(str(w))
-            
-        h = self.unitConv.convert(value = self.scalebarDict['height'], fromUnit = 'inch',
-                                                toUnit =  self.scalebarDict['unitsHeight']) 
+
+        h = self.unitConv.convert(
+            value=self.scalebarDict['height'],
+            fromUnit='inch',
+            toUnit=self.scalebarDict['unitsHeight'])
         self.heightTextCtrl.SetValue(str(h))
-        
-        gridBagSizer.Add(lengthText, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.lengthTextCtrl, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.unitsLength, pos = (0, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        gridBagSizer.Add(heightText, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.heightTextCtrl, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.unitsHeight, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-      
+
+        gridBagSizer.Add(
+            lengthText, pos=(0, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.lengthTextCtrl, pos=(0, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.unitsLength,
+            pos=(
+                0,
+                2),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+            border=0)
+        gridBagSizer.Add(
+            heightText, pos=(1, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.heightTextCtrl, pos=(1, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.unitsHeight,
+            pos=(
+                1,
+                2),
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+            border=0)
+
         gridBagSizer.AddGrowableCol(1)
-        sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
+        sizer.Add(
+            gridBagSizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
         #
-        #style
+        # style
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Style"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Style"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
-        
-        
-        sbTypeText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Type:"))
-        self.sbCombo = wx.combo.BitmapComboBox(panel, style = wx.CB_READONLY)
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
+
+        sbTypeText = wx.StaticText(panel, id=wx.ID_ANY, label=_("Type:"))
+        self.sbCombo = wx.combo.BitmapComboBox(panel, style=wx.CB_READONLY)
         # only temporary, images must be moved away
-        imagePath = os.path.join(globalvar.IMGDIR, "scalebar-fancy.png"), os.path.join(globalvar.IMGDIR, "scalebar-simple.png") 
+        imagePath = os.path.join(
+            globalvar.IMGDIR, "scalebar-fancy.png"), os.path.join(
+            globalvar.IMGDIR, "scalebar-simple.png")
         for item, path in zip(['fancy', 'simple'], imagePath):
             if not os.path.exists(path):
-                bitmap = wx.EmptyBitmap(0,0)
+                bitmap = wx.EmptyBitmap(0, 0)
             else:
                 bitmap = wx.Bitmap(path)
-            self.sbCombo.Append(item = '', bitmap = bitmap, clientData = item[0])
+            self.sbCombo.Append(item='', bitmap=bitmap, clientData=item[0])
         #self.sbCombo.Append(item = 'simple', bitmap = wx.Bitmap("./images/scalebar-simple.png"), clientData = 's')
         if self.scalebarDict['scalebar'] == 'f':
             self.sbCombo.SetSelection(0)
         elif self.scalebarDict['scalebar'] == 's':
             self.sbCombo.SetSelection(1)
-            
-        sbSegmentsText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Number of segments:"))
-        self.sbSegmentsCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 30, initial = 4)
+
+        sbSegmentsText = wx.StaticText(
+            panel, id=wx.ID_ANY, label=_("Number of segments:"))
+        self.sbSegmentsCtrl = wx.SpinCtrl(
+            panel, id=wx.ID_ANY, min=1, max=30, initial=4)
         self.sbSegmentsCtrl.SetValue(self.scalebarDict['segment'])
-        
-        sbLabelsText1 = wx.StaticText(panel, id = wx.ID_ANY, label = _("Label every "))
-        sbLabelsText2 = wx.StaticText(panel, id = wx.ID_ANY, label = _("segments"))
-        self.sbLabelsCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 30, initial = 1)
+
+        sbLabelsText1 = wx.StaticText(
+            panel, id=wx.ID_ANY, label=_("Label every "))
+        sbLabelsText2 = wx.StaticText(panel, id=wx.ID_ANY, label=_("segments"))
+        self.sbLabelsCtrl = wx.SpinCtrl(
+            panel, id=wx.ID_ANY, min=1, max=30, initial=1)
         self.sbLabelsCtrl.SetValue(self.scalebarDict['numbers'])
-        
-        #font
-        fontsizeText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Font size:"))
-        self.fontsizeCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 4, max = 30, initial = 10)
+
+        # font
+        fontsizeText = wx.StaticText(
+            panel, id=wx.ID_ANY, label=_("Font size:"))
+        self.fontsizeCtrl = wx.SpinCtrl(
+            panel, id=wx.ID_ANY, min=4, max=30, initial=10)
         self.fontsizeCtrl.SetValue(self.scalebarDict['fontsize'])
-        
-        self.backgroundCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("transparent text background"))
+
+        self.backgroundCheck = wx.CheckBox(
+            panel, id=wx.ID_ANY, label=_("transparent text background"))
         if self.scalebarDict['background'] == 'y':
             self.backgroundCheck.SetValue(False)
         else:
             self.backgroundCheck.SetValue(True)
 
-        gridBagSizer.Add(sbTypeText, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.sbCombo, pos = (0,1), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
-        gridBagSizer.Add(sbSegmentsText, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.sbSegmentsCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(sbLabelsText1, pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.sbLabelsCtrl, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(sbLabelsText2, pos = (2,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(fontsizeText, pos = (3,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.fontsizeCtrl, pos = (3,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.backgroundCheck, pos = (4, 0), span = (1,3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        
-        sizer.Add(gridBagSizer, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+        gridBagSizer.Add(
+            sbTypeText, pos=(0, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.sbCombo, pos=(
+                0, 1), span=(
+                1, 2), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+        gridBagSizer.Add(
+            sbSegmentsText, pos=(1, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.sbSegmentsCtrl, pos=(1, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            sbLabelsText1, pos=(2, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.sbLabelsCtrl, pos=(2, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            sbLabelsText2, pos=(2, 2),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            fontsizeText, pos=(3, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.fontsizeCtrl, pos=(3, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.backgroundCheck, pos=(
+                4, 0), span=(
+                1, 3), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+
+        sizer.Add(
+            gridBagSizer,
+            proportion=1,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         panel.SetSizer(border)
-        
+
         return panel
-                           
+
     def update(self):
         """Save information from dialog"""
 
-        #units
-        currUnit = self.unitConv.findUnit(self.panel.units['unitsCtrl'].GetStringSelection())
+        # units
+        currUnit = self.unitConv.findUnit(
+            self.panel.units['unitsCtrl'].GetStringSelection())
         self.scalebarDict['unit'] = currUnit
         # position
         if self.panel.position['xCtrl'].GetValue():
-            x = self.panel.position['xCtrl'].GetValue() 
+            x = self.panel.position['xCtrl'].GetValue()
         else:
             x = self.scalebarDict['where'][0]
 
         if self.panel.position['yCtrl'].GetValue():
-            y = self.panel.position['yCtrl'].GetValue() 
+            y = self.panel.position['yCtrl'].GetValue()
         else:
             y = self.scalebarDict['where'][1]
 
-        x = self.unitConv.convert(value = float(self.panel.position['xCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
-        y = self.unitConv.convert(value = float(self.panel.position['yCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
-        
-        #style
-        self.scalebarDict['scalebar'] = self.sbCombo.GetClientData(self.sbCombo.GetSelection())
+        x = self.unitConv.convert(
+            value=float(
+                self.panel.position['xCtrl'].GetValue()),
+            fromUnit=currUnit,
+            toUnit='inch')
+        y = self.unitConv.convert(
+            value=float(
+                self.panel.position['yCtrl'].GetValue()),
+            fromUnit=currUnit,
+            toUnit='inch')
+
+        # style
+        self.scalebarDict['scalebar'] = self.sbCombo.GetClientData(
+            self.sbCombo.GetSelection())
         self.scalebarDict['segment'] = self.sbSegmentsCtrl.GetValue()
         self.scalebarDict['numbers'] = self.sbLabelsCtrl.GetValue()
         self.scalebarDict['fontsize'] = self.fontsizeCtrl.GetValue()
         if self.backgroundCheck.GetValue():
-            self.scalebarDict['background'] = 'n' 
+            self.scalebarDict['background'] = 'n'
         else:
             self.scalebarDict['background'] = 'y'
 
-        
         # size
-        
+
         # height
-        self.scalebarDict['unitsHeight'] = self.unitConv.findUnit(self.unitsHeight.GetStringSelection())
+        self.scalebarDict['unitsHeight'] = self.unitConv.findUnit(
+            self.unitsHeight.GetStringSelection())
         try:
-            height = float(self.heightTextCtrl.GetValue())  
-            height = self.unitConv.convert(value = height, fromUnit = self.scalebarDict['unitsHeight'], toUnit = 'inch') 
+            height = float(self.heightTextCtrl.GetValue())
+            height = self.unitConv.convert(
+                value=height,
+                fromUnit=self.scalebarDict['unitsHeight'],
+                toUnit='inch')
         except (ValueError, SyntaxError):
-            height = 0.1 #default in inch
-        self.scalebarDict['height'] = height    
-        
-        #length
+            height = 0.1  # default in inch
+        self.scalebarDict['height'] = height
+
+        # length
         if self.unitsLength.GetSelection() == 0:
             selected = 'auto'
         else:
-            selected = self.unitConv.findUnit(self.unitsLength.GetStringSelection())
+            selected = self.unitConv.findUnit(
+                self.unitsLength.GetStringSelection())
             if selected == 'nautical miles':
                 selected = 'nautmiles'
         self.scalebarDict['unitsLength'] = selected
         try:
             length = float(self.lengthTextCtrl.GetValue())
         except (ValueError, SyntaxError):
-            wx.MessageBox(message = _("Length of scale bar is not defined"),
-                                    caption = _('Invalid input'), style = wx.OK|wx.ICON_ERROR)
+            wx.MessageBox(
+                message=_("Length of scale bar is not defined"),
+                caption=_('Invalid input'),
+                style=wx.OK | wx.ICON_ERROR)
             return False
         self.scalebarDict['length'] = length
-            
+
         # estimation of size
         map = self.instruction.FindInstructionByType('map')
         if not map:
             map = self.instruction.FindInstructionByType('initMap')
         mapId = map.id
-         
-        rectSize = self.scalebar.EstimateSize(scalebarDict = self.scalebarDict,
-                                                                scale = self.instruction[mapId]['scale'])
-        self.scalebarDict['rect'] = Rect2D(x = x, y = y, width = rectSize[0], height = rectSize[1])
-        self.scalebarDict['where'] = self.scalebarDict['rect'].GetCentre() 
 
+        rectSize = self.scalebar.EstimateSize(
+            scalebarDict=self.scalebarDict,
+            scale=self.instruction[mapId]['scale'])
+        self.scalebarDict['rect'] = Rect2D(
+            x=x, y=y, width=rectSize[0], height=rectSize[1])
+        self.scalebarDict['where'] = self.scalebarDict['rect'].GetCentre()
+
         if self.id not in self.instruction:
             scalebar = Scalebar(self.id)
             self.instruction.AddInstruction(scalebar)
         self.instruction[self.id].SetInstruction(self.scalebarDict)
         if self.id not in self.parent.objectId:
             self.parent.objectId.append(self.id)
-            
+
         return True
-    
+
     def updateDialog(self):
         """Update scalebar coordinates, after moving"""
         x, y = self.scalebarDict['rect'][:2]
-        currUnit = self.unitConv.findUnit(self.panel.units['unitsCtrl'].GetStringSelection())
-        x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
-        y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
+        currUnit = self.unitConv.findUnit(
+            self.panel.units['unitsCtrl'].GetStringSelection())
+        x = self.unitConv.convert(value=x, fromUnit='inch', toUnit=currUnit)
+        y = self.unitConv.convert(value=y, fromUnit='inch', toUnit=currUnit)
         self.panel.position['xCtrl'].SetValue("%5.3f" % x)
         self.panel.position['yCtrl'].SetValue("%5.3f" % y)
-        
- 
-        
+
+
 class TextDialog(PsmapDialog):
+
     def __init__(self, parent, id, settings):
-        PsmapDialog.__init__(self, parent = parent, id = id, title = "Text settings", settings = settings)
+        PsmapDialog.__init__(
+            self,
+            parent=parent,
+            id=id,
+            title="Text settings",
+            settings=settings)
         self.objectType = ('text',)
         if self.id is not None:
             self.textDict = self.instruction[id].GetInstruction()
         else:
-            self.id = wx.NewId()  
+            self.id = wx.NewId()
             text = Text(self.id)
             self.textDict = text.GetInstruction()
-            page = self.instruction.FindInstructionByType('page').GetInstruction()
-            self.textDict['where'] = page['Left'], page['Top'] 
-                
+            page = self.instruction.FindInstructionByType(
+                'page').GetInstruction()
+            self.textDict['where'] = page['Left'], page['Top']
+
         map = self.instruction.FindInstructionByType('map')
         if not map:
             map = self.instruction.FindInstructionByType('initMap')
         self.mapId = map.id
 
-        self.textDict['east'], self.textDict['north'] = PaperMapCoordinates(mapInstr = map, x = self.textDict['where'][0], y = self.textDict['where'][1], paperToMap = True)
-        
-        notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)     
+        self.textDict['east'], self.textDict['north'] = PaperMapCoordinates(
+            mapInstr=map, x=self.textDict['where'][0],
+            y=self.textDict['where'][1],
+            paperToMap=True)
+
+        notebook = wx.Notebook(parent=self, id=wx.ID_ANY, style=wx.BK_DEFAULT)
         self.textPanel = self._textPanel(notebook)
         self.positionPanel = self._positionPanel(notebook)
         self.OnBackground(None)
@@ -3692,212 +5168,375 @@
         self.OnBorder(None)
         self.OnPositionType(None)
         self.OnRotation(None)
-     
+
         self._layout(notebook)
 
     def _textPanel(self, notebook):
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL)
-        notebook.AddPage(page = panel, text = _("Text"))
-        
+        panel = wx.Panel(parent=notebook, id=wx.ID_ANY, style=wx.TAB_TRAVERSAL)
+        notebook.AddPage(page=panel, text=_("Text"))
+
         border = wx.BoxSizer(wx.VERTICAL)
-        
-        # text entry    
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Text"))
+
+        # text entry
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Text"))
         sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
-        
-        textLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("Enter text:"))
-        self.textCtrl = ExpandoTextCtrl(panel, id = wx.ID_ANY, value = self.textDict['text'])
-        
-        sizer.Add(textLabel, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
-        sizer.Add(self.textCtrl, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)        
-        
-        #font       
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Font settings"))
+
+        textLabel = wx.StaticText(panel, id=wx.ID_ANY, label=_("Enter text:"))
+        self.textCtrl = ExpandoTextCtrl(
+            panel, id=wx.ID_ANY, value=self.textDict['text'])
+
+        sizer.Add(
+            textLabel,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5)
+        sizer.Add(
+            self.textCtrl,
+            proportion=1,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
+        # font
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Font settings"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        flexGridSizer = wx.FlexGridSizer (rows = 3, cols = 2, hgap = 5, vgap = 5)
-        
-        self.AddFont(parent = panel, dialogDict = self.textDict)
-        
-        flexGridSizer.Add(panel.font['fontLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        flexGridSizer.Add(panel.font['fontCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        flexGridSizer.Add(panel.font['fontSizeLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        flexGridSizer.Add(panel.font['fontSizeCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        flexGridSizer.Add(panel.font['colorLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)        
-        flexGridSizer.Add(panel.font['colorCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
+        flexGridSizer = wx.FlexGridSizer(rows=3, cols=2, hgap=5, vgap=5)
+
+        self.AddFont(parent=panel, dialogDict=self.textDict)
+
+        flexGridSizer.Add(
+            panel.font['fontLabel'],
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+        flexGridSizer.Add(
+            panel.font['fontCtrl'],
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+        flexGridSizer.Add(
+            panel.font['fontSizeLabel'],
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+        flexGridSizer.Add(
+            panel.font['fontSizeCtrl'],
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+        flexGridSizer.Add(
+            panel.font['colorLabel'],
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+        flexGridSizer.Add(
+            panel.font['colorCtrl'],
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
         flexGridSizer.AddGrowableCol(1)
-        
-        sizer.Add(item = flexGridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
-        #text effects        
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Text effects"))
+
+        sizer.Add(
+            item=flexGridSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=1)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
+        # text effects
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Text effects"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
-        
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
+
         self.effect = {}
-        self.effect['backgroundCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("text background"))
-        self.effect['backgroundColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
-        
-        self.effect['highlightCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("highlight"))
-        self.effect['highlightColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
-        self.effect['highlightWidth'] = wx.SpinCtrl(panel, id = wx.ID_ANY, size = self.spinCtrlSize, min = 0, max = 5, initial = 1)
-        self.effect['highlightWidthLabel'] = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width (pts):"))
-        
-        self.effect['borderCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("text border"))
-        self.effect['borderColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
-        self.effect['borderWidth'] = wx.SpinCtrl(panel, id = wx.ID_ANY, size = self.spinCtrlSize, min = 1, max = 25, initial = 1)
-        self.effect['borderWidthLabel'] = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width (pts):"))
+        self.effect['backgroundCtrl'] = wx.CheckBox(
+            panel, id=wx.ID_ANY, label=_("text background"))
+        self.effect['backgroundColor'] = wx.ColourPickerCtrl(
+            panel, id=wx.ID_ANY)
 
-        #set values
-        if self.textDict['background'] == None:
+        self.effect['highlightCtrl'] = wx.CheckBox(
+            panel, id=wx.ID_ANY, label=_("highlight"))
+        self.effect['highlightColor'] = wx.ColourPickerCtrl(
+            panel, id=wx.ID_ANY)
+        self.effect['highlightWidth'] = wx.SpinCtrl(
+            panel, id=wx.ID_ANY, size=self.spinCtrlSize, min=0, max=5, initial=1)
+        self.effect['highlightWidthLabel'] = wx.StaticText(
+            panel, id=wx.ID_ANY, label=_("Width (pts):"))
+
+        self.effect['borderCtrl'] = wx.CheckBox(
+            panel, id=wx.ID_ANY, label=_("text border"))
+        self.effect['borderColor'] = wx.ColourPickerCtrl(panel, id=wx.ID_ANY)
+        self.effect['borderWidth'] = wx.SpinCtrl(
+            panel, id=wx.ID_ANY, size=self.spinCtrlSize, min=1, max=25, initial=1)
+        self.effect['borderWidthLabel'] = wx.StaticText(
+            panel, id=wx.ID_ANY, label=_("Width (pts):"))
+
+        # set values
+        if self.textDict['background'] is None:
             self.textDict['background'] = 'none'
         if self.textDict['background'] != 'none':
-            self.effect['backgroundCtrl'].SetValue(True) 
-            self.effect['backgroundColor'].SetColour(convertRGB(self.textDict['background']))
+            self.effect['backgroundCtrl'].SetValue(True)
+            self.effect['backgroundColor'].SetColour(
+                convertRGB(self.textDict['background']))
         else:
             self.effect['backgroundCtrl'].SetValue(False)
             self.effect['backgroundColor'].SetColour(convertRGB('white'))
 
-        if self.textDict['hcolor'] == None:
-             self.textDict['hcolor'] = 'none'
+        if self.textDict['hcolor'] is None:
+            self.textDict['hcolor'] = 'none'
         if self.textDict['hcolor'] != 'none':
-            self.effect['highlightCtrl'].SetValue(True) 
-            self.effect['highlightColor'].SetColour(convertRGB(self.textDict['hcolor']))
+            self.effect['highlightCtrl'].SetValue(True)
+            self.effect['highlightColor'].SetColour(
+                convertRGB(self.textDict['hcolor']))
         else:
             self.effect['highlightCtrl'].SetValue(False)
             self.effect['highlightColor'].SetColour(convertRGB('grey'))
 
         self.effect['highlightWidth'].SetValue(float(self.textDict['hwidth']))
-        
-        if self.textDict['border'] == None:
+
+        if self.textDict['border'] is None:
             self.textDict['border'] = 'none'
         if self.textDict['border'] != 'none':
-            self.effect['borderCtrl'].SetValue(True) 
-            self.effect['borderColor'].SetColour(convertRGB(self.textDict['border'])) 
+            self.effect['borderCtrl'].SetValue(True)
+            self.effect['borderColor'].SetColour(
+                convertRGB(self.textDict['border']))
         else:
             self.effect['borderCtrl'].SetValue(False)
             self.effect['borderColor'].SetColour(convertRGB('black'))
 
         self.effect['borderWidth'].SetValue(float(self.textDict['width']))
-        
-        gridBagSizer.Add(self.effect['backgroundCtrl'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.effect['backgroundColor'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.effect['highlightCtrl'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.effect['highlightColor'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.effect['highlightWidthLabel'], pos = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.effect['highlightWidth'], pos = (1,3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.effect['borderCtrl'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.effect['borderColor'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.effect['borderWidthLabel'], pos = (2,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizer.Add(self.effect['borderWidth'], pos = (2,3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        
-        sizer.Add(item = gridBagSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+
+        gridBagSizer.Add(self.effect['backgroundCtrl'], pos=(
+            0, 0), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(self.effect['backgroundColor'], pos=(
+            0, 1), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(self.effect['highlightCtrl'], pos=(
+            1, 0), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(self.effect['highlightColor'], pos=(
+            1, 1), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(
+            self.effect['highlightWidthLabel'], pos=(
+                1, 2), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(self.effect['highlightWidth'], pos=(
+            1, 3), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(self.effect['borderCtrl'], pos=(
+            2, 0), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(self.effect['borderColor'], pos=(
+            2, 1), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(self.effect['borderWidthLabel'], pos=(
+            2, 2), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizer.Add(self.effect['borderWidth'], pos=(
+            2, 3), flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+
+        sizer.Add(
+            item=gridBagSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=1)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         self.Bind(EVT_ETC_LAYOUT_NEEDED, self.OnRefit, self.textCtrl)
-        self.Bind(wx.EVT_CHECKBOX, self.OnBackground, self.effect['backgroundCtrl'])
-        self.Bind(wx.EVT_CHECKBOX, self.OnHighlight, self.effect['highlightCtrl'])
+        self.Bind(
+            wx.EVT_CHECKBOX,
+            self.OnBackground,
+            self.effect['backgroundCtrl'])
+        self.Bind(
+            wx.EVT_CHECKBOX,
+            self.OnHighlight,
+            self.effect['highlightCtrl'])
         self.Bind(wx.EVT_CHECKBOX, self.OnBorder, self.effect['borderCtrl'])
-        
+
         panel.SetSizer(border)
         panel.Fit()
-        
-        return panel 
-        
+
+        return panel
+
     def _positionPanel(self, notebook):
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL)
-        notebook.AddPage(page = panel, text = _("Position"))
+        panel = wx.Panel(parent=notebook, id=wx.ID_ANY, style=wx.TAB_TRAVERSAL)
+        notebook.AddPage(page=panel, text=_("Position"))
 
-        border = wx.BoxSizer(wx.VERTICAL) 
+        border = wx.BoxSizer(wx.VERTICAL)
 
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Position"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Position"))
         sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
-        gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
-        
-        #Position
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
+
+        # Position
         self.AddExtendedPosition(panel, gridBagSizer, self.textDict)
-        
-        #offset
-        box3   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " %_("Offset"))
+
+        # offset
+        box3 = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Offset"))
         sizerO = wx.StaticBoxSizer(box3, wx.VERTICAL)
-        gridBagSizerO = wx.GridBagSizer (hgap = 5, vgap = 5)
-        self.xoffLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("horizontal (pts):"))
-        self.yoffLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("vertical (pts):"))
-        self.xoffCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, size = (50, -1), min = -50, max = 50, initial = 0)
-        self.yoffCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, size = (50, -1), min = -50, max = 50, initial = 0) 
-        self.xoffCtrl.SetValue(self.textDict['xoffset'])       
+        gridBagSizerO = wx.GridBagSizer(hgap=5, vgap=5)
+        self.xoffLabel = wx.StaticText(
+            panel, id=wx.ID_ANY, label=_("horizontal (pts):"))
+        self.yoffLabel = wx.StaticText(
+            panel, id=wx.ID_ANY, label=_("vertical (pts):"))
+        self.xoffCtrl = wx.SpinCtrl(
+            panel, id=wx.ID_ANY, size=(50, -1),
+            min=-50, max=50, initial=0)
+        self.yoffCtrl = wx.SpinCtrl(
+            panel, id=wx.ID_ANY, size=(50, -1),
+            min=-50, max=50, initial=0)
+        self.xoffCtrl.SetValue(self.textDict['xoffset'])
         self.yoffCtrl.SetValue(self.textDict['yoffset'])
-        gridBagSizerO.Add(self.xoffLabel, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizerO.Add(self.yoffLabel, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizerO.Add(self.xoffCtrl, pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridBagSizerO.Add(self.yoffCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        
-        sizerO.Add(gridBagSizerO, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        gridBagSizer.Add(sizerO, pos = (3,0), flag = wx.ALIGN_CENTER_HORIZONTAL|wx.EXPAND, border = 0)
+        gridBagSizerO.Add(
+            self.xoffLabel, pos=(0, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizerO.Add(
+            self.yoffLabel, pos=(1, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizerO.Add(
+            self.xoffCtrl, pos=(0, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+        gridBagSizerO.Add(
+            self.yoffCtrl, pos=(1, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL, border=0)
+
+        sizerO.Add(
+            gridBagSizerO,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        gridBagSizer.Add(
+            sizerO,
+            pos=(
+                3,
+                0),
+            flag=wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND,
+            border=0)
         # reference point
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " %_(" Reference point"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _(" Reference point"))
         sizerR = wx.StaticBoxSizer(box, wx.VERTICAL)
-        flexSizer = wx.FlexGridSizer(rows = 3, cols = 3, hgap = 5, vgap = 5)
+        flexSizer = wx.FlexGridSizer(rows=3, cols=3, hgap=5, vgap=5)
         ref = []
         for row in ["upper", "center", "lower"]:
             for col in ["left", "center", "right"]:
                 ref.append(row + " " + col)
-        self.radio = [wx.RadioButton(panel, id = wx.ID_ANY, label = '', style = wx.RB_GROUP, name = ref[0])]
+        self.radio = [
+            wx.RadioButton(
+                panel,
+                id=wx.ID_ANY,
+                label='',
+                style=wx.RB_GROUP,
+                name=ref[0])]
         self.radio[0].SetValue(False)
-        flexSizer.Add(self.radio[0], proportion = 0, flag = wx.ALIGN_CENTER, border = 0)
-        for i in range(1,9):
-            self.radio.append(wx.RadioButton(panel, id = wx.ID_ANY, label = '', name = ref[i]))
+        flexSizer.Add(
+            self.radio[0],
+            proportion=0,
+            flag=wx.ALIGN_CENTER,
+            border=0)
+        for i in range(1, 9):
+            self.radio.append(
+                wx.RadioButton(
+                    panel,
+                    id=wx.ID_ANY,
+                    label='',
+                    name=ref[i]))
             self.radio[-1].SetValue(False)
-            flexSizer.Add(self.radio[-1], proportion = 0, flag = wx.ALIGN_CENTER, border = 0)
+            flexSizer.Add(self.radio[-1], proportion=0,
+                          flag=wx.ALIGN_CENTER, border=0)
         self.FindWindowByName(self.textDict['ref']).SetValue(True)
         flexSizer.AddGrowableCol(0)
         flexSizer.AddGrowableCol(1)
         flexSizer.AddGrowableCol(2)
-                
-        sizerR.Add(flexSizer, proportion = 1, flag = wx.EXPAND, border = 0)
-        gridBagSizer.Add(sizerR, pos = (3,1), flag = wx.ALIGN_LEFT|wx.EXPAND, border = 0)
+
+        sizerR.Add(flexSizer, proportion=1, flag=wx.EXPAND, border=0)
+        gridBagSizer.Add(
+            sizerR, pos=(3, 1),
+            flag=wx.ALIGN_LEFT | wx.EXPAND, border=0)
         gridBagSizer.AddGrowableCol(0)
         gridBagSizer.AddGrowableCol(1)
-        
-        sizer.Add(gridBagSizer, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-                
-        #rotation
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Text rotation"))
+
+        sizer.Add(
+            gridBagSizer,
+            proportion=1,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
+        # rotation
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Text rotation"))
         sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
 
-        self.rotCtrl = wx.CheckBox(panel, id = wx.ID_ANY, label = _("rotate text (counterclockwise)"))
-        self.rotValue = wx.SpinCtrl(panel, wx.ID_ANY, size = (50, -1), min = 0, max = 360, initial = 0)
+        self.rotCtrl = wx.CheckBox(
+            panel,
+            id=wx.ID_ANY,
+            label=_("rotate text (counterclockwise)"))
+        self.rotValue = wx.SpinCtrl(
+            panel, wx.ID_ANY, size=(50, -1),
+            min=0, max=360, initial=0)
         if self.textDict['rotate']:
             self.rotValue.SetValue(int(self.textDict['rotate']))
             self.rotCtrl.SetValue(True)
         else:
             self.rotValue.SetValue(0)
             self.rotCtrl.SetValue(False)
-        sizer.Add(self.rotCtrl, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT|wx.ALL, border = 5)
-        sizer.Add(self.rotValue, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT|wx.ALL, border = 5)
-        
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+        sizer.Add(
+            self.rotCtrl,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT | wx.ALL,
+            border=5)
+        sizer.Add(
+            self.rotValue,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT | wx.ALL,
+            border=5)
+
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         panel.SetSizer(border)
         panel.Fit()
-          
-        self.Bind(wx.EVT_RADIOBUTTON, self.OnPositionType, panel.position['toPaper']) 
-        self.Bind(wx.EVT_RADIOBUTTON, self.OnPositionType, panel.position['toMap'])
+
+        self.Bind(
+            wx.EVT_RADIOBUTTON,
+            self.OnPositionType,
+            panel.position['toPaper'])
+        self.Bind(
+            wx.EVT_RADIOBUTTON,
+            self.OnPositionType,
+            panel.position['toMap'])
         self.Bind(wx.EVT_CHECKBOX, self.OnRotation, self.rotCtrl)
-        
+
         return panel
-     
+
     def OnRefit(self, event):
         self.Fit()
-        
+
     def OnRotation(self, event):
         if self.rotCtrl.GetValue():
             self.rotValue.Enable()
-        else: 
+        else:
             self.rotValue.Disable()
-            
+
     def OnPositionType(self, event):
         if self.positionPanel.position['toPaper'].GetValue():
             for widget in self.gridBagSizerP.GetChildren():
@@ -3909,14 +5548,14 @@
                 widget.GetWindow().Enable()
             for widget in self.gridBagSizerP.GetChildren():
                 widget.GetWindow().Disable()
-                
+
     def OnBackground(self, event):
         if self.effect['backgroundCtrl'].GetValue():
             self.effect['backgroundColor'].Enable()
             self.update()
         else:
             self.effect['backgroundColor'].Disable()
-    
+
     def OnHighlight(self, event):
         if self.effect['highlightCtrl'].GetValue():
             self.effect['highlightColor'].Enable()
@@ -3927,7 +5566,7 @@
             self.effect['highlightColor'].Disable()
             self.effect['highlightWidth'].Disable()
             self.effect['highlightWidthLabel'].Disable()
-            
+
     def OnBorder(self, event):
         if self.effect['borderCtrl'].GetValue():
             self.effect['borderColor'].Enable()
@@ -3938,35 +5577,37 @@
             self.effect['borderColor'].Disable()
             self.effect['borderWidth'].Disable()
             self.effect['borderWidthLabel'].Disable()
-            
-    def update(self): 
-        #text
+
+    def update(self):
+        # text
         self.textDict['text'] = self.textCtrl.GetValue()
         if not self.textDict['text']:
             wx.MessageBox(_("No text entered!"), _("Error"))
             return False
-            
-        #font
-        self.textDict['font'] = self.textPanel.font['fontCtrl'].GetStringSelection()
-        self.textDict['fontsize'] = self.textPanel.font['fontSizeCtrl'].GetValue()
+
+        # font
+        self.textDict['font'] = self.textPanel.font[
+            'fontCtrl'].GetStringSelection()
+        self.textDict['fontsize'] = self.textPanel.font[
+            'fontSizeCtrl'].GetValue()
         color = self.textPanel.font['colorCtrl'].GetColour()
         self.textDict['color'] = convertRGB(color)
 
-        #effects
+        # effects
         if self.effect['backgroundCtrl'].GetValue():
             background = self.effect['backgroundColor'].GetColour()
             self.textDict['background'] = convertRGB(background)
         else:
-            self.textDict['background'] = 'none'        
-                
+            self.textDict['background'] = 'none'
+
         if self.effect['borderCtrl'].GetValue():
             border = self.effect['borderColor'].GetColour()
             self.textDict['border'] = convertRGB(border)
         else:
-            self.textDict['border'] = 'none' 
-                     
+            self.textDict['border'] = 'none'
+
         self.textDict['width'] = self.effect['borderWidth'].GetValue()
-        
+
         if self.effect['highlightCtrl'].GetValue():
             highlight = self.effect['highlightColor'].GetColour()
             self.textDict['hcolor'] = convertRGB(highlight)
@@ -3974,89 +5615,107 @@
             self.textDict['hcolor'] = 'none'
 
         self.textDict['hwidth'] = self.effect['highlightWidth'].GetValue()
-        
-        #offset
+
+        # offset
         self.textDict['xoffset'] = self.xoffCtrl.GetValue()
         self.textDict['yoffset'] = self.yoffCtrl.GetValue()
 
-        #position
+        # position
         if self.positionPanel.position['toPaper'].GetValue():
             self.textDict['XY'] = True
-            currUnit = self.unitConv.findUnit(self.positionPanel.units['unitsCtrl'].GetStringSelection())
+            currUnit = self.unitConv.findUnit(
+                self.positionPanel.units['unitsCtrl'].GetStringSelection())
             self.textDict['unit'] = currUnit
             if self.positionPanel.position['xCtrl'].GetValue():
-                x = self.positionPanel.position['xCtrl'].GetValue() 
+                x = self.positionPanel.position['xCtrl'].GetValue()
             else:
                 x = self.textDict['where'][0]
 
             if self.positionPanel.position['yCtrl'].GetValue():
-                y = self.positionPanel.position['yCtrl'].GetValue() 
+                y = self.positionPanel.position['yCtrl'].GetValue()
             else:
                 y = self.textDict['where'][1]
 
-            x = self.unitConv.convert(value = float(x), fromUnit = currUnit, toUnit = 'inch')
-            y = self.unitConv.convert(value = float(y), fromUnit = currUnit, toUnit = 'inch')
+            x = self.unitConv.convert(
+                value=float(x), fromUnit=currUnit, toUnit='inch')
+            y = self.unitConv.convert(
+                value=float(y), fromUnit=currUnit, toUnit='inch')
             self.textDict['where'] = x, y
-            self.textDict['east'], self.textDict['north'] = PaperMapCoordinates(self.instruction[self.mapId], x, y, paperToMap = True)
+            self.textDict['east'], self.textDict['north'] = PaperMapCoordinates(
+                self.instruction[self.mapId], x, y, paperToMap=True)
         else:
             self.textDict['XY'] = False
             if self.positionPanel.position['eCtrl'].GetValue():
-                self.textDict['east'] = self.positionPanel.position['eCtrl'].GetValue() 
+                self.textDict['east'] = self.positionPanel.position[
+                    'eCtrl'].GetValue()
             else:
                 self.textDict['east'] = self.textDict['east']
 
             if self.positionPanel.position['nCtrl'].GetValue():
-                self.textDict['north'] = self.positionPanel.position['nCtrl'].GetValue() 
+                self.textDict['north'] = self.positionPanel.position[
+                    'nCtrl'].GetValue()
             else:
                 self.textDict['north'] = self.textDict['north']
 
-            self.textDict['where'] = PaperMapCoordinates(mapInstr = self.instruction[self.mapId], x = float(self.textDict['east']),
-                                                            y = float(self.textDict['north']), paperToMap = False)
-        #rotation
+            self.textDict['where'] = PaperMapCoordinates(
+                mapInstr=self.instruction[
+                    self.mapId], x=float(
+                    self.textDict['east']), y=float(
+                    self.textDict['north']), paperToMap=False)
+        # rotation
         if self.rotCtrl.GetValue():
             self.textDict['rotate'] = self.rotValue.GetValue()
         else:
             self.textDict['rotate'] = None
-        #reference point
+        # reference point
         for radio in self.radio:
             if radio.GetValue() == True:
                 self.textDict['ref'] = radio.GetName()
-                
+
         if self.id not in self.instruction:
             text = Text(self.id)
             self.instruction.AddInstruction(text)
         self.instruction[self.id].SetInstruction(self.textDict)
-        
+
         if self.id not in self.parent.objectId:
             self.parent.objectId.append(self.id)
 
 #        self.updateDialog()
 
         return True
-    
+
     def updateDialog(self):
         """Update text coordinates, after moving"""
         # XY coordinates
         x, y = self.textDict['where'][:2]
-        currUnit = self.unitConv.findUnit(self.positionPanel.units['unitsCtrl'].GetStringSelection())
-        x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
-        y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
+        currUnit = self.unitConv.findUnit(
+            self.positionPanel.units['unitsCtrl'].GetStringSelection())
+        x = self.unitConv.convert(value=x, fromUnit='inch', toUnit=currUnit)
+        y = self.unitConv.convert(value=y, fromUnit='inch', toUnit=currUnit)
         self.positionPanel.position['xCtrl'].SetValue("%5.3f" % x)
         self.positionPanel.position['yCtrl'].SetValue("%5.3f" % y)
         # EN coordinates
         e, n = self.textDict['east'], self.textDict['north']
-        self.positionPanel.position['eCtrl'].SetValue(str(self.textDict['east']))
-        self.positionPanel.position['nCtrl'].SetValue(str(self.textDict['north']))
-        
+        self.positionPanel.position['eCtrl'].SetValue(
+            str(self.textDict['east']))
+        self.positionPanel.position['nCtrl'].SetValue(
+            str(self.textDict['north']))
+
+
 class ImageDialog(PsmapDialog):
     """Dialog for setting image properties.
-    
+
     It's base dialog for North Arrow dialog.
     """
-    def __init__(self, parent, id, settings, imagePanelName = _("Image")):
-        PsmapDialog.__init__(self, parent = parent, id = id, title = "Image settings",
-                             settings = settings)
-        
+
+    def __init__(self, parent, id, settings, imagePanelName=_("Image")):
+        PsmapDialog.__init__(
+            self,
+            parent=parent,
+            id=id,
+            title="Image settings",
+            settings=settings)
+
         self.objectType = ('image',)
         if self.id is not None:
             self.imageObj = self.instruction[self.id]
@@ -4065,109 +5724,142 @@
             self.id = wx.NewId()
             self.imageObj = self._newObject()
             self.imageDict = self.imageObj.GetInstruction()
-            page = self.instruction.FindInstructionByType('page').GetInstruction()
-            self.imageDict['where'] = page['Left'], page['Top'] 
-                
+            page = self.instruction.FindInstructionByType(
+                'page').GetInstruction()
+            self.imageDict['where'] = page['Left'], page['Top']
+
         map = self.instruction.FindInstructionByType('map')
         if not map:
             map = self.instruction.FindInstructionByType('initMap')
         self.mapId = map.id
 
-        self.imageDict['east'], self.imageDict['north'] = PaperMapCoordinates(mapInstr = map, x = self.imageDict['where'][0], y = self.imageDict['where'][1], paperToMap = True)
-        
-        notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
+        self.imageDict['east'], self.imageDict['north'] = PaperMapCoordinates(
+            mapInstr=map, x=self.imageDict['where'][0],
+            y=self.imageDict['where'][1],
+            paperToMap=True)
+
+        notebook = wx.Notebook(parent=self, id=wx.ID_ANY, style=wx.BK_DEFAULT)
         self.imagePanelName = imagePanelName
         self.imagePanel = self._imagePanel(notebook)
         self.positionPanel = self._positionPanel(notebook)
         self.OnPositionType(None)
-        
+
         if self.imageDict['epsfile']:
-            self.imagePanel.image['dir'].SetValue(os.path.dirname(self.imageDict['epsfile']))
+            self.imagePanel.image['dir'].SetValue(
+                os.path.dirname(self.imageDict['epsfile']))
         else:
             self.imagePanel.image['dir'].SetValue(self._getImageDirectory())
         self.OnDirChanged(None)
-     
+
         self._layout(notebook)
-        
-        
+
     def _newObject(self):
         """Create corresponding instruction object"""
         return Image(self.id, self.instruction)
-        
+
     def _imagePanel(self, notebook):
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
-        notebook.AddPage(page = panel, text = self.imagePanelName)
+        panel = wx.Panel(
+            parent=notebook, id=wx.ID_ANY, size=(-1, -1),
+            style=wx.TAB_TRAVERSAL)
+        notebook.AddPage(page=panel, text=self.imagePanelName)
         border = wx.BoxSizer(wx.VERTICAL)
         #
         # choose image
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Image"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Image"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
+
         # choose directory
         panel.image = {}
         if self.imageDict['epsfile']:
             startDir = os.path.dirname(self.imageDict['epsfile'])
         else:
             startDir = self._getImageDirectory()
-        dir = filebrowse.DirBrowseButton(parent = panel, id = wx.ID_ANY,
-                                         labelText = _("Choose a directory:"),
-                                         dialogTitle = _("Choose a directory with images"),
-                                         buttonText = _('Browse'),
-                                         startDirectory = startDir,
-                                         changeCallback = self.OnDirChanged)
+        dir = filebrowse.DirBrowseButton(
+            parent=panel,
+            id=wx.ID_ANY,
+            labelText=_("Choose a directory:"),
+            dialogTitle=_("Choose a directory with images"),
+            buttonText=_('Browse'),
+            startDirectory=startDir,
+            changeCallback=self.OnDirChanged)
         panel.image['dir'] = dir
-       
-        
-        sizer.Add(item = dir, proportion = 0, flag = wx.EXPAND, border = 0)
-        
+
+        sizer.Add(item=dir, proportion=0, flag=wx.EXPAND, border=0)
+
         # image list
         hSizer = wx.BoxSizer(wx.HORIZONTAL)
-        
-        imageList = wx.ListBox(parent = panel, id = wx.ID_ANY)
+
+        imageList = wx.ListBox(parent=panel, id=wx.ID_ANY)
         panel.image['list'] = imageList
         imageList.Bind(wx.EVT_LISTBOX, self.OnImageSelectionChanged)
-        
-        hSizer.Add(item = imageList, proportion = 1, flag = wx.EXPAND | wx.RIGHT, border = 10)
-        
+
+        hSizer.Add(
+            item=imageList,
+            proportion=1,
+            flag=wx.EXPAND | wx.RIGHT,
+            border=10)
+
         # image preview
         vSizer = wx.BoxSizer(wx.VERTICAL)
         self.previewSize = (150, 150)
         img = wx.EmptyImage(*self.previewSize)
-        panel.image['preview'] = wx.StaticBitmap(parent = panel, id = wx.ID_ANY,
-                                                bitmap = wx.BitmapFromImage(img))
-        vSizer.Add(item = panel.image['preview'], proportion = 0, flag = wx.EXPAND | wx.BOTTOM, border = 5)
-        panel.image['sizeInfo'] = wx.StaticText(parent = panel, id = wx.ID_ANY)
-        vSizer.Add(item = panel.image['sizeInfo'], proportion = 0, flag = wx.ALIGN_CENTER, border = 0)
-        
-        hSizer.Add(item = vSizer, proportion = 0, flag = wx.EXPAND, border = 0)
-        sizer.Add(item = hSizer, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 3)
-        
-        epsInfo = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                label = _("Note: only EPS format supported"))
-        sizer.Add(item = epsInfo, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 3)
-        
-        
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+        panel.image['preview'] = wx.StaticBitmap(
+            parent=panel, id=wx.ID_ANY, bitmap=wx.BitmapFromImage(img))
+        vSizer.Add(
+            item=panel.image['preview'],
+            proportion=0,
+            flag=wx.EXPAND | wx.BOTTOM,
+            border=5)
+        panel.image['sizeInfo'] = wx.StaticText(parent=panel, id=wx.ID_ANY)
+        vSizer.Add(
+            item=panel.image['sizeInfo'],
+            proportion=0,
+            flag=wx.ALIGN_CENTER,
+            border=0)
+
+        hSizer.Add(item=vSizer, proportion=0, flag=wx.EXPAND, border=0)
+        sizer.Add(item=hSizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=3)
+
+        epsInfo = wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                label=_("Note: only EPS format supported"))
+        sizer.Add(
+            item=epsInfo,
+            proportion=0,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=3)
+
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         #
         # rotation
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Scale And Rotation"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Scale And Rotation"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
-        gridSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
-        
-        scaleLabel = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Scale:"))
+
+        gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
+
+        scaleLabel = wx.StaticText(
+            parent=panel, id=wx.ID_ANY, label=_("Scale:"))
         if fs:
-            panel.image['scale'] = fs.FloatSpin(panel, id = wx.ID_ANY, min_val = 0, max_val = 50,
-                                          increment = 0.5, value = 1, style = fs.FS_RIGHT, size = self.spinCtrlSize)
+            panel.image['scale'] = fs.FloatSpin(
+                panel, id=wx.ID_ANY, min_val=0, max_val=50, increment=0.5,
+                value=1, style=fs.FS_RIGHT, size=self.spinCtrlSize)
             panel.image['scale'].SetFormat("%f")
             panel.image['scale'].SetDigits(1)
         else:
-            panel.image['scale'] = wx.TextCtrl(panel, id = wx.ID_ANY, size = self.spinCtrlSize,
-                                                  validator = TCValidator(flag = 'DIGIT_ONLY'))
-        
+            panel.image['scale'] = wx.TextCtrl(
+                panel, id=wx.ID_ANY, size=self.spinCtrlSize,
+                validator=TCValidator(flag='DIGIT_ONLY'))
+
         if self.imageDict['scale']:
             if fs:
                 value = float(self.imageDict['scale'])
@@ -4179,84 +5871,125 @@
             else:
                 value = '0'
         panel.image['scale'].SetValue(value)
-            
-        gridSizer.Add(item = scaleLabel, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = panel.image['scale'], pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        
-        rotLabel = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Rotation angle (deg):"))
+
+        gridSizer.Add(
+            item=scaleLabel, pos=(0, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=panel.image['scale'],
+            pos=(0, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL)
+
+        rotLabel = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Rotation angle (deg):"))
         if fs:
-            panel.image['rotate'] = fs.FloatSpin(panel, id = wx.ID_ANY, min_val = 0, max_val = 360,
-                                          increment = 0.5, value = 0, style = fs.FS_RIGHT, size = self.spinCtrlSize)
+            panel.image['rotate'] = fs.FloatSpin(
+                panel, id=wx.ID_ANY, min_val=0, max_val=360, increment=0.5,
+                value=0, style=fs.FS_RIGHT, size=self.spinCtrlSize)
             panel.image['rotate'].SetFormat("%f")
             panel.image['rotate'].SetDigits(1)
         else:
-            panel.image['rotate'] = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = self.spinCtrlSize,
-                                                min = 0, max = 359, initial = 0)
-        panel.image['rotate'].SetToolTipString(_("Counterclockwise rotation in degrees"))
+            panel.image['rotate'] = wx.SpinCtrl(
+                parent=panel,
+                id=wx.ID_ANY,
+                size=self.spinCtrlSize,
+                min=0,
+                max=359,
+                initial=0)
+        panel.image['rotate'].SetToolTipString(
+            _("Counterclockwise rotation in degrees"))
         if self.imageDict['rotate']:
             panel.image['rotate'].SetValue(int(self.imageDict['rotate']))
         else:
             panel.image['rotate'].SetValue(0)
-            
-        gridSizer.Add(item = rotLabel, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridSizer.Add(item = panel.image['rotate'], pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        self._addConvergence(panel = panel, gridBagSizer = gridSizer)
-        sizer.Add(item = gridSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+
+        gridSizer.Add(
+            item=rotLabel,
+            pos=(
+                1,
+                0),
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+        gridSizer.Add(
+            item=panel.image['rotate'], pos=(
+                1, 1), flag=wx.ALIGN_CENTER_VERTICAL)
+
+        self._addConvergence(panel=panel, gridBagSizer=gridSizer)
+        sizer.Add(
+            item=gridSizer,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         panel.SetSizer(border)
         panel.Fit()
-        
+
         return panel
-        
+
     def _positionPanel(self, notebook):
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
-        notebook.AddPage(page = panel, text = _("Position"))
+        panel = wx.Panel(
+            parent=notebook, id=wx.ID_ANY, size=(-1, -1),
+            style=wx.TAB_TRAVERSAL)
+        notebook.AddPage(page=panel, text=_("Position"))
         border = wx.BoxSizer(wx.VERTICAL)
         #
         # set position
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Position"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Position"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
-        gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
-        
+
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
+
         self.AddExtendedPosition(panel, gridBagSizer, self.imageDict)
-        
-        self.Bind(wx.EVT_RADIOBUTTON, self.OnPositionType, panel.position['toPaper']) 
-        self.Bind(wx.EVT_RADIOBUTTON, self.OnPositionType, panel.position['toMap'])
-        
-        
+
+        self.Bind(
+            wx.EVT_RADIOBUTTON,
+            self.OnPositionType,
+            panel.position['toPaper'])
+        self.Bind(
+            wx.EVT_RADIOBUTTON,
+            self.OnPositionType,
+            panel.position['toMap'])
+
         gridBagSizer.AddGrowableCol(0)
         gridBagSizer.AddGrowableCol(1)
-        sizer.Add(gridBagSizer, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL| wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+        sizer.Add(
+            gridBagSizer,
+            proportion=1,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         panel.SetSizer(border)
         panel.Fit()
-        
+
         return panel
-        
+
     def OnDirChanged(self, event):
         """Image directory changed"""
         path = self.imagePanel.image['dir'].GetValue()
         try:
             files = os.listdir(path)
-        except OSError: # no such directory
+        except OSError:  # no such directory
             files = []
         imageList = []
-        
+
         # no setter for startDirectory?
         try:
             self.imagePanel.image['dir'].startDirectory = path
-        except AttributeError: # for sure
+        except AttributeError:  # for sure
             pass
         for file in files:
             if os.path.splitext(file)[1].lower() == '.eps':
                 imageList.append(file)
-        
+
         imageList.sort()
         self.imagePanel.image['list'].SetItems(imageList)
         if self.imageDict['epsfile']:
@@ -4265,7 +5998,7 @@
         elif imageList:
             self.imagePanel.image['list'].SetSelection(0)
         self.OnImageSelectionChanged(None)
-        
+
     def OnPositionType(self, event):
         if self.positionPanel.position['toPaper'].GetValue():
             for widget in self.gridBagSizerP.GetChildren():
@@ -4277,23 +6010,24 @@
                 widget.GetWindow().Enable()
             for widget in self.gridBagSizerP.GetChildren():
                 widget.GetWindow().Disable()
-                
+
     def _getImageDirectory(self):
         """Default image directory"""
         return os.getcwd()
-        
+
     def _addConvergence(self, panel, gridBagSizer):
         pass
-        
+
     def OnImageSelectionChanged(self, event):
         """Image selected, show preview and size"""
-        if not self.imagePanel.image['dir']: # event is emitted when closing dialog an it causes error
+        if not self.imagePanel.image[
+                'dir']:  # event is emitted when closing dialog an it causes error
             return
-            
+
         if not havePILImage:
             self.DrawWarningText(_("PIL\nmissing"))
             return
-        
+
         imageName = self.imagePanel.image['list'].GetStringSelection()
         if not imageName:
             self.ClearPreview()
@@ -4302,7 +6036,7 @@
         file = os.path.join(basePath, imageName)
         if not os.path.exists(file):
             return
-            
+
         if os.path.splitext(file)[1].lower() == '.eps':
             try:
                 pImg = PILImage.open(file)
@@ -4311,18 +6045,18 @@
                     pImg.load = types.MethodType(loadPSForWindows, pImg)
                 img = PilImageToWxImage(pImg)
             except IOError as e:
-                GError(message = _("Unable to read file %s") % file)
+                GError(message=_("Unable to read file %s") % file)
                 self.ClearPreview()
                 return
             self.SetSizeInfoLabel(img)
             img = self.ScaleToPreview(img)
             bitmap = img.ConvertToBitmap()
             self.DrawBitmap(bitmap)
-            
+
         else:
             # TODO: read other formats and convert by PIL to eps
             pass
-    
+
     def ScaleToPreview(self, img):
         """Scale image to preview size"""
         w = img.GetWidth()
@@ -4336,7 +6070,7 @@
             newH = self.previewSize[0]
             newW = self.previewSize[0] * w / h
         return img.Scale(newW, newH, wx.IMAGE_QUALITY_HIGH)
-        
+
     def DrawWarningText(self, warning):
         """Draw text on preview window"""
         buffer = wx.EmptyBitmap(*self.previewSize)
@@ -4350,10 +6084,11 @@
         dc.DrawText(warning, posX, posY)
         self.imagePanel.image['preview'].SetBitmap(buffer)
         dc.SelectObject(wx.NullBitmap)
-        
+
     def DrawBitmap(self, bitmap):
         """Draw bitmap, center it if smaller than preview size"""
-        if bitmap.GetWidth() <= self.previewSize[0] and bitmap.GetHeight() <= self.previewSize[1]:
+        if bitmap.GetWidth() <= self.previewSize[
+                0] and bitmap.GetHeight() <= self.previewSize[1]:
             buffer = wx.EmptyBitmap(*self.previewSize)
             dc = wx.MemoryDC()
             dc.SelectObject(buffer)
@@ -4367,14 +6102,15 @@
         else:
             self.imagePanel.image['preview'].SetBitmap(bitmap)
         self.imagePanel.Refresh()
-            
+
     def SetSizeInfoLabel(self, image):
         """Update image size label"""
-        self.imagePanel.image['sizeInfo'].SetLabel(_("size: %(width)s x %(height)s pts") % \
-                                                       { 'width'  : image.GetWidth(),
-                                                         'height' : image.GetHeight() })
+        self.imagePanel.image['sizeInfo'].SetLabel(
+            _("size: %(width)s x %(height)s pts") %
+            {'width': image.GetWidth(),
+             'height': image.GetHeight()})
         self.imagePanel.image['sizeInfo'].GetContainingSizer().Layout()
-        
+
     def ClearPreview(self):
         """Clear preview window"""
         buffer = wx.EmptyBitmap(*self.previewSize)
@@ -4386,142 +6122,159 @@
         mask = wx.Mask(buffer, wx.WHITE)
         buffer.SetMask(mask)
         self.imagePanel.image['preview'].SetBitmap(buffer)
-        
-    def update(self): 
+
+    def update(self):
         # epsfile
         selected = self.imagePanel.image['list'].GetStringSelection()
         basePath = self.imagePanel.image['dir'].GetValue()
         if not selected:
-            GMessage(parent = self, message = _("No image selected."))
+            GMessage(parent=self, message=_("No image selected."))
             return False
-            
+
         self.imageDict['epsfile'] = os.path.join(basePath, selected)
-        
-        #position
+
+        # position
         if self.positionPanel.position['toPaper'].GetValue():
             self.imageDict['XY'] = True
-            currUnit = self.unitConv.findUnit(self.positionPanel.units['unitsCtrl'].GetStringSelection())
+            currUnit = self.unitConv.findUnit(
+                self.positionPanel.units['unitsCtrl'].GetStringSelection())
             self.imageDict['unit'] = currUnit
             if self.positionPanel.position['xCtrl'].GetValue():
-                x = self.positionPanel.position['xCtrl'].GetValue() 
+                x = self.positionPanel.position['xCtrl'].GetValue()
             else:
                 x = self.imageDict['where'][0]
 
             if self.positionPanel.position['yCtrl'].GetValue():
-                y = self.positionPanel.position['yCtrl'].GetValue() 
+                y = self.positionPanel.position['yCtrl'].GetValue()
             else:
                 y = self.imageDict['where'][1]
 
-            x = self.unitConv.convert(value = float(x), fromUnit = currUnit, toUnit = 'inch')
-            y = self.unitConv.convert(value = float(y), fromUnit = currUnit, toUnit = 'inch')
+            x = self.unitConv.convert(
+                value=float(x), fromUnit=currUnit, toUnit='inch')
+            y = self.unitConv.convert(
+                value=float(y), fromUnit=currUnit, toUnit='inch')
             self.imageDict['where'] = x, y
-            
+
         else:
             self.imageDict['XY'] = False
             if self.positionPanel.position['eCtrl'].GetValue():
-                e = self.positionPanel.position['eCtrl'].GetValue() 
+                e = self.positionPanel.position['eCtrl'].GetValue()
             else:
                 self.imageDict['east'] = self.imageDict['east']
 
             if self.positionPanel.position['nCtrl'].GetValue():
-                n = self.positionPanel.position['nCtrl'].GetValue() 
+                n = self.positionPanel.position['nCtrl'].GetValue()
             else:
                 self.imageDict['north'] = self.imageDict['north']
 
-            x, y = PaperMapCoordinates(mapInstr = self.instruction[self.mapId], x = float(self.imageDict['east']),
-                                       y = float(self.imageDict['north']), paperToMap = False)
+            x, y = PaperMapCoordinates(
+                mapInstr=self.instruction[
+                    self.mapId], x=float(
+                    self.imageDict['east']), y=float(
+                    self.imageDict['north']), paperToMap=False)
 
-        #rotation
+        # rotation
         rot = self.imagePanel.image['rotate'].GetValue()
         if rot == 0:
             self.imageDict['rotate'] = None
         else:
             self.imageDict['rotate'] = rot
-        
-        #scale
+
+        # scale
         self.imageDict['scale'] = self.imagePanel.image['scale'].GetValue()
-                
+
         # scale
         w, h = self.imageObj.GetImageOrigSize(self.imageDict['epsfile'])
         if self.imageDict['rotate']:
-            self.imageDict['size'] = BBoxAfterRotation(w, h, self.imageDict['rotate'])
+            self.imageDict['size'] = BBoxAfterRotation(
+                w, h, self.imageDict['rotate'])
         else:
             self.imageDict['size'] = w, h
-            
-        w = self.unitConv.convert(value = self.imageDict['size'][0],
-                                  fromUnit = 'point', toUnit = 'inch')
-        h = self.unitConv.convert(value = self.imageDict['size'][1],
-                                  fromUnit = 'point', toUnit = 'inch')
-                                  
-    
-        self.imageDict['rect'] = Rect2D(x = x, y = y,
-                                        width = w * self.imageDict['scale'],
-                                        height = h * self.imageDict['scale'])
-        
+
+        w = self.unitConv.convert(value=self.imageDict['size'][0],
+                                  fromUnit='point', toUnit='inch')
+        h = self.unitConv.convert(value=self.imageDict['size'][1],
+                                  fromUnit='point', toUnit='inch')
+
+        self.imageDict['rect'] = Rect2D(x=x, y=y,
+                                        width=w * self.imageDict['scale'],
+                                        height=h * self.imageDict['scale'])
+
         if self.id not in self.instruction:
             image = self._newObject()
             self.instruction.AddInstruction(image)
         self.instruction[self.id].SetInstruction(self.imageDict)
-        
+
         if self.id not in self.parent.objectId:
             self.parent.objectId.append(self.id)
 
         return True
-        
+
     def updateDialog(self):
         """Update text coordinates, after moving"""
         # XY coordinates
         x, y = self.imageDict['where'][:2]
-        currUnit = self.unitConv.findUnit(self.positionPanel.units['unitsCtrl'].GetStringSelection())
-        x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
-        y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
+        currUnit = self.unitConv.findUnit(
+            self.positionPanel.units['unitsCtrl'].GetStringSelection())
+        x = self.unitConv.convert(value=x, fromUnit='inch', toUnit=currUnit)
+        y = self.unitConv.convert(value=y, fromUnit='inch', toUnit=currUnit)
         self.positionPanel.position['xCtrl'].SetValue("%5.3f" % x)
         self.positionPanel.position['yCtrl'].SetValue("%5.3f" % y)
         # EN coordinates
         e, n = self.imageDict['east'], self.imageDict['north']
-        self.positionPanel.position['eCtrl'].SetValue(str(self.imageDict['east']))
-        self.positionPanel.position['nCtrl'].SetValue(str(self.imageDict['north']))
-        
-        
+        self.positionPanel.position['eCtrl'].SetValue(
+            str(self.imageDict['east']))
+        self.positionPanel.position['nCtrl'].SetValue(
+            str(self.imageDict['north']))
+
+
 class NorthArrowDialog(ImageDialog):
+
     def __init__(self, parent, id, settings):
-        ImageDialog.__init__(self, parent = parent, id = id, settings = settings,
-                             imagePanelName = _("North Arrow"))
-        
+        ImageDialog.__init__(self, parent=parent, id=id, settings=settings,
+                             imagePanelName=_("North Arrow"))
+
         self.objectType = ('northArrow',)
         self.SetTitle(_("North Arrow settings"))
-    
+
     def _newObject(self):
         return NorthArrow(self.id, self.instruction)
-        
+
     def _getImageDirectory(self):
         gisbase = os.getenv("GISBASE")
         return os.path.join(gisbase, 'etc', 'paint', 'decorations')
-    
+
     def _addConvergence(self, panel, gridBagSizer):
-        convergence = wx.Button(parent = panel, id = wx.ID_ANY,
-                                               label = _("Compute convergence"))
-        gridBagSizer.Add(item = convergence, pos = (1, 2),
-                      flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
+        convergence = wx.Button(parent=panel, id=wx.ID_ANY,
+                                label=_("Compute convergence"))
+        gridBagSizer.Add(item=convergence, pos=(1, 2),
+                         flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
         convergence.Bind(wx.EVT_BUTTON, self.OnConvergence)
         panel.image['convergence'] = convergence
-        
+
     def OnConvergence(self, event):
-        ret = RunCommand('g.region', read = True, flags = 'ng')
+        ret = RunCommand('g.region', read=True, flags='ng')
         if ret:
             convergence = float(ret.strip().split('=')[1])
             if convergence < 0:
                 self.imagePanel.image['rotate'].SetValue(abs(convergence))
             else:
                 self.imagePanel.image['rotate'].SetValue(360 - convergence)
-            
-        
+
+
 class PointDialog(PsmapDialog):
     """Dialog for setting point properties."""
-    def __init__(self, parent, id, settings, coordinates = None, pointPanelName = _("Point")):
-        PsmapDialog.__init__(self, parent = parent, id = id, title = "Point settings",
-                             settings = settings)
-        
+
+    def __init__(
+            self, parent, id, settings, coordinates=None,
+            pointPanelName=_("Point")):
+        PsmapDialog.__init__(
+            self,
+            parent=parent,
+            id=id,
+            title="Point settings",
+            settings=settings)
+
         self.objectType = ('point',)
         if self.id is not None:
             self.pointObj = self.instruction[self.id]
@@ -4530,173 +6283,279 @@
             self.id = wx.NewId()
             self.pointObj = Point(self.id)
             self.pointDict = self.pointObj.GetInstruction()
-            self.pointDict['where'] = coordinates 
+            self.pointDict['where'] = coordinates
         self.defaultDict = self.pointObj.defaultInstruction
-                
+
         mapObj = self.instruction.FindInstructionByType('map')
         if not mapObj:
             mapObj = self.instruction.FindInstructionByType('initMap')
         self.mapId = mapObj.id
-        
-        self.pointDict['east'], self.pointDict['north'] = PaperMapCoordinates(mapInstr = mapObj, x = self.pointDict['where'][0], y = self.pointDict['where'][1], paperToMap = True)
-        
-        notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
+
+        self.pointDict['east'], self.pointDict['north'] = PaperMapCoordinates(
+            mapInstr=mapObj, x=self.pointDict['where'][0],
+            y=self.pointDict['where'][1],
+            paperToMap=True)
+
+        notebook = wx.Notebook(parent=self, id=wx.ID_ANY, style=wx.BK_DEFAULT)
         self.pointPanelName = pointPanelName
         self.pointPanel = self._pointPanel(notebook)
         self.positionPanel = self._positionPanel(notebook)
         self.OnPositionType(None)
-        
-     
+
         self._layout(notebook)
-        
+
     def _pointPanel(self, notebook):
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
-        notebook.AddPage(page = panel, text = self.pointPanelName)
+        panel = wx.Panel(
+            parent=notebook, id=wx.ID_ANY, size=(-1, -1),
+            style=wx.TAB_TRAVERSAL)
+        notebook.AddPage(page=panel, text=self.pointPanelName)
         border = wx.BoxSizer(wx.VERTICAL)
         #
         # choose image
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Symbol"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Symbol"))
         sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
-        
-        gridSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
 
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Select symbol:")),
-                      pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        self.symbolLabel = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                          label = self.pointDict['symbol'])
-        gridSizer.Add(item = self.symbolLabel, pos = (0, 1),
-                      flag = wx.ALIGN_CENTER_VERTICAL )
+        gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
+
+        gridSizer.Add(
+            item=wx.StaticText(
+                parent=panel, id=wx.ID_ANY, label=_("Select symbol:")), pos=(
+                0, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+
+        self.symbolLabel = wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=self.pointDict['symbol'])
+        gridSizer.Add(item=self.symbolLabel, pos=(0, 1),
+                      flag=wx.ALIGN_CENTER_VERTICAL)
         bitmap = wx.Bitmap(os.path.join(globalvar.SYMBDIR,
                                         self.pointDict['symbol']) + '.png')
-        self.symbolButton = wx.BitmapButton(panel, id = wx.ID_ANY, bitmap = bitmap)
+        self.symbolButton = wx.BitmapButton(panel, id=wx.ID_ANY, bitmap=bitmap)
         self.symbolButton.Bind(wx.EVT_BUTTON, self.OnSymbolSelection)
 
-        gridSizer.Add(self.symbolButton, pos = (0, 2), flag = wx.ALIGN_CENTER_VERTICAL)
-        self.noteLabel = wx.StaticText(parent = panel, id = wx.ID_ANY, 
-                                       label = _("Note: Selected symbol is not displayed\n"
-                                                 "in draft mode (only in preview mode)"))
-        gridSizer.Add(self.noteLabel, pos = (1, 0), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            self.symbolButton, pos=(0, 2),
+            flag=wx.ALIGN_CENTER_VERTICAL)
+        self.noteLabel = wx.StaticText(
+            parent=panel, id=wx.ID_ANY, label=_(
+                "Note: Selected symbol is not displayed\n"
+                "in draft mode (only in preview mode)"))
+        gridSizer.Add(
+            self.noteLabel, pos=(
+                1, 0), span=(
+                1, 2), flag=wx.ALIGN_CENTER_VERTICAL)
 
         gridSizer.AddGrowableCol(1)
-        sizer.Add(item = gridSizer, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
-        
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+        sizer.Add(
+            item=gridSizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         #
         # outline/fill color
         #
 
         # outline
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Color"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Color"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
-        gridSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
-        
-        outlineLabel = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Outline color:"))
-        self.outlineColorCtrl = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
-        self.outlineTranspCtrl = wx.CheckBox(panel, id = wx.ID_ANY, label = _("transparent"))
 
+        gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
+
+        outlineLabel = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Outline color:"))
+        self.outlineColorCtrl = wx.ColourPickerCtrl(panel, id=wx.ID_ANY)
+        self.outlineTranspCtrl = wx.CheckBox(
+            panel, id=wx.ID_ANY, label=_("transparent"))
+
         if self.pointDict['color'] != 'none':
             self.outlineTranspCtrl.SetValue(False)
-            self.outlineColorCtrl.SetColour(convertRGB(self.pointDict['color']))
+            self.outlineColorCtrl.SetColour(
+                convertRGB(self.pointDict['color']))
         else:
             self.outlineTranspCtrl.SetValue(True)
-            self.outlineColorCtrl.SetColour(convertRGB(self.defaultDict['color']))
+            self.outlineColorCtrl.SetColour(
+                convertRGB(self.defaultDict['color']))
 
-        gridSizer.Add(item = outlineLabel, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = self.outlineColorCtrl, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = self.outlineTranspCtrl, pos = (0, 2), flag = wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=outlineLabel, pos=(0, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=self.outlineColorCtrl, pos=(
+                0, 1), flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=self.outlineTranspCtrl, pos=(
+                0, 2), flag=wx.ALIGN_CENTER_VERTICAL)
 
-        fillLabel = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Fill color:"))
-        self.fillColorCtrl = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
-        self.fillTranspCtrl = wx.CheckBox(panel, id = wx.ID_ANY, label = _("transparent"))
+        fillLabel = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Fill color:"))
+        self.fillColorCtrl = wx.ColourPickerCtrl(panel, id=wx.ID_ANY)
+        self.fillTranspCtrl = wx.CheckBox(
+            panel, id=wx.ID_ANY, label=_("transparent"))
 
         if self.pointDict['fcolor'] != 'none':
             self.fillTranspCtrl.SetValue(False)
             self.fillColorCtrl.SetColour(convertRGB(self.pointDict['fcolor']))
         else:
             self.fillTranspCtrl.SetValue(True)
-            self.fillColorCtrl.SetColour(convertRGB(self.defaultDict['fcolor']))
+            self.fillColorCtrl.SetColour(
+                convertRGB(self.defaultDict['fcolor']))
 
-        gridSizer.Add(item = fillLabel, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = self.fillColorCtrl, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = self.fillTranspCtrl, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        sizer.Add(item = gridSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
+        gridSizer.Add(
+            item=fillLabel, pos=(1, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=self.fillColorCtrl, pos=(
+                1, 1), flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=self.fillTranspCtrl, pos=(
+                1, 2), flag=wx.ALIGN_CENTER_VERTICAL)
 
+        sizer.Add(
+            item=gridSizer,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         #
         # size and rotation
         #
 
         # size
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Size and Rotation"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Size and Rotation"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
-        gridSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
-        
-        sizeLabel = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Size (pt):"))
-        self.sizeCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, size = self.spinCtrlSize)
+
+        gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
+
+        sizeLabel = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Size (pt):"))
+        self.sizeCtrl = wx.SpinCtrl(
+            panel, id=wx.ID_ANY, size=self.spinCtrlSize)
         self.sizeCtrl.SetToolTipString(_("Symbol size in points"))
         self.sizeCtrl.SetValue(self.pointDict['size'])
-        
-        gridSizer.Add(item = sizeLabel, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = self.sizeCtrl, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL)
-        
+
+        gridSizer.Add(
+            item=sizeLabel, pos=(0, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=self.sizeCtrl, pos=(
+                0, 1), flag=wx.ALIGN_CENTER_VERTICAL)
+
         # rotation
-        rotLabel = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Rotation angle (deg):"))
+        rotLabel = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Rotation angle (deg):"))
         if fs:
-            self.rotCtrl = fs.FloatSpin(panel, id = wx.ID_ANY, min_val = -360, max_val = 360,
-                                          increment = 1, value = 0, style = fs.FS_RIGHT, size = self.spinCtrlSize)
+            self.rotCtrl = fs.FloatSpin(
+                panel,
+                id=wx.ID_ANY,
+                min_val=-360,
+                max_val=360,
+                increment=1,
+                value=0,
+                style=fs.FS_RIGHT,
+                size=self.spinCtrlSize)
             self.rotCtrl.SetFormat("%f")
             self.rotCtrl.SetDigits(1)
         else:
-            self.rotCtrl = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = self.spinCtrlSize,
-                                                min = -360, max = 360, initial = 0)
-        self.rotCtrl.SetToolTipString(_("Counterclockwise rotation in degrees"))
+            self.rotCtrl = wx.SpinCtrl(
+                parent=panel,
+                id=wx.ID_ANY,
+                size=self.spinCtrlSize,
+                min=-360,
+                max=360,
+                initial=0)
+        self.rotCtrl.SetToolTipString(
+            _("Counterclockwise rotation in degrees"))
         self.rotCtrl.SetValue(float(self.pointDict['rotate']))
-            
-        gridSizer.Add(item = rotLabel, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-        gridSizer.Add(item = self.rotCtrl, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL)
-        
-        sizer.Add(item = gridSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+
+        gridSizer.Add(
+            item=rotLabel,
+            pos=(
+                1,
+                0),
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            border=0)
+        gridSizer.Add(
+            item=self.rotCtrl, pos=(1, 1),
+            flag=wx.ALIGN_CENTER_VERTICAL)
+
+        sizer.Add(
+            item=gridSizer,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         panel.SetSizer(border)
         panel.Fit()
-        
+
         return panel
-        
+
     def _positionPanel(self, notebook):
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
-        notebook.AddPage(page = panel, text = _("Position"))
+        panel = wx.Panel(
+            parent=notebook, id=wx.ID_ANY, size=(-1, -1),
+            style=wx.TAB_TRAVERSAL)
+        notebook.AddPage(page=panel, text=_("Position"))
         border = wx.BoxSizer(wx.VERTICAL)
         #
         # set position
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Position"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Position"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
-        gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
-        
+
+        gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
+
         self.AddExtendedPosition(panel, gridBagSizer, self.pointDict)
-        
-        self.Bind(wx.EVT_RADIOBUTTON, self.OnPositionType, panel.position['toPaper']) 
-        self.Bind(wx.EVT_RADIOBUTTON, self.OnPositionType, panel.position['toMap'])
-        
-        
+
+        self.Bind(
+            wx.EVT_RADIOBUTTON,
+            self.OnPositionType,
+            panel.position['toPaper'])
+        self.Bind(
+            wx.EVT_RADIOBUTTON,
+            self.OnPositionType,
+            panel.position['toMap'])
+
         gridBagSizer.AddGrowableCol(0)
         gridBagSizer.AddGrowableCol(1)
-        sizer.Add(gridBagSizer, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL| wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        
+        sizer.Add(
+            gridBagSizer,
+            proportion=1,
+            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+            border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
         panel.SetSizer(border)
         panel.Fit()
-        
+
         return panel
-        
+
     def OnPositionType(self, event):
         if self.positionPanel.position['toPaper'].GetValue():
             for widget in self.gridBagSizerP.GetChildren():
@@ -4708,106 +6567,120 @@
                 widget.GetWindow().Enable()
             for widget in self.gridBagSizerP.GetChildren():
                 widget.GetWindow().Disable()
-                
+
     def OnSymbolSelection(self, event):
-        dlg = SymbolDialog(self, symbolPath = globalvar.SYMBDIR,
-                           currentSymbol = self.symbolLabel.GetLabel())
+        dlg = SymbolDialog(self, symbolPath=globalvar.SYMBDIR,
+                           currentSymbol=self.symbolLabel.GetLabel())
         if dlg.ShowModal() == wx.ID_OK:
             img = dlg.GetSelectedSymbolPath()
             name = dlg.GetSelectedSymbolName()
             self.symbolButton.SetBitmapLabel(wx.Bitmap(img + '.png'))
             self.symbolLabel.SetLabel(name)
-            
+
         dlg.Destroy()
-        
-    def update(self): 
+
+    def update(self):
         # symbol
         self.pointDict['symbol'] = self.symbolLabel.GetLabel()
 
-        
-        #position
+        # position
         if self.positionPanel.position['toPaper'].GetValue():
             self.pointDict['XY'] = True
-            currUnit = self.unitConv.findUnit(self.positionPanel.units['unitsCtrl'].GetStringSelection())
+            currUnit = self.unitConv.findUnit(
+                self.positionPanel.units['unitsCtrl'].GetStringSelection())
             self.pointDict['unit'] = currUnit
             if self.positionPanel.position['xCtrl'].GetValue():
-                x = self.positionPanel.position['xCtrl'].GetValue() 
+                x = self.positionPanel.position['xCtrl'].GetValue()
             else:
                 x = self.pointDict['where'][0]
 
             if self.positionPanel.position['yCtrl'].GetValue():
-                y = self.positionPanel.position['yCtrl'].GetValue() 
+                y = self.positionPanel.position['yCtrl'].GetValue()
             else:
                 y = self.pointDict['where'][1]
 
-            x = self.unitConv.convert(value = float(x), fromUnit = currUnit, toUnit = 'inch')
-            y = self.unitConv.convert(value = float(y), fromUnit = currUnit, toUnit = 'inch')
+            x = self.unitConv.convert(
+                value=float(x), fromUnit=currUnit, toUnit='inch')
+            y = self.unitConv.convert(
+                value=float(y), fromUnit=currUnit, toUnit='inch')
             self.pointDict['where'] = x, y
-            
+
         else:
             self.pointDict['XY'] = False
             if self.positionPanel.position['eCtrl'].GetValue():
-                e = self.positionPanel.position['eCtrl'].GetValue() 
+                e = self.positionPanel.position['eCtrl'].GetValue()
             else:
                 self.pointDict['east'] = self.pointDict['east']
 
             if self.positionPanel.position['nCtrl'].GetValue():
-                n = self.positionPanel.position['nCtrl'].GetValue() 
+                n = self.positionPanel.position['nCtrl'].GetValue()
             else:
                 self.pointDict['north'] = self.pointDict['north']
 
-            x, y = PaperMapCoordinates(mapInstr = self.instruction[self.mapId], x = float(self.pointDict['east']),
-                                       y = float(self.pointDict['north']), paperToMap = False)
+            x, y = PaperMapCoordinates(
+                mapInstr=self.instruction[
+                    self.mapId], x=float(
+                    self.pointDict['east']), y=float(
+                    self.pointDict['north']), paperToMap=False)
 
-        #rotation
+        # rotation
         self.pointDict['rotate'] = self.rotCtrl.GetValue()
-        
+
         # size
         self.pointDict['size'] = self.sizeCtrl.GetValue()
-            
-        w = h = self.unitConv.convert(value = self.pointDict['size'],
-                                  fromUnit = 'point', toUnit = 'inch')
-                                  
+
+        w = h = self.unitConv.convert(value=self.pointDict['size'],
+                                      fromUnit='point', toUnit='inch')
+
         # outline color
         if self.outlineTranspCtrl.GetValue():
             self.pointDict['color'] = 'none'
         else:
-            self.pointDict['color'] = convertRGB(self.outlineColorCtrl.GetColour())
+            self.pointDict['color'] = convertRGB(
+                self.outlineColorCtrl.GetColour())
 
         # fill color
         if self.fillTranspCtrl.GetValue():
             self.pointDict['fcolor'] = 'none'
         else:
-            self.pointDict['fcolor'] = convertRGB(self.fillColorCtrl.GetColour())
+            self.pointDict['fcolor'] = convertRGB(
+                self.fillColorCtrl.GetColour())
 
-        self.pointDict['rect'] = Rect2D(x = x - w / 2, y = y - h / 2, width = w, height = h)
-        
+        self.pointDict['rect'] = Rect2D(
+            x=x - w / 2, y=y - h / 2, width=w, height=h)
+
         if self.id not in self.instruction:
             point = Point(self.id)
             self.instruction.AddInstruction(point)
         self.instruction[self.id].SetInstruction(self.pointDict)
-        
+
         if self.id not in self.parent.objectId:
             self.parent.objectId.append(self.id)
 
         return True
-        
+
     def updateDialog(self):
         """Update text coordinates, after moving"""
         # XY coordinates
         x, y = self.pointDict['where'][:2]
-        currUnit = self.unitConv.findUnit(self.positionPanel.units['unitsCtrl'].GetStringSelection())
-        x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
-        y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
+        currUnit = self.unitConv.findUnit(
+            self.positionPanel.units['unitsCtrl'].GetStringSelection())
+        x = self.unitConv.convert(value=x, fromUnit='inch', toUnit=currUnit)
+        y = self.unitConv.convert(value=y, fromUnit='inch', toUnit=currUnit)
         self.positionPanel.position['xCtrl'].SetValue("%5.3f" % x)
         self.positionPanel.position['yCtrl'].SetValue("%5.3f" % y)
         # EN coordinates
         e, n = self.pointDict['east'], self.pointDict['north']
-        self.positionPanel.position['eCtrl'].SetValue(str(self.pointDict['east']))
-        self.positionPanel.position['nCtrl'].SetValue(str(self.pointDict['north']))
-        
+        self.positionPanel.position['eCtrl'].SetValue(
+            str(self.pointDict['east']))
+        self.positionPanel.position['nCtrl'].SetValue(
+            str(self.pointDict['north']))
+
+
 class RectangleDialog(PsmapDialog):
-    def __init__(self, parent, id, settings, type = 'rectangle', coordinates = None):
+
+    def __init__(self, parent, id, settings,
+                 type='rectangle', coordinates=None):
         """
 
         :param coordinates: begin and end point coordinate (wx.Point, wx.Point)
@@ -4816,8 +6689,13 @@
             title = _("Rectangle settings")
         else:
             title = _("Line settings")
-        PsmapDialog.__init__(self, parent = parent, id = id, title = title, settings = settings)
-        
+        PsmapDialog.__init__(
+            self,
+            parent=parent,
+            id=id,
+            title=title,
+            settings=settings)
+
         self.objectType = (type,)
 
         if self.id is not None:
@@ -4836,84 +6714,130 @@
 
         self.defaultDict = self.rectObj.defaultInstruction
         self.panel = self._rectPanel()
-        
+
         self._layout(self.panel)
 
     def _rectPanel(self):
-        panel = wx.Panel(parent = self, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL)
+        panel = wx.Panel(parent=self, id=wx.ID_ANY, style=wx.TAB_TRAVERSAL)
         border = wx.BoxSizer(wx.VERTICAL)
-                
+
         # color
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Color"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Color"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
-        
-        outlineLabel = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Outline color:"))
-        self.outlineColorCtrl = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
-        self.outlineTranspCtrl = wx.CheckBox(panel, id = wx.ID_ANY, label = _("transparent"))
+        gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
 
+        outlineLabel = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Outline color:"))
+        self.outlineColorCtrl = wx.ColourPickerCtrl(panel, id=wx.ID_ANY)
+        self.outlineTranspCtrl = wx.CheckBox(
+            panel, id=wx.ID_ANY, label=_("transparent"))
+
         if self.rectDict['color'] != 'none':
             self.outlineTranspCtrl.SetValue(False)
             self.outlineColorCtrl.SetColour(convertRGB(self.rectDict['color']))
         else:
             self.outlineTranspCtrl.SetValue(True)
-            self.outlineColorCtrl.SetColour(convertRGB(self.defaultDict['color']))
+            self.outlineColorCtrl.SetColour(
+                convertRGB(self.defaultDict['color']))
 
         # transparent outline makes sense only for rectangle
         if self.objectType == ('line',):
             self.outlineTranspCtrl.Hide()
 
-        gridSizer.Add(item = outlineLabel, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = self.outlineColorCtrl, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = self.outlineTranspCtrl, pos = (0, 2), flag = wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=outlineLabel, pos=(0, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=self.outlineColorCtrl, pos=(
+                0, 1), flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=self.outlineTranspCtrl, pos=(
+                0, 2), flag=wx.ALIGN_CENTER_VERTICAL)
 
         # fill color only in rectangle
         if self.objectType == ('rectangle',):
-            fillLabel = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Fill color:"))
-            self.fillColorCtrl = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
-            self.fillTranspCtrl = wx.CheckBox(panel, id = wx.ID_ANY, label = _("transparent"))
+            fillLabel = wx.StaticText(
+                parent=panel, id=wx.ID_ANY, label=_("Fill color:"))
+            self.fillColorCtrl = wx.ColourPickerCtrl(panel, id=wx.ID_ANY)
+            self.fillTranspCtrl = wx.CheckBox(
+                panel, id=wx.ID_ANY, label=_("transparent"))
 
             if self.rectDict['fcolor'] != 'none':
                 self.fillTranspCtrl.SetValue(False)
-                self.fillColorCtrl.SetColour(convertRGB(self.rectDict['fcolor']))
+                self.fillColorCtrl.SetColour(
+                    convertRGB(self.rectDict['fcolor']))
             else:
                 self.fillTranspCtrl.SetValue(True)
                 self.fillColorCtrl.SetColour(wx.WHITE)
 
-            gridSizer.Add(item = fillLabel, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-            gridSizer.Add(item = self.fillColorCtrl, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL)
-            gridSizer.Add(item = self.fillTranspCtrl, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL)
+            gridSizer.Add(
+                item=fillLabel, pos=(1, 0),
+                flag=wx.ALIGN_CENTER_VERTICAL)
+            gridSizer.Add(
+                item=self.fillColorCtrl, pos=(
+                    1, 1), flag=wx.ALIGN_CENTER_VERTICAL)
+            gridSizer.Add(
+                item=self.fillTranspCtrl, pos=(
+                    1, 2), flag=wx.ALIGN_CENTER_VERTICAL)
 
-        sizer.Add(gridSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
-        gridSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
+        sizer.Add(gridSizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+        gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
 
         # width
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Line style"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Line style"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
-        widthLabel = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Line width:"))
+
+        widthLabel = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Line width:"))
         if fs:
-            self.widthCtrl = fs.FloatSpin(panel, id = wx.ID_ANY, min_val = 0, max_val = 50,
-                                          increment = 1, value = 0, style = fs.FS_RIGHT, size = self.spinCtrlSize)
+            self.widthCtrl = fs.FloatSpin(
+                panel,
+                id=wx.ID_ANY,
+                min_val=0,
+                max_val=50,
+                increment=1,
+                value=0,
+                style=fs.FS_RIGHT,
+                size=self.spinCtrlSize)
             self.widthCtrl.SetFormat("%f")
             self.widthCtrl.SetDigits(1)
         else:
-            self.widthCtrl = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = self.spinCtrlSize,
-                                                min = -360, max = 360, initial = 0)
+            self.widthCtrl = wx.SpinCtrl(
+                parent=panel,
+                id=wx.ID_ANY,
+                size=self.spinCtrlSize,
+                min=-360,
+                max=360,
+                initial=0)
         self.widthCtrl.SetToolTipString(_("Line width in points"))
         self.widthCtrl.SetValue(float(self.rectDict['width']))
 
-        gridSizer.Add(item = widthLabel, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.Add(item = self.widthCtrl, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=widthLabel, pos=(0, 0),
+            flag=wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            item=self.widthCtrl, pos=(
+                0, 1), flag=wx.ALIGN_CENTER_VERTICAL)
 
-        sizer.Add(gridSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
+        sizer.Add(gridSizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
 
         panel.SetSizer(border)
-        
+
         return panel
-        
 
     def update(self):
         mapInstr = self.instruction.FindInstructionByType('map')
@@ -4922,29 +6846,27 @@
         self.mapId = mapInstr.id
         point1 = self.rectDict['where'][0]
         point2 = self.rectDict['where'][1]
-        self.rectDict['east1'], self.rectDict['north1'] = PaperMapCoordinates(mapInstr = mapInstr,
-                                                                                x = point1[0],
-                                                                                y = point1[1],
-                                                                                paperToMap = True)
-        self.rectDict['east2'], self.rectDict['north2'] = PaperMapCoordinates(mapInstr = mapInstr,
-                                                                                x = point2[0],
-                                                                                y = point2[1],
-                                                                                paperToMap = True)
+        self.rectDict['east1'], self.rectDict['north1'] = PaperMapCoordinates(
+            mapInstr=mapInstr, x=point1[0], y=point1[1], paperToMap=True)
+        self.rectDict['east2'], self.rectDict['north2'] = PaperMapCoordinates(
+            mapInstr=mapInstr, x=point2[0], y=point2[1], paperToMap=True)
         # width
         self.rectDict['width'] = self.widthCtrl.GetValue()
-        
+
         # outline color
         if self.outlineTranspCtrl.GetValue():
             self.rectDict['color'] = 'none'
         else:
-            self.rectDict['color'] = convertRGB(self.outlineColorCtrl.GetColour())
+            self.rectDict['color'] = convertRGB(
+                self.outlineColorCtrl.GetColour())
 
         # fill color
         if self.objectType == ('rectangle',):
             if self.fillTranspCtrl.GetValue():
                 self.rectDict['fcolor'] = 'none'
             else:
-                self.rectDict['fcolor'] = convertRGB(self.fillColorCtrl.GetColour())
+                self.rectDict['fcolor'] = convertRGB(
+                    self.fillColorCtrl.GetColour())
 
         if self.id not in self.instruction:
             if self.objectType == ('rectangle',):
@@ -4952,12 +6874,12 @@
             else:
                 rect = Line(self.id)
             self.instruction.AddInstruction(rect)
-            
+
         self.instruction[self.id].SetInstruction(self.rectDict)
 
         if self.id not in self.parent.objectId:
             self.parent.objectId.append(self.id)
-            
+
         self.updateDialog()
 
         return True
@@ -4968,9 +6890,14 @@
 
 
 class LabelsDialog(PsmapDialog):
+
     def __init__(self, parent, id, settings):
-        PsmapDialog.__init__(self, parent = parent, id = id, title = _("Vector labels"),
-                             settings=settings)
+        PsmapDialog.__init__(
+            self,
+            parent=parent,
+            id=id,
+            title=_("Vector labels"),
+            settings=settings)
         self.objectType = ('labels',)
         if self.id is not None:
             self.labels = self.instruction[self.id]
@@ -4987,18 +6914,34 @@
 
         border = wx.BoxSizer(wx.VERTICAL)
 
-        box   = wx.StaticBox(parent=panel, id=wx.ID_ANY,
-                             label=" %s " % _("Vector label files created beforehand by v.label module"))
+        box = wx.StaticBox(
+            parent=panel, id=wx.ID_ANY, label=" %s " %
+            _("Vector label files created beforehand by v.label module"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
 
-
-        self.select = Select(parent=panel, multiple=True, type='labels', fullyQualified=False)
+        self.select = Select(
+            parent=panel,
+            multiple=True,
+            type='labels',
+            fullyQualified=False)
         self.select.SetValue(','.join(self.labelsDict['labels']))
         self.select.SetFocus()
-        sizer.Add(item=self.select, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
-        helpText = wx.StaticText(panel, id=wx.ID_ANY, label=_("You can select multiple label files."))
-        helpText.SetForegroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_GRAYTEXT))
-        sizer.Add(item=helpText, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5)
+        sizer.Add(
+            item=self.select,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        helpText = wx.StaticText(
+            panel, id=wx.ID_ANY,
+            label=_("You can select multiple label files."))
+        helpText.SetForegroundColour(
+            wx.SystemSettings_GetColour(
+                wx.SYS_COLOUR_GRAYTEXT))
+        sizer.Add(
+            item=helpText,
+            proportion=0,
+            flag=wx.EXPAND | wx.LEFT | wx.RIGHT,
+            border=5)
 
         border.Add(sizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
         panel.SetSizer(border)

Modified: grass/trunk/gui/wxpython/psmap/frame.py
===================================================================
--- grass/trunk/gui/wxpython/psmap/frame.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/psmap/frame.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -29,84 +29,101 @@
 
 import grass.script as grass
 
-from core               import globalvar
-from gui_core.menu      import Menu
-from core.gconsole      import CmdThread, EVT_CMD_DONE
-from psmap.toolbars     import PsMapToolbar
-from core.gcmd          import RunCommand, GError, GMessage
-from core.settings      import UserSettings
+from core import globalvar
+from gui_core.menu import Menu
+from core.gconsole import CmdThread, EVT_CMD_DONE
+from psmap.toolbars import PsMapToolbar
+from core.gcmd import RunCommand, GError, GMessage
+from core.settings import UserSettings
 from core.utils import _, PilImageToWxImage
-from gui_core.forms     import GUI
-from gui_core.dialogs   import HyperlinkDialog
-from gui_core.ghelp     import ShowAboutDialog
-from psmap.menudata     import PsMapMenuData
+from gui_core.forms import GUI
+from gui_core.dialogs import HyperlinkDialog
+from gui_core.ghelp import ShowAboutDialog
+from psmap.menudata import PsMapMenuData
 from gui_core.toolbars import ToolSwitcher
 
-from psmap.dialogs      import *
+from psmap.dialogs import *
 from psmap.instructions import *
-from psmap.utils        import *
+from psmap.utils import *
 
+
 class PsMapFrame(wx.Frame):
-    def __init__(self, parent = None, id = wx.ID_ANY,
-                 title = _("GRASS GIS Cartographic Composer"), **kwargs):
+
+    def __init__(self, parent=None, id=wx.ID_ANY,
+                 title=_("GRASS GIS Cartographic Composer"), **kwargs):
         """Main window of ps.map GUI
-        
+
         :param parent: parent window
         :param id: window id
         :param title: window title
-        
+
         :param kwargs: wx.Frames' arguments
         """
         self.parent = parent
 
-        wx.Frame.__init__(self, parent = parent, id = id, title = title, name = "PsMap", **kwargs)
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
-        #menubar
-        self.menubar = Menu(parent = self, model = PsMapMenuData().GetModel(separators=True))
+        wx.Frame.__init__(
+            self,
+            parent=parent,
+            id=id,
+            title=title,
+            name="PsMap",
+            **kwargs)
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass.ico'),
+                wx.BITMAP_TYPE_ICO))
+        # menubar
+        self.menubar = Menu(
+            parent=self,
+            model=PsMapMenuData().GetModel(
+                separators=True))
         self.SetMenuBar(self.menubar)
-        #toolbar
+        # toolbar
 
         self._toolSwitcher = ToolSwitcher()
-        self.toolbar = PsMapToolbar(parent=self, toolSwitcher=self._toolSwitcher)
+        self.toolbar = PsMapToolbar(
+            parent=self, toolSwitcher=self._toolSwitcher)
         # workaround for http://trac.wxwidgets.org/ticket/13888
         if sys.platform != 'darwin':
             self.SetToolBar(self.toolbar)
-        
+
         self.iconsize = (16, 16)
-        #satusbar
-        self.statusbar = self.CreateStatusBar(number = 1)
-        
+        # satusbar
+        self.statusbar = self.CreateStatusBar(number=1)
+
         # mouse attributes -- position on the screen, begin and end of
         # dragging, and type of drawing
         self.mouse = {
-            'begin': [0, 0], # screen coordinates
-            'end'  : [0, 0],
-            'use'  : "pointer",
-            }
+            'begin': [0, 0],  # screen coordinates
+            'end': [0, 0],
+            'use': "pointer",
+        }
         # available cursors
         self.cursors = {
-            "default" : wx.StockCursor(wx.CURSOR_ARROW),
-            "cross"   : wx.StockCursor(wx.CURSOR_CROSS),
-            "hand"    : wx.StockCursor(wx.CURSOR_HAND),
+            "default": wx.StockCursor(wx.CURSOR_ARROW),
+            "cross": wx.StockCursor(wx.CURSOR_CROSS),
+            "hand": wx.StockCursor(wx.CURSOR_HAND),
             "sizenwse": wx.StockCursor(wx.CURSOR_SIZENWSE)
-            }
+        }
         # pen and brush
         self.pen = {
-            'paper': wx.Pen(colour = "BLACK", width = 1),
-            'margins': wx.Pen(colour = "GREY", width = 1),
-            'map': wx.Pen(colour = wx.Colour(86, 122, 17), width = 2),
-            'rasterLegend': wx.Pen(colour = wx.Colour(219, 216, 4), width = 2),
-            'vectorLegend': wx.Pen(colour = wx.Colour(219, 216, 4), width = 2),
-            'mapinfo': wx.Pen(colour = wx.Colour(5, 184, 249), width = 2),
-            'scalebar': wx.Pen(colour = wx.Colour(150, 150, 150), width = 2),
-            'image': wx.Pen(colour = wx.Colour(255, 150, 50), width = 2),
-            'northArrow': wx.Pen(colour = wx.Colour(200, 200, 200), width = 2),
-            'point': wx.Pen(colour = wx.Colour(100, 100, 100), width = 2),
-            'line': wx.Pen(colour = wx.Colour(0, 0, 0), width = 2),
-            'box': wx.Pen(colour = 'RED', width = 2, style = wx.SHORT_DASH),
-            'select': wx.Pen(colour = 'BLACK', width = 1, style = wx.SHORT_DASH),
-            'resize': wx.Pen(colour = 'BLACK', width = 1)
-            }
+            'paper': wx.Pen(colour="BLACK", width=1),
+            'margins': wx.Pen(colour="GREY", width=1),
+            'map': wx.Pen(colour=wx.Colour(86, 122, 17), width=2),
+            'rasterLegend': wx.Pen(colour=wx.Colour(219, 216, 4), width=2),
+            'vectorLegend': wx.Pen(colour=wx.Colour(219, 216, 4), width=2),
+            'mapinfo': wx.Pen(colour=wx.Colour(5, 184, 249), width=2),
+            'scalebar': wx.Pen(colour=wx.Colour(150, 150, 150), width=2),
+            'image': wx.Pen(colour=wx.Colour(255, 150, 50), width=2),
+            'northArrow': wx.Pen(colour=wx.Colour(200, 200, 200), width=2),
+            'point': wx.Pen(colour=wx.Colour(100, 100, 100), width=2),
+            'line': wx.Pen(colour=wx.Colour(0, 0, 0), width=2),
+            'box': wx.Pen(colour='RED', width=2, style=wx.SHORT_DASH),
+            'select': wx.Pen(colour='BLACK', width=1, style=wx.SHORT_DASH),
+            'resize': wx.Pen(colour='BLACK', width=1)
+        }
         self.brush = {
             'paper': wx.WHITE_BRUSH,
             'margins': wx.TRANSPARENT_BRUSH,
@@ -120,41 +137,51 @@
             'point': wx.Brush(wx.Colour(200, 200, 200)),
             'line': wx.TRANSPARENT_BRUSH,
             'box': wx.TRANSPARENT_BRUSH,
-            'select':wx.TRANSPARENT_BRUSH,
+            'select': wx.TRANSPARENT_BRUSH,
             'resize': wx.BLACK_BRUSH
-            } 
-        
+        }
 
         # list of objects to draw
         self.objectId = []
-        
+
         # instructions
-        self.instruction = Instruction(parent = self, objectsToDraw = self.objectId)
+        self.instruction = Instruction(
+            parent=self, objectsToDraw=self.objectId)
         # open dialogs
         self.openDialogs = dict()
-        
+
         self.pageId = wx.NewId()
-        #current page of flatnotebook
+        # current page of flatnotebook
         self.currentPage = 0
-        #canvas for draft mode
-        self.canvas = PsMapBufferedWindow(parent = self, mouse = self.mouse, pen = self.pen,
-                                          brush = self.brush, cursors = self.cursors, 
-                                          instruction = self.instruction, openDialogs = self.openDialogs,
-                                          pageId = self.pageId, objectId = self.objectId,
-                                          preview = False)
-        
+        # canvas for draft mode
+        self.canvas = PsMapBufferedWindow(
+            parent=self,
+            mouse=self.mouse,
+            pen=self.pen,
+            brush=self.brush,
+            cursors=self.cursors,
+            instruction=self.instruction,
+            openDialogs=self.openDialogs,
+            pageId=self.pageId,
+            objectId=self.objectId,
+            preview=False)
+
         self.canvas.SetCursor(self.cursors["default"])
         self.getInitMap()
-        
-        
+
         # image path
         env = grass.gisenv()
         self.imgName = grass.tempfile()
-        
-        #canvas for preview
-        self.previewCanvas = PsMapBufferedWindow(parent = self, mouse = self.mouse, cursors = self.cursors,
-                                                 pen = self.pen, brush = self.brush, preview = True)
-        
+
+        # canvas for preview
+        self.previewCanvas = PsMapBufferedWindow(
+            parent=self,
+            mouse=self.mouse,
+            cursors=self.cursors,
+            pen=self.pen,
+            brush=self.brush,
+            preview=True)
+
         # set WIND_OVERRIDE
         grass.use_temp_region()
 
@@ -165,7 +192,7 @@
         self.resultQ = Queue.Queue()
         # thread
         self.cmdThread = CmdThread(self, self.requestQ, self.resultQ)
-        
+
         self._layout()
         self.SetMinSize(wx.Size(775, 600))
         # workaround for http://trac.wxwidgets.org/ticket/13628
@@ -175,88 +202,90 @@
         self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
         self.Bind(EVT_CMD_DONE, self.OnCmdDone)
-        
+
         if not havePILImage:
             wx.CallAfter(self._showErrMsg)
-        
+
     def _showErrMsg(self):
         """Show error message (missing preview)
         """
-        GError(parent = self,
-               message = _("Python Imaging Library is not available.\n"
-                           "'Preview' functionality won't work."),
-               showTraceback = False)
-        
+        GError(parent=self,
+               message=_("Python Imaging Library is not available.\n"
+                         "'Preview' functionality won't work."),
+               showTraceback=False)
+
     def _layout(self):
         """Do layout
         """
         mainSizer = wx.BoxSizer(wx.VERTICAL)
         if globalvar.hasAgw:
-            self.book = fnb.FlatNotebook(parent = self, id = wx.ID_ANY,
-                                         agwStyle = fnb.FNB_FANCY_TABS | fnb.FNB_BOTTOM |
+            self.book = fnb.FlatNotebook(parent=self, id=wx.ID_ANY,
+                                         agwStyle=fnb.FNB_FANCY_TABS | fnb.FNB_BOTTOM |
                                          fnb.FNB_NO_NAV_BUTTONS | fnb.FNB_NO_X_BUTTON)
         else:
-            self.book = fnb.FlatNotebook(parent = self, id = wx.ID_ANY,
-                                         style = fnb.FNB_FANCY_TABS | fnb.FNB_BOTTOM |
+            self.book = fnb.FlatNotebook(parent=self, id=wx.ID_ANY,
+                                         style=fnb.FNB_FANCY_TABS | fnb.FNB_BOTTOM |
                                          fnb.FNB_NO_NAV_BUTTONS | fnb.FNB_NO_X_BUTTON)
         #self.book = fnb.FlatNotebook(self, wx.ID_ANY, style = fnb.FNB_BOTTOM)
         self.book.AddPage(self.canvas, "Draft mode")
         self.book.AddPage(self.previewCanvas, "Preview")
         self.book.SetSelection(0)
-        
-        mainSizer.Add(self.book,1, wx.EXPAND)
-        
+
+        mainSizer.Add(self.book, 1, wx.EXPAND)
+
         self.SetSizer(mainSizer)
         mainSizer.Fit(self)
 
-        
     def InstructionFile(self):
         """Creates mapping instructions"""
-        
+
         return str(self.instruction)
 
     def OnPSFile(self, event):
         """Generate PostScript"""
-        filename = self.getFile(wildcard = "PostScript (*.ps)|*.ps|Encapsulated PostScript (*.eps)|*.eps")
+        filename = self.getFile(
+            wildcard="PostScript (*.ps)|*.ps|Encapsulated PostScript (*.eps)|*.eps")
         if filename:
             self.PSFile(filename)
-    
+
     def OnPsMapDialog(self, event):
         """Launch ps.map dialog
         """
-        GUI(parent = self).ParseCommand(cmd = ['ps.map'])
+        GUI(parent=self).ParseCommand(cmd=['ps.map'])
 
     def OnPDFFile(self, event):
         """Generate PDF from PS with ps2pdf if available"""
         if not sys.platform == 'win32':
             try:
-                p = grass.Popen(["ps2pdf"], stderr = grass.PIPE)
+                p = grass.Popen(["ps2pdf"], stderr=grass.PIPE)
                 p.stderr.close()
-            
+
             except OSError:
-                GMessage(parent = self,
-                         message = _("Program ps2pdf is not available. Please install it first to create PDF."))
+                GMessage(
+                    parent=self,
+                    message=_(
+                        "Program ps2pdf is not available. Please install it first to create PDF."))
                 return
-        
-        filename = self.getFile(wildcard = "PDF (*.pdf)|*.pdf")
-        if filename:  
-            self.PSFile(filename, pdf = True)   
-            
+
+        filename = self.getFile(wildcard="PDF (*.pdf)|*.pdf")
+        if filename:
+            self.PSFile(filename, pdf=True)
+
     def OnPreview(self, event):
         """Run ps.map and show result"""
         self.PSFile()
-        
-    def PSFile(self, filename = None, pdf = False):
+
+    def PSFile(self, filename=None, pdf=False):
         """Create temporary instructions file and run ps.map with output = filename"""
         instrFile = grass.tempfile()
-        instrFileFd = open(instrFile, mode = 'w')
+        instrFileFd = open(instrFile, mode='w')
         instrFileFd.write(self.InstructionFile())
         instrFileFd.flush()
         instrFileFd.close()
-        
+
         temp = False
         regOld = grass.region()
-        
+
         if pdf:
             pdfname = filename
         else:
@@ -265,12 +294,12 @@
         if not filename or (filename and pdf):
             temp = True
             filename = grass.tempfile()
-            if not pdf: # lower resolution for preview
+            if not pdf:  # lower resolution for preview
                 if self.instruction.FindInstructionByType('map'):
                     mapId = self.instruction.FindInstructionByType('map').id
-                    SetResolution(dpi = 100, width = self.instruction[mapId]['rect'][2],
-                                  height = self.instruction[mapId]['rect'][3])
-        
+                    SetResolution(dpi=100, width=self.instruction[mapId]['rect'][
+                                  2], height=self.instruction[mapId]['rect'][3])
+
         cmd = ['ps.map', '--overwrite']
         if os.path.splitext(filename)[1] == '.eps':
             cmd.append('-e')
@@ -284,22 +313,30 @@
             self.SetStatusText(_('Generating PostScript...'), 0)
         else:
             self.SetStatusText(_('Generating preview...'), 0)
-            
-        self.cmdThread.RunCmd(cmd, userData = {'instrFile' : instrFile, 'filename' : filename,
-                                               'pdfname' : pdfname, 'temp' : temp, 'regionOld' : regOld})
-        
+
+        self.cmdThread.RunCmd(
+            cmd,
+            userData={
+                'instrFile': instrFile,
+                'filename': filename,
+                'pdfname': pdfname,
+                'temp': temp,
+                'regionOld': regOld})
+
     def OnCmdDone(self, event):
         """ps.map process finished"""
-        
+
         if event.returncode != 0:
-            GMessage(parent = self,
-                     message = _("Ps.map exited with return code %s") % event.returncode)
-            
+            GMessage(
+                parent=self,
+                message=_("Ps.map exited with return code %s") %
+                event.returncode)
+
             grass.try_remove(event.userData['instrFile'])
             if event.userData['temp']:
-                grass.try_remove(event.userData['filename']) 
+                grass.try_remove(event.userData['filename'])
             return
-        
+
         if event.userData['pdfname']:
             if sys.platform == 'win32':
                 command = ['gswin32c',
@@ -314,31 +351,41 @@
                            '-P-', '-dSAFER',
                            '-dCompatibilityLevel=1.4',
                            '-c', '.setpdfwrite', '-f',
-                            event.userData['filename']]
+                           event.userData['filename']]
             else:
-                command = ['ps2pdf', '-dPDFSETTINGS=/prepress', '-r1200', 
-                           event.userData['filename'], event.userData['pdfname']]
+                command = [
+                    'ps2pdf',
+                    '-dPDFSETTINGS=/prepress',
+                    '-r1200',
+                    event.userData['filename'],
+                    event.userData['pdfname']]
             try:
                 proc = grass.Popen(command)
-                ret = proc.wait()                        
+                ret = proc.wait()
                 if ret > 0:
-                    GMessage(parent = self,
-                             message = _("%(prg)s exited with return code %(code)s") % {'prg': command[0],
-                                                                                        'code': ret})
+                    GMessage(
+                        parent=self,
+                        message=_("%(prg)s exited with return code %(code)s") % {
+                            'prg': command[0],
+                            'code': ret})
                 else:
                     self.SetStatusText(_('PDF generated'), 0)
             except OSError as e:
-                GError(parent = self,
-                       message = _("Program ps2pdf is not available. Please install it to create PDF.\n\n %s") % e)
+                GError(parent=self, message=_(
+                    "Program ps2pdf is not available. Please install it to create PDF.\n\n %s") % e)
 
         elif not event.userData['temp']:
             self.SetStatusText(_('PostScript file generated'), 0)
 
-        # show preview only when user doesn't want to create ps or pdf 
-        if havePILImage and event.userData['temp'] and not event.userData['pdfname']:
-            RunCommand('g.region', cols = event.userData['regionOld']['cols'], rows = event.userData['regionOld']['rows'])
+        # show preview only when user doesn't want to create ps or pdf
+        if havePILImage and event.userData[
+                'temp'] and not event.userData['pdfname']:
+            RunCommand('g.region', cols=event.userData['regionOld'][
+                       'cols'], rows=event.userData['regionOld']['rows'])
             # wx.BusyInfo does not display the message
-            busy = wx.BusyInfo(message = _("Generating preview, wait please"), parent = self)
+            busy = wx.BusyInfo(
+                message=_("Generating preview, wait please"),
+                parent=self)
             wx.Yield()
             try:
                 im = PILImage.open(event.userData['filename'])
@@ -349,33 +396,37 @@
                 if sys.platform == 'win32':
                     import types
                     im.load = types.MethodType(loadPSForWindows, im)
-                im.save(self.imgName, format = 'PNG')
+                im.save(self.imgName, format='PNG')
             except (IOError, OSError) as e:
                 del busy
-                dlg = HyperlinkDialog(self, title=_("Preview not available"),
-                                      message=_("Preview is not available probably because Ghostscript is not installed or not on PATH."),
-                                      hyperlink='http://trac.osgeo.org/grass/wiki/CompileOnWindows#Ghostscript',
-                                      hyperlinkLabel=_("Please follow instructions on GRASS Trac Wiki."))
+                dlg = HyperlinkDialog(
+                    self, title=_("Preview not available"),
+                    message=_(
+                        "Preview is not available probably because Ghostscript is not installed or not on PATH."),
+                    hyperlink='http://trac.osgeo.org/grass/wiki/CompileOnWindows#Ghostscript',
+                    hyperlinkLabel=_(
+                        "Please follow instructions on GRASS Trac Wiki."))
                 dlg.ShowModal()
                 dlg.Destroy()
                 return
-            
-                
+
             rect = self.previewCanvas.ImageRect()
-            self.previewCanvas.image = wx.Image(self.imgName, wx.BITMAP_TYPE_PNG)
-            self.previewCanvas.DrawImage(rect = rect)
-            
+            self.previewCanvas.image = wx.Image(
+                self.imgName, wx.BITMAP_TYPE_PNG)
+            self.previewCanvas.DrawImage(rect=rect)
+
             del busy
             self.SetStatusText(_('Preview generated'), 0)
             self.book.SetSelection(1)
             self.currentPage = 1
-        
+
         grass.try_remove(event.userData['instrFile'])
         if event.userData['temp']:
             grass.try_remove(event.userData['filename'])
-            
-        self.delayedCall = wx.CallLater(4000, lambda: self.SetStatusText("", 0))
 
+        self.delayedCall = wx.CallLater(
+            4000, lambda: self.SetStatusText("", 0))
+
     def getFile(self, wildcard):
         suffix = []
         for filter in wildcard.split('|')[1::2]:
@@ -385,20 +436,21 @@
             suffix.append(s)
         raster = self.instruction.FindInstructionByType('raster')
         if raster:
-            rasterId = raster.id 
+            rasterId = raster.id
         else:
             rasterId = None
 
-
         if rasterId and self.instruction[rasterId]['raster']:
-            mapName = self.instruction[rasterId]['raster'].split('@')[0] + suffix[0]
+            mapName = self.instruction[rasterId][
+                'raster'].split('@')[0] + suffix[0]
         else:
             mapName = ''
-            
+
         filename = ''
-        dlg = wx.FileDialog(self, message = _("Save file as"), defaultDir = "", 
-                            defaultFile = mapName, wildcard = wildcard,
-                            style = wx.FD_CHANGE_DIR | wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
+        dlg = wx.FileDialog(
+            self, message=_("Save file as"),
+            defaultDir="", defaultFile=mapName, wildcard=wildcard,
+            style=wx.FD_CHANGE_DIR | wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
         if dlg.ShowModal() == wx.ID_OK:
             filename = dlg.GetPath()
             suffix = suffix[dlg.GetFilterIndex()]
@@ -406,24 +458,29 @@
                 filename = filename + suffix
             elif os.path.splitext(filename)[1] != suffix and suffix != '':
                 filename = os.path.splitext(filename)[0] + suffix
-            
+
         dlg.Destroy()
         return filename
-    
+
     def OnInstructionFile(self, event):
-        filename = self.getFile(wildcard = "*.psmap|*.psmap|Text file(*.txt)|*.txt|All files(*.*)|*.*")        
-        if filename:    
+        filename = self.getFile(
+            wildcard="*.psmap|*.psmap|Text file(*.txt)|*.txt|All files(*.*)|*.*")
+        if filename:
             instrFile = open(filename, "w")
             instrFile.write(self.InstructionFile())
-            instrFile.close()   
-            
+            instrFile.close()
+
     def OnLoadFile(self, event):
         """Launch file dialog and load selected file"""
-        #find file
+        # find file
         filename = ''
-        dlg = wx.FileDialog(self, message = "Find instructions file", defaultDir = "", 
-                            defaultFile = '', wildcard = "All files (*.*)|*.*",
-                            style = wx.FD_CHANGE_DIR|wx.FD_OPEN)
+        dlg = wx.FileDialog(
+            self,
+            message="Find instructions file",
+            defaultDir="",
+            defaultFile='',
+            wildcard="All files (*.*)|*.*",
+            style=wx.FD_CHANGE_DIR | wx.FD_OPEN)
         if dlg.ShowModal() == wx.ID_OK:
             filename = dlg.GetPath()
         dlg.Destroy()
@@ -435,58 +492,59 @@
     def LoadFile(self, filename):
         """Load file and read instructions"""
         readObjectId = []
-        readInstruction = Instruction(parent = self, objectsToDraw = readObjectId)
+        readInstruction = Instruction(parent=self, objectsToDraw=readObjectId)
         ok = readInstruction.Read(filename)
         if not ok:
             GMessage(_("Failed to read file %s.") % filename)
         else:
             self.instruction = self.canvas.instruction = readInstruction
             self.objectId = self.canvas.objectId = readObjectId
-            self.pageId = self.canvas.pageId = self.instruction.FindInstructionByType('page').id
+            self.pageId = self.canvas.pageId = self.instruction.FindInstructionByType(
+                'page').id
             self.canvas.UpdateMapLabel()
             self.canvas.dragId = -1
             self.canvas.Clear()
             self.canvas.SetPage()
-            #self.canvas.ZoomAll()
-            
+            # self.canvas.ZoomAll()
+
             self.DialogDataChanged(self.objectId)
 
-    def OnPageSetup(self, event = None):
+    def OnPageSetup(self, event=None):
         """Specify paper size, margins and orientation"""
         id = self.instruction.FindInstructionByType('page').id
-        dlg = PageSetupDialog(self, id = id, settings = self.instruction) 
+        dlg = PageSetupDialog(self, id=id, settings=self.instruction)
         dlg.CenterOnScreen()
         val = dlg.ShowModal()
         if val == wx.ID_OK:
             self.canvas.SetPage()
             self.getInitMap()
-            self.canvas.RecalculatePosition(ids = self.objectId)
+            self.canvas.RecalculatePosition(ids=self.objectId)
         dlg.Destroy()
-        
+
     def OnPointer(self, event):
         self.mouse["use"] = "pointer"
         self.canvas.SetCursor(self.cursors["default"])
         self.previewCanvas.SetCursor(self.cursors["default"])
-        
+
     def OnPan(self, event):
         self.mouse["use"] = "pan"
         self.canvas.SetCursor(self.cursors["hand"])
         self.previewCanvas.SetCursor(self.cursors["hand"])
-        
+
     def OnZoomIn(self, event):
         self.mouse["use"] = "zoomin"
         self.canvas.SetCursor(self.cursors["cross"])
         self.previewCanvas.SetCursor(self.cursors["cross"])
-        
+
     def OnZoomOut(self, event):
         self.mouse["use"] = "zoomout"
         self.canvas.SetCursor(self.cursors["cross"])
         self.previewCanvas.SetCursor(self.cursors["cross"])
-        
+
     def OnZoomAll(self, event):
         self.mouseOld = self.mouse['use']
         if self.currentPage == 0:
-            self.cursorOld = self.canvas.GetCursor() 
+            self.cursorOld = self.canvas.GetCursor()
         else:
             self.cursorOld = self.previewCanvas.GetCursor()
             self.previewCanvas.GetCursor()
@@ -495,46 +553,50 @@
             self.canvas.ZoomAll()
         else:
             self.previewCanvas.ZoomAll()
-        self.mouse["use"] = self.mouseOld 
+        self.mouse["use"] = self.mouseOld
         if self.currentPage == 0:
             self.canvas.SetCursor(self.cursorOld)
         else:
             self.previewCanvas.SetCursor(self.cursorOld)
-        
-        
-    def OnAddMap(self, event, notebook = False):
-        """Add or edit map frame"""      
+
+    def OnAddMap(self, event, notebook=False):
+        """Add or edit map frame"""
         if self.instruction.FindInstructionByType('map'):
             mapId = self.instruction.FindInstructionByType('map').id
-        else: mapId = None
+        else:
+            mapId = None
         id = [mapId, None, None]
-        
+
         if notebook:
             if self.instruction.FindInstructionByType('vector'):
                 vectorId = self.instruction.FindInstructionByType('vector').id
-            else: vectorId = None
+            else:
+                vectorId = None
             if self.instruction.FindInstructionByType('raster'):
                 rasterId = self.instruction.FindInstructionByType('raster').id
-            else: rasterId = None
+            else:
+                rasterId = None
             id[1] = rasterId
             id[2] = vectorId
-        
-        
-        if mapId: # map exists        
+
+        if mapId:  # map exists
             self.toolbar.SelectDefault()
 
             if notebook:
-                #check map, raster, vector and save, destroy them
+                # check map, raster, vector and save, destroy them
                 if 'map' in self.openDialogs:
-                    self.openDialogs['map'].OnOK(event = None)
+                    self.openDialogs['map'].OnOK(event=None)
                 if 'raster' in self.openDialogs:
-                    self.openDialogs['raster'].OnOK(event = None)
+                    self.openDialogs['raster'].OnOK(event=None)
                 if 'vector' in self.openDialogs:
-                    self.openDialogs['vector'].OnOK(event = None)
-                    
+                    self.openDialogs['vector'].OnOK(event=None)
+
                 if 'mapNotebook' not in self.openDialogs:
-                    dlg = MapDialog(parent = self, id  = id, settings = self.instruction,
-                                    notebook = notebook)
+                    dlg = MapDialog(
+                        parent=self,
+                        id=id,
+                        settings=self.instruction,
+                        notebook=notebook)
                     self.openDialogs['mapNotebook'] = dlg
                 self.openDialogs['mapNotebook'].Show()
             else:
@@ -542,11 +604,13 @@
                     self.openDialogs['mapNotebook'].notebook.ChangeSelection(0)
                 else:
                     if 'map' not in self.openDialogs:
-                        dlg = MapDialog(parent = self, id  = id, settings = self.instruction,
-                                        notebook = notebook)
+                        dlg = MapDialog(
+                            parent=self,
+                            id=id,
+                            settings=self.instruction,
+                            notebook=notebook)
                         self.openDialogs['map'] = dlg
                     self.openDialogs['map'].Show()
-                    
 
         else:    # sofar no map
             self.mouse["use"] = "addMap"
@@ -554,79 +618,89 @@
             if self.currentPage == 1:
                 self.book.SetSelection(0)
                 self.currentPage = 0
-                
+
     def OnAddRaster(self, event):
         """Add raster map"""
         if self.instruction.FindInstructionByType('raster'):
             id = self.instruction.FindInstructionByType('raster').id
-        else: id = None
+        else:
+            id = None
         if self.instruction.FindInstructionByType('map'):
             mapId = self.instruction.FindInstructionByType('map').id
-        else: mapId = None
+        else:
+            mapId = None
 
         if not id:
             if not mapId:
-                GMessage(message = _("Please, create map frame first."))
+                GMessage(message=_("Please, create map frame first."))
                 return
-            
+
 ##        dlg = RasterDialog(self, id = id, settings = self.instruction)
-##        dlg.ShowModal()
+# dlg.ShowModal()
         if 'mapNotebook' in self.openDialogs:
             self.openDialogs['mapNotebook'].notebook.ChangeSelection(1)
         else:
             if 'raster' not in self.openDialogs:
-                dlg = RasterDialog(self, id = id, settings = self.instruction)
+                dlg = RasterDialog(self, id=id, settings=self.instruction)
                 self.openDialogs['raster'] = dlg
             self.openDialogs['raster'].Show()
-            
+
     def OnAddVect(self, event):
         """Add vector map"""
         if self.instruction.FindInstructionByType('vector'):
             id = self.instruction.FindInstructionByType('vector').id
-        else: id = None
+        else:
+            id = None
         if self.instruction.FindInstructionByType('map'):
             mapId = self.instruction.FindInstructionByType('map').id
-        else: mapId = None
+        else:
+            mapId = None
         if not id:
             if not mapId:
-                GMessage(message = _("Please, create map frame first."))
+                GMessage(message=_("Please, create map frame first."))
                 return
-            
+
 ##        dlg = MainVectorDialog(self, id = id, settings = self.instruction)
-##        dlg.ShowModal()
+# dlg.ShowModal()
         if 'mapNotebook' in self.openDialogs:
             self.openDialogs['mapNotebook'].notebook.ChangeSelection(2)
         else:
             if 'vector' not in self.openDialogs:
-                dlg =  MainVectorDialog(self, id = id, settings = self.instruction)
+                dlg = MainVectorDialog(self, id=id, settings=self.instruction)
                 self.openDialogs['vector'] = dlg
             self.openDialogs['vector'].Show()
-       
+
     def OnAddScalebar(self, event):
         """Add scalebar"""
         if projInfo()['proj'] == 'll':
-            GMessage(message = _("Scalebar is not appropriate for this projection"))
+            GMessage(
+                message=_("Scalebar is not appropriate for this projection"))
             return
         if self.instruction.FindInstructionByType('scalebar'):
             id = self.instruction.FindInstructionByType('scalebar').id
-        else: id = None
-        
+        else:
+            id = None
+
         if 'scalebar' not in self.openDialogs:
-            dlg = ScalebarDialog(self, id = id, settings = self.instruction)
+            dlg = ScalebarDialog(self, id=id, settings=self.instruction)
             self.openDialogs['scalebar'] = dlg
         self.openDialogs['scalebar'].Show()
-        
-    def OnAddLegend(self, event, page = 0):
+
+    def OnAddLegend(self, event, page=0):
         """Add raster or vector legend"""
         if self.instruction.FindInstructionByType('rasterLegend'):
             idR = self.instruction.FindInstructionByType('rasterLegend').id
-        else: idR = None
+        else:
+            idR = None
         if self.instruction.FindInstructionByType('vectorLegend'):
             idV = self.instruction.FindInstructionByType('vectorLegend').id
-        else: idV = None
+        else:
+            idV = None
 
-        if 'rasterLegend' not in self.openDialogs:    
-            dlg = LegendDialog(self, id = [idR, idV], settings = self.instruction, page = page)
+        if 'rasterLegend' not in self.openDialogs:
+            dlg = LegendDialog(
+                self, id=[idR, idV],
+                settings=self.instruction, page=page)
             self.openDialogs['rasterLegend'] = dlg
             self.openDialogs['vectorLegend'] = dlg
         self.openDialogs['rasterLegend'].notebook.ChangeSelection(page)
@@ -635,56 +709,58 @@
     def OnAddMapinfo(self, event):
         if self.instruction.FindInstructionByType('mapinfo'):
             id = self.instruction.FindInstructionByType('mapinfo').id
-        else: id = None
-        
+        else:
+            id = None
+
         if 'mapinfo' not in self.openDialogs:
-            dlg = MapinfoDialog(self, id = id, settings = self.instruction)
+            dlg = MapinfoDialog(self, id=id, settings=self.instruction)
             self.openDialogs['mapinfo'] = dlg
         self.openDialogs['mapinfo'].Show()
-        
-    def OnAddImage(self, event, id = None):
+
+    def OnAddImage(self, event, id=None):
         """Show dialog for image adding and editing"""
         position = None
         if 'image' in self.openDialogs:
             position = self.openDialogs['image'].GetPosition()
-            self.openDialogs['image'].OnApply(event = None)
+            self.openDialogs['image'].OnApply(event=None)
             self.openDialogs['image'].Destroy()
-        dlg = ImageDialog(self, id = id, settings = self.instruction)
-        self.openDialogs['image'] = dlg 
-        if position: 
+        dlg = ImageDialog(self, id=id, settings=self.instruction)
+        self.openDialogs['image'] = dlg
+        if position:
             dlg.SetPosition(position)
         dlg.Show()
-        
-    def OnAddNorthArrow(self, event, id = None):
+
+    def OnAddNorthArrow(self, event, id=None):
         """Show dialog for north arrow adding and editing"""
         if self.instruction.FindInstructionByType('northArrow'):
             id = self.instruction.FindInstructionByType('northArrow').id
-        else: id = None
-        
+        else:
+            id = None
+
         if 'northArrow' not in self.openDialogs:
-            dlg = NorthArrowDialog(self, id = id, settings = self.instruction)
+            dlg = NorthArrowDialog(self, id=id, settings=self.instruction)
             self.openDialogs['northArrow'] = dlg
         self.openDialogs['northArrow'].Show()
-        
-    def OnAddText(self, event, id = None):
+
+    def OnAddText(self, event, id=None):
         """Show dialog for text adding and editing"""
         position = None
         if 'text' in self.openDialogs:
             position = self.openDialogs['text'].GetPosition()
-            self.openDialogs['text'].OnApply(event = None)
+            self.openDialogs['text'].OnApply(event=None)
             self.openDialogs['text'].Destroy()
-        dlg = TextDialog(self, id = id, settings = self.instruction)
-        self.openDialogs['text'] = dlg 
-        if position: 
+        dlg = TextDialog(self, id=id, settings=self.instruction)
+        self.openDialogs['text'] = dlg
+        if position:
             dlg.SetPosition(position)
         dlg.Show()
-        
+
     def OnAddPoint(self, event):
         """Add point action selected"""
         self.mouse["use"] = "addPoint"
         self.canvas.SetCursor(self.cursors["cross"])
-        
-    def AddPoint(self, id = None, coordinates = None):
+
+    def AddPoint(self, id=None, coordinates=None):
         """Add point and open property dialog.
 
         :param id: id point id (None if creating new point)
@@ -693,40 +769,40 @@
         position = None
         if 'point' in self.openDialogs:
             position = self.openDialogs['point'].GetPosition()
-            self.openDialogs['point'].OnApply(event = None)
+            self.openDialogs['point'].OnApply(event=None)
             self.openDialogs['point'].Destroy()
-        dlg = PointDialog(self, id = id, settings = self.instruction,
-                          coordinates = coordinates)
+        dlg = PointDialog(self, id=id, settings=self.instruction,
+                          coordinates=coordinates)
         self.openDialogs['point'] = dlg
-        if position: 
+        if position:
             dlg.SetPosition(position)
         if coordinates:
-            dlg.OnApply(event = None)
+            dlg.OnApply(event=None)
         dlg.Show()
-        
+
     def OnAddLine(self, event):
         """Add line action selected"""
         self.mouse["use"] = "addLine"
         self.canvas.SetCursor(self.cursors["cross"])
 
-    def AddLine(self, id = None, coordinates = None):
+    def AddLine(self, id=None, coordinates=None):
         """Add line and open property dialog.
-        
+
         :param id: id line id (None if creating new line)
         :param coordinates: coordinates of new line
         """
         position = None
         if 'line' in self.openDialogs:
             position = self.openDialogs['line'].GetPosition()
-            self.openDialogs['line'].OnApply(event = None)
+            self.openDialogs['line'].OnApply(event=None)
             self.openDialogs['line'].Destroy()
-        dlg = RectangleDialog(self, id = id, settings = self.instruction,
-                              type = 'line', coordinates = coordinates)
+        dlg = RectangleDialog(self, id=id, settings=self.instruction,
+                              type='line', coordinates=coordinates)
         self.openDialogs['line'] = dlg
-        if position: 
+        if position:
             dlg.SetPosition(position)
         if coordinates:
-            dlg.OnApply(event = None)
+            dlg.OnApply(event=None)
         dlg.Show()
 
     def OnAddRectangle(self, event):
@@ -734,64 +810,65 @@
         self.mouse["use"] = "addRectangle"
         self.canvas.SetCursor(self.cursors["cross"])
 
-    def AddRectangle(self, id = None, coordinates = None):
+    def AddRectangle(self, id=None, coordinates=None):
         """Add rectangle and open property dialog.
-        
+
         :param id: id rectangle id (None if creating new rectangle)
         :param coordinates: coordinates of new rectangle
         """
         position = None
         if 'rectangle' in self.openDialogs:
             position = self.openDialogs['rectangle'].GetPosition()
-            self.openDialogs['rectangle'].OnApply(event = None)
+            self.openDialogs['rectangle'].OnApply(event=None)
             self.openDialogs['rectangle'].Destroy()
-        dlg = RectangleDialog(self, id = id, settings = self.instruction,
-                              type = 'rectangle', coordinates = coordinates)
+        dlg = RectangleDialog(self, id=id, settings=self.instruction,
+                              type='rectangle', coordinates=coordinates)
         self.openDialogs['rectangle'] = dlg
-        if position: 
+        if position:
             dlg.SetPosition(position)
         if coordinates:
-            dlg.OnApply(event = None)
+            dlg.OnApply(event=None)
         dlg.Show()
 
-    def OnAddLabels(self, event, id = None):
+    def OnAddLabels(self, event, id=None):
         """Show dialog for labels"""
         if self.instruction.FindInstructionByType('labels'):
             id = self.instruction.FindInstructionByType('labels').id
-        else: id = None
-        
+        else:
+            id = None
+
         if 'labels' not in self.openDialogs:
-            dlg = LabelsDialog(self, id = id, settings = self.instruction)
+            dlg = LabelsDialog(self, id=id, settings=self.instruction)
             self.openDialogs['labels'] = dlg
         self.openDialogs['labels'].Show()
 
     def getModifiedTextBounds(self, x, y, textExtent, rotation):
         """computes bounding box of rotated text, not very precisely"""
         w, h = textExtent
-        rotation = float(rotation)/180*pi
+        rotation = float(rotation) / 180 * pi
         H = float(w) * sin(rotation)
         W = float(w) * cos(rotation)
         X, Y = x, y
-        if pi/2 < rotation <= 3*pi/2:
-            X = x + W 
+        if pi / 2 < rotation <= 3 * pi / 2:
+            X = x + W
         if 0 < rotation < pi:
             Y = y - H
         if rotation == 0:
-            return wx.Rect(x,y, *textExtent)
+            return wx.Rect(x, y, *textExtent)
         else:
-            return wx.Rect(X, Y, abs(W), abs(H)).Inflate(h,h) 
+            return wx.Rect(X, Y, abs(W), abs(H)).Inflate(h, h)
 
     def makePSFont(self, textDict):
         """creates a wx.Font object from selected postscript font. To be
         used for estimating bounding rectangle of text"""
-        
+
         fontsize = textDict['fontsize'] * self.canvas.currScale
         fontface = textDict['font'].split('-')[0]
         try:
             fontstyle = textDict['font'].split('-')[1]
         except IndexError:
             fontstyle = ''
-        
+
         if fontface == "Times":
             family = wx.FONTFAMILY_ROMAN
             face = "times"
@@ -804,72 +881,79 @@
         else:
             family = wx.FONTFAMILY_DEFAULT
             face = ''
-            
+
         style = wx.FONTSTYLE_NORMAL
         weight = wx.FONTWEIGHT_NORMAL
-            
+
         if 'Oblique' in fontstyle:
-            style =  wx.FONTSTYLE_SLANT
-            
+            style = wx.FONTSTYLE_SLANT
+
         if 'Italic' in fontstyle:
-            style =  wx.FONTSTYLE_ITALIC
-            
+            style = wx.FONTSTYLE_ITALIC
+
         if 'Bold' in fontstyle:
             weight = wx.FONTWEIGHT_BOLD
-        
+
         try:
-            fn = wx.Font(pointSize = fontsize, family = family, style = style,
-                         weight = weight, face = face)
+            fn = wx.Font(pointSize=fontsize, family=family, style=style,
+                         weight=weight, face=face)
         except:
-            fn = wx.Font(pointSize = fontsize, family = wx.FONTFAMILY_DEFAULT, 
-                         style = wx.FONTSTYLE_NORMAL, weight = wx.FONTWEIGHT_NORMAL)
+            fn = wx.Font(
+                pointSize=fontsize,
+                family=wx.FONTFAMILY_DEFAULT,
+                style=wx.FONTSTYLE_NORMAL,
+                weight=wx.FONTWEIGHT_NORMAL)
 
         return fn
-       
-       
+
     def getTextExtent(self, textDict):
         """Estimates bounding rectangle of text"""
         #fontsize = str(fontsize if fontsize >= 4 else 4)
-        dc = wx.ClientDC(self) # dc created because of method GetTextExtent, which pseudoDC lacks
-       
+        # dc created because of method GetTextExtent, which pseudoDC lacks
+        dc = wx.ClientDC(self)
+
         fn = self.makePSFont(textDict)
 
         try:
             dc.SetFont(fn)
-            w,h,lh = dc.GetMultiLineTextExtent(textDict['text'])
-            return (w,h)
+            w, h, lh = dc.GetMultiLineTextExtent(textDict['text'])
+            return (w, h)
         except:
-            return (0,0)
-    
+            return (0, 0)
+
     def getInitMap(self):
         """Create default map frame when no map is selected, needed for coordinates in map units"""
         instrFile = grass.tempfile()
-        instrFileFd = open(instrFile, mode = 'w')
+        instrFileFd = open(instrFile, mode='w')
         instrFileFd.write(self.InstructionFile())
         instrFileFd.flush()
         instrFileFd.close()
-        
+
         page = self.instruction.FindInstructionByType('page')
-        mapInitRect = GetMapBounds(instrFile, portrait = (page['Orientation'] == 'Portrait'))
+        mapInitRect = GetMapBounds(
+            instrFile, portrait=(
+                page['Orientation'] == 'Portrait'))
         grass.try_remove(instrFile)
-        
+
         region = grass.region()
         units = UnitConversion(self)
-        realWidth = units.convert(value = abs(region['w'] - region['e']), fromUnit = 'meter', toUnit = 'inch')
-        scale = mapInitRect.Get()[2]/realWidth  
-        
+        realWidth = units.convert(
+            value=abs(region['w'] - region['e']),
+            fromUnit='meter', toUnit='inch')
+        scale = mapInitRect.Get()[2] / realWidth
+
         initMap = self.instruction.FindInstructionByType('initMap')
         if initMap:
-            id = initMap.id 
+            id = initMap.id
         else:
             id = None
 
-        
         if not id:
             id = wx.NewId()
             initMap = InitMap(id)
             self.instruction.AddInstruction(initMap)
-        self.instruction[id].SetInstruction(dict(rect = mapInitRect, scale = scale))
+        self.instruction[id].SetInstruction(
+            dict(rect=mapInitRect, scale=scale))
 
     def OnDelete(self, event):
         if self.canvas.dragId != -1 and self.currentPage == 0:
@@ -878,49 +962,64 @@
                 self.getInitMap()
                 self.canvas.RecalculateEN()
             else:
-                self.deleteObject(self.canvas.dragId)   
-    
+                self.deleteObject(self.canvas.dragId)
+
     def deleteObject(self, id):
         """Deletes object, his id and redraws"""
-        #delete from canvas
+        # delete from canvas
         self.canvas.pdcObj.RemoveId(id)
         if id == self.canvas.dragId:
             self.canvas.pdcTmp.RemoveAll()
             self.canvas.dragId = -1
         self.canvas.Refresh()
-        
+
         # delete from instructions
         del self.instruction[id]
 
     def DialogDataChanged(self, id):
         ids = id
-        if type(id) == int:
+        if isinstance(id, int):
             ids = [id]
         for id in ids:
             itype = self.instruction[id].type
-            
+
             if itype in ('scalebar', 'mapinfo', 'image'):
-                drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
-                self.canvas.UpdateLabel(itype = itype, id = id)
-                self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
-                                 pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
+                drawRectangle = self.canvas.CanvasPaperCoordinates(
+                    rect=self.instruction[id]['rect'], canvasToPaper=False)
+                self.canvas.UpdateLabel(itype=itype, id=id)
+                self.canvas.Draw(
+                    pen=self.pen[itype],
+                    brush=self.brush[itype],
+                    pdc=self.canvas.pdcObj,
+                    drawid=id,
+                    pdctype='rectText',
+                    bb=drawRectangle)
                 self.canvas.RedrawSelectBox(id)
             if itype == 'northArrow':
-                self.canvas.UpdateLabel(itype = itype, id = id)
-                drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
-                self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
-                                 pdc = self.canvas.pdcObj, drawid = id, pdctype = 'bitmap', bb = drawRectangle)
+                self.canvas.UpdateLabel(itype=itype, id=id)
+                drawRectangle = self.canvas.CanvasPaperCoordinates(
+                    rect=self.instruction[id]['rect'], canvasToPaper=False)
+                self.canvas.Draw(
+                    pen=self.pen[itype],
+                    brush=self.brush[itype],
+                    pdc=self.canvas.pdcObj,
+                    drawid=id,
+                    pdctype='bitmap',
+                    bb=drawRectangle)
                 self.canvas.RedrawSelectBox(id)
 
             if itype in ('point', 'line', 'rectangle'):
-                drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
+                drawRectangle = self.canvas.CanvasPaperCoordinates(
+                    rect=self.instruction[id]['rect'], canvasToPaper=False)
                 # coords only for line
                 coords = None
                 if itype == 'line':
                     point1 = self.instruction[id]['where'][0]
                     point2 = self.instruction[id]['where'][1]
-                    point1Coords = self.canvas.CanvasPaperCoordinates(rect = Rect2DPS(point1, (0, 0)), canvasToPaper = False)[:2]
-                    point2Coords = self.canvas.CanvasPaperCoordinates(rect = Rect2DPS(point2, (0, 0)), canvasToPaper = False)[:2]
+                    point1Coords = self.canvas.CanvasPaperCoordinates(
+                        rect=Rect2DPS(point1, (0, 0)), canvasToPaper=False)[:2]
+                    point2Coords = self.canvas.CanvasPaperCoordinates(
+                        rect=Rect2DPS(point2, (0, 0)), canvasToPaper=False)[:2]
                     coords = (point1Coords, point2Coords)
 
                 # fill color is not in line
@@ -932,105 +1031,142 @@
                 if 'width' in self.instruction[id].GetInstruction():
                     width = self.instruction[id]['width']
 
-                self.canvas.DrawGraphics(drawid = id, color = self.instruction[id]['color'], shape = itype,
-                                       fcolor = fcolor, width = width, bb = drawRectangle, lineCoords = coords)
+                self.canvas.DrawGraphics(
+                    drawid=id,
+                    color=self.instruction[id]['color'],
+                    shape=itype,
+                    fcolor=fcolor,
+                    width=width,
+                    bb=drawRectangle,
+                    lineCoords=coords)
 
                 self.canvas.RedrawSelectBox(id)
 
             if itype == 'text':
-                
+
                 if self.instruction[id]['rotate']:
-                    rot = float(self.instruction[id]['rotate']) 
+                    rot = float(self.instruction[id]['rotate'])
                 else:
                     rot = 0
 
-                extent = self.getTextExtent(textDict = self.instruction[id].GetInstruction())
+                extent = self.getTextExtent(
+                    textDict=self.instruction[id].GetInstruction())
                 rect = Rect2DPS(self.instruction[id]['where'], (0, 0))
-                self.instruction[id]['coords'] = list(self.canvas.CanvasPaperCoordinates(rect = rect, canvasToPaper = False)[:2])
-                
-                #computes text coordinates according to reference point, not precisely
+                self.instruction[id]['coords'] = list(
+                    self.canvas.CanvasPaperCoordinates(
+                        rect=rect, canvasToPaper=False)[: 2])
+
+                # computes text coordinates according to reference point, not
+                # precisely
                 if self.instruction[id]['ref'].split()[0] == 'lower':
                     self.instruction[id]['coords'][1] -= extent[1]
                 elif self.instruction[id]['ref'].split()[0] == 'center':
-                    self.instruction[id]['coords'][1] -= extent[1]/2
+                    self.instruction[id]['coords'][1] -= extent[1] / 2
                 if self.instruction[id]['ref'].split()[1] == 'right':
-                    self.instruction[id]['coords'][0] -= extent[0] * cos(rot/180*pi)
-                    self.instruction[id]['coords'][1] += extent[0] * sin(rot/180*pi)
+                    self.instruction[id]['coords'][
+                        0] -= extent[0] * cos(rot / 180 * pi)
+                    self.instruction[id]['coords'][
+                        1] += extent[0] * sin(rot / 180 * pi)
                 elif self.instruction[id]['ref'].split()[1] == 'center':
-                    self.instruction[id]['coords'][0] -= extent[0]/2 * cos(rot/180*pi)
-                    self.instruction[id]['coords'][1] += extent[0]/2 * sin(rot/180*pi)
-                    
-                self.instruction[id]['coords'][0] += self.instruction[id]['xoffset']
-                self.instruction[id]['coords'][1] -= self.instruction[id]['yoffset']
+                    self.instruction[id]['coords'][
+                        0] -= extent[0] / 2 * cos(rot / 180 * pi)
+                    self.instruction[id]['coords'][
+                        1] += extent[0] / 2 * sin(rot / 180 * pi)
+
+                self.instruction[id]['coords'][
+                    0] += self.instruction[id]['xoffset']
+                self.instruction[id]['coords'][
+                    1] -= self.instruction[id]['yoffset']
                 coords = self.instruction[id]['coords']
-                self.instruction[id]['rect'] = bounds = self.getModifiedTextBounds(coords[0], coords[1], extent, rot)
-                self.canvas.DrawRotText(pdc = self.canvas.pdcObj, drawId = id,
-                                        textDict = self.instruction[id].GetInstruction(),
-                                        coords = coords, bounds = bounds)
+                self.instruction[id]['rect'] = bounds = self.getModifiedTextBounds(
+                    coords[0], coords[1], extent, rot)
+                self.canvas.DrawRotText(
+                    pdc=self.canvas.pdcObj, drawId=id,
+                    textDict=self.instruction[id].GetInstruction(),
+                    coords=coords, bounds=bounds)
                 self.canvas.RedrawSelectBox(id)
-                
+
             if itype in ('map', 'vector', 'raster', 'labels'):
-                
-                if itype == 'raster':#set resolution
+
+                if itype == 'raster':  # set resolution
                     info = grass.raster_info(self.instruction[id]['raster'])
-                    RunCommand('g.region', nsres = info['nsres'], ewres = info['ewres'])
+                    RunCommand(
+                        'g.region',
+                        nsres=info['nsres'],
+                        ewres=info['ewres'])
                     # change current raster in raster legend
-                    
+
                 if 'rasterLegend' in self.openDialogs:
                     self.openDialogs['rasterLegend'].updateDialog()
                 id = self.instruction.FindInstructionByType('map').id
-                
-                #check resolution
+
+                # check resolution
                 if itype == 'raster':
-                    SetResolution(dpi = self.instruction[id]['resolution'], 
-                                  width = self.instruction[id]['rect'].width,
-                                  height = self.instruction[id]['rect'].height)   
-                rectCanvas = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'],
-                                                                canvasToPaper = False)
+                    SetResolution(dpi=self.instruction[id]['resolution'],
+                                  width=self.instruction[id]['rect'].width,
+                                  height=self.instruction[id]['rect'].height)
+                rectCanvas = self.canvas.CanvasPaperCoordinates(
+                    rect=self.instruction[id]['rect'], canvasToPaper=False)
                 self.canvas.RecalculateEN()
                 self.canvas.UpdateMapLabel()
-                
-                self.canvas.Draw(pen = self.pen['map'], brush = self.brush['map'],
-                                 pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = rectCanvas)
-                # redraw select box  
+
+                self.canvas.Draw(
+                    pen=self.pen['map'],
+                    brush=self.brush['map'],
+                    pdc=self.canvas.pdcObj,
+                    drawid=id,
+                    pdctype='rectText',
+                    bb=rectCanvas)
+                # redraw select box
                 self.canvas.RedrawSelectBox(id)
                 self.canvas.pdcTmp.RemoveId(self.canvas.idZoomBoxTmp)
                 # redraw to get map to the bottom layer
                 #self.canvas.Zoom(zoomFactor = 1, view = (0, 0))
-                
+
             if itype == 'rasterLegend':
                 if self.instruction[id]['rLegend']:
-                    self.canvas.UpdateLabel(itype = itype, id = id)
-                    drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
-                    self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
-                                     pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
+                    self.canvas.UpdateLabel(itype=itype, id=id)
+                    drawRectangle = self.canvas.CanvasPaperCoordinates(
+                        rect=self.instruction[id]['rect'], canvasToPaper=False)
+                    self.canvas.Draw(
+                        pen=self.pen[itype],
+                        brush=self.brush[itype],
+                        pdc=self.canvas.pdcObj,
+                        drawid=id,
+                        pdctype='rectText',
+                        bb=drawRectangle)
                     self.canvas.RedrawSelectBox(id)
                 else:
                     self.deleteObject(id)
-                    
+
             if itype == 'vectorLegend':
                 if not self.instruction.FindInstructionByType('vector'):
                     self.deleteObject(id)
                 elif self.instruction[id]['vLegend']:
-                    self.canvas.UpdateLabel(itype = itype, id = id)
-                    drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
-                    self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
-                                     pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
+                    self.canvas.UpdateLabel(itype=itype, id=id)
+                    drawRectangle = self.canvas.CanvasPaperCoordinates(
+                        rect=self.instruction[id]['rect'], canvasToPaper=False)
+                    self.canvas.Draw(
+                        pen=self.pen[itype],
+                        brush=self.brush[itype],
+                        pdc=self.canvas.pdcObj,
+                        drawid=id,
+                        pdctype='rectText',
+                        bb=drawRectangle)
                     self.canvas.RedrawSelectBox(id)
 
                 else:
                     self.deleteObject(id)
-                
+
     def OnPageChanged(self, event):
         """Flatnotebook page has changed"""
         self.currentPage = self.book.GetPageIndex(self.book.GetCurrentPage())
         if self.currentPage == 1:
-            self.SetStatusText(_("Press button with green triangle icon to generate preview."))
+            self.SetStatusText(
+                _("Press button with green triangle icon to generate preview."))
         else:
             self.SetStatusText('')
 
-        
-        
     def OnPageChanging(self, event):
         """Flatnotebook page is changing"""
         if self.currentPage == 0 and self.mouse['use'] == 'addMap':
@@ -1044,12 +1180,14 @@
                         'entry=wxGUI.psmap'])
         else:
             RunCommand('g.manual',
-                       quiet = True,
-                       entry = 'wxGUI.psmap')
-        
+                       quiet=True,
+                       entry='wxGUI.psmap')
+
     def OnAbout(self, event):
         """Display About window"""
-        ShowAboutDialog(prgName=_('wxGUI Cartographic Composer'), startYear='2011')
+        ShowAboutDialog(
+            prgName=_('wxGUI Cartographic Composer'),
+            startYear='2011')
 
     def OnCloseWindow(self, event):
         """Close window"""
@@ -1063,90 +1201,89 @@
         self.Destroy()
 
 
-
 class PsMapBufferedWindow(wx.Window):
     """A buffered window class."""
-    def __init__(self, parent, id =  wx.ID_ANY,
-                 style = wx.NO_FULL_REPAINT_ON_RESIZE,
+
+    def __init__(self, parent, id=wx.ID_ANY,
+                 style=wx.NO_FULL_REPAINT_ON_RESIZE,
                  **kwargs):
         """
         :param parent: parent window
         :param kwargs: other wx.Window parameters
         """
-        wx.Window.__init__(self, parent, id = id, style = style)
+        wx.Window.__init__(self, parent, id=id, style=style)
         self.parent = parent
-    
+
         self.FitInside()
-        
+
         # store an off screen empty bitmap for saving to file
         self._buffer = None
         # indicates whether or not a resize event has taken place
-        self.resize = False 
-        
+        self.resize = False
+
         self.mouse = kwargs['mouse']
         self.cursors = kwargs['cursors']
         self.preview = kwargs['preview']
         self.pen = kwargs['pen']
         self.brush = kwargs['brush']
-        
-        if kwargs.has_key('instruction'):
+
+        if 'instruction' in kwargs:
             self.instruction = kwargs['instruction']
-        if kwargs.has_key('openDialogs'):
+        if 'openDialogs' in kwargs:
             self.openDialogs = kwargs['openDialogs']
-        if kwargs.has_key('pageId'):
+        if 'pageId' in kwargs:
             self.pageId = kwargs['pageId']
-        if kwargs.has_key('objectId'):
+        if 'objectId' in kwargs:
             self.objectId = kwargs['objectId']
-        
-        
-        #labels
-        self.itemLabelsDict = { 'map': _("MAP FRAME"),
-                                'rasterLegend': _("RASTER LEGEND"),
-                                'vectorLegend': _("VECTOR LEGEND"),
-                                'mapinfo': _("MAP INFO"),
-                                'scalebar': _("SCALE BAR"),
-                                'image': _("IMAGE"),
-                                'northArrow': _("NORTH ARROW")}
+
+        # labels
+        self.itemLabelsDict = {'map': _("MAP FRAME"),
+                               'rasterLegend': _("RASTER LEGEND"),
+                               'vectorLegend': _("VECTOR LEGEND"),
+                               'mapinfo': _("MAP INFO"),
+                               'scalebar': _("SCALE BAR"),
+                               'image': _("IMAGE"),
+                               'northArrow': _("NORTH ARROW")}
         self.itemLabels = {}
-        
+
         # define PseudoDC
         self.pdc = wx.PseudoDC()
         self.pdcObj = wx.PseudoDC()
         self.pdcPaper = wx.PseudoDC()
         self.pdcTmp = wx.PseudoDC()
         self.pdcImage = wx.PseudoDC()
-        
-        self.SetClientSize((700,510))#?
+
+        self.SetClientSize((700, 510))  # ?
         self._buffer = wx.EmptyBitmap(*self.GetClientSize())
-        
+
         self.idBoxTmp = wx.NewId()
         self.idZoomBoxTmp = wx.NewId()
         self.idResizeBoxTmp = wx.NewId()
-        self.idLinePointsTmp = (wx.NewId(), wx.NewId()) # ids of marks for moving line vertices
+        # ids of marks for moving line vertices
+        self.idLinePointsTmp = (wx.NewId(), wx.NewId())
 
         self.resizeBoxSize = wx.Size(8, 8)
-        self.showResizeHelp = False # helper for correctly working statusbar
-        
+        self.showResizeHelp = False  # helper for correctly working statusbar
+
         self.dragId = -1
-        
+
         if self.preview:
             self.image = None
             self.imageId = 2000
             self.imgName = self.parent.imgName
-            
+
         self.currScale = None
-        
+
         self.Clear()
-        
+
         self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
-        
+
         self.Bind(wx.EVT_PAINT, self.OnPaint)
-        self.Bind(wx.EVT_SIZE,  self.OnSize)
-        self.Bind(wx.EVT_IDLE,  self.OnIdle)
+        self.Bind(wx.EVT_SIZE, self.OnSize)
+        self.Bind(wx.EVT_IDLE, self.OnIdle)
         # self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
         self.Bind(wx.EVT_MOUSE_EVENTS, self.MouseActions)
 
-
     def Clear(self):
         """Clear canvas and set paper
         """
@@ -1155,61 +1292,77 @@
         self.pdcPaper.SetBackground(bg)
         self.pdcPaper.Clear()
         self.pdcPaper.EndDrawing()
-        
+
         self.pdcObj.RemoveAll()
         self.pdcTmp.RemoveAll()
-        
+
         if not self.preview:
             self.SetPage()
 
-    
-    def CanvasPaperCoordinates(self, rect, canvasToPaper = True):
+    def CanvasPaperCoordinates(self, rect, canvasToPaper=True):
         """Converts canvas (pixel) -> paper (inch) coordinates and size and vice versa"""
-        
+
         units = UnitConversion(self)
-        
+
         fromU = 'pixel'
         toU = 'inch'
         pRect = self.pdcPaper.GetIdBounds(self.pageId)
-        pRectx, pRecty = pRect.x, pRect.y 
-        scale = 1/self.currScale
-        if not canvasToPaper: # paper -> canvas
+        pRectx, pRecty = pRect.x, pRect.y
+        scale = 1 / self.currScale
+        if not canvasToPaper:  # paper -> canvas
             fromU = 'inch'
             toU = 'pixel'
             scale = self.currScale
-            pRectx = units.convert(value =  - pRect.x, fromUnit = 'pixel', toUnit = 'inch' ) /scale #inch, real, negative
-            pRecty = units.convert(value =  - pRect.y, fromUnit = 'pixel', toUnit = 'inch' ) /scale 
-        Width = units.convert(value = rect.GetWidth(), fromUnit = fromU, toUnit = toU) * scale
-        Height = units.convert(value = rect.GetHeight(), fromUnit = fromU, toUnit = toU) * scale
-        X = units.convert(value = (rect.GetX() - pRectx), fromUnit = fromU, toUnit = toU) * scale
-        Y = units.convert(value = (rect.GetY() - pRecty), fromUnit = fromU, toUnit = toU) * scale
+            pRectx = units.convert(
+                value=- pRect.x,
+                fromUnit='pixel',
+                toUnit='inch') / scale  # inch, real, negative
+            pRecty = units.convert(
+                value=- pRect.y,
+                fromUnit='pixel',
+                toUnit='inch') / scale
+        Width = units.convert(
+            value=rect.GetWidth(),
+            fromUnit=fromU,
+            toUnit=toU) * scale
+        Height = units.convert(
+            value=rect.GetHeight(),
+            fromUnit=fromU,
+            toUnit=toU) * scale
+        X = units.convert(
+            value=(
+                rect.GetX() - pRectx),
+            fromUnit=fromU,
+            toUnit=toU) * scale
+        Y = units.convert(
+            value=(
+                rect.GetY() - pRecty),
+            fromUnit=fromU,
+            toUnit=toU) * scale
 
         return Rect2D(X, Y, Width, Height)
 
-    
-    
     def SetPage(self):
         """Sets and changes page, redraws paper"""
-        
+
         page = self.instruction[self.pageId]
         if not page:
-            page = PageSetup(id = self.pageId)
+            page = PageSetup(id=self.pageId)
             self.instruction.AddInstruction(page)
-        
+
         ppi = wx.ClientDC(self).GetPPI()
         cW, cH = self.GetClientSize()
-        pW, pH = page['Width']*ppi[0], page['Height']*ppi[1]
+        pW, pH = page['Width'] * ppi[0], page['Height'] * ppi[1]
 
         if self.currScale is None:
-            self.currScale = min(cW/pW, cH/pH)
+            self.currScale = min(cW / pW, cH / pH)
         pW = pW * self.currScale
         pH = pH * self.currScale
-        
-        x = cW/2 - pW/2
-        y = cH/2 - pH/2
+
+        x = cW / 2 - pW / 2
+        y = cH / 2 - pH / 2
         self.DrawPaper(wx.Rect(x, y, pW, pH))
 
-
     def modifyRectangle(self, r):
         """Recalculates rectangle not to have negative size"""
         if r.GetWidth() < 0:
@@ -1218,39 +1371,55 @@
             r.SetY(r.GetY() + r.GetHeight())
         r.SetWidth(abs(r.GetWidth()))
         r.SetHeight(abs(r.GetHeight()))
-        return r 
-    
+        return r
+
     def RecalculateEN(self):
         """Recalculate east and north for texts (eps, points) after their or map's movement"""
         try:
             mapId = self.instruction.FindInstructionByType('map').id
         except AttributeError:
             mapId = self.instruction.FindInstructionByType('initMap').id
-        
-        for itemType in ('text', 'image', 'northArrow', 'point', 'line', 'rectangle'):
-            items = self.instruction.FindInstructionByType(itemType, list = True)
+
+        for itemType in ('text', 'image', 'northArrow',
+                         'point', 'line', 'rectangle'):
+            items = self.instruction.FindInstructionByType(itemType, list=True)
             for item in items:
                 instr = self.instruction[item.id]
                 if itemType in ('line', 'rectangle'):
                     if itemType == 'line':
-                        e1, n1 = PaperMapCoordinates(mapInstr = self.instruction[mapId], x = instr['where'][0][0],
-                                                     y = instr['where'][0][1], paperToMap = True)
-                        e2, n2 = PaperMapCoordinates(mapInstr = self.instruction[mapId], x = instr['where'][1][0],
-                                                     y = instr['where'][1][1], paperToMap = True)
-                    else: 
-                        e1, n1 = PaperMapCoordinates(mapInstr = self.instruction[mapId], x = instr['rect'].GetLeft(),
-                                                     y = instr['rect'].GetTop(), paperToMap = True)
-                        e2, n2 = PaperMapCoordinates(mapInstr = self.instruction[mapId], x = instr['rect'].GetRight(),
-                                                     y = instr['rect'].GetBottom(), paperToMap = True)
+                        e1, n1 = PaperMapCoordinates(
+                            mapInstr=self.instruction[mapId],
+                            x=instr['where'][0][0],
+                            y=instr['where'][0][1],
+                            paperToMap=True)
+                        e2, n2 = PaperMapCoordinates(
+                            mapInstr=self.instruction[mapId],
+                            x=instr['where'][1][0],
+                            y=instr['where'][1][1],
+                            paperToMap=True)
+                    else:
+                        e1, n1 = PaperMapCoordinates(
+                            mapInstr=self.instruction[mapId],
+                            x=instr['rect'].GetLeft(),
+                            y=instr['rect'].GetTop(),
+                            paperToMap=True)
+                        e2, n2 = PaperMapCoordinates(
+                            mapInstr=self.instruction[mapId],
+                            x=instr['rect'].GetRight(),
+                            y=instr['rect'].GetBottom(),
+                            paperToMap=True)
                     instr['east1'] = e1
                     instr['north1'] = n1
                     instr['east2'] = e2
                     instr['north2'] = n2
                 else:
-                    e, n = PaperMapCoordinates(mapInstr = self.instruction[mapId], x = instr['where'][0],
-                                               y = instr['where'][1], paperToMap = True)
+                    e, n = PaperMapCoordinates(
+                        mapInstr=self.instruction[mapId],
+                        x=instr['where'][0],
+                        y=instr['where'][1],
+                        paperToMap=True)
                     instr['east'], instr['north'] = e, n
-                
+
     def OnPaint(self, event):
         """Draw pseudo DC to buffer
         """
@@ -1260,77 +1429,77 @@
         # use PrepareDC to set position correctly
         # probably does nothing, removed from wxPython 2.9
         # self.PrepareDC(dc)
-        
+
         dc.SetBackground(wx.LIGHT_GREY_BRUSH)
         dc.Clear()
-        
+
         # draw paper
         if not self.preview:
             self.pdcPaper.DrawToDC(dc)
         # draw to the DC using the calculated clipping rect
 
         rgn = self.GetUpdateRegion()
-        
+
         if not self.preview:
             self.pdcObj.DrawToDCClipped(dc, rgn.GetBox())
-        else: 
+        else:
             self.pdcImage.DrawToDCClipped(dc, rgn.GetBox())
         self.pdcTmp.DrawToDCClipped(dc, rgn.GetBox())
-        
+
     def MouseActions(self, event):
         """Mouse motion and button click notifier
         """
         # 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)
-        
+
         elif event.Moving():
             self.OnMouseMoving(event)
-                
+
     def OnMouseWheel(self, event):
         """Mouse wheel scrolled.
 
         Changes zoom."""
-        if UserSettings.Get(group = 'display',
-                            key = 'mouseWheelZoom',
-                            subkey = 'selection') == 2:
+        if UserSettings.Get(group='display',
+                            key='mouseWheelZoom',
+                            subkey='selection') == 2:
             event.Skip()
             return
 
         zoom = event.GetWheelRotation()
         oldUse = self.mouse['use']
         self.mouse['begin'] = event.GetPosition()
-        
-        if UserSettings.Get(group = 'display',
-                            key = 'scrollDirection',
-                            subkey = 'selection'):
+
+        if UserSettings.Get(group='display',
+                            key='scrollDirection',
+                            subkey='selection'):
             zoom *= -1
-            
+
         if zoom > 0:
             self.mouse['use'] = 'zoomin'
         else:
             self.mouse['use'] = 'zoomout'
-            
+
         zoomFactor, view = self.ComputeZoom(wx.Rect(0, 0, 0, 0))
         self.Zoom(zoomFactor, view)
         self.mouse['use'] = oldUse
@@ -1346,16 +1515,18 @@
         if self.mouse['use'] in ('pointer', 'resize'):
             pos = event.GetPosition()
             foundResize = self.pdcTmp.FindObjects(pos[0], pos[1])
-            if foundResize and foundResize[0] in (self.idResizeBoxTmp,) + self.idLinePointsTmp:
+            if foundResize and foundResize[0] in (
+                    self.idResizeBoxTmp,) + self.idLinePointsTmp:
                 self.SetCursor(self.cursors["sizenwse"])
-                self.parent.SetStatusText(_('Click and drag to resize object'), 0)
+                self.parent.SetStatusText(
+                    _('Click and drag to resize object'), 0)
                 self.showResizeHelp = True
             else:
                 if self.showResizeHelp:
                     self.parent.SetStatusText('', 0)
                     self.SetCursor(self.cursors["default"])
                     self.showResizeHelp = False
-                
+
     def OnLeftDown(self, event):
         """Left mouse button pressed.
 
@@ -1363,15 +1534,19 @@
         """
         self.mouse['begin'] = event.GetPosition()
         self.begin = self.mouse['begin']
-        
+
         # select
         if self.mouse['use'] == 'pointer':
-            found = self.pdcObj.FindObjects(self.mouse['begin'][0], self.mouse['begin'][1])
-            foundResize = self.pdcTmp.FindObjects(self.mouse['begin'][0], self.mouse['begin'][1])
+            found = self.pdcObj.FindObjects(
+                self.mouse['begin'][0],
+                self.mouse['begin'][1])
+            foundResize = self.pdcTmp.FindObjects(
+                self.mouse['begin'][0], self.mouse['begin'][1])
 
-            if foundResize and foundResize[0] in (self.idResizeBoxTmp,) + self.idLinePointsTmp:
+            if foundResize and foundResize[0] in (
+                    self.idResizeBoxTmp,) + self.idLinePointsTmp:
                 self.mouse['use'] = 'resize'
-                
+
                 # when resizing, proportions match region
                 if self.instruction[self.dragId].type == 'map':
                     self.constraint = False
@@ -1381,19 +1556,23 @@
                         self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
 
                 if self.instruction[self.dragId].type == 'line':
-                    self.currentLinePoint = self.idLinePointsTmp.index(foundResize[0])
-                
+                    self.currentLinePoint = self.idLinePointsTmp.index(
+                        foundResize
+                        [0])
+
             elif found:
                 self.dragId = found[0]
                 self.RedrawSelectBox(self.dragId)
-                if self.instruction[self.dragId].type not in ('map', 'rectangle'):
+                if self.instruction[
+                        self.dragId].type not in (
+                        'map', 'rectangle'):
                     self.pdcTmp.RemoveId(self.idResizeBoxTmp)
                     self.Refresh()
                 if self.instruction[self.dragId].type != 'line':
                     for id in self.idLinePointsTmp:
                         self.pdcTmp.RemoveId(id)
                     self.Refresh()
-                    
+
             else:
                 self.dragId = -1
                 self.pdcTmp.RemoveId(self.idBoxTmp)
@@ -1408,7 +1587,7 @@
         Recalculate zooming/resizing/moving and redraw.
         """
         # zoom in, zoom out
-        if self.mouse['use'] in ('zoomin','zoomout'):
+        if self.mouse['use'] in ('zoomin', 'zoomout'):
             zoomR = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
             self.pdcTmp.RemoveId(self.idZoomBoxTmp)
             self.Refresh()
@@ -1423,13 +1602,15 @@
                 self.pdcTmp.RemoveId(self.idZoomBoxTmp)
                 self.Refresh()
                 return
-            rectPaper = self.CanvasPaperCoordinates(rect = rectTmp, canvasToPaper = True)
+            rectPaper = self.CanvasPaperCoordinates(
+                rect=rectTmp, canvasToPaper=True)
 
-            dlg = MapDialog(parent = self.parent, id = [None, None, None], settings = self.instruction, 
-                            rect = rectPaper)
+            dlg = MapDialog(
+                parent=self.parent, id=[None, None, None],
+                settings=self.instruction, rect=rectPaper)
             self.openDialogs['map'] = dlg
             self.openDialogs['map'].Show()
-            
+
             self.parent.toolbar.SelectDefault()
             return
 
@@ -1439,72 +1620,87 @@
             if not mapObj:
                 mapObj = self.instruction.FindInstructionByType('initMap')
             mapId = mapObj.id
-            
+
             if self.dragId == mapId:
-                # necessary to change either map frame (scaleType 0,1,2) or region (scaletype 3)
+                # necessary to change either map frame (scaleType 0,1,2) or
+                # region (scaletype 3)
                 newRectCanvas = self.pdcObj.GetIdBounds(mapId)
-                newRectPaper = self.CanvasPaperCoordinates(rect = newRectCanvas, canvasToPaper = True)
+                newRectPaper = self.CanvasPaperCoordinates(
+                    rect=newRectCanvas, canvasToPaper=True)
                 self.instruction[mapId]['rect'] = newRectPaper
-                
+
                 if self.instruction[mapId]['scaleType'] in (0, 1, 2):
                     if self.instruction[mapId]['scaleType'] == 0:
-                        
-                        scale, foo, rect = AutoAdjust(self, scaleType = 0,
-                                                      map = self.instruction[mapId]['map'],
-                                                      mapType = self.instruction[mapId]['mapType'], 
-                                                      rect = self.instruction[mapId]['rect'])
-                        
+
+                        scale, foo, rect = AutoAdjust(
+                            self, scaleType=0, map=self.instruction[mapId]
+                            ['map'],
+                            mapType=self.instruction[mapId]['mapType'],
+                            rect=self.instruction[mapId]['rect'])
+
                     elif self.instruction[mapId]['scaleType'] == 1:
-                        scale, foo, rect = AutoAdjust(self, scaleType = 1,
-                                                      region = self.instruction[mapId]['region'],
-                                                      rect = self.instruction[mapId]['rect'])
+                        scale, foo, rect = AutoAdjust(
+                            self, scaleType=1,
+                            region=self.instruction[mapId]['region'],
+                            rect=self.instruction[mapId]['rect'])
                     else:
-                        scale, foo, rect = AutoAdjust(self, scaleType = 2,
-                                                      rect = self.instruction[mapId]['rect'])
+                        scale, foo, rect = AutoAdjust(
+                            self, scaleType=2, rect=self.instruction[mapId]['rect'])
                     self.instruction[mapId]['rect'] = rect
                     self.instruction[mapId]['scale'] = scale
-                    
-                    rectCanvas = self.CanvasPaperCoordinates(rect = rect, canvasToPaper = False)
-                    self.Draw(pen = self.pen['map'], brush = self.brush['map'],
-                              pdc = self.pdcObj, drawid = mapId, pdctype = 'rectText', bb = rectCanvas)
-                    
+
+                    rectCanvas = self.CanvasPaperCoordinates(
+                        rect=rect, canvasToPaper=False)
+                    self.Draw(
+                        pen=self.pen['map'],
+                        brush=self.brush['map'],
+                        pdc=self.pdcObj,
+                        drawid=mapId,
+                        pdctype='rectText',
+                        bb=rectCanvas)
+
                 elif self.instruction[mapId]['scaleType'] == 3:
-                    ComputeSetRegion(self, mapDict = self.instruction[mapId].GetInstruction())
-                #check resolution
-                SetResolution(dpi = self.instruction[mapId]['resolution'],
-                              width = self.instruction[mapId]['rect'].width,
-                              height = self.instruction[mapId]['rect'].height)
-                
+                    ComputeSetRegion(
+                        self, mapDict=self.instruction[mapId].GetInstruction())
+                # check resolution
+                SetResolution(dpi=self.instruction[mapId]['resolution'],
+                              width=self.instruction[mapId]['rect'].width,
+                              height=self.instruction[mapId]['rect'].height)
+
                 self.RedrawSelectBox(mapId)
-                self.Zoom(zoomFactor = 1, view = (0, 0))
+                self.Zoom(zoomFactor=1, view=(0, 0))
 
             elif self.instruction[self.dragId].type == 'line':
                 points = self.instruction[self.dragId]['where']
-                self.instruction[self.dragId]['rect'] = Rect2DPP(points[0], points[1])
-                self.RecalculatePosition(ids = [self.dragId])
+                self.instruction[
+                    self.dragId]['rect'] = Rect2DPP(
+                    points[0], points[1])
+                self.RecalculatePosition(ids=[self.dragId])
 
             elif self.instruction[self.dragId].type == 'rectangle':
-                self.RecalculatePosition(ids = [self.dragId])
+                self.RecalculatePosition(ids=[self.dragId])
 
             self.mouse['use'] = 'pointer'
-            
+
         # recalculate the position of objects after dragging
         if self.mouse['use'] in ('pointer', 'resize') and self.dragId != -1:
-            if self.mouse['begin'] != event.GetPosition(): #for double click
-                
-                self.RecalculatePosition(ids = [self.dragId])
+            if self.mouse['begin'] != event.GetPosition():  # for double click
+
+                self.RecalculatePosition(ids=[self.dragId])
                 if self.instruction[self.dragId].type in self.openDialogs:
-                    self.openDialogs[self.instruction[self.dragId].type].updateDialog()
-        
+                    self.openDialogs[
+                        self.instruction[
+                            self.dragId].type].updateDialog()
+
         elif self.mouse['use'] in ('addPoint', 'addLine', 'addRectangle'):
-            endCoordinates = self.CanvasPaperCoordinates(rect = wx.Rect(event.GetX(), event.GetY(), 0, 0),
-                                                         canvasToPaper = True)[:2]
+            endCoordinates = self.CanvasPaperCoordinates(rect=wx.Rect(
+                event.GetX(), event.GetY(), 0, 0), canvasToPaper=True)[:2]
 
             diffX = event.GetX() - self.mouse['begin'][0]
             diffY = event.GetY() - self.mouse['begin'][1]
 
             if self.mouse['use'] == 'addPoint':
-                self.parent.AddPoint(coordinates = endCoordinates)
+                self.parent.AddPoint(coordinates=endCoordinates)
             elif self.mouse['use'] in ('addLine', 'addRectangle'):
                 # not too small lines/rectangles
                 if sqrt(diffX * diffX + diffY * diffY) < 5:
@@ -1512,24 +1708,34 @@
                     self.Refresh()
                     return
 
-                beginCoordinates = self.CanvasPaperCoordinates(rect = wx.Rect(self.mouse['begin'][0],
-                                                                              self.mouse['begin'][1], 0, 0),
-                                                               canvasToPaper = True)[:2]
+                beginCoordinates = self.CanvasPaperCoordinates(
+                    rect=wx.Rect(
+                        self.mouse['begin'][0],
+                        self.mouse['begin'][1],
+                        0, 0),
+                    canvasToPaper=True)[
+                    : 2]
                 if self.mouse['use'] == 'addLine':
-                    self.parent.AddLine(coordinates = [beginCoordinates, endCoordinates])
+                    self.parent.AddLine(
+                        coordinates=[
+                            beginCoordinates,
+                            endCoordinates])
                 else:
-                    self.parent.AddRectangle(coordinates = [beginCoordinates, endCoordinates])
+                    self.parent.AddRectangle(
+                        coordinates=[
+                            beginCoordinates,
+                            endCoordinates])
                 self.pdcTmp.RemoveId(self.idZoomBoxTmp)
                 self.Refresh()
 
     def OnButtonDClick(self, event):
         """Open object dialog for editing."""
         if self.mouse['use'] == 'pointer' and self.dragId != -1:
-            itemCall = {'text':self.parent.OnAddText,
+            itemCall = {'text': self.parent.OnAddText,
                         'mapinfo': self.parent.OnAddMapinfo,
                         'scalebar': self.parent.OnAddScalebar,
                         'image': self.parent.OnAddImage,
-                        'northArrow' : self.parent.OnAddNorthArrow,
+                        'northArrow': self.parent.OnAddNorthArrow,
                         'point': self.parent.AddPoint,
                         'line': self.parent.AddLine,
                         'rectangle': self.parent.AddRectangle,
@@ -1537,17 +1743,17 @@
                         'vectorLegend': self.parent.OnAddLegend,
                         'map': self.parent.OnAddMap}
 
-            itemArg = { 'text': dict(event = None, id = self.dragId),
-                        'mapinfo': dict(event = None),
-                        'scalebar': dict(event = None),
-                        'image': dict(event = None, id = self.dragId),
-                        'northArrow': dict(event = None, id = self.dragId),
-                        'point': dict(id = self.dragId),
-                        'line': dict(id = self.dragId),
-                        'rectangle': dict(id = self.dragId),
-                        'rasterLegend': dict(event = None),
-                        'vectorLegend': dict(event = None, page = 1),
-                        'map': dict(event = None, notebook = True)}
+            itemArg = {'text': dict(event=None, id=self.dragId),
+                       'mapinfo': dict(event=None),
+                       'scalebar': dict(event=None),
+                       'image': dict(event=None, id=self.dragId),
+                       'northArrow': dict(event=None, id=self.dragId),
+                       'point': dict(id=self.dragId),
+                       'line': dict(id=self.dragId),
+                       'rectangle': dict(id=self.dragId),
+                       'rasterLegend': dict(event=None),
+                       'vectorLegend': dict(event=None, page=1),
+                       'map': dict(event=None, notebook=True)}
 
             type = self.instruction[self.dragId].type
             itemCall[type](**itemArg[type])
@@ -1557,15 +1763,21 @@
         if event.MiddleIsDown():
             # panning
             self.mouse['end'] = event.GetPosition()
-            self.Pan(begin = self.mouse['begin'], end = self.mouse['end'])
+            self.Pan(begin=self.mouse['begin'], end=self.mouse['end'])
             self.mouse['begin'] = event.GetPosition()
 
         elif event.LeftIsDown():
-            # draw box when zooming, creating map 
-            if self.mouse['use'] in ('zoomin', 'zoomout', 'addMap', 'addLine', 'addRectangle'):
+            # draw box when zooming, creating map
+            if self.mouse['use'] in (
+                    'zoomin', 'zoomout', 'addMap', 'addLine', 'addRectangle'):
                 self.mouse['end'] = event.GetPosition()
-                r = wx.Rect(self.mouse['begin'][0], self.mouse['begin'][1],
-                            self.mouse['end'][0]-self.mouse['begin'][0], self.mouse['end'][1]-self.mouse['begin'][1])
+                r = wx.Rect(
+                    self.mouse['begin'][0],
+                    self.mouse['begin'][1],
+                    self.mouse['end'][0] -
+                    self.mouse['begin'][0],
+                    self.mouse['end'][1] -
+                    self.mouse['begin'][1])
                 r = self.modifyRectangle(r)
 
                 if self.mouse['use'] in ('addLine', 'addRectangle'):
@@ -1579,33 +1791,34 @@
                             # to avoid strange behavoiur
                             return
 
-                    self.Draw(pen = self.pen['line'], brush = self.brush['line'],
-                              pdc = self.pdcTmp, drawid = self.idZoomBoxTmp,
-                              pdctype = pdcType, bb = r, lineCoords = lineCoords)
+                    self.Draw(pen=self.pen['line'], brush=self.brush['line'],
+                              pdc=self.pdcTmp, drawid=self.idZoomBoxTmp,
+                              pdctype=pdcType, bb=r, lineCoords=lineCoords)
 
                 else:
-                    self.Draw(pen = self.pen['box'], brush = self.brush['box'],
-                              pdc = self.pdcTmp, drawid = self.idZoomBoxTmp,
-                              pdctype = 'rect', bb = r)
+                    self.Draw(pen=self.pen['box'], brush=self.brush['box'],
+                              pdc=self.pdcTmp, drawid=self.idZoomBoxTmp,
+                              pdctype='rect', bb=r)
 
             # panning
             if self.mouse["use"] == 'pan':
                 self.mouse['end'] = event.GetPosition()
-                self.Pan(begin = self.mouse['begin'], end = self.mouse['end'])
+                self.Pan(begin=self.mouse['begin'], end=self.mouse['end'])
                 self.mouse['begin'] = event.GetPosition()
 
             # move object
             if self.mouse['use'] == 'pointer' and self.dragId != -1:
                 self.mouse['end'] = event.GetPosition()
-                dx, dy = self.mouse['end'][0] - self.begin[0], self.mouse['end'][1] - self.begin[1]
+                dx, dy = self.mouse['end'][
+                    0] - self.begin[0], self.mouse['end'][1] - self.begin[1]
                 self.pdcObj.TranslateId(self.dragId, dx, dy)
                 self.pdcTmp.TranslateId(self.idBoxTmp, dx, dy)
                 self.pdcTmp.TranslateId(self.idResizeBoxTmp, dx, dy)
                 for id in self.idLinePointsTmp:
                     self.pdcTmp.TranslateId(id, dx, dy)
-                if self.instruction[self.dragId].type == 'text': 
-                    self.instruction[self.dragId]['coords'] = self.instruction[self.dragId]['coords'][0] + dx,\
-                        self.instruction[self.dragId]['coords'][1] + dy
+                if self.instruction[self.dragId].type == 'text':
+                    self.instruction[self.dragId]['coords'] = self.instruction[self.dragId][
+                        'coords'][0] + dx, self.instruction[self.dragId]['coords'][1] + dy
                 self.begin = event.GetPosition()
                 self.Refresh()
 
@@ -1621,32 +1834,44 @@
                     if self.constraint:
                         if width > height:
                             newWidth = width + diffX
-                            newHeight = height + diffX * (float(height) / width)
+                            newHeight = height + diffX * \
+                                (float(height) / width)
                         else:
                             newWidth = width + diffY * (float(width) / height)
                             newHeight = height + diffY
                     else:
                         newWidth = width + diffX
                         newHeight = height + diffY
-                        
+
                     if newWidth < 10 or newHeight < 10:
                         return
 
                     bounds = wx.Rect(x, y, newWidth, newHeight)
-                    self.Draw(pen = self.pen['map'], brush = self.brush['map'], pdc = self.pdcObj, drawid = self.dragId,
-                              pdctype = 'rectText', bb = bounds)
+                    self.Draw(
+                        pen=self.pen['map'],
+                        brush=self.brush['map'],
+                        pdc=self.pdcObj,
+                        drawid=self.dragId,
+                        pdctype='rectText',
+                        bb=bounds)
 
                 elif self.instruction[self.dragId].type == 'rectangle':
                     instr = self.instruction[self.dragId]
-                    rect = self.CanvasPaperCoordinates(rect = instr['rect'], canvasToPaper = False)
+                    rect = self.CanvasPaperCoordinates(
+                        rect=instr['rect'], canvasToPaper=False)
                     rect.SetWidth(rect.GetWidth() + diffX)
                     rect.SetHeight(rect.GetHeight() + diffY)
 
                     if rect.GetWidth() < 5 or rect.GetHeight() < 5:
                         return
 
-                    self.DrawGraphics(drawid = self.dragId, shape = 'rectangle', color = instr['color'],
-                                      fcolor = instr['fcolor'], width = instr['width'], bb = rect)
+                    self.DrawGraphics(
+                        drawid=self.dragId,
+                        shape='rectangle',
+                        color=instr['color'],
+                        fcolor=instr['fcolor'],
+                        width=instr['width'],
+                        bb=rect)
 
                 elif self.instruction[self.dragId].type == 'line':
                     instr = self.instruction[self.dragId]
@@ -1656,15 +1881,22 @@
                         pPaper = points[1]
                     else:
                         pPaper = points[0]
-                    pCanvas = self.CanvasPaperCoordinates(rect = Rect2DPS(pPaper, (0, 0)),
-                                                          canvasToPaper = False)[:2]
+                    pCanvas = self.CanvasPaperCoordinates(
+                        rect=Rect2DPS(pPaper, (0, 0)), canvasToPaper=False)[:2]
                     bounds = wx.RectPP(pCanvas, pos)
-                    self.DrawGraphics(drawid = self.dragId, shape = 'line', color = instr['color'],
-                                      width = instr['width'], bb = bounds, lineCoords = (pos, pCanvas))
+                    self.DrawGraphics(
+                        drawid=self.dragId,
+                        shape='line',
+                        color=instr['color'],
+                        width=instr['width'],
+                        bb=bounds,
+                        lineCoords=(
+                            pos,
+                            pCanvas))
 
                     # update paper coordinates
-                    points[self.currentLinePoint] = self.CanvasPaperCoordinates(rect = wx.RectPS(pos, (0, 0)),
-                                                                                canvasToPaper = True)[:2]
+                    points[self.currentLinePoint] = self.CanvasPaperCoordinates(
+                        rect=wx.RectPS(pos, (0, 0)), canvasToPaper=True)[:2]
 
                 self.RedrawSelectBox(self.dragId)
 
@@ -1674,173 +1906,188 @@
 
     def Pan(self, begin, end):
         """Move canvas while dragging.
-        
+
         :param begin: x,y coordinates of first point
         :param end: x,y coordinates of second point
         """
         view = begin[0] - end[0], begin[1] - end[1]
         zoomFactor = 1
         self.Zoom(zoomFactor, view)
-                
+
     def RecalculatePosition(self, ids):
         for id in ids:
             itype = self.instruction[id].type
             if itype in ('map', 'rectangle'):
-                self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
-                                                                           canvasToPaper = True)
+                self.instruction[id]['rect'] = self.CanvasPaperCoordinates(
+                    rect=self.pdcObj.GetIdBounds(id), canvasToPaper=True)
                 self.RecalculateEN()
-                
-            elif itype in ('mapinfo' ,'rasterLegend', 'vectorLegend', 'image', 'northArrow'):
-                self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
-                                                                           canvasToPaper = True)
-                self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
-                                                                            canvasToPaper = True)[:2] 
+
+            elif itype in ('mapinfo', 'rasterLegend', 'vectorLegend', 'image', 'northArrow'):
+                self.instruction[id]['rect'] = self.CanvasPaperCoordinates(
+                    rect=self.pdcObj.GetIdBounds(id), canvasToPaper=True)
+                self.instruction[id]['where'] = self.CanvasPaperCoordinates(
+                    rect=self.pdcObj.GetIdBounds(id), canvasToPaper=True)[:2]
                 if itype in ('image', 'northArrow'):
                     self.RecalculateEN()
 
             elif itype == 'point':
                 rect = self.pdcObj.GetIdBounds(id)
-                self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = rect,
-                                                                           canvasToPaper = True)
-                rect.OffsetXY(rect.GetWidth()/2, rect.GetHeight()/2)
-                self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = rect,
-                                                                            canvasToPaper = True)[:2]
+                self.instruction[id]['rect'] = self.CanvasPaperCoordinates(
+                    rect=rect, canvasToPaper=True)
+                rect.OffsetXY(rect.GetWidth() / 2, rect.GetHeight() / 2)
+                self.instruction[id]['where'] = self.CanvasPaperCoordinates(
+                    rect=rect, canvasToPaper=True)[: 2]
                 self.RecalculateEN()
 
             elif itype == 'line':
                 rect = self.pdcObj.GetIdBounds(id)
                 oldRect = self.instruction[id]['rect']
-                newRect = self.CanvasPaperCoordinates(rect = rect, canvasToPaper = True)
+                newRect = self.CanvasPaperCoordinates(
+                    rect=rect, canvasToPaper=True)
                 xDiff = newRect[0] - oldRect[0]
                 yDiff = newRect[1] - oldRect[1]
                 self.instruction[id]['rect'] = newRect
 
-                point1 = wx.Point2D(xDiff, yDiff) + self.instruction[id]['where'][0]
-                point2 = wx.Point2D(xDiff, yDiff) + self.instruction[id]['where'][1]
+                point1 = wx.Point2D(
+                    xDiff, yDiff) + self.instruction[id]['where'][0]
+                point2 = wx.Point2D(
+                    xDiff, yDiff) + self.instruction[id]['where'][1]
                 self.instruction[id]['where'] = [point1, point2]
-                
+
                 self.RecalculateEN()
 
-            elif  itype == 'scalebar':
-                self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
-                                                                           canvasToPaper = True)
+            elif itype == 'scalebar':
+                self.instruction[id]['rect'] = self.CanvasPaperCoordinates(
+                    rect=self.pdcObj.GetIdBounds(id), canvasToPaper=True)
 
-                
-                self.instruction[id]['where'] = self.instruction[id]['rect'].GetCentre()
-                
-            elif  itype == 'text':
+                self.instruction[id]['where'] = self.instruction[
+                    id]['rect'].GetCentre()
+
+            elif itype == 'text':
                 x, y = self.instruction[id]['coords'][0] - self.instruction[id]['xoffset'],\
                     self.instruction[id]['coords'][1] + self.instruction[id]['yoffset']
-                extent = self.parent.getTextExtent(textDict = self.instruction[id])
+                extent = self.parent.getTextExtent(
+                    textDict=self.instruction[id])
                 if self.instruction[id]['rotate'] is not None:
-                    rot = float(self.instruction[id]['rotate'])/180*pi 
+                    rot = float(self.instruction[id]['rotate']) / 180 * pi
                 else:
                     rot = 0
 
                 if self.instruction[id]['ref'].split()[0] == 'lower':
                     y += extent[1]
                 elif self.instruction[id]['ref'].split()[0] == 'center':
-                    y += extent[1]/2
+                    y += extent[1] / 2
                 if self.instruction[id]['ref'].split()[1] == 'right':
                     x += extent[0] * cos(rot)
                     y -= extent[0] * sin(rot)
                 elif self.instruction[id]['ref'].split()[1] == 'center':
-                    x += extent[0]/2 * cos(rot)
-                    y -= extent[0]/2 * sin(rot)
-                
-                self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = Rect2D(x, y, 0, 0),
-                                                                            canvasToPaper = True)[:2]
+                    x += extent[0] / 2 * cos(rot)
+                    y -= extent[0] / 2 * sin(rot)
+
+                self.instruction[id]['where'] = self.CanvasPaperCoordinates(
+                    rect=Rect2D(x, y, 0, 0), canvasToPaper=True)[:2]
                 self.RecalculateEN()
-        
+
     def ComputeZoom(self, rect):
         """Computes zoom factor and scroll view"""
         zoomFactor = 1
         cW, cH = self.GetClientSize()
         cW = float(cW)
-        if rect.IsEmpty(): # clicked on canvas
+        if rect.IsEmpty():  # clicked on canvas
             zoomFactor = 1.5
             if self.mouse['use'] == 'zoomout':
-                zoomFactor = 1./zoomFactor
-            x,y = self.mouse['begin']
-            xView = x - x/zoomFactor#x - cW/(zoomFactor * 2)
-            yView = y - y/zoomFactor#y - cH/(zoomFactor * 2)
+                zoomFactor = 1. / zoomFactor
+            x, y = self.mouse['begin']
+            xView = x - x / zoomFactor  # x - cW/(zoomFactor * 2)
+            yView = y - y / zoomFactor  # y - cH/(zoomFactor * 2)
 
-        else:   #dragging    
+        else:  # dragging
             rW, rH = float(rect.GetWidth()), float(rect.GetHeight())
             try:
-                zoomFactor = 1/max(rW/cW, rH/cH)
+                zoomFactor = 1 / max(rW / cW, rH / cH)
             except ZeroDivisionError:
                 zoomFactor = 1
-            # when zooming to full extent, in some cases, there was zoom 1.01..., which causes problem
+            # when zooming to full extent, in some cases, there was zoom
+            # 1.01..., which causes problem
             if abs(zoomFactor - 1) > 0.01:
-                zoomFactor = zoomFactor 
+                zoomFactor = zoomFactor
             else:
                 zoomFactor = 1.
 
-
             if self.mouse['use'] == 'zoomout':
-                zoomFactor = min(rW/cW, rH/cH)
+                zoomFactor = min(rW / cW, rH / cH)
             try:
-                if rW/rH > cW/cH:
-                    yView = rect.GetY() - (rW*(cH/cW) - rH)/2
+                if rW / rH > cW / cH:
+                    yView = rect.GetY() - (rW * (cH / cW) - rH) / 2
                     xView = rect.GetX()
-                    
+
                     if self.mouse['use'] == 'zoomout':
-                        x,y = rect.GetX() + (rW-(cW/cH)*rH)/2, rect.GetY()
+                        x, y = rect.GetX() + (rW - (cW / cH) * rH) / 2, rect.GetY()
                         xView, yView = -x, -y
                 else:
-                    xView = rect.GetX() - (rH*(cW/cH) - rW)/2
+                    xView = rect.GetX() - (rH * (cW / cH) - rW) / 2
                     yView = rect.GetY()
                     if self.mouse['use'] == 'zoomout':
-                        x,y = rect.GetX(), rect.GetY() + (rH-(cH/cW)*rW)/2
+                        x, y = rect.GetX(), rect.GetY() + (rH - (cH / cW) * rW) / 2
                         xView, yView = -x, -y
             except ZeroDivisionError:
                 xView, yView = rect.GetX(), rect.GetY()
         return zoomFactor, (int(xView), int(yView))
-    
-    
+
     def Zoom(self, zoomFactor, view):
         """Zoom to specified region, scroll view, redraw"""
         if not self.currScale:
             return
-        self.currScale = self.currScale*zoomFactor
-        
+        self.currScale = self.currScale * zoomFactor
+
         if self.currScale > 10 or self.currScale < 0.1:
-            self.currScale = self.currScale/zoomFactor
-            return 
+            self.currScale = self.currScale / zoomFactor
+            return
         if not self.preview:
             # redraw paper
             pRect = self.pdcPaper.GetIdBounds(self.pageId)
             pRect.OffsetXY(-view[0], -view[1])
-            pRect = self.ScaleRect(rect = pRect, scale = zoomFactor)
+            pRect = self.ScaleRect(rect=pRect, scale=zoomFactor)
             self.DrawPaper(pRect)
-            
-            #redraw objects
+
+            # redraw objects
             for id in self.objectId:
                 type = self.instruction[id].type
                 if type == 'labels':  # why it's here? it should not
                     continue
                 oRect = self.CanvasPaperCoordinates(
-                    rect = self.instruction[id]['rect'], canvasToPaper = False)
-                
+                    rect=self.instruction[id]['rect'], canvasToPaper=False)
+
                 if type == 'text':
-                    coords = self.instruction[id]['coords']# recalculate coordinates, they are not equal to BB
-                    self.instruction[id]['coords'] = coords = [(int(coord) - view[i]) * zoomFactor
-                                                               for i, coord in enumerate(coords)]
-                    extent = self.parent.getTextExtent(textDict = self.instruction[id])
+                    # recalculate coordinates, they are not equal to BB
+                    coords = self.instruction[id]['coords']
+                    self.instruction[id]['coords'] = coords = [
+                        (int(coord) - view[i]) * zoomFactor for i, coord in enumerate(coords)]
+                    extent = self.parent.getTextExtent(
+                        textDict=self.instruction[id])
                     if self.instruction[id]['rotate']:
-                        rot = float(self.instruction[id]['rotate']) 
+                        rot = float(self.instruction[id]['rotate'])
                     else:
                         rot = 0
-                    self.instruction[id]['rect'] = bounds = self.parent.getModifiedTextBounds(coords[0], coords[1], extent, rot)
-                    self.DrawRotText(pdc = self.pdcObj, drawId = id, textDict = self.instruction[id],
-                                     coords = coords, bounds = bounds )
+                    self.instruction[id]['rect'] = bounds = self.parent.getModifiedTextBounds(
+                        coords[0], coords[1], extent, rot)
+                    self.DrawRotText(
+                        pdc=self.pdcObj,
+                        drawId=id,
+                        textDict=self.instruction[id],
+                        coords=coords,
+                        bounds=bounds)
 
                     self.pdcObj.SetIdBounds(id, bounds)
 
                 elif type == 'northArrow':
-                    self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj,
-                              drawid = id, pdctype = 'bitmap', bb = oRect)
+                    self.Draw(
+                        pen=self.pen[type],
+                        brush=self.brush[type],
+                        pdc=self.pdcObj,
+                        drawid=id,
+                        pdctype='bitmap',
+                        bb=oRect)
 
                 elif type in ('point', 'line', 'rectangle'):
                     instr = self.instruction[id]
@@ -1853,47 +2100,59 @@
                         width = self.instruction[id]['width']
                     if type in ('line'):
                         point1, point2 = instr['where'][0], instr['where'][1]
-                        point1 = self.CanvasPaperCoordinates(rect = Rect2DPS(point1, (0, 0)),
-                                                             canvasToPaper = False)[:2]
-                        point2 = self.CanvasPaperCoordinates(rect = Rect2DPS(point2, (0, 0)),
-                                                             canvasToPaper = False)[:2]
+                        point1 = self.CanvasPaperCoordinates(
+                            rect=Rect2DPS(point1, (0, 0)), canvasToPaper=False)[:2]
+                        point2 = self.CanvasPaperCoordinates(
+                            rect=Rect2DPS(point2, (0, 0)), canvasToPaper=False)[:2]
                         coords = (point1, point2)
 
-                    self.DrawGraphics(drawid = id, shape = type, bb = oRect, lineCoords = coords,
-                                    color = color, fcolor = fcolor, width = width)
+                    self.DrawGraphics(
+                        drawid=id,
+                        shape=type,
+                        bb=oRect,
+                        lineCoords=coords,
+                        color=color,
+                        fcolor=fcolor,
+                        width=width)
 
                 else:
-                    self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj,
-                              drawid = id, pdctype = 'rectText', bb = oRect)
-            #redraw tmp objects
+                    self.Draw(
+                        pen=self.pen[type],
+                        brush=self.brush[type],
+                        pdc=self.pdcObj,
+                        drawid=id,
+                        pdctype='rectText',
+                        bb=oRect)
+            # redraw tmp objects
             if self.dragId != -1:
                 self.RedrawSelectBox(self.dragId)
-                
-        #redraw preview
-        else: # preview mode    
+
+        # redraw preview
+        else:  # preview mode
             imageRect = self.pdcImage.GetIdBounds(self.imageId)
             imageRect.OffsetXY(-view[0], -view[1])
-            imageRect = self.ScaleRect(rect = imageRect, scale = zoomFactor)
+            imageRect = self.ScaleRect(rect=imageRect, scale=zoomFactor)
             self.DrawImage(imageRect)
-        
+
     def ZoomAll(self):
         """Zoom to full extent"""
         if not self.preview:
             bounds = self.pdcPaper.GetIdBounds(self.pageId)
         else:
             bounds = self.pdcImage.GetIdBounds(self.imageId)
-        zoomP = bounds.Inflate(bounds.width/20, bounds.height/20)
+        zoomP = bounds.Inflate(bounds.width / 20, bounds.height / 20)
         zoomFactor, view = self.ComputeZoom(zoomP)
         self.Zoom(zoomFactor, view)
-        
-    def Draw(self, pen, brush, pdc, drawid = None, pdctype = 'rect', bb = wx.Rect(0,0,0,0), lineCoords = None): 
+
+    def Draw(self, pen, brush, pdc, drawid=None, pdctype='rect',
+             bb=wx.Rect(0, 0, 0, 0), lineCoords=None):
         """Draw object with given pen and brush.
 
         :param pdc: PseudoDC
         :param pdctype: 'bitmap'/'rectText'/'rect'/'point'/'line'
         :param bb: bounding box
         :param lineCoords: coordinates of line start, end points (wx.Point, wx.Point)
-        """  
+        """
         if drawid is None:
             drawid = wx.NewId()
         bb = bb.Get()
@@ -1902,20 +2161,25 @@
         pdc.SetId(drawid)
         pdc.SetPen(pen)
         pdc.SetBrush(brush)
-        
+
         if pdctype == 'bitmap':
             if havePILImage:
                 file = self.instruction[drawid]['epsfile']
                 rotation = self.instruction[drawid]['rotate']
-                self.DrawBitmap(pdc = pdc, filePath = file, rotation = rotation, bbox = bb)
-            else: # draw only rectangle with label
+                self.DrawBitmap(
+                    pdc=pdc,
+                    filePath=file,
+                    rotation=rotation,
+                    bbox=bb)
+            else:  # draw only rectangle with label
                 pdctype = 'rectText'
-                
+
         if pdctype in ('rect', 'rectText'):
             pdc.DrawRectangle(*bb)
-            
+
         if pdctype == 'rectText':
-            dc = wx.ClientDC(self) # dc created because of method GetTextExtent, which pseudoDC lacks
+            # dc created because of method GetTextExtent, which pseudoDC lacks
+            dc = wx.ClientDC(self)
             font = dc.GetFont()
             size = 10
             font.SetPointSize(size)
@@ -1923,8 +2187,8 @@
             dc.SetFont(font)
             pdc.SetFont(font)
             text = '\n'.join(self.itemLabels[drawid])
-            w,h,lh = dc.GetMultiLineTextExtent(text)
-            textExtent = (w,h)
+            w, h, lh = dc.GetMultiLineTextExtent(text)
+            textExtent = (w, h)
             textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
             r = map(int, bb)
             while not wx.Rect(*r).ContainsRect(textRect) and size >= 8:
@@ -1934,15 +2198,15 @@
                 pdc.SetFont(font)
                 textExtent = dc.GetTextExtent(text)
                 textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
-            pdc.SetTextForeground(wx.Colour(100,100,100,200)) 
+            pdc.SetTextForeground(wx.Colour(100, 100, 100, 200))
             pdc.SetBackgroundMode(wx.TRANSPARENT)
-            pdc.DrawLabel(text = text, rect = textRect)
+            pdc.DrawLabel(text=text, rect=textRect)
 
         elif pdctype == 'point':
-            pdc.DrawCircle(x = bb[0] + bb[2] / 2,
-                           y = bb[1] + bb[3] / 2,
-                           radius = bb[2] / 2)
-                           
+            pdc.DrawCircle(x=bb[0] + bb[2] / 2,
+                           y=bb[1] + bb[3] / 2,
+                           radius=bb[2] / 2)
+
         elif pdctype == 'line':
             pdc.DrawLinePoint(lineCoords[0], lineCoords[1])
 
@@ -1951,8 +2215,9 @@
         self.Refresh()
 
         return drawid
-    
-    def DrawGraphics(self, drawid, shape, color, bb, width = None, fcolor = None, lineCoords = None):
+
+    def DrawGraphics(self, drawid, shape, color, bb,
+                     width=None, fcolor=None, lineCoords=None):
         """Draw point/line/rectangle with given color and width
 
         :param drawid: id of drawn object
@@ -1963,78 +2228,92 @@
         :param bb: bounding box
         :param lineCoords: line coordinates (for line only)
         """
-        pdctype = {'point'     : 'point',
-                   'line'      : 'line',
-                   'rectangle' : 'rect'}
+        pdctype = {'point': 'point',
+                   'line': 'line',
+                   'rectangle': 'rect'}
 
         if color == 'none':
             pen = wx.TRANSPARENT_PEN
         else:
             if width is not None:
                 units = UnitConversion(self)
-                width = int(units.convert(value = width, fromUnit = 'point', toUnit = 'pixel') * self.currScale)
+                width = int(
+                    units.convert(
+                        value=width,
+                        fromUnit='point',
+                        toUnit='pixel') *
+                    self.currScale)
             else:
                 width = 2
-            pen = wx.Pen(colour = convertRGB(color), width = width)
-            pen.SetCap(wx.CAP_BUTT) # this is how ps.map draws
+            pen = wx.Pen(colour=convertRGB(color), width=width)
+            pen.SetCap(wx.CAP_BUTT)  # this is how ps.map draws
 
         brush = wx.TRANSPARENT_BRUSH
         if fcolor and fcolor != 'none':
-            brush = wx.Brush(colour = convertRGB(fcolor))
-        
-        self.Draw(pen = pen, brush = brush, pdc = self.pdcObj, pdctype = pdctype[shape],
-                  drawid = drawid, bb = bb, lineCoords = lineCoords)
+            brush = wx.Brush(colour=convertRGB(fcolor))
 
+        self.Draw(
+            pen=pen,
+            brush=brush,
+            pdc=self.pdcObj,
+            pdctype=pdctype[shape],
+            drawid=drawid,
+            bb=bb,
+            lineCoords=lineCoords)
+
     def DrawBitmap(self, pdc, filePath, rotation, bbox):
         """Draw bitmap using PIL"""
         pImg = PILImage.open(filePath)
         if sys.platform == 'win32' and \
            'eps' in os.path.splitext(filePath)[1].lower():
-               import types
-               pImg.load = types.MethodType(loadPSForWindows, pImg)
-        
+            import types
+            pImg.load = types.MethodType(loadPSForWindows, pImg)
+
         if rotation:
             # get rid of black background
             pImg = pImg.convert("RGBA")
-            rot = pImg.rotate(rotation, expand = 1)
+            rot = pImg.rotate(rotation, expand=1)
             new = PILImage.new('RGBA', rot.size, (255,) * 4)
             pImg = PILImage.composite(rot, new, rot)
-        pImg = pImg.resize((int(bbox[2]), int(bbox[3])), resample = PILImage.BICUBIC)
+        pImg = pImg.resize(
+            (int(
+                bbox[2]), int(
+                bbox[3])), resample=PILImage.BICUBIC)
         img = PilImageToWxImage(pImg)
         bitmap = img.ConvertToBitmap()
         mask = wx.Mask(bitmap, wx.WHITE)
         bitmap.SetMask(mask)
-        pdc.DrawBitmap(bitmap, bbox[0], bbox[1], useMask = True)
-        
+        pdc.DrawBitmap(bitmap, bbox[0], bbox[1], useMask=True)
+
     def DrawRotText(self, pdc, drawId, textDict, coords, bounds):
         if textDict['rotate']:
-            rot = float(textDict['rotate']) 
+            rot = float(textDict['rotate'])
         else:
             rot = 0
 
         if textDict['background'] != 'none':
-            background = textDict['background'] 
+            background = textDict['background']
         else:
             background = None
 
         pdc.RemoveId(drawId)
         pdc.SetId(drawId)
         pdc.BeginDrawing()
-        
+
         # border is not redrawn when zoom changes, why?
-##        if textDict['border'] != 'none' and not rot:
+# if textDict['border'] != 'none' and not rot:
 ##            units = UnitConversion(self)
-##            borderWidth = units.convert(value = textDict['width'],
-##                                        fromUnit = 'point', toUnit = 'pixel' ) * self.currScale
+# borderWidth = units.convert(value = textDict['width'],
+# fromUnit = 'point', toUnit = 'pixel' ) * self.currScale
 ##            pdc.SetPen(wx.Pen(colour = convertRGB(textDict['border']), width = borderWidth))
-##            pdc.DrawRectangle(*bounds)
-            
+# pdc.DrawRectangle(*bounds)
+
         if background:
             pdc.SetTextBackground(convertRGB(background))
             pdc.SetBackgroundMode(wx.SOLID)
         else:
             pdc.SetBackgroundMode(wx.TRANSPARENT)
-        
+
         fn = self.parent.makePSFont(textDict)
 
         pdc.SetFont(fn)
@@ -2043,28 +2322,27 @@
             pdc.DrawLabel(text=textDict['text'], rect=bounds)
         else:
             pdc.DrawRotatedText(textDict['text'], coords[0], coords[1], rot)
-        
+
         pdc.SetIdBounds(drawId, wx.Rect(*bounds))
         self.Refresh()
         pdc.EndDrawing()
-        
+
     def DrawImage(self, rect):
         """Draw preview image to pseudoDC"""
         self.pdcImage.ClearId(self.imageId)
         self.pdcImage.SetId(self.imageId)
         img = self.image
-        
 
         if img.GetWidth() != rect.width or img.GetHeight() != rect.height:
             img = img.Scale(rect.width, rect.height)
         bitmap = img.ConvertToBitmap()
-        
+
         self.pdcImage.BeginDrawing()
         self.pdcImage.DrawBitmap(bitmap, rect.x, rect.y)
         self.pdcImage.SetIdBounds(self.imageId, rect)
         self.pdcImage.EndDrawing()
         self.Refresh()
-        
+
     def DrawPaper(self, rect):
         """Draw paper and margins"""
         page = self.instruction[self.pageId]
@@ -2073,110 +2351,128 @@
         h = (page['Height'] - page['Top'] - page['Bottom']) / scale
         x = page['Left'] / scale + rect.GetX()
         y = page['Top'] / scale + rect.GetY()
-        
+
         self.pdcPaper.BeginDrawing()
         self.pdcPaper.RemoveId(self.pageId)
         self.pdcPaper.SetId(self.pageId)
         self.pdcPaper.SetPen(self.pen['paper'])
         self.pdcPaper.SetBrush(self.brush['paper'])
         self.pdcPaper.DrawRectangleRect(rect)
-        
+
         self.pdcPaper.SetPen(self.pen['margins'])
         self.pdcPaper.SetBrush(self.brush['margins'])
         self.pdcPaper.DrawRectangle(x, y, w, h)
-        
+
         self.pdcPaper.SetIdBounds(self.pageId, rect)
         self.pdcPaper.EndDrawing()
         self.Refresh()
 
-        
     def ImageRect(self):
         """Returns image centered in canvas, computes scale"""
         img = wx.Image(self.imgName, wx.BITMAP_TYPE_PNG)
         cW, cH = self.GetClientSize()
         iW, iH = img.GetWidth(), img.GetHeight()
 
-        self.currScale = min(float(cW)/iW, float(cH)/iH)
+        self.currScale = min(float(cW) / iW, float(cH) / iH)
         iW = iW * self.currScale
         iH = iH * self.currScale
-        x = cW/2 - iW/2
-        y = cH/2 - iH/2
+        x = cW / 2 - iW / 2
+        y = cH / 2 - iH / 2
         imageRect = wx.Rect(x, y, iW, iH)
 
-        return imageRect 
-    
+        return imageRect
+
     def RedrawSelectBox(self, id):
         """Redraws select box when selected object changes its size"""
         if self.dragId == id:
             rect = self.pdcObj.GetIdBounds(id)
             if self.instruction[id].type != 'line':
-                rect = rect.Inflate(3,3)
+                rect = rect.Inflate(3, 3)
             # draw select box around object
-            self.Draw(pen = self.pen['select'], brush = self.brush['select'], pdc = self.pdcTmp,
-                      drawid = self.idBoxTmp, pdctype = 'rect', bb = rect)
-            
+            self.Draw(
+                pen=self.pen['select'],
+                brush=self.brush['select'],
+                pdc=self.pdcTmp,
+                drawid=self.idBoxTmp,
+                pdctype='rect',
+                bb=rect)
+
             # draw small marks signalizing resizing
             if self.instruction[id].type in ('map', 'rectangle'):
                 controlP = self.pdcObj.GetIdBounds(id).GetBottomRight()
-                rect  = wx.RectPS(controlP, self.resizeBoxSize)
-                self.Draw(pen = self.pen['resize'], brush = self.brush['resize'], pdc = self.pdcTmp,
-                          drawid = self.idResizeBoxTmp, pdctype = 'rect', bb = rect)
+                rect = wx.RectPS(controlP, self.resizeBoxSize)
+                self.Draw(
+                    pen=self.pen['resize'],
+                    brush=self.brush['resize'],
+                    pdc=self.pdcTmp,
+                    drawid=self.idResizeBoxTmp,
+                    pdctype='rect',
+                    bb=rect)
 
             elif self.instruction[id].type == 'line':
                 p1Paper = self.instruction[id]['where'][0]
                 p2Paper = self.instruction[id]['where'][1]
-                p1Canvas = self.CanvasPaperCoordinates(rect = Rect2DPS(p1Paper, (0, 0)), canvasToPaper = False)[:2]
-                p2Canvas = self.CanvasPaperCoordinates(rect = Rect2DPS(p2Paper, (0, 0)), canvasToPaper = False)[:2]
+                p1Canvas = self.CanvasPaperCoordinates(
+                    rect=Rect2DPS(p1Paper, (0, 0)), canvasToPaper=False)[:2]
+                p2Canvas = self.CanvasPaperCoordinates(
+                    rect=Rect2DPS(p2Paper, (0, 0)), canvasToPaper=False)[:2]
                 rect = []
                 box = wx.RectS(self.resizeBoxSize)
                 rect.append(box.CenterIn(wx.RectPS(p1Canvas, wx.Size())))
                 rect.append(box.CenterIn(wx.RectPS(p2Canvas, wx.Size())))
                 for i, point in enumerate((p1Canvas, p2Canvas)):
-                    self.Draw(pen = self.pen['resize'], brush = self.brush['resize'], pdc = self.pdcTmp,
-                              drawid = self.idLinePointsTmp[i], pdctype = 'rect', bb = rect[i])
-        
+                    self.Draw(
+                        pen=self.pen['resize'],
+                        brush=self.brush['resize'],
+                        pdc=self.pdcTmp,
+                        drawid=self.idLinePointsTmp[i],
+                        pdctype='rect',
+                        bb=rect[i])
+
     def UpdateMapLabel(self):
         """Updates map frame label"""
 
         vector = self.instruction.FindInstructionByType('vector')
         if vector:
-            vectorId = vector.id 
+            vectorId = vector.id
         else:
             vectorId = None
 
         raster = self.instruction.FindInstructionByType('raster')
         if raster:
-            rasterId = raster.id 
+            rasterId = raster.id
         else:
             rasterId = None
 
         rasterName = 'None'
         if rasterId:
             rasterName = self.instruction[rasterId]['raster'].split('@')[0]
-            
+
         mapId = self.instruction.FindInstructionByType('map').id
         self.itemLabels[mapId] = []
         self.itemLabels[mapId].append(self.itemLabelsDict['map'])
         self.itemLabels[mapId].append("raster: " + rasterName)
-        if vectorId: 
+        if vectorId:
             for map in self.instruction[vectorId]['list']:
-                self.itemLabels[mapId].append('vector: ' + map[0].split('@')[0])
-                
+                self.itemLabels[mapId].append(
+                    'vector: ' + map[0].split('@')[0])
+
         labels = self.instruction.FindInstructionByType('labels')
         if labels:
             labelFiles = self.instruction[labels.id]['labels']
             if not labelFiles:
                 return
             labelFiles = [lFile.split('@')[0] for lFile in labelFiles]
-            self.itemLabels[mapId].append(_("labels: ") + ', '.join(labelFiles))
-            
+            self.itemLabels[mapId].append(
+                _("labels: ") + ', '.join(labelFiles))
+
     def UpdateLabel(self, itype, id):
         self.itemLabels[id] = []
         self.itemLabels[id].append(self.itemLabelsDict[itype])
         if itype == 'image':
             file = os.path.basename(self.instruction[id]['epsfile'])
             self.itemLabels[id].append(file)
-        
+
     def OnSize(self, event):
         """Init image size to match window size
         """
@@ -2185,12 +2481,12 @@
             self.ZoomAll()
         self.OnIdle(None)
         event.Skip()
-        
+
     def OnIdle(self, event):
         """Only re-render a image during idle time instead of
         multiple times during resizing.
         """
-        
+
         width, height = self.GetClientSize()
         # Make new off screen bitmap: this bitmap will always have the
         # current drawing in it, so it can be used to save the image
@@ -2198,9 +2494,8 @@
         self._buffer = wx.EmptyBitmap(width, height)
         # re-render image on idle
         self.resize = True
-        
+
     def ScaleRect(self, rect, scale):
         """Scale rectangle"""
-        return wx.Rect(rect.GetLeft()*scale, rect.GetTop()*scale,
-                       rect.GetSize()[0]*scale, rect.GetSize()[1]*scale)   
-
+        return wx.Rect(rect.GetLeft() * scale, rect.GetTop() * scale,
+                       rect.GetSize()[0] * scale, rect.GetSize()[1] * scale)

Modified: grass/trunk/gui/wxpython/psmap/g.gui.psmap.py
===================================================================
--- grass/trunk/gui/wxpython/psmap/g.gui.psmap.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/psmap/g.gui.psmap.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -39,10 +39,10 @@
     options, flags = gscript.parser()
 
     import wx
-    
+
     from grass.script.setup import set_gui_path
     set_gui_path()
-    
+
     from core.globalvar import CheckWxVersion
     from psmap.frame import PsMapFrame
 

Modified: grass/trunk/gui/wxpython/psmap/instructions.py
===================================================================
--- grass/trunk/gui/wxpython/psmap/instructions.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/psmap/instructions.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -41,33 +41,37 @@
 import grass.script as grass
 from grass.script.task import cmdlist_to_tuple
 
-from core.gcmd          import RunCommand, GError, GMessage, GWarning
-from core.utils         import GetCmdString, _
-from dbmgr.vinfo        import VectorDBInfo
-from psmap.utils        import *
+from core.gcmd import RunCommand, GError, GMessage, GWarning
+from core.utils import GetCmdString, _
+from dbmgr.vinfo import VectorDBInfo
+from psmap.utils import *
 
+
 class Instruction:
     """Class which represents instruction file"""
+
     def __init__(self, parent, objectsToDraw):
-        
+
         self.parent = parent
         self.objectsToDraw = objectsToDraw
-        #here are kept objects like mapinfo, rasterlegend, etc.
+        # here are kept objects like mapinfo, rasterlegend, etc.
         self.instruction = list()
-        
+
     def __str__(self):
         """Returns text for instruction file"""
-        comment = "# timestamp: " + strftime("%Y-%m-%d %H:%M", localtime()) + '\n'
+        comment = "# timestamp: " + strftime("%Y-%m-%d %H:%M",
+                                             localtime()) + '\n'
         env = grass.gisenv()
         comment += "# location: %s\n" % env['LOCATION_NAME']
         comment += "# mapset: %s\n" % env['MAPSET']
-        comment += "# page orientation: %s\n" % self.FindInstructionByType('page')['Orientation']
+        comment += "# page orientation: %s\n" % self.FindInstructionByType('page')[
+            'Orientation']
         border = ''
         if not self.FindInstructionByType('map'):
             border = 'border n\n'
         text = [str(each) for each in self.instruction]
         return comment + border + '\n'.join(text) + '\nend'
-    
+
     def __getitem__(self, id):
         for each in self.instruction:
             if each.id == id:
@@ -80,25 +84,26 @@
             if each.id == id:
                 return True
         return False
-    
+
     def __delitem__(self, id):
         """Delete instruction"""
         for each in self.instruction:
             if each.id == id:
                 if each.type == 'map':
-                    #must remove raster, vector layers too
-                    vektor = self.FindInstructionByType('vector', list = True)
-                    vProperties = self.FindInstructionByType('vProperties', list = True)
-                    raster = self.FindInstructionByType('raster', list = True)
+                    # must remove raster, vector layers too
+                    vektor = self.FindInstructionByType('vector', list=True)
+                    vProperties = self.FindInstructionByType(
+                        'vProperties', list=True)
+                    raster = self.FindInstructionByType('raster', list=True)
                     for item in vektor + vProperties + raster:
                         if item in self.instruction:
                             self.instruction.remove(item)
-                            
+
                 self.instruction.remove(each)
                 if id in self.objectsToDraw:
                     self.objectsToDraw.remove(id)
                 return
-            
+
     def AddInstruction(self, instruction):
         """Add instruction"""
         # add to instructions
@@ -107,14 +112,14 @@
         else:
             self.instruction.append(instruction)
         # add to drawable objects
-        if instruction.type not in ('page', 'raster', 'vector', 'vProperties', 'initMap'):
+        if instruction.type not in (
+                'page', 'raster', 'vector', 'vProperties', 'initMap'):
             if instruction.type == 'map':
-                self.objectsToDraw.insert(0, instruction.id) 
+                self.objectsToDraw.insert(0, instruction.id)
             else:
-                self.objectsToDraw.append(instruction.id) 
-                
-            
-    def FindInstructionByType(self, type, list = False):
+                self.objectsToDraw.append(instruction.id)
+
+    def FindInstructionByType(self, type, list=False):
         """Find instruction(s) with the given type"""
         inst = []
         for each in self.instruction:
@@ -123,7 +128,7 @@
         if len(inst) == 1 and not list:
             return inst[0]
         return inst
-    
+
     def Read(self, filename):
         """Reads instruction file and creates instruction objects"""
         self.filename = filename
@@ -131,38 +136,47 @@
         try:
             file = open(filename, 'r')
         except IOError:
-            GError(message = _("Unable to open file\n%s") % filename)
+            GError(message=_("Unable to open file\n%s") % filename)
             return
         # first read file to get information about region and scaletype
         isRegionComment = False
         orientation = 'Portrait'
         for line in file:
             if '# g.region' in line:
-                self.SetRegion(regionInstruction = line)
+                self.SetRegion(regionInstruction=line)
                 isRegionComment = True
                 break
             if '# page orientation' in line:
                 orientation = line.split(':')[-1].strip()
-                
+
         if not isRegionComment:
-            self.SetRegion(regionInstruction = None)
+            self.SetRegion(regionInstruction=None)
         # then run ps.map -b to get information for maploc
-        # compute scale and center 
+        # compute scale and center
         map = self.FindInstructionByType('map')
         region = grass.region()
-        map['center'] = (region['n'] + region['s']) / 2, (region['w'] + region['e']) / 2
-        mapRect = GetMapBounds(self.filename, portrait = (orientation == 'Portrait'))
+        map['center'] = (region['n'] + region['s']
+                         ) / 2, (region['w'] + region['e']) / 2
+        mapRect = GetMapBounds(
+            self.filename, portrait=(
+                orientation == 'Portrait'))
         map['rect'] = mapRect
         proj = projInfo()
         toM = 1.0
         if proj['units']:
             toM = float(proj['meters'])
         units = UnitConversion(self.parent)
-        w = units.convert(value = mapRect.Get()[2], fromUnit = 'inch', toUnit = 'meter') / toM
+        w = units.convert(
+            value=mapRect.Get()[2],
+            fromUnit='inch',
+            toUnit='meter') / toM
         map['scale'] = w / abs((region['w'] - region['e']))
-        
-        SetResolution(dpi = 300, width = map['rect'].width, height = map['rect'].height)
-        
+
+        SetResolution(
+            dpi=300,
+            width=map['rect'].width,
+            height=map['rect'].height)
+
         # read file again, now with information about map bounds
         isBuffer = False
         buffer = []
@@ -170,7 +184,7 @@
         vectorMapNumber = 1
         file.seek(0)
         for line in file:
-            if not line.strip(): 
+            if not line.strip():
                 continue
             line = line.strip()
             if isBuffer:
@@ -188,40 +202,46 @@
                         vectorMapNumber += 1
                     elif instruction == 'paper':
                         kwargs['Orientation'] = orientation
-                        
+
                     ok = self.SendToRead(instruction, buffer, **kwargs)
-                    if not ok: return False
+                    if not ok:
+                        return False
                     buffer = []
-                continue 
-            
+                continue
+
             elif line.startswith('paper'):
                 instruction = 'paper'
                 isBuffer = True
                 buffer.append(line)
-            
+
             elif line.startswith('border'):
                 if line.split()[1].lower() in ('n', 'no', 'none'):
                     ok = self.SendToRead('border', [line])
-                    if not ok: return False
+                    if not ok:
+                        return False
                 elif line.split()[1].lower() in ('y', 'yes'):
                     instruction = 'border'
                     isBuffer = True
                     buffer.append(line)
-            
+
             elif line.startswith('scale '):
                 if isBuffer:
                     continue
-                ok = self.SendToRead('scale', line, isRegionComment = isRegionComment)
-                if not ok: return False
-            
+                ok = self.SendToRead(
+                    'scale', line, isRegionComment=isRegionComment)
+                if not ok:
+                    return False
+
             elif line.startswith('maploc'):
-                ok = self.SendToRead(instruction = 'maploc', text = line)
-                if not ok: return False
-                
+                ok = self.SendToRead(instruction='maploc', text=line)
+                if not ok:
+                    return False
+
             elif line.startswith('raster'):
-                ok = self.SendToRead(instruction = 'raster', text = line)
-                if not ok: return False
-            
+                ok = self.SendToRead(instruction='raster', text=line)
+                if not ok:
+                    return False
+
             elif line.startswith('mapinfo'):
                 instruction = 'mapinfo'
                 isBuffer = True
@@ -230,13 +250,13 @@
             elif line.startswith('scalebar'):
                 instruction = 'scalebar'
                 isBuffer = True
-                buffer.append(line) 
-            
+                buffer.append(line)
+
             elif line.startswith('text'):
                 instruction = 'text'
                 isBuffer = True
                 buffer.append(line)
-                
+
             elif line.startswith('eps'):
                 instruction = 'eps'
                 isBuffer = True
@@ -255,30 +275,31 @@
             elif line.startswith('rectangle'):
                 instruction = 'rectangle'
                 isBuffer = True
-                buffer.append(line) 
-            
+                buffer.append(line)
+
             elif line.startswith('colortable'):
-                if len(line.split()) == 2 and line.split()[1].lower() in ('n', 'no', 'none'):
+                if len(line.split()) == 2 and line.split()[
+                        1].lower() in ('n', 'no', 'none'):
                     break
                 instruction = 'colortable'
                 isBuffer = True
-                buffer.append(line) 
-        
+                buffer.append(line)
+
             elif line.startswith('vlegend'):
                 instruction = 'vlegend'
                 isBuffer = True
-                buffer.append(line) 
-                
+                buffer.append(line)
+
             elif line.startswith('vpoints'):
                 instruction = 'vpoints'
                 isBuffer = True
-                buffer.append(line) 
-                
+                buffer.append(line)
+
             elif line.startswith('vlines'):
                 instruction = 'vlines'
                 isBuffer = True
                 buffer.append(line)
-                
+
             elif line.startswith('vareas'):
                 instruction = 'vareas'
                 isBuffer = True
@@ -288,16 +309,13 @@
                 instruction = 'labels'
                 isBuffer = True
                 buffer.append(line)
-            
 
-
-        
         rasterLegend = self.FindInstructionByType('rasterLegend')
         raster = self.FindInstructionByType('raster')
         page = self.FindInstructionByType('page')
         vector = self.FindInstructionByType('vector')
         vectorLegend = self.FindInstructionByType('vectorLegend')
-        vectorMaps = self.FindInstructionByType('vProperties', list = True)
+        vectorMaps = self.FindInstructionByType('vProperties', list=True)
 
         # check (in case of scaletype 0) if map is drawn also
         map['drawMap'] = False
@@ -316,41 +334,52 @@
             if rasterLegend['rasterDefault'] and raster:
                 rasterLegend['raster'] = raster['raster']
                 if not rasterLegend['discrete']:
-                    rasterType = getRasterType(map = rasterLegend['raster'])
+                    rasterType = getRasterType(map=rasterLegend['raster'])
                     if rasterType == 'CELL':
                         rasterLegend['discrete'] = 'y'
                     else:
                         rasterLegend['discrete'] = 'n'
-            
-            #estimate size
-            height = rasterLegend.EstimateHeight(raster = rasterLegend['raster'], discrete = rasterLegend['discrete'], 
-                                                 fontsize = rasterLegend['fontsize'],
-                                                 cols = rasterLegend['cols'], 
-                                                 height = rasterLegend['height'])
-            width = rasterLegend.EstimateWidth(raster = rasterLegend['raster'], discrete = rasterLegend['discrete'], 
-                                               fontsize = rasterLegend['fontsize'],
-                                               cols = rasterLegend['cols'] , 
-                                               width = rasterLegend['width'],
-                                               paperInstr = page)
-            rasterLegend['rect'] = Rect2D(x = float(rasterLegend['where'][0]), y = float(rasterLegend['where'][1]),
-                                          width = width, height = height)
-            
-        # vectors, vlegend        
-        
+
+            # estimate size
+            height = rasterLegend.EstimateHeight(
+                raster=rasterLegend['raster'],
+                discrete=rasterLegend['discrete'],
+                fontsize=rasterLegend['fontsize'],
+                cols=rasterLegend['cols'],
+                height=rasterLegend['height'])
+            width = rasterLegend.EstimateWidth(
+                raster=rasterLegend['raster'],
+                discrete=rasterLegend['discrete'],
+                fontsize=rasterLegend['fontsize'],
+                cols=rasterLegend['cols'],
+                width=rasterLegend['width'],
+                paperInstr=page)
+            rasterLegend['rect'] = Rect2D(
+                x=float(rasterLegend['where'][0]),
+                y=float(rasterLegend['where'][1]),
+                width=width, height=height)
+
+        # vectors, vlegend
+
         if vector:
             for vmap in vectorMaps:
                 for i, each in enumerate(vector['list']):
                     if each[2] == vmap.id:
-                        
+
                         vector['list'][i][4] = vmap['label']
                         vector['list'][i][3] = vmap['lpos']
             if vectorLegend:
-                size = vectorLegend.EstimateSize(vectorInstr = vector, fontsize = vectorLegend['fontsize'],
-                                                 width = vectorLegend['width'], cols = vectorLegend['cols'])                            
-                vectorLegend['rect'] = Rect2D(x = float(vectorLegend['where'][0]), y = float(vectorLegend['where'][1]),
-                                              width = size[0], height = size[1])
-        
-        
+                size = vectorLegend.EstimateSize(
+                    vectorInstr=vector,
+                    fontsize=vectorLegend['fontsize'],
+                    width=vectorLegend['width'],
+                    cols=vectorLegend['cols'])
+                vectorLegend['rect'] = Rect2D(
+                    x=float(vectorLegend['where'][0]),
+                    y=float(vectorLegend['where'][1]),
+                    width=size[0],
+                    height=size[1])
+
         page = self.FindInstructionByType('page')
         if not page:
             page = PageSetup(wx.NewId())
@@ -358,59 +387,59 @@
         else:
             page['Orientation'] = orientation
 
-
         #
         return True
-    
+
     def SendToRead(self, instruction, text, **kwargs):
-        psmapInstrDict = dict(paper = ['page'],
-                              maploc = ['map'],
-                              scale = ['map'],
-                              border = ['map'],
-                              raster = ['raster'],
-                              mapinfo = ['mapinfo'],
-                              scalebar = ['scalebar'],
-                              text = ['text'],
-                              eps = ['image', 'northArrow'],
-                              point = ['point'],
-                              line = ['line'],
-                              rectangle = ['rectangle'],
-                              vpoints = ['vector', 'vProperties'],
-                              vlines = ['vector', 'vProperties'],
-                              vareas = ['vector', 'vProperties'],
-                              colortable = ['rasterLegend'],
-                              vlegend = ['vectorLegend'],
-                              labels = ['labels']
+        psmapInstrDict = dict(paper=['page'],
+                              maploc=['map'],
+                              scale=['map'],
+                              border=['map'],
+                              raster=['raster'],
+                              mapinfo=['mapinfo'],
+                              scalebar=['scalebar'],
+                              text=['text'],
+                              eps=['image', 'northArrow'],
+                              point=['point'],
+                              line=['line'],
+                              rectangle=['rectangle'],
+                              vpoints=['vector', 'vProperties'],
+                              vlines=['vector', 'vProperties'],
+                              vareas=['vector', 'vProperties'],
+                              colortable=['rasterLegend'],
+                              vlegend=['vectorLegend'],
+                              labels=['labels']
                               )
-        
-        myInstrDict = dict(page = PageSetup,
-                           map = MapFrame,
-                           raster = Raster,
-                           mapinfo = Mapinfo,
-                           scalebar = Scalebar,
-                           text = Text,
-                           image = Image,
-                           northArrow = NorthArrow,
-                           point = Point,
-                           line = Line,
-                           rectangle = Rectangle,
-                           rasterLegend = RasterLegend,
-                           vectorLegend = VectorLegend,
-                           vector = Vector,
-                           vProperties = VProperties,
-                           labels = Labels
+
+        myInstrDict = dict(page=PageSetup,
+                           map=MapFrame,
+                           raster=Raster,
+                           mapinfo=Mapinfo,
+                           scalebar=Scalebar,
+                           text=Text,
+                           image=Image,
+                           northArrow=NorthArrow,
+                           point=Point,
+                           line=Line,
+                           rectangle=Rectangle,
+                           rasterLegend=RasterLegend,
+                           vectorLegend=VectorLegend,
+                           vector=Vector,
+                           vProperties=VProperties,
+                           labels=Labels
                            )
-        
+
         myInstruction = psmapInstrDict[instruction]
-        
+
         for i in myInstruction:
             instr = self.FindInstructionByType(i)
-            if i in ('text', 'vProperties', 'image', 'northArrow', 'point', 'line', 'rectangle') or not instr:
-                
-                id = wx.NewId() #!vProperties expect subtype
+            if i in ('text', 'vProperties', 'image', 'northArrow',
+                     'point', 'line', 'rectangle') or not instr:
+
+                id = wx.NewId()  # !vProperties expect subtype
                 if i == 'vProperties':
                     id = kwargs['id']
-                    newInstr = myInstrDict[i](id, subType = instruction[1:])
+                    newInstr = myInstrDict[i](id, subType=instruction[1:])
                 elif i in ('image', 'northArrow'):
                     commentFound = False
                     for line in text:
@@ -419,7 +448,7 @@
                     if i == 'image' and commentFound or \
                        i == 'northArrow' and not commentFound:
                         continue
-                    newInstr = myInstrDict[i](id, settings = self)
+                    newInstr = myInstrDict[i](id, settings=self)
                 else:
                     newInstr = myInstrDict[i](id)
                 ok = newInstr.Read(instruction, text, **kwargs)
@@ -434,83 +463,86 @@
                 if not ok:
                     return False
         return True
-    
+
     def SetRegion(self, regionInstruction):
         """Sets region from file comment or sets current region in case of no comment"""
         map = MapFrame(wx.NewId())
         self.AddInstruction(map)
         if regionInstruction:
             cmd = cmdlist_to_tuple(regionInstruction.strip('# ').split())
-            
+
             # define scaleType
             if len(cmd[1]) <= 3:
                 if 'raster' in cmd[1]:
                     map['scaleType'] = 0
-                    map['mapType'] = 'raster'   
-                    map['map'] = cmd[1]['raster']  
+                    map['mapType'] = 'raster'
+                    map['map'] = cmd[1]['raster']
                 elif 'vector' in cmd[1]:
                     map['scaleType'] = 0
-                    map['mapType'] = 'vector' 
-                    map['map'] = cmd[1]['vector']  
+                    map['mapType'] = 'vector'
+                    map['map'] = cmd[1]['vector']
                 elif 'region' in cmd[1]:
-                    map['scaleType'] = 1  
+                    map['scaleType'] = 1
                     map['region'] = cmd[1]['region']
-                    
+
             else:
-                map['scaleType'] = 2  
+                map['scaleType'] = 2
         else:
             map['scaleType'] = 2
             grass.del_temp_region()
             region = grass.region()
-            grass.use_temp_region()    
+            grass.use_temp_region()
             cmd = ['g.region', region]
         cmdString = GetCmdString(cmd).replace('g.region', '')
-        GMessage(_("Instruction file will be loaded with following region: %s\n") % cmdString)
+        GMessage(
+            _("Instruction file will be loaded with following region: %s\n") %
+            cmdString)
         try:
             RunCommand(cmd[0], **cmd[1])
-            
+
         except grass.ScriptError as e:
             GError(_("Region cannot be set\n%s") % e)
             return False
-        
 
+
 class InstructionObject:
     """Abtract class representing single instruction"""
-    def __init__(self, id): 
+
+    def __init__(self, id):
         self.id = id
-        
+
         # default values
         self.defaultInstruction = dict()
         # current values
-        self.instruction = self.defaultInstruction   
+        self.instruction = self.defaultInstruction
         # converting units
-        self.unitConv = UnitConversion() 
-    
+        self.unitConv = UnitConversion()
+
     def __str__(self):
         """Returns particular part of text instruction"""
         return ''
-    
+
     def __getitem__(self, key):
         for each in self.instruction.keys():
             if each == key:
                 return self.instruction[key]
         return None
-    
+
     def __setitem__(self, key, value):
         self.instruction[key] = value
-    
+
     def GetInstruction(self):
         """Get current values"""
         return self.instruction
-    
+
     def SetInstruction(self, instruction):
         """Set default values"""
         self.instruction = instruction
-        
+
     def Read(self, instruction, text, **kwargs):
         """Read instruction and save them"""
         pass
-        
+
     def PercentToReal(self, e, n):
         """Converts text coordinates from percent of region to map coordinates"""
         e, n = float(e.strip('%')), float(n.strip('%'))
@@ -519,60 +551,78 @@
         E = region['w'] + (region['e'] - region['w']) / 100 * e
         return E, N
 
+
 class InitMap(InstructionObject):
     """Class representing virtual map"""
+
     def __init__(self, id):
-        InstructionObject.__init__(self, id = id)
+        InstructionObject.__init__(self, id=id)
         self.type = 'initMap'
-        
+
         # default values
-        self.defaultInstruction = dict(rect = None, scale =  None)
+        self.defaultInstruction = dict(rect=None, scale=None)
         # current values
         self.instruction = dict(self.defaultInstruction)
-        
-    
+
+
 class MapFrame(InstructionObject):
     """Class representing map (instructions maploc, scale, border)"""
+
     def __init__(self, id):
-        InstructionObject.__init__(self, id = id)
+        InstructionObject.__init__(self, id=id)
         self.type = 'map'
         # default values
-        self.defaultInstruction = dict(map = None, mapType = None, drawMap = True, region = None,
-                                       rect = Rect2D(), scaleType = 0, scale = None, center = None,
-                                       resolution = 300, border = 'y', width = 1, color = '0:0:0') 
+        self.defaultInstruction = dict(
+            map=None,
+            mapType=None,
+            drawMap=True,
+            region=None,
+            rect=Rect2D(),
+            scaleType=0,
+            scale=None,
+            center=None,
+            resolution=300,
+            border='y',
+            width=1,
+            color='0:0:0')
         # current values
         self.instruction = dict(self.defaultInstruction)
-        
+
     def __str__(self):
         instr = ''
         comment = ''
-        
-        #region settings
+
+        # region settings
         region = grass.region()
-        if self.instruction['scaleType'] == 0: #match map
+        if self.instruction['scaleType'] == 0:  # match map
             map = self.instruction['map']
             if self.instruction['mapType'] == 'raster':
-                comment = "# g.region raster=%s nsres=%s ewres=%s\n" % (map, region['nsres'], region['ewres'])
+                comment = "# g.region raster=%s nsres=%s ewres=%s\n" % (
+                    map, region['nsres'], region['ewres'])
             else:
                 comment = "# g.region vector=%s\n" % (map)
-        elif self.instruction['scaleType'] == 1:# saved region
+        elif self.instruction['scaleType'] == 1:  # saved region
             region = self.instruction['region']
             comment = "# g.region region=%s\n" % region
-        elif self.instruction['scaleType'] in (2, 3): #current region, fixed scale
-            comment = string.Template("# g.region n=$n s=$s e=$e w=$w rows=$rows cols=$cols \n").substitute(**region)
-        
+        # current region, fixed scale
+        elif self.instruction['scaleType'] in (2, 3):
+            comment = string.Template(
+                "# g.region n=$n s=$s e=$e w=$w rows=$rows cols=$cols \n").substitute(**region)
+
         instr += comment
         instr += '\n'
         # maploc
-        maplocInstruction = "maploc %.3f %.3f" % (self.instruction['rect'].x, self.instruction['rect'].y)
+        maplocInstruction = "maploc %.3f %.3f" % (
+            self.instruction['rect'].x, self.instruction['rect'].y)
         if self.instruction['scaleType'] != 3:
-            maplocInstruction += "  %.3f %.3f"% (self.instruction['rect'].width, self.instruction['rect'].height)
+            maplocInstruction += "  %.3f %.3f" % (
+                self.instruction['rect'].width, self.instruction['rect'].height)
         instr += maplocInstruction
         instr += '\n'
-        
+
         # scale
-        if self.instruction['scaleType'] == 3: #fixed scale
-            scaleInstruction = "scale 1:%.0f" % (1/self.instruction['scale'])
+        if self.instruction['scaleType'] == 3:  # fixed scale
+            scaleInstruction = "scale 1:%.0f" % (1 / self.instruction['scale'])
             instr += scaleInstruction
             instr += '\n'
         # border
@@ -581,19 +631,21 @@
             borderInstruction = "border n"
         else:
             borderInstruction = "border y\n"
-            borderInstruction += string.Template("    width $width\n    color $color\n").substitute(self.instruction)
+            borderInstruction += string.Template(
+                "    width $width\n    color $color\n").substitute(
+                self.instruction)
             borderInstruction += "    end"
         instr += borderInstruction
         instr += '\n'
 
-        return instr  
-    
+        return instr
+
     def Read(self, instruction, text, **kwargs):
         """Read instruction and save information"""
         if 'isRegionComment' in kwargs:
             isRegionComment = kwargs['isRegionComment']
         instr = {}
-        
+
         if instruction == 'border':
             for line in text:
                 if line.startswith('end'):
@@ -611,86 +663,114 @@
                 except IndexError:
                     GError(_("Failed to read instruction %s") % instruction)
                     return False
-                
+
         elif instruction == 'scale':
             try:
                 scaleText = text.strip('scale ').split(':')[1]
-                # when scale instruction given and region comment also, then scaletype is fixed scale
+                # when scale instruction given and region comment also, then
+                # scaletype is fixed scale
                 if not isRegionComment:
-                    instr['scaleType'] = 2 
+                    instr['scaleType'] = 2
                 else:
                     instr['scaleType'] = 3
 
-                scale = 1/float(scaleText)
+                scale = 1 / float(scaleText)
                 if abs(scale - self.instruction['scale']) > (0.01 * scale):
-                    GWarning(_("Scale has changed, old value: %(old)s\nnew value: %(new)s") % \
-                                 { 'old' : scale, 'new' : self.instruction['scale'] })
+                    GWarning(_("Scale has changed, old value: %(old)s\nnew value: %(new)s") %
+                             {'old': scale, 'new': self.instruction['scale']})
             except (ValueError, IndexError):
-                GError(_("Failed to read instruction %s.\nUse 1:25000 notation.") % instruction)
+                GError(
+                    _("Failed to read instruction %s.\nUse 1:25000 notation.") %
+                    instruction)
                 return False
-        
+
         elif instruction == 'maploc':
             maploc = text.strip('maploc ').split()
             if len(maploc) >= 2:
                 if  abs(self.instruction['rect'].Get()[0] - float(maploc[0])) > 0.5 or \
                         abs(self.instruction['rect'].Get()[1] - float(maploc[1])) > 0.5:
-                    GWarning(_("Map frame position changed, old value: %(old1)s %(old2)s\nnew value: %(new1)s %(new2)s") % \
-                                 { 'old1' : maploc[0], 'old2' : maploc[1],
-                                   'new1' : self.instruction['rect'].Get()[0], 'new2' : self.instruction['rect'].Get()[1] })
-                    
+                    GWarning(
+                        _("Map frame position changed, old value: %(old1)s %(old2)s\nnew value: %(new1)s %(new2)s") % {
+                            'old1': maploc[0],
+                            'old2': maploc[1],
+                            'new1': self.instruction['rect'].Get()[0],
+                            'new2': self.instruction['rect'].Get()[1]})
+
                 #instr['rect'] = wx.Rect2D(float(maploc[0]), float(maploc[1]), self.instruction['rect'][2], self.instruction['rect'][3])
             if len(maploc) == 4:
                 if  abs(self.instruction['rect'].Get()[2] - float(maploc[2])) > 0.5 or \
                         abs(self.instruction['rect'].Get()[3] - float(maploc[3])) > 0.5:
-                    GWarning(_("Map frame size changed, old value: %(old1)s %(old2)s\nnew value: %(new1)s %(new2)s") % \
-                                 { 'old1' : maploc[2], 'old2' : maploc[3],
-                                   'new1' : self.instruction['rect'].Get()[2], 'new2' : self.instruction['rect'].Get()[3] })
+                    GWarning(
+                        _("Map frame size changed, old value: %(old1)s %(old2)s\nnew value: %(new1)s %(new2)s") % {
+                            'old1': maploc[2],
+                            'old2': maploc[3],
+                            'new1': self.instruction['rect'].Get()[2],
+                            'new2': self.instruction['rect'].Get()[3]})
                 #instr['rect'] = wx.Rect2D(*map(float, maploc))
-        self.instruction.update(instr)   
-        return True 
-    
+        self.instruction.update(instr)
+        return True
+
+
 class PageSetup(InstructionObject):
     """Class representing page instruction"""
+
     def __init__(self, id):
-        InstructionObject.__init__(self, id = id)
+        InstructionObject.__init__(self, id=id)
         self.type = 'page'
         # default values
-        self.defaultInstruction = dict(Units = 'inch', Format = 'a4', Orientation = 'Portrait',
-                                       Width = 8.268, Height = 11.693, Left = 0.5, Right = 0.5, Top = 1, Bottom = 1)
+        self.defaultInstruction = dict(
+            Units='inch',
+            Format='a4',
+            Orientation='Portrait',
+            Width=8.268,
+            Height=11.693,
+            Left=0.5,
+            Right=0.5,
+            Top=1,
+            Bottom=1)
         # current values
         self.instruction = dict(self.defaultInstruction)
-        
+
     def __str__(self):
         if self.instruction['Format'] == 'custom':
-            instr = string.Template("paper\n    width $Width\n    height $Height\n").substitute(self.instruction)
+            instr = string.Template(
+                "paper\n    width $Width\n    height $Height\n").substitute(
+                self.instruction)
         else:
-            instr = string.Template("paper $Format\n").substitute(self.instruction)
-        instr += string.Template("    left $Left\n    right $Right\n    bottom $Bottom\n    top $Top\n    end").substitute(self.instruction)
+            instr = string.Template(
+                "paper $Format\n").substitute(self.instruction)
+        instr += string.Template(
+            "    left $Left\n    right $Right\n    bottom $Bottom\n    top $Top\n    end").substitute(self.instruction)
 
         return instr
-    
+
     def Read(self, instruction, text, **kwargs):
         """Read instruction and save information"""
         instr = {}
         self.cats = ['Width', 'Height', 'Left', 'Right', 'Top', 'Bottom']
-        self.subInstr = dict(zip(['width', 'height', 'left', 'right', 'top', 'bottom'], self.cats))
-        
-        if instruction == 'paper': # just for sure
+        self.subInstr = dict(
+            zip(['width', 'height', 'left', 'right', 'top', 'bottom'], self.cats))
+
+        if instruction == 'paper':  # just for sure
             for line in text:
-                if line.startswith('paper'): 
+                if line.startswith('paper'):
                     if len(line.split()) > 1:
                         pformat = line.split()[1]
-                        availableFormats = self._toDict(grass.read_command('ps.map', flags = 'p',
-                                                                           quiet = True))
-                        # e.g. paper a3 
+                        availableFormats = self._toDict(
+                            grass.read_command(
+                                'ps.map', flags='p', quiet=True))
+                        # e.g. paper a3
                         try:
                             instr['Format'] = pformat
-                            for key, value in availableFormats[pformat].iteritems():
+                            for key, value in availableFormats[
+                                    pformat].iteritems():
                                 instr[key] = float(value)
                             break
                         except KeyError:
-                            GError(_("Failed to read instruction %(file)s.\nUnknown format %(for)s") % \
-                                       { 'file' : instruction, 'for' : format })
+                            GError(
+                                _("Failed to read instruction %(file)s.\nUnknown format %(for)s") % {
+                                    'file': instruction,
+                                    'for': format})
                             return False
                     else:
                         # paper
@@ -701,51 +781,70 @@
                     text = line.split()
                     try:
                         instr[self.subInstr[text[0]]] = float(text[1])
-                    except  (IndexError, KeyError):
-                        GError(_("Failed to read instruction %s.") % instruction)
+                    except (IndexError, KeyError):
+                        GError(
+                            _("Failed to read instruction %s.") %
+                            instruction)
                         return False
-                    
-            if 'Orientation' in kwargs and kwargs['Orientation'] == 'Landscape':
-                instr['Width'], instr['Height'] = instr['Height'], instr['Width']
-                
+
+            if 'Orientation' in kwargs and kwargs[
+                    'Orientation'] == 'Landscape':
+                instr['Width'], instr['Height'] = instr[
+                    'Height'], instr['Width']
+
             self.instruction.update(instr)
-        return True  
-    
-    def _toDict(self, paperStr):    
+        return True
+
+    def _toDict(self, paperStr):
         sizeDict = dict()
 #     cats = self.subInstr[ 'Width', 'Height', 'Left', 'Right', 'Top', 'Bottom']
         for line in paperStr.strip().split('\n'):
             d = dict(zip(self.cats, line.split()[1:]))
             sizeDict[line.split()[0]] = d
-            
-        return sizeDict    
-    
+
+        return sizeDict
+
+
 class Mapinfo(InstructionObject):
     """Class representing mapinfo instruction"""
+
     def __init__(self, id):
-        InstructionObject.__init__(self, id = id)
+        InstructionObject.__init__(self, id=id)
         self.type = 'mapinfo'
         # default values
-        self.defaultInstruction = dict(unit = 'inch', where = (0, 0),
-                                       font = 'Helvetica', fontsize = 10, color = '0:0:0', background = 'none', 
-                                       border = 'none', rect = None)
+        self.defaultInstruction = dict(
+            unit='inch',
+            where=(
+                0,
+                0),
+            font='Helvetica',
+            fontsize=10,
+            color='0:0:0',
+            background='none',
+            border='none',
+            rect=None)
         # current values
         self.instruction = dict(self.defaultInstruction)
-        
+
     def __str__(self):
         instr = "mapinfo\n"
-        instr += "    where %.3f %.3f\n" % (self.instruction['where'][0], self.instruction['where'][1])
-        instr += string.Template("    font $font\n    fontsize $fontsize\n    color $color\n").substitute(self.instruction)            
-        instr += string.Template("    background $background\n    border $border\n").substitute(self.instruction)  
+        instr += "    where %.3f %.3f\n" % (
+            self.instruction['where'][0],
+            self.instruction['where'][1])
+        instr += string.Template(
+            "    font $font\n    fontsize $fontsize\n    color $color\n").substitute(self.instruction)
+        instr += string.Template(
+            "    background $background\n    border $border\n").substitute(
+            self.instruction)
         instr += "    end"
         return instr
-    
+
     def Read(self, instruction, text):
         """Read instruction and save information"""
         instr = {}
         try:
             for line in text:
-                sub = line.split(None,1)
+                sub = line.split(None, 1)
                 if sub[0] == 'font':
                     instr['font'] = sub[1]
                 elif sub[0] == 'fontsize':
@@ -757,56 +856,74 @@
                 elif sub[0] == 'border':
                     instr['border'] = sub[1]
                 elif sub[0] == 'where':
-                    instr['where'] = float(sub[1].split()[0]), float(sub[1].split()[1])
+                    instr['where'] = float(
+                        sub[1].split()[0]), float(
+                        sub[1].split()[1])
         except (ValueError, IndexError):
             GError(_("Failed to read instruction %s") % instruction)
             return False
         self.instruction.update(instr)
-        self.instruction['rect'] = self.EstimateRect(mapinfoDict = self.instruction)
+        self.instruction['rect'] = self.EstimateRect(
+            mapinfoDict=self.instruction)
         return True
-    
+
     def EstimateRect(self, mapinfoDict):
         """Estimate size to draw mapinfo"""
-        w = mapinfoDict['fontsize'] * 20 # any better estimation? 
+        w = mapinfoDict['fontsize'] * 20  # any better estimation?
         h = mapinfoDict['fontsize'] * 7
-        width = self.unitConv.convert(value = w, fromUnit = 'point', toUnit = 'inch')
-        height = self.unitConv.convert(value = h, fromUnit = 'point', toUnit = 'inch')
-        return Rect2D(x = float(mapinfoDict['where'][0]), y = float(mapinfoDict['where'][1]),
-                      width = width, height = height)
-    
+        width = self.unitConv.convert(value=w, fromUnit='point', toUnit='inch')
+        height = self.unitConv.convert(
+            value=h, fromUnit='point', toUnit='inch')
+        return Rect2D(x=float(mapinfoDict['where'][0]), y=float(
+            mapinfoDict['where'][1]), width=width, height=height)
+
+
 class Text(InstructionObject):
     """Class representing text instruction"""
+
     def __init__(self, id):
-        InstructionObject.__init__(self, id = id)
+        InstructionObject.__init__(self, id=id)
         self.type = 'text'
         # default values
-        self.defaultInstruction = dict(text = "", font = "Helvetica", fontsize = 10, color = 'black', background = 'none',
-                                       hcolor = 'none', hwidth = 1, border = 'none', width = '1', XY = True,
-                                       where = (0,0), unit = 'inch', rotate = None, 
-                                       ref = "center center", xoffset = 0, yoffset = 0, east = None, north = None)
+        self.defaultInstruction = dict(
+            text="", font="Helvetica", fontsize=10, color='black',
+            background='none', hcolor='none', hwidth=1, border='none',
+            width='1', XY=True, where=(0, 0),
+            unit='inch', rotate=None, ref="center center", xoffset=0,
+            yoffset=0, east=None, north=None)
         # current values
         self.instruction = dict(self.defaultInstruction)
-        
+
     def __str__(self):
-        text = self.instruction['text'].replace('\n','\\n')
-        instr = u"text %s %s" % (self.instruction['east'], self.instruction['north'])
+        text = self.instruction['text'].replace('\n', '\\n')
+        instr = u"text %s %s" % (
+            self.instruction['east'],
+            self.instruction['north'])
         instr += " %s\n" % text
-        instr += (string.Template("    font $font\n    fontsize $fontsize\n    color $color\n").
-                                                                   substitute(self.instruction))
+        instr += (
+            string.Template("    font $font\n    fontsize $fontsize\n    color $color\n"). substitute(
+                self.instruction))
         instr += string.Template("    hcolor $hcolor\n").substitute(self.instruction)
         if self.instruction['hcolor'] != 'none':
-            instr += string.Template("    hwidth $hwidth\n").substitute(self.instruction)
+            instr += string.Template(
+                "    hwidth $hwidth\n").substitute(self.instruction)
         instr += string.Template("    border $border\n").substitute(self.instruction)
         if self.instruction['border'] != 'none':
-            instr += string.Template("    width $width\n").substitute(self.instruction)
-        instr += string.Template("    background $background\n").substitute(self.instruction)
+            instr += string.Template(
+                "    width $width\n").substitute(self.instruction)
+        instr += string.Template(
+            "    background $background\n").substitute(self.instruction)
         if self.instruction["ref"] != '0':
             instr += string.Template("    ref $ref\n").substitute(self.instruction)
         if self.instruction["rotate"]:
-            instr += string.Template("    rotate $rotate\n").substitute(self.instruction)
-        if float(self.instruction["xoffset"]) or float(self.instruction["yoffset"]):
-            instr += (string.Template("    xoffset $xoffset\n    yoffset $yoffset\n").
-                                                            substitute(self.instruction))
+            instr += string.Template(
+                "    rotate $rotate\n").substitute(self.instruction)
+        if float(
+                self.instruction["xoffset"]) or float(
+                self.instruction["yoffset"]):
+            instr += (
+                string.Template("    xoffset $xoffset\n    yoffset $yoffset\n"). substitute(
+                    self.instruction))
         instr += "    end"
         try:
             instr = instr.encode('latin1')
@@ -823,11 +940,11 @@
                 message = _("Not all characters are supported "
                             "by ISO-8859-1 (Latin 1) encoding "
                             "which is required by module ps.map.")
-            GMessage(message = message)
+            GMessage(message=message)
             return ''
-        
+
         return instr
-    
+
     def Read(self, instruction, text, **kwargs):
         """Read instruction and save information"""
         map = kwargs['mapInstruction']
@@ -839,13 +956,14 @@
                     e, n = line.split(None, 3)[1:3]
                     if '%' in e and '%' in n:
                         instr['XY'] = True
-                        instr['east'], instr['north'] = self.PercentToReal(e, n)
+                        instr['east'], instr[
+                            'north'] = self.PercentToReal(e, n)
                     else:
                         instr['XY'] = False
                         instr['east'], instr['north'] = float(e), float(n)
-                        
+
                     instr['text'] = line.split(None, 3)[3].decode('latin_1')
-                
+
                 elif sub == 'font':
                     instr['font'] = line.split(None, 1)[1]
                 elif sub == 'fontsize':
@@ -873,41 +991,59 @@
                 elif sub == 'opaque':
                     if line.split(None, 1)[1].lower() in ('n', 'none'):
                         instr['background'] = 'none'
-                        
+
             except(IndexError, ValueError):
                 GError(_("Failed to read instruction %s") % instruction)
                 return False
-        instr['where'] = PaperMapCoordinates(mapInstr = map, x = instr['east'], y = instr['north'], paperToMap = False)       
+        instr['where'] = PaperMapCoordinates(
+            mapInstr=map, x=instr['east'],
+            y=instr['north'],
+            paperToMap=False)
         self.instruction.update(instr)
 
-        return True 
-        
+        return True
+
+
 class Image(InstructionObject):
     """Class representing eps instruction - image"""
+
     def __init__(self, id, settings):
-        InstructionObject.__init__(self, id = id)
+        InstructionObject.__init__(self, id=id)
         self.settings = settings
         self.type = 'image'
         # default values
-        self.defaultInstruction = dict(epsfile = "", XY = True, where = (0,0), unit = 'inch',
-                                       east = None, north = None,
-                                       rotate = None, scale = 1)
+        self.defaultInstruction = dict(
+            epsfile="",
+            XY=True,
+            where=(
+                0,
+                0),
+            unit='inch',
+            east=None,
+            north=None,
+            rotate=None,
+            scale=1)
         # current values
         self.instruction = dict(self.defaultInstruction)
-        
+
     def __str__(self):
-        self.ChangeRefPoint(toCenter = True)
-        epsfile = self.instruction['epsfile'].replace(os.getenv('GISBASE'), "$GISBASE")
-        
-        instr = "eps %s %s\n" % (self.instruction['east'], self.instruction['north'])
+        self.ChangeRefPoint(toCenter=True)
+        epsfile = self.instruction['epsfile'].replace(
+            os.getenv('GISBASE'), "$GISBASE")
+
+        instr = "eps %s %s\n" % (
+            self.instruction['east'],
+            self.instruction['north'])
         instr += "    epsfile %s\n" % epsfile
         if self.instruction["rotate"]:
-            instr += string.Template("    rotate $rotate\n").substitute(self.instruction)
+            instr += string.Template(
+                "    rotate $rotate\n").substitute(self.instruction)
         if self.instruction["scale"]:
-            instr += string.Template("    scale $scale\n").substitute(self.instruction)
+            instr += string.Template(
+                "    scale $scale\n").substitute(self.instruction)
         instr += "    end"
         return instr
-    
+
     def Read(self, instruction, text, **kwargs):
         """Read instruction and save information"""
         mapInstr = kwargs['mapInstruction']
@@ -919,44 +1055,57 @@
                     e, n = line.split(None, 3)[1:3]
                     if '%' in e and '%' in n:
                         instr['XY'] = True
-                        instr['east'], instr['north'] = self.PercentToReal(e, n)
+                        instr['east'], instr[
+                            'north'] = self.PercentToReal(e, n)
                     else:
                         instr['XY'] = False
                         instr['east'], instr['north'] = float(e), float(n)
-                
+
                 elif sub == 'epsfile':
                     epsfile = line.split(None, 1)[1]
-                    instr['epsfile'] = epsfile.replace("$GISBASE", os.getenv("GISBASE"))
+                    instr['epsfile'] = epsfile.replace(
+                        "$GISBASE", os.getenv("GISBASE"))
                 elif sub == 'rotate':
                     instr['rotate'] = float(line.split(None, 1)[1])
                 elif sub == 'scale':
                     instr['scale'] = float(line.split(None, 1)[1])
-                        
+
             except(IndexError, ValueError):
                 GError(_("Failed to read instruction %s") % instruction)
                 return False
         if not os.path.exists(instr['epsfile']):
             GError(_("Failed to read instruction %(inst)s: "
-                     "file %(file)s not found.") % { 'inst' : instruction,
-                                                     'file' : instr['epsfile'] })
+                     "file %(file)s not found.") % {'inst': instruction,
+                                                    'file': instr['epsfile']})
             return False
-        
+
         instr['epsfile'] = os.path.abspath(instr['epsfile'])
         instr['size'] = self.GetImageOrigSize(instr['epsfile'])
         if 'rotate' in instr:
-            instr['size'] = BBoxAfterRotation(instr['size'][0], instr['size'][1], instr['rotate'])
+            instr['size'] = BBoxAfterRotation(
+                instr['size'][0], instr['size'][1], instr['rotate'])
         self.instruction.update(instr)
-        self.ChangeRefPoint(toCenter = False)
-        instr['where'] = PaperMapCoordinates(mapInstr = mapInstr, x = self.instruction['east'],
-                                             y = self.instruction['north'], paperToMap = False)       
-        w = self.unitConv.convert(value = instr['size'][0], fromUnit = 'point', toUnit = 'inch')
-        h = self.unitConv.convert(value = instr['size'][1], fromUnit = 'point', toUnit = 'inch')
-        instr['rect'] = Rect2D(x = float(instr['where'][0]), y = float(instr['where'][1]),
-                               width = w * self.instruction['scale'], height = h * self.instruction['scale'])
+        self.ChangeRefPoint(toCenter=False)
+        instr['where'] = PaperMapCoordinates(
+            mapInstr=mapInstr,
+            x=self.instruction['east'],
+            y=self.instruction['north'],
+            paperToMap=False)
+        w = self.unitConv.convert(
+            value=instr['size'][0],
+            fromUnit='point', toUnit='inch')
+        h = self.unitConv.convert(
+            value=instr['size'][1],
+            fromUnit='point', toUnit='inch')
+        instr['rect'] = Rect2D(
+            x=float(instr['where'][0]),
+            y=float(instr['where'][1]),
+            width=w * self.instruction['scale'],
+            height=h * self.instruction['scale'])
         self.instruction.update(instr)
 
-        return True 
-        
+        return True
+
     def ChangeRefPoint(self, toCenter):
         """Change reference point (left top x center)"""
         mapInstr = self.settings.FindInstructionByType('map')
@@ -965,30 +1114,42 @@
         mapId = mapInstr.id
         if toCenter:
             center = self.instruction['rect'].GetCentre()
-            ENCenter = PaperMapCoordinates(mapInstr = self.settings[mapId],
-                                           x = center[0], y = center[1], paperToMap = True)
-                                           
+            ENCenter = PaperMapCoordinates(
+                mapInstr=self.settings[mapId],
+                x=center[0],
+                y=center[1],
+                paperToMap=True)
+
             self.instruction['east'], self.instruction['north'] = ENCenter
         else:
-            x, y = PaperMapCoordinates(mapInstr = self.settings[mapId], x = self.instruction['east'],
-                                       y = self.instruction['north'], paperToMap = False)
-            w = self.unitConv.convert(value = self.instruction['size'][0], fromUnit = 'point', toUnit = 'inch')
-            h = self.unitConv.convert(value = self.instruction['size'][1], fromUnit = 'point', toUnit = 'inch')
+            x, y = PaperMapCoordinates(
+                mapInstr=self.settings[mapId],
+                x=self.instruction['east'],
+                y=self.instruction['north'],
+                paperToMap=False)
+            w = self.unitConv.convert(
+                value=self.instruction['size'][0],
+                fromUnit='point', toUnit='inch')
+            h = self.unitConv.convert(
+                value=self.instruction['size'][1],
+                fromUnit='point', toUnit='inch')
             x -= w * self.instruction['scale'] / 2
             y -= h * self.instruction['scale'] / 2
-            e, n = PaperMapCoordinates(mapInstr = self.settings[mapId], x = x, y = y, paperToMap = True)
+            e, n = PaperMapCoordinates(
+                mapInstr=self.settings[mapId],
+                x=x, y=y, paperToMap=True)
             self.instruction['east'], self.instruction['north'] = e, n
 
     def GetImageOrigSize(self, imagePath):
         """Get image size.
-        
+
         If eps, size is read from image header.
         """
         fileName = os.path.split(imagePath)[1]
         # if eps, read info from header
         if os.path.splitext(fileName)[1].lower() == '.eps':
             bbInfo = "%%BoundingBox"
-            file = open(imagePath,"r")
+            file = open(imagePath, "r")
             w = h = 0
             while file:
                 line = file.readline()
@@ -997,46 +1158,56 @@
                     break
             file.close()
             return float(w), float(h)
-        else: # we can use wx.Image
+        else:  # we can use wx.Image
             img = wx.Image(fileName, type=wx.BITMAP_TYPE_ANY)
             return img.GetWidth(), img.GetHeight()
-            
+
+
 class NorthArrow(Image):
     """Class representing eps instruction -- North Arrow"""
+
     def __init__(self, id, settings):
-        Image.__init__(self, id = id, settings = settings)
+        Image.__init__(self, id=id, settings=settings)
         self.type = 'northArrow'
-        
+
     def __str__(self):
-        self.ChangeRefPoint(toCenter = True)
-        epsfile = self.instruction['epsfile'].replace(os.getenv('GISBASE'), "$GISBASE")
+        self.ChangeRefPoint(toCenter=True)
+        epsfile = self.instruction['epsfile'].replace(
+            os.getenv('GISBASE'), "$GISBASE")
 
-        instr = "eps %s %s\n" % (self.instruction['east'], self.instruction['north'])
+        instr = "eps %s %s\n" % (
+            self.instruction['east'],
+            self.instruction['north'])
         instr += "# north arrow\n"
         instr += "    epsfile %s\n" % epsfile
         if self.instruction["rotate"]:
-            instr += string.Template("    rotate $rotate\n").substitute(self.instruction)
+            instr += string.Template(
+                "    rotate $rotate\n").substitute(self.instruction)
         if self.instruction["scale"]:
-            instr += string.Template("    scale $scale\n").substitute(self.instruction)
+            instr += string.Template(
+                "    scale $scale\n").substitute(self.instruction)
         instr += "    end"
         return instr
-        
+
+
 class Point(InstructionObject):
     """Class representing point instruction"""
+
     def __init__(self, id):
-        InstructionObject.__init__(self, id = id)
+        InstructionObject.__init__(self, id=id)
         self.type = 'point'
         # default values
-        self.defaultInstruction = dict(symbol = os.path.join('basic', 'x'),
-                                       color = '0:0:0', fcolor = '200:200:200',
-                                       rotate = 0, size = 10,
-                                       XY = True, where = (0,0), unit = 'inch',
-                                       east = None, north = None)
+        self.defaultInstruction = dict(symbol=os.path.join('basic', 'x'),
+                                       color='0:0:0', fcolor='200:200:200',
+                                       rotate=0, size=10,
+                                       XY=True, where=(0, 0), unit='inch',
+                                       east=None, north=None)
         # current values
         self.instruction = dict(self.defaultInstruction)
-        
+
     def __str__(self):
-        instr = string.Template("point $east $north\n").substitute(self.instruction)
+        instr = string.Template(
+            "point $east $north\n").substitute(self.instruction)
         instr += string.Template("    symbol $symbol\n").substitute(self.instruction)
         instr += string.Template("    color $color\n").substitute(self.instruction)
         instr += string.Template("    fcolor $fcolor\n").substitute(self.instruction)
@@ -1044,7 +1215,7 @@
         instr += string.Template("    size $size\n").substitute(self.instruction)
         instr += "    end"
         return instr
-    
+
     def Read(self, instruction, text, **kwargs):
         """Read instruction and save information"""
         mapInstr = kwargs['mapInstruction']
@@ -1056,11 +1227,12 @@
                     e, n = line.split(None, 3)[1:3]
                     if '%' in e and '%' in n:
                         instr['XY'] = True
-                        instr['east'], instr['north'] = self.PercentToReal(e, n)
+                        instr['east'], instr[
+                            'north'] = self.PercentToReal(e, n)
                     else:
                         instr['XY'] = False
                         instr['east'], instr['north'] = float(e), float(n)
-                
+
                 elif sub == 'symbol':
                     instr['symbol'] = line.split(None, 1)[1]
                 elif sub == 'rotate':
@@ -1072,41 +1244,50 @@
                 elif sub == 'fcolor':
                     instr['fcolor'] = line.split(None, 1)[1]
 
-                        
             except(IndexError, ValueError):
                 GError(_("Failed to read instruction %s") % instruction)
                 return False
-        
+
         self.instruction.update(instr)
-        instr['where'] = PaperMapCoordinates(mapInstr = mapInstr, x = self.instruction['east'],
-                                             y = self.instruction['north'], paperToMap = False)
-        w = h = self.unitConv.convert(value = instr['size'], fromUnit = 'point', toUnit = 'inch')
-        instr['rect'] = Rect2D(x = float(instr['where'][0]) - w / 2, y = float(instr['where'][1] - h / 2),
-                               width = w, height = h)
+        instr['where'] = PaperMapCoordinates(
+            mapInstr=mapInstr,
+            x=self.instruction['east'],
+            y=self.instruction['north'],
+            paperToMap=False)
+        w = h = self.unitConv.convert(
+            value=instr['size'],
+            fromUnit='point', toUnit='inch')
+        instr['rect'] = Rect2D(
+            x=float(instr['where'][0]) - w / 2,
+            y=float(instr['where'][1] - h / 2),
+            width=w, height=h)
         self.instruction.update(instr)
 
         return True
 
+
 class Line(InstructionObject):
     """Class representing line instruction"""
+
     def __init__(self, id):
-        InstructionObject.__init__(self, id = id)
+        InstructionObject.__init__(self, id=id)
         self.type = 'line'
         # default values
-        self.defaultInstruction = dict(color = '0:0:0', width = 2,
-                                       where = [wx.Point2D(), wx.Point2D()],
-                                       east1 = None, north1 = None,
-                                       east2 = None, north2 = None)
+        self.defaultInstruction = dict(color='0:0:0', width=2,
+                                       where=[wx.Point2D(), wx.Point2D()],
+                                       east1=None, north1=None,
+                                       east2=None, north2=None)
         # current values
         self.instruction = dict(self.defaultInstruction)
-        
+
     def __str__(self):
-        instr = string.Template("line $east1 $north1 $east2 $north2\n").substitute(self.instruction)
+        instr = string.Template(
+            "line $east1 $north1 $east2 $north2\n").substitute(self.instruction)
         instr += string.Template("    color $color\n").substitute(self.instruction)
         instr += string.Template("    width $width\n").substitute(self.instruction)
         instr += "    end\n"
         return instr
-    
+
     def Read(self, instruction, text, **kwargs):
         """Read instruction and save information"""
         mapInstr = kwargs['mapInstruction']
@@ -1117,52 +1298,61 @@
                 if sub == 'line':
                     e1, n1, e2, n2 = line.split(None, 5)[1:5]
                     if '%' in e1 and '%' in n1 and '%' in e2 and '%' in n2:
-                        instr['east1'], instr['north1'] = self.PercentToReal(e1, n1)
-                        instr['east2'], instr['north2'] = self.PercentToReal(e2, n2)
+                        instr['east1'], instr[
+                            'north1'] = self.PercentToReal(e1, n1)
+                        instr['east2'], instr[
+                            'north2'] = self.PercentToReal(e2, n2)
                     else:
                         instr['east1'], instr['north1'] = float(e1), float(n1)
                         instr['east2'], instr['north2'] = float(e2), float(n2)
-                
+
                 elif sub == 'width':
                     instr['width'] = float(line.split(None, 1)[1])
                 elif sub == 'color':
                     instr['color'] = line.split(None, 1)[1]
-                        
+
             except(IndexError, ValueError):
                 GError(_("Failed to read instruction %s") % instruction)
                 return False
-        
+
         self.instruction.update(instr)
-        e1, n1 = PaperMapCoordinates(mapInstr = mapInstr, x = self.instruction['east1'],
-                                     y = self.instruction['north1'], paperToMap = False)
-        e2, n2 = PaperMapCoordinates(mapInstr = mapInstr, x = self.instruction['east2'],
-                                     y = self.instruction['north2'], paperToMap = False)
+        e1, n1 = PaperMapCoordinates(
+            mapInstr=mapInstr, x=self.instruction['east1'],
+            y=self.instruction['north1'],
+            paperToMap=False)
+        e2, n2 = PaperMapCoordinates(
+            mapInstr=mapInstr, x=self.instruction['east2'],
+            y=self.instruction['north2'],
+            paperToMap=False)
         instr['where'] = [wx.Point2D(e1, n1), wx.Point2D(e2, n2)]
         instr['rect'] = Rect2DPP(instr['where'][0], instr['where'][1])
         self.instruction.update(instr)
 
         return True
 
+
 class Rectangle(InstructionObject):
     """Class representing rectangle instruction"""
+
     def __init__(self, id):
-        InstructionObject.__init__(self, id = id)
+        InstructionObject.__init__(self, id=id)
         self.type = 'rectangle'
         # default values
-        self.defaultInstruction = dict(color = '0:0:0', fcolor = 'none', width = 2,
-                                       east1 = None, north1 = None,
-                                       east2 = None, north2 = None)
+        self.defaultInstruction = dict(color='0:0:0', fcolor='none', width=2,
+                                       east1=None, north1=None,
+                                       east2=None, north2=None)
         # current values
         self.instruction = dict(self.defaultInstruction)
-        
+
     def __str__(self):
-        instr = string.Template("rectangle $east1 $north1 $east2 $north2\n").substitute(self.instruction)
+        instr = string.Template(
+            "rectangle $east1 $north1 $east2 $north2\n").substitute(self.instruction)
         instr += string.Template("    color $color\n").substitute(self.instruction)
         instr += string.Template("    fcolor $fcolor\n").substitute(self.instruction)
         instr += string.Template("    width $width\n").substitute(self.instruction)
         instr += "    end\n"
         return instr
-    
+
     def Read(self, instruction, text, **kwargs):
         """Read instruction and save information"""
         mapInstr = kwargs['mapInstruction']
@@ -1173,12 +1363,14 @@
                 if sub == 'rectangle':
                     e1, n1, e2, n2 = line.split(None, 5)[1:5]
                     if '%' in e1 and '%' in n1 and '%' in e2 and '%' in n2:
-                        instr['east1'], instr['north1'] = self.PercentToReal(e1, n1)
-                        instr['east2'], instr['north2'] = self.PercentToReal(e2, n2)
+                        instr['east1'], instr[
+                            'north1'] = self.PercentToReal(e1, n1)
+                        instr['east2'], instr[
+                            'north2'] = self.PercentToReal(e2, n2)
                     else:
                         instr['east1'], instr['north1'] = float(e1), float(n1)
                         instr['east2'], instr['north2'] = float(e2), float(n2)
-                
+
                 elif sub == 'width':
                     instr['width'] = float(line.split(None, 1)[1])
                 elif sub == 'color':
@@ -1186,45 +1378,57 @@
                 elif sub == 'fcolor':
                     instr['fcolor'] = line.split(None, 1)[1]
 
-                        
             except(IndexError, ValueError):
                 GError(_("Failed to read instruction %s") % instruction)
                 return False
-        
+
         self.instruction.update(instr)
-        e1, n1 = PaperMapCoordinates(mapInstr = mapInstr, x = self.instruction['east1'],
-                                       y = self.instruction['north1'], paperToMap = False)
-        e2, n2 = PaperMapCoordinates(mapInstr = mapInstr, x = self.instruction['east2'],
-                                       y = self.instruction['north2'], paperToMap = False)
+        e1, n1 = PaperMapCoordinates(
+            mapInstr=mapInstr, x=self.instruction['east1'],
+            y=self.instruction['north1'],
+            paperToMap=False)
+        e2, n2 = PaperMapCoordinates(
+            mapInstr=mapInstr, x=self.instruction['east2'],
+            y=self.instruction['north2'],
+            paperToMap=False)
         instr['rect'] = Rect2DPP(wx.Point2D(e1, n1), wx.Point2D(e2, n2))
         self.instruction.update(instr)
 
         return True
-        
+
+
 class Scalebar(InstructionObject):
     """Class representing scalebar instruction"""
+
     def __init__(self, id):
-        InstructionObject.__init__(self, id = id)
+        InstructionObject.__init__(self, id=id)
         self.type = 'scalebar'
         # default values
-        self.defaultInstruction = dict(unit = 'inch', where = (1,1),
-                                       unitsLength = 'auto', unitsHeight = 'inch',
-                                       length = None, height = 0.1, rect = None,
-                                       fontsize = 10, background = 'y',
-                                       scalebar = 'f', segment = 4, numbers = 1)
+        self.defaultInstruction = dict(unit='inch', where=(1, 1),
+                                       unitsLength='auto', unitsHeight='inch',
+                                       length=None, height=0.1, rect=None,
+                                       fontsize=10, background='y',
+                                       scalebar='f', segment=4, numbers=1)
         # current values
         self.instruction = dict(self.defaultInstruction)
-        
+
     def __str__(self):
-        instr = string.Template("scalebar $scalebar\n").substitute(self.instruction)
-        instr += "    where %.3f %.3f\n" % (self.instruction['where'][0], self.instruction['where'][1])
-        instr += string.Template("    length $length\n    units $unitsLength\n").substitute(self.instruction)
+        instr = string.Template(
+            "scalebar $scalebar\n").substitute(self.instruction)
+        instr += "    where %.3f %.3f\n" % (
+            self.instruction['where'][0],
+            self.instruction['where'][1])
+        instr += string.Template(
+            "    length $length\n    units $unitsLength\n").substitute(self.instruction)
         instr += string.Template("    height $height\n").substitute(self.instruction)
-        instr += string.Template("    segment $segment\n    numbers $numbers\n").substitute(self.instruction)
-        instr += string.Template("    fontsize $fontsize\n    background $background\n").substitute(self.instruction)
+        instr += string.Template(
+            "    segment $segment\n    numbers $numbers\n").substitute(self.instruction)
+        instr += string.Template(
+            "    fontsize $fontsize\n    background $background\n").substitute(
+            self.instruction)
         instr += "    end"
         return instr
-    
+
     def Read(self, instruction, text, **kwargs):
         """Read instruction and save information"""
         scale = kwargs['scale']
@@ -1241,7 +1445,9 @@
                 elif line.startswith('length'):
                     instr['length'] = float(line.split()[1])
                 elif line.startswith('units'):
-                    if line.split()[1] in ['auto', 'meters', 'kilometers', 'feet', 'miles', 'nautmiles']:
+                    if line.split()[1] in[
+                            'auto', 'meters', 'kilometers', 'feet', 'miles',
+                            'nautmiles']:
                         instr['unitsLength'] = line.split()[1]
                 elif line.startswith('height'):
                     instr['height'] = float(line.split()[1])
@@ -1252,74 +1458,90 @@
                 elif line.startswith('segment'):
                     instr['segment'] = int(line.split()[1])
                 elif line.startswith('background'):
-                    if line.split()[1].strip().lower() in ('y','yes'):
+                    if line.split()[1].strip().lower() in ('y', 'yes'):
                         instr['background'] = 'y'
-                    elif line.split()[1].strip().lower() in ('n','no', 'none'):
+                    elif line.split()[1].strip().lower() in ('n', 'no', 'none'):
                         instr['background'] = 'n'
             except(IndexError, ValueError):
                 GError(_("Failed to read instruction %s") % instruction)
                 return False
-            
+
         self.instruction.update(instr)
-        w, h = self.EstimateSize(scalebarDict = self.instruction, scale = scale)
-        x = self.instruction['where'][0] - w / 2 
+        w, h = self.EstimateSize(scalebarDict=self.instruction, scale=scale)
+        x = self.instruction['where'][0] - w / 2
         y = self.instruction['where'][1] - h / 2
         self.instruction['rect'] = Rect2D(x, y, w, h)
-        return True 
-    
+        return True
+
     def EstimateSize(self, scalebarDict, scale):
         """Estimate size to draw scalebar"""
         units = projInfo()['units']
         if not units or units not in self.unitConv.getAllUnits():
             units = 'meters'
         if scalebarDict['unitsLength'] != 'auto':
-            length = self.unitConv.convert(value = scalebarDict['length'], fromUnit = scalebarDict['unitsLength'], toUnit = 'inch')
+            length = self.unitConv.convert(
+                value=scalebarDict['length'],
+                fromUnit=scalebarDict['unitsLength'],
+                toUnit='inch')
         else:
-            length = self.unitConv.convert(value = scalebarDict['length'], fromUnit = units, toUnit = 'inch')
-            
+            length = self.unitConv.convert(
+                value=scalebarDict['length'],
+                fromUnit=units, toUnit='inch')
+
         length *= scale
-        length *= 1.1 #for numbers on the edge
-        height = scalebarDict['height'] + 2 * self.unitConv.convert(value = scalebarDict['fontsize'], fromUnit = 'point', toUnit = 'inch')     
+        length *= 1.1  # for numbers on the edge
+        height = scalebarDict['height'] + 2 * self.unitConv.convert(
+            value=scalebarDict['fontsize'], fromUnit='point', toUnit='inch')
         return (length, height)
-    
+
+
 class RasterLegend(InstructionObject):
     """Class representing colortable instruction"""
+
     def __init__(self, id):
-        InstructionObject.__init__(self, id = id)
+        InstructionObject.__init__(self, id=id)
         self.type = 'rasterLegend'
         # default values
-        self.defaultInstruction = dict(rLegend = False, unit = 'inch', rasterDefault = True, raster = None,
-                                       discrete = None, type = None,
-                                       where = (0, 0),
-                                       width = None, height = None, cols = 1, font = "Helvetica", fontsize = 10,
-                                       #color = '0:0:0', tickbar = False, range = False, min = 0, max = 0,
-                                       color = 'black', tickbar = 'n', range = False, min = 0, max = 0,
-                                       nodata = 'n')
+        self.defaultInstruction = dict(rLegend=False, unit='inch', rasterDefault=True, raster=None,
+                                       discrete=None, type=None,
+                                       where=(0, 0),
+                                       width=None, height=None, cols=1, font="Helvetica", fontsize=10,
+                                       # color = '0:0:0', tickbar = False,
+                                       # range = False, min = 0, max = 0,
+                                       color='black', tickbar='n', range=False, min=0, max=0,
+                                       nodata='n')
         # current values
         self.instruction = dict(self.defaultInstruction)
-        
+
     def __str__(self):
         instr = "colortable y\n"
         instr += string.Template("    raster $raster\n").substitute(self.instruction)
-        instr += "    where %.3f %.3f\n" % (self.instruction['where'][0], self.instruction['where'][1])
+        instr += "    where %.3f %.3f\n" % (
+            self.instruction['where'][0],
+            self.instruction['where'][1])
         if self.instruction['width']:
-            instr += string.Template("    width $width\n").substitute(self.instruction)
-        instr += string.Template("    discrete $discrete\n").substitute(self.instruction)
+            instr += string.Template(
+                "    width $width\n").substitute(self.instruction)
+        instr += string.Template(
+            "    discrete $discrete\n").substitute(self.instruction)
         if self.instruction['discrete'] == 'n':
             if self.instruction['height']:
-                instr += string.Template("    height $height\n").substitute(self.instruction)
-            instr += string.Template("    tickbar $tickbar\n").substitute(self.instruction)
+                instr += string.Template(
+                    "    height $height\n").substitute(self.instruction)
+            instr += string.Template(
+                "    tickbar $tickbar\n").substitute(self.instruction)
             if self.instruction['range']:
-                instr += string.Template("    range $min $max\n").substitute(self.instruction)
+                instr += string.Template(
+                    "    range $min $max\n").substitute(self.instruction)
         else:
             instr += string.Template("    cols $cols\n").substitute(self.instruction)
-            instr += string.Template("    nodata $nodata\n").substitute(self.instruction)
+            instr += string.Template(
+                "    nodata $nodata\n").substitute(self.instruction)
         instr += string.Template("    font $font\n    fontsize $fontsize\n    color $color\n")\
             .substitute(self.instruction)
         instr += "    end"
-        return instr    
-    
-    
+        return instr
+
     def Read(self, instruction, text, **kwargs):
         """Read instruction and save information"""
         instr = {}
@@ -1341,129 +1563,149 @@
                 elif line.startswith('height'):
                     instr['height'] = float(line.split()[1])
                 elif line.startswith('cols'):
-                    instr['cols'] = int(line.split()[1])                    
+                    instr['cols'] = int(line.split()[1])
                 elif line.startswith('range'):
                     instr['range'] = True
                     instr['min'] = float(line.split()[1])
                     instr['max'] = float(line.split()[2])
                 elif line.startswith('nodata'):
-                    if line.split()[1].strip().lower() in ('y','yes'):
+                    if line.split()[1].strip().lower() in ('y', 'yes'):
                         instr['nodata'] = 'y'
-                    elif line.split()[1].strip().lower() in ('n','no', 'none'):
+                    elif line.split()[1].strip().lower() in ('n', 'no', 'none'):
                         instr['nodata'] = 'n'
                 elif line.startswith('tickbar'):
-                    if line.split()[1].strip().lower() in ('y','yes'):
+                    if line.split()[1].strip().lower() in ('y', 'yes'):
                         instr['tickbar'] = 'y'
-                    elif line.split()[1].strip().lower() in ('n','no', 'none'):
+                    elif line.split()[1].strip().lower() in ('n', 'no', 'none'):
                         instr['tickbar'] = 'n'
                 elif line.startswith('discrete'):
-                    if line.split()[1].strip().lower() in ('y','yes'):
+                    if line.split()[1].strip().lower() in ('y', 'yes'):
                         instr['discrete'] = 'y'
-                    elif line.split()[1].strip().lower() in ('n','no', 'none'):
-                        instr['discrete'] = 'n'            
+                    elif line.split()[1].strip().lower() in ('n', 'no', 'none'):
+                        instr['discrete'] = 'n'
 
             except(IndexError, ValueError):
                 GError(_("Failed to read instruction %s") % instruction)
                 return False
-            
+
         if 'raster' in instr:
             instr['rasterDefault'] = False
             if 'discrete' not in instr:
-                rasterType = getRasterType(map = instr['raster'])
+                rasterType = getRasterType(map=instr['raster'])
                 instr['type'] = rasterType
                 if rasterType == 'CELL':
                     instr['discrete'] = 'y'
                 else:
                     instr['discrete'] = 'n'
-            
+
         else:
             instr['rasterDefault'] = True
         self.instruction.update(instr)
         # add 'rect' in the end
-            
-        return True 
-    
-    def EstimateHeight(self, raster, discrete, fontsize, cols = None,  height = None):
+
+        return True
+
+    def EstimateHeight(self, raster, discrete, fontsize,
+                       cols=None, height=None):
         """Estimate height to draw raster legend"""
         if discrete == 'n':
             if height:
                 height = height
             else:
-                height = self.unitConv.convert(value = fontsize * 10,
-                                                    fromUnit = 'point', toUnit = 'inch')
-                                                    
+                height = self.unitConv.convert(value=fontsize * 10,
+                                               fromUnit='point', toUnit='inch')
+
         if discrete == 'y':
             if cols:
-                cols = cols 
+                cols = cols
             else:
-                cols = 1 
+                cols = 1
 
             rinfo = grass.raster_info(raster)
             if rinfo['datatype'] in ('DCELL', 'FCELL'):
                 minim, maxim = rinfo['min'], rinfo['max']
-                rows = ceil(maxim / cols )
+                rows = ceil(maxim / cols)
             else:
-                cat = grass.read_command('r.category', map = raster,
-                                    sep = ':').strip().split('\n')
-                rows = ceil(float(len(cat)) / cols )
-                            
-                
-            height = self.unitConv.convert(value =  1.5 * rows * fontsize, fromUnit = 'point', toUnit = 'inch')
-            
+                cat = grass.read_command('r.category', map=raster,
+                                         sep=':').strip().split('\n')
+                rows = ceil(float(len(cat)) / cols)
+
+            height = self.unitConv.convert(
+                value=1.5 * rows * fontsize,
+                fromUnit='point',
+                toUnit='inch')
+
         return height
-        
-    def EstimateWidth(self, raster, discrete, fontsize, cols = None, width = None, paperInstr = None):
+
+    def EstimateWidth(self, raster, discrete, fontsize,
+                      cols=None, width=None, paperInstr=None):
         """Estimate size to draw raster legend"""
-        
+
         if discrete == 'n':
             rinfo = grass.raster_info(raster)
             minim, maxim = rinfo['min'], rinfo['max']
             if width:
                 width = width
             else:
-                width = self.unitConv.convert(value = fontsize * 2,
-                                                    fromUnit = 'point', toUnit = 'inch')
-            text = len(max(str(minim), str(maxim), key = len))
-            textPart = self.unitConv.convert(value = text * fontsize / 2,
-                                                    fromUnit = 'point', toUnit = 'inch')
+                width = self.unitConv.convert(value=fontsize * 2,
+                                              fromUnit='point', toUnit='inch')
+            text = len(max(str(minim), str(maxim), key=len))
+            textPart = self.unitConv.convert(value=text * fontsize / 2,
+                                             fromUnit='point', toUnit='inch')
             width += textPart
-                                                    
+
         elif discrete == 'y':
             if cols:
-                cols = cols 
+                cols = cols
             else:
-                cols = 1    
+                cols = 1
 
             if width:
                 width = width
             else:
-                paperWidth = paperInstr['Width'] - paperInstr['Right'] - paperInstr['Left']
+                paperWidth = paperInstr[
+                    'Width'] - paperInstr['Right'] - paperInstr['Left']
                 width = (paperWidth / cols) * (cols - 1) + 1
-                
-        return width    
-             
+
+        return width
+
+
 class VectorLegend(InstructionObject):
     """Class representing colortable instruction"""
+
     def __init__(self, id):
-        InstructionObject.__init__(self, id = id)
+        InstructionObject.__init__(self, id=id)
         self.type = 'vectorLegend'
         # default values
-        self.defaultInstruction = dict(vLegend = False, unit = 'inch', where = (0, 0),
-                                                defaultSize = True, width = 0.4, cols = 1, span = None,
-                                                font = "Helvetica", fontsize = 10,
-                                                border = 'none')
+        self.defaultInstruction = dict(
+            vLegend=False,
+            unit='inch',
+            where=(
+                0,
+                0),
+            defaultSize=True,
+            width=0.4,
+            cols=1,
+            span=None,
+            font="Helvetica",
+            fontsize=10,
+            border='none')
         # current values
         self.instruction = dict(self.defaultInstruction)
-        
+
     def __str__(self):
         instr = "vlegend\n"
-        instr += "    where %.3f %.3f\n" % (self.instruction['where'][0], self.instruction['where'][1])
-        instr += string.Template("    font $font\n    fontsize $fontsize\n").substitute(self.instruction)
-        instr += string.Template("    width $width\n    cols $cols\n").substitute(self.instruction)
+        instr += "    where %.3f %.3f\n" % (
+            self.instruction['where'][0],
+            self.instruction['where'][1])
+        instr += string.Template(
+            "    font $font\n    fontsize $fontsize\n").substitute(self.instruction)
+        instr += string.Template(
+            "    width $width\n    cols $cols\n").substitute(self.instruction)
         if self.instruction['span']:
             instr += string.Template("    span $span\n").substitute(self.instruction)
-        instr += string.Template("    border $border\n").substitute(self.instruction)  
-        instr += "    end"  
+        instr += string.Template("    border $border\n").substitute(self.instruction)
+        instr += "    end"
         return instr
 
     def Read(self, instruction, text, **kwargs):
@@ -1481,57 +1723,60 @@
                 elif line.startswith('width'):
                     instr['width'] = float(line.split()[1])
                 elif line.startswith('cols'):
-                    instr['cols'] = int(line.split()[1]) 
+                    instr['cols'] = int(line.split()[1])
                 elif line.startswith('span'):
                     instr['span'] = float(line.split()[1])
                 elif line.startswith('border'):
                     instr['border'] = line.split()[1]
-                    
+
             except(IndexError, ValueError):
                 GError(_("Failed to read instruction %s") % instruction)
                 return False
-            
+
         self.instruction.update(instr)
-            
-        return True 
-    
-    def EstimateSize(self, vectorInstr, fontsize, width = None, cols = None):
+
+        return True
+
+    def EstimateSize(self, vectorInstr, fontsize, width=None, cols=None):
         """Estimate size to draw vector legend"""
         if width:
-            width = width 
+            width = width
         else:
-            width = fontsize/24.0
+            width = fontsize / 24.0
 
         if cols:
-            cols = cols 
+            cols = cols
         else:
             cols = 1
 
         vectors = vectorInstr['list']
         labels = [vector[4] for vector in vectors if vector[3] != 0]
-        extent = (len(max(labels, key = len)) * fontsize / 2, fontsize)
-        wExtent = self.unitConv.convert(value = extent[0], fromUnit = 'point', toUnit = 'inch')
-        hExtent = self.unitConv.convert(value = extent[1], fromUnit = 'point', toUnit = 'inch')
+        extent = (len(max(labels, key=len)) * fontsize / 2, fontsize)
+        wExtent = self.unitConv.convert(
+            value=extent[0], fromUnit='point', toUnit='inch')
+        hExtent = self.unitConv.convert(
+            value=extent[1], fromUnit='point', toUnit='inch')
         w = (width + wExtent) * cols
         h = len(labels) * hExtent / cols
         h *= 1.1
         return (w, h)
-            
-   
+
+
 class Raster(InstructionObject):
     """Class representing raster instruction"""
+
     def __init__(self, id):
-        InstructionObject.__init__(self, id = id)
+        InstructionObject.__init__(self, id=id)
         self.type = 'raster'
         # default values
-        self.defaultInstruction = dict(isRaster = False, raster = None)
+        self.defaultInstruction = dict(isRaster=False, raster=None)
         # current values
         self.instruction = dict(self.defaultInstruction)
-        
+
     def __str__(self):
         instr = string.Template("raster $raster").substitute(self.instruction)
         return instr
-    
+
     def Read(self, instruction, text):
         """Read instruction and save information"""
         instr = {}
@@ -1542,34 +1787,38 @@
             GError(_("Failed to read instruction %s") % instruction)
             return False
         try:
-            info = grass.find_file(map, element = 'cell')
+            info = grass.find_file(map, element='cell')
         except grass.ScriptError as e:
-            GError(message = e.value)
+            GError(message=e.value)
             return False
         instr['raster'] = info['fullname']
 
-        
         self.instruction.update(instr)
         return True
-    
+
+
 class Vector(InstructionObject):
     """Class keeps vector layers"""
+
     def __init__(self, id):
-        InstructionObject.__init__(self, id = id)
+        InstructionObject.__init__(self, id=id)
         self.type = 'vector'
         # default values
-        self.defaultInstruction = dict(list = None)# [vmap, type, id, lpos, label] 
+        self.defaultInstruction = dict(
+            list=None)  # [vmap, type, id, lpos, label]
         # current values
         self.instruction = dict(self.defaultInstruction)
+
     def __str__(self):
         return ''
-    
+
     def Read(self, instruction, text, **kwargs):
         """Read instruction and save information"""
         instr = {}
-        
+
         for line in text:
-            if line.startswith('vpoints') or line.startswith('vlines') or line.startswith('vareas'):
+            if line.startswith('vpoints') or line.startswith(
+                    'vlines') or line.startswith('vareas'):
                 # subtype
                 if line.startswith('vpoints'):
                     subType = 'points'
@@ -1580,115 +1829,171 @@
                 # name of vector map
                 vmap = line.split()[1]
                 try:
-                    info = grass.find_file(vmap, element = 'vector')
+                    info = grass.find_file(vmap, element='vector')
                 except grass.ScriptError as e:
-                    GError(message = e.value)
+                    GError(message=e.value)
                     return False
                 vmap = info['fullname']
                 # id
                 id = kwargs['id']
                 # lpos
                 lpos = kwargs['vectorMapNumber']
-                #label
+                # label
                 label = '('.join(vmap.split('@')) + ')'
                 break
-        instr = [vmap, subType, id, lpos, label] 
+        instr = [vmap, subType, id, lpos, label]
         if not self.instruction['list']:
             self.instruction['list'] = []
         self.instruction['list'].append(instr)
-        
-        return True    
-    
+
+        return True
+
+
 class VProperties(InstructionObject):
     """Class represents instructions vareas, vlines, vpoints"""
+
     def __init__(self, id, subType):
-        InstructionObject.__init__(self, id = id)
+        InstructionObject.__init__(self, id=id)
         self.type = 'vProperties'
         self.subType = subType
         # default values
         if self.subType == 'points':
-            dd = dict(subType  = 'points', name = None, type = 'point or centroid', connection = False, layer = '1',
-                        masked = 'n', color = '0:0:0', width = 1,
-                        fcolor = '255:0:0', rgbcolumn = None, symbol = os.path.join('basic', 'x'), eps = None,
-                        size = 5, sizecolumn = None, scale = None,
-                        rotation = False, rotate = 0, rotatecolumn = None, label = None, lpos = None)
+            dd = dict(
+                subType='points',
+                name=None,
+                type='point or centroid',
+                connection=False,
+                layer='1',
+                masked='n',
+                color='0:0:0',
+                width=1,
+                fcolor='255:0:0',
+                rgbcolumn=None,
+                symbol=os.path.join(
+                    'basic',
+                    'x'),
+                eps=None,
+                size=5,
+                sizecolumn=None,
+                scale=None,
+                rotation=False,
+                rotate=0,
+                rotatecolumn=None,
+                label=None,
+                lpos=None)
         elif self.subType == 'lines':
-            dd = dict(subType = 'lines', name = None, type = 'line or boundary', connection = False, layer = '1',
-                        masked = 'n', color = '0:0:0', hwidth = 1,
-                        hcolor = 'none', rgbcolumn = None,
-                        width = 1, cwidth = None,
-                        style = 'solid', linecap = 'butt', label = None, lpos = None)
-        else: # areas
-            dd = dict(subType = 'areas', name = None, connection = False, layer = '1',    
-                        masked = 'n', color = '0:0:0', width = 1,
-                        fcolor = 'none', rgbcolumn = None,
-                        pat = None, pwidth = 1, scale = 1, label = None, lpos = None)
+            dd = dict(
+                subType='lines',
+                name=None,
+                type='line or boundary',
+                connection=False,
+                layer='1',
+                masked='n',
+                color='0:0:0',
+                hwidth=1,
+                hcolor='none',
+                rgbcolumn=None,
+                width=1,
+                cwidth=None,
+                style='solid',
+                linecap='butt',
+                label=None,
+                lpos=None)
+        else:  # areas
+            dd = dict(subType='areas', name=None, connection=False, layer='1',
+                      masked='n', color='0:0:0', width=1,
+                      fcolor='none', rgbcolumn=None,
+                      pat=None, pwidth=1, scale=1, label=None, lpos=None)
         self.defaultInstruction = dd
         # current values
         self.instruction = dict(self.defaultInstruction)
-        
+
     def __str__(self):
         dic = self.instruction
         vInstruction = string.Template("v$subType $name\n").substitute(dic)
-        #data selection
+        # data selection
         if self.subType in ('points', 'lines'):
-           vInstruction += string.Template("    type $type\n").substitute(dic) 
+            vInstruction += string.Template("    type $type\n").substitute(dic)
         if dic['connection']:
-            vInstruction += string.Template("    layer $layer\n").substitute(dic)
-            if dic.has_key('cats'):
-                vInstruction += string.Template("    cats $cats\n").substitute(dic)
-            elif dic.has_key('where'):
-                    vInstruction += string.Template("    where $where\n").substitute(dic)
+            vInstruction += string.Template(
+                "    layer $layer\n").substitute(dic)
+            if 'cats' in dic:
+                vInstruction += string.Template(
+                    "    cats $cats\n").substitute(dic)
+            elif 'where' in dic:
+                vInstruction += string.Template(
+                    "    where $where\n").substitute(dic)
         vInstruction += string.Template("    masked $masked\n").substitute(dic)
-        #colors
+        # colors
         vInstruction += string.Template("    color $color\n").substitute(dic)
         if self.subType in ('points', 'areas'):
             if dic['color'] != 'none':
-                vInstruction += string.Template("    width $width\n").substitute(dic)
+                vInstruction += string.Template(
+                    "    width $width\n").substitute(dic)
             if dic['rgbcolumn']:
-                vInstruction += string.Template("    rgbcolumn $rgbcolumn\n").substitute(dic)
-            vInstruction += string.Template("    fcolor $fcolor\n").substitute(dic)
+                vInstruction += string.Template(
+                    "    rgbcolumn $rgbcolumn\n").substitute(dic)
+            vInstruction += string.Template(
+                "    fcolor $fcolor\n").substitute(dic)
         else:
             if dic['rgbcolumn']:
-                vInstruction += string.Template("    rgbcolumn $rgbcolumn\n").substitute(dic)
+                vInstruction += string.Template(
+                    "    rgbcolumn $rgbcolumn\n").substitute(dic)
             elif dic['hcolor'] != 'none':
-                vInstruction += string.Template("    hwidth $hwidth\n").substitute(dic)
-                vInstruction += string.Template("    hcolor $hcolor\n").substitute(dic)
-        
+                vInstruction += string.Template(
+                    "    hwidth $hwidth\n").substitute(dic)
+                vInstruction += string.Template(
+                    "    hcolor $hcolor\n").substitute(dic)
+
         # size and style
         if self.subType == 'points':
             if not dic['eps']:
-                vInstruction += string.Template("    symbol $symbol\n").substitute(dic)
-            else: #eps
-                vInstruction += string.Template("    eps $eps\n").substitute(dic)
+                vInstruction += string.Template(
+                    "    symbol $symbol\n").substitute(dic)
+            else:  # eps
+                vInstruction += string.Template(
+                    "    eps $eps\n").substitute(dic)
             if dic['size']:
-                vInstruction += string.Template("    size $size\n").substitute(dic)            
-            else: # sizecolumn
-                vInstruction += string.Template("    sizecolumn $sizecolumn\n").substitute(dic)
-                vInstruction += string.Template("    scale $scale\n").substitute(dic)
+                vInstruction += string.Template(
+                    "    size $size\n").substitute(dic)
+            else:  # sizecolumn
+                vInstruction += string.Template(
+                    "    sizecolumn $sizecolumn\n").substitute(dic)
+                vInstruction += string.Template(
+                    "    scale $scale\n").substitute(dic)
             if dic['rotation']:
                 if dic['rotate'] is not None:
-                    vInstruction += string.Template("    rotate $rotate\n").substitute(dic)
+                    vInstruction += string.Template(
+                        "    rotate $rotate\n").substitute(dic)
                 else:
-                    vInstruction += string.Template("    rotatecolumn $rotatecolumn\n").substitute(dic)
-                    
+                    vInstruction += string.Template(
+                        "    rotatecolumn $rotatecolumn\n").substitute(dic)
+
         if self.subType == 'areas':
             if dic['pat'] is not None:
-                patternFile = dic['pat'].replace(os.getenv("GISBASE"), "$GISBASE")
+                patternFile = dic['pat'].replace(
+                    os.getenv("GISBASE"), "$GISBASE")
                 vInstruction += "    pat %s\n" % patternFile
-                vInstruction += string.Template("    pwidth $pwidth\n").substitute(dic)
-                vInstruction += string.Template("    scale $scale\n").substitute(dic)
-                
+                vInstruction += string.Template(
+                    "    pwidth $pwidth\n").substitute(dic)
+                vInstruction += string.Template(
+                    "    scale $scale\n").substitute(dic)
+
         if self.subType == 'lines':
             if dic['width'] is not None:
-                vInstruction += string.Template("    width $width\n").substitute(dic)
+                vInstruction += string.Template(
+                    "    width $width\n").substitute(dic)
             else:
-                vInstruction += string.Template("    cwidth $cwidth\n").substitute(dic)
-            vInstruction += string.Template("    style $style\n").substitute(dic)
-            vInstruction += string.Template("    linecap $linecap\n").substitute(dic)
+                vInstruction += string.Template(
+                    "    cwidth $cwidth\n").substitute(dic)
+            vInstruction += string.Template(
+                "    style $style\n").substitute(dic)
+            vInstruction += string.Template(
+                "    linecap $linecap\n").substitute(dic)
         #position and label in vlegend
-        vInstruction += string.Template("    label $label\n    lpos $lpos\n").substitute(dic)
-        
+        vInstruction += string.Template(
+            "    label $label\n    lpos $lpos\n").substitute(dic)
+
         vInstruction += "    end"
         try:
             vInstruction = vInstruction.encode('Latin_1')
@@ -1705,26 +2010,26 @@
                 message = _("Not all characters are supported "
                             "by ISO-8859-1 (Latin 1) encoding "
                             "which is required by module ps.map.")
-            GMessage(message = message)
+            GMessage(message=message)
             return ''
         return vInstruction
-    
+
     def Read(self, instruction, text, **kwargs):
         """Read instruction and save information"""
         instr = {}
         try:
-            info = grass.find_file(name = text[0].split()[1], element = 'vector')
+            info = grass.find_file(name=text[0].split()[1], element='vector')
         except grass.ScriptError as e:
-            GError(message = e.value)
+            GError(message=e.value)
             return False
         instr['name'] = info['fullname']
-        #connection
+        # connection
         instr['connection'] = True
         self.mapDBInfo = VectorDBInfo(instr['name'])
         self.layers = self.mapDBInfo.layers.keys()
         if not self.layers:
             instr['connection'] = False
-            
+
         # points
         if text[0].startswith('vpoints'):
             for line in text[1:]:
@@ -1757,8 +2062,8 @@
                     instr['rotatecolumn'] = line.split()[1]
                     instr['rotation'] = True
                     instr['rotate'] = None
-                    
-        # lines            
+
+        # lines
         elif text[0].startswith('vlines'):
             for line in text[1:]:
                 if line.startswith('type'):
@@ -1773,29 +2078,29 @@
                 elif line.startswith('hcolor'):
                     instr['hcolor'] = line.split()[1]
                 elif line.startswith('rgbcolumn'):
-                    instr['rgbcolumn'] = line.split()[1]                    
+                    instr['rgbcolumn'] = line.split()[1]
                 elif line.startswith('cwidth'):
                     instr['cwidth'] = float(line.split()[1])
                     instr['width'] = None
                 elif line.startswith('style'):
-                    instr['style'] = line.split()[1]       
+                    instr['style'] = line.split()[1]
                 elif line.startswith('linecap'):
                     instr['linecap'] = line.split()[1]
-         
+
         elif text[0].startswith('vareas'):
             for line in text[1:]:
                 if line.startswith('fcolor'):
-                    instr['fcolor'] = line.split()[1]    
+                    instr['fcolor'] = line.split()[1]
                 elif line.startswith('pat'):
                     patternFile = line.split()[1]
-                    instr['pat'] = patternFile.replace("$GISBASE", os.getenv("GISBASE"))
+                    instr['pat'] = patternFile.replace(
+                        "$GISBASE", os.getenv("GISBASE"))
                 elif line.startswith('pwidth'):
                     instr['pwidth'] = float(line.split()[1])
                 elif line.startswith('scale'):
                     instr['scale'] = float(line.split()[1])
-            
-            
-        # same properties for all    
+
+        # same properties for all
         for line in text[1:]:
             if line.startswith('lpos'):
                 instr['lpos'] = int(line.split()[1])
@@ -1811,35 +2116,37 @@
             elif line.startswith('color'):
                 instr['color'] = line.split()[1]
             elif line.startswith('rgbcolumn'):
-                instr['rgbcolumn'] = line.split()[1] 
+                instr['rgbcolumn'] = line.split()[1]
             elif line.startswith('width'):
                 instr['width'] = float(line.split()[1])
-                
+
         if 'label' not in instr:
             instr['label'] = '('.join(instr['name'].split('@')) + ')'
         if 'lpos' not in instr:
             instr['lpos'] = kwargs['vectorMapNumber']
         self.instruction.update(instr)
-        
+
         return True
 
+
 class Labels(InstructionObject):
     """Class representing labels instruction"""
+
     def __init__(self, id):
-        InstructionObject.__init__(self, id = id)
+        InstructionObject.__init__(self, id=id)
         self.type = 'labels'
         # default values
         self.defaultInstruction = dict(labels=[])
         # current values
         self.instruction = dict(self.defaultInstruction)
-        
+
     def __str__(self):
         instr = ''
         for label in self.instruction['labels']:
             instr += "labels %s\n" % label
             instr += "end\n"
         return instr
-    
+
     def Read(self, instruction, text, **kwargs):
         """Read instruction and save information"""
         for line in text:
@@ -1850,6 +2157,5 @@
             except(IndexError, ValueError):
                 GError(_("Failed to read instruction %s") % instruction)
                 return False
-        
 
         return True

Modified: grass/trunk/gui/wxpython/psmap/menudata.py
===================================================================
--- grass/trunk/gui/wxpython/psmap/menudata.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/psmap/menudata.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -19,13 +19,18 @@
 from core import globalvar
 from core.menutree import MenuTreeModelBuilder
 
+
 class PsMapMenuData(MenuTreeModelBuilder):
-    def __init__(self, path = None):
+
+    def __init__(self, path=None):
         """Menu for Cartographic Composer (psmap.py)
-        
+
         :param path: path to XML to be read (None for menudata_psmap.xml)
         """
         if not path:
-            path = os.path.join(globalvar.WXGUIDIR, 'xml', 'menudata_psmap.xml')
-        
+            path = os.path.join(
+                globalvar.WXGUIDIR,
+                'xml',
+                'menudata_psmap.xml')
+
         MenuTreeModelBuilder.__init__(self, path)

Modified: grass/trunk/gui/wxpython/psmap/toolbars.py
===================================================================
--- grass/trunk/gui/wxpython/psmap/toolbars.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/psmap/toolbars.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -18,15 +18,17 @@
 
 import wx
 
-from core              import globalvar
+from core import globalvar
 from core.utils import _
 from gui_core.toolbars import BaseToolbar, BaseIcons
-from icons.icon        import MetaIcon
+from icons.icon import MetaIcon
 
+
 class PsMapToolbar(BaseToolbar):
+
     def __init__(self, parent, toolSwitcher):
         """Toolbar Cartographic Composer (psmap.py)
-        
+
         :param parent: parent window
         """
         BaseToolbar.__init__(self, parent, toolSwitcher)
@@ -37,10 +39,11 @@
 
         self.InitToolbar(self._toolbarData())
         self._default = self.pointer
-        
+
         for tool in (self.pointer, self.pan, self.zoomin, self.zoomout,
                      self.drawGraphics, self.addMap):
-            self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=tool)
+            self.toolSwitcher.AddToolToGroup(
+                group='mouseUse', toolbar=self, tool=tool)
 
         # custom button for graphics mode selection
         # TODO: could this be somehow generalized?
@@ -49,68 +52,68 @@
         self.arrowButton.Bind(wx.EVT_BUTTON, self.OnDrawGraphicsMenu)
 
         self.drawGraphicsAction = None
-        self.OnAddPoint(event = None)
+        self.OnAddPoint(event=None)
 
         self.Realize()
 
         from psmap.frame import havePILImage
         if not havePILImage:
             self.EnableTool(self.preview, False)
-        
+
     def _toolbarData(self):
         """Toolbar data
         """
         icons = {
-            'scriptSave' : MetaIcon(img = 'script-save',
-                                    label = _('Generate text file with mapping instructions')),
-            'scriptLoad' : MetaIcon(img = 'script-load',
-                                    label = _('Load text file with mapping instructions')),                           
-            'psExport'   : MetaIcon(img = 'ps-export',
-                                    label = _('Generate PostScript output')),
-            'pdfExport'  : MetaIcon(img = 'pdf-export',
-                                    label = _('Generate PDF output')),
-            'pageSetup'  : MetaIcon(img = 'page-settings',
-                                    label = _('Page setup'),
-                                    desc = _('Specify paper size, margins and orientation')),
-            'fullExtent' : MetaIcon(img = 'zoom-extent',
-                                    label = _("Full extent"),
-                                    desc = _("Zoom to full extent")),
-            'addMap'     : MetaIcon(img = 'layer-add',
-                                    label = _("Map frame"),
-                                    desc = _("Click and drag to place map frame")),
-            'deleteObj'  : MetaIcon(img = 'layer-remove',
-                                    label = _("Delete selected object")),
-            'preview'    : MetaIcon(img = 'execute',
-                                    label = _("Show preview")),
-            'quit'       : MetaIcon(img = 'quit',
-                                    label = _('Quit Cartographic Composer')),
-            'addText'    : MetaIcon(img = 'text-add',
-                                    label = _('Text')),
-            'addMapinfo' : MetaIcon(img = 'map-info',
-                                    label = _('Map info')),
-            'addLegend'  : MetaIcon(img = 'legend-add',
-                                    label = _('Legend')),
-            'addScalebar' : MetaIcon(img = 'scalebar-add',
-                                     label = _('Scale bar')),
-            'addImage'   : MetaIcon(img = 'image-add',
-                                    label = _('Image')),
-            'addNorthArrow': MetaIcon(img = 'north-arrow-add',
-                                      label = _('North Arrow')),
-            'pointAdd'    : MetaIcon(img = 'point-add',
-                                     label = _('Point')),
-            'lineAdd'     : MetaIcon(img = 'line-add',
-                                     label = _('Line')),
-            'rectangleAdd': MetaIcon(img = 'rectangle-add',
-                                     label = _('Rectangle')),
-            'overlaysAdd': MetaIcon(img = 'layer-more',
-                                    label = _("Add overlays")),
-            'labelsAdd': MetaIcon(img = 'layer-label-add',
-                                    label = _("Add labels"))
-            }
+            'scriptSave': MetaIcon(img='script-save',
+                                   label=_('Generate text file with mapping instructions')),
+            'scriptLoad': MetaIcon(img='script-load',
+                                   label=_('Load text file with mapping instructions')),
+            'psExport': MetaIcon(img='ps-export',
+                                 label=_('Generate PostScript output')),
+            'pdfExport': MetaIcon(img='pdf-export',
+                                  label=_('Generate PDF output')),
+            'pageSetup': MetaIcon(img='page-settings',
+                                  label=_('Page setup'),
+                                  desc=_('Specify paper size, margins and orientation')),
+            'fullExtent': MetaIcon(img='zoom-extent',
+                                   label=_("Full extent"),
+                                   desc=_("Zoom to full extent")),
+            'addMap': MetaIcon(img='layer-add',
+                               label=_("Map frame"),
+                               desc=_("Click and drag to place map frame")),
+            'deleteObj': MetaIcon(img='layer-remove',
+                                  label=_("Delete selected object")),
+            'preview': MetaIcon(img='execute',
+                                label=_("Show preview")),
+            'quit': MetaIcon(img='quit',
+                             label=_('Quit Cartographic Composer')),
+            'addText': MetaIcon(img='text-add',
+                                label=_('Text')),
+            'addMapinfo': MetaIcon(img='map-info',
+                                   label=_('Map info')),
+            'addLegend': MetaIcon(img='legend-add',
+                                  label=_('Legend')),
+            'addScalebar': MetaIcon(img='scalebar-add',
+                                    label=_('Scale bar')),
+            'addImage': MetaIcon(img='image-add',
+                                 label=_('Image')),
+            'addNorthArrow': MetaIcon(img='north-arrow-add',
+                                      label=_('North Arrow')),
+            'pointAdd': MetaIcon(img='point-add',
+                                 label=_('Point')),
+            'lineAdd': MetaIcon(img='line-add',
+                                label=_('Line')),
+            'rectangleAdd': MetaIcon(img='rectangle-add',
+                                     label=_('Rectangle')),
+            'overlaysAdd': MetaIcon(img='layer-more',
+                                    label=_("Add overlays")),
+            'labelsAdd': MetaIcon(img='layer-label-add',
+                                  label=_("Add labels"))
+        }
         self.icons = icons
-        
+
         return self._getToolbarData((('loadFile', icons['scriptLoad'],
-                                      self.parent.OnLoadFile),                                    
+                                      self.parent.OnLoadFile),
                                      ('instructionFile', icons['scriptSave'],
                                       self.parent.OnInstructionFile),
                                      (None, ),
@@ -135,7 +138,7 @@
                                      ('addVector', BaseIcons['addVect'],
                                       self.parent.OnAddVect),
                                      ('overlaysAdd', icons['overlaysAdd'],
-                                      self.OnAddOverlays), 
+                                      self.OnAddOverlays),
                                      ("delete", icons["deleteObj"],
                                       self.parent.OnDelete),
                                      ("dec", BaseIcons["overlay"],
@@ -159,11 +162,11 @@
     def OnDecoration(self, event):
         """Decorations overlay menu
         """
-        self._onMenu(((self.icons["addLegend"],     self.parent.OnAddLegend),
-                      (self.icons["addMapinfo"],    self.parent.OnAddMapinfo),
-                      (self.icons["addScalebar"],   self.parent.OnAddScalebar),
-                      (self.icons["addText"],       self.parent.OnAddText),
-                      (self.icons["addImage"],      self.parent.OnAddImage),
+        self._onMenu(((self.icons["addLegend"], self.parent.OnAddLegend),
+                      (self.icons["addMapinfo"], self.parent.OnAddMapinfo),
+                      (self.icons["addScalebar"], self.parent.OnAddScalebar),
+                      (self.icons["addText"], self.parent.OnAddText),
+                      (self.icons["addImage"], self.parent.OnAddImage),
                       (self.icons["addNorthArrow"], self.parent.OnAddNorthArrow)))
 
     def OnAddOverlays(self, event):
@@ -182,18 +185,22 @@
     def OnDrawGraphicsMenu(self, event):
         """Simple geometry features (point, line, rectangle) overlay menu
         """
-        self._onMenu(((self.icons["pointAdd"],      self.OnAddPoint),
-                      (self.icons["lineAdd"],       self.OnAddLine),
-                      (self.icons["rectangleAdd"],  self.OnAddRectangle),
-                    ))
+        self._onMenu(((self.icons["pointAdd"], self.OnAddPoint),
+                      (self.icons["lineAdd"], self.OnAddLine),
+                      (self.icons["rectangleAdd"], self.OnAddRectangle),
+                      ))
 
     def OnAddPoint(self, event):
         """Point mode selected.
 
         Graphics drawing tool is activated. Tooltip changed.
         """
-        self.SetToolNormalBitmap(self.drawGraphics, self.icons["pointAdd"].GetBitmap())
-        self.SetToolShortHelp(self.drawGraphics, _("Add simple graphics: points"))
+        self.SetToolNormalBitmap(
+            self.drawGraphics,
+            self.icons["pointAdd"].GetBitmap())
+        self.SetToolShortHelp(
+            self.drawGraphics,
+            _("Add simple graphics: points"))
         self.drawGraphicsAction = 'pointAdd'
         if event:
             self.ToggleTool(self.drawGraphics, True)
@@ -204,8 +211,12 @@
 
         Graphics drawing tool is activated. Tooltip changed.
         """
-        self.SetToolNormalBitmap(self.drawGraphics, self.icons["lineAdd"].GetBitmap())
-        self.SetToolShortHelp(self.drawGraphics, _("Add simple graphics: lines"))
+        self.SetToolNormalBitmap(
+            self.drawGraphics,
+            self.icons["lineAdd"].GetBitmap())
+        self.SetToolShortHelp(
+            self.drawGraphics,
+            _("Add simple graphics: lines"))
         self.ToggleTool(self.drawGraphics, True)
         if event:
             self.drawGraphicsAction = 'lineAdd'
@@ -216,8 +227,12 @@
 
         Graphics drawing tool is activated. Tooltip changed.
         """
-        self.SetToolNormalBitmap(self.drawGraphics, self.icons["rectangleAdd"].GetBitmap())
-        self.SetToolShortHelp(self.drawGraphics, _("Add simple graphics: rectangles"))
+        self.SetToolNormalBitmap(
+            self.drawGraphics,
+            self.icons["rectangleAdd"].GetBitmap())
+        self.SetToolShortHelp(
+            self.drawGraphics,
+            _("Add simple graphics: rectangles"))
         self.ToggleTool(self.drawGraphics, True)
         if event:
             self.drawGraphicsAction = 'rectangleAdd'

Modified: grass/trunk/gui/wxpython/psmap/utils.py
===================================================================
--- grass/trunk/gui/wxpython/psmap/utils.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/psmap/utils.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -27,9 +27,10 @@
     havePILImage = False
 
 import grass.script as grass
-from core.gcmd          import RunCommand
+from core.gcmd import RunCommand
 from core.utils import _
 
+
 class Rect2D(wx.Rect2D):
     """Class representing rectangle with floating point values.
 
@@ -37,12 +38,13 @@
     different (e.g. wx.Rect.GetTopLeft() x wx.Rect2D.GetLeftTop()).
     More methods can be added depending on needs.
     """
-    def __init__(self, x = 0, y = 0, width = 0, height = 0):
-        wx.Rect2D.__init__(self, x = x, y = y, w = width, h = height)
 
+    def __init__(self, x=0, y=0, width=0, height=0):
+        wx.Rect2D.__init__(self, x=x, y=y, w=width, h=height)
+
     def GetX(self):
         return self.x
-        
+
     def GetY(self):
         return self.y
 
@@ -51,21 +53,23 @@
 
     def SetWidth(self, width):
         self.width = width
-        
+
     def GetHeight(self):
         return self.height
 
     def SetHeight(self, height):
         self.height = height
 
+
 class Rect2DPP(Rect2D):
     """Rectangle specified by 2 points (with floating point values).
 
     :class:`Rect2D`, :class:`Rect2DPS`
     """
-    def __init__(self, topLeft = wx.Point2D(), bottomRight = wx.Point2D()):
-        Rect2D.__init__(self, x = 0, y = 0, width = 0, height = 0)
 
+    def __init__(self, topLeft=wx.Point2D(), bottomRight=wx.Point2D()):
+        Rect2D.__init__(self, x=0, y=0, width=0, height=0)
+
         x1, y1 = topLeft[0], topLeft[1]
         x2, y2 = bottomRight[0], bottomRight[1]
 
@@ -74,90 +78,114 @@
         self.SetRight(max(x1, x2))
         self.SetBottom(max(y1, y2))
 
+
 class Rect2DPS(Rect2D):
     """Rectangle specified by point and size (with floating point values).
 
     :class:`Rect2D`, :class:`Rect2DPP`
     """
-    def __init__(self, pos = wx.Point2D(), size = (0, 0)):
-        Rect2D.__init__(self, x = pos[0], y = pos[1], width = size[0], height = size[1])
 
+    def __init__(self, pos=wx.Point2D(), size=(0, 0)):
+        Rect2D.__init__(
+            self, x=pos[0],
+            y=pos[1],
+            width=size[0],
+            height=size[1])
+
+
 class UnitConversion:
     """ Class for converting units"""
-    def __init__(self, parent = None):
+
+    def __init__(self, parent=None):
         self.parent = parent
         if self.parent:
             ppi = wx.ClientDC(self.parent).GetPPI()
-        else: 
+        else:
             ppi = (72, 72)
-        self._unitsPage = { 'inch'          : {'val': 1.0, 'tr' : _("inch")},
-                            'point'         : {'val': 72.0, 'tr' : _("point")},
-                            'centimeter'    : {'val': 2.54, 'tr' : _("centimeter")},
-                            'millimeter'    : {'val': 25.4, 'tr' : _("millimeter")}}
-        self._unitsMap = {  'meters'        : {'val': 0.0254, 'tr' : _("meters")},
-                            'kilometers'    : {'val': 2.54e-5, 'tr' : _("kilometers")},
-                            'feet'          : {'val': 1./12, 'tr' : _("feet")},
-                            'miles'         : {'val': 1./63360, 'tr' : _("miles")},
-                            'nautical miles': {'val': 1/72913.386, 'tr' : _("nautical miles")}}
+        self._unitsPage = {'inch': {'val': 1.0, 'tr': _("inch")},
+                           'point': {'val': 72.0, 'tr': _("point")},
+                           'centimeter': {'val': 2.54, 'tr': _("centimeter")},
+                           'millimeter': {'val': 25.4, 'tr': _("millimeter")}}
+        self._unitsMap = {
+            'meters': {
+                'val': 0.0254,
+                'tr': _("meters")},
+            'kilometers': {
+                'val': 2.54e-5,
+                'tr': _("kilometers")},
+            'feet': {
+                'val': 1. / 12,
+                'tr': _("feet")},
+            'miles': {
+                'val': 1. / 63360,
+                'tr': _("miles")},
+            'nautical miles': {
+                'val': 1 / 72913.386,
+                'tr': _("nautical miles")}}
 
-        self._units = { 'pixel'     : {'val': ppi[0], 'tr' : _("pixel")},
-                        'meter'     : {'val': 0.0254, 'tr' : _("meter")},
-                        'nautmiles' : {'val': 1/72913.386, 'tr' :_("nautical miles")},
-                        'degrees'   : {'val': 0.0254 , 'tr' : _("degree")} #like 1 meter, incorrect
-                        }
+        self._units = {'pixel': {'val': ppi[0], 'tr': _("pixel")},
+                       'meter': {'val': 0.0254, 'tr': _("meter")},
+                       'nautmiles': {'val': 1 / 72913.386, 'tr': _("nautical miles")},
+                       # like 1 meter, incorrect
+                       'degrees': {'val': 0.0254, 'tr': _("degree")}
+                       }
         self._units.update(self._unitsPage)
         self._units.update(self._unitsMap)
 
     def getPageUnitsNames(self):
-        return sorted(self._unitsPage[unit]['tr'] for unit in self._unitsPage.keys())
-    
+        return sorted(self._unitsPage[unit]['tr']
+                      for unit in self._unitsPage.keys())
+
     def getMapUnitsNames(self):
-        return sorted(self._unitsMap[unit]['tr'] for unit in self._unitsMap.keys())
-    
+        return sorted(self._unitsMap[unit]['tr']
+                      for unit in self._unitsMap.keys())
+
     def getAllUnits(self):
         return sorted(self._units.keys())
-    
+
     def findUnit(self, name):
         """Returns unit by its tr. string"""
         for unit in self._units.keys():
             if self._units[unit]['tr'] == name:
                 return unit
         return None
-    
+
     def findName(self, unit):
         """Returns tr. string of a unit"""
         try:
             return self._units[unit]['tr']
         except KeyError:
             return None
-    
-    def convert(self, value, fromUnit = None, toUnit = None):
-        return float(value) / self._units[fromUnit]['val'] * self._units[toUnit]['val']
 
+    def convert(self, value, fromUnit=None, toUnit=None):
+        return float(
+            value) / self._units[fromUnit]['val'] * self._units[toUnit]['val']
+
+
 def convertRGB(rgb):
     """Converts wx.Colour(r,g,b,a) to string 'r:g:b' or named color,
             or named color/r:g:b string to wx.Colour, depending on input"""
-    # transform a wx.Colour tuple into an r:g:b string    
-    if type(rgb) == wx.Colour:
-        for name, color in grass.named_colors.items(): 
+    # transform a wx.Colour tuple into an r:g:b string
+    if isinstance(rgb, wx.Colour):
+        for name, color in grass.named_colors.items():
             if  rgb.Red() == int(color[0] * 255) and\
-                rgb.Green() == int(color[1] * 255) and\
-                rgb.Blue() == int(color[2] * 255):
+                    rgb.Green() == int(color[1] * 255) and\
+                    rgb.Blue() == int(color[2] * 255):
                 return name
         return str(rgb.Red()) + ':' + str(rgb.Green()) + ':' + str(rgb.Blue())
     # transform a GRASS named color or an r:g:b string into a wx.Colour tuple
     else:
-        color = (grass.parse_color(rgb)[0]*255,
-                 grass.parse_color(rgb)[1]*255,
-                 grass.parse_color(rgb)[2]*255)
+        color = (grass.parse_color(rgb)[0] * 255,
+                 grass.parse_color(rgb)[1] * 255,
+                 grass.parse_color(rgb)[2] * 255)
         color = wx.Colour(*color)
         if color.IsOk():
             return color
-        else:  
+        else:
             return None
-        
-        
-def PaperMapCoordinates(mapInstr, x, y, paperToMap = True):
+
+
+def PaperMapCoordinates(mapInstr, x, y, paperToMap=True):
     """Converts paper (inch) coordinates <-> map coordinates.
 
     :param mapInstr: map frame instruction
@@ -199,25 +227,25 @@
     (scale is not fixed)
     """
     currRegionDict = {}
-    if scaleType == 0 and map:# automatic, region from raster or vector
+    if scaleType == 0 and map:  # automatic, region from raster or vector
         res = ''
-        if mapType == 'raster': 
+        if mapType == 'raster':
             try:
-                res = grass.read_command("g.region", flags = 'gu', raster = map)
+                res = grass.read_command("g.region", flags='gu', raster=map)
             except grass.ScriptError:
                 pass
         elif mapType == 'vector':
-            res = grass.read_command("g.region", flags = 'gu', vector = map)
-        currRegionDict = grass.parse_key_val(res, val_type = float)
-    elif scaleType == 1 and region: # saved region
-        res = grass.read_command("g.region", flags = 'gu', region = region)
-        currRegionDict = grass.parse_key_val(res, val_type = float)
-    elif scaleType == 2: # current region
+            res = grass.read_command("g.region", flags='gu', vector=map)
+        currRegionDict = grass.parse_key_val(res, val_type=float)
+    elif scaleType == 1 and region:  # saved region
+        res = grass.read_command("g.region", flags='gu', region=region)
+        currRegionDict = grass.parse_key_val(res, val_type=float)
+    elif scaleType == 2:  # current region
         currRegionDict = grass.region()
-                                                                
+
     else:
         return None, None, None
-    
+
     if not currRegionDict:
         return None, None, None
     rX = rect.x
@@ -230,29 +258,42 @@
     if projInfo()['proj'] != 'xy':
         toM = float(projInfo()['meters'])
 
-    mW = self.unitConv.convert(value = (currRegionDict['e'] - currRegionDict['w']) * toM, fromUnit = 'meter', toUnit = 'inch')
-    mH = self.unitConv.convert(value = (currRegionDict['n'] - currRegionDict['s']) * toM, fromUnit = 'meter', toUnit = 'inch')
-    scale = min(rW/mW, rH/mH)
-    
-    if rW/rH > mW/mH:
-        x = rX - (rH*(mW/mH) - rW)/2
+    mW = self.unitConv.convert(
+        value=(
+            currRegionDict['e'] -
+            currRegionDict['w']) *
+        toM,
+        fromUnit='meter',
+        toUnit='inch')
+    mH = self.unitConv.convert(
+        value=(
+            currRegionDict['n'] -
+            currRegionDict['s']) *
+        toM,
+        fromUnit='meter',
+        toUnit='inch')
+    scale = min(rW / mW, rH / mH)
+
+    if rW / rH > mW / mH:
+        x = rX - (rH * (mW / mH) - rW) / 2
         y = rY
-        rWNew = rH*(mW/mH)
+        rWNew = rH * (mW / mH)
         rHNew = rH
     else:
         x = rX
-        y = rY - (rW*(mH/mW) - rH)/2
-        rHNew = rW*(mH/mW)
+        y = rY - (rW * (mH / mW) - rH) / 2
+        rHNew = rW * (mH / mW)
         rWNew = rW
 
     # center
-    cE = (currRegionDict['w'] + currRegionDict['e'])/2
-    cN = (currRegionDict['n'] + currRegionDict['s'])/2
-    return scale, (cE, cN), Rect2D(x, y, rWNew, rHNew) #inch
+    cE = (currRegionDict['w'] + currRegionDict['e']) / 2
+    cN = (currRegionDict['n'] + currRegionDict['s']) / 2
+    return scale, (cE, cN), Rect2D(x, y, rWNew, rHNew)  # inch
 
+
 def SetResolution(dpi, width, height):
     """If resolution is too high, lower it
-    
+
     :param dpi: max DPI
     :param width: map frame width
     :param height: map frame height
@@ -261,59 +302,68 @@
     if region['cols'] > width * dpi or region['rows'] > height * dpi:
         rows = height * dpi
         cols = width * dpi
-        RunCommand('g.region', rows = rows, cols = cols)
-               
+        RunCommand('g.region', rows=rows, cols=cols)
+
+
 def ComputeSetRegion(self, mapDict):
     """Computes and sets region from current scale, map center
     coordinates and map rectangle
     """
 
-    if mapDict['scaleType'] == 3: # fixed scale
+    if mapDict['scaleType'] == 3:  # fixed scale
         scale = mapDict['scale']
-            
+
         if not hasattr(self, 'unitConv'):
             self.unitConv = UnitConversion(self)
-        
+
         fromM = 1
         if projInfo()['proj'] != 'xy':
             fromM = float(projInfo()['meters'])
-        rectHalfInch = (mapDict['rect'].width/2, mapDict['rect'].height/2)
-        rectHalfMeter = (self.unitConv.convert(value = rectHalfInch[0], fromUnit = 'inch', toUnit = 'meter')/ fromM /scale,
-                         self.unitConv.convert(value = rectHalfInch[1], fromUnit = 'inch', toUnit = 'meter')/ fromM /scale) 
-        
+        rectHalfInch = (mapDict['rect'].width / 2, mapDict['rect'].height / 2)
+        rectHalfMeter = (
+            self.unitConv.convert(
+                value=rectHalfInch[0],
+                fromUnit='inch',
+                toUnit='meter') / fromM / scale,
+            self.unitConv.convert(
+                value=rectHalfInch[1],
+                fromUnit='inch',
+                toUnit='meter') / fromM / scale)
+
         centerE = mapDict['center'][0]
         centerN = mapDict['center'][1]
-        
+
         raster = self.instruction.FindInstructionByType('raster')
         if raster:
-            rasterId = raster.id 
+            rasterId = raster.id
         else:
             rasterId = None
 
         if rasterId:
-            RunCommand('g.region', n = ceil(centerN + rectHalfMeter[1]),
-                       s = floor(centerN - rectHalfMeter[1]),
-                       e = ceil(centerE + rectHalfMeter[0]),
-                       w = floor(centerE - rectHalfMeter[0]),
-                       rast = self.instruction[rasterId]['raster'])
+            RunCommand('g.region', n=ceil(centerN + rectHalfMeter[1]),
+                       s=floor(centerN - rectHalfMeter[1]),
+                       e=ceil(centerE + rectHalfMeter[0]),
+                       w=floor(centerE - rectHalfMeter[0]),
+                       rast=self.instruction[rasterId]['raster'])
         else:
-            RunCommand('g.region', n = ceil(centerN + rectHalfMeter[1]),
-                       s = floor(centerN - rectHalfMeter[1]),
-                       e = ceil(centerE + rectHalfMeter[0]),
-                       w = floor(centerE - rectHalfMeter[0]))
-                    
+            RunCommand('g.region', n=ceil(centerN + rectHalfMeter[1]),
+                       s=floor(centerN - rectHalfMeter[1]),
+                       e=ceil(centerE + rectHalfMeter[0]),
+                       w=floor(centerE - rectHalfMeter[0]))
+
+
 def projInfo():
     """Return region projection and map units information,
     taken from render.py
     """
-    
+
     projinfo = dict()
-    
-    ret = RunCommand('g.proj', read = True, flags = 'p')
-    
+
+    ret = RunCommand('g.proj', read=True, flags='p')
+
     if not ret:
         return projinfo
-    
+
     for line in ret.splitlines():
         if ':' in line:
             key, val = line.split(':')
@@ -322,32 +372,38 @@
             projinfo['proj'] = 'xy'
             projinfo['units'] = ''
             break
-    
+
     return projinfo
 
-def GetMapBounds(filename, portrait = True):
+
+def GetMapBounds(filename, portrait=True):
     """Run ps.map -b to get information about map bounding box
-    
+
     :param filename: psmap input file
     :param portrait: page orientation"""
     orient = ''
     if not portrait:
         orient = 'r'
     try:
-        bb = map(float, grass.read_command('ps.map',
-                                           flags = 'b' + orient,
-                                           quiet = True,
-                                           input = filename).strip().split('=')[1].split(','))
+        bb = map(
+            float,
+            grass.read_command(
+                'ps.map',
+                flags='b' +
+                orient,
+                quiet=True,
+                input=filename).strip().split('=')[1].split(','))
     except (grass.ScriptError, IndexError):
-        GError(message = _("Unable to run `ps.map -b`"))
+        GError(message=_("Unable to run `ps.map -b`"))
         return None
     return Rect2D(bb[0], bb[3], bb[2] - bb[0], bb[1] - bb[3])
 
+
 def getRasterType(map):
     """Returns type of raster map (CELL, FCELL, DCELL)"""
     if map is None:
         map = ''
-    file = grass.find_file(name = map, element = 'cell')
+    file = grass.find_file(name=map, element='cell')
     if file['file']:
         rasterType = grass.raster_info(map)['datatype']
         return rasterType
@@ -357,7 +413,7 @@
 
 def BBoxAfterRotation(w, h, angle):
     """Compute bounding box or rotated rectangle
-    
+
     :param w: rectangle width
     :param h: rectangle height
     :param angle: angle (0, 360) in degrees
@@ -365,13 +421,13 @@
     angleRad = angle / 180. * pi
     ct = cos(angleRad)
     st = sin(angleRad)
-    
+
     hct = h * ct
     wct = w * ct
     hst = h * st
     wst = w * st
     y = x = 0
-    
+
     if 0 < angle <= 90:
         y_min = y
         y_max = y + hct + wst
@@ -392,13 +448,15 @@
         y_max = y + hct
         x_min = x
         x_max = x + wct - hst
-        
+
     width = int(ceil(abs(x_max) + abs(x_min)))
     height = int(ceil(abs(y_max) + abs(y_min)))
     return width, height
 
 # hack for Windows, loading EPS works only on Unix
 # these functions are taken from EpsImagePlugin.py
+
+
 def loadPSForWindows(self):
     # Load EPS via Ghostscript
     if not self.tile:
@@ -408,13 +466,15 @@
     self.size = self.im.size
     self.tile = []
 
+
 def GhostscriptForWindows(tile, size, fp):
     """Render an image using Ghostscript (Windows only)"""
     # Unpack decoder tile
     decoder, tile, offset, data = tile[0]
     length, bbox = data
 
-    import tempfile, os
+    import tempfile
+    import os
 
     file = tempfile.mkstemp()[1]
 
@@ -424,8 +484,8 @@
                "-g%dx%d" % size,        # set output geometry (pixels)
                "-dNOPAUSE -dSAFER",     # don't pause between pages, safe mode
                "-sDEVICE=ppmraw",       # ppm driver
-               "-sOutputFile=%s" % file # output file
-              ]
+               "-sOutputFile=%s" % file  # output file
+               ]
 
     command = string.join(command)
 
@@ -448,7 +508,9 @@
         im = PILImage.core.open_ppm(file)
 
     finally:
-        try: os.unlink(file)
-        except: pass
+        try:
+            os.unlink(file)
+        except:
+            pass
 
     return im

Modified: grass/trunk/gui/wxpython/rdigit/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/rdigit/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/rdigit/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -1,4 +1,4 @@
 all = [
     'controller',
     'toolbars'
-    ]
+]

Modified: grass/trunk/gui/wxpython/rdigit/controller.py
===================================================================
--- grass/trunk/gui/wxpython/rdigit/controller.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/rdigit/controller.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -37,6 +37,7 @@
     """Controller object for raster digitizer.
     Inherits from EvtHandler to be able to send wx events from thraed.
     """
+
     def __init__(self, giface, mapWindow):
         """Constructs controller
 
@@ -55,7 +56,8 @@
         self._backgroundRaster = None
         # name of temporary raster used to backup original state
         self._backupRasterName = None
-        # if we edit an old raster or a new one (important for setting color table)
+        # if we edit an old raster or a new one (important for setting color
+        # table)
         self._editOldRaster = False
         # type of output raster map (CELL, FCELL, DCELL)
         self._mapType = None
@@ -87,8 +89,10 @@
         self.newRasterCreated = Signal('RDigitController:newRasterCreated')
         # signal to add just used cell value in toolbar combo
         self.newFeatureCreated = Signal('RDigitController:newFeatureCreated')
-        # signal to upload unique categories of background map into toolbar combo
-        self.uploadMapCategories = Signal('RDigitController:uploadMapCategories')
+        # signal to upload unique categories of background map into toolbar
+        # combo
+        self.uploadMapCategories = Signal(
+            'RDigitController:uploadMapCategories')
         self.quitDigitizer = Signal('RDigitController:quitDigitizer')
         self.showNotification = Signal('RDigitController:showNotification')
 
@@ -102,7 +106,9 @@
         self._mapWindow.mouseLeftDown.disconnect(self._start)
         self._mapWindow.mouseLeftUp.disconnect(self._addPoint)
         self._mapWindow.mouseRightUp.disconnect(self._finish)
-        self._mapWindow.Bind(wx.EVT_CONTEXT_MENU, self._mapWindow.OnContextMenu)
+        self._mapWindow.Bind(
+            wx.EVT_CONTEXT_MENU,
+            self._mapWindow.OnContextMenu)
 
     def _start(self, x, y):
         """Start digitizing a new object.
@@ -113,7 +119,8 @@
             return
 
         if not self._editedRaster:
-            GMessage(parent=self._mapWindow, message=_("Please select first the raster map"))
+            GMessage(parent=self._mapWindow, message=_(
+                "Please select first the raster map"))
             return
         if not self._drawing:
             if self._graphicsType == 'area':
@@ -219,8 +226,9 @@
             # TODO: better solution for drawing this line
             self._mapWindow.mouse['use'] = None
             self._mapWindow.mouse['box'] = "line"
-            self._mapWindow.pen = wx.Pen(colour='red', width=2, style=wx.SHORT_DASH)
-             # change the cursor
+            self._mapWindow.pen = wx.Pen(
+                colour='red', width=2, style=wx.SHORT_DASH)
+            # change the cursor
             self._mapWindow.SetNamedCursor('pencil')
 
         self._graphicsType = drawingType
@@ -251,25 +259,38 @@
         # TODO: better solution for drawing this line
         self._mapWindow.mouse['use'] = None
         self._mapWindow.mouse['box'] = "line"
-        self._mapWindow.pen = wx.Pen(colour='red', width=2, style=wx.SHORT_DASH)
+        self._mapWindow.pen = wx.Pen(
+            colour='red', width=2, style=wx.SHORT_DASH)
 
         color = self._drawColor[:3] + (self._drawTransparency,)
-        self._areas = self._mapWindow.RegisterGraphicsToDraw(graphicsType='polygon',
-                                                             pdc=self._mapWindow.pdcTransparent,
-                                                             mapCoords=True)
-        self._areas.AddPen('pen1', wx.Pen(colour=color, width=2, style=wx.SOLID))
+        self._areas = self._mapWindow.RegisterGraphicsToDraw(
+            graphicsType='polygon', pdc=self._mapWindow.pdcTransparent, mapCoords=True)
+        self._areas.AddPen(
+            'pen1',
+            wx.Pen(
+                colour=color,
+                width=2,
+                style=wx.SOLID))
         self._areas.AddBrush('done', wx.Brush(colour=color, style=wx.SOLID))
 
-        self._lines = self._mapWindow.RegisterGraphicsToDraw(graphicsType='line',
-                                                             pdc=self._mapWindow.pdcTransparent,
-                                                             mapCoords=True)
-        self._lines.AddPen('pen1', wx.Pen(colour=color, width=2, style=wx.SOLID))
+        self._lines = self._mapWindow.RegisterGraphicsToDraw(
+            graphicsType='line', pdc=self._mapWindow.pdcTransparent, mapCoords=True)
+        self._lines.AddPen(
+            'pen1',
+            wx.Pen(
+                colour=color,
+                width=2,
+                style=wx.SOLID))
         self._lines.AddBrush('done', wx.Brush(colour=color, style=wx.SOLID))
 
-        self._points = self._mapWindow.RegisterGraphicsToDraw(graphicsType='point',
-                                                              pdc=self._mapWindow.pdcTransparent,
-                                                              mapCoords=True)
-        self._points.AddPen('pen1', wx.Pen(colour=color, width=2, style=wx.SOLID))
+        self._points = self._mapWindow.RegisterGraphicsToDraw(
+            graphicsType='point', pdc=self._mapWindow.pdcTransparent, mapCoords=True)
+        self._points.AddPen(
+            'pen1',
+            wx.Pen(
+                colour=color,
+                width=2,
+                style=wx.SOLID))
         self._points.AddBrush('done', wx.Brush(colour=color, style=wx.SOLID))
 
         # change the cursor
@@ -277,8 +298,11 @@
 
     def Stop(self):
         """Before stopping digitizer, asks to save edits"""
-        dlg = wx.MessageDialog(self._mapWindow, _("Do you want to save changes?"),
-                               _("Save raster map changes"), wx.YES_NO)
+        dlg = wx.MessageDialog(
+            self._mapWindow,
+            _("Do you want to save changes?"),
+            _("Save raster map changes"),
+            wx.YES_NO)
         if dlg.ShowModal() == wx.ID_YES:
             self._thread.Run(callable=self._exportRaster,
                              ondone=lambda event: self._updateAndQuit())
@@ -294,7 +318,8 @@
         """Undo a change, goes object back (finished or not finished)"""
         if len(self._all):
             removed = self._all.pop(-1)
-            # try to remove from each, it fails quietly when theitem is not there
+            # try to remove from each, it fails quietly when theitem is not
+            # there
             self._areas.DeleteItem(removed)
             self._lines.DeleteItem(removed)
             self._points.DeleteItem(removed)
@@ -306,7 +331,12 @@
         :param restore: if restore previous cursor, mouse['use']
         """
         try:
-            gcore.run_command('g.remove', type='raster', flags='f', name=self._backupRasterName, quiet=True)
+            gcore.run_command(
+                'g.remove',
+                type='raster',
+                flags='f',
+                name=self._backupRasterName,
+                quiet=True)
         except CalledModuleError:
             pass
 
@@ -323,7 +353,8 @@
         self._mapWindow.UpdateMap(render=False)
 
         if restore:
-            # restore mouse['use'] and cursor to the state before measuring starts
+            # restore mouse['use'] and cursor to the state before measuring
+            # starts
             self._mapWindow.SetNamedCursor(self._oldCursor)
             self._mapWindow.mouse['use'] = self._oldMouseUse
 
@@ -343,7 +374,8 @@
         try:
             self._backupRaster(name)
         except ScriptError:
-            GError(parent=self._mapWindow, message=_("Failed to create backup copy of edited raster map."))
+            GError(parent=self._mapWindow, message=_(
+                "Failed to create backup copy of edited raster map."))
             return False
         self._editedRaster = name
         self._mapType = grast.raster_info(map=name)['datatype']
@@ -361,7 +393,8 @@
                                    backgroundMap=dlg.GetBackgroundMapName(),
                                    mapType=dlg.GetMapType())
             except ScriptError:
-                GError(parent=self._mapWindow, message=_("Failed to create new raster map."))
+                GError(parent=self._mapWindow, message=_(
+                    "Failed to create new raster map."))
                 return False
             finally:
                 dlg.Destroy()
@@ -380,17 +413,26 @@
         else:
             back = 'null()'
         try:
-            grast.mapcalc(exp="{name} = {mtype}({back})".format(name=name, mtype=types[mapType],
-                                                                back=back),
-                          overwrite=True, quiet=True)
+            grast.mapcalc(
+                exp="{name} = {mtype}({back})".format(
+                    name=name,
+                    mtype=types[mapType],
+                    back=back),
+                overwrite=True,
+                quiet=True)
             if background:
                 self._backgroundRaster = backgroundMap
-                gcore.run_command('r.colors', map=name, raster=self._backgroundRaster, quiet=True)
+                gcore.run_command(
+                    'r.colors',
+                    map=name,
+                    raster=self._backgroundRaster,
+                    quiet=True)
                 if mapType == 'CELL':
                     values = gcore.read_command('r.describe', flags='1n',
                                                 map=name, quiet=True).strip()
                     if values:
-                        self.uploadMapCategories.emit(values=values.split('\n'))
+                        self.uploadMapCategories.emit(
+                            values=values.split('\n'))
         except CalledModuleError:
             raise ScriptError
         self._backupRaster(name)
@@ -441,57 +483,77 @@
             rastersToPatch = []
             i = 0
             lastCellValue = lastWidthValue = None
-            evt = updateProgress(range=len(self._all), value=0, text=_("Rasterizing..."))
+            evt = updateProgress(
+                range=len(self._all),
+                value=0, text=_("Rasterizing..."))
             wx.PostEvent(self, evt)
             lastCellValue = self._all[0].GetPropertyVal('cellValue')
             lastWidthValue = self._all[0].GetPropertyVal('widthValue')
             for item in self._all:
                 if item.GetPropertyVal('widthValue') and \
                     (lastCellValue != item.GetPropertyVal('cellValue') or
-                    lastWidthValue != item.GetPropertyVal('widthValue')):
+                     lastWidthValue != item.GetPropertyVal('widthValue')):
                     if text:
-                        out = self._rasterize(text, lastWidthValue, self._mapType, tempRaster)
+                        out = self._rasterize(
+                            text, lastWidthValue, self._mapType, tempRaster)
                         rastersToPatch.append(out)
                         text = []
                     self._writeItem(item, text)
-                    out = self._rasterize(text, item.GetPropertyVal('widthValue'),
-                                          self._mapType, tempRaster)
+                    out = self._rasterize(
+                        text, item.GetPropertyVal('widthValue'),
+                        self._mapType, tempRaster)
                     rastersToPatch.append(out)
                     text = []
                 else:
                     self._writeItem(item, text)
-    
+
                 lastCellValue = item.GetPropertyVal('cellValue')
                 lastWidthValue = item.GetPropertyVal('widthValue')
-    
+
                 i += 1
-                evt = updateProgress(range=len(self._all), value=i, text=_("Rasterizing..."))
+                evt = updateProgress(
+                    range=len(self._all),
+                    value=i, text=_("Rasterizing..."))
                 wx.PostEvent(self, evt)
             if text:
                 out = self._rasterize(text, item.GetPropertyVal('widthValue'),
                                       self._mapType, tempRaster)
                 rastersToPatch.append(out)
-    
-            gcore.run_command('r.patch', input=rastersToPatch[::-1] + [self._backupRasterName],
-                              output=self._editedRaster, overwrite=True, quiet=True)
-            gcore.run_command('g.remove', type='raster', flags='f', name=rastersToPatch + [tempRaster],
-                          quiet=True)
+
+            gcore.run_command(
+                'r.patch', input=rastersToPatch[:: -1] +
+                [self._backupRasterName],
+                output=self._editedRaster, overwrite=True, quiet=True)
+            gcore.run_command(
+                'g.remove',
+                type='raster',
+                flags='f',
+                name=rastersToPatch +
+                [tempRaster],
+                quiet=True)
         try:
             # setting the right color table
             if self._editOldRaster:
                 return
             if not self._backgroundRaster:
-                table = UserSettings.Get(group='rasterLayer', key='colorTable', subkey='selection')
+                table = UserSettings.Get(
+                    group='rasterLayer',
+                    key='colorTable',
+                    subkey='selection')
                 if not table:
                     table = 'rainbow'
-                gcore.run_command('r.colors', color=table, map=self._editedRaster, quiet=True)
+                gcore.run_command(
+                    'r.colors',
+                    color=table,
+                    map=self._editedRaster,
+                    quiet=True)
             else:
                 gcore.run_command('r.colors', map=self._editedRaster,
                                   raster=self._backgroundRaster, quiet=True)
         except CalledModuleError:
             self._running = False
-            GError(parent=self._mapWindow,
-                   message=_("Failed to set default color table for edited raster map"))
+            GError(parent=self._mapWindow, message=_(
+                "Failed to set default color table for edited raster map"))
 
     def _writeFeature(self, item, vtype, text):
         """Writes digitized features in r.in.poly format."""
@@ -533,8 +595,13 @@
 
         if bufferDist:
             bufferDist /= 2.
-            gcore.run_command('r.in.poly', input=asciiFile.name, output=tempRaster,
-                              type_=mapType, overwrite=True, quiet=True)
+            gcore.run_command(
+                'r.in.poly',
+                input=asciiFile.name,
+                output=tempRaster,
+                type_=mapType,
+                overwrite=True,
+                quiet=True)
             gcore.run_command('r.grow', input=tempRaster, output=output,
                               flags='m', radius=bufferDist, quiet=True)
         else:

Modified: grass/trunk/gui/wxpython/rdigit/dialogs.py
===================================================================
--- grass/trunk/gui/wxpython/rdigit/dialogs.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/rdigit/dialogs.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -28,6 +28,7 @@
 class NewRasterDialog(wx.Dialog):
     """Dialog for new raster map name and type selection
     and selection of optional background map."""
+
     def __init__(self, parent):
         wx.Dialog.__init__(self, parent)
         self.SetTitle(_("Create new raster map"))
@@ -52,8 +53,11 @@
         sizer.Add(wx.StaticText(self, label=_("Name for new raster map:")),
                   pos=(0, 0), span=(1, 2), flag=wx.ALIGN_CENTER_VERTICAL)
         sizer.Add(self._mapSelect, pos=(1, 0), span=(1, 2))
-        sizer.Add(wx.StaticText(self, label=_("Optionally select background raster map:")),
-                  pos=(2, 0), span=(1, 2), flag=wx.ALIGN_CENTER_VERTICAL)
+        sizer.Add(
+            wx.StaticText(
+                self, label=_("Optionally select background raster map:")), pos=(
+                2, 0), span=(
+                1, 2), flag=wx.ALIGN_CENTER_VERTICAL)
         sizer.Add(self._backgroundSelect, pos=(3, 0), span=(1, 2))
         sizer.Add(wx.StaticText(self, label=_("New raster map type:")),
                   pos=(4, 0), flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
@@ -84,15 +88,21 @@
     def OnOK(self, event):
         mapName = self.GetMapName()
         if not mapName:
-            GWarning(parent=self.GetParent(), message=_("Please specify name for a new raster map"))
+            GWarning(parent=self.GetParent(), message=_(
+                "Please specify name for a new raster map"))
         else:
-            found = gcore.find_file(name=mapName, mapset=gcore.gisenv()['MAPSET'])
+            found = gcore.find_file(
+                name=mapName, mapset=gcore.gisenv()['MAPSET'])
             if found and found['mapset'] == gcore.gisenv()['MAPSET']:
                 dlgOverwrite = wx.MessageDialog(
-                    self.GetParent(), message=_("Raster map <%s> already exists "
-                                                "in the current mapset. "
-                                                "Do you want to overwrite it?") % mapName,
-                    caption=_("Overwrite?"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+                    self.GetParent(),
+                    message=_(
+                        "Raster map <%s> already exists "
+                        "in the current mapset. "
+                        "Do you want to overwrite it?") %
+                    mapName,
+                    caption=_("Overwrite?"),
+                    style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
                 if not dlgOverwrite.ShowModal() == wx.ID_YES:
                     dlgOverwrite.Destroy()
                     return

Modified: grass/trunk/gui/wxpython/rdigit/toolbars.py
===================================================================
--- grass/trunk/gui/wxpython/rdigit/toolbars.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/rdigit/toolbars.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -37,6 +37,7 @@
 class RDigitToolbar(BaseToolbar):
     """RDigit toolbar
     """
+
     def __init__(self, parent, controller, toolSwitcher):
         """RDigit toolbar constructor
         """
@@ -45,9 +46,10 @@
         self.InitToolbar(self._toolbarData())
 
         self._mapSelectionComboId = wx.NewId()
-        self._mapSelectionCombo = wx.ComboBox(self, id=self._mapSelectionComboId,
-                                              value=_("Select raster map"),
-                                              choices=[], size=(120, -1))
+        self._mapSelectionCombo = wx.ComboBox(
+            self, id=self._mapSelectionComboId, value=_("Select raster map"),
+            choices=[],
+            size=(120, -1))
         self._mapSelectionCombo.Bind(wx.EVT_COMBOBOX, self.OnMapSelection)
         self._mapSelectionCombo.SetEditable(False)
         self.InsertControl(0, self._mapSelectionCombo)
@@ -56,28 +58,42 @@
         self._colorId = wx.NewId()
         self._color = csel.ColourSelect(parent=self, colour=wx.GREEN,
                                         size=(30, 30))
-        self._color.Bind(csel.EVT_COLOURSELECT, lambda evt: self._changeDrawColor())
-        self._color.SetToolTipString(_("Set drawing color (not raster cell color)"))
+        self._color.Bind(
+            csel.EVT_COLOURSELECT,
+            lambda evt: self._changeDrawColor())
+        self._color.SetToolTipString(
+            _("Set drawing color (not raster cell color)"))
         self.InsertControl(4, self._color)
 
         self._cellValues = set(['1'])
         self._valueComboId = wx.NewId()
-        # validator does not work with combobox, SetBackgroundColor is not working
-        self._valueCombo = wx.ComboBox(self, id=self._valueComboId,
-                                       choices=list(self._cellValues), size=(80, -1),
-                                       validator=FloatValidator())
-        self._valueCombo.Bind(wx.EVT_COMBOBOX, lambda evt: self._cellValueChanged())
-        self._valueCombo.Bind(wx.EVT_TEXT, lambda evt: self._cellValueChanged())
+        # validator does not work with combobox, SetBackgroundColor is not
+        # working
+        self._valueCombo = wx.ComboBox(
+            self, id=self._valueComboId, choices=list(
+                self._cellValues), size=(
+                80, -1), validator=FloatValidator())
+        self._valueCombo.Bind(
+            wx.EVT_COMBOBOX,
+            lambda evt: self._cellValueChanged())
+        self._valueCombo.Bind(wx.EVT_TEXT,
+                              lambda evt: self._cellValueChanged())
         self._valueCombo.SetSelection(0)
         self._cellValueChanged()
-        self.InsertControl(6, wx.StaticText(self, label=" %s" % _("Cell value:")))
+        self.InsertControl(
+            6, wx.StaticText(
+                self, label=" %s" %
+                _("Cell value:")))
         self.InsertControl(7, self._valueCombo)
 
         self._widthValueId = wx.NewId()
-        # validator does not work with combobox, SetBackgroundColor is not working
-        self._widthValue = wx.TextCtrl(self, id=self._widthValueId, value='0',
-                                       size=(80, -1), validator=FloatValidator())
-        self._widthValue.Bind(wx.EVT_TEXT, lambda evt: self._widthValueChanged())
+        # validator does not work with combobox, SetBackgroundColor is not
+        # working
+        self._widthValue = wx.TextCtrl(
+            self, id=self._widthValueId, value='0', size=(
+                80, -1), validator=FloatValidator())
+        self._widthValue.Bind(wx.EVT_TEXT,
+                              lambda evt: self._widthValueChanged())
         self._widthValueChanged()
         self._widthValue.SetToolTipString(
             _("Width of currently digitized line or diameter of a digitized point in map units."))
@@ -85,7 +101,8 @@
         self.InsertControl(9, self._widthValue)
 
         for tool in (self.area, self.line, self.point):
-            self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=tool)
+            self.toolSwitcher.AddToolToGroup(
+                group='mouseUse', toolbar=self, tool=tool)
         self.toolSwitcher.toggleToolChanged.connect(self.CheckSelectedTool)
         self._default = self.area
         # realize the toolbar
@@ -93,23 +110,24 @@
 
     def _toolbarData(self):
         """Toolbar data"""
-        return self._getToolbarData((('area', rdigitIcons['area'],
-                                      lambda event: self._controller.SelectType('area'),
-                                      wx.ITEM_CHECK),
-                                     ('line', rdigitIcons['line'],
-                                      lambda event: self._controller.SelectType('line'),
-                                      wx.ITEM_CHECK),
-                                     ('point', rdigitIcons['point'],
-                                      lambda event: self._controller.SelectType('point'),
-                                      wx.ITEM_CHECK),
-                                     (None, ),
-                                     (None, ),
-                                     ('undo', rdigitIcons['undo'],
-                                      lambda event: self._controller.Undo()),
-                                     ('save', rdigitIcons['save'],
-                                      lambda event: self._controller.Save()),
-                                     ('quit', rdigitIcons['quit'],
-                                      lambda event: self._controller.Stop())))
+        return self._getToolbarData(
+            (('area', rdigitIcons['area'],
+              lambda event: self._controller.SelectType('area'),
+              wx.ITEM_CHECK),
+             ('line', rdigitIcons['line'],
+              lambda event: self._controller.SelectType('line'),
+              wx.ITEM_CHECK),
+             ('point', rdigitIcons['point'],
+              lambda event: self._controller.SelectType('point'),
+              wx.ITEM_CHECK),
+             (None,),
+             (None,),
+             ('undo', rdigitIcons['undo'],
+              lambda event: self._controller.Undo()),
+             ('save', rdigitIcons['save'],
+              lambda event: self._controller.Save()),
+             ('quit', rdigitIcons['quit'],
+              lambda event: self._controller.Stop())))
 
     def CheckSelectedTool(self, id):
         if self.toolSwitcher.IsToolInGroup(tool=id, group='mouseUse') \
@@ -128,7 +146,8 @@
         if idx == 0:
             ret = self._controller.SelectNewMap()
         else:
-            ret = self._controller.SelectOldMap(self._mapSelectionCombo.GetString(idx))
+            ret = self._controller.SelectOldMap(
+                self._mapSelectionCombo.GetString(idx))
         if not ret:
             # in wxpython 3 we can't set value which is not in the items
             # when not editable

Modified: grass/trunk/gui/wxpython/rlisetup/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/rlisetup/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/rlisetup/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -4,4 +4,4 @@
     'functions',
     'frame',
     'sampling_frame'
-    ]
+]

Modified: grass/trunk/gui/wxpython/rlisetup/frame.py
===================================================================
--- grass/trunk/gui/wxpython/rlisetup/frame.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/rlisetup/frame.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -18,10 +18,11 @@
 
 
 class ViewFrame(wx.Frame):
+
     def __init__(self, parent, conf, giface=None, id=wx.ID_ANY,
                  title=_("Modify the configuration file"),
                  style=wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER, **kwargs):
-        ###VARIABLES
+        # VARIABLES
         self.parent = parent
         self.rlipath = retRLiPath()
         self.confile = conf
@@ -31,16 +32,18 @@
         self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'),
                              wx.BITMAP_TYPE_ICO))
         self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
-        self.confilesBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
-                                        label=_("View and modify the " \
-                                        "configuration file '{name}'".format(name=self.confile)))
+        self.confilesBox = wx.StaticBox(
+            parent=self.panel, id=wx.ID_ANY, label=_(
+                "View and modify the "
+                "configuration file '{name}'".format(
+                    name=self.confile)))
         self.textCtrl = wx.TextCtrl(parent=self.panel, id=wx.ID_ANY,
                                     style=wx.TE_MULTILINE, size=(-1, 75))
         self.textCtrl.Bind(wx.EVT_TEXT, self.OnFileText)
         f = open(self.pathfile)
         self.textCtrl.SetValue(''.join(f.readlines()))
         f.close()
-        ###BUTTONS      #definition
+        # BUTTONS      #definition
         self.btn_close = wx.Button(parent=self, id=wx.ID_EXIT)
         self.btn_ok = wx.Button(parent=self, id=wx.ID_SAVE)
         self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
@@ -52,19 +55,19 @@
         """Set the layout"""
         panelsizer = wx.GridBagSizer(1, 1)
         mainsizer = wx.BoxSizer(wx.VERTICAL)
-        ###CONFILES
+        # CONFILES
         confilesSizer = wx.StaticBoxSizer(self.confilesBox, wx.HORIZONTAL)
         confilesSizer.Add(item=self.textCtrl, proportion=1, flag=wx.EXPAND)
-        ###END CONFILES
-        ###BUTTONS
+        # END CONFILES
+        # BUTTONS
         buttonSizer = wx.BoxSizer(wx.HORIZONTAL)
         buttonSizer.Add(item=self.btn_ok, flag=wx.ALL, border=5)
         buttonSizer.Add(item=self.btn_close, flag=wx.ALL, border=5)
-        ###END BUTTONS
-        #add listbox to staticbox
+        # END BUTTONS
+        # add listbox to staticbox
         panelsizer.Add(item=confilesSizer, pos=(0, 0), flag=wx.EXPAND,
                        border=3)
-        #add panel and buttons
+        # add panel and buttons
         mainsizer.Add(item=self.panel, proportion=1, flag=wx.EXPAND, border=3)
         mainsizer.Add(item=buttonSizer, proportion=0, flag=wx.EXPAND, border=3)
         panelsizer.AddGrowableRow(0)
@@ -80,13 +83,16 @@
 
     def OnOk(self, event):
         """Launches help"""
-        dlg = wx.MessageDialog(parent=self.parent,
-                                message=_("Are you sure that you want modify" \
-                                          " r.li configuration file {name}?" \
-                                          "\nYou could broke the configuration" \
-                                          " file...").format(name=self.confile),
-                                caption=_("WARNING"),
-                                style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_WARNING)
+        dlg = wx.MessageDialog(
+            parent=self.parent,
+            message=_(
+                "Are you sure that you want modify"
+                " r.li configuration file {name}?"
+                "\nYou could broke the configuration"
+                " file...").format(
+                name=self.confile),
+            caption=_("WARNING"),
+            style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_WARNING)
 
         if dlg.ShowModal() == wx.ID_YES:
             f = codecs.open(self.pathfile, encoding=self.enc, mode='w',
@@ -102,28 +108,32 @@
 
 
 class RLiSetupFrame(wx.Frame):
-    def __init__(self, parent, giface=None, id=wx.ID_ANY, title=_("GRASS" \
-                 " GIS Setup for r.li modules"),
-                 style=wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER, **kwargs):
-        ###VARIABLES
+
+    def __init__(
+            self, parent, giface=None, id=wx.ID_ANY,
+            title=_("GRASS"
+                    " GIS Setup for r.li modules"),
+            style=wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER, **kwargs):
+        # VARIABLES
         self.parent = parent
 #        self.cmd = "r.li.setup"
         self.rlipath = retRLiPath()
         self.listfiles = self.ListFiles()
-        ###END VARIABLES
-        #init of frame
+        # END VARIABLES
+        # init of frame
         wx.Frame.__init__(self, parent=parent, id=id, title=title,
                           **kwargs)
         self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'),
                              wx.BITMAP_TYPE_ICO))
         self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
-        #box for select configuration file
-        self.confilesBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
-                                        label=_('Available sampling area configuration files'))
-        self.listfileBox = wx.ListBox(parent=self.panel,  id=wx.ID_ANY,
-                    choices=self.listfiles)
+        # box for select configuration file
+        self.confilesBox = wx.StaticBox(
+            parent=self.panel, id=wx.ID_ANY,
+            label=_('Available sampling area configuration files'))
+        self.listfileBox = wx.ListBox(parent=self.panel, id=wx.ID_ANY,
+                                      choices=self.listfiles)
 
-        ###BUTTONS      #definition
+        # BUTTONS      #definition
         self.btn_close = wx.Button(parent=self, id=wx.ID_CLOSE)
         self.btn_help = wx.Button(parent=self, id=wx.ID_HELP)
         self.btn_remove = wx.Button(parent=self, id=wx.ID_ANY,
@@ -136,9 +146,9 @@
                                     label=_("Rename"))
         self.btn_rename.SetToolTipString(_('Rename a configuration file'))
         self.btn_view = wx.Button(parent=self, id=wx.ID_ANY,
-                                    label=_("View/Edit"))
+                                  label=_("View/Edit"))
         self.btn_view.SetToolTipString(_('View and edit a configuration file'))
-        #set action for button
+        # set action for button
         self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
         self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
         self.btn_remove.Bind(wx.EVT_BUTTON, self.OnRemove)
@@ -146,23 +156,23 @@
         self.btn_rename.Bind(wx.EVT_BUTTON, self.OnRename)
         self.btn_view.Bind(wx.EVT_BUTTON, self.OnView)
         self._layout()
-        ###END BUTTONS
-        ###SIZE FRAME
+        # END BUTTONS
+        # SIZE FRAME
         self.SetMinSize(self.GetBestSize())
-        ##Please check this because without this the size it is not the min
+        # Please check this because without this the size it is not the min
         self.SetClientSize(self.GetBestSize())
-        ###END SIZE
+        # END SIZE
 
     def _layout(self):
         """Set the layout"""
         panelsizer = wx.GridBagSizer(1, 1)
         mainsizer = wx.BoxSizer(wx.VERTICAL)
-        ###CONFILES
+        # CONFILES
         confilesSizer = wx.StaticBoxSizer(self.confilesBox, wx.HORIZONTAL)
         confilesSizer.Add(item=self.listfileBox, proportion=1,
-                         flag=wx.EXPAND)
-        ###END CONFILES
-        ###BUTTONS
+                          flag=wx.EXPAND)
+        # END CONFILES
+        # BUTTONS
         buttonSizer = wx.BoxSizer(wx.HORIZONTAL)
         buttonSizer.Add(item=self.btn_new, flag=wx.ALL, border=5)
         buttonSizer.Add(item=self.btn_rename, flag=wx.ALL, border=5)
@@ -170,12 +180,12 @@
         buttonSizer.Add(item=self.btn_remove, flag=wx.ALL, border=5)
         buttonSizer.Add(item=self.btn_help, flag=wx.ALL, border=5)
         buttonSizer.Add(item=self.btn_close, flag=wx.ALL, border=5)
-        ###END BUTTONS
-        #add listbox to staticbox
+        # END BUTTONS
+        # add listbox to staticbox
         panelsizer.Add(item=confilesSizer, pos=(0, 0), flag=wx.EXPAND,
                        border=3)
 
-        #add panel and buttons
+        # add panel and buttons
         mainsizer.Add(item=self.panel, proportion=1, flag=wx.EXPAND, border=3)
         mainsizer.Add(item=buttonSizer, proportion=0, flag=wx.EXPAND, border=3)
 
@@ -191,8 +201,8 @@
         """Check the configuration files inside the path"""
         # list of configuration file
         listfiles = []
-        #return all the configuration files in self.rlipath, check if there are
-        #link or directory and doesn't add them
+        # return all the configuration files in self.rlipath, check if there are
+        # link or directory and doesn't add them
         for l in os.listdir(self.rlipath):
             if os.path.isfile(os.path.join(self.rlipath, l)):
                 listfiles.append(l)
@@ -209,11 +219,14 @@
     def OnRemove(self, event):
         """Remove configuration file from path and update the list"""
         confile = self.listfiles[self.listfileBox.GetSelections()[0]]
-        dlg = wx.MessageDialog(parent=self.parent,
-                                message=_("Do you want remove r.li " \
-                                          "configuration file <%s>?") % confile,
-                                caption=_("Remove new r.li configuration file?"),
-                                style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+        dlg = wx.MessageDialog(
+            parent=self.parent,
+            message=_(
+                "Do you want remove r.li "
+                "configuration file <%s>?") %
+            confile,
+            caption=_("Remove new r.li configuration file?"),
+            style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
 
         if dlg.ShowModal() == wx.ID_YES:
             self.listfileBox.Delete(self.listfileBox.GetSelections()[0])

Modified: grass/trunk/gui/wxpython/rlisetup/functions.py
===================================================================
--- grass/trunk/gui/wxpython/rlisetup/functions.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/rlisetup/functions.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -122,7 +122,7 @@
     """Create the strings to add to the configuration file using vector"""
     areanum = len(vect_cats)
     output = []
-    #TODO if areanum == 0 exit from the program
+    # TODO if areanum == 0 exit from the program
     if areanum == 0:
         GError(message=_("The polygon seems to have 0 areas"))
         return None
@@ -133,8 +133,8 @@
         rast_name = "{pref}{cat}".format(pref=outpref, cat=cat)
         # check if raster already axist
 
-        if len(grass.list_strings('raster', pattern=rast_name, mapset='.')) == 1 \
-           and not overwrite:
+        if len(grass.list_strings('raster', pattern=rast_name,
+                                  mapset='.')) == 1 and not overwrite:
             GError(message=_("The raster map <%s> already exists."
                              " Please remove or rename the maps "
                              "with the prefix '%s' or select the "

Modified: grass/trunk/gui/wxpython/rlisetup/g.gui.rlisetup.py
===================================================================
--- grass/trunk/gui/wxpython/rlisetup/g.gui.rlisetup.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/rlisetup/g.gui.rlisetup.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -36,7 +36,7 @@
 
     from grass.script.setup import set_gui_path
     set_gui_path()
-    
+
     from core.giface import StandaloneGrassInterface
     from core.globalvar import CheckWxVersion
     from rlisetup.frame import RLiSetupFrame

Modified: grass/trunk/gui/wxpython/rlisetup/sampling_frame.py
===================================================================
--- grass/trunk/gui/wxpython/rlisetup/sampling_frame.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/rlisetup/sampling_frame.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -23,14 +23,14 @@
 import wx.aui
 
 
-#start new import
+# start new import
 import tempfile
 from core.gcmd import RunCommand
 import grass.script.core as grass
 from core import gcmd
 
 try:
-    from grass.lib.gis    import *
+    from grass.lib.gis import *
     from grass.lib.vector import *
     from grass.lib.raster import *
 except ImportError:
@@ -51,12 +51,14 @@
 
 
 class Circle:
+
     def __init__(self, pt, r):
         self.point = pt
         self.radius = r
 
 
 class MaskedArea(object):
+
     def __init__(self, region, raster, radius):
         self.region = region
         self.raster = raster
@@ -65,6 +67,7 @@
 
 class RLiSetupMapPanel(wx.Panel):
     """Panel with mapwindow used in r.li.setup"""
+
     def __init__(self, parent, samplingType, icon=None, map_=None):
         wx.Panel.__init__(self, parent=parent)
 
@@ -104,16 +107,22 @@
 
         if self.samplingtype == SamplingType.REGIONS:
             self.afterRegionDrawn = Signal('RLiSetupMapPanel.afterRegionDrawn')
-            self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(graphicsType='line')
+            self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(
+                graphicsType='line')
         elif self.samplingtype in [SamplingType.MUNITSR, SamplingType.MMVWINR]:
-            self.sampleFrameChanged = Signal('RLiSetupMapPanel.sampleFrameChanged')
-            self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(graphicsType='rectangle')
+            self.sampleFrameChanged = Signal(
+                'RLiSetupMapPanel.sampleFrameChanged')
+            self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(
+                graphicsType='rectangle')
         elif self.samplingtype in [SamplingType.MUNITSC, SamplingType.MMVWINC]:
             self.afterCircleDrawn = Signal('RLiSetupMapPanel.afterCircleDrawn')
-            self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(graphicsType='line')
+            self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(
+                graphicsType='line')
         else:
-            self.sampleFrameChanged = Signal('RLiSetupMapPanel.sampleFrameChanged')
-            self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(graphicsType='rectangle')
+            self.sampleFrameChanged = Signal(
+                'RLiSetupMapPanel.sampleFrameChanged')
+            self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(
+                graphicsType='rectangle')
 
         self._registeredGraphics.AddPen('rlisetup', wx.Pen(wx.GREEN, width=2,
                                                            style=wx.SOLID))
@@ -176,7 +185,8 @@
         item = self._registeredGraphics.GetItem(0)
         coords = item.GetCoords()
         if len(coords) == 0:
-            coords.extend([self.mapWindow.Pixel2Cell(self.mapWindow.mouse['begin'])])
+            coords.extend([self.mapWindow.Pixel2Cell(
+                self.mapWindow.mouse['begin'])])
         coords.extend([[x, y]])
 
         item.SetCoords(coords)
@@ -202,12 +212,16 @@
             if ret == wx.ID_OK:
                 raster = dlg.GetValue()
                 if checkMapExists(raster):
-                    GMessage(parent=self, message=_("The raster file %s already"
-                             " exists, please change name") % raster)
+                    GMessage(
+                        parent=self, message=_(
+                            "The raster file %s already"
+                            " exists, please change name") %
+                        raster)
                     ret = dlg.ShowModal()
                 else:
                     dlg.Destroy()
-                    marea = self.writeArea(self._registeredGraphics.GetItem(0).GetCoords(), raster)
+                    marea = self.writeArea(
+                        self._registeredGraphics.GetItem(0).GetCoords(), raster)
                     self.nextRegion(next=True, area=marea)
                     break
             else:
@@ -225,8 +239,8 @@
         if next is True:
             self.afterRegionDrawn.emit(marea=area)
         else:
-            gcmd.GMessage(parent=self.parent,
-                          message=_("Raster map not created. Please redraw region."))
+            gcmd.GMessage(parent=self.parent, message=_(
+                "Raster map not created. Please redraw region."))
 
     def writeArea(self, coords, rasterName):
         polyfile = tempfile.NamedTemporaryFile(delete=False)
@@ -298,15 +312,20 @@
         self.createCricle(circle)
 
     def createCricle(self, c):
-        dlg = wx.TextEntryDialog(None, 'Name of sample circle region',
-                                 'Create circle region', 'circle' + str(self.catId))
+        dlg = wx.TextEntryDialog(None,
+                                 'Name of sample circle region',
+                                 'Create circle region',
+                                 'circle' + str(self.catId))
         ret = dlg.ShowModal()
-        while True:        
+        while True:
             if ret == wx.ID_OK:
                 raster = dlg.GetValue()
                 if checkMapExists(raster):
-                    GMessage(parent=self, message=_("The raster file %s already"
-                             " exists, please change name") % raster)
+                    GMessage(
+                        parent=self, message=_(
+                            "The raster file %s already"
+                            " exists, please change name") %
+                        raster)
                     ret = dlg.ShowModal()
                 else:
                     dlg.Destroy()
@@ -326,8 +345,8 @@
         if next is True:
             self.afterCircleDrawn.emit(region=circle)
         else:
-            gcmd.GMessage(parent=self.parent,
-                          message=_("Raster map not created. redraw region again."))
+            gcmd.GMessage(parent=self.parent, message=_(
+                "Raster map not created. redraw region again."))
 
     def writeCircle(self, circle, rasterName):
         coords = self.mapWindow.Pixel2Cell(circle.point)
@@ -378,23 +397,29 @@
             """When drawing finished, get region values"""
             self.sampleFrameChanged.emit(region=region)
 
-icons = {'draw': MetaIcon(img='edit',
-                          label=_('Draw sampling frame'),
-                          desc=_('Draw sampling frame by clicking and dragging')),
-         'digitizeunit': MetaIcon(img='edit',
-                          label=_('Draw sampling rectangle'),
-                          desc=_('Draw sampling rectangle by clicking and dragging')),
-         'digitizeunitc': MetaIcon(img='line-create',
-                          label=_('Draw sampling circle'),
-                          desc=_('Draw sampling circle radius by clicking and dragging')),
-         'digitizeregion': MetaIcon(img='polygon-create',
-                          label=_('Draw sampling region'),
-                          desc=_('Draw sampling region by polygon. Right Double click to end drawing'))}
+icons = {
+    'draw': MetaIcon(
+        img='edit',
+        label=_('Draw sampling frame'),
+        desc=_('Draw sampling frame by clicking and dragging')),
+    'digitizeunit': MetaIcon(
+        img='edit',
+        label=_('Draw sampling rectangle'),
+        desc=_('Draw sampling rectangle by clicking and dragging')),
+    'digitizeunitc': MetaIcon(
+        img='line-create',
+        label=_('Draw sampling circle'),
+        desc=_('Draw sampling circle radius by clicking and dragging')),
+    'digitizeregion': MetaIcon(
+        img='polygon-create',
+        label=_('Draw sampling region'),
+        desc=_('Draw sampling region by polygon. Right Double click to end drawing'))}
 
 
 class RLiSetupToolbar(BaseToolbar):
     """IClass toolbar
     """
+
     def __init__(self, parent, toolSwitcher):
         """RLiSetup toolbar constructor
         """
@@ -443,21 +468,22 @@
                         wx.ITEM_CHECK)
         if self.parent.samplingtype == SamplingType.VECT:
             return self._getToolbarData((
-                       ('pan', BaseIcons['pan'], self.parent.OnPan,
-                        wx.ITEM_CHECK),
-                       ('zoomIn', BaseIcons['zoomIn'], self.parent.OnZoomIn,
-                        wx.ITEM_CHECK),
-                       ('zoomOut', BaseIcons['zoomOut'], self.parent.OnZoomOut,
-                        wx.ITEM_CHECK),
-                       ('zoomExtent', BaseIcons['zoomExtent'],
-                        self.parent.OnZoomToMap),))
+                ('pan', BaseIcons['pan'], self.parent.OnPan,
+                 wx.ITEM_CHECK),
+                ('zoomIn', BaseIcons['zoomIn'], self.parent.OnZoomIn,
+                 wx.ITEM_CHECK),
+                ('zoomOut', BaseIcons['zoomOut'], self.parent.OnZoomOut,
+                 wx.ITEM_CHECK),
+                ('zoomExtent', BaseIcons['zoomExtent'],
+                 self.parent.OnZoomToMap),))
         else:
-            return self._getToolbarData((drawTool, (None, ),
-                       ('pan', BaseIcons['pan'], self.parent.OnPan,
-                        wx.ITEM_CHECK),
-                       ('zoomIn', BaseIcons['zoomIn'], self.parent.OnZoomIn,
-                        wx.ITEM_CHECK),
-                       ('zoomOut', BaseIcons['zoomOut'], self.parent.OnZoomOut,
-                        wx.ITEM_CHECK),
-                       ('zoomExtent', BaseIcons['zoomExtent'],
-                        self.parent.OnZoomToMap),))
+            return self._getToolbarData(
+                (drawTool, (None,),
+                 ('pan', BaseIcons['pan'],
+                  self.parent.OnPan, wx.ITEM_CHECK),
+                 ('zoomIn', BaseIcons['zoomIn'],
+                  self.parent.OnZoomIn, wx.ITEM_CHECK),
+                 ('zoomOut', BaseIcons['zoomOut'],
+                  self.parent.OnZoomOut, wx.ITEM_CHECK),
+                 ('zoomExtent', BaseIcons['zoomExtent'],
+                  self.parent.OnZoomToMap),))

Modified: grass/trunk/gui/wxpython/rlisetup/wizard.py
===================================================================
--- grass/trunk/gui/wxpython/rlisetup/wizard.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/rlisetup/wizard.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -112,11 +112,14 @@
         self.wizard.FitToPage(self.startpage)
         # run_wizard
         if self.wizard.RunWizard(self.startpage):
-            dlg = wx.MessageDialog(parent=self.parent,
-                                message=_("Do you want to create r.li "
-                                          "configuration file <%s>?") % self.startpage.conf_name,
-                                caption=_("Create new r.li configuration file?"),
-                                style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+            dlg = wx.MessageDialog(
+                parent=self.parent,
+                message=_(
+                    "Do you want to create r.li "
+                    "configuration file <%s>?") %
+                self.startpage.conf_name,
+                caption=_("Create new r.li configuration file?"),
+                style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
 
             if dlg.ShowModal() == wx.ID_NO:
                 self._cleanup()
@@ -175,9 +178,11 @@
             self.SF_RL = float(self.keyboardpage.row_len)
             self.SF_CL = float(self.keyboardpage.col_len)
             self.SF_N = self.gregion['n'] - (self.SF_NSRES * self.SF_Y)
-            self.SF_S = self.gregion['n'] - (self.SF_NSRES * self.SF_Y + self.SF_RL)
+            self.SF_S = self.gregion[
+                'n'] - (self.SF_NSRES * self.SF_Y + self.SF_RL)
             self.SF_W = self.gregion['w'] + (self.SF_EWRES * self.SF_X)
-            self.SF_E = self.gregion['w'] + (self.SF_EWRES * self.SF_X + self.SF_CL)
+            self.SF_E = self.gregion[
+                'w'] + (self.SF_EWRES * self.SF_X + self.SF_CL)
             self.per_x = float(self.SF_X) / float(self.rasterinfo['cols'])
             self.per_y = float(self.SF_Y) / float(self.rasterinfo['rows'])
             self.per_rl = float(self.SF_RL) / float(self.rasterinfo['rows'])
@@ -197,13 +202,29 @@
             self.SF_E = newreg['e']  # set env(SF_E) $e
             self.SF_W = newreg['w']  # set env(SF_W) $w
 
-            self.SF_Y = abs(round(self.gregion['n'] - newreg['n']) / newreg['nsres'])
+            self.SF_Y = abs(
+                round(
+                    self.gregion['n'] -
+                    newreg['n']) /
+                newreg['nsres'])
 #         set env(SF_Y) [expr abs(round(($s_n - $n) / $nres)) ]
-            self.SF_X = abs(round(self.gregion['w'] - newreg['w']) / newreg['ewres'])
+            self.SF_X = abs(
+                round(
+                    self.gregion['w'] -
+                    newreg['w']) /
+                newreg['ewres'])
 #         set env(SF_X) [expr abs(round(($s_w - $w) / $sres)) ]
-            self.SF_RL = abs(round(newreg['n'] - newreg['s']) / newreg['nsres'])
+            self.SF_RL = abs(
+                round(
+                    newreg['n'] -
+                    newreg['s']) /
+                newreg['nsres'])
 #         set env(SF_RL) [expr abs(round(($n - $s) / $nres)) ]
-            self.SF_CL = abs(round(newreg['e'] - newreg['w']) / newreg['ewres'])
+            self.SF_CL = abs(
+                round(
+                    newreg['e'] -
+                    newreg['w']) /
+                newreg['ewres'])
 #         set env(SF_CL) [expr abs(round(($e - $w) / $sres)) ]
             self.per_x = float(self.SF_X) / float(self.rasterinfo['cols'])
 #         double($env(SF_X)) / double($cols)
@@ -213,12 +234,14 @@
 #         double($env(SF_RL)) / double($rows)
             self.per_cl = float(self.SF_CL) / float(self.rasterinfo['cols'])
 #         double($env(SF_CL)) / double($cols)
-            fil.write("SAMPLINGFRAME %r|%r|%r|%r\n" % (self.per_x, self.per_y,
-                                                       self.per_rl, self.per_cl))
+            fil.write("SAMPLINGFRAME %r|%r|%r|%r\n" %
+                      (self.per_x, self.per_y, self.per_rl, self.per_cl))
 
     def _value_for_circle(self, radius):
-        self.CIR_RL = round((2 * float(radius)) / float(self.rasterinfo['ewres']))
-        self.CIR_CL = round((2 * float(radius)) / float(self.rasterinfo['nsres']))
+        self.CIR_RL = round((2 * float(radius)) /
+                            float(self.rasterinfo['ewres']))
+        self.CIR_CL = round((2 * float(radius)) /
+                            float(self.rasterinfo['nsres']))
         if not self.CIR_RL % 2:
             self.CIR_RL += 1
         if not self.CIR_CL % 2:
@@ -284,11 +307,11 @@
         """Write the area according the type"""
         samtype = self.getSamplingType()
 
-        #sampling type is whole
+        # sampling type is whole
         if samtype == SamplingType.WHOLE:
             cl = float(self.SF_CL) / float(self.rasterinfo['cols'])
             rl = float(self.SF_RL) / float(self.rasterinfo['rows'])
-            #this two variable are unused, problably to remove
+            # this two variable are unused, problably to remove
             x = float(self.SF_X) / float(self.rasterinfo['cols'])
             y = float(self.SF_Y) / float(self.rasterinfo['rows'])
             fil.write("SAMPLEAREA %r|%r|%r|%r\n" % (self.per_x, self.per_y,
@@ -301,19 +324,21 @@
             fil.write("MASKEDSAMPLEAREA -1|-1|%r|%r" % (rl, cl))
             fil.write("|%s" % self.moving.height)
             fil.write("\nMOVINGWINDOW\n")
-        ##KMWINR = samplingtype moving, regionbox=keyboard, shape=rectangle
+        # KMWINR = samplingtype moving, regionbox=keyboard, shape=rectangle
         elif samtype == SamplingType.KMVWINR:
             cl = float(self.moving.width) / float(self.rasterinfo['cols'])
             rl = float(self.moving.height) / float(self.rasterinfo['rows'])
             fil.write("SAMPLEAREA -1|-1|%r|%r" % (rl, cl))
             fil.write("\nMOVINGWINDOW\n")
-        ##MMVWINR = samplingtype moving, regionbox=mouse, shape=rectangle
+        # MMVWINR = samplingtype moving, regionbox=mouse, shape=rectangle
         elif samtype == SamplingType.MMVWINR:
-            cl = float(self.msAreaList[0]['cols']) / float(self.rasterinfo['cols'])
-            rl = float(self.msAreaList[0]['rows']) / float(self.rasterinfo['rows'])
+            cl = float(self.msAreaList[0]['cols']
+                       ) / float(self.rasterinfo['cols'])
+            rl = float(self.msAreaList[0]['rows']
+                       ) / float(self.rasterinfo['rows'])
             fil.write("SAMPLEAREA -1|-1|%r|%r" % (rl, cl))
             fil.write("\nMOVINGWINDOW\n")
-        ##MMVWINR = samplingtype moving, regionbox=mouse, shape=circle
+        # MMVWINR = samplingtype moving, regionbox=mouse, shape=circle
         elif samtype == SamplingType.MMVWINC:
             self._value_for_circle(self.msAreaList[0].radius)
             cl = float(self.CIR_CL) / float(self.rasterinfo['cols'])
@@ -345,7 +370,8 @@
             elif self.units.distrtype == 'centered_oversites':
                 fil.write("")
 
-        #elif self.samplingareapage.samplingtype == SamplingType.UNITS and self.samplingareapage.regionbox=='mouse':
+        # elif self.samplingareapage.samplingtype == SamplingType.UNITS and
+        # self.samplingareapage.regionbox=='mouse':
 
         ##MUNITSC = samplingtype=units, regionbox=mouse, shape=cirlce
         ##MUNITSR = samplingtype=units, regionbox=mouse, shape=rectangle
@@ -362,10 +388,22 @@
             for tregion in self.msAreaList:
                 if self.samplingareapage.samplingtype == SamplingType.MUNITSC:
                     tregion = tregion.region
-                abs_y = abs(round((float(s_n) - tregion['n']) / tregion['nsres']))
-                abs_x = abs(round((float(s_w) - tregion['w']) / tregion['ewres']))
-                abs_rl = abs(round((tregion['n'] - tregion['s']) / tregion['nsres']))
-                abs_cl = abs(round((tregion['e'] - tregion['w']) / tregion['ewres']))
+                abs_y = abs(
+                    round(
+                        (float(s_n) - tregion['n']) / tregion
+                        ['nsres']))
+                abs_x = abs(
+                    round(
+                        (float(s_w) - tregion['w']) / tregion
+                        ['ewres']))
+                abs_rl = abs(
+                    round(
+                        (tregion['n'] - tregion['s']) /
+                        tregion['nsres']))
+                abs_cl = abs(
+                    round(
+                        (tregion['e'] - tregion['w']) /
+                        tregion['ewres']))
 
                 x = float(abs_x) / float(cols)
                 y = float(abs_y) / float(rows)
@@ -383,17 +421,28 @@
             cols = float(self.rasterinfo['cols'])
             for marea in self.msAreaList:
                 gregion = marea.region
-                abs_y = self.SF_Y + abs(round((self.SF_N - gregion['n']) / self.SF_NSRES))
-                abs_x = self.SF_X + abs(round((self.SF_W - gregion['w']) / self.SF_EWRES))
-                abs_rl = abs(round(gregion['n'] - gregion['s']) / self.SF_NSRES)
-                abs_cl = abs(round(gregion['e'] - gregion['w']) / self.SF_EWRES)
+                abs_y = self.SF_Y + abs(
+                    round((self.SF_N - gregion['n']) / self.SF_NSRES))
+                abs_x = self.SF_X + abs(
+                    round((self.SF_W - gregion['w']) / self.SF_EWRES))
+                abs_rl = abs(
+                    round(
+                        gregion['n'] -
+                        gregion['s']) /
+                    self.SF_NSRES)
+                abs_cl = abs(
+                    round(
+                        gregion['e'] -
+                        gregion['w']) /
+                    self.SF_EWRES)
 
                 x = float(abs_x) / float(cols)
                 y = float(abs_y) / float(rows)
                 rl = float(abs_rl) / float(rows)
                 cl = float(abs_cl) / float(cols)
 
-                maskArea = str(x) + "|" + str(y) + "|" + str(rl) + "|" + str(cl) + "|" + marea.raster
+                maskArea = str(
+                    x) + "|" + str(y) + "|" + str(rl) + "|" + str(cl) + "|" + marea.raster
                 fil.write("SQUAREAREA %s\n" % maskArea)
         elif self.samplingareapage.samplingtype == SamplingType.VECT:
             for marea in self.msAreaList:
@@ -425,6 +474,7 @@
     """
     !Set name of configuration file, choose raster and optionally vector/sites
     """
+
     def __init__(self, wizard, parent):
         TitledPage.__init__(self, wizard, _("Select maps and define name"))
 
@@ -436,9 +486,10 @@
 
         self.parent = parent
 
-        #name of output configuration file
-        self.newconflabel = wx.StaticText(parent=self, id=wx.ID_ANY,
-                                          label=_('Name for new configuration file to create'))
+        # name of output configuration file
+        self.newconflabel = wx.StaticText(
+            parent=self, id=wx.ID_ANY,
+            label=_('Name for new configuration file to create'))
 
         self.newconftxt = wx.TextCtrl(parent=self, id=wx.ID_ANY,
                                       size=(250, -1))
@@ -448,9 +499,10 @@
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
         self.sizer.Add(item=self.newconftxt, border=5, pos=(0, 1),
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
-        #raster
-        self.mapsellabel = wx.StaticText(parent=self, id=wx.ID_ANY,
-                                         label=_('Raster map to use to select areas'))
+        # raster
+        self.mapsellabel = wx.StaticText(
+            parent=self, id=wx.ID_ANY,
+            label=_('Raster map to use to select areas'))
         self.mapselect = gselect.Select(parent=self, id=wx.ID_ANY,
                                         size=(250, -1), type='cell',
                                         multiple=False)
@@ -458,9 +510,10 @@
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
         self.sizer.Add(item=self.mapselect, border=5, pos=(1, 1),
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
-        #vector
-        self.vectsellabel = wx.StaticText(parent=self, id=wx.ID_ANY,
-                                          label=_('Vector map to use to select areas'))
+        # vector
+        self.vectsellabel = wx.StaticText(
+            parent=self, id=wx.ID_ANY,
+            label=_('Vector map to use to select areas'))
         self.vectselect = gselect.Select(parent=self, id=wx.ID_ANY,
                                          size=(250, -1), type='vector',
                                          multiple=False)
@@ -468,24 +521,29 @@
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
         self.sizer.Add(item=self.vectselect, border=5, pos=(2, 1),
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
-        #vector layer
-        self.vectlaylabel = wx.StaticText(parent=self, id=wx.ID_ANY,
-                                          label=_('Vector map layer to use to select areas'))
-        self.vectlayer = wx.ComboBox(parent = self, id = wx.ID_ANY,
+        # vector layer
+        self.vectlaylabel = wx.StaticText(
+            parent=self, id=wx.ID_ANY,
+            label=_('Vector map layer to use to select areas'))
+        self.vectlayer = wx.ComboBox(parent=self, id=wx.ID_ANY,
                                      size=(250, -1))
         self.sizer.Add(item=self.vectlaylabel, border=5, pos=(3, 0),
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
         self.sizer.Add(item=self.vectlayer, border=5, pos=(3, 1),
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
-        #define sampling region
-        self.sampling_reg = wx.RadioBox(parent=self, id=wx.ID_ANY,
-                                        label=" %s " % _("Define sampling "
-                                                         "region (region for analysis)"),
-                                        choices=[_('Whole map layer'),
-                                                 _('Keyboard setting'),
-                                                 _('Draw the sampling frame')],
-                                        majorDimension=1,
-                                        style=wx.RA_SPECIFY_ROWS)
+        # define sampling region
+        self.sampling_reg = wx.RadioBox(
+            parent=self,
+            id=wx.ID_ANY,
+            label=" %s " % _(
+                "Define sampling "
+                "region (region for analysis)"),
+            choices=[
+                _('Whole map layer'),
+                _('Keyboard setting'),
+                _('Draw the sampling frame')],
+            majorDimension=1,
+            style=wx.RA_SPECIFY_ROWS)
 
         self.sizer.Add(item=self.sampling_reg,
                        flag=wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, border=5,
@@ -496,7 +554,7 @@
                        flag=wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, border=5,
                        pos=(6, 0), span=(1, 2))
 
-        #bindings
+        # bindings
         self.sampling_reg.Bind(wx.EVT_RADIOBOX, self.OnSampling)
         self.newconftxt.Bind(wx.EVT_KILL_FOCUS, self.OnName)
         self.newconftxt.Bind(wx.EVT_TEXT, self.OnNameChanged)
@@ -523,8 +581,11 @@
     def OnName(self, event):
         """Sets the name of configuration file"""
         if self.conf_name in self.parent.parent.listfiles:
-            GMessage(parent=self, message=_("The configuration file %s "
-                     "already exists, please change name") % self.conf_name)
+            GMessage(
+                parent=self, message=_(
+                    "The configuration file %s "
+                    "already exists, please change name") %
+                self.conf_name)
             self.newconftxt.SetValue('')
             self.conf_name = ''
 
@@ -562,7 +623,6 @@
         next = wx.FindWindowById(wx.ID_FORWARD)
         next.Enable(self.CheckInput())
 
-
     def OnLayer(self, event):
         try:
             self.vectorlayer = self.vectlayer.GetValue()
@@ -586,16 +646,16 @@
             areas = gvect.vector_info_topo(vector)['areas']
         except CalledModuleError:
             self.infoError.SetLabel(_("Vector %s was not found, please "
-                                    "select another vector") % vector)
+                                      "select another vector") % vector)
             return False, []
         if areas == 0:
             self.infoError.SetLabel(_("Vector %s has no areas, please "
-                                    "select another vector") % vector)
+                                      "select another vector") % vector)
             return False, []
         links = gvect.vector_info(vector)['num_dblinks']
         if links == 0:
             self.infoError.SetLabel(_("Vector %s has no table connected, "
-                                    "please select another vector") % vector)
+                                      "please select another vector") % vector)
             return False, []
         elif links > 0:
             layers = []
@@ -612,7 +672,7 @@
                  False otherwise
         """
         return bool(self.conf_name and bool(self.rast and
-                    bool(self.VectorEnabled)))
+                                            bool(self.VectorEnabled)))
 
     def OnExitPage(self, event=None):
         """Function during exiting"""
@@ -627,7 +687,8 @@
                 self.parent.samplingareapage.SetPrev(self)
             elif self.region == 'draw':
                 self.SetNext(self.parent.drawsampleframepage)
-                self.parent.samplingareapage.SetPrev(self.parent.drawsampleframepage)
+                self.parent.samplingareapage.SetPrev(
+                    self.parent.drawsampleframepage)
                 return
 
 
@@ -635,6 +696,7 @@
     """
     !Choose the region setting the values of border using the keyboard
     """
+
     def __init__(self, wizard, parent):
         TitledPage.__init__(self, wizard, _("Insert sampling frame parameter"))
 
@@ -644,7 +706,7 @@
         self.col_up = '0'
         self.row_up = '0'
 
-        #column up/left
+        # column up/left
         self.ColUpLeftlabel = wx.StaticText(parent=self, id=wx.ID_ANY,
                                             label=_("Column of upper left "
                                                     "corner"))
@@ -658,9 +720,9 @@
         self.sizer.Add(item=self.ColUpLefttxt, border=5, pos=(1, 2),
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
         self.sizer.AddGrowableCol(2)
-        #row up/left
-        self.RowUpLeftlabel = wx.StaticText(parent=self, id=wx.ID_ANY,
-                                            label=_('Row of upper left corner'))
+        # row up/left
+        self.RowUpLeftlabel = wx.StaticText(
+            parent=self, id=wx.ID_ANY, label=_('Row of upper left corner'))
 
         self.RowUpLefttxt = wx.TextCtrl(parent=self, id=wx.ID_ANY,
                                         size=(250, -1))
@@ -671,9 +733,11 @@
         self.sizer.Add(item=self.RowUpLefttxt, border=5, pos=(2, 2),
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
 
-        #row length
-        self.RowLenlabel = wx.StaticText(parent=self, id=wx.ID_ANY,
-                                         label=_('Row length of sampling frame'))
+        # row length
+        self.RowLenlabel = wx.StaticText(
+            parent=self,
+            id=wx.ID_ANY,
+            label=_('Row length of sampling frame'))
 
         self.RowLentxt = wx.TextCtrl(parent=self, id=wx.ID_ANY, size=(250, -1))
         wx.CallAfter(self.RowLenlabel.SetFocus)
@@ -683,9 +747,11 @@
         self.sizer.Add(item=self.RowLentxt, border=5, pos=(3, 2),
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
 
-        #column length
-        self.ColLenlabel = wx.StaticText(parent=self, id=wx.ID_ANY,
-                                         label=_('Row length of sampling frame'))
+        # column length
+        self.ColLenlabel = wx.StaticText(
+            parent=self,
+            id=wx.ID_ANY,
+            label=_('Row length of sampling frame'))
 
         self.ColLentxt = wx.TextCtrl(parent=self, id=wx.ID_ANY, size=(250, -1))
         wx.CallAfter(self.ColLenlabel.SetFocus)
@@ -728,7 +794,7 @@
     def OnEnterPage(self, event):
         """Sets the default values, for the entire map
         """
-        #R# check if raster exists before anything
+        # R# check if raster exists before anything
         if self.col_len == '' and self.row_len == '':
             rastinfo = grast.raster_info(self.parent.startpage.rast)
             self.col_len = rastinfo['cols']
@@ -747,6 +813,7 @@
 
 class DrawSampleFramePage(TitledPage):
     """Choose the region setting the values drawing a box"""
+
     def __init__(self, wizard, parent):
         TitledPage.__init__(self, wizard, _("Draw sampling frame"))
         self.parent = parent
@@ -798,6 +865,7 @@
     Set name of configuration file, choose raster and optionally vector/sites.
     This is coming after choose the region
     """
+
     def __init__(self, wizard, parent):
         TitledPage.__init__(self, wizard, _("Insert sampling areas"))
         self.samplingtype = 'whole'
@@ -818,12 +886,15 @@
         self.sizer.SetVGap(10)
         self.sizer.Add(item=self.radioBox, flag=wx.ALIGN_LEFT, pos=(0, 0))
 
-        self.regionBox = wx.RadioBox(parent=self, id=wx.ID_ANY,
-                                     label=_("Choose a method"),
-                                     choices=[_('Use keyboard to enter sampling area'),
-                                              _('Use mouse to draw sampling area')],
-                                     majorDimension=1,
-                                     style=wx.RA_SPECIFY_ROWS)
+        self.regionBox = wx.RadioBox(
+            parent=self,
+            id=wx.ID_ANY,
+            label=_("Choose a method"),
+            choices=[
+                _('Use keyboard to enter sampling area'),
+                _('Use mouse to draw sampling area')],
+            majorDimension=1,
+            style=wx.RA_SPECIFY_ROWS)
         #self.regionBox.EnableItem(1, False)
         self.regionBox.SetItemToolTip(1, _("This option is not supported yet"))
         self.sizer.Add(self.regionBox, flag=wx.ALIGN_CENTER, pos=(1, 0))
@@ -835,9 +906,9 @@
 
         self.regionPanelSizer = wx.GridBagSizer(1, 2)
         self.regionNumPanel = wx.Panel(parent=self, id=wx.ID_ANY)
-        self.regionNumLabel = wx.StaticText(parent=self.regionNumPanel,
-                                            id=wx.ID_ANY,
-                                            label=_('Number of regions to draw:'))
+        self.regionNumLabel = wx.StaticText(
+            parent=self.regionNumPanel, id=wx.ID_ANY,
+            label=_('Number of regions to draw:'))
         self.regionNumTxt = wx.TextCtrl(parent=self.regionNumPanel,
                                         id=wx.ID_ANY, size=(50, -1))
         self.regionPanelSizer.Add(self.regionNumLabel, flag=wx.ALIGN_CENTER,
@@ -850,12 +921,14 @@
 
         self.areaPanelSizer = wx.GridBagSizer(2, 3)
         self.areaPanel = wx.Panel(parent=self, id=wx.ID_ANY)
-        self.overwriteText = wx.StaticText(parent=self.areaPanel, id=wx.ID_ANY,
-                                      label=_('Do you want to overwrite existing'
-                                              ' temporal maps if they exist?'))
+        self.overwriteText = wx.StaticText(
+            parent=self.areaPanel, id=wx.ID_ANY, label=_(
+                'Do you want to overwrite existing'
+                ' temporal maps if they exist?'))
         self.overwriteCheck = wx.CheckBox(parent=self.areaPanel, id=wx.ID_ANY)
-        self.areaText = wx.StaticText(parent=self.areaPanel, id=wx.ID_ANY,
-                                      label=_('Do you want to check vector areas?'))
+        self.areaText = wx.StaticText(
+            parent=self.areaPanel, id=wx.ID_ANY,
+            label=_('Do you want to check vector areas?'))
         self.areaOK = wx.Button(self.areaPanel, wx.ID_ANY, 'Yes', (50, 80))
         self.areaOK.SetToolTip(wx.ToolTip(_("Select if use area by area")))
         self.areaNO = wx.Button(self.areaPanel, wx.ID_ANY, 'No', (50, 80))
@@ -874,8 +947,9 @@
         self.areaPanel.SetSizer(self.areaPanelSizer)
         self.sizer.Add(self.areaPanel, flag=wx.ALIGN_CENTER, pos=(3, 0))
 
-        self.calculatingAreas = wx.StaticText(parent=self, id=wx.ID_ANY,
-                                     label=_('Analysing all vector features...'))
+        self.calculatingAreas = wx.StaticText(
+            parent=self, id=wx.ID_ANY,
+            label=_('Analysing all vector features...'))
         self.sizer.Add(self.calculatingAreas, flag=wx.ALIGN_CENTER, pos=(4, 0))
         self.numregions = ''
         self.regionNumTxt.Bind(wx.EVT_TEXT, self.OnNumRegions)
@@ -972,20 +1046,21 @@
         vect_cats = obtainCategories(self.parent.startpage.vect,
                                      self.parent.startpage.vectorlayer)
 
-        self._progressDlg = wx.ProgressDialog(title=_("Analysing vector"),
-                                              message="Analysing vector",
-                                              maximum=len(vect_cats),
-                                              parent=self,
-                                              style=wx.PD_CAN_ABORT | wx.PD_APP_MODAL |
-                                              wx.PD_AUTO_HIDE | wx.PD_SMOOTH)
+        self._progressDlg = wx.ProgressDialog(
+            title=_("Analysing vector"),
+            message="Analysing vector",
+            maximum=len(vect_cats),
+            parent=self,
+            style=wx.PD_CAN_ABORT | wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_SMOOTH)
         self._progressDlgMax = len(vect_cats)
         grass.use_temp_region()
-        self.parent.msAreaList = sampleAreaVector(self.parent.startpage.vect,
-                                                  self.parent.startpage.rast,
-                                                  vect_cats,
-                                                  self.parent.startpage.vectorlayer,
-                                                  self.overwriteTemp,
-                                                  self._progressDlg)
+        self.parent.msAreaList = sampleAreaVector(
+            self.parent.startpage.vect,
+            self.parent.startpage.rast,
+            vect_cats,
+            self.parent.startpage.vectorlayer,
+            self.overwriteTemp,
+            self._progressDlg)
         grass.del_temp_region()
         if self.parent.msAreaList:
             self.calculatingAreas.SetLabel(_("All feature are been analyzed."))
@@ -1021,6 +1096,7 @@
 
 
 class DrawRegionsPage(TitledPage):
+
     def __init__(self, wizard, parent):
         self.parent = parent
         TitledPage.__init__(self, wizard, _("Draw sampling regions"))
@@ -1052,9 +1128,8 @@
         elif self.parent.samplingareapage.samplingtype == SamplingType.UNITS:
             self.title.SetLabel(_("Draw sampling region"))
         if self.mapPanel is None:
-            self.mapPanel = RLiSetupMapPanel(self,
-                                             samplingType=self.parent.samplingareapage.samplingtype,
-                                             )
+            self.mapPanel = RLiSetupMapPanel(
+                self, samplingType=self.parent.samplingareapage.samplingtype, )
             self.mapPanel.afterRegionDrawn.connect(self.afterRegionDrawn)
 
             self.sizer.Add(item=self.mapPanel, flag=wx.EXPAND, pos=(1, 0))
@@ -1072,10 +1147,10 @@
             map_.AddLayer(ltype='raster', command=cmdlist, active=True,
                           name=rast, hidden=False, opacity=1.0, render=True)
 
-    #def OnExitPage(self, event=None):
+    # def OnExitPage(self, event=None):
         #!Function during exiting
-        #print event.GetDirection()
-        #if event.GetDirection():
+        # print event.GetDirection()
+        # if event.GetDirection():
         #    self.SetNext(self.parent.samplingareapage)
         #    self.parent.samplingareapage.SetPrev(self)
 
@@ -1087,7 +1162,8 @@
     """
 
     def __init__(self, wizard, parent):
-        TitledPage.__init__(self, wizard, _("Select sample units from keyboard"))
+        TitledPage.__init__(self, wizard, _(
+            "Select sample units from keyboard"))
 
         self.parent = parent
         self.scrollPanel = scrolled.ScrolledPanel(parent=self, id=wx.ID_ANY)
@@ -1111,55 +1187,65 @@
         self.widthTxt = wx.TextCtrl(parent=self.scrollPanel, id=wx.ID_ANY,
                                     size=(250, -1))
 
-        self.panelSizer.Add(item=self.widthLabel, pos=(1, 0),
-                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
-        self.panelSizer.Add(item=self.widthTxt, pos=(1, 1),
-                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
+        self.panelSizer.Add(
+            item=self.widthLabel, pos=(1, 0),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
+        self.panelSizer.Add(
+            item=self.widthTxt, pos=(1, 1),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
 
         self.heightLabel = wx.StaticText(parent=self.scrollPanel, id=wx.ID_ANY)
         self.heightTxt = wx.TextCtrl(parent=self.scrollPanel, id=wx.ID_ANY,
                                      size=(250, -1))
 
-        self.panelSizer.Add(item=self.heightLabel, pos=(2, 0),
-                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
-        self.panelSizer.Add(item=self.heightTxt, pos=(2, 1),
-                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
+        self.panelSizer.Add(
+            item=self.heightLabel, pos=(2, 0),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
+        self.panelSizer.Add(
+            item=self.heightTxt, pos=(2, 1),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
         self.widthLabels = [_('Width size (in cells)?'),
                             _('What radius size (in meters)?')]
         self.heightLabels = [_('Height size (in cells)?'),
                              _('Name of the circle mask')]
 
-        self.distributionBox = wx.RadioBox(parent=self.scrollPanel,
-                                           id=wx.ID_ANY,
-                                           majorDimension=1,
-                                           style=wx.RA_SPECIFY_COLS,
-                                           label= " %s " % _("Select method of sampling unit distribution"),
-                                           choices=[_('Random non overlapping'),
-                                                    _('Systematic contiguos'),
-                                                    _('Stratified random'),
-                                                    _('Systematic non contiguos'),
-                                                    _('Centered over sites')]
-                                          )
-        self.panelSizer.Add(item=self.distributionBox, pos=(3, 0), span=(1, 2),
-                    flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
+        self.distributionBox = wx.RadioBox(
+            parent=self.scrollPanel,
+            id=wx.ID_ANY,
+            majorDimension=1,
+            style=wx.RA_SPECIFY_COLS,
+            label=" %s " %
+            _("Select method of sampling unit distribution"),
+            choices=[
+                _('Random non overlapping'),
+                _('Systematic contiguos'),
+                _('Stratified random'),
+                _('Systematic non contiguos'),
+                _('Centered over sites')])
+        self.panelSizer.Add(item=self.distributionBox, pos=(3, 0), span=(
+            1, 2), flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
 
         self.distr1Label = wx.StaticText(parent=self.scrollPanel, id=wx.ID_ANY,
                                          label=_("What number of Sampling "
                                                  "Units to use?"))
         self.distr1Txt = wx.TextCtrl(parent=self.scrollPanel, id=wx.ID_ANY,
                                      size=(250, -1))
-        self.panelSizer.Add(item=self.distr1Label, pos=(4, 0),
-                    flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
-        self.panelSizer.Add(item=self.distr1Txt, pos=(4, 1),
-                    flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
+        self.panelSizer.Add(
+            item=self.distr1Label, pos=(4, 0),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
+        self.panelSizer.Add(
+            item=self.distr1Txt, pos=(4, 1),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
         self.distr2Label = wx.StaticText(parent=self.scrollPanel, id=wx.ID_ANY,
                                          label="")
         self.distr2Txt = wx.TextCtrl(parent=self.scrollPanel, id=wx.ID_ANY,
                                      size=(250, -1))
-        self.panelSizer.Add(item=self.distr2Label, pos=(5, 0),
-                    flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
-        self.panelSizer.Add(item=self.distr2Txt, pos=(5, 1),
-                    flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
+        self.panelSizer.Add(
+            item=self.distr2Label, pos=(5, 0),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
+        self.panelSizer.Add(
+            item=self.distr2Txt, pos=(5, 1),
+            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
         self.panelSizer.Hide(self.distr2Txt)
 
         self.typeBox.Bind(wx.EVT_RADIOBOX, self.OnType)
@@ -1204,7 +1290,8 @@
         chosen = self.distributionBox.GetSelection()
         if chosen == 0:
             self.distrtype = 'non_overlapping'
-            self.distr1Label.SetLabel(_("What number of Sampling Units to use?"))
+            self.distr1Label.SetLabel(
+                _("What number of Sampling Units to use?"))
             self.panelSizer.Show(self.distr1Txt)
             self.distr2Label.SetLabel("")
             self.panelSizer.Hide(self.distr2Txt)
@@ -1265,7 +1352,7 @@
         self.typeBox = wx.RadioBox(parent=self, id=wx.ID_ANY,
                                    label=" %s " % _("Select type of shape"),
                                    choices=[_('Rectangle'), _('Circle')],
-#                                               ('None')],
+                                   #                                               ('None')],
                                    majorDimension=1,
                                    style=wx.RA_SPECIFY_COLS)
 
@@ -1301,8 +1388,8 @@
 
     def OnEnterPage(self, event):
         # This is an hack to force the user to choose Rectangle or Circle
-#        self.typeBox.SetSelection(2),
-#        self.typeBox.ShowItem(2, False)
+        #        self.typeBox.SetSelection(2),
+        #        self.typeBox.ShowItem(2, False)
         if self.parent.samplingareapage.samplingtype == SamplingType.MVWIN:
             self.title.SetLabel(_("Set moving windows"))
         self.OnType(None)
@@ -1343,6 +1430,7 @@
        areas with rectangle or circle. It is used both from 'Moving windows'
        and 'Sample units'.
     """
+
     def __init__(self, wizard, parent):
         self.parent = parent
         self.wizard = wizard
@@ -1362,9 +1450,9 @@
 
         self.regionPanelSizer = wx.GridBagSizer(1, 2)
         self.regionNumPanel = wx.Panel(parent=self, id=wx.ID_ANY)
-        self.regionNumLabel = wx.StaticText(parent=self.regionNumPanel,
-                                            id=wx.ID_ANY,
-                                            label=_('Number of sampling area to draw:'))
+        self.regionNumLabel = wx.StaticText(
+            parent=self.regionNumPanel, id=wx.ID_ANY,
+            label=_('Number of sampling area to draw:'))
         self.regionNumTxt = wx.TextCtrl(parent=self.regionNumPanel,
                                         id=wx.ID_ANY, size=(50, -1))
         self.regionPanelSizer.Add(self.regionNumLabel, flag=wx.ALIGN_CENTER,
@@ -1408,18 +1496,16 @@
     def OnType(self, event):
         chosen = self.typeBox.GetSelection()
         if chosen == 0:
-            if self.parent.samplingareapage.samplingtype in [SamplingType.MVWIN,
-                                                             SamplingType.MMVWINR,
-                                                             SamplingType.MMVWINC]:
+            if self.parent.samplingareapage.samplingtype in [
+                    SamplingType.MVWIN, SamplingType.MMVWINR, SamplingType.MMVWINC]:
                 self.parent.samplingareapage.samplingtype = SamplingType.MMVWINR
                 wx.FindWindowById(wx.ID_FORWARD).Enable(True)
             else:
                 self.parent.samplingareapage.samplingtype = SamplingType.MUNITSR
             self.drawtype = 'rectangle'
         else:
-            if self.parent.samplingareapage.samplingtype in [SamplingType.MVWIN,
-                                                             SamplingType.MMVWINR,
-                                                             SamplingType.MMVWINC]:
+            if self.parent.samplingareapage.samplingtype in [
+                    SamplingType.MVWIN, SamplingType.MMVWINR, SamplingType.MMVWINC]:
                 self.parent.samplingareapage.samplingtype = SamplingType.MMVWINC
                 wx.FindWindowById(wx.ID_FORWARD).Enable(True)
             else:
@@ -1444,6 +1530,7 @@
 
 class DrawSampleUnitsPage(TitledPage):
     """Choose the sampling area drawing them"""
+
     def __init__(self, wizard, parent):
         TitledPage.__init__(self, wizard, _("Draw sampling units"))
         self.parent = parent
@@ -1462,8 +1549,8 @@
             wx.FindWindowById(wx.ID_FORWARD).Enable(True)
             self.parent.wizard.ShowPage(self.parent.summarypage)
         else:
-            self.title.SetLabel(_('Draw Sampling ' + drawtype + ' ' \
-                                  + str(self.regioncount) + ' of ' \
+            self.title.SetLabel(_('Draw Sampling ' + drawtype + ' '
+                                  + str(self.regioncount) + ' of '
                                   + str(self.numregions)))
             wx.FindWindowById(wx.ID_FORWARD).Enable(False)
 
@@ -1481,9 +1568,8 @@
             self.sizer.Remove(self.mapPanel)
 
         gtype = self.parent.drawunits.drawtype
-        self.mapPanel = RLiSetupMapPanel(self,
-                                         samplingType=self.parent.samplingareapage.samplingtype,
-                                         )
+        self.mapPanel = RLiSetupMapPanel(
+            self, samplingType=self.parent.samplingareapage.samplingtype, )
         if gtype == 'circle':
             self.mapPanel.afterCircleDrawn.connect(self.SampleFrameChanged)
         else:
@@ -1508,13 +1594,14 @@
         #!Function during exiting
         print event.GetDirection()
 
-        #if event.GetDirection():
+        # if event.GetDirection():
         #    self.SetNext(self.parent.samplingareapage)
         #    self.parent.samplingareapage.SetPrev(self)
 
 
 class VectorAreasPage(TitledPage):
     """Choose the sampling area using the vector features"""
+
     def __init__(self, wizard, parent):
         TitledPage.__init__(self, wizard, _("Select sampling areas"))
         self.parent = parent
@@ -1548,7 +1635,7 @@
             self.areaNO.Enable(False)
             return True
         else:
-            self.title.SetLabel(_('Select sample area ' + str(self.areascount + 1) \
+            self.title.SetLabel(_('Select sample area ' + str(self.areascount + 1)
                                   + ' of ' + str(self.areanum)))
             wx.FindWindowById(wx.ID_FORWARD).Enable(False)
             return False
@@ -1573,8 +1660,8 @@
         self.outname = "{pref}{cat}".format(pref=self.outpref, cat=cat)
         # check if raster already axist
 
-        if len(grass.list_strings('raster', pattern=self.outname, mapset='.')) == 1 \
-           and not self.parent.samplingareapage.overwriteTemp:
+        if len(grass.list_strings('raster', pattern=self.outname, mapset='.')
+               ) == 1 and not self.parent.samplingareapage.overwriteTemp:
             GError(parent=self, message=_("The raster map <%s> already exists."
                                           " Please remove or rename the maps "
                                           "with the prefix '%s' or select the "
@@ -1602,7 +1689,8 @@
         feature"""
         print self.parent.samplingareapage.overwriteTemp
         if self.mapPanel is None:
-            self.mapPanel = RLiSetupMapPanel(self, samplingType=self.parent.samplingareapage.samplingtype)
+            self.mapPanel = RLiSetupMapPanel(
+                self, samplingType=self.parent.samplingareapage.samplingtype)
             self.sizer.Add(item=self.mapPanel, flag=wx.EXPAND, pos=(1, 0))
             self.sizer.AddGrowableCol(0)
             self.sizer.AddGrowableRow(1)
@@ -1610,8 +1698,8 @@
 
         self.rast = self.parent.startpage.rast
         self.vect = self.parent.startpage.vect
-        self.vect_cats = obtainCategories(self.vect,
-                                          layer=self.parent.startpage.vectorlayer)
+        self.vect_cats = obtainCategories(
+            self.vect, layer=self.parent.startpage.vectorlayer)
 
         self.areanum = len(self.vect_cats)
         if self.areanum == 0:
@@ -1639,13 +1727,14 @@
 
 class SummaryPage(TitledPage):
     """Shows summary result of choosing data"""
+
     def __init__(self, wizard, parent):
         TitledPage.__init__(self, wizard, _("Summary"))
         global rlisettings
 
         self.parent = parent
 
-        #configuration file name
+        # configuration file name
         self.conflabel = wx.StaticText(parent=self, id=wx.ID_ANY,
                                        label=_('Configuration file name:'))
         self.conftxt = wx.StaticText(parent=self, id=wx.ID_ANY,
@@ -1654,7 +1743,7 @@
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
         self.sizer.Add(item=self.conftxt, border=5, pos=(0, 1),
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
-        #raster name
+        # raster name
         self.rastlabel = wx.StaticText(parent=self, id=wx.ID_ANY,
                                        label=_('Raster name:'))
         self.rasttxt = wx.StaticText(parent=self, id=wx.ID_ANY,
@@ -1664,7 +1753,7 @@
         self.sizer.Add(item=self.rasttxt, border=5, pos=(1, 1),
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
 
-        #vector name
+        # vector name
         self.vectlabel = wx.StaticText(parent=self, id=wx.ID_ANY,
                                        label=_('Vector name:'))
         self.vecttxt = wx.StaticText(parent=self, id=wx.ID_ANY, label="")
@@ -1673,7 +1762,7 @@
         self.sizer.Add(item=self.vecttxt, border=5, pos=(2, 1),
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
 
-        #region type name
+        # region type name
         self.regionlabel = wx.StaticText(parent=self, id=wx.ID_ANY,
                                          label=_('Region type:'))
         self.regiontxt = wx.StaticText(parent=self, id=wx.ID_ANY, label="")
@@ -1682,7 +1771,7 @@
         self.sizer.Add(item=self.regiontxt, border=5, pos=(3, 1),
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
 
-        #region keyboard
+        # region keyboard
         self.regionkeylabel = wx.StaticText(parent=self, id=wx.ID_ANY,
                                             label="")
         self.regionkeytxt = wx.StaticText(parent=self, id=wx.ID_ANY, label="")
@@ -1691,7 +1780,7 @@
         self.sizer.Add(item=self.regionkeytxt, border=5, pos=(4, 1),
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
         self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
-        #sampling area
+        # sampling area
         self.samplinglabel = wx.StaticText(parent=self, id=wx.ID_ANY,
                                            label=_('Sampling area type:'))
         self.samplingtxt = wx.StaticText(parent=self, id=wx.ID_ANY, label="")
@@ -1699,14 +1788,14 @@
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
         self.sizer.Add(item=self.samplingtxt, border=5, pos=(5, 1),
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
-        #shapetype
+        # shapetype
         self.shapelabel = wx.StaticText(parent=self, id=wx.ID_ANY, label="")
         self.shapetxt = wx.StaticText(parent=self, id=wx.ID_ANY, label="")
         self.sizer.Add(item=self.shapelabel, border=5, pos=(6, 0),
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
         self.sizer.Add(item=self.shapetxt, border=5, pos=(6, 1),
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
-        #shapedim
+        # shapedim
         self.shapewidthlabel = wx.StaticText(parent=self, id=wx.ID_ANY,
                                              label="")
         self.shapewidthtxt = wx.StaticText(parent=self, id=wx.ID_ANY,
@@ -1723,7 +1812,7 @@
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
         self.sizer.Add(item=self.shapeheighttxt, border=5, pos=(8, 1),
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
-        #units type
+        # units type
         self.unitslabel = wx.StaticText(parent=self, id=wx.ID_ANY, label="")
         self.unitstxt = wx.StaticText(parent=self, id=wx.ID_ANY, label="")
         self.sizer.Add(item=self.unitslabel, border=5, pos=(9, 0),
@@ -1745,7 +1834,6 @@
         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
@@ -1756,21 +1844,21 @@
         self.regiontxt.SetLabel(self.parent.startpage.region)
         self.vecttxt.SetLabel(self.parent.startpage.vect)
         if self.parent.startpage.region == 'key':
-            #region keyboard values
+            # region keyboard values
             self.regionkeylabel.SetLabel(_('Region keyboard values:'))
             regKeyVals = "Column left up: %s - Row left up: %s\n" \
                          "Column length: %s - Row length: %s\n" % (
-                         self.parent.keyboardpage.col_up,
-                         self.parent.keyboardpage.row_up,
-                         self.parent.keyboardpage.col_len,
-                         self.parent.keyboardpage.row_len)
+                             self.parent.keyboardpage.col_up,
+                             self.parent.keyboardpage.row_up,
+                             self.parent.keyboardpage.col_len,
+                             self.parent.keyboardpage.row_len)
             self.regionkeytxt.SetLabel(regKeyVals)
         else:
             self.regionkeylabel.SetLabel("")
             self.regionkeytxt.SetLabel("")
 
         if self.parent.samplingareapage.samplingtype == SamplingType.UNITS \
-        and self.parent.samplingareapage.regionbox == 'keyboard':
+                and self.parent.samplingareapage.regionbox == 'keyboard':
             self.shapelabel.SetLabel(_('Type of shape:'))
             self.shapetxt.SetLabel(self.parent.units.boxtype)
             if self.parent.units.boxtype == 'circle':
@@ -1795,7 +1883,7 @@
                 self.unitsmorelabel2.SetLabel(_("Number column strates:"))
                 self.unitsmoretxt2.SetLabel(self.parent.units.distr2)
         elif self.parent.samplingareapage.samplingtype == SamplingType.UNITS \
-        and self.parent.samplingareapage.regionbox == 'mouse':
+                and self.parent.samplingareapage.regionbox == 'mouse':
             self.shapelabel.SetLabel(_('Type of shape:'))
             self.shapetxt.SetLabel(self.parent.units.boxtype)
             self.unitstxt.SetLabel('by mouse')

Modified: grass/trunk/gui/wxpython/timeline/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/timeline/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/timeline/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -1,4 +1,4 @@
 all = [
     'g.gui.timeline',
     'frame',
-    ]
+]

Modified: grass/trunk/gui/wxpython/timeline/frame.py
===================================================================
--- grass/trunk/gui/wxpython/timeline/frame.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/timeline/frame.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -22,6 +22,7 @@
 import numpy as np
 
 import wx
+from functools import reduce
 
 try:
     import matplotlib
@@ -67,8 +68,13 @@
 
 class TimelineFrame(wx.Frame):
     """The main frame of the application"""
+
     def __init__(self, parent):
-        wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=_("GRASS GIS Timeline Tool"))
+        wx.Frame.__init__(
+            self,
+            parent,
+            id=wx.ID_ANY,
+            title=_("GRASS GIS Timeline Tool"))
 
         tgis.init(True)
         self.datasets = []
@@ -128,8 +134,9 @@
         self.drawButton.Bind(wx.EVT_BUTTON, self.OnRedraw)
         self.helpButton = wx.Button(self.panel, id=wx.ID_ANY, label=_("Help"))
         self.helpButton.Bind(wx.EVT_BUTTON, self.OnHelp)
-        self.view3dCheck = wx.CheckBox(self.panel, id=wx.ID_ANY,
-                                       label=_("3D plot of spatio-temporal extents"))
+        self.view3dCheck = wx.CheckBox(
+            self.panel, id=wx.ID_ANY,
+            label=_("3D plot of spatio-temporal extents"))
         self.view3dCheck.Bind(wx.EVT_CHECKBOX, self.OnRedraw)
         if not check_version(1, 0, 0):
             self.view3dCheck.SetLabel(_("3D plot of spatio-temporal extents "
@@ -142,9 +149,15 @@
         gridSizer.Add(self.datasetSelect, pos=(1, 0), flag=wx.EXPAND)
         gridSizer.Add(self.drawButton, pos=(1, 1), flag=wx.EXPAND)
         gridSizer.Add(self.helpButton, pos=(1, 2), flag=wx.EXPAND)
-        gridSizer.Add(self.view3dCheck, pos=(2, 0), flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
+        gridSizer.Add(
+            self.view3dCheck, pos=(2, 0),
+            flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
 
-        self.vbox.Add(gridSizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=10)
+        self.vbox.Add(
+            gridSizer,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=10)
 
         self.panel.SetSizer(self.vbox)
         self.vbox.Fit(self)
@@ -160,34 +173,44 @@
             etype = series[2]
             sp = tgis.dataset_factory(etype, name)
             if not sp.is_in_db(dbif=self.dbif):
-                GError(self, message=_("Dataset <%s> not found in temporal database") % (name))
+                GError(
+                    self,
+                    message=_("Dataset <%s> not found in temporal database") %
+                    (name))
                 return
 
             sp.select(dbif=self.dbif)
 
             self.timeData[name] = {}
             self.timeData[name]['elementType'] = series[2]
-            self.timeData[name]['temporalType'] = sp.get_temporal_type()  # abs/rel
+            self.timeData[name][
+                'temporalType'] = sp.get_temporal_type()  # abs/rel
 
             if mode is None:
                 mode = self.timeData[name]['temporalType']
             elif self.timeData[name]['temporalType'] != mode:
-                GError(parent=self, message=_("Datasets have different temporal type "
-                                              "(absolute x relative), which is not allowed."))
+                GError(
+                    parent=self, message=_(
+                        "Datasets have different temporal type "
+                        "(absolute x relative), which is not allowed."))
                 return
 
             # check topology
             maps = sp.get_registered_maps_as_objects(dbif=self.dbif)
-            self.timeData[name]['validTopology'] = sp.check_temporal_topology(maps=maps, dbif=self.dbif)
+            self.timeData[name]['validTopology'] = sp.check_temporal_topology(
+                maps=maps, dbif=self.dbif)
 
-            self.timeData[name]['temporalMapType'] = sp.get_map_time()  # point/interval
+            self.timeData[name][
+                'temporalMapType'] = sp.get_map_time()  # point/interval
             self.timeData[name]['unit'] = None  # only with relative
             if self.timeData[name]['temporalType'] == 'relative':
-                start, end, self.timeData[name]['unit'] = sp.get_relative_time()
+                start, end, self.timeData[name][
+                    'unit'] = sp.get_relative_time()
                 if unit is None:
                     unit = self.timeData[name]['unit']
                 elif self.timeData[name]['unit'] != unit:
-                    GError(self, _("Datasets have different time unit which is not allowed."))
+                    GError(
+                        self, _("Datasets have different time unit which is not allowed."))
                     return
 
             self.timeData[name]['start_datetime'] = []
@@ -206,7 +229,12 @@
             rows = sp.get_registered_maps(columns=columns, where=None,
                                           order='start_time', dbif=self.dbif)
             if not rows:
-                GError(parent=self, message=_("Dataset <{name}> is empty").format(name=series[0] + '@' + series[1]))
+                GError(
+                    parent=self,
+                    message=_("Dataset <{name}> is empty").format(
+                        name=series[0] +
+                        '@' +
+                        series[1]))
                 return
             for row in rows:
                 mapName, start, end, north, south, west, east = row
@@ -290,7 +318,8 @@
         plots = []
         lookUp = LookUp(self.timeData)
         for i, name in enumerate(self.datasets):
-            yticksNames.append(name[0])  # just name; with mapset it would be long
+            # just name; with mapset it would be long
+            yticksNames.append(name[0])
             name = name[0] + '@' + name[1]
             yticksPos.append(i)
             barData = []
@@ -310,14 +339,29 @@
             else:
                 # self.timeData[name]['end_plot'] = None
                 pointData = start
-                lookUp.AddDataset(type_='point', yrange=i, xranges=pointData, datasetName=name)
+                lookUp.AddDataset(
+                    type_='point',
+                    yrange=i,
+                    xranges=pointData,
+                    datasetName=name)
             color = colors.next()
             if mapType == 'interval':
-                plots.append(self.axes2d.broken_barh(xranges=barData, yrange=(i - 0.1, 0.2),
-                                                     facecolors=color, alpha=ALPHA))
+                plots.append(
+                    self.axes2d.broken_barh(
+                        xranges=barData,
+                        yrange=(
+                            i - 0.1,
+                            0.2),
+                        facecolors=color,
+                        alpha=ALPHA))
             else:
-                plots.append(self.axes2d.plot(pointData, [i] * len(pointData),
-                                              marker='o', linestyle='None', color=color)[0])
+                plots.append(
+                    self.axes2d.plot(
+                        pointData,
+                        [i] * len(pointData),
+                        marker='o',
+                        linestyle='None',
+                        color=color)[0])
 
         if self.temporalType == 'absolute':
             self.axes2d.xaxis_date()
@@ -348,7 +392,7 @@
             datasets = self._checkDatasets(datasets)
             if not datasets:
                 return
-        except GException, e:
+        except GException as e:
             GError(parent=self, message=unicode(e), showTraceback=False)
             return
 
@@ -370,9 +414,11 @@
             if self.view3dCheck.IsChecked():
                 self.axes2d.change_geometry(2, 1, 1)
                 if not self.axes3d:
-                    # do not remove this import - unused but it is required for 3D
+                    # do not remove this import - unused but it is required for
+                    # 3D
                     from mpl_toolkits.mplot3d import Axes3D  # pylint: disable=W0611
-                    self.axes3d = self.fig.add_subplot(2, 1, 2, projection='3d')
+                    self.axes3d = self.fig.add_subplot(
+                        2, 1, 2, projection='3d')
 
                 self.axes3d.set_visible(True)
                 self._draw3dFigure()
@@ -394,35 +440,47 @@
         tDict = tgis.tlist_grouped('stds', group_type=True, dbif=self.dbif)
         # nested list with '(map, mapset, etype)' items
         allDatasets = [[[(map, mapset, etype) for map in maps]
-                     for etype, maps in etypesDict.iteritems()]
-                    for mapset, etypesDict in tDict.iteritems()]
+                        for etype, maps in etypesDict.iteritems()]
+                       for mapset, etypesDict in tDict.iteritems()]
         # flatten this list
         if allDatasets:
-            allDatasets = reduce(lambda x, y: x + y, reduce(lambda x, y: x + y, allDatasets))
+            allDatasets = reduce(
+                lambda x,
+                y: x + y,
+                reduce(
+                    lambda x,
+                    y: x + y,
+                    allDatasets))
             mapsets = tgis.get_tgis_c_library_interface().available_mapsets()
-            allDatasets = [i for i in sorted(allDatasets, key=lambda l: mapsets.index(l[1]))]
+            allDatasets = [
+                i
+                for i in sorted(
+                    allDatasets, key=lambda l: mapsets.index(l[1]))]
 
         for dataset in datasets:
             errorMsg = _("Space time dataset <%s> not found.") % dataset
             if dataset.find("@") >= 0:
                 nameShort, mapset = dataset.split('@', 1)
-                indices = [n for n, (mapName, mapsetName, etype) in enumerate(allDatasets)
-                           if nameShort == mapName and mapsetName == mapset]
+                indices = [n for n, (mapName, mapsetName, etype) in enumerate(
+                    allDatasets) if nameShort == mapName and mapsetName == mapset]
             else:
-                indices = [n for n, (mapName, mapset, etype) in enumerate(allDatasets)
-                           if dataset == mapName]
+                indices = [n for n, (mapName, mapset, etype) in enumerate(
+                    allDatasets) if dataset == mapName]
 
             if len(indices) == 0:
                 raise GException(errorMsg)
             elif len(indices) >= 2:
-                dlg = wx.SingleChoiceDialog(self,
-                         message=_("Please specify the space time dataset <%s>." % dataset),
-                         caption=_("Ambiguous dataset name"),
-                         choices=[("%(map)s@%(mapset)s: %(etype)s" % {'map': allDatasets[i][0],
-                                                                      'mapset': allDatasets[i][1],
-                                                                      'etype': allDatasets[i][2]})
-                                                                               for i in indices],
-                         style=wx.CHOICEDLG_STYLE | wx.OK)
+                dlg = wx.SingleChoiceDialog(
+                    self,
+                    message=_(
+                        "Please specify the space time dataset <%s>." %
+                        dataset),
+                    caption=_("Ambiguous dataset name"),
+                    choices=[("%(map)s@%(mapset)s: %(etype)s" %
+                              {'map': allDatasets[i][0],
+                               'mapset': allDatasets[i][1],
+                               'etype': allDatasets[i][2]}) for i in indices],
+                    style=wx.CHOICEDLG_STYLE | wx.OK)
                 if dlg.ShowModal() == wx.ID_OK:
                     index = dlg.GetSelection()
                     validated.append(allDatasets[indices[index]])
@@ -446,11 +504,12 @@
             datasets = self._checkDatasets(datasets)
             if not datasets:
                 return
-        except GException, e:
+        except GException as e:
             GError(parent=self, message=unicode(e), showTraceback=False)
             return
         self.datasets = datasets
-        self.datasetSelect.SetValue(','.join(map(lambda x: x[0] + '@' + x[1], datasets)))
+        self.datasetSelect.SetValue(
+            ','.join(map(lambda x: x[0] + '@' + x[1], datasets)))
         self._redraw()
 
     def Show3D(self, show):
@@ -461,6 +520,7 @@
 
 class LookUp:
     """Helper class for searching info by coordinates"""
+
     def __init__(self, timeData):
         self.data = {}
         self.timeData = timeData
@@ -480,7 +540,7 @@
         for keyY in self.data.keys():
             if keyY[0] <= y <= keyY[1]:
                 for keyX in self.data[keyY].keys():
-                    if keyX != 'name' and  keyX[0] <= x <= keyX[1]:
+                    if keyX != 'name' and keyX[0] <= x <= keyX[1]:
                         keys = keyY, keyX
                         break
                 if keys:
@@ -490,7 +550,7 @@
 
         datasetName = self.data[keys[0]]['name']
         mapIndex = self.data[keys[0]][keys[1]]
-        return  self.timeData, datasetName, mapIndex
+        return self.timeData, datasetName, mapIndex
 
 
 def InfoFormat(timeData, datasetName, mapIndex):
@@ -507,8 +567,12 @@
 
     text.append(_("Mapset: %s") % mapset)
     text.append(_("Map name: %s") % timeData[datasetName]['names'][mapIndex])
-    text.append(_("Start time: %s") % timeData[datasetName]['start_datetime'][mapIndex])
-    text.append(_("End time: %s") % timeData[datasetName]['end_datetime'][mapIndex])
+    text.append(
+        _("Start time: %s") %
+        timeData[datasetName]['start_datetime'][mapIndex])
+    text.append(
+        _("End time: %s") %
+        timeData[datasetName]['end_datetime'][mapIndex])
 
     if not timeData[datasetName]['validTopology']:
         text.append(_("WARNING: invalid topology"))
@@ -526,8 +590,11 @@
     Source: http://stackoverflow.com/questions/4652439/
             is-there-a-matplotlib-equivalent-of-matlabs-datacursormode/4674445
     """
-    def __init__(self, artists, lookUp, formatFunction, tolerance=5, offsets=(-30, 30),
-                 display_all=False):
+
+    def __init__(
+            self, artists, lookUp, formatFunction, tolerance=5,
+            offsets=(-30, 30),
+            display_all=False):
         """Create the data cursor and connect it to the relevant figure.
         "artists" is the matplotlib artist or sequence of artists that will be
             selected.
@@ -569,11 +636,15 @@
 
     def annotate(self, ax):
         """Draws and hides the annotation box for the given axis "ax"."""
-        annotation = ax.annotate(self.formatFunction, xy=(0, 0), ha='center',
-                xytext=self.offsets, textcoords='offset points', va='bottom',
-                bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.7),
-                arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'),
-                annotation_clip=False, multialignment='left')
+        annotation = ax.annotate(
+            self.formatFunction, xy=(0, 0),
+            ha='center', xytext=self.offsets, textcoords='offset points',
+            va='bottom',
+            bbox=dict(
+                boxstyle='round,pad=0.5', fc='yellow', alpha=0.7),
+            arrowprops=dict(
+                arrowstyle='->', connectionstyle='arc3,rad=0'),
+            annotation_clip=False, multialignment='left')
         annotation.set_visible(False)
 
         return annotation

Modified: grass/trunk/gui/wxpython/timeline/g.gui.timeline.py
===================================================================
--- grass/trunk/gui/wxpython/timeline/g.gui.timeline.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/timeline/g.gui.timeline.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -43,7 +43,7 @@
 
     from grass.script.setup import set_gui_path
     set_gui_path()
-    
+
     try:
         from timeline.frame import TimelineFrame
     except ImportError as e:

Modified: grass/trunk/gui/wxpython/tools/build_modules_xml.py
===================================================================
--- grass/trunk/gui/wxpython/tools/build_modules_xml.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/tools/build_modules_xml.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -48,7 +48,7 @@
 
 def parse_modules(fd):
     """Writes metadata to xml file."""
-    # TODO: what about ms windows? does gtask handle this? 
+    # TODO: what about ms windows? does gtask handle this?
     mlist = list(gcore.get_commands()[0])
     indent = 4
     for m in mlist:
@@ -59,8 +59,11 @@
         fd.write('%s<module-item name="%s">\n' % (' ' * indent, m))
         indent += 4
         fd.write('%s<module>%s</module>\n' % (' ' * indent, m))
-        fd.write('%s<description>%s</description>\n' % (' ' * indent, escapeXML(desc)))
-        fd.write('%s<keywords>%s</keywords>\n' % (' ' * indent, escapeXML(','.join(keyw))))
+        fd.write(
+            '%s<description>%s</description>\n' %
+            (' ' * indent, escapeXML(desc)))
+        fd.write('%s<keywords>%s</keywords>\n' %
+                 (' ' * indent, escapeXML(','.join(keyw))))
         indent -= 4
         fd.write('%s</module-item>\n' % (' ' * indent))
 
@@ -88,7 +91,9 @@
 def header(fd):
     fd.write('<?xml version="1.0" encoding="UTF-8"?>\n')
     fd.write('<!DOCTYPE module-items SYSTEM "module_items.dtd">\n')
-    fd.write('<!--This file is automatically generated using %s-->\n' % sys.argv[0])
+    fd.write(
+        '<!--This file is automatically generated using %s-->\n' %
+        sys.argv[0])
     # g.version -r is crashing, commenting this block for now
 #    vInfo = gcore.version()
 #    fd.write('<!--version="%s" revision="%s" date="%s"-->\n' % \

Modified: grass/trunk/gui/wxpython/tools/update_menudata.py
===================================================================
--- grass/trunk/gui/wxpython/tools/update_menudata.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/tools/update_menudata.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -25,24 +25,25 @@
 try:
     import xml.etree.ElementTree as etree
 except ImportError:
-    import elementtree.ElementTree as etree # Python <= 2.4
+    import elementtree.ElementTree as etree  # Python <= 2.4
 
 from grass.script import core as grass
 from grass.script import task as gtask
 
-from lmgr.menudata  import LayerManagerMenuData
+from lmgr.menudata import LayerManagerMenuData
 from core.globalvar import grassCmd
 
+
 def parseModules():
     """Parse modules' interface"""
     modules = dict()
-    
+
     # list of modules to be ignored
-    ignore =  [ 'g.mapsets_picker.py',
-                'v.type_wrapper.py',
-                'g.parser',
-                'vcolors' ]
-    
+    ignore = ['g.mapsets_picker.py',
+              'v.type_wrapper.py',
+              'g.parser',
+              'vcolors']
+
     count = len(grassCmd)
     i = 0
     for module in grassCmd:
@@ -56,18 +57,19 @@
         except Exception as e:
             grass.error(module + ': ' + str(e))
             continue
-        modules[interface.name] = { 'label'   : interface.label,
-                                    'desc'    : interface.description,
-                                    'keywords': interface.keywords }
-        
+        modules[interface.name] = {'label': interface.label,
+                                   'desc': interface.description,
+                                   'keywords': interface.keywords}
+
     return modules
 
+
 def updateData(data, modules):
     """Update menu data tree"""
     # list of modules to be ignored
     ignore = ['v.type_wrapper.py',
               'vcolors']
-    
+
     menu_modules = list()
     for node in data.tree.getiterator():
         if node.tag != 'menuitem':
@@ -76,25 +78,25 @@
         item = dict()
         for child in node.getchildren():
             item[child.tag] = child.text
-        
+
         if 'command' not in item:
             continue
-        
+
         if item['command'] in ignore:
             continue
-        
+
         module = item['command'].split(' ')[0]
         if module not in modules:
             grass.warning("'%s' not found in modules" % item['command'])
             continue
-        
+
         if modules[module]['label']:
             desc = modules[module]['label']
         else:
             desc = modules[module]['desc']
         if node.find('handler').text == 'OnMenuCmd':
             node.find('help').text = desc
-        
+
         if 'keywords' not in modules[module]:
             grass.warning('%s: keywords missing' % module)
         else:
@@ -102,24 +104,25 @@
                 node.insert(2, etree.Element('keywords'))
                 grass.warning("Adding tag 'keywords' to '%s'" % module)
             node.find('keywords').text = ','.join(modules[module]['keywords'])
-        
+
         menu_modules.append(item['command'])
 
     for module in modules.keys():
         if module not in menu_modules:
             grass.warning("'%s' not available from the menu" % module)
-    
-def writeData(data, file = None):
+
+
+def writeData(data, file=None):
     """Write updated menudata.xml"""
     if file is None:
         file = os.path.join('xml', 'menudata.xml')
-    
+
     try:
         data.tree.write(file)
     except IOError:
         print >> sys.stderr, "'%s' not found. Please run the script from 'gui/wxpython'." % file
         return
-    
+
     try:
         f = open(file, 'a')
         try:
@@ -128,8 +131,9 @@
             f.close()
     except IOError:
         print >> sys.stderr, "ERROR: Unable to write to menudata file."
-    
-def main(argv = None):
+
+
+def main(argv=None):
     if argv is None:
         argv = sys.argv
 
@@ -141,10 +145,10 @@
     if len(argv) > 1 and argv[1] == '-h':
         print >> sys.stderr, __doc__
         return 1
-    
+
     nuldev = file(os.devnull, 'w+')
     grass.info("Step 1: running make...")
-    grass.call(['make'], stderr = nuldev)
+    grass.call(['make'], stderr=nuldev)
     grass.info("Step 2: parsing modules...")
     modules = dict()
     modules = parseModules()
@@ -152,23 +156,23 @@
     data = LayerManagerMenuData()
     grass.info("Step 4: updating menu data...")
     updateData(data, modules)
-    
+
     if printDiff:
         tempFile = tempfile.NamedTemporaryFile()
         grass.info("Step 5: diff menu data...")
         writeData(data, tempFile.name)
-        
+
         grass.call(['diff', '-u',
                     os.path.join('xml', 'menudata.xml'),
-                    tempFile.name], stderr = nuldev)
+                    tempFile.name], stderr=nuldev)
     else:
         grass.info("Step 5: writing menu data (menudata.xml)...")
         writeData(data)
-        
+
     return 0
 
 if __name__ == '__main__':
     if os.getenv("GISBASE") is None:
         sys.exit("You must be in GRASS GIS to run this program.")
-    
+
     sys.exit(main())

Modified: grass/trunk/gui/wxpython/tplot/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/tplot/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/tplot/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -1,4 +1,4 @@
 all = [
     'g.gui.tplot',
     'frame',
-    ]
+]

Modified: grass/trunk/gui/wxpython/tplot/frame.py
===================================================================
--- grass/trunk/gui/wxpython/tplot/frame.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/tplot/frame.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -26,6 +26,7 @@
 
 import grass.script as grass
 from core.utils import _
+from functools import reduce
 
 try:
     import matplotlib
@@ -171,22 +172,23 @@
         # ------------ITEMS IN NOTEBOOK PAGE (RASTER)------------------------
 
         self.controlPanelRaster = wx.Panel(parent=self.ntb, id=wx.ID_ANY)
-        self.datasetSelectLabelR = wx.StaticText(parent=self.controlPanelRaster,
-                                                 id=wx.ID_ANY,
-                                                 label=_('Raster temporal '
-                                                         'dataset (strds)'))
+        self.datasetSelectLabelR = wx.StaticText(
+            parent=self.controlPanelRaster,
+            id=wx.ID_ANY,
+            label=_(
+                'Raster temporal '
+                'dataset (strds)'))
 
-        self.datasetSelectR = gselect.Select(parent=self.controlPanelRaster,
-                                             id=wx.ID_ANY,
-                                             size=globalvar.DIALOG_GSELECT_SIZE,
-                                             type='strds', multiple=True)
+        self.datasetSelectR = gselect.Select(
+            parent=self.controlPanelRaster, id=wx.ID_ANY,
+            size=globalvar.DIALOG_GSELECT_SIZE, type='strds', multiple=True)
         self.coor = wx.StaticText(parent=self.controlPanelRaster, id=wx.ID_ANY,
                                   label=_('X and Y coordinates separated by '
                                           'comma:'))
         try:
             self._giface.GetMapWindow()
-            self.coorval = gselect.CoordinatesSelect(parent=self.controlPanelRaster,
-                                                     giface=self._giface)
+            self.coorval = gselect.CoordinatesSelect(
+                parent=self.controlPanelRaster, giface=self._giface)
         except:
             self.coorval = wx.TextCtrl(parent=self.controlPanelRaster,
                                        id=wx.ID_ANY,
@@ -213,18 +215,18 @@
 
         # ------------ITEMS IN NOTEBOOK PAGE (VECTOR)------------------------
         self.controlPanelVector = wx.Panel(parent=self.ntb, id=wx.ID_ANY)
-        self.datasetSelectLabelV = wx.StaticText(parent=self.controlPanelVector,
-                                                 id=wx.ID_ANY,
-                                                 label=_('Vector temporal '
-                                                         'dataset (strds)\n'
-                                                         'Please press enter if'
-                                                         ' you digit the name'
-                                                         ' instead select with'
-                                                         ' combobox'))
-        self.datasetSelectV = gselect.Select(parent=self.controlPanelVector,
-                                             id=wx.ID_ANY,
-                                             size=globalvar.DIALOG_GSELECT_SIZE,
-                                             type='stvds', multiple=True)
+        self.datasetSelectLabelV = wx.StaticText(
+            parent=self.controlPanelVector, id=wx.ID_ANY,
+            label=_(
+                'Vector temporal '
+                'dataset (strds)\n'
+                'Please press enter if'
+                ' you digit the name'
+                ' instead select with'
+                ' combobox'))
+        self.datasetSelectV = gselect.Select(
+            parent=self.controlPanelVector, id=wx.ID_ANY,
+            size=globalvar.DIALOG_GSELECT_SIZE, type='stvds', multiple=True)
         self.datasetSelectV.Bind(wx.EVT_COMBOBOX_CLOSEUP,
                                  self.OnVectorSelected)
 
@@ -235,19 +237,21 @@
         # TODO fix the category selection as done for coordinates
         try:
             self._giface.GetMapWindow()
-            self.cats = gselect.VectorCategorySelect(parent=self.controlPanelVector,
-                                                     giface=self._giface)
+            self.cats = gselect.VectorCategorySelect(
+                parent=self.controlPanelVector, giface=self._giface)
         except:
-            self.cats = wx.TextCtrl(parent=self.controlPanelVector, id=wx.ID_ANY,
-                                    size=globalvar.DIALOG_TEXTCTRL_SIZE)
+            self.cats = wx.TextCtrl(
+                parent=self.controlPanelVector,
+                id=wx.ID_ANY,
+                size=globalvar.DIALOG_TEXTCTRL_SIZE)
         self.catsLabel = wx.StaticText(parent=self.controlPanelVector,
                                        id=wx.ID_ANY,
                                        label=_('Select category of vector(s)'))
 
         self.controlPanelSizerVector = wx.BoxSizer(wx.VERTICAL)
-        #self.controlPanelSizer.Add(wx.StaticText(self.panel, id=wx.ID_ANY,
-        #label=_("Select space time raster dataset(s):")),
-        #pos=(0, 0), flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
+        # self.controlPanelSizer.Add(wx.StaticText(self.panel, id=wx.ID_ANY,
+        # label=_("Select space time raster dataset(s):")),
+        # pos=(0, 0), flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
         self.controlPanelSizerVector.Add(self.datasetSelectLabelV,
                                          flag=wx.EXPAND)
         self.controlPanelSizerVector.Add(self.datasetSelectV, flag=wx.EXPAND)
@@ -263,7 +267,6 @@
         self.ntb.AddPage(page=self.controlPanelVector, text=_('STVDS'),
                          name='STVDS')
 
-
         # ------------Buttons on the bottom(draw,help)------------
         self.vButtPanel = wx.Panel(self.mainPanel, id=wx.ID_ANY)
         self.vButtSizer = wx.BoxSizer(wx.HORIZONTAL)
@@ -310,7 +313,6 @@
             self.plotNameListR.append(name)
             self.timeDataR[name] = OrderedDict()
 
-
             self.timeDataR[name]['temporalDataType'] = etype
             self.timeDataR[name]['temporalType'] = sp.get_temporal_type()
             self.timeDataR[name]['granularity'] = sp.get_granularity()
@@ -318,18 +320,22 @@
             if mode is None:
                 mode = self.timeDataR[name]['temporalType']
             elif self.timeDataR[name]['temporalType'] != mode:
-                GError(parent=self, message=_("Datasets have different temporal"
-                                              " type (absolute x relative), "
-                                              "which is not allowed."))
+                GError(
+                    parent=self, message=_(
+                        "Datasets have different temporal"
+                        " type (absolute x relative), "
+                        "which is not allowed."))
                 return
 
             # check topology
             maps = sp.get_registered_maps_as_objects(dbif=self.dbif)
-            self.timeDataR[name]['validTopology'] = sp.check_temporal_topology(maps=maps, dbif=self.dbif)
+            self.timeDataR[name]['validTopology'] = sp.check_temporal_topology(
+                maps=maps, dbif=self.dbif)
 
             self.timeDataR[name]['unit'] = None  # only with relative
             if self.timeDataR[name]['temporalType'] == 'relative':
-                start, end, self.timeDataR[name]['unit'] = sp.get_relative_time()
+                start, end, self.timeDataR[name][
+                    'unit'] = sp.get_relative_time()
                 if unit is None:
                     unit = self.timeDataR[name]['unit']
                 elif self.timeDataR[name]['unit'] != unit:
@@ -411,7 +417,7 @@
             if not sp.is_in_db(dbif=self.dbif):
                 GError(message=_("Dataset <%s> not found in temporal "
                                  "database") % (fullname), parent=self,
-                                 showTraceback=False)
+                       showTraceback=False)
                 return
             sp.select(dbif=self.dbif)
 
@@ -426,13 +432,15 @@
             if mode is None:
                 mode = self.timeDataV[name]['temporalType']
             elif self.timeDataV[name]['temporalType'] != mode:
-                GError(parent=self, showTraceback=False,
-                       message=_("Datasets have different temporal type ("
-                                 "absolute x relative), which is not allowed."))
+                GError(
+                    parent=self, showTraceback=False, message=_(
+                        "Datasets have different temporal type ("
+                        "absolute x relative), which is not allowed."))
                 return
             self.timeDataV[name]['unit'] = None  # only with relative
             if self.timeDataV[name]['temporalType'] == 'relative':
-                start, end, self.timeDataV[name]['unit'] = sp.get_relative_time()
+                start, end, self.timeDataV[name][
+                    'unit'] = sp.get_relative_time()
                 if unit is None:
                     unit = self.timeDataV[name]['unit']
                 elif self.timeDataV[name]['unit'] != unit:
@@ -459,9 +467,12 @@
                         lay = "{map}_{layer}".format(map=row['name'],
                                                      layer=values['Layer'])
                         self.timeDataV[name][lay] = {}
-                        self.timeDataV[name][lay]['start_datetime'] = row['start_time']
-                        self.timeDataV[name][lay]['end_datetime'] = row['start_time']
-                        self.timeDataV[name][lay]['value'] = values['Attributes'][attribute]
+                        self.timeDataV[name][lay][
+                            'start_datetime'] = row['start_time']
+                        self.timeDataV[name][lay][
+                            'end_datetime'] = row['start_time']
+                        self.timeDataV[name][lay]['value'] = values[
+                            'Attributes'][attribute]
             else:
                 wherequery = ''
                 cats = self._getExistingCategories(rows[0]['name'], cats)
@@ -486,22 +497,26 @@
                     lay = int(row['layer'])
                     catkey = self._parseVDbConn(row['name'], lay)
                     if not catkey:
-                        GError(parent=self, showTraceback=False,
-                           message=_("No connection between vector map {vmap} "
-                                     "and layer {la}".format(vmap=row['name'],
-                                                              la=lay)))
+                        GError(
+                            parent=self, showTraceback=False, message=_(
+                                "No connection between vector map {vmap} "
+                                "and layer {la}".format(
+                                    vmap=row['name'], la=lay)))
                         return
-                    vals = grass.vector_db_select(map=row['name'], layer=lay,
-                                                  where=wherequery.format(key=catkey),
-                                                  columns=attribute)
+                    vals = grass.vector_db_select(
+                        map=row['name'], layer=lay, where=wherequery.format(
+                            key=catkey), columns=attribute)
                     layn = "lay{num}".format(num=lay)
                     for cat in cats:
                         catn = "cat{num}".format(num=cat)
                         if layn not in self.timeDataV[name][catn].keys():
                             self.timeDataV[name][catn][layn] = {}
-                        self.timeDataV[name][catn][layn]['start_datetime'] = row['start_time']
-                        self.timeDataV[name][catn][layn]['end_datetime'] = row['end_time']
-                        self.timeDataV[name][catn][layn]['value'] = vals['values'][int(cat)][0]
+                        self.timeDataV[name][catn][layn][
+                            'start_datetime'] = row['start_time']
+                        self.timeDataV[name][catn][layn][
+                            'end_datetime'] = row['end_time']
+                        self.timeDataV[name][catn][layn]['value'] = vals['values'][int(cat)][
+                            0]
         self.unit = unit
         self.temporalType = mode
         return
@@ -569,7 +584,8 @@
                                                label=self.plotNameListR[i])[0])
 
         if self.temporalType == 'absolute':
-            self.axes2d.set_xlabel(_("Temporal resolution: %s" % self.timeDataR[name]['granularity']))
+            self.axes2d.set_xlabel(
+                _("Temporal resolution: %s" % self.timeDataR[name]['granularity']))
         else:
             self.axes2d.set_xlabel(_("Time [%s]") % self.unit)
         self.axes2d.set_ylabel(', '.join(self.yticksNames))
@@ -588,7 +604,9 @@
             self.yticksPos.append(1)  # TODO
             xdata = []
             ydata = []
-            for keys, values in self.timeDataV[name_cat[0]][name_cat[1]].iteritems():
+            for keys, values in self.timeDataV[
+                    name_cat[0]][
+                    name_cat[1]].iteritems():
                 if keys in ['temporalType', 'granularity', 'validTopology',
                             'unit', 'temporalDataType']:
                     continue
@@ -604,11 +622,17 @@
                                    datasetName=name)
             color = self.colors.next()
 
-            self.plots.append(self.axes2d.plot(xdata, ydata, marker='o',
-                                               color=color, label=labelname)[0])
+            self.plots.append(
+                self.axes2d.plot(
+                    xdata,
+                    ydata,
+                    marker='o',
+                    color=color,
+                    label=labelname)[0])
         # ============================
         if self.temporalType == 'absolute':
-            self.axes2d.set_xlabel(_("Temporal resolution: %s" % self.timeDataV[name]['granularity']))
+            self.axes2d.set_xlabel(
+                _("Temporal resolution: %s" % self.timeDataV[name]['granularity']))
         else:
             self.axes2d.set_xlabel(_("Time [%s]") % self.unit)
         self.axes2d.set_ylabel(', '.join(self.yticksNames))
@@ -645,7 +669,8 @@
                                                color=color, label=name)[0])
         # ============================
         if self.temporalType == 'absolute':
-            self.axes2d.set_xlabel(_("Temporal resolution: %s" % self.timeDataV[name]['granularity']))
+            self.axes2d.set_xlabel(
+                _("Temporal resolution: %s" % self.timeDataV[name]['granularity']))
         else:
             self.axes2d.set_xlabel(_("Time [%s]") % self.unit)
         self.axes2d.set_ylabel(', '.join(self.yticksNames))
@@ -766,33 +791,38 @@
             allDatasets = reduce(lambda x, y: x + y, reduce(lambda x, y: x + y,
                                                             allDatasets))
             mapsets = tgis.get_tgis_c_library_interface().available_mapsets()
-            allDatasets = [i for i in sorted(allDatasets,
-                                             key=lambda l: mapsets.index(l[1]))]
+            allDatasets = [
+                i
+                for i in sorted(
+                    allDatasets, key=lambda l: mapsets.index(l[1]))]
 
         for dataset in datasets:
             errorMsg = _("Space time dataset <%s> not found.") % dataset
             if dataset.find("@") >= 0:
                 nameShort, mapset = dataset.split('@', 1)
-                indices = [n for n, (mapName, mapsetName, etype) in enumerate(allDatasets)
-                           if nameShort == mapName and mapsetName == mapset]
+                indices = [n for n, (mapName, mapsetName, etype) in enumerate(
+                    allDatasets) if nameShort == mapName and mapsetName == mapset]
             else:
-                indices = [n for n, (mapName, mapset, etype) in enumerate(allDatasets)
-                           if dataset == mapName]
+                indices = [n for n, (mapName, mapset, etype) in enumerate(
+                    allDatasets) if dataset == mapName]
 
             if len(indices) == 0:
                 raise GException(errorMsg)
             elif len(indices) >= 2:
-                dlg = wx.SingleChoiceDialog(self,
-                                            message=_("Please specify the "
-                                                      "space time dataset "
-                                                      "<%s>." % dataset),
-                                            caption=_("Ambiguous dataset name"),
-                                            choices=[("%(map)s@%(mapset)s:"
-                                                      " %(etype)s" % {'map': allDatasets[i][0],
-                                                                      'mapset': allDatasets[i][1],
-                                                                      'etype': allDatasets[i][2]})
-                                                     for i in indices],
-                                            style=wx.CHOICEDLG_STYLE | wx.OK)
+                dlg = wx.SingleChoiceDialog(
+                    self,
+                    message=_(
+                        "Please specify the "
+                        "space time dataset "
+                        "<%s>." % dataset),
+                    caption=_("Ambiguous dataset name"),
+                    choices=[
+                        ("%(map)s@%(mapset)s:"
+                         " %(etype)s" % {
+                             'map': allDatasets[i][0],
+                             'mapset': allDatasets[i][1],
+                             'etype': allDatasets[i][2]}) for i in indices],
+                    style=wx.CHOICEDLG_STYLE | wx.OK)
                 if dlg.ShowModal() == wx.ID_OK:
                     index = dlg.GetSelection()
                     validated.append(allDatasets[indices[index]])
@@ -848,8 +878,8 @@
             if cats:
                 self.cats.SetValue(cats)
         if self.datasetsR:
-            self.datasetSelectR.SetValue(','.join(map(lambda x: x[0] + '@' + x[1],
-                                                      self.datasetsR)))
+            self.datasetSelectR.SetValue(
+                ','.join(map(lambda x: x[0] + '@' + x[1], self.datasetsR)))
         self._redraw()
 
     def OnVectorSelected(self, event):
@@ -861,8 +891,10 @@
                                                input=dataset, column='name')
             except Exception:
                 self.attribute.Clear()
-                GError(parent=self, message=_("Invalid input temporal dataset"),
-                       showTraceback=False)
+                GError(
+                    parent=self,
+                    message=_("Invalid input temporal dataset"),
+                    showTraceback=False)
                 return
             vect_list = list(set(sorted(vect_list.split())))
             for vec in vect_list:
@@ -913,7 +945,7 @@
             text.append(_("Space time 3D raster dataset: %s") % key)
 
         text.append(_("Value for {date} is {val}".format(date=val[0],
-                      val=val[1])))
+                                                         val=val[1])))
         text.append('\n')
     text.append(_("Press Del to dismiss."))
 

Modified: grass/trunk/gui/wxpython/tplot/g.gui.tplot.py
===================================================================
--- grass/trunk/gui/wxpython/tplot/g.gui.tplot.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/tplot/g.gui.tplot.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -41,7 +41,7 @@
 #% required: no
 #%end
 
-#TODO use option G_OPT_V_CATS
+# TODO use option G_OPT_V_CATS
 #%option
 #% key: cats
 #% label: Categories of vectores features

Modified: grass/trunk/gui/wxpython/vdigit/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/vdigit/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/vdigit/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -7,4 +7,4 @@
     'wxdisplay',
     'g.gui.vdigit',
     'toolbars',
-    ]
+]

Modified: grass/trunk/gui/wxpython/vdigit/dialogs.py
===================================================================
--- grass/trunk/gui/wxpython/vdigit/dialogs.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/vdigit/dialogs.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -24,18 +24,19 @@
 import wx
 import wx.lib.mixins.listctrl as listmix
 
-from core.gcmd        import RunCommand, GError
-from core.debug       import Debug
-from core.settings    import UserSettings
+from core.gcmd import RunCommand, GError
+from core.debug import Debug
+from core.settings import UserSettings
 from core.utils import _
 
 
 class VDigitCategoryDialog(wx.Dialog, listmix.ColumnSorterMixin):
+
     def __init__(self, parent, title,
-                 vectorName, query = None, cats = None,
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
+                 vectorName, query=None, cats=None,
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
         """Dialog used to display/modify categories of vector objects
-        
+
         :param parent:
         :param title: dialog title
         :param query: {coordinates, qdist} - used by v.edit/v.what
@@ -44,13 +45,13 @@
         """
         self.parent = parent  # map window class instance
         self.digit = parent.digit
-        
+
         # map name
         self.vectorName = vectorName
-        
+
         # line : {layer: [categories]}
         self.cats = {}
-        
+
         # do not display dialog if no line is found (-> self.cats)
         if cats is None:
             if self._getCategories(query[0], query[1]) == 0 or not self.line:
@@ -60,23 +61,24 @@
             for line in cats.keys():
                 for layer in cats[line].keys():
                     self.cats[line][layer] = list(cats[line][layer])
-            
+
             layers = []
             for layer in self.digit.GetLayers():
                 layers.append(str(layer))
-        
+
         # make copy of cats (used for 'reload')
         self.cats_orig = copy.deepcopy(self.cats)
-        
-        wx.Dialog.__init__(self, parent = self.parent, id = wx.ID_ANY, title = title,
-                           style = style, **kwargs)
-        
+
+        wx.Dialog.__init__(self, parent=self.parent, id=wx.ID_ANY, title=title,
+                           style=style, **kwargs)
+
         # list of categories
-        box = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                           label = " %s " % _("List of categories - right-click to delete"))
+        box = wx.StaticBox(
+            parent=self, id=wx.ID_ANY, label=" %s " %
+            _("List of categories - right-click to delete"))
         listSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        self.list = CategoryListCtrl(parent = self, id = wx.ID_ANY,
-                                     style = wx.LC_REPORT |
+        self.list = CategoryListCtrl(parent=self, id=wx.ID_ANY,
+                                     style=wx.LC_REPORT |
                                      wx.BORDER_NONE |
                                      wx.LC_SORT_ASCENDING |
                                      wx.LC_HRULES |
@@ -85,10 +87,10 @@
         self.fid = self.cats.keys()[0]
         self.itemDataMap = self.list.Populate(self.cats[self.fid])
         listmix.ColumnSorterMixin.__init__(self, 2)
-        self.fidMulti = wx.Choice(parent = self, id = wx.ID_ANY,
-                                  size = (150, -1))
+        self.fidMulti = wx.Choice(parent=self, id=wx.ID_ANY,
+                                  size=(150, -1))
         self.fidMulti.Bind(wx.EVT_CHOICE, self.OnFeature)
-        self.fidText = wx.StaticText(parent = self, id = wx.ID_ANY)
+        self.fidText = wx.StaticText(parent=self, id=wx.ID_ANY)
         if len(self.cats.keys()) == 1:
             self.fidMulti.Show(False)
             self.fidText.SetLabel(str(self.fid))
@@ -99,45 +101,49 @@
                 choices.append(str(fid))
             self.fidMulti.SetItems(choices)
             self.fidMulti.SetSelection(0)
-        
-        listSizer.Add(item = self.list, proportion = 1, flag = wx.EXPAND)
 
+        listSizer.Add(item=self.list, proportion=1, flag=wx.EXPAND)
+
         # add new category
-        box = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                           label = " %s " % _("Add new category"))
+        box = wx.StaticBox(parent=self, id=wx.ID_ANY,
+                           label=" %s " % _("Add new category"))
         addSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        flexSizer = wx.FlexGridSizer (cols = 5, hgap = 5, vgap = 5)
+        flexSizer = wx.FlexGridSizer(cols=5, hgap=5, vgap=5)
         flexSizer.AddGrowableCol(3)
 
-        layerNewTxt = wx.StaticText(parent = self, id = wx.ID_ANY,
-                                 label = "%s:" % _("Layer"))
-        self.layerNew = wx.Choice(parent = self, id = wx.ID_ANY, size = (75, -1),
-                                  choices = layers)
+        layerNewTxt = wx.StaticText(parent=self, id=wx.ID_ANY,
+                                    label="%s:" % _("Layer"))
+        self.layerNew = wx.Choice(parent=self, id=wx.ID_ANY, size=(75, -1),
+                                  choices=layers)
         if len(layers) > 0:
             self.layerNew.SetSelection(0)
-        
-        catNewTxt = wx.StaticText(parent = self, id = wx.ID_ANY,
-                               label = "%s:" % _("Category"))
 
+        catNewTxt = wx.StaticText(parent=self, id=wx.ID_ANY,
+                                  label="%s:" % _("Category"))
+
         try:
             newCat = max(self.cats[self.fid][1]) + 1
         except KeyError:
             newCat = 1
-        self.catNew = wx.SpinCtrl(parent = self, id = wx.ID_ANY, size = (75, -1),
-                                  initial = newCat, min = 0, max = 1e9)
+        self.catNew = wx.SpinCtrl(parent=self, id=wx.ID_ANY, size=(75, -1),
+                                  initial=newCat, min=0, max=1e9)
         btnAddCat = wx.Button(self, wx.ID_ADD)
-        flexSizer.Add(item = layerNewTxt, proportion = 0,
-                      flag = wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
-        flexSizer.Add(item = self.layerNew, proportion = 0,
-                      flag = wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
-        flexSizer.Add(item = catNewTxt, proportion = 0,
-                      flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
-                      border = 10)
-        flexSizer.Add(item = self.catNew, proportion = 0,
-                      flag = wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
-        flexSizer.Add(item = btnAddCat, proportion = 0,
-                      flag = wx.EXPAND | wx.ALIGN_RIGHT | wx.FIXED_MINSIZE)
-        addSizer.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
+        flexSizer.Add(item=layerNewTxt, proportion=0,
+                      flag=wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
+        flexSizer.Add(item=self.layerNew, proportion=0,
+                      flag=wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
+        flexSizer.Add(item=catNewTxt, proportion=0,
+                      flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
+                      border=10)
+        flexSizer.Add(item=self.catNew, proportion=0,
+                      flag=wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
+        flexSizer.Add(item=btnAddCat, proportion=0,
+                      flag=wx.EXPAND | wx.ALIGN_RIGHT | wx.FIXED_MINSIZE)
+        addSizer.Add(
+            item=flexSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=5)
 
         # buttons
         btnApply = wx.Button(self, wx.ID_APPLY)
@@ -151,32 +157,32 @@
         # sizers
         btnSizer = wx.StdDialogButtonSizer()
         btnSizer.AddButton(btnCancel)
-        #btnSizer.AddButton(btnReload)
-        #btnSizer.SetNegativeButton(btnReload)
+        # btnSizer.AddButton(btnReload)
+        # btnSizer.SetNegativeButton(btnReload)
         btnSizer.AddButton(btnApply)
         btnSizer.AddButton(btnOk)
         btnSizer.Realize()
-        
+
         mainSizer = wx.BoxSizer(wx.VERTICAL)
-        mainSizer.Add(item = listSizer, proportion = 1,
-                      flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
-        mainSizer.Add(item = addSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALIGN_CENTER |
-                      wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
+        mainSizer.Add(item=listSizer, proportion=1,
+                      flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
+        mainSizer.Add(item=addSizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALIGN_CENTER |
+                      wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
         fidSizer = wx.BoxSizer(wx.HORIZONTAL)
-        fidSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
-                                        label = _("Feature id:")),
-                     proportion = 0, border = 5,
-                     flag = wx.ALIGN_CENTER_VERTICAL)
-        fidSizer.Add(item = self.fidMulti, proportion = 0,
-                     flag = wx.EXPAND | wx.ALL,  border = 5)
-        fidSizer.Add(item = self.fidText, proportion = 0,
-                     flag = wx.EXPAND | wx.ALL,  border = 5)
-        mainSizer.Add(item = fidSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL, border = 5)
-        mainSizer.Add(item = btnSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
-        
+        fidSizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY,
+                                        label=_("Feature id:")),
+                     proportion=0, border=5,
+                     flag=wx.ALIGN_CENTER_VERTICAL)
+        fidSizer.Add(item=self.fidMulti, proportion=0,
+                     flag=wx.EXPAND | wx.ALL, border=5)
+        fidSizer.Add(item=self.fidText, proportion=0,
+                     flag=wx.EXPAND | wx.ALL, border=5)
+        mainSizer.Add(item=fidSizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALL, border=5)
+        mainSizer.Add(item=btnSizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
+
         self.SetSizer(mainSizer)
         mainSizer.Fit(self)
         self.SetAutoLayout(True)
@@ -190,10 +196,10 @@
         btnAddCat.Bind(wx.EVT_BUTTON, self.OnAddCat)
         btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel)
         self.Bind(wx.EVT_CLOSE, lambda evt: self.Hide())
-                                     
+
         # list
-        self.list.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightUp) #wxMSW
-        self.list.Bind(wx.EVT_RIGHT_UP, self.OnRightUp) #wxGTK
+        self.list.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightUp)  # wxMSW
+        self.list.Bind(wx.EVT_RIGHT_UP, self.OnRightUp)  # wxGTK
         self.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT, self.OnBeginEdit, self.list)
         self.Bind(wx.EVT_LIST_END_LABEL_EDIT, self.OnEndEdit, self.list)
         self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick, self.list)
@@ -207,7 +213,7 @@
         """Click on column header (order by)
         """
         event.Skip()
-        
+
     def OnBeginEdit(self, event):
         """Editing of item started
         """
@@ -217,8 +223,8 @@
         """Finish editing of item
         """
         itemIndex = event.GetIndex()
-        layerOld = int (self.list.GetItem(itemIndex, 0).GetText())
-        catOld = int (self.list.GetItem(itemIndex, 1).GetText())
+        layerOld = int(self.list.GetItem(itemIndex, 0).GetText())
+        catOld = int(self.list.GetItem(itemIndex, 1).GetText())
 
         if event.GetColumn() == 0:
             layerNew = int(event.GetLabel())
@@ -226,7 +232,7 @@
         else:
             layerNew = layerOld
             catNew = int(event.GetLabel())
-        
+
         try:
             if layerNew not in self.cats[self.fid].keys():
                 self.cats[self.fid][layerNew] = []
@@ -236,12 +242,14 @@
             event.Veto()
             self.list.SetStringItem(itemIndex, 0, str(layerNew))
             self.list.SetStringItem(itemIndex, 1, str(catNew))
-            dlg = wx.MessageDialog(self, _("Unable to add new layer/category <%(layer)s/%(category)s>.\n"
-                                           "Layer and category number must be integer.\n"
-                                           "Layer number must be greater than zero.") %
-                                   { 'layer': self.layerNew.GetStringSelection(),
-                                     'category' : str(self.catNew.GetValue()) },
-                                   _("Error"), wx.OK | wx.ICON_ERROR)
+            dlg = wx.MessageDialog(
+                self, _(
+                    "Unable to add new layer/category <%(layer)s/%(category)s>.\n"
+                    "Layer and category number must be integer.\n"
+                    "Layer number must be greater than zero.") %
+                {
+                    'layer': self.layerNew.GetStringSelection(), 'category': str(
+                        self.catNew.GetValue())}, _("Error"), wx.OK | wx.ICON_ERROR)
             dlg.ShowModal()
             dlg.Destroy()
             return False
@@ -266,9 +274,9 @@
             self.popupID1 = wx.NewId()
             self.popupID2 = wx.NewId()
             self.popupID3 = wx.NewId()
-            self.Bind(wx.EVT_MENU, self.OnItemDelete,    id = self.popupID1)
-            self.Bind(wx.EVT_MENU, self.OnItemDeleteAll, id = self.popupID2)
-            self.Bind(wx.EVT_MENU, self.OnReload, id = self.popupID3)
+            self.Bind(wx.EVT_MENU, self.OnItemDelete, id=self.popupID1)
+            self.Bind(wx.EVT_MENU, self.OnItemDeleteAll, id=self.popupID2)
+            self.Bind(wx.EVT_MENU, self.OnReload, id=self.popupID3)
 
         # generate popup-menu
         menu = wx.Menu()
@@ -293,15 +301,15 @@
         """
         item = self.list.GetFirstSelected()
         while item != -1:
-            layer = int (self.list.GetItem(item, 0).GetText())
-            cat = int (self.list.GetItem(item, 1).GetText())
+            layer = int(self.list.GetItem(item, 0).GetText())
+            cat = int(self.list.GetItem(item, 1).GetText())
             self.list.DeleteItem(item)
             self.cats[self.fid][layer].remove(cat)
 
             item = self.list.GetFirstSelected()
-            
+
         event.Skip()
-        
+
     def OnItemDeleteAll(self, event):
         """Delete all items from the list
         """
@@ -314,19 +322,19 @@
         """Feature id changed (on duplicates)
         """
         self.fid = int(event.GetString())
-        
+
         self.itemDataMap = self.list.Populate(self.cats[self.fid],
-                                              update = True)
+                                              update=True)
 
         try:
             newCat = max(self.cats[self.fid][1]) + 1
         except KeyError:
             newCat = 1
-            
+
         self.catNew.SetValue(newCat)
-        
+
         event.Skip()
-        
+
     def _getCategories(self, coords, qdist):
         """Get layer/category pairs for all available
         layers
@@ -334,25 +342,25 @@
         :return: True line found or False if not found
         """
         ret = RunCommand('v.what',
-                         parent = self,
-                         quiet = True,
-                         map = self.vectorName,
-                         east_north = '%f,%f' % \
-                             (float(coords[0]), float(coords[1])),
-                         distance = qdist)
+                         parent=self,
+                         quiet=True,
+                         map=self.vectorName,
+                         east_north='%f,%f' %
+                         (float(coords[0]), float(coords[1])),
+                         distance=qdist)
 
         if not ret:
             return False
 
         for item in ret.splitlines():
             litem = item.lower()
-            if "id:" in litem: # get line id
+            if "id:" in litem:  # get line id
                 self.line = int(item.split(':')[1].strip())
-            elif "layer:" in litem: # add layer
+            elif "layer:" in litem:  # add layer
                 layer = int(item.split(':')[1].strip())
                 if layer not in self.cats.keys():
                     self.cats[layer] = []
-            elif "category:" in litem: # add category
+            elif "category:" in litem:  # add category
                 self.cats[layer].append(int(item.split(':')[1].strip()))
 
         return True
@@ -365,7 +373,7 @@
 
         # polulate list
         self.itemDataMap = self.list.Populate(self.cats[self.fid],
-                                              update = True)
+                                              update=True)
 
         event.Skip()
 
@@ -375,10 +383,10 @@
         self.parent.parent.dialogs['category'] = None
         if self.digit:
             self.digit.GetDisplay().SetSelected([])
-            self.parent.UpdateMap(render = False)
+            self.parent.UpdateMap(render=False)
         else:
             self.parent.parent.OnRender(None)
-            
+
         self.Close()
 
     def OnApply(self, event):
@@ -388,9 +396,9 @@
             newfid = self.ApplyChanges(fid)
             if fid == self.fid and newfid > 0:
                 self.fid = newfid
-            
+
     def ApplyChanges(self, fid):
-        """Apply changes 
+        """Apply changes
 
         :param fid: feature id
         """
@@ -398,11 +406,11 @@
         cats_orig = self.cats_orig[fid]
 
         # action : (catsFrom, catsTo)
-        check = {'catadd': (cats,      cats_orig),
+        check = {'catadd': (cats, cats_orig),
                  'catdel': (cats_orig, cats)}
 
         newfid = -1
-        
+
         # add/delete new category
         for action, catsCurr in check.iteritems():
             for layer in catsCurr[0].keys():
@@ -416,7 +424,7 @@
                         add = True
                     else:
                         add = False
-                        
+
                     newfid = self.digit.SetLineCats(fid, layer,
                                                     catList, add)
                     if len(self.cats.keys()) == 1:
@@ -426,17 +434,20 @@
                         choices[choices.index(str(fid))] = str(newfid)
                         self.fidMulti.SetItems(choices)
                         self.fidMulti.SetStringSelection(str(newfid))
-                    
+
                     self.cats[newfid] = self.cats[fid]
                     del self.cats[fid]
-                    
+
                     fid = newfid
                     if self.fid < 0:
-                        wx.MessageBox(parent = self, message = _("Unable to update vector map."),
-                                      caption = _("Error"), style = wx.OK | wx.ICON_ERROR)
-        
+                        wx.MessageBox(
+                            parent=self,
+                            message=_("Unable to update vector map."),
+                            caption=_("Error"),
+                            style=wx.OK | wx.ICON_ERROR)
+
         self.cats_orig[fid] = copy.deepcopy(cats)
-        
+
         return newfid
 
     def OnOK(self, event):
@@ -450,30 +461,34 @@
         """
         try:
             layer = int(self.layerNew.GetStringSelection())
-            cat   = int(self.catNew.GetValue())
+            cat = int(self.catNew.GetValue())
             if layer <= 0:
                 raise ValueError
         except ValueError:
-            GError(parent = self,
-                   message = _("Unable to add new layer/category <%(layer)s/%(category)s>.\n"
-                               "Layer and category number must be integer.\n"
-                               "Layer number must be greater than zero.") %
-                   {'layer' : str(self.layerNew.GetValue()),
-                    'category' : str(self.catNew.GetValue())})
+            GError(
+                parent=self,
+                message=_(
+                    "Unable to add new layer/category <%(layer)s/%(category)s>.\n"
+                    "Layer and category number must be integer.\n"
+                    "Layer number must be greater than zero.") % {
+                    'layer': str(
+                        self.layerNew.GetValue()),
+                    'category': str(
+                        self.catNew.GetValue())})
             return False
-        
+
         if layer not in self.cats[self.fid].keys():
             self.cats[self.fid][layer] = []
-        
+
         self.cats[self.fid][layer].append(cat)
-        
+
         # reload list
         self.itemDataMap = self.list.Populate(self.cats[self.fid],
-                                              update = True)
-        
+                                              update=True)
+
         # update category number for add
         self.catNew.SetValue(cat + 1)
-        
+
         event.Skip()
 
         return True
@@ -483,9 +498,9 @@
         """
         return self.cats.keys()
 
-    def UpdateDialog(self, query = None, cats = None):
+    def UpdateDialog(self, query=None, cats=None):
         """Update dialog
-        
+
         :param query: {coordinates, distance} - v.what
         :param cats:  directory layer/cats    - vdigit
         :return: True if updated otherwise False
@@ -504,21 +519,21 @@
         if ret == 0 or len(self.cats.keys()) < 1:
             Debug.msg(3, "VDigitCategoryDialog(): nothing found!")
             return False
-        
+
         # make copy of cats (used for 'reload')
         self.cats_orig = copy.deepcopy(self.cats)
 
         # polulate list
         self.fid = self.cats.keys()[0]
         self.itemDataMap = self.list.Populate(self.cats[self.fid],
-                                              update = True)
+                                              update=True)
 
         try:
             newCat = max(self.cats[self.fid][1]) + 1
         except KeyError:
             newCat = 1
         self.catNew.SetValue(newCat)
-        
+
         if len(self.cats.keys()) == 1:
             self.fidText.Show(True)
             self.fidMulti.Show(False)
@@ -533,26 +548,28 @@
             self.fidMulti.SetSelection(0)
 
         self.Layout()
-        
+
         return True
 
+
 class CategoryListCtrl(wx.ListCtrl,
                        listmix.ListCtrlAutoWidthMixin,
                        listmix.TextEditMixin):
-    def __init__(self, parent, id, pos = wx.DefaultPosition,
-                 size = wx.DefaultSize, style = 0):
+
+    def __init__(self, parent, id, pos=wx.DefaultPosition,
+                 size=wx.DefaultSize, style=0):
         """List of layers/categories"""
         self.parent = parent
-        
+
         wx.ListCtrl.__init__(self, parent, id, pos, size, style)
 
         listmix.ListCtrlAutoWidthMixin.__init__(self)
         listmix.TextEditMixin.__init__(self)
 
-    def Populate(self, cats, update = False):
+    def Populate(self, cats, update=False):
         """Populate the list
         """
-        itemData = {} # requested by sorter
+        itemData = {}  # requested by sorter
 
         if not update:
             self.InsertColumn(0, _("Layer"))
@@ -564,7 +581,7 @@
         for layer in cats.keys():
             catsList = cats[layer]
             for cat in catsList:
-                index = self.InsertStringItem(sys.maxint, str(catsList[0]))
+                index = self.InsertStringItem(sys.maxsize, str(catsList[0]))
                 self.SetStringItem(index, 0, str(layer))
                 self.SetStringItem(index, 1, str(cat))
                 self.SetItemData(index, i)
@@ -579,47 +596,71 @@
 
         return itemData
 
+
 class VDigitZBulkDialog(wx.Dialog):
-    def __init__(self, parent, title, nselected, style = wx.DEFAULT_DIALOG_STYLE):
+
+    def __init__(self, parent, title, nselected,
+                 style=wx.DEFAULT_DIALOG_STYLE):
         """Dialog used for Z bulk-labeling tool
         """
-        wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY, title = title, style = style)
+        wx.Dialog.__init__(
+            self,
+            parent=parent,
+            id=wx.ID_ANY,
+            title=title,
+            style=style)
 
         self.parent = parent  # map window class instance
 
         # panel  = wx.Panel(parent=self, id=wx.ID_ANY)
 
         border = wx.BoxSizer(wx.VERTICAL)
-        
-        txt = wx.StaticText(parent = self,
-                            label = _("%d lines selected for z bulk-labeling") % nselected);
-        border.Add(item = txt, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
 
-        box   = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Set value"))
+        txt = wx.StaticText(
+            parent=self,
+            label=_("%d lines selected for z bulk-labeling") %
+            nselected)
+        border.Add(item=txt, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+
+        box = wx.StaticBox(
+            parent=self,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Set value"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        flexSizer = wx.FlexGridSizer (cols = 2, hgap = 5, vgap = 5)
+        flexSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
         flexSizer.AddGrowableCol(0)
 
         # starting value
-        txt = wx.StaticText(parent = self,
-                            label = _("Starting value"));
-        self.value = wx.SpinCtrl(parent = self, id = wx.ID_ANY, size = (150, -1),
-                                 initial = 0,
-                                 min = -1e6, max = 1e6)
-        flexSizer.Add(txt, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL)
-        flexSizer.Add(self.value, proportion = 0, flag = wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
+        txt = wx.StaticText(parent=self,
+                            label=_("Starting value"))
+        self.value = wx.SpinCtrl(parent=self, id=wx.ID_ANY, size=(150, -1),
+                                 initial=0,
+                                 min=-1e6, max=1e6)
+        flexSizer.Add(txt, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
+        flexSizer.Add(
+            self.value,
+            proportion=0,
+            flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
 
         # step
-        txt = wx.StaticText(parent = self,
-                            label = _("Step"))
-        self.step  = wx.SpinCtrl(parent = self, id = wx.ID_ANY, size = (150, -1),
-                                 initial = 0,
-                                 min = 0, max = 1e6)
-        flexSizer.Add(txt, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL)
-        flexSizer.Add(self.step, proportion = 0, flag = wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
+        txt = wx.StaticText(parent=self,
+                            label=_("Step"))
+        self.step = wx.SpinCtrl(parent=self, id=wx.ID_ANY, size=(150, -1),
+                                initial=0,
+                                min=0, max=1e6)
+        flexSizer.Add(txt, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
+        flexSizer.Add(
+            self.step,
+            proportion=0,
+            flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
 
-        sizer.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
-        border.Add(item = sizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 0)
+        sizer.Add(
+            item=flexSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=1)
+        border.Add(item=sizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=0)
 
         # buttons
         btnCancel = wx.Button(self, wx.ID_CANCEL)
@@ -631,24 +672,35 @@
         btnSizer.AddButton(btnCancel)
         btnSizer.AddButton(btnOk)
         btnSizer.Realize()
-        
+
         mainSizer = wx.BoxSizer(wx.VERTICAL)
-        mainSizer.Add(item = border, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
-        mainSizer.Add(item = btnSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
+        mainSizer.Add(
+            item=border,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        mainSizer.Add(item=btnSizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
 
         self.SetSizer(mainSizer)
         mainSizer.Fit(self)
 
+
 class VDigitDuplicatesDialog(wx.Dialog):
-    def __init__(self, parent, data, title = _("List of duplicates"),
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
-                 pos = wx.DefaultPosition):
+
+    def __init__(self, parent, data, title=_("List of duplicates"),
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
+                 pos=wx.DefaultPosition):
         """Show duplicated feature ids
         """
-        wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY, title = title, style = style,
-                           pos = pos)
-        
+        wx.Dialog.__init__(
+            self,
+            parent=parent,
+            id=wx.ID_ANY,
+            title=title,
+            style=style,
+            pos=pos)
+
         self.parent = parent  # map window instance
         self.data = data
         self.winList = []
@@ -656,21 +708,22 @@
         # panel  = wx.Panel(parent=self, id=wx.ID_ANY)
 
         # notebook
-        self.notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
+        self.notebook = wx.Notebook(
+            parent=self, id=wx.ID_ANY, style=wx.BK_DEFAULT)
 
         id = 1
         for key in self.data.keys():
-            panel = wx.Panel(parent = self.notebook, id = wx.ID_ANY)
-            self.notebook.AddPage(page = panel, text = " %d " % (id))
-            
+            panel = wx.Panel(parent=self.notebook, id=wx.ID_ANY)
+            self.notebook.AddPage(page=panel, text=" %d " % (id))
+
             # notebook body
             border = wx.BoxSizer(wx.VERTICAL)
 
-            win = CheckListFeature(parent = panel, data = list(self.data[key]))
+            win = CheckListFeature(parent=panel, data=list(self.data[key]))
             self.winList.append(win.GetId())
 
-            border.Add(item = win, proportion = 1,
-                       flag = wx.ALL | wx.EXPAND, border = 5)
+            border.Add(item=win, proportion=1,
+                       flag=wx.ALL | wx.EXPAND, border=5)
 
             panel.SetSizer(border)
 
@@ -686,11 +739,15 @@
         btnSizer.AddButton(btnCancel)
         btnSizer.AddButton(btnOk)
         btnSizer.Realize()
-        
+
         mainSizer = wx.BoxSizer(wx.VERTICAL)
-        mainSizer.Add(item = self.notebook, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
-        mainSizer.Add(item = btnSizer, proportion = 0,
-                      flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
+        mainSizer.Add(
+            item=self.notebook,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        mainSizer.Add(item=btnSizer, proportion=0,
+                      flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
 
         self.SetSizer(mainSizer)
         mainSizer.Fit(self)
@@ -711,19 +768,22 @@
             for item in range(wlist.GetItemCount()):
                 if not wlist.IsChecked(item):
                     ids.append(int(wlist.GetItem(item, 0).GetText()))
-                    
+
         return ids
 
-class CheckListFeature(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.CheckListCtrlMixin):
+
+class CheckListFeature(
+        wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.CheckListCtrlMixin):
+
     def __init__(self, parent, data,
-                 pos = wx.DefaultPosition, log = None):
+                 pos=wx.DefaultPosition, log=None):
         """List of mapset/owner/group
         """
         self.parent = parent
         self.data = data
 
         wx.ListCtrl.__init__(self, parent, wx.ID_ANY,
-                             style = wx.LC_REPORT)
+                             style=wx.LC_REPORT)
 
         listmix.CheckListCtrlMixin.__init__(self)
 
@@ -741,16 +801,16 @@
         self.InsertColumn(1, _('Layer (Categories)'))
 
         for item in data:
-            index = self.InsertStringItem(sys.maxint, str(item[0]))
+            index = self.InsertStringItem(sys.maxsize, str(item[0]))
             self.SetStringItem(index, 1, str(item[1]))
 
         # enable all items by default
         for item in range(self.GetItemCount()):
             self.CheckItem(item, True)
 
-        self.SetColumnWidth(col = 0, width = wx.LIST_AUTOSIZE_USEHEADER)
-        self.SetColumnWidth(col = 1, width = wx.LIST_AUTOSIZE_USEHEADER)
-                
+        self.SetColumnWidth(col=0, width=wx.LIST_AUTOSIZE_USEHEADER)
+        self.SetColumnWidth(col=1, width=wx.LIST_AUTOSIZE_USEHEADER)
+
     def OnCheckItem(self, index, flag):
         """Mapset checked/unchecked
         """

Modified: grass/trunk/gui/wxpython/vdigit/g.gui.vdigit.py
===================================================================
--- grass/trunk/gui/wxpython/vdigit/g.gui.vdigit.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/vdigit/g.gui.vdigit.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -49,7 +49,7 @@
 
     from grass.script.setup import set_gui_path
     set_gui_path()
-    
+
     from core.globalvar import CheckWxVersion
     from core.utils import _
     from core.render import Map
@@ -62,6 +62,7 @@
     # define classes which needs imports as local
     # for longer definitions, a separate file would be a better option
     class VDigitMapFrame(MapFrame):
+
         def __init__(self, vectorMap):
             MapFrame.__init__(
                 self, parent=None, Map=Map(), giface=DMonGrassInterface(None),
@@ -87,13 +88,18 @@
                            mapset=grass.gisenv()['MAPSET'])['fullname']:
         if not flags['c']:
             grass.fatal(_("Vector map <%s> not found in current mapset. "
-                          "New vector map can be created by providing '-c' flag.") % options['map'])
+                          "New vector map can be created by providing '-c' flag.") %
+                        options['map'])
         else:
             grass.verbose(_("New vector map <%s> created") % options['map'])
             try:
-                grass.run_command('v.edit', map=options['map'], tool='create', quiet=True)
+                grass.run_command(
+                    'v.edit', map=options['map'],
+                    tool='create', quiet=True)
             except CalledModuleError:
-                grass.fatal(_("Unable to create new vector map <%s>") % options['map'])
+                grass.fatal(
+                    _("Unable to create new vector map <%s>") %
+                    options['map'])
 
     # allow immediate rendering
     driver = UserSettings.Get(group='display', key='driver', subkey='type')

Modified: grass/trunk/gui/wxpython/vdigit/main.py
===================================================================
--- grass/trunk/gui/wxpython/vdigit/main.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/vdigit/main.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -17,16 +17,20 @@
 try:
     from vdigit.wxdigit import IVDigit, GV_LINES, CFUNCTYPE
     haveVDigit = True
-    errorMsg   = ''
+    errorMsg = ''
 except (ImportError, NameError) as err:
     haveVDigit = False
-    errorMsg   = err
-    GV_LINES   = -1
+    errorMsg = err
+    GV_LINES = -1
+
     class IVDigit:
+
         def __init__(self):
             pass
 
+
 class VDigit(IVDigit):
+
     def __init__(self, mapwindow):
         """Base class of vector digitizer
 

Modified: grass/trunk/gui/wxpython/vdigit/mapwindow.py
===================================================================
--- grass/trunk/gui/wxpython/vdigit/mapwindow.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/vdigit/mapwindow.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -19,30 +19,32 @@
 
 from grass.pydispatch.signal import Signal
 
-from dbmgr.dialogs  import DisplayAttributesDialog
-from core.gcmd      import RunCommand, GMessage, GError
-from core.debug     import Debug
+from dbmgr.dialogs import DisplayAttributesDialog
+from core.gcmd import RunCommand, GMessage, GError
+from core.debug import Debug
 from mapwin.buffered import BufferedMapWindow
-from core.settings  import UserSettings
-from core.utils     import ListOfCatsToRange, _
+from core.settings import UserSettings
+from core.utils import ListOfCatsToRange, _
 from core.globalvar import QUERYLAYER
 from vdigit.dialogs import VDigitCategoryDialog, VDigitZBulkDialog, VDigitDuplicatesDialog
-from gui_core       import gselect
+from gui_core import gselect
 
+
 class VDigitWindow(BufferedMapWindow):
     """A Buffered window extended for vector digitizer.
     """
+
     def __init__(self, parent, giface, Map, properties, tree=None,
                  id=wx.ID_ANY, lmgr=None,
-                 style = wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):
+                 style=wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):
         BufferedMapWindow.__init__(self, parent=parent, giface=giface, Map=Map,
                                    properties=properties,
                                    style=style, **kwargs)
         self.lmgr = lmgr
         self.tree = tree
         self.pdcVector = wx.PseudoDC()
-        self.toolbar   = self.parent.GetToolbar('vdigit')
-        self.digit     = None # wxvdigit.IVDigit
+        self.toolbar = self.parent.GetToolbar('vdigit')
+        self.digit = None  # wxvdigit.IVDigit
         self._digitizingInfo = False  # digitizing with info
 
         # Emitted when info about digitizing updated
@@ -68,7 +70,7 @@
     def GetDigit(self):
         """Get digit class"""
         return self.digit
-    
+
     def SetToolbar(self, toolbar):
         """Set up related toolbar
         """
@@ -96,7 +98,7 @@
                                      (e, n), screen=False)[0]
         distance_tot = distance_seg
         for idx in range(1, len(self.polycoords)):
-            distance_tot += self.Distance(self.polycoords[idx-1],
+            distance_tot += self.Distance(self.polycoords[idx - 1],
                                           self.polycoords[idx],
                                           screen=False)[0]
         text = "seg: %.*f; tot: %.*f" % (precision, distance_seg,
@@ -107,24 +109,24 @@
         """Key pressed"""
         shift = event.ShiftDown()
         kc = event.GetKeyCode()
-        
+
         event = None
         if not shift:
             if kc == ord('P'):
-                event = wx.CommandEvent(winid = self.toolbar.addPoint)
+                event = wx.CommandEvent(winid=self.toolbar.addPoint)
                 tool = self.toolbar.OnAddPoint
             elif kc == ord('L'):
-                event = wx.CommandEvent(winid = self.toolbar.addLine)
+                event = wx.CommandEvent(winid=self.toolbar.addLine)
                 tool = self.toolbar.OnAddLine
         if event:
             self.toolbar.OnTool(event)
             tool(event)
-        
+
     def _updateMap(self):
         if not self.toolbar or \
                 not self.toolbar.GetLayer():
             return
-        
+
         # set region
         self.digit.GetDisplay().UpdateRegion()
         # re-calculate threshold for digitization tool
@@ -132,20 +134,21 @@
         # draw map
         # self.pdcVector.Clear()
         self.pdcVector.RemoveAll()
-        
+
         item = None
         if self.tree:
             try:
-                item = self.tree.FindItemByData('maplayer', self.toolbar.GetLayer())
+                item = self.tree.FindItemByData(
+                    'maplayer', self.toolbar.GetLayer())
             except TypeError:
                 pass
-        
+
         if not self.tree or \
-                (self.tree and item and \
-                     self.tree.IsItemChecked(item)):
+                (self.tree and item and
+                 self.tree.IsItemChecked(item)):
             self.redrawAll = True
             self.digit.GetDisplay().DrawMap()
-        
+
         # translate tmp objects (pointer position)
         if self.toolbar.GetAction() == 'moveLine' and \
                 hasattr(self, "moveInfo"):
@@ -156,7 +159,7 @@
                                             self.moveInfo['beginDiff'][0],
                                             self.moveInfo['beginDiff'][1])
                 del self.moveInfo['beginDiff']
-        
+
     def OnLeftDownAddLine(self, event):
         """Left mouse button pressed - add new feature
         """
@@ -164,32 +167,42 @@
             mapLayer = self.toolbar.GetLayer().GetName()
         except:
             return
-        
+
         if self.toolbar.GetAction('type') in ['point', 'centroid']:
             # add new point / centroiud
             east, north = self.Pixel2Cell(self.mouse['begin'])
-            nfeat, fids = self.digit.AddFeature(self.toolbar.GetAction('type'), [(east, north)])
+            nfeat, fids = self.digit.AddFeature(
+                self.toolbar.GetAction('type'),
+                [(east, north)])
             if nfeat < 1:
                 return
-            
-            self.UpdateMap(render = False) # redraw map
-            
+
+            self.UpdateMap(render=False)  # redraw map
+
             # add new record into atribute table
-            if UserSettings.Get(group = 'vdigit', key = "addRecord", subkey = 'enabled'):
+            if UserSettings.Get(
+                    group='vdigit', key="addRecord", subkey='enabled'):
                 # select attributes based on layer and category
-                cats = { fids[0] : {
-                        UserSettings.Get(group = 'vdigit', key = "layer", subkey = 'value') :
-                            (UserSettings.Get(group = 'vdigit', key = "category", subkey = 'value'), )
-                        }}
-                
-                posWindow = self.ClientToScreen((self.mouse['end'][0] + self.dialogOffset,
-                                                 self.mouse['end'][1] + self.dialogOffset))
-                
-                addRecordDlg = DisplayAttributesDialog(parent = self, map = mapLayer,
-                                                       cats = cats,
-                                                       pos = posWindow,
-                                                       action = "add", ignoreError = True)
-                
+                cats = {
+                    fids[0]: {
+                        UserSettings.Get(
+                            group='vdigit',
+                            key="layer",
+                            subkey='value'): (
+                            UserSettings.Get(
+                                group='vdigit',
+                                key="category",
+                                subkey='value'),
+                        )}}
+
+                posWindow = self.ClientToScreen(
+                    (self.mouse['end'][0] + self.dialogOffset,
+                     self.mouse['end'][1] + self.dialogOffset))
+
+                addRecordDlg = DisplayAttributesDialog(
+                    parent=self, map=mapLayer, cats=cats, pos=posWindow,
+                    action="add", ignoreError=True)
+
                 if self.toolbar.GetAction('type') == 'centroid':
                     for fid in fids:
                         self._geomAttrb(fid, addRecordDlg, 'area')
@@ -201,24 +214,26 @@
 
         elif self.toolbar.GetAction('type') in ["line", "boundary", "area"]:
             # add new point to the line
-            self.polycoords.append(self.Pixel2Cell(event.GetPositionTuple()[:]))
-            self.DrawLines(pdc = self.pdcTmp)
-        
+            self.polycoords.append(
+                self.Pixel2Cell(
+                    event.GetPositionTuple()[:]))
+            self.DrawLines(pdc=self.pdcTmp)
+
     def _geomAttrb(self, fid, dialog, attrb):
         """Define geometry attributes
         """
         mapLayer = self.toolbar.GetLayer()
         if self.tree:
             item = self.tree.FindItemByData('maplayer', mapLayer)
-            vdigit = self.tree.GetLayerInfo(item, key = 'vdigit')
+            vdigit = self.tree.GetLayerInfo(item, key='vdigit')
         else:
             item = vdigit = None
-        
+
         if not vdigit or \
                 'geomAttr' not in vdigit or \
                 attrb not in vdigit['geomAttr']:
             return
-        
+
         val = -1
         if attrb == 'length':
             val = self.digit.GetLineLength(fid)
@@ -229,32 +244,37 @@
         elif attrb == 'perimeter':
             val = self.digit.GetAreaPerimeter(fid)
             type = 'length'
-        
+
         if val > 0:
-            layer = int(UserSettings.Get(group = 'vdigit', key = "layer", subkey = 'value'))
+            layer = int(
+                UserSettings.Get(
+                    group='vdigit',
+                    key="layer",
+                    subkey='value'))
             column = vdigit['geomAttr'][attrb]['column']
-            val = UnitsConvertValue(val, type, vdigit['geomAttr'][attrb]['units'])
+            val = UnitsConvertValue(
+                val, type, vdigit['geomAttr'][attrb]['units'])
             dialog.SetColumnValue(layer, column, val)
             dialog.OnReset()
-        
+
     def _geomAttrbUpdate(self, fids):
         """Update geometry atrributes of currently selected features
-        
+
         :param fid: list feature id
         """
         mapLayer = self.parent.toolbars['vdigit'].GetLayer()
-        vectorName =  mapLayer.GetName()
+        vectorName = mapLayer.GetName()
         if self.tree:
             item = self.tree.FindItemByData('maplayer', mapLayer)
-            vdigit = self.tree.GetLayerInfo(item, key = 'vdigit')
+            vdigit = self.tree.GetLayerInfo(item, key='vdigit')
         else:
             item = vdigit = None
-        
+
         if not vdigit or 'geomAttr' not in vdigit:
             return
-        
+
         dbInfo = gselect.VectorDBInfo(vectorName)
-        sqlfile = tempfile.NamedTemporaryFile(mode = "w")
+        sqlfile = tempfile.NamedTemporaryFile(mode="w")
         for fid in fids:
             for layer, cats in self.digit.GetLineCats(fid).iteritems():
                 table = dbInfo.GetTable(layer)
@@ -269,49 +289,50 @@
                     elif attrb == 'perimeter':
                         val = self.digit.GetAreaPerimeter(fid)
                         type = 'length'
-                    
+
                     if val < 0:
                         continue
                     val = UnitsConvertValue(val, type, item['units'])
-                    
+
                     for cat in cats:
-                        sqlfile.write('UPDATE %s SET %s = %f WHERE %s = %d;\n' % \
-                                          (table, item['column'], val,
-                                           dbInfo.GetKeyColumn(layer), cat))
-            
+                        sqlfile.write(
+                            'UPDATE %s SET %s = %f WHERE %s = %d;\n' %
+                            (table, item['column'], val, dbInfo.GetKeyColumn(layer), cat))
+
             sqlfile.file.flush()
             RunCommand('db.execute',
-                       parent = True,
-                       quiet = True,
-                       input = sqlfile.name)
-            
+                       parent=True,
+                       quiet=True,
+                       input=sqlfile.name)
+
     def _updateATM(self):
         """Update open Attribute Table Manager
-        
+
         .. todo::
             use AddDataRow() instead
         """
         if not self.lmgr:
             return
-        
+
         # update ATM
         digitVector = self.toolbar.GetLayer().GetName()
-                            
+
         for atm in self.lmgr.dialogs['atm']:
             atmVector = atm.GetVectorName()
             if atmVector == digitVector:
-                layer = UserSettings.Get(group = 'vdigit', key = "layer", subkey = 'value')
+                layer = UserSettings.Get(
+                    group='vdigit', key="layer", subkey='value')
                 # TODO: use AddDataRow instead
                 atm.LoadData(layer)
-        
+
     def OnLeftDownEditLine(self, event):
         """Left mouse button pressed - edit linear feature - add new
         vertex.
         """
         self.polycoords.append(self.Pixel2Cell(self.mouse['begin']))
         self.moveInfo['id'].append(wx.NewId())
-        self.DrawLines(pdc = self.pdcTmp)
-        
+        self.DrawLines(pdc=self.pdcTmp)
+
     def OnLeftDownMoveLine(self, event):
         """Left mouse button pressed - vector digitizer move
         feature/vertex, edit linear feature
@@ -319,17 +340,17 @@
         self.moveInfo = dict()
         # geographic coordinates of initial position (left-down)
         self.moveInfo['begin'] = None
-        # list of ids to modify    
+        # list of ids to modify
         self.moveInfo['id'] = list()
-        
+
         # set pen
         if self.toolbar.GetAction() in ["moveVertex", "editLine"]:
-            pcolor = UserSettings.Get(group = 'vdigit', key = "symbol",
-                                      subkey = ["highlight", "color"])
-            self.pen = self.polypen = wx.Pen(colour = pcolor,
-                                             width = 2, style = wx.SHORT_DASH)
+            pcolor = UserSettings.Get(group='vdigit', key="symbol",
+                                      subkey=["highlight", "color"])
+            self.pen = self.polypen = wx.Pen(colour=pcolor,
+                                             width=2, style=wx.SHORT_DASH)
             self.pdcTmp.SetPen(self.polypen)
-        
+
     def OnLeftDownDisplayCA(self, event):
         """Left mouse button pressed - vector digitizer display categories
         or attributes action
@@ -338,47 +359,50 @@
             mapLayer = self.toolbar.GetLayer().GetName()
         except:
             return
-        
+
         coords = self.Pixel2Cell(self.mouse['begin'])
-        
+
         # unselect
         self.digit.GetDisplay().SetSelected([])
-        
+
         # select feature by point
         cats = {}
-        self.digit.GetDisplay().SelectLineByPoint(coords) 
-        
+        self.digit.GetDisplay().SelectLineByPoint(coords)
+
         if not self.digit.GetDisplay().GetSelected():
             for key in ('attributes', 'category'):
                 if self.parent.dialogs[key] and \
                         self.parent.dialogs[key].IsShown():
                     self.parent.dialogs[key].Hide()
-            self.UpdateMap(render = False, renderVector = True)
+            self.UpdateMap(render=False, renderVector=True)
             return
-        
-        if UserSettings.Get(group = 'vdigit', key = 'checkForDupl',
-                            subkey = 'enabled'):
+
+        if UserSettings.Get(group='vdigit', key='checkForDupl',
+                            subkey='enabled'):
             lines = self.digit.GetDisplay().GetSelected()
         else:
-            lines = (self.digit.GetDisplay().GetSelected()[0],) # only first found
-                        
+            lines = (
+                self.digit.GetDisplay().GetSelected()[0],
+            )  # only first found
+
         for line in lines:
             cats[line] = self.digit.GetLineCats(line)
-        
-        posWindow = self.ClientToScreen((self.mouse['end'][0] + self.dialogOffset,
-                                         self.mouse['end'][1] + self.dialogOffset))
-        
+
+        posWindow = self.ClientToScreen(
+            (self.mouse['end'][0] + self.dialogOffset,
+             self.mouse['end'][1] + self.dialogOffset))
+
         if self.toolbar.GetAction() == "displayAttrs":
             # select attributes based on coordinates (all layers)
             if self.parent.dialogs['attributes'] is None:
                 self.parent.dialogs['attributes'] = \
-                    DisplayAttributesDialog(parent = self, map = mapLayer,
-                                            cats = cats,
-                                            action = "update")
+                    DisplayAttributesDialog(parent=self, map=mapLayer,
+                                            cats=cats,
+                                            action="update")
             else:
                 # upgrade dialog
-                self.parent.dialogs['attributes'].UpdateDialog(cats = cats)
-           
+                self.parent.dialogs['attributes'].UpdateDialog(cats=cats)
+
             if self.parent.dialogs['attributes'] and \
                     self.parent.dialogs['attributes'].mapDBInfo:
                 if len(cats.keys()) > 0:
@@ -389,20 +413,20 @@
                     if self.parent.dialogs['attributes'] and \
                             self.parent.dialogs['attributes'].IsShown():
                         self.parent.dialogs['attributes'].Hide()
-        
-        else: # displayCats
+
+        else:  # displayCats
             if self.parent.dialogs['category'] is None:
                 # open new dialog
-                dlg = VDigitCategoryDialog(parent = self,
-                                           vectorName = mapLayer,
-                                           cats = cats,
-                                           pos = posWindow,
-                                           title = _("Update categories"))
+                dlg = VDigitCategoryDialog(parent=self,
+                                           vectorName=mapLayer,
+                                           cats=cats,
+                                           pos=posWindow,
+                                           title=_("Update categories"))
                 self.parent.dialogs['category'] = dlg
             else:
                 # update currently open dialog
-                self.parent.dialogs['category'].UpdateDialog(cats = cats)
-                
+                self.parent.dialogs['category'].UpdateDialog(cats=cats)
+
             if self.parent.dialogs['category']:
                 if len(cats.keys()) > 0:
                     # highlight feature & re-draw map
@@ -411,9 +435,9 @@
                 else:
                     if self.parent.dialogs['category'].IsShown():
                         self.parent.dialogs['category'].Hide()
-        
-        self.UpdateMap(render = False, renderVector = True)
-        
+
+        self.UpdateMap(render=False, renderVector=True)
+
     def OnLeftDownCopyCA(self, event):
         """Left mouse button pressed - vector digitizer copy
         categories or attributes action
@@ -423,7 +447,7 @@
         else:
             self.copyCatsIds = []
             self.mouse['box'] = 'box'
-        
+
     def OnLeftDownCopyLine(self, event):
         """Left mouse button pressed - vector digitizer copy lines
         action
@@ -431,51 +455,51 @@
         if not hasattr(self, "copyIds"):
             self.copyIds = []
             self.layerTmp = None
-        
+
     def OnLeftDownBulkLine(self, event):
         """Left mouse button pressed - vector digitizer label 3D
         vector lines
         """
-        if len(self.polycoords) > 1: # start new line
+        if len(self.polycoords) > 1:  # start new line
             self.polycoords = []
-            self.ClearLines(pdc = self.pdcTmp)
+            self.ClearLines(pdc=self.pdcTmp)
         self.polycoords.append(self.Pixel2Cell(event.GetPositionTuple()[:]))
         if len(self.polycoords) == 1:
             begin = self.Pixel2Cell(self.polycoords[-1])
-            end   = self.Pixel2Cell(self.mouse['end'])
+            end = self.Pixel2Cell(self.mouse['end'])
         else:
-            end   = self.Pixel2Cell(self.polycoords[-1])
+            end = self.Pixel2Cell(self.polycoords[-1])
             begin = self.Pixel2Cell(self.mouse['begin'])
-            
-            self.DrawLines(self.pdcTmp, polycoords = (begin, end))
-        
+
+            self.DrawLines(self.pdcTmp, polycoords=(begin, end))
+
     def OnLeftDownUndo(self, event):
         """Left mouse button pressed with control key - vector
         digitizer undo functionality
         """
         if self.mouse["use"] != "pointer" or not self.toolbar:
             return
-        
+
         action = self.toolbar.GetAction()
-        if (action == "addLine" and \
-                self.toolbar.GetAction('type') in ["line", "boundary", "area"]) or \
-                action == "editLine":
+        if (action == "addLine" and self.toolbar.GetAction('type')
+                in ["line", "boundary", "area"]) or action == "editLine":
             # add line or boundary -> remove last point from the line
             try:
                 removed = self.polycoords.pop()
-                Debug.msg(4, "VDigitWindow.OnMiddleDown(): polycoords_poped=%s" %
-                          [removed, ])
+                Debug.msg(
+                    4, "VDigitWindow.OnMiddleDown(): polycoords_poped=%s" %
+                    [removed, ])
                 # self.mouse['begin'] = self.Cell2Pixel(self.polycoords[-1])
             except:
                 pass
-            
+
         if action == "editLine":
             # remove last vertex & line
             if len(self.moveInfo['id']) > 1:
                 self.moveInfo['id'].pop()
-                
-            self.UpdateMap(render = False, renderVector = False)
-            
+
+            self.UpdateMap(render=False, renderVector=False)
+
         elif action in ["deleteLine", "deleteArea", "moveLine", "splitLine",
                         "addVertex", "removeVertex", "moveVertex",
                         "copyCats", "flipLine", "mergeLine",
@@ -483,36 +507,36 @@
                         "queryLine", "breakLine", "typeConv"]:
             # various tools -> unselected selected features
             self.digit.GetDisplay().SetSelected([])
-            
+
             if action in ["moveLine", "moveVertex", "editLine"] and \
                     hasattr(self, "moveInfo"):
                 del self.moveInfo
-                
+
             elif action == "copyCats":
                 try:
                     del self.copyCatsList
                     del self.copyCatsIds
                 except AttributeError:
                     pass
-                
+
             elif action == "copyLine":
                 del self.copyIds
                 if self.layerTmp:
                     self.Map.DeleteLayer(self.layerTmp)
-                    self.UpdateMap(render = True, renderVector = False)
+                    self.UpdateMap(render=True, renderVector=False)
                 del self.layerTmp
 
             self.polycoords = []
-            self.UpdateMap(render = False) # render vector
-        
+            self.UpdateMap(render=False)  # render vector
+
         elif action == "zbulkLine":
             # reset polyline
             self.polycoords = []
             self.digit.GetDisplay().SetSelected([])
-            self.UpdateMap(render = False)
-        
+            self.UpdateMap(render=False)
+
         self.redrawAll = True
-        self.UpdateMap(render = False, renderVector = False)
+        self.UpdateMap(render=False, renderVector=False)
 
     def _onLeftDown(self, event):
         """Left mouse button donw - vector digitizer various actions
@@ -520,41 +544,54 @@
         try:
             mapLayer = self.toolbar.GetLayer().GetName()
         except:
-            GMessage(parent = self,
-                     message = _("No vector map selected for editing."))
+            GMessage(parent=self,
+                     message=_("No vector map selected for editing."))
             event.Skip()
             return
-        
+
         action = self.toolbar.GetAction()
-        
+
         if not action:
-            GMessage(parent = self,
-                     message = _("Nothing to do. "
-                                 "Choose appropriate tool from digitizer toolbar."))
+            GMessage(
+                parent=self, message=_(
+                    "Nothing to do. "
+                    "Choose appropriate tool from digitizer toolbar."))
             event.Skip()
             return
-        
+
         if action not in ("moveVertex",
                           "addVertex",
                           "removeVertex",
                           "editLine"):
             # set pen
-            self.pen = wx.Pen(colour = UserSettings.Get(group = 'vdigit', key = 'symbol',
-                                                        subkey = ['newSegment', 'color']),
-                              width = 2, style = wx.SHORT_DASH)
-            self.polypen = wx.Pen(colour = UserSettings.Get(group = 'vdigit', key = 'symbol',
-                                                            subkey = ['newLine', 'color']),
-                                  width = 2, style = wx.SOLID)
-        
+            self.pen = wx.Pen(
+                colour=UserSettings.Get(
+                    group='vdigit',
+                    key='symbol',
+                    subkey=[
+                        'newSegment',
+                        'color']),
+                width=2,
+                style=wx.SHORT_DASH)
+            self.polypen = wx.Pen(
+                colour=UserSettings.Get(
+                    group='vdigit',
+                    key='symbol',
+                    subkey=[
+                        'newLine',
+                        'color']),
+                width=2,
+                style=wx.SOLID)
+
         if action in ("addVertex",
                       "removeVertex",
                       "splitLines"):
             # unselect
             self.digit.GetDisplay().SetSelected([])
-        
+
         if action == "addLine":
             self.OnLeftDownAddLine(event)
-        
+
         elif action == "editLine" and \
                 hasattr(self, "moveInfo"):
             self.OnLeftDownEditLine(event)
@@ -562,53 +599,56 @@
         elif action in ("moveLine", "moveVertex", "editLine") and \
                 not hasattr(self, "moveInfo"):
             self.OnLeftDownMoveLine(event)
-        
+
         elif action in ("displayAttrs"
                         "displayCats"):
             self.OnLeftDownDisplayCA(event)
-            
+
         elif action in ("copyCats",
                         "copyAttrs"):
             self.OnLeftDownCopyCA(event)
-            
+
         elif action == "copyLine":
             self.OnLeftDownCopyLine(event)
-            
+
         elif action == "zbulkLine":
             self.OnLeftDownBulkLine(event)
-        
+
     def OnLeftUpVarious(self, event):
         """Left mouse button released - vector digitizer various
         actions
         """
         pos1 = self.Pixel2Cell(self.mouse['begin'])
         pos2 = self.Pixel2Cell(self.mouse['end'])
-        
+
         nselected = 0
         action = self.toolbar.GetAction()
         # -> delete line || move line || move vertex
         if action in ("moveVertex",
                       "editLine"):
             if len(self.digit.GetDisplay().GetSelected()) == 0:
-                nselected = int(self.digit.GetDisplay().SelectLineByPoint(pos1)['line'] != -1)
-                
+                nselected = int(
+                    self.digit.GetDisplay().SelectLineByPoint(pos1)['line'] != -1)
+
                 if action == "editLine":
                     try:
-                        selVertex = self.digit.GetDisplay().GetSelectedVertex(pos1)[0]
+                        selVertex = self.digit.GetDisplay(
+                        ).GetSelectedVertex(pos1)[0]
                     except IndexError:
                         selVertex = None
-                        
+
                     if selVertex:
                         # self.UpdateMap(render=False)
-                        ids = self.digit.GetDisplay().GetSelected(grassId = False)
+                        ids = self.digit.GetDisplay().GetSelected(grassId=False)
                         # move this line to tmp layer
                         self.polycoords = []
                         for id in ids:
-                            if id % 2: # register only vertices
-                                e, n = self.Pixel2Cell(self.pdcVector.GetIdBounds(id)[0:2])
+                            if id % 2:  # register only vertices
+                                e, n = self.Pixel2Cell(
+                                    self.pdcVector.GetIdBounds(id)[0:2])
                                 self.polycoords.append((e, n))
-                        self.digit.GetDisplay().DrawSelected(False) 
-                                
+                        self.digit.GetDisplay().DrawSelected(False)
+
                         if selVertex < ids[-1] / 2:
                             # choose first or last node of line
                             self.moveInfo['id'].reverse()
@@ -617,14 +657,15 @@
                         # unselect
                         self.digit.GetDisplay().SetSelected([])
                         del self.moveInfo
-                
-                    self.UpdateMap(render = False)
-            
+
+                    self.UpdateMap(render=False)
+
         elif action in ("copyCats",
                         "copyAttrs"):
             if not hasattr(self, "copyCatsIds"):
                 # 'from' -> select by point
-                nselected = int(self.digit.GetDisplay().SelectLineByPoint(pos1)['line'] != -1)
+                nselected = int(
+                    self.digit.GetDisplay().SelectLineByPoint(pos1)['line'] != -1)
                 if nselected:
                     self.copyCatsList = self.digit.GetDisplay().GetSelected()
             else:
@@ -633,17 +674,18 @@
                 # return number of selected features (by box/point)
                 nselected = self.digit.GetDisplay().SelectLinesByBox((pos1, pos2))
                 if nselected == 0:
-                    nselected = int(self.digit.GetDisplay().SelectLineByPoint(pos1)['line'] != -1)
-                        
+                    nselected = int(
+                        self.digit.GetDisplay().SelectLineByPoint(pos1)['line'] != -1)
+
                 if nselected > 0:
                     self.copyCatsIds = self.digit.GetDisplay().GetSelected()
-        
+
         elif action == "queryLine":
-            selected = self.digit.SelectLinesByQuery(bbox = (pos1, pos2))
+            selected = self.digit.SelectLinesByQuery(bbox=(pos1, pos2))
             nselected = len(selected)
             if nselected > 0:
                 self.digit.GetDisplay().SetSelected(selected)
-        
+
         else:
             # -> moveLine || deleteLine, etc. (select by point/box)
             if action == 'moveLine' and \
@@ -651,17 +693,19 @@
                 nselected = 0
             else:
                 if action == 'deleteArea':
-                    nselected = int(self.digit.GetDisplay().SelectAreaByPoint(pos1)['area'] != -1)
+                    nselected = int(
+                        self.digit.GetDisplay().SelectAreaByPoint(pos1)['area'] != -1)
                 else:
                     if action == 'moveLine':
                         drawSeg = True
                     else:
                         drawSeg = False
-                        
-                    nselected = self.digit.GetDisplay().SelectLinesByBox(bbox = (pos1, pos2),
-                                                                         drawSeg = drawSeg)
+
+                    nselected = self.digit.GetDisplay().SelectLinesByBox(
+                        bbox=(pos1, pos2), drawSeg=drawSeg)
                     if nselected == 0:
-                        nselected = int(self.digit.GetDisplay().SelectLineByPoint(pos1)['line'] != -1)
+                        nselected = int(
+                            self.digit.GetDisplay().SelectLineByPoint(pos1)['line'] != -1)
 
         if nselected > 0:
             if action in ("moveLine", "moveVertex") and \
@@ -669,121 +713,139 @@
                 # get pseudoDC id of objects which should be redrawn
                 if action == "moveLine":
                     # -> move line
-                    self.moveInfo['id'] = self.digit.GetDisplay().GetSelected(grassId = False)
-                else: # moveVertex
-                    self.moveInfo['id'] = self.digit.GetDisplay().GetSelectedVertex(pos1)
-                    if len(self.moveInfo['id']) == 0: # no vertex found
+                    self.moveInfo['id'] = self.digit.GetDisplay(
+                    ).GetSelected(grassId=False)
+                else:  # moveVertex
+                    self.moveInfo['id'] = self.digit.GetDisplay(
+                    ).GetSelectedVertex(pos1)
+                    if len(self.moveInfo['id']) == 0:  # no vertex found
                         self.digit.GetDisplay().SetSelected([])
-            
+
             #
             # check for duplicates
             #
-            if UserSettings.Get(group = 'vdigit', key = 'checkForDupl', subkey = 'enabled'):
+            if UserSettings.Get(
+                    group='vdigit', key='checkForDupl', subkey='enabled'):
                 dupl = self.digit.GetDisplay().GetDuplicates()
-                self.UpdateMap(render = False)
-                    
+                self.UpdateMap(render=False)
+
                 if dupl:
-                    posWindow = self.ClientToScreen((self.mouse['end'][0] + self.dialogOffset,
-                                                     self.mouse['end'][1] + self.dialogOffset))
-                    
-                    dlg = VDigitDuplicatesDialog(parent = self, data = dupl, pos = posWindow)
-                    
+                    posWindow = self.ClientToScreen(
+                        (self.mouse['end'][0] + self.dialogOffset,
+                         self.mouse['end'][1] + self.dialogOffset))
+
+                    dlg = VDigitDuplicatesDialog(
+                        parent=self, data=dupl, pos=posWindow)
+
                     if dlg.ShowModal() == wx.ID_OK:
                         self.digit.GetDisplay().UnSelect(dlg.GetUnSelected())
                         # update selected
-                        self.UpdateMap(render = False)
-                
+                        self.UpdateMap(render=False)
+
             if action != "editLine":
                 # -> move line || move vertex
-                self.UpdateMap(render = False)
-        
-        else: # no vector object found
+                self.UpdateMap(render=False)
+
+        else:  # no vector object found
             if not (action in ("moveLine",
-                               "moveVertex") and \
-                        hasattr(self, "moveInfo") and \
-                        len(self.moveInfo['id']) > 0):
+                               "moveVertex") and
+                    hasattr(self, "moveInfo") and
+                    len(self.moveInfo['id']) > 0):
                 # avoid left-click when features are already selected
-                self.UpdateMap(render = False, renderVector = False)
-        
+                self.UpdateMap(render=False, renderVector=False)
+
     def OnLeftUpModifyLine(self, event):
         """Left mouse button released - vector digitizer split line,
         add/remove vertex action
         """
         pos1 = self.Pixel2Cell(self.mouse['begin'])
-        
+
         pointOnLine = self.digit.GetDisplay().SelectLineByPoint(pos1)['point']
         if not pointOnLine:
             return
-        
+
         if self.toolbar.GetAction() in ["splitLine", "addVertex"]:
-            self.UpdateMap(render = False) # highlight object
-            self.DrawCross(pdc = self.pdcTmp, coords = self.Cell2Pixel((pointOnLine[0], pointOnLine[1])),
-                           size = 5)
-        else: # removeVertex
+            self.UpdateMap(render=False)  # highlight object
+            self.DrawCross(
+                pdc=self.pdcTmp, coords=self.Cell2Pixel(
+                    (pointOnLine[0], pointOnLine[1])), size=5)
+        else:  # removeVertex
             # get only id of vertex
             try:
                 id = self.digit.GetDisplay().GetSelectedVertex(pos1)[0]
             except IndexError:
                 id = None
-            
+
             if id:
                 x, y = self.pdcVector.GetIdBounds(id)[0:2]
                 self.pdcVector.RemoveId(id)
-                self.UpdateMap(render = False) # highlight object
-                self.DrawCross(pdc = self.pdcTmp, coords = (x, y),
-                               size = 5)
+                self.UpdateMap(render=False)  # highlight object
+                self.DrawCross(pdc=self.pdcTmp, coords=(x, y),
+                               size=5)
             else:
                 # unselect
                 self.digit.GetDisplay().SetSelected([])
-                self.UpdateMap(render = False)
-        
+                self.UpdateMap(render=False)
+
     def OnLeftUpCopyLine(self, event):
         """Left mouse button released - vector digitizer copy feature
         action
         """
         pos1 = self.Pixel2Cell(self.mouse['begin'])
         pos2 = self.Pixel2Cell(self.mouse['end'])
-        
-        if UserSettings.Get(group = 'vdigit', key = 'bgmap',
+
+        if UserSettings.Get(group='vdigit', key='bgmap',
                             subkey='value', settings_type='internal') == '':
             # no background map -> copy from current vector map layer
             nselected = self.digit.GetDisplay().SelectLinesByBox((pos1, pos2))
-            
+
             if nselected > 0:
                 # highlight selected features
-                self.UpdateMap(render = False)
+                self.UpdateMap(render=False)
             else:
-                self.UpdateMap(render = False, renderVector = False)
+                self.UpdateMap(render=False, renderVector=False)
         else:
             # copy features from background map
-            self.copyIds = self.digit.SelectLinesFromBackgroundMap(bbox = (pos1, pos2))
+            self.copyIds = self.digit.SelectLinesFromBackgroundMap(
+                bbox=(pos1,
+                      pos2))
             if len(self.copyIds) > 0:
-                color = UserSettings.Get(group = 'vdigit', key = 'symbol',
-                                         subkey = ['highlight', 'color'])
-                colorStr = str(color[0]) + ":" + str(color[1]) + ":" + str(color[2])
-                dVectTmp = ['d.vect',
-                            'map=%s' % UserSettings.Get(group = 'vdigit', key = 'bgmap',
-                                                        subkey='value', settings_type='internal'),
-                            'cats=%s' % ListOfCatsToRange(self.copyIds),
-                            '-i',
-                            'color=%s' % colorStr,
-                            'fill_color=%s' % colorStr,
-                            'type=point,line,boundary,centroid',
-                            'width=2']
-                
+                color = UserSettings.Get(group='vdigit', key='symbol',
+                                         subkey=['highlight', 'color'])
+                colorStr = str(color[0]) + ":" + str(color[1]
+                                                     ) + ":" + str(color[2])
+                dVectTmp = [
+                    'd.vect',
+                    'map=%s' %
+                    UserSettings.Get(
+                        group='vdigit',
+                        key='bgmap',
+                        subkey='value',
+                        settings_type='internal'),
+                    'cats=%s' %
+                    ListOfCatsToRange(
+                        self.copyIds),
+                    '-i',
+                    'color=%s' %
+                    colorStr,
+                    'fill_color=%s' %
+                    colorStr,
+                    'type=point,line,boundary,centroid',
+                    'width=2']
+
                 if not self.layerTmp:
-                    self.layerTmp = self.Map.AddLayer(ltype = 'vector',
-                                                      name = QUERYLAYER,
-                                                      command = dVectTmp)
+                    self.layerTmp = self.Map.AddLayer(ltype='vector',
+                                                      name=QUERYLAYER,
+                                                      command=dVectTmp)
                 else:
                     self.layerTmp.SetCmd(dVectTmp)
             else:
                 if self.layerTmp:
                     self.Map.DeleteLayer(self.layerTmp)
                     self.layerTmp = None
-            
-            self.UpdateMap(render = True, renderVector = True)
-            
+
+            self.UpdateMap(render=True, renderVector=True)
+
     def OnLeftUpBulkLine(self, event):
         """Left mouse button released - vector digitizer z-bulk line
         action
@@ -792,33 +854,34 @@
         pos1 = self.polycoords[0]
         pos2 = self.polycoords[1]
         nselected = self.digit.GetDisplay().SelectLinesByBox((pos1, pos2))
-        
+
         if nselected > 0:
             # highlight selected features
-            self.UpdateMap(render = False)
-            self.DrawLines(pdc = self.pdcTmp) # redraw temp line
+            self.UpdateMap(render=False)
+            self.DrawLines(pdc=self.pdcTmp)  # redraw temp line
         else:
-            self.UpdateMap(render = False, renderVector = False)
-            
+            self.UpdateMap(render=False, renderVector=False)
+
     def OnLeftUpConnectLine(self, event):
         """Left mouse button released - vector digitizer connect line
         action
         """
         if len(self.digit.GetDisplay().GetSelected()) > 0:
-            self.UpdateMap(render = False)
-        
+            self.UpdateMap(render=False)
+
     def _onLeftUp(self, event):
         """Left mouse button released"""
         if event.ControlDown():
             return
-        
+
         if hasattr(self, "moveInfo"):
             if len(self.digit.GetDisplay().GetSelected()) == 0:
-                self.moveInfo['begin'] = self.Pixel2Cell(self.mouse['begin']) # left down
-            
+                self.moveInfo['begin'] = self.Pixel2Cell(
+                    self.mouse['begin'])  # left down
+
             # eliminate initial mouse moving efect
-            self.mouse['begin'] = self.mouse['end'] 
-        
+            self.mouse['begin'] = self.mouse['end']
+
         action = self.toolbar.GetAction()
         if action in ("deleteLine",
                       "deleteArea",
@@ -835,25 +898,25 @@
                       "typeConv",
                       "connectLine"):
             self.OnLeftUpVarious(event)
-        
+
         elif action in ("splitLine",
                         "addVertex",
                         "removeVertex"):
             self.OnLeftUpModifyLine(event)
-        
+
         elif action == "copyLine":
             self.OnLeftUpCopyLine(event)
-            
+
         elif action == "zbulkLine" and \
                 len(self.polycoords) == 2:
             self.OnLeftUpBulkLine(event)
-        
+
         elif action == "connectLine":
             self.OnLeftUpConnectLine(event)
-        
+
         if len(self.digit.GetDisplay().GetSelected()) > 0:
             self.redrawAll = None
-        
+
     def _onRightDown(self, event):
         # digitization tool (confirm action)
         action = self.toolbar.GetAction()
@@ -861,10 +924,10 @@
                 hasattr(self, "moveInfo"):
             pFrom = self.moveInfo['begin']
             pTo = self.Pixel2Cell(event.GetPositionTuple())
-            
+
             move = (pTo[0] - pFrom[0],
                     pTo[1] - pFrom[1])
-            
+
             if action == "moveLine":
                 # move line
                 if self.digit.MoveSelectedLines(move) < 0:
@@ -874,11 +937,11 @@
                 fid = self.digit.MoveSelectedVertex(pFrom, move)
                 if fid < 0:
                     return
-                
-                self._geomAttrbUpdate([fid,])
-            
+
+                self._geomAttrbUpdate([fid, ])
+
             del self.moveInfo
-        
+
     def _onRightUp(self, event):
         """Right mouse button released (confirm action)
         """
@@ -890,44 +953,51 @@
                 mapName = self.toolbar.GetLayer().GetName()
             except:
                 mapName = None
-                GError(parent = self,
-                       message = _("No vector map selected for editing."))
-                    
+                GError(parent=self,
+                       message=_("No vector map selected for editing."))
+
             if mapName:
                 if self.toolbar.GetAction('type') == 'line':
                     line = True
                 else:
                     line = False
-                    
-                if len(self.polycoords) < 2: # ignore 'one-point' lines
+
+                if len(self.polycoords) < 2:  # ignore 'one-point' lines
                     return
-                    
-                nfeat, fids = self.digit.AddFeature(self.toolbar.GetAction('type'), self.polycoords)
+
+                nfeat, fids = self.digit.AddFeature(
+                    self.toolbar.GetAction('type'), self.polycoords)
                 if nfeat < 0:
                     return
-                    
+
                 position = self.Cell2Pixel(self.polycoords[-1])
                 self.polycoords = []
-                self.UpdateMap(render = False)
+                self.UpdateMap(render=False)
                 self.redrawAll = True
                 self.Refresh()
-                
+
                 # add new record into atribute table
                 if self._addRecord() and (line is True or (not line and nfeat > 0)):
-                    posWindow = self.ClientToScreen((position[0] + self.dialogOffset,
-                                                     position[1] + self.dialogOffset))
-                        
+                    posWindow = self.ClientToScreen(
+                        (position[0] + self.dialogOffset, position[1] + self.dialogOffset))
+
                     # select attributes based on layer and category
-                    cats = { fids[0] : {
-                            UserSettings.Get(group = 'vdigit', key = "layer", subkey = 'value') :
-                                (UserSettings.Get(group = 'vdigit', key = "category", subkey = 'value'), )
-                            }}
-                    
-                    addRecordDlg = DisplayAttributesDialog(parent = self, map = mapName,
-                                                           cats = cats,
-                                                           pos = posWindow,
-                                                           action = "add", ignoreError = True)
-                    
+                    cats = {
+                        fids[0]: {
+                            UserSettings.Get(
+                                group='vdigit',
+                                key="layer",
+                                subkey='value'): (
+                                UserSettings.Get(
+                                    group='vdigit',
+                                    key="category",
+                                    subkey='value'),
+                            )}}
+
+                    addRecordDlg = DisplayAttributesDialog(
+                        parent=self, map=mapName, cats=cats, pos=posWindow,
+                        action="add", ignoreError=True)
+
                     for fid in fids:
                         self._geomAttrb(fid, addRecordDlg, 'length')
                         # auto-placing centroid
@@ -962,30 +1032,30 @@
             fid = self.digit.RemoveVertex(self.Pixel2Cell(self.mouse['begin']))
             if fid < 0:
                 return
-            self._geomAttrbUpdate([fid,])
+            self._geomAttrbUpdate([fid, ])
         elif action in ("copyCats", "copyAttrs"):
             if action == 'copyCats':
                 if self.digit.CopyCats(self.copyCatsList,
-                                       self.copyCatsIds, copyAttrb = False) < 0:
+                                       self.copyCatsIds, copyAttrb=False) < 0:
                     return
             else:
                 if self.digit.CopyCats(self.copyCatsList,
-                                       self.copyCatsIds, copyAttrb = True) < 0:
+                                       self.copyCatsIds, copyAttrb=True) < 0:
                     return
-                
+
             del self.copyCatsList
             del self.copyCatsIds
-            
+
             self._updateATM()
-                
+
         elif action == "editLine" and \
                 hasattr(self, "moveInfo"):
             line = self.digit.GetDisplay().GetSelected()[0]
             if self.digit.EditLine(line, self.polycoords) < 0:
                 return
-                
+
             del self.moveInfo
-                
+
         elif action == "flipLine":
             if self.digit.FlipLine() < 0:
                 return
@@ -1008,21 +1078,23 @@
             del self.copyIds
             if self.layerTmp:
                 self.Map.DeleteLayer(self.layerTmp)
-                self.UpdateMap(render = True, renderVector = False)
+                self.UpdateMap(render=True, renderVector=False)
             del self.layerTmp
-        
+
         elif action == "zbulkLine" and len(self.polycoords) == 2:
             pos1 = self.polycoords[0]
             pos2 = self.polycoords[1]
-            
+
             selected = self.digit.GetDisplay().GetSelected()
-            dlg = VDigitZBulkDialog(parent = self, title = _("Z bulk-labeling dialog"),
-                                    nselected = len(selected))
+            dlg = VDigitZBulkDialog(
+                parent=self,
+                title=_("Z bulk-labeling dialog"),
+                nselected=len(selected))
             if dlg.ShowModal() == wx.ID_OK:
                 if self.digit.ZBulkLines(pos1, pos2, dlg.value.GetValue(),
                                          dlg.step.GetValue()) < 0:
                     return
-            self.UpdateMap(render = False)
+            self.UpdateMap(render=False)
         elif action == "typeConv":
             # -> feature type conversion
             # - point <-> centroid
@@ -1034,8 +1106,8 @@
             # unselect and re-render
             self.digit.GetDisplay().SetSelected([])
             self.polycoords = []
-            self.UpdateMap(render = False)
-        
+            self.UpdateMap(render=False)
+
     def _onMouseMoving(self, event):
         self.mouse['end'] = event.GetPositionTuple()[:]
 
@@ -1046,13 +1118,14 @@
         if action == "addLine" and \
                 self.toolbar.GetAction('type') in ["line", "boundary", "area"]:
             if len(self.polycoords) > 0:
-                self.MouseDraw(pdc = self.pdcTmp, begin = self.Cell2Pixel(self.polycoords[-1]))
-        
+                self.MouseDraw(pdc=self.pdcTmp,
+                               begin=self.Cell2Pixel(self.polycoords[-1]))
+
         elif action in ["moveLine", "moveVertex", "editLine"] \
                 and hasattr(self, "moveInfo"):
             dx = self.mouse['end'][0] - self.mouse['begin'][0]
             dy = self.mouse['end'][1] - self.mouse['begin'][1]
-        
+
             # draw lines on new position
             if action == "moveLine" and \
                     len(self.moveInfo['id']) > 0:
@@ -1063,38 +1136,44 @@
                 # move vertex ->
                 # (vertex, left vertex, left line,
                 # right vertex, right line)
-                
+
                 # do not draw static lines
                 if action == "moveVertex" and \
                         len(self.moveInfo['id']) > 0:
                     self.polycoords = []
                     self.pdcTmp.RemoveId(self.moveInfo['id'][0])
-                    if self.moveInfo['id'][1] > 0: # previous vertex
-                        x, y = self.Pixel2Cell(self.pdcTmp.GetIdBounds(self.moveInfo['id'][1])[0:2])
+                    if self.moveInfo['id'][1] > 0:  # previous vertex
+                        x, y = self.Pixel2Cell(
+                            self.pdcTmp.GetIdBounds(
+                                self.moveInfo['id'][1])[
+                                0:2])
                         self.pdcTmp.RemoveId(self.moveInfo['id'][1] + 1)
                         self.polycoords.append((x, y))
                     self.polycoords.append(self.Pixel2Cell(self.mouse['end']))
 
-                    if self.moveInfo['id'][2] > 0: # next vertex
-                        x, y = self.Pixel2Cell(self.pdcTmp.GetIdBounds(self.moveInfo['id'][2])[0:2])
-                        self.pdcTmp.RemoveId(self.moveInfo['id'][2]-1)
+                    if self.moveInfo['id'][2] > 0:  # next vertex
+                        x, y = self.Pixel2Cell(
+                            self.pdcTmp.GetIdBounds(
+                                self.moveInfo['id'][2])[
+                                0:2])
+                        self.pdcTmp.RemoveId(self.moveInfo['id'][2] - 1)
                         self.polycoords.append((x, y))
-                    
-                    self.ClearLines(pdc = self.pdcTmp)
-                    self.DrawLines(pdc = self.pdcTmp)
-                        
+
+                    self.ClearLines(pdc=self.pdcTmp)
+                    self.DrawLines(pdc=self.pdcTmp)
+
                 if action == "editLine":
-                    self.MouseDraw(pdc = self.pdcTmp,
-                                   begin = self.Cell2Pixel(self.polycoords[-1]))
-                
-            self.Refresh() # TODO: use RefreshRect()
+                    self.MouseDraw(pdc=self.pdcTmp,
+                                   begin=self.Cell2Pixel(self.polycoords[-1]))
+
+            self.Refresh()  # TODO: use RefreshRect()
             self.mouse['begin'] = self.mouse['end']
-            
+
         elif action == "zbulkLine":
             if len(self.polycoords) == 1:
                 # draw mouse moving
                 self.MouseDraw(self.pdcTmp)
-                
+
     def _zoom(self, event):
         tmp1 = self.mouse['end']
         tmp2 = self.Cell2Pixel(self.moveInfo['begin'])
@@ -1103,6 +1182,7 @@
         self.moveInfo['beginDiff'] = (dx, dy)
         for id in self.moveInfo['id']:
             self.pdcTmp.RemoveId(id)
-        
+
     def _addRecord(self):
-        return UserSettings.Get(group = 'vdigit', key = "addRecord", subkey = 'enabled')
+        return UserSettings.Get(
+            group='vdigit', key="addRecord", subkey='enabled')

Modified: grass/trunk/gui/wxpython/vdigit/preferences.py
===================================================================
--- grass/trunk/gui/wxpython/vdigit/preferences.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/vdigit/preferences.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -19,27 +19,33 @@
 import wx
 import wx.lib.colourselect as csel
 
-from core             import globalvar
-from core.debug       import Debug
+from core import globalvar
+from core.debug import Debug
 from gui_core.gselect import ColumnSelect
-from core.units       import Units
-from core.settings    import UserSettings
+from core.units import Units
+from core.settings import UserSettings
 from core.utils import _
 
 
 class VDigitSettingsDialog(wx.Dialog):
-    def __init__(self, parent, giface, title = _("Digitization settings"),
-                 style = wx.DEFAULT_DIALOG_STYLE):
+
+    def __init__(self, parent, giface, title=_("Digitization settings"),
+                 style=wx.DEFAULT_DIALOG_STYLE):
         """Standard settings dialog for digitization purposes
         """
-        wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY, title = title, style = style)
+        wx.Dialog.__init__(
+            self,
+            parent=parent,
+            id=wx.ID_ANY,
+            title=title,
+            style=style)
 
         self._giface = giface
         self.parent = parent                     # MapFrame
         self.digit = self.parent.MapWindow.digit
-        
+
         # notebook
-        notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
+        notebook = wx.Notebook(parent=self, id=wx.ID_ANY, style=wx.BK_DEFAULT)
         self._createGeneralPage(notebook)
         self._createSymbologyPage(notebook)
         self.digit.SetCategory()
@@ -57,293 +63,504 @@
         btnApply.SetToolTipString(_("Apply changes for this session"))
         btnApply.SetDefault()
         btnSave.Bind(wx.EVT_BUTTON, self.OnSave)
-        btnSave.SetToolTipString(_("Close dialog and save changes to user settings file"))
+        btnSave.SetToolTipString(
+            _("Close dialog and save changes to user settings file"))
         btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel)
         btnCancel.SetToolTipString(_("Close dialog and ignore changes"))
-        
+
         # sizers
         btnSizer = wx.wx.BoxSizer(wx.HORIZONTAL)
-        btnSizer.Add(btnCancel, proportion = 0,
-                     flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
-        btnSizer.Add(btnApply, proportion = 0,
-                     flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
-        btnSizer.Add(btnSave, proportion = 0,
-                     flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
-        
+        btnSizer.Add(btnCancel, proportion=0,
+                     flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
+        btnSizer.Add(btnApply, proportion=0,
+                     flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
+        btnSizer.Add(btnSave, proportion=0,
+                     flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
+
         mainSizer = wx.BoxSizer(wx.VERTICAL)
-        mainSizer.Add(item = notebook, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
-        mainSizer.Add(item = btnSizer, proportion = 0,
-                      flag = wx.ALIGN_RIGHT, border = 5)
-        
+        mainSizer.Add(
+            item=notebook,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        mainSizer.Add(item=btnSizer, proportion=0,
+                      flag=wx.ALIGN_RIGHT, border=5)
+
         self.Bind(wx.EVT_CLOSE, self.OnCancel)
-        
+
         self.SetSizer(mainSizer)
         mainSizer.Fit(self)
 
     def _createSymbologyPage(self, notebook):
         """Create notebook page concerning symbology settings"""
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY)
-        notebook.AddPage(page = panel, text = _("Symbology"))
+        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
+        notebook.AddPage(page=panel, text=_("Symbology"))
 
         sizer = wx.BoxSizer(wx.VERTICAL)
-        
-        flexSizer = wx.FlexGridSizer (cols = 3, hgap = 5, vgap = 5)
+
+        flexSizer = wx.FlexGridSizer(cols=3, hgap=5, vgap=5)
         flexSizer.AddGrowableCol(0)
 
         self.symbology = {}
         for label, key in self._symbologyData():
             textLabel = wx.StaticText(panel, wx.ID_ANY, label)
-            color = csel.ColourSelect(panel, id = wx.ID_ANY,
-                                      colour = UserSettings.Get(group = 'vdigit', key = 'symbol',
-                                                                subkey = [key, 'color']),
-                                      size = (40, 25))
-            isEnabled = UserSettings.Get(group = 'vdigit', key = 'symbol',
-                                         subkey = [key, 'enabled'])
+            color = csel.ColourSelect(
+                panel, id=wx.ID_ANY, colour=UserSettings.Get(
+                    group='vdigit', key='symbol', subkey=[
+                        key, 'color']), size=(
+                    40, 25))
+            isEnabled = UserSettings.Get(group='vdigit', key='symbol',
+                                         subkey=[key, 'enabled'])
             if isEnabled is not None:
-                enabled = wx.CheckBox(panel, id = wx.ID_ANY, label = "")
+                enabled = wx.CheckBox(panel, id=wx.ID_ANY, label="")
                 enabled.SetValue(isEnabled)
                 self.symbology[key] = (enabled, color)
             else:
                 enabled = (1, 1)
                 self.symbology[key] = (None, color)
-            
-            flexSizer.Add(textLabel, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL)
-            flexSizer.Add(enabled, proportion = 0, flag = wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
-            flexSizer.Add(color, proportion = 0, flag = wx.ALIGN_RIGHT | wx.FIXED_MINSIZE)
+
+            flexSizer.Add(
+                textLabel,
+                proportion=0,
+                flag=wx.ALIGN_CENTER_VERTICAL)
+            flexSizer.Add(
+                enabled,
+                proportion=0,
+                flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
+            flexSizer.Add(
+                color,
+                proportion=0,
+                flag=wx.ALIGN_RIGHT | wx.FIXED_MINSIZE)
             color.SetName("GetColour")
-        
-        sizer.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 10)
-        
+
+        sizer.Add(
+            item=flexSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=10)
+
         panel.SetSizer(sizer)
-        
+
         return panel
 
     def _createGeneralPage(self, notebook):
         """Create notebook page concerning general settings"""
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY)
-        notebook.AddPage(page = panel, text = _("General"))
+        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
+        notebook.AddPage(page=panel, text=_("General"))
 
         border = wx.BoxSizer(wx.VERTICAL)
-        
+
         #
         # display section
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Display"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Display"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        flexSizer = wx.FlexGridSizer (cols = 3, hgap = 5, vgap = 5)
+        flexSizer = wx.FlexGridSizer(cols=3, hgap=5, vgap=5)
         flexSizer.AddGrowableCol(0)
         # line width
-        text = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Line width"))
-        self.lineWidthValue = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (75, -1),
-                                          initial = UserSettings.Get(group = 'vdigit', key = "lineWidth", subkey = 'value'),
-                                          min = 1, max = 1e6)
-        units = wx.StaticText(parent = panel, id = wx.ID_ANY, size = (115, -1),
-                              label = UserSettings.Get(group = 'vdigit', key = "lineWidth", subkey = 'units'),
-                              style = wx.ALIGN_LEFT)
-        flexSizer.Add(text, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL)
-        flexSizer.Add(self.lineWidthValue, proportion = 0, flag = wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
-        flexSizer.Add(units, proportion = 0, flag = wx.ALIGN_RIGHT | wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
-                      border = 10)
+        text = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Line width"))
+        self.lineWidthValue = wx.SpinCtrl(
+            parent=panel, id=wx.ID_ANY, size=(75, -1),
+            initial=UserSettings.Get(
+                group='vdigit', key="lineWidth", subkey='value'),
+            min=1, max=1e6)
+        units = wx.StaticText(
+            parent=panel, id=wx.ID_ANY, size=(115, -1),
+            label=UserSettings.Get(
+                group='vdigit', key="lineWidth", subkey='units'),
+            style=wx.ALIGN_LEFT)
+        flexSizer.Add(text, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
+        flexSizer.Add(
+            self.lineWidthValue,
+            proportion=0,
+            flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
+        flexSizer.Add(
+            units,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT | wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
+            border=10)
 
-        sizer.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
+        sizer.Add(
+            item=flexSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=1)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
 
         #
         # snapping section
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Snapping"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Snapping"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        flexSizer = wx.FlexGridSizer(cols = 3, hgap = 5, vgap = 5)
+        flexSizer = wx.FlexGridSizer(cols=3, hgap=5, vgap=5)
         flexSizer.AddGrowableCol(0)
 
         # snapping
-        text = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Snapping threshold"))
-        self.snappingValue = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (75, -1),
-                                         initial = UserSettings.Get(group = 'vdigit', key = "snapping", subkey = 'value'),
-                                         min = -1, max = 1e6)
+        text = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Snapping threshold"))
+        self.snappingValue = wx.SpinCtrl(
+            parent=panel, id=wx.ID_ANY, size=(75, -1),
+            initial=UserSettings.Get(
+                group='vdigit', key="snapping", subkey='value'),
+            min=-1, max=1e6)
         self.snappingValue.Bind(wx.EVT_SPINCTRL, self.OnChangeSnappingValue)
         self.snappingValue.Bind(wx.EVT_TEXT, self.OnChangeSnappingValue)
-        self.snappingUnit = wx.Choice(parent = panel, id = wx.ID_ANY, size = (125, -1),
-                                      choices = [_("screen pixels"), _("map units")])
-        self.snappingUnit.SetStringSelection(UserSettings.Get(group = 'vdigit', key = "snapping", subkey = 'units'))
+        self.snappingUnit = wx.Choice(parent=panel, id=wx.ID_ANY, size=(
+            125, -1), choices=[_("screen pixels"), _("map units")])
+        self.snappingUnit.SetStringSelection(
+            UserSettings.Get(
+                group='vdigit',
+                key="snapping",
+                subkey='units'))
         self.snappingUnit.Bind(wx.EVT_CHOICE, self.OnChangeSnappingUnits)
-        flexSizer.Add(text, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL)
-        flexSizer.Add(self.snappingValue, proportion = 0, flag = wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
-        flexSizer.Add(self.snappingUnit, proportion = 0, flag = wx.ALIGN_RIGHT | wx.FIXED_MINSIZE)
+        flexSizer.Add(text, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
+        flexSizer.Add(
+            self.snappingValue,
+            proportion=0,
+            flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
+        flexSizer.Add(
+            self.snappingUnit,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT | wx.FIXED_MINSIZE)
 
         vertexSizer = wx.BoxSizer(wx.VERTICAL)
-        self.snapVertex = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                      label = _("Snap also to vertex"))
-        self.snapVertex.SetValue(UserSettings.Get(group = 'vdigit', key = "snapToVertex", subkey = 'enabled'))
-        vertexSizer.Add(item = self.snapVertex, proportion = 0, flag = wx.EXPAND)
+        self.snapVertex = wx.CheckBox(parent=panel, id=wx.ID_ANY,
+                                      label=_("Snap also to vertex"))
+        self.snapVertex.SetValue(
+            UserSettings.Get(
+                group='vdigit',
+                key="snapToVertex",
+                subkey='enabled'))
+        vertexSizer.Add(item=self.snapVertex, proportion=0, flag=wx.EXPAND)
         self.mapUnits = self.parent.MapWindow.Map.GetProjInfo()['units']
-        self.snappingInfo = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                          label = _("Snapping threshold is %(value).1f %(units)s") % \
-                                              {'value' : self.digit.GetDisplay().GetThreshold(),
-                                               'units' : self.mapUnits})
-        vertexSizer.Add(item = self.snappingInfo, proportion = 0,
-                        flag = wx.ALL | wx.EXPAND, border = 1)
+        self.snappingInfo = wx.StaticText(
+            parent=panel, id=wx.ID_ANY,
+            label=_("Snapping threshold is %(value).1f %(units)s") %
+            {'value': self.digit.GetDisplay().GetThreshold(),
+             'units': self.mapUnits})
+        vertexSizer.Add(item=self.snappingInfo, proportion=0,
+                        flag=wx.ALL | wx.EXPAND, border=1)
 
-        sizer.Add(item = flexSizer, proportion = 1, flag = wx.EXPAND)
-        sizer.Add(item = vertexSizer, proportion = 1, flag = wx.EXPAND)
-        border.Add(item = sizer, proportion = 0, flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
+        sizer.Add(item=flexSizer, proportion=1, flag=wx.EXPAND)
+        sizer.Add(item=vertexSizer, proportion=1, flag=wx.EXPAND)
+        border.Add(item=sizer, proportion=0, flag=wx.LEFT |
+                   wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=5)
 
         #
         # select box
         #
-        box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Select vector features"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Select vector features"))
         # feature type
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
         inSizer = wx.BoxSizer(wx.HORIZONTAL)
         self.selectFeature = {}
         for feature in ('point', 'line',
                         'centroid', 'boundary'):
-            chkbox = wx.CheckBox(parent = panel, label = feature)
+            chkbox = wx.CheckBox(parent=panel, label=feature)
             self.selectFeature[feature] = chkbox.GetId()
-            chkbox.SetValue(UserSettings.Get(group = 'vdigit', key = 'selectType',
-                                             subkey = [feature, 'enabled']))
-            inSizer.Add(item = chkbox, proportion = 0,
-                        flag = wx.EXPAND | wx.ALL, border = 5)
-        sizer.Add(item = inSizer, proportion = 0, flag = wx.EXPAND)
+            chkbox.SetValue(UserSettings.Get(group='vdigit', key='selectType',
+                                             subkey=[feature, 'enabled']))
+            inSizer.Add(item=chkbox, proportion=0,
+                        flag=wx.EXPAND | wx.ALL, border=5)
+        sizer.Add(item=inSizer, proportion=0, flag=wx.EXPAND)
         # threshold
-        flexSizer = wx.FlexGridSizer (cols = 3, hgap = 5, vgap = 5)
+        flexSizer = wx.FlexGridSizer(cols=3, hgap=5, vgap=5)
         flexSizer.AddGrowableCol(0)
-        text = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Select threshold"))
-        self.selectThreshValue = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (75, -1),
-                                             initial = UserSettings.Get(group = 'vdigit', key = "selectThresh", subkey = 'value'),
-                                             min = 1, max = 1e6)
-        units = wx.StaticText(parent = panel, id = wx.ID_ANY, size = (115, -1),
-                              label = UserSettings.Get(group = 'vdigit', key = "lineWidth", subkey = 'units'),
-                              style = wx.ALIGN_LEFT)
-        flexSizer.Add(text, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL)
-        flexSizer.Add(self.selectThreshValue, proportion = 0, flag = wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
-        flexSizer.Add(units, proportion = 0, flag = wx.ALIGN_RIGHT | wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
-                      border = 10)
+        text = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Select threshold"))
+        self.selectThreshValue = wx.SpinCtrl(
+            parent=panel, id=wx.ID_ANY, size=(75, -1),
+            initial=UserSettings.Get(
+                group='vdigit', key="selectThresh", subkey='value'),
+            min=1, max=1e6)
+        units = wx.StaticText(
+            parent=panel, id=wx.ID_ANY, size=(115, -1),
+            label=UserSettings.Get(
+                group='vdigit', key="lineWidth", subkey='units'),
+            style=wx.ALIGN_LEFT)
+        flexSizer.Add(text, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
+        flexSizer.Add(self.selectThreshValue, proportion=0,
+                      flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
+        flexSizer.Add(
+            units,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT | wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
+            border=10)
 
-        self.selectIn = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                    label = _("Select only features inside of selection bounding box"))
-        self.selectIn.SetValue(UserSettings.Get(group = 'vdigit', key = "selectInside", subkey = 'enabled'))
-        self.selectIn.SetToolTipString(_("By default are selected all features overlapping selection bounding box "))
-        
-        self.checkForDupl = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                        label = _("Check for duplicates"))
-        self.checkForDupl.SetValue(UserSettings.Get(group = 'vdigit', key = "checkForDupl", subkey = 'enabled'))
+        self.selectIn = wx.CheckBox(parent=panel, id=wx.ID_ANY, label=_(
+            "Select only features inside of selection bounding box"))
+        self.selectIn.SetValue(
+            UserSettings.Get(
+                group='vdigit',
+                key="selectInside",
+                subkey='enabled'))
+        self.selectIn.SetToolTipString(
+            _("By default are selected all features overlapping selection bounding box "))
 
+        self.checkForDupl = wx.CheckBox(parent=panel, id=wx.ID_ANY,
+                                        label=_("Check for duplicates"))
+        self.checkForDupl.SetValue(
+            UserSettings.Get(
+                group='vdigit',
+                key="checkForDupl",
+                subkey='enabled'))
 
-        sizer.Add(item = flexSizer, proportion = 0, flag = wx.EXPAND)
-        sizer.Add(item = self.selectIn, proportion = 0, flag = wx.EXPAND | wx.ALL, border = 1)
-        sizer.Add(item = self.checkForDupl, proportion = 0, flag = wx.EXPAND | wx.ALL, border = 1)        
-        border.Add(item = sizer, proportion = 0, flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
+        sizer.Add(item=flexSizer, proportion=0, flag=wx.EXPAND)
+        sizer.Add(
+            item=self.selectIn,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=1)
+        sizer.Add(
+            item=self.checkForDupl,
+            proportion=0,
+            flag=wx.EXPAND | wx.ALL,
+            border=1)
+        border.Add(item=sizer, proportion=0, flag=wx.EXPAND |
+                   wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
 
         #
         # digitize lines box
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Digitize lines/boundaries"))
+        box = wx.StaticBox(
+            parent=panel, id=wx.ID_ANY, label=" %s " %
+            _("Digitize lines/boundaries"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
 
-        self.intersect = wx.CheckBox(parent = panel, label = _("Break lines at intersection"))
-        self.intersect.SetValue(UserSettings.Get(group = 'vdigit', key = 'breakLines', subkey = 'enabled'))
-        
-        sizer.Add(item = self.intersect, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 1)
+        self.intersect = wx.CheckBox(
+            parent=panel, label=_("Break lines at intersection"))
+        self.intersect.SetValue(
+            UserSettings.Get(
+                group='vdigit',
+                key='breakLines',
+                subkey='enabled'))
 
-        border.Add(item = sizer, proportion = 0, flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
+        sizer.Add(
+            item=self.intersect,
+            proportion=0,
+            flag=wx.ALL | wx.EXPAND,
+            border=1)
 
+        border.Add(item=sizer, proportion=0, flag=wx.EXPAND |
+                   wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
+
         #
         # digitize areas box
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Digitize areas"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Digitize areas"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
 
-        self.closeBoundary = wx.CheckBox(parent = panel, label = _("Close boundary (snap to the start node)"))
-        self.closeBoundary.SetValue(UserSettings.Get(group = 'vdigit', key = 'closeBoundary', subkey = 'enabled'))
-        
-        sizer.Add(item = self.closeBoundary, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 1)
+        self.closeBoundary = wx.CheckBox(
+            parent=panel, label=_("Close boundary (snap to the start node)"))
+        self.closeBoundary.SetValue(
+            UserSettings.Get(
+                group='vdigit',
+                key='closeBoundary',
+                subkey='enabled'))
 
-        border.Add(item = sizer, proportion = 0, flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
+        sizer.Add(
+            item=self.closeBoundary,
+            proportion=0,
+            flag=wx.ALL | wx.EXPAND,
+            border=1)
 
+        border.Add(item=sizer, proportion=0, flag=wx.EXPAND |
+                   wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
+
         #
         # save-on-exit box
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Save changes"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Save changes"))
         # save changes on exit?
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        self.save = wx.CheckBox(parent = panel, label = _("Save changes on exit"))
-        self.save.SetValue(UserSettings.Get(group = 'vdigit', key = 'saveOnExit', subkey = 'enabled'))
-        sizer.Add(item = self.save, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 1)
-        border.Add(item = sizer, proportion = 0, flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
+        self.save = wx.CheckBox(parent=panel, label=_("Save changes on exit"))
+        self.save.SetValue(
+            UserSettings.Get(
+                group='vdigit',
+                key='saveOnExit',
+                subkey='enabled'))
+        sizer.Add(
+            item=self.save,
+            proportion=0,
+            flag=wx.ALL | wx.EXPAND,
+            border=1)
+        border.Add(item=sizer, proportion=0, flag=wx.EXPAND |
+                   wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
 
         panel.SetSizer(border)
-        
+
         return panel
 
     def _createQueryPage(self, notebook):
         """Create notebook page for query tool"""
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY)
-        notebook.AddPage(page = panel, text = _("Query tool"))
+        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
+        notebook.AddPage(page=panel, text=_("Query tool"))
 
         border = wx.BoxSizer(wx.VERTICAL)
 
         #
         # query tool box
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Choose query tool"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Choose query tool"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
 
         LocUnits = self.parent.MapWindow.Map.GetProjInfo()['units']
 
-        self.queryBox = wx.CheckBox(parent = panel, id = wx.ID_ANY, label = _("Select by box"))
-        self.queryBox.SetValue(UserSettings.Get(group = 'vdigit', key = "query", subkey = 'box'))
+        self.queryBox = wx.CheckBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Select by box"))
+        self.queryBox.SetValue(
+            UserSettings.Get(
+                group='vdigit',
+                key="query",
+                subkey='box'))
 
-        sizer.Add(item = self.queryBox, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 1)
+        sizer.Add(
+            item=self.queryBox,
+            proportion=0,
+            flag=wx.ALL | wx.EXPAND,
+            border=1)
         sizer.Add((0, 5))
 
         #
         # length
         #
-        self.queryLength = wx.RadioButton(parent = panel, id = wx.ID_ANY, label = _("length"))
+        self.queryLength = wx.RadioButton(
+            parent=panel, id=wx.ID_ANY, label=_("length"))
         self.queryLength.Bind(wx.EVT_RADIOBUTTON, self.OnChangeQuery)
-        sizer.Add(item = self.queryLength, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 1)
-        flexSizer = wx.FlexGridSizer (cols = 4, hgap = 5, vgap = 5)
+        sizer.Add(
+            item=self.queryLength,
+            proportion=0,
+            flag=wx.ALL | wx.EXPAND,
+            border=1)
+        flexSizer = wx.FlexGridSizer(cols=4, hgap=5, vgap=5)
         flexSizer.AddGrowableCol(0)
-        txt = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Select lines"))
-        self.queryLengthSL = wx.Choice (parent = panel, id = wx.ID_ANY, 
-                                        choices  =  [_("shorter than"), _("longer than")])
-        self.queryLengthSL.SetSelection(UserSettings.Get(group = 'vdigit', key = "queryLength", subkey = 'than-selection'))
-        self.queryLengthValue = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (100, -1),
-                                            initial = 1,
-                                            min = 0, max = 1e6)
-        self.queryLengthValue.SetValue(UserSettings.Get(group = 'vdigit', key = "queryLength", subkey = 'thresh'))
-        units = wx.StaticText(parent = panel, id = wx.ID_ANY, label = "%s" % LocUnits)
-        flexSizer.Add(txt, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL)
-        flexSizer.Add(self.queryLengthSL, proportion = 0, flag = wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
-        flexSizer.Add(self.queryLengthValue, proportion = 0, flag = wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
-        flexSizer.Add(units, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL)
-        sizer.Add(item = flexSizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 1)
+        txt = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Select lines"))
+        self.queryLengthSL = wx.Choice(
+            parent=panel, id=wx.ID_ANY, choices=[
+                _("shorter than"), _("longer than")])
+        self.queryLengthSL.SetSelection(
+            UserSettings.Get(
+                group='vdigit',
+                key="queryLength",
+                subkey='than-selection'))
+        self.queryLengthValue = wx.SpinCtrl(
+            parent=panel, id=wx.ID_ANY, size=(
+                100, -1), initial=1, min=0, max=1e6)
+        self.queryLengthValue.SetValue(
+            UserSettings.Get(
+                group='vdigit',
+                key="queryLength",
+                subkey='thresh'))
+        units = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label="%s" %
+            LocUnits)
+        flexSizer.Add(txt, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
+        flexSizer.Add(
+            self.queryLengthSL,
+            proportion=0,
+            flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
+        flexSizer.Add(
+            self.queryLengthValue,
+            proportion=0,
+            flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
+        flexSizer.Add(units, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
+        sizer.Add(
+            item=flexSizer,
+            proportion=0,
+            flag=wx.ALL | wx.EXPAND,
+            border=1)
 
         #
         # dangle
         #
-        self.queryDangle = wx.RadioButton(parent = panel, id = wx.ID_ANY, label = _("dangle"))
+        self.queryDangle = wx.RadioButton(
+            parent=panel, id=wx.ID_ANY, label=_("dangle"))
         self.queryDangle.Bind(wx.EVT_RADIOBUTTON, self.OnChangeQuery)
-        sizer.Add(item = self.queryDangle, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 1)
-        flexSizer = wx.FlexGridSizer (cols = 4, hgap = 5, vgap = 5)
+        sizer.Add(
+            item=self.queryDangle,
+            proportion=0,
+            flag=wx.ALL | wx.EXPAND,
+            border=1)
+        flexSizer = wx.FlexGridSizer(cols=4, hgap=5, vgap=5)
         flexSizer.AddGrowableCol(0)
-        txt = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Select dangles"))
-        self.queryDangleSL = wx.Choice (parent = panel, id = wx.ID_ANY, 
-                                        choices = [_("shorter than"), _("longer than")])
-        self.queryDangleSL.SetSelection(UserSettings.Get(group = 'vdigit', key = "queryDangle", subkey = 'than-selection'))
-        self.queryDangleValue = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (100, -1),
-                                       initial = 1,
-                                       min = 0, max = 1e6)
-        self.queryDangleValue.SetValue(UserSettings.Get(group = 'vdigit', key = "queryDangle", subkey = 'thresh'))
-        units = wx.StaticText(parent = panel, id = wx.ID_ANY, label = "%s" % LocUnits)
-        flexSizer.Add(txt, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL)
-        flexSizer.Add(self.queryDangleSL, proportion = 0, flag = wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
-        flexSizer.Add(self.queryDangleValue, proportion = 0, flag = wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
-        flexSizer.Add(units, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL)
-        sizer.Add(item = flexSizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 1)
+        txt = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Select dangles"))
+        self.queryDangleSL = wx.Choice(
+            parent=panel, id=wx.ID_ANY, choices=[
+                _("shorter than"), _("longer than")])
+        self.queryDangleSL.SetSelection(
+            UserSettings.Get(
+                group='vdigit',
+                key="queryDangle",
+                subkey='than-selection'))
+        self.queryDangleValue = wx.SpinCtrl(
+            parent=panel, id=wx.ID_ANY, size=(
+                100, -1), initial=1, min=0, max=1e6)
+        self.queryDangleValue.SetValue(
+            UserSettings.Get(
+                group='vdigit',
+                key="queryDangle",
+                subkey='thresh'))
+        units = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label="%s" %
+            LocUnits)
+        flexSizer.Add(txt, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
+        flexSizer.Add(
+            self.queryDangleSL,
+            proportion=0,
+            flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
+        flexSizer.Add(
+            self.queryDangleValue,
+            proportion=0,
+            flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
+        flexSizer.Add(units, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
+        sizer.Add(
+            item=flexSizer,
+            proportion=0,
+            flag=wx.ALL | wx.EXPAND,
+            border=1)
 
-        if UserSettings.Get(group = 'vdigit', key = "query", subkey = 'selection') == 0:
+        if UserSettings.Get(group='vdigit', key="query",
+                            subkey='selection') == 0:
             self.queryLength.SetValue(True)
         else:
             self.queryDangle.SetValue(True)
@@ -351,96 +568,137 @@
         # enable & disable items
         self.OnChangeQuery(None)
 
-        border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
+        border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
 
         panel.SetSizer(border)
-        
+
         return panel
 
     def _createAttributesPage(self, notebook):
         """Create notebook page for attributes"""
-        panel = wx.Panel(parent = notebook, id = wx.ID_ANY)
-        notebook.AddPage(page = panel, text = _("Attributes"))
+        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
+        notebook.AddPage(page=panel, text=_("Attributes"))
 
         border = wx.BoxSizer(wx.VERTICAL)
 
         #
         # add new record
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Digitize new feature"))
+        box = wx.StaticBox(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=" %s " %
+            _("Digitize new feature"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
 
         # checkbox
-        self.addRecord = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                     label = _("Add new record into table"))
-        self.addRecord.SetValue(UserSettings.Get(group = 'vdigit', key = "addRecord", subkey = 'enabled'))
-        sizer.Add(item = self.addRecord, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 1)
+        self.addRecord = wx.CheckBox(parent=panel, id=wx.ID_ANY,
+                                     label=_("Add new record into table"))
+        self.addRecord.SetValue(
+            UserSettings.Get(
+                group='vdigit',
+                key="addRecord",
+                subkey='enabled'))
+        sizer.Add(
+            item=self.addRecord,
+            proportion=0,
+            flag=wx.ALL | wx.EXPAND,
+            border=1)
         # settings
-        flexSizer = wx.FlexGridSizer(cols = 2, hgap = 3, vgap = 3)
+        flexSizer = wx.FlexGridSizer(cols=2, hgap=3, vgap=3)
         flexSizer.AddGrowableCol(0)
-        settings = ((_("Layer"), 1), (_("Category"), 1), (_("Mode"), _("Next to use")))
+        settings = ((_("Layer"), 1), (_("Category"), 1),
+                    (_("Mode"), _("Next to use")))
         # layer
-        text = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Layer"))
-        self.layer = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (125, -1),
-                                 min = 1, max = 1e3)
-        self.layer.SetValue(int(UserSettings.Get(group = 'vdigit', key = "layer", subkey = 'value')))
-        flexSizer.Add(item = text, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL)
-        flexSizer.Add(item = self.layer, proportion = 0,
-                      flag = wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
+        text = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Layer"))
+        self.layer = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(125, -1),
+                                 min=1, max=1e3)
+        self.layer.SetValue(int(UserSettings.Get(
+            group='vdigit', key="layer", subkey='value')))
+        flexSizer.Add(item=text, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
+        flexSizer.Add(item=self.layer, proportion=0,
+                      flag=wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
         # category number
-        text = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Category number"))
-        self.category = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (125, -1),
-                                    initial = UserSettings.Get(group = 'vdigit', key = "category", subkey = 'value'),
-                                    min = -1e9, max = 1e9) 
-        if UserSettings.Get(group = 'vdigit', key = "categoryMode", subkey = 'selection') != 1:
+        text = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Category number"))
+        self.category = wx.SpinCtrl(
+            parent=panel, id=wx.ID_ANY, size=(125, -1),
+            initial=UserSettings.Get(
+                group='vdigit', key="category", subkey='value'),
+            min=-1e9, max=1e9)
+        if UserSettings.Get(group='vdigit', key="categoryMode",
+                            subkey='selection') != 1:
             self.category.Enable(False)
-        flexSizer.Add(item = text, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL)
-        flexSizer.Add(item = self.category, proportion = 0,
-                      flag = wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
+        flexSizer.Add(item=text, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
+        flexSizer.Add(item=self.category, proportion=0,
+                      flag=wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
         # category mode
-        text = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Category mode"))
-        self.categoryMode = wx.Choice(parent = panel, id = wx.ID_ANY, size = (125, -1),
-                                      choices = [_("Next to use"), _("Manual entry"), _("No category")])
-        self.categoryMode.SetSelection(UserSettings.Get(group = 'vdigit', key = "categoryMode", subkey = 'selection'))
-        flexSizer.Add(item = text, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL)
-        flexSizer.Add(item = self.categoryMode, proportion = 0,
-                      flag = wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
+        text = wx.StaticText(
+            parent=panel,
+            id=wx.ID_ANY,
+            label=_("Category mode"))
+        self.categoryMode = wx.Choice(parent=panel, id=wx.ID_ANY, size=(
+            125, -1), choices=[_("Next to use"), _("Manual entry"), _("No category")])
+        self.categoryMode.SetSelection(
+            UserSettings.Get(
+                group='vdigit',
+                key="categoryMode",
+                subkey='selection'))
+        flexSizer.Add(item=text, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
+        flexSizer.Add(item=self.categoryMode, proportion=0,
+                      flag=wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
 
-        sizer.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
-        border.Add(item = sizer, proportion = 0,
-                   flag = wx.ALL | wx.EXPAND, border = 5)
+        sizer.Add(
+            item=flexSizer,
+            proportion=1,
+            flag=wx.ALL | wx.EXPAND,
+            border=1)
+        border.Add(item=sizer, proportion=0,
+                   flag=wx.ALL | wx.EXPAND, border=5)
 
         #
         # delete existing record
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Delete existing feature(s)"))
+        box = wx.StaticBox(
+            parent=panel, id=wx.ID_ANY, label=" %s " %
+            _("Delete existing feature(s)"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
+
         # checkbox
-        self.deleteRecord = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                        label = _("Delete record from table"))
-        self.deleteRecord.SetValue(UserSettings.Get(group = 'vdigit', key = "delRecord", subkey = 'enabled'))
-        sizer.Add(item = self.deleteRecord, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 1)
-        border.Add(item = sizer, proportion = 0,
-                   flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
+        self.deleteRecord = wx.CheckBox(parent=panel, id=wx.ID_ANY,
+                                        label=_("Delete record from table"))
+        self.deleteRecord.SetValue(
+            UserSettings.Get(
+                group='vdigit',
+                key="delRecord",
+                subkey='enabled'))
+        sizer.Add(
+            item=self.deleteRecord,
+            proportion=0,
+            flag=wx.ALL | wx.EXPAND,
+            border=1)
+        border.Add(item=sizer, proportion=0,
+                   flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=5)
 
         #
         # geometry attributes (currently only length and area are supported)
         #
-        box   = wx.StaticBox (parent = panel, id = wx.ID_ANY,
-                              label = " %s " % _("Geometry attributes"))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s " % _("Geometry attributes"))
         sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(hgap = 3, vgap = 3)
-        self.geomAttrb = { 'length' : { 'label' : _('length') },
-                           'area' : { 'label' : _('area') },
-                           'perimeter' : { 'label' : _('perimeter') } }
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
+        self.geomAttrb = {'length': {'label': _('length')},
+                          'area': {'label': _('area')},
+                          'perimeter': {'label': _('perimeter')}}
 
         digitToolbar = self.parent.toolbars['vdigit']
         try:
             vectorName = digitToolbar.GetLayer().GetName()
         except AttributeError:
-            vectorName = None # no vector selected for editing
-        layer = UserSettings.Get(group = 'vdigit', key = "layer", subkey = 'value')
+            vectorName = None  # no vector selected for editing
+        layer = UserSettings.Get(group='vdigit', key="layer", subkey='value')
         mapLayer = self.parent.toolbars['vdigit'].GetLayer()
         tree = self.parent.tree
         if tree:
@@ -450,70 +708,72 @@
         row = 0
         for attrb in ['length', 'area', 'perimeter']:
             # checkbox
-            check = wx.CheckBox(parent = panel, id = wx.ID_ANY,
-                                label = self.geomAttrb[attrb]['label'])
+            check = wx.CheckBox(parent=panel, id=wx.ID_ANY,
+                                label=self.geomAttrb[attrb]['label'])
             ### self.deleteRecord.SetValue(UserSettings.Get(group='vdigit', key="delRecord", subkey='enabled'))
             check.Bind(wx.EVT_CHECKBOX, self.OnGeomAttrb)
             # column (only numeric)
-            column = ColumnSelect(parent = panel, size = (200, -1))
-            column.InsertColumns(vector = vectorName,
-                                 layer = layer, excludeKey = True,
-                                 type = ['integer', 'double precision'])
-            # units 
+            column = ColumnSelect(parent=panel, size=(200, -1))
+            column.InsertColumns(vector=vectorName,
+                                 layer=layer, excludeKey=True,
+                                 type=['integer', 'double precision'])
+            # units
             if attrb == 'area':
                 choices = Units.GetUnitsList('area')
             else:
                 choices = Units.GetUnitsList('length')
-            win_units = wx.Choice(parent = panel, id = wx.ID_ANY,
-                                  choices = choices, size = (120, -1))
-            
+            win_units = wx.Choice(parent=panel, id=wx.ID_ANY,
+                                  choices=choices, size=(120, -1))
+
             # default values
             check.SetValue(False)
-            if item and tree.GetLayerInfo(item, key = 'vdigit') and \
-                    'geomAttr' in tree.GetLayerInfo(item, key = 'vdigit') and \
-                    attrb in tree.GetLayerInfo(item, key = 'vdigit')['geomAttr']:
+            if item and tree.GetLayerInfo(item, key='vdigit') and \
+                    'geomAttr' in tree.GetLayerInfo(item, key='vdigit') and \
+                    attrb in tree.GetLayerInfo(item, key='vdigit')['geomAttr']:
                 check.SetValue(True)
-                column.SetStringSelection(tree.GetLayerInfo(item, key = 'vdigit')['geomAttr'][attrb]['column'])
+                column.SetStringSelection(
+                    tree.GetLayerInfo(item, key='vdigit')['geomAttr']
+                    [attrb]['column'])
                 if attrb == 'area':
                     type = 'area'
                 else:
                     type = 'length'
-                unitsIdx = Units.GetUnitsIndex(type, 
-                                                tree.GetLayerInfo(item, key = 'vdigit')['geomAttr'][attrb]['units'])
+                unitsIdx = Units.GetUnitsIndex(type, tree.GetLayerInfo(
+                    item, key='vdigit')['geomAttr'][attrb]['units'])
                 win_units.SetSelection(unitsIdx)
 
             if not vectorName:
                 check.Enable(False)
                 column.Enable(False)
-            
+
             if not check.IsChecked():
                 column.Enable(False)
-            
-            self.geomAttrb[attrb]['check']  = check.GetId()
+
+            self.geomAttrb[attrb]['check'] = check.GetId()
             self.geomAttrb[attrb]['column'] = column.GetId()
-            self.geomAttrb[attrb]['units']  = win_units.GetId()
+            self.geomAttrb[attrb]['units'] = win_units.GetId()
 
-            gridSizer.Add(item = check,
-                          flag = wx.ALIGN_CENTER_VERTICAL,
-                          pos = (row, 0))
-            gridSizer.Add(item = column,
-                          pos = (row, 1))
-            gridSizer.Add(item = win_units,
-                          pos = (row, 2))
+            gridSizer.Add(item=check,
+                          flag=wx.ALIGN_CENTER_VERTICAL,
+                          pos=(row, 0))
+            gridSizer.Add(item=column,
+                          pos=(row, 1))
+            gridSizer.Add(item=win_units,
+                          pos=(row, 2))
             row += 1
-        
+
         note = '\n'.join(textwrap.wrap(_("Note: These settings are stored "
                                          "in the workspace not in the vector digitizer "
                                          "preferences."), 55))
-        gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
-                                           label = note),
-                      pos = (3, 0), span = (1, 3))
-                      
+        gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+                                         label=note),
+                      pos=(3, 0), span=(1, 3))
+
         gridSizer.AddGrowableCol(0)
-        sizer.Add(item = gridSizer, proportion = 1,
-                  flag = wx.ALL | wx.EXPAND, border = 1)
-        border.Add(item = sizer, proportion = 0,
-                   flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
+        sizer.Add(item=gridSizer, proportion=1,
+                  flag=wx.ALL | wx.EXPAND, border=1)
+        border.Add(item=sizer, proportion=0,
+                   flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=5)
 
         # bindings
         self.Bind(wx.EVT_CHECKBOX, self.OnChangeAddRecord, self.addRecord)
@@ -521,7 +781,7 @@
         self.Bind(wx.EVT_SPINCTRL, self.OnChangeLayer, self.layer)
 
         panel.SetSizer(border)
-        
+
         return panel
 
     def _symbologyData(self):
@@ -559,38 +819,54 @@
             if val['check'] == id:
                 key = attrb
                 break
-        
+
         column = self.FindWindowById(self.geomAttrb[key]['column'])
         if checked:
             column.Enable()
         else:
             column.Enable(False)
-        
+
     def OnChangeCategoryMode(self, event):
         """Change category mode
         """
         mode = event.GetSelection()
-        UserSettings.Set(group = 'vdigit', key = "categoryMode", subkey = 'selection', value = mode)
-        if mode == 1: # manual entry
+        UserSettings.Set(
+            group='vdigit',
+            key="categoryMode",
+            subkey='selection',
+            value=mode)
+        if mode == 1:  # manual entry
             self.category.Enable(True)
-        elif self.category.IsEnabled(): # disable
+        elif self.category.IsEnabled():  # disable
             self.category.Enable(False)
-        
-        if mode == 2 and self.addRecord.IsChecked(): # no category
+
+        if mode == 2 and self.addRecord.IsChecked():  # no category
             self.addRecord.SetValue(False)
-        
+
         self.digit.SetCategory()
-        self.category.SetValue(UserSettings.Get(group = 'vdigit', key = 'category', subkey = 'value'))
+        self.category.SetValue(
+            UserSettings.Get(
+                group='vdigit',
+                key='category',
+                subkey='value'))
 
     def OnChangeLayer(self, event):
         """Layer changed
         """
         layer = event.GetInt()
         if layer > 0:
-            UserSettings.Set(group = 'vdigit', key = 'layer', subkey = 'value', value = layer)
+            UserSettings.Set(
+                group='vdigit',
+                key='layer',
+                subkey='value',
+                value=layer)
             self.digit.SetCategory()
-            self.category.SetValue(UserSettings.Get(group = 'vdigit', key = 'category', subkey = 'value'))
-            
+            self.category.SetValue(
+                UserSettings.Get(
+                    group='vdigit',
+                    key='category',
+                    subkey='value'))
+
         event.Skip()
 
     def OnChangeAddRecord(self, event):
@@ -598,34 +874,35 @@
         """
         pass
         # self.category.SetValue(self.digit.SetCategory())
-            
+
     def OnChangeSnappingValue(self, event):
         """Change snapping value - update static text
         """
         value = self.snappingValue.GetValue()
-        
+
         if value < 0:
             region = self.parent.MapWindow.Map.GetRegion()
             res = (region['nsres'] + region['ewres']) / 2.
-            threshold = self.digit.GetDisplay().GetThreshold(value = res)
+            threshold = self.digit.GetDisplay().GetThreshold(value=res)
         else:
             if self.snappingUnit.GetStringSelection() == "map units":
                 threshold = value
             else:
-                threshold = self.digit.GetDisplay().GetThreshold(value = value)
-            
+                threshold = self.digit.GetDisplay().GetThreshold(value=value)
+
         if value == 0:
             self.snappingInfo.SetLabel(_("Snapping disabled"))
         elif value < 0:
-            self.snappingInfo.SetLabel(_("Snapping threshold is %(value).1f %(units)s "
-                                         "(based on comp. resolution)") % 
-                                       {'value' : threshold,
-                                        'units' : self.mapUnits.lower()})
+            self.snappingInfo.SetLabel(
+                _(
+                    "Snapping threshold is %(value).1f %(units)s "
+                    "(based on comp. resolution)") %
+                {'value': threshold, 'units': self.mapUnits.lower()})
         else:
-            self.snappingInfo.SetLabel(_("Snapping threshold is %(value).1f %(units)s") % 
-                                       {'value' : threshold,
-                                        'units' : self.mapUnits.lower()})
-        
+            self.snappingInfo.SetLabel(
+                _("Snapping threshold is %(value).1f %(units)s") %
+                {'value': threshold, 'units': self.mapUnits.lower()})
+
         event.Skip()
 
     def OnChangeSnappingUnits(self, event):
@@ -633,17 +910,17 @@
         """
         value = self.snappingValue.GetValue()
         units = self.snappingUnit.GetStringSelection()
-        threshold = self.digit.GetDisplay().GetThreshold(value = value, units = units)
+        threshold = self.digit.GetDisplay().GetThreshold(value=value, units=units)
 
         if units == "map units":
-            self.snappingInfo.SetLabel(_("Snapping threshold is %(value).1f %(units)s") % 
-                                       {'value' : value,
-                                        'units' : self.mapUnits})
+            self.snappingInfo.SetLabel(
+                _("Snapping threshold is %(value).1f %(units)s") %
+                {'value': value, 'units': self.mapUnits})
         else:
-            self.snappingInfo.SetLabel(_("Snapping threshold is %(value).1f %(units)s") % 
-                                       {'value' : threshold,
-                                        'units' : self.mapUnits})
-            
+            self.snappingInfo.SetLabel(
+                _("Snapping threshold is %(value).1f %(units)s") %
+                {'value': threshold, 'units': self.mapUnits})
+
         event.Skip()
 
     def OnChangeQuery(self, event):
@@ -669,16 +946,18 @@
         self.parent.toolbars['vdigit'].settingsDialog = None
 
         fileSettings = {}
-        UserSettings.ReadSettingsFile(settings = fileSettings)
-        fileSettings['vdigit'] = UserSettings.Get(group = 'vdigit')
-        
+        UserSettings.ReadSettingsFile(settings=fileSettings)
+        fileSettings['vdigit'] = UserSettings.Get(group='vdigit')
+
         sfile = UserSettings.SaveToFile(fileSettings)
-        self._giface.WriteLog(_('Vector digitizer settings saved to file <%s>.') % sfile)
-        
+        self._giface.WriteLog(
+            _('Vector digitizer settings saved to file <%s>.') %
+            sfile)
+
         self.Destroy()
 
         event.Skip()
-        
+
     def OnApply(self, event):
         """Button 'Apply' pressed
         """
@@ -692,55 +971,58 @@
 
         if event:
             event.Skip()
-        
+
     def UpdateSettings(self):
         """Update digitizer settings
 
         .. todo::
-            Needs refactoring 
+            Needs refactoring
         """
         # TODO: it seems that it needs to be replaced by signal
-        # but if it makes sense generally for wxGUI it can be added to giface 
+        # but if it makes sense generally for wxGUI it can be added to giface
         if self.parent.GetLayerManager():
-            self.parent.GetLayerManager().WorkspaceChanged() # geometry attributes
+            self.parent.GetLayerManager().WorkspaceChanged()  # geometry attributes
         # symbology
         for key, (enabled, color) in self.symbology.iteritems():
             if enabled:
-                UserSettings.Set(group = 'vdigit', key = 'symbol',
-                                 subkey = [key, 'enabled'],
-                                 value = enabled.IsChecked())
-                UserSettings.Set(group = 'vdigit', key = 'symbol',
-                                 subkey = [key, 'color'],
-                                 value = tuple(color.GetColour()))
+                UserSettings.Set(group='vdigit', key='symbol',
+                                 subkey=[key, 'enabled'],
+                                 value=enabled.IsChecked())
+                UserSettings.Set(group='vdigit', key='symbol',
+                                 subkey=[key, 'color'],
+                                 value=tuple(color.GetColour()))
             else:
-                UserSettings.Set(group = 'vdigit', key = 'symbol',
-                                 subkey = [key, 'color'],
-                                 value = tuple(color.GetColour()))
+                UserSettings.Set(group='vdigit', key='symbol',
+                                 subkey=[key, 'color'],
+                                 value=tuple(color.GetColour()))
         # display
-        UserSettings.Set(group = 'vdigit', key = "lineWidth", subkey = 'value',
-                         value = int(self.lineWidthValue.GetValue()))
+        UserSettings.Set(group='vdigit', key="lineWidth", subkey='value',
+                         value=int(self.lineWidthValue.GetValue()))
 
         # snapping
-        UserSettings.Set(group = 'vdigit', key = "snapping", subkey = 'value',
-                         value = int(self.snappingValue.GetValue()))
-        UserSettings.Set(group = 'vdigit', key = "snapping", subkey = 'units',
-                         value = self.snappingUnit.GetStringSelection())
-        UserSettings.Set(group = 'vdigit', key = "snapToVertex", subkey = 'enabled',
-                         value = self.snapVertex.IsChecked())
-        
+        UserSettings.Set(group='vdigit', key="snapping", subkey='value',
+                         value=int(self.snappingValue.GetValue()))
+        UserSettings.Set(group='vdigit', key="snapping", subkey='units',
+                         value=self.snappingUnit.GetStringSelection())
+        UserSettings.Set(group='vdigit', key="snapToVertex", subkey='enabled',
+                         value=self.snapVertex.IsChecked())
+
         # digitize new feature
-        UserSettings.Set(group = 'vdigit', key = "addRecord", subkey = 'enabled',
-                         value = self.addRecord.IsChecked())
-        UserSettings.Set(group = 'vdigit', key = "layer", subkey = 'value',
-                         value = int(self.layer.GetValue()))
-        UserSettings.Set(group = 'vdigit', key = "category", subkey = 'value',
-                         value = int(self.category.GetValue()))
-        UserSettings.Set(group = 'vdigit', key = "categoryMode", subkey = 'selection',
-                         value = self.categoryMode.GetSelection())
+        UserSettings.Set(group='vdigit', key="addRecord", subkey='enabled',
+                         value=self.addRecord.IsChecked())
+        UserSettings.Set(group='vdigit', key="layer", subkey='value',
+                         value=int(self.layer.GetValue()))
+        UserSettings.Set(group='vdigit', key="category", subkey='value',
+                         value=int(self.category.GetValue()))
+        UserSettings.Set(
+            group='vdigit',
+            key="categoryMode",
+            subkey='selection',
+            value=self.categoryMode.GetSelection())
 
         # delete existing feature
-        UserSettings.Set(group = 'vdigit', key = "delRecord", subkey = 'enabled',
-                         value = self.deleteRecord.IsChecked())
+        UserSettings.Set(group='vdigit', key="delRecord", subkey='enabled',
+                         value=self.deleteRecord.IsChecked())
 
         # geometry attributes (workspace)
         mapLayer = self.parent.toolbars['vdigit'].GetLayer()
@@ -751,69 +1033,79 @@
             item = None
         for key, val in self.geomAttrb.iteritems():
             checked = self.FindWindowById(val['check']).IsChecked()
-            column  = self.FindWindowById(val['column']).GetValue()
+            column = self.FindWindowById(val['column']).GetValue()
             unitsIdx = self.FindWindowById(val['units']).GetSelection()
-            if item and not tree.GetLayerInfo(item, key = 'vdigit'): 
-                tree.SetLayerInfo(item, key = 'vdigit', value = { 'geomAttr' : dict() })
-            
-            if checked: # enable
+            if item and not tree.GetLayerInfo(item, key='vdigit'):
+                tree.SetLayerInfo(
+                    item, key='vdigit', value={
+                        'geomAttr': dict()})
+
+            if checked:  # enable
                 if key == 'area':
                     type = key
                 else:
                     type = 'length'
                 unitsKey = Units.GetUnitsKey(type, unitsIdx)
-                tree.GetLayerInfo(item, key = 'vdigit')['geomAttr'][key] = { 'column' : column,
-                                                                       'units' : unitsKey }
+                tree.GetLayerInfo(item, key='vdigit')['geomAttr'][key] = {
+                    'column': column, 'units': unitsKey}
             else:
-                if item and tree.GetLayerInfo(item, key = 'vdigit') and \
-                        key in tree.GetLayerInfo(item, key = 'vdigit')['geomAttr']:
-                    del tree.GetLayerInfo(item, key = 'vdigit')['geomAttr'][key]
-        
+                if item and tree.GetLayerInfo(
+                        item, key='vdigit') and key in tree.GetLayerInfo(
+                        item, key='vdigit')['geomAttr']:
+                    del tree.GetLayerInfo(item, key='vdigit')['geomAttr'][key]
+
         # query tool
         if self.queryLength.GetValue():
-            UserSettings.Set(group = 'vdigit', key = "query", subkey = 'selection',
-                             value = 0)
+            UserSettings.Set(group='vdigit', key="query", subkey='selection',
+                             value=0)
         else:
-            UserSettings.Set(group = 'vdigit', key = "query", subkey = 'type',
-                             value = 1)
-        UserSettings.Set(group = 'vdigit', key = "query", subkey = 'box',
-                         value = self.queryBox.IsChecked())
-        UserSettings.Set(group = 'vdigit', key = "queryLength", subkey = 'than-selection',
-                         value = self.queryLengthSL.GetSelection())
-        UserSettings.Set(group = 'vdigit', key = "queryLength", subkey = 'thresh',
-                         value = int(self.queryLengthValue.GetValue()))
-        UserSettings.Set(group = 'vdigit', key = "queryDangle", subkey = 'than-selection',
-                         value = self.queryDangleSL.GetSelection())
-        UserSettings.Set(group = 'vdigit', key = "queryDangle", subkey = 'thresh',
-                         value = int(self.queryDangleValue.GetValue()))
+            UserSettings.Set(group='vdigit', key="query", subkey='type',
+                             value=1)
+        UserSettings.Set(group='vdigit', key="query", subkey='box',
+                         value=self.queryBox.IsChecked())
+        UserSettings.Set(
+            group='vdigit',
+            key="queryLength",
+            subkey='than-selection',
+            value=self.queryLengthSL.GetSelection())
+        UserSettings.Set(group='vdigit', key="queryLength", subkey='thresh',
+                         value=int(self.queryLengthValue.GetValue()))
+        UserSettings.Set(
+            group='vdigit',
+            key="queryDangle",
+            subkey='than-selection',
+            value=self.queryDangleSL.GetSelection())
+        UserSettings.Set(group='vdigit', key="queryDangle", subkey='thresh',
+                         value=int(self.queryDangleValue.GetValue()))
 
         # select features
         for feature in ('point', 'line',
                         'centroid', 'boundary'):
-            UserSettings.Set(group = 'vdigit', key = 'selectType',
-                             subkey = [feature, 'enabled'],
-                             value = self.FindWindowById(self.selectFeature[feature]).IsChecked())
-        UserSettings.Set(group = 'vdigit', key = "selectThresh", subkey = 'value',
-                         value = int(self.selectThreshValue.GetValue()))
-        UserSettings.Set(group = 'vdigit', key = "checkForDupl", subkey = 'enabled',
-                         value = self.checkForDupl.IsChecked())
-        UserSettings.Set(group = 'vdigit', key = "selectInside", subkey = 'enabled',
-                         value = self.selectIn.IsChecked())
+            UserSettings.Set(
+                group='vdigit', key='selectType', subkey=[
+                    feature, 'enabled'], value=self.FindWindowById(
+                    self.selectFeature[feature]).IsChecked())
+        UserSettings.Set(group='vdigit', key="selectThresh", subkey='value',
+                         value=int(self.selectThreshValue.GetValue()))
+        UserSettings.Set(group='vdigit', key="checkForDupl", subkey='enabled',
+                         value=self.checkForDupl.IsChecked())
+        UserSettings.Set(group='vdigit', key="selectInside", subkey='enabled',
+                         value=self.selectIn.IsChecked())
 
         # on-exit
-        UserSettings.Set(group = 'vdigit', key = "saveOnExit", subkey = 'enabled',
-                         value = self.save.IsChecked())
+        UserSettings.Set(group='vdigit', key="saveOnExit", subkey='enabled',
+                         value=self.save.IsChecked())
 
         # break lines
-        UserSettings.Set(group = 'vdigit', key = "breakLines", subkey = 'enabled',
-                         value = self.intersect.IsChecked())
+        UserSettings.Set(group='vdigit', key="breakLines", subkey='enabled',
+                         value=self.intersect.IsChecked())
 
         # close boundary
-        UserSettings.Set(group = 'vdigit', key = "closeBoundary", subkey = 'enabled',
-                         value = self.closeBoundary.IsChecked())
-        
+        UserSettings.Set(group='vdigit', key="closeBoundary", subkey='enabled',
+                         value=self.closeBoundary.IsChecked())
+
         self.digit.UpdateSettings()
-        
+
         # redraw map if auto-rendering is enabled
-        if self.parent.IsAutoRendered(): 
+        if self.parent.IsAutoRendered():
             self.parent.OnRender(None)

Modified: grass/trunk/gui/wxpython/vdigit/toolbars.py
===================================================================
--- grass/trunk/gui/wxpython/vdigit/toolbars.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/vdigit/toolbars.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -19,30 +19,32 @@
 from grass import script as grass
 from grass.pydispatch.signal import Signal
 
-from gui_core.toolbars  import BaseToolbar, BaseIcons
-from gui_core.dialogs   import CreateNewVector, VectorDialog
+from gui_core.toolbars import BaseToolbar, BaseIcons
+from gui_core.dialogs import CreateNewVector, VectorDialog
 from vdigit.preferences import VDigitSettingsDialog
-from core.debug         import Debug
-from core.settings      import UserSettings
-from core.gcmd          import GError, RunCommand
+from core.debug import Debug
+from core.settings import UserSettings
+from core.gcmd import GError, RunCommand
 from core.utils import _
-from icons.icon         import MetaIcon
-from iclass.digit       import IClassVDigit
-from core.giface        import Notification
+from icons.icon import MetaIcon
+from iclass.digit import IClassVDigit
+from core.giface import Notification
 
+
 class VDigitToolbar(BaseToolbar):
     """Toolbar for digitization
     """
+
     def __init__(self, parent, toolSwitcher, MapWindow, digitClass, giface,
                  tools=[]):
-        self.MapWindow     = MapWindow
-        self.Map           = MapWindow.GetMap() # Map class instance
-        self.tools         = tools
-        self.digitClass    = digitClass
+        self.MapWindow = MapWindow
+        self.Map = MapWindow.GetMap()  # Map class instance
+        self.tools = tools
+        self.digitClass = digitClass
         BaseToolbar.__init__(self, parent, toolSwitcher)
-        self.digit         = None
-        self._giface       = giface
-        self.fType         = None     # feature type for simple features editing
+        self.digit = None
+        self._giface = giface
+        self.fType = None     # feature type for simple features editing
 
         self.editingStarted = Signal("VDigitToolbar.editingStarted")
         self.editingStopped = Signal("VDigitToolbar.editingStopped")
@@ -52,132 +54,140 @@
             self.editingStarted.connect(layerTree.StartEditing)
             self.editingStopped.connect(layerTree.StopEditing)
             self.editingBgMap.connect(layerTree.SetBgMapForEditing)
-            
-        # currently selected map layer for editing (reference to MapLayer instance)
+
+        # currently selected map layer for editing (reference to MapLayer
+        # instance)
         self.mapLayer = None
         # list of vector layers from Layer Manager (only in the current mapset)
-        self.layers   = [] 
-        
-        self.comboid  = self.combo = None
-        self.undo     = -1
-        self.redo     = -1
-        
+        self.layers = []
+
+        self.comboid = self.combo = None
+        self.undo = -1
+        self.redo = -1
+
         # only one dialog can be open
-        self.settingsDialog   = None
+        self.settingsDialog = None
 
         # create toolbars (two rows optionally)
         self.InitToolbar(self._toolbarData())
-        
+
         self._default = -1
         # default action (digitize new point, line, etc.)
-        self.action = { 'desc' : '',
-                        'type' : '',
-                        'id'   : -1 }
+        self.action = {'desc': '',
+                       'type': '',
+                       'id': -1}
         self._currentAreaActionType = None
-        
+
         # list of available vector maps
-        self.UpdateListOfLayers(updateTool = True)
+        self.UpdateListOfLayers(updateTool=True)
 
-        for tool in ('addPoint', 'addLine', 'addBoundary', 'addCentroid', 'addArea',
-                     'addVertex', 'deleteLine', 'deleteArea', 'displayAttr', 'displayCats',
-                     'editLine', 'moveLine', 'moveVertex', 'removeVertex', 'additionalTools'):
+        for tool in (
+                'addPoint', 'addLine', 'addBoundary', 'addCentroid', 'addArea',
+                'addVertex', 'deleteLine', 'deleteArea', 'displayAttr',
+                'displayCats', 'editLine', 'moveLine', 'moveVertex',
+                'removeVertex', 'additionalTools'):
             if hasattr(self, tool):
                 tool = getattr(self, tool)
-                self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=tool)
+                self.toolSwitcher.AddToolToGroup(
+                    group='mouseUse', toolbar=self, tool=tool)
             else:
                 Debug.msg(1, '%s skipped' % tool)
-        
+
         # custom button for digitization of area/boundary/centroid
         # TODO: could this be somehow generalized?
         nAreaTools = 0
-        if self.tools and 'addBoundary' in self.tools: nAreaTools += 1
-        if self.tools and 'addCentroid' in self.tools: nAreaTools += 1
-        if self.tools and 'addArea' in self.tools: nAreaTools += 1
+        if self.tools and 'addBoundary' in self.tools:
+            nAreaTools += 1
+        if self.tools and 'addCentroid' in self.tools:
+            nAreaTools += 1
+        if self.tools and 'addArea' in self.tools:
+            nAreaTools += 1
         if nAreaTools != 1:
-            self.areaButton = self.CreateSelectionButton(_("Select area/boundary/centroid tool"))
+            self.areaButton = self.CreateSelectionButton(
+                _("Select area/boundary/centroid tool"))
             self.areaButtonId = self.InsertControl(5, self.areaButton)
             self.areaButton.Bind(wx.EVT_BUTTON, self.OnAddAreaMenu)
-        
+
         # realize toolbar
         self.Realize()
         # workaround for Mac bug. May be fixed by 2.8.8, but not before then.
         if self.combo:
             self.combo.Hide()
             self.combo.Show()
-        
+
         # disable undo/redo
         if self.undo > 0:
             self.EnableTool(self.undo, False)
         if self.redo > 0:
             self.EnableTool(self.redo, False)
 
-        self.FixSize(width = 105)
+        self.FixSize(width=105)
 
     def _toolbarData(self):
         """Toolbar data
         """
         data = []
-        
+
         self.icons = {
-            'addPoint'        : MetaIcon(img = 'point-create',
-                                         label = _('Digitize new point'),
-                                         desc = _('Left: new point')),
-            'addLine'         : MetaIcon(img = 'line-create',
-                                         label = _('Digitize new line'),
-                                         desc = _('Left: new point; Ctrl+Left: undo last point; Right: close line')),
-            'addBoundary'     : MetaIcon(img = 'boundary-create',
-                                         label = _('Digitize new boundary'),
-                                         desc = _('Left: new point; Ctrl+Left: undo last point; Right: close line')),
-            'addCentroid'     : MetaIcon(img = 'centroid-create',
-                                         label = _('Digitize new centroid'),
-                                         desc = _('Left: new point')),
-            'addArea'         : MetaIcon(img = 'polygon-create',
-                                         label = _('Digitize new area (boundary without category)'),
-                                         desc = _('Left: new point')),
-            'addVertex'       : MetaIcon(img = 'vertex-create',
-                                         label = _('Add new vertex to line or boundary'),
-                                         desc = _('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
-            'deleteLine'      : MetaIcon(img = 'line-delete',
-                                         label = _('Delete selected point(s), line(s), boundary(ies) or centroid(s)'),
-                                         desc = _('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
-            'deleteArea'      : MetaIcon(img = 'polygon-delete',
-                                         label = _('Delete selected area(s)'),
-                                         desc = _('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
-            'displayAttr'     : MetaIcon(img = 'attributes-display',
-                                         label = _('Display/update attributes'),
-                                         desc = _('Left: Select')),
-            'displayCats'     : MetaIcon(img = 'cats-display',
-                                         label = _('Display/update categories'),
-                                         desc = _('Left: Select')),
-            'editLine'        : MetaIcon(img = 'line-edit',
-                                         label = _('Edit selected line/boundary'),
-                                         desc = _('Left: new point; Ctrl+Left: undo last point; Right: close line')),
-            'moveLine'        : MetaIcon(img = 'line-move',
-                                         label = _('Move selected point(s), line(s), boundary(ies) or centroid(s)'),
-                                         desc = _('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
-            'moveVertex'      : MetaIcon(img = 'vertex-move',
-                                         label = _('Move selected vertex'),
-                                         desc = _('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
-            'removeVertex'    : MetaIcon(img = 'vertex-delete',
-                                         label = _('Remove selected vertex'),
-                                         desc = _('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
-            'settings'        : BaseIcons['settings'].SetLabel(_('Digitization settings')),
-            'quit'            : BaseIcons['quit'].SetLabel(label = _('Quit digitizer'),
-                                                           desc = _('Quit digitizer and save changes')),
-            'help'            : BaseIcons['help'].SetLabel(label = _('Vector Digitizer manual'),
-                                                           desc = _('Show Vector Digitizer manual')),
-            'additionalTools' : MetaIcon(img = 'tools',
-                                         label = _('Additional tools '
-                                                   '(copy, flip, connect, etc.)'),
-                                         desc = _('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
-            'undo'            : MetaIcon(img = 'undo',
-                                         label = _('Undo'),
-                                         desc = _('Undo previous changes')),
-            'redo'            : MetaIcon(img = 'redo',
-                                         label = _('Redo'),
-                                         desc = _('Redo previous changes')),
-            }
-        
+            'addPoint': MetaIcon(img='point-create',
+                                 label=_('Digitize new point'),
+                                 desc=_('Left: new point')),
+            'addLine': MetaIcon(img='line-create',
+                                label=_('Digitize new line'),
+                                desc=_('Left: new point; Ctrl+Left: undo last point; Right: close line')),
+            'addBoundary': MetaIcon(img='boundary-create',
+                                    label=_('Digitize new boundary'),
+                                    desc=_('Left: new point; Ctrl+Left: undo last point; Right: close line')),
+            'addCentroid': MetaIcon(img='centroid-create',
+                                    label=_('Digitize new centroid'),
+                                    desc=_('Left: new point')),
+            'addArea': MetaIcon(img='polygon-create',
+                                label=_('Digitize new area (boundary without category)'),
+                                desc=_('Left: new point')),
+            'addVertex': MetaIcon(img='vertex-create',
+                                  label=_('Add new vertex to line or boundary'),
+                                  desc=_('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
+            'deleteLine': MetaIcon(img='line-delete',
+                                   label=_('Delete selected point(s), line(s), boundary(ies) or centroid(s)'),
+                                   desc=_('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
+            'deleteArea': MetaIcon(img='polygon-delete',
+                                   label=_('Delete selected area(s)'),
+                                   desc=_('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
+            'displayAttr': MetaIcon(img='attributes-display',
+                                    label=_('Display/update attributes'),
+                                    desc=_('Left: Select')),
+            'displayCats': MetaIcon(img='cats-display',
+                                    label=_('Display/update categories'),
+                                    desc=_('Left: Select')),
+            'editLine': MetaIcon(img='line-edit',
+                                 label=_('Edit selected line/boundary'),
+                                 desc=_('Left: new point; Ctrl+Left: undo last point; Right: close line')),
+            'moveLine': MetaIcon(img='line-move',
+                                 label=_('Move selected point(s), line(s), boundary(ies) or centroid(s)'),
+                                 desc=_('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
+            'moveVertex': MetaIcon(img='vertex-move',
+                                   label=_('Move selected vertex'),
+                                   desc=_('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
+            'removeVertex': MetaIcon(img='vertex-delete',
+                                     label=_('Remove selected vertex'),
+                                     desc=_('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
+            'settings': BaseIcons['settings'].SetLabel(_('Digitization settings')),
+            'quit': BaseIcons['quit'].SetLabel(label=_('Quit digitizer'),
+                                               desc=_('Quit digitizer and save changes')),
+            'help': BaseIcons['help'].SetLabel(label=_('Vector Digitizer manual'),
+                                               desc=_('Show Vector Digitizer manual')),
+            'additionalTools': MetaIcon(img='tools',
+                                        label=_('Additional tools '
+                                                '(copy, flip, connect, etc.)'),
+                                        desc=_('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
+            'undo': MetaIcon(img='undo',
+                             label=_('Undo'),
+                             desc=_('Undo previous changes')),
+            'redo': MetaIcon(img='redo',
+                             label=_('Redo'),
+                             desc=_('Redo previous changes')),
+        }
+
         if not self.tools or 'selector' in self.tools:
             data.append((None, ))
         if not self.tools or 'addPoint' in self.tools:
@@ -186,12 +196,12 @@
                          wx.ITEM_CHECK))
         if not self.tools or 'addLine' in self.tools:
             data.append(("addLine", self.icons["addLine"],
-                        self.OnAddLine,
-                        wx.ITEM_CHECK))
+                         self.OnAddLine,
+                         wx.ITEM_CHECK))
         if not self.tools or 'addArea' in self.tools:
             data.append(("addArea", self.icons["addArea"],
-                        self.OnAddAreaTool,
-                        wx.ITEM_CHECK))
+                         self.OnAddAreaTool,
+                         wx.ITEM_CHECK))
         if not self.tools or 'deleteLine' in self.tools:
             data.append(("deleteLine", self.icons["deleteLine"],
                          self.OnDeleteLine,
@@ -200,7 +210,7 @@
             data.append(("deleteArea", self.icons["deleteArea"],
                          self.OnDeleteArea,
                          wx.ITEM_CHECK))
-        if not self.tools or 'moveVertex' in self.tools:            
+        if not self.tools or 'moveVertex' in self.tools:
             data.append(("moveVertex", self.icons["moveVertex"],
                          self.OnMoveVertex,
                          wx.ITEM_CHECK))
@@ -212,7 +222,7 @@
             data.append(("removeVertex", self.icons["removeVertex"],
                          self.OnRemoveVertex,
                          wx.ITEM_CHECK))
-        if not self.tools or 'editLine' in self.tools:            
+        if not self.tools or 'editLine' in self.tools:
             data.append(("editLine", self.icons["editLine"],
                          self.OnEditLine,
                          wx.ITEM_CHECK))
@@ -254,7 +264,7 @@
         if not self.tools or 'quit' in self.tools:
             data.append(("quit", self.icons["quit"],
                          self.OnExit))
-        
+
         return self._getToolbarData(data)
 
     def OnTool(self, event):
@@ -263,101 +273,106 @@
         Debug.msg(3, "VDigitToolbar.OnTool(): id = %s" % event.GetId())
         # set cursor
         self.MapWindow.SetNamedCursor('cross')
-        self.MapWindow.mouse['box'] = 'point' 
+        self.MapWindow.mouse['box'] = 'point'
         self.MapWindow.mouse['use'] = 'pointer'
-         
-        aId = self.action.get('id', -1)       
+
+        aId = self.action.get('id', -1)
         BaseToolbar.OnTool(self, event)
 
         # clear tmp canvas
         if self.action['id'] != aId or aId == -1:
             self.MapWindow.polycoords = []
-            self.MapWindow.ClearLines(pdc = self.MapWindow.pdcTmp)
+            self.MapWindow.ClearLines(pdc=self.MapWindow.pdcTmp)
             if self.digit and \
                     len(self.MapWindow.digit.GetDisplay().GetSelected()) > 0:
                 # cancel action
                 self.MapWindow.OnMiddleDown(None)
-        
+
         # set no action
         if self.action['id'] == -1:
-            self.action = { 'desc' : '',
-                            'type' : '',
-                            'id'   : -1 }
-        
+            self.action = {'desc': '',
+                           'type': '',
+                           'id': -1}
+
         # set focus
         self.MapWindow.SetFocus()
-        
+
     def OnAddPoint(self, event):
         """Add point to the vector map Laier"""
-        Debug.msg (2, "VDigitToolbar.OnAddPoint()")
-        self.action = { 'desc' : "addLine",
-                        'type' : "point",
-                        'id'   : self.addPoint }
+        Debug.msg(2, "VDigitToolbar.OnAddPoint()")
+        self.action = {'desc': "addLine",
+                       'type': "point",
+                       'id': self.addPoint}
         self.MapWindow.mouse['box'] = 'point'
-        
+
     def OnAddLine(self, event):
         """Add line to the vector map layer"""
-        Debug.msg (2, "VDigitToolbar.OnAddLine()")
-        self.action = { 'desc' : "addLine",
-                        'type' : "line",
-                        'id'   : self.addLine }
+        Debug.msg(2, "VDigitToolbar.OnAddLine()")
+        self.action = {'desc': "addLine",
+                       'type': "line",
+                       'id': self.addLine}
         self.MapWindow.mouse['box'] = 'line'
-        ### self.MapWindow.polycoords = [] # reset temp line
+        # self.MapWindow.polycoords = [] # reset temp line
 
     def OnAddBoundary(self, event):
         """Add boundary to the vector map layer"""
-        Debug.msg (2, "VDigitToolbar.OnAddBoundary()")
+        Debug.msg(2, "VDigitToolbar.OnAddBoundary()")
 
         self._toggleAreaIfNeeded()
 
-         # reset temp line
+        # reset temp line
         if self.action['desc'] != 'addLine' or \
                 self.action['type'] != 'boundary':
             self.MapWindow.polycoords = []
 
         # update icon and tooltip
-        self.SetToolNormalBitmap(self.addArea, self.icons['addBoundary'].GetBitmap())
-        self.SetToolShortHelp(self.addArea, self.icons['addBoundary'].GetLabel())
+        self.SetToolNormalBitmap(self.addArea, self.icons[
+                                 'addBoundary'].GetBitmap())
+        self.SetToolShortHelp(self.addArea,
+                              self.icons['addBoundary'].GetLabel())
 
         # set action
-        self.action = { 'desc' : "addLine",
-                        'type' : "boundary",
-                        'id'   : self.addArea }
+        self.action = {'desc': "addLine",
+                       'type': "boundary",
+                       'id': self.addArea}
         self.MapWindow.mouse['box'] = 'line'
         self._currentAreaActionType = 'boundary'
-        
+
     def OnAddCentroid(self, event):
         """Add centroid to the vector map layer"""
-        Debug.msg (2, "VDigitToolbar.OnAddCentroid()")
+        Debug.msg(2, "VDigitToolbar.OnAddCentroid()")
 
         self._toggleAreaIfNeeded()
 
         # update icon and tooltip
-        self.SetToolNormalBitmap(self.addArea, self.icons['addCentroid'].GetBitmap())
-        self.SetToolShortHelp(self.addArea, self.icons['addCentroid'].GetLabel())
-        
+        self.SetToolNormalBitmap(self.addArea, self.icons[
+                                 'addCentroid'].GetBitmap())
+        self.SetToolShortHelp(self.addArea,
+                              self.icons['addCentroid'].GetLabel())
+
         # set action
-        self.action = { 'desc' : "addLine",
-                        'type' : "centroid",
-                        'id'   : self.addArea }
+        self.action = {'desc': "addLine",
+                       'type': "centroid",
+                       'id': self.addArea}
         self.MapWindow.mouse['box'] = 'point'
         self._currentAreaActionType = 'centroid'
 
     def OnAddArea(self, event):
         """Add area to the vector map layer"""
 
-        Debug.msg (2, "VDigitToolbar.OnAddArea()")
+        Debug.msg(2, "VDigitToolbar.OnAddArea()")
 
         self._toggleAreaIfNeeded()
 
         # update icon and tooltip
-        self.SetToolNormalBitmap(self.addArea, self.icons['addArea'].GetBitmap())
+        self.SetToolNormalBitmap(
+            self.addArea, self.icons['addArea'].GetBitmap())
         self.SetToolShortHelp(self.addArea, self.icons['addArea'].GetLabel())
-        
+
         # set action
-        self.action = { 'desc' : "addLine",
-                        'type' : "area",
-                        'id'   : self.addArea }
+        self.action = {'desc': "addLine",
+                       'type': "area",
+                       'id': self.addArea}
         self.MapWindow.mouse['box'] = 'line'
         self._currentAreaActionType = 'area'
 
@@ -369,10 +384,10 @@
 
     def OnAddAreaTool(self, event):
         """Area tool activated."""
-        Debug.msg (2, "VDigitToolbar.OnAddAreaTool()")
+        Debug.msg(2, "VDigitToolbar.OnAddAreaTool()")
 
         # we need the previous id
-        if not self._currentAreaActionType or self._currentAreaActionType == 'area': # default action
+        if not self._currentAreaActionType or self._currentAreaActionType == 'area':  # default action
             self.OnAddArea(event)
         elif self._currentAreaActionType == 'boundary':
             self.OnAddBoundary(event)
@@ -387,20 +402,20 @@
         if not self.fType and not self.tools or 'addBoundary' in self.tools:
             menuItems.append((self.icons["addBoundary"], self.OnAddBoundary))
         if not self.fType and not self.tools or 'addCentroid' in self.tools:
-            menuItems.append((self.icons["addCentroid"],  self.OnAddCentroid))
-        
+            menuItems.append((self.icons["addCentroid"], self.OnAddCentroid))
+
         self._onMenu(menuItems)
 
-    def OnExit (self, event = None):
+    def OnExit(self, event=None):
         """Quit digitization tool"""
         # stop editing of the currently selected map layer
         if self.mapLayer:
             self.StopEditing()
-        
+
         # close dialogs if still open
         if self.settingsDialog:
             self.settingsDialog.OnCancel(None)
-        
+
         # set default mouse settings
         self.parent.GetMapToolbar().SelectDefault()
         self.MapWindow.polycoords = []
@@ -411,100 +426,100 @@
             self.parent.RemoveToolbar("vdigit")
         else:
             self.parent.Close()
-                
+
     def OnMoveVertex(self, event):
         """Move line vertex"""
         Debug.msg(2, "Digittoolbar.OnMoveVertex():")
-        self.action = { 'desc' : "moveVertex",
-                        'id'   : self.moveVertex }
+        self.action = {'desc': "moveVertex",
+                       'id': self.moveVertex}
         self.MapWindow.mouse['box'] = 'point'
 
     def OnAddVertex(self, event):
         """Add line vertex"""
         Debug.msg(2, "Digittoolbar.OnAddVertex():")
-        self.action = { 'desc' : "addVertex",
-                        'id'   : self.addVertex }
+        self.action = {'desc': "addVertex",
+                       'id': self.addVertex}
         self.MapWindow.mouse['box'] = 'point'
-        
+
     def OnRemoveVertex(self, event):
         """Remove line vertex"""
         Debug.msg(2, "Digittoolbar.OnRemoveVertex():")
-        self.action = { 'desc' : "removeVertex",
-                        'id'   : self.removeVertex }
+        self.action = {'desc': "removeVertex",
+                       'id': self.removeVertex}
         self.MapWindow.mouse['box'] = 'point'
 
     def OnEditLine(self, event):
         """Edit line"""
         Debug.msg(2, "Digittoolbar.OnEditLine():")
-        self.action = { 'desc' : "editLine",
-                        'id'   : self.editLine }
+        self.action = {'desc': "editLine",
+                       'id': self.editLine}
         self.MapWindow.mouse['box'] = 'line'
 
     def OnMoveLine(self, event):
         """Move line"""
         Debug.msg(2, "Digittoolbar.OnMoveLine():")
-        self.action = { 'desc' : "moveLine",
-                        'id'   : self.moveLine }
+        self.action = {'desc': "moveLine",
+                       'id': self.moveLine}
         self.MapWindow.mouse['box'] = 'box'
 
     def OnDeleteLine(self, event):
         """Delete line"""
         Debug.msg(2, "Digittoolbar.OnDeleteLine():")
-        self.action = { 'desc' : "deleteLine",
-                        'id'   : self.deleteLine }
+        self.action = {'desc': "deleteLine",
+                       'id': self.deleteLine}
         self.MapWindow.mouse['box'] = 'box'
 
     def OnDeleteArea(self, event):
         """Delete Area"""
         Debug.msg(2, "Digittoolbar.OnDeleteArea():")
-        self.action = { 'desc' : "deleteArea",
-                        'id'   : self.deleteArea }
+        self.action = {'desc': "deleteArea",
+                       'id': self.deleteArea}
         self.MapWindow.mouse['box'] = 'box'
 
     def OnDisplayCats(self, event):
         """Display/update categories"""
         Debug.msg(2, "Digittoolbar.OnDisplayCats():")
-        self.action = { 'desc' : "displayCats",
-                        'id'   : self.displayCats }
+        self.action = {'desc': "displayCats",
+                       'id': self.displayCats}
         self.MapWindow.mouse['box'] = 'point'
 
     def OnDisplayAttr(self, event):
         """Display/update attributes"""
         Debug.msg(2, "Digittoolbar.OnDisplayAttr():")
-        self.action = { 'desc' : "displayAttrs",
-                        'id'   : self.displayAttr }
+        self.action = {'desc': "displayAttrs",
+                       'id': self.displayAttr}
         self.MapWindow.mouse['box'] = 'point'
-        
+
     def OnUndo(self, event):
         """Undo previous changes"""
         self.digit.Undo()
-        
+
         event.Skip()
 
     def OnRedo(self, event):
         """Undo previous changes"""
-        self.digit.Undo(level = 1)
-        
+        self.digit.Undo(level=1)
+
         event.Skip()
-        
-    def EnableUndo(self, enable = True):
+
+    def EnableUndo(self, enable=True):
         """Enable 'Undo' in toolbar
-        
+
         :param enable: False for disable
         """
         self._enableTool(self.undo, enable)
 
-    def EnableRedo(self, enable = True):
+    def EnableRedo(self, enable=True):
         """Enable 'Redo' in toolbar
-        
+
         :param enable: False for disable
         """
         self._enableTool(self.redo, enable)
-        
+
     def _enableTool(self, tool, enable):
         if not self.FindById(tool):
             return
-        
+
         if enable:
             if self.GetToolEnabled(tool) is False:
                 self.EnableTool(tool, True)
@@ -512,7 +527,7 @@
             if self.GetToolEnabled(tool) is True:
                 self.EnableTool(tool, False)
 
-    def GetAction(self, type = 'desc'):
+    def GetAction(self, type='desc'):
         """Get current action info"""
         return self.action.get(type, '')
 
@@ -520,23 +535,25 @@
         """Show settings dialog"""
         if self.digit is None:
             try:
-                self.digit = self.MapWindow.digit = self.digitClass(mapwindow = self.MapWindow)
+                self.digit = self.MapWindow.digit = self.digitClass(
+                    mapwindow=self.MapWindow)
             except SystemExit:
                 self.digit = self.MapWindow.digit = None
-        
+
         if not self.settingsDialog:
-            self.settingsDialog = VDigitSettingsDialog(parent = self.parent, giface = self._giface)
+            self.settingsDialog = VDigitSettingsDialog(
+                parent=self.parent, giface=self._giface)
             self.settingsDialog.Show()
 
     def OnHelp(self, event):
         """Show digitizer help page in web browser"""
         self._giface.Help('wxGUI.vdigit')
-        
+
     def OnAdditionalToolMenu(self, event):
         """Menu for additional tools"""
         point = wx.GetMousePosition()
         toolMenu = wx.Menu()
-        
+
         for label, itype, handler, desc in (
             (_('Break selected lines/boundaries at intersection'),
              wx.ITEM_CHECK, self.OnBreak, "breakLine"),
@@ -563,198 +580,202 @@
             (_('Z bulk-labeling of 3D lines'),
              wx.ITEM_CHECK, self.OnZBulk, "zbulkLine")):
             # Add items to the menu
-            item = wx.MenuItem(parentMenu = toolMenu, id = wx.ID_ANY,
-                               text = label,
-                               kind = itype)
+            item = wx.MenuItem(parentMenu=toolMenu, id=wx.ID_ANY,
+                               text=label,
+                               kind=itype)
             toolMenu.AppendItem(item)
             self.MapWindow.Bind(wx.EVT_MENU, handler, item)
             if self.action['desc'] == desc:
                 item.Check(True)
-        
+
         # Popup the menu.  If an item is selected then its handler
         # will be called before PopupMenu returns.
         self.MapWindow.PopupMenu(toolMenu)
         toolMenu.Destroy()
-        
+
         if self.action['desc'] == 'addPoint':
             self.ToggleTool(self.additionalTools, False)
-        
+
     def OnCopy(self, event):
         """Copy selected features from (background) vector map"""
         if not self.digit:
             GError(_("No vector map open for editing."), self.parent)
             return
-        
+
         # select background map
-        dlg = VectorDialog(self.parent, title = _("Select background vector map"),
-                           layerTree = self._giface.GetLayerTree())
+        dlg = VectorDialog(self.parent,
+                           title=_("Select background vector map"),
+                           layerTree=self._giface.GetLayerTree())
         if dlg.ShowModal() != wx.ID_OK:
             dlg.Destroy()
             return
-        
+
         mapName = dlg.GetName(full=True)
         dlg.Destroy()
-        
+
         # close open background map if any
-        bgMap = UserSettings.Get(group = 'vdigit', key = 'bgmap', subkey = 'value',
+        bgMap = UserSettings.Get(group='vdigit', key='bgmap', subkey='value',
                                  settings_type='internal')
         if bgMap:
             self.digit.CloseBackgroundMap()
-            self.editingBgMap.emit(mapName = bgMap, unset=True)
+            self.editingBgMap.emit(mapName=bgMap, unset=True)
 
         # open background map for reading
-        UserSettings.Set(group = 'vdigit', key = 'bgmap', subkey = 'value',
+        UserSettings.Set(group='vdigit', key='bgmap', subkey='value',
                          value=str(mapName), settings_type='internal')
         self.digit.OpenBackgroundMap(mapName)
-        self.editingBgMap.emit(mapName = mapName)
+        self.editingBgMap.emit(mapName=mapName)
 
-        if self.action['desc'] == 'copyLine': # select previous action
+        if self.action['desc'] == 'copyLine':  # select previous action
             self.ToggleTool(self.addPoint, True)
             self.ToggleTool(self.additionalTools, False)
             self.OnAddPoint(event)
             return
-        
+
         Debug.msg(2, "Digittoolbar.OnCopy():")
-        self.action = { 'desc' : "copyLine",
-                        'id'   : self.additionalTools }
+        self.action = {'desc': "copyLine",
+                       'id': self.additionalTools}
         self.MapWindow.mouse['box'] = 'box'
 
     def OnSplitLine(self, event):
         """Split line"""
-        if self.action['desc'] == 'splitLine': # select previous action
+        if self.action['desc'] == 'splitLine':  # select previous action
             self.ToggleTool(self.addPoint, True)
             self.ToggleTool(self.additionalTools, False)
             self.OnAddPoint(event)
             return
-        
+
         Debug.msg(2, "Digittoolbar.OnSplitLine():")
-        self.action = { 'desc' : "splitLine",
-                        'id'   : self.additionalTools }
+        self.action = {'desc': "splitLine",
+                       'id': self.additionalTools}
         self.MapWindow.mouse['box'] = 'point'
 
-
     def OnCopyCats(self, event):
         """Copy categories"""
-        if self.action['desc'] == 'copyCats': # select previous action
+        if self.action['desc'] == 'copyCats':  # select previous action
             self.ToggleTool(self.addPoint, True)
             self.ToggleTool(self.copyCats, False)
             self.OnAddPoint(event)
             return
-        
+
         Debug.msg(2, "Digittoolbar.OnCopyCats():")
-        self.action = { 'desc' : "copyCats",
-                        'id'   : self.additionalTools }
+        self.action = {'desc': "copyCats",
+                       'id': self.additionalTools}
         self.MapWindow.mouse['box'] = 'point'
 
     def OnCopyAttrb(self, event):
         """Copy attributes"""
-        if self.action['desc'] == 'copyAttrs': # select previous action
+        if self.action['desc'] == 'copyAttrs':  # select previous action
             self.ToggleTool(self.addPoint, True)
             self.ToggleTool(self.copyCats, False)
             self.OnAddPoint(event)
             return
-        
+
         Debug.msg(2, "Digittoolbar.OnCopyAttrb():")
-        self.action = { 'desc' : "copyAttrs",
-                        'id'   : self.additionalTools }
+        self.action = {'desc': "copyAttrs",
+                       'id': self.additionalTools}
         self.MapWindow.mouse['box'] = 'point'
-        
 
     def OnFlip(self, event):
         """Flip selected lines/boundaries"""
-        if self.action['desc'] == 'flipLine': # select previous action
+        if self.action['desc'] == 'flipLine':  # select previous action
             self.ToggleTool(self.addPoint, True)
             self.ToggleTool(self.additionalTools, False)
             self.OnAddPoint(event)
             return
-        
+
         Debug.msg(2, "Digittoolbar.OnFlip():")
-        self.action = { 'desc' : "flipLine",
-                        'id'   : self.additionalTools }
+        self.action = {'desc': "flipLine",
+                       'id': self.additionalTools}
         self.MapWindow.mouse['box'] = 'box'
 
     def OnMerge(self, event):
         """Merge selected lines/boundaries"""
-        if self.action['desc'] == 'mergeLine': # select previous action
+        if self.action['desc'] == 'mergeLine':  # select previous action
             self.ToggleTool(self.addPoint, True)
             self.ToggleTool(self.additionalTools, False)
             self.OnAddPoint(event)
             return
-        
+
         Debug.msg(2, "Digittoolbar.OnMerge():")
-        self.action = { 'desc' : "mergeLine",
-                        'id'   : self.additionalTools }
+        self.action = {'desc': "mergeLine",
+                       'id': self.additionalTools}
         self.MapWindow.mouse['box'] = 'box'
 
     def OnBreak(self, event):
         """Break selected lines/boundaries"""
-        if self.action['desc'] == 'breakLine': # select previous action
+        if self.action['desc'] == 'breakLine':  # select previous action
             self.ToggleTool(self.addPoint, True)
             self.ToggleTool(self.additionalTools, False)
             self.OnAddPoint(event)
             return
-        
+
         Debug.msg(2, "Digittoolbar.OnBreak():")
-        self.action = { 'desc' : "breakLine",
-                        'id'   : self.additionalTools }
+        self.action = {'desc': "breakLine",
+                       'id': self.additionalTools}
         self.MapWindow.mouse['box'] = 'box'
 
     def OnSnap(self, event):
         """Snap selected features"""
-        if self.action['desc'] == 'snapLine': # select previous action
+        if self.action['desc'] == 'snapLine':  # select previous action
             self.ToggleTool(self.addPoint, True)
             self.ToggleTool(self.additionalTools, False)
             self.OnAddPoint(event)
             return
-        
+
         Debug.msg(2, "Digittoolbar.OnSnap():")
-        self.action = { 'desc' : "snapLine",
-                        'id'   : self.additionalTools }
+        self.action = {'desc': "snapLine",
+                       'id': self.additionalTools}
         self.MapWindow.mouse['box'] = 'box'
 
     def OnConnect(self, event):
         """Connect selected lines/boundaries"""
-        if self.action['desc'] == 'connectLine': # select previous action
+        if self.action['desc'] == 'connectLine':  # select previous action
             self.ToggleTool(self.addPoint, True)
             self.ToggleTool(self.additionalTools, False)
             self.OnAddPoint(event)
             return
-        
+
         Debug.msg(2, "Digittoolbar.OnConnect():")
-        self.action = { 'desc' : "connectLine",
-                        'id'   : self.additionalTools }
+        self.action = {'desc': "connectLine",
+                       'id': self.additionalTools}
         self.MapWindow.mouse['box'] = 'box'
 
     def OnQuery(self, event):
         """Query selected lines/boundaries"""
-        if self.action['desc'] == 'queryLine': # select previous action
+        if self.action['desc'] == 'queryLine':  # select previous action
             self.ToggleTool(self.addPoint, True)
             self.ToggleTool(self.additionalTools, False)
             self.OnAddPoint(event)
             return
-        
-        Debug.msg(2, "Digittoolbar.OnQuery(): %s" % \
-                      UserSettings.Get(group = 'vdigit', key = 'query', subkey = 'selection'))
-        self.action = { 'desc' : "queryLine",
-                        'id'   : self.additionalTools }
+
+        Debug.msg(
+            2,
+            "Digittoolbar.OnQuery(): %s" %
+            UserSettings.Get(
+                group='vdigit',
+                key='query',
+                subkey='selection'))
+        self.action = {'desc': "queryLine",
+                       'id': self.additionalTools}
         self.MapWindow.mouse['box'] = 'box'
 
     def OnZBulk(self, event):
         """Z bulk-labeling selected lines/boundaries"""
         if not self.digit.IsVector3D():
-            GError(parent = self.parent,
-                   message = _("Vector map is not 3D. Operation canceled."))
+            GError(parent=self.parent,
+                   message=_("Vector map is not 3D. Operation canceled."))
             return
-        
-        if self.action['desc'] == 'zbulkLine': # select previous action
+
+        if self.action['desc'] == 'zbulkLine':  # select previous action
             self.ToggleTool(self.addPoint, True)
             self.ToggleTool(self.additionalTools, False)
             self.OnAddPoint(event)
             return
-        
+
         Debug.msg(2, "Digittoolbar.OnZBulk():")
-        self.action = { 'desc' : "zbulkLine",
-                        'id'   : self.additionalTools }
+        self.action = {'desc': "zbulkLine",
+                       'id': self.additionalTools}
         self.MapWindow.mouse['box'] = 'line'
 
     def OnTypeConversion(self, event):
@@ -764,27 +785,28 @@
          - point <-> centroid
          - line <-> boundary
         """
-        if self.action['desc'] == 'typeConv': # select previous action
+        if self.action['desc'] == 'typeConv':  # select previous action
             self.ToggleTool(self.addPoint, True)
             self.ToggleTool(self.additionalTools, False)
             self.OnAddPoint(event)
             return
-        
+
         Debug.msg(2, "Digittoolbar.OnTypeConversion():")
-        self.action = { 'desc' : "typeConv",
-                        'id'   : self.additionalTools }
+        self.action = {'desc': "typeConv",
+                       'id': self.additionalTools}
         self.MapWindow.mouse['box'] = 'box'
 
-    def OnSelectMap (self, event):
+    def OnSelectMap(self, event):
         """Select vector map layer for editing
 
         If there is a vector map layer already edited, this action is
         firstly terminated. The map layer is closed. After this the
         selected map layer activated for editing.
         """
-        if event.GetSelection() == 0: # create new vector map layer
+        if event.GetSelection() == 0:  # create new vector map layer
             if self.mapLayer:
-                openVectorMap = self.mapLayer.GetName(fullyQualified = False)['name']
+                openVectorMap = self.mapLayer.GetName(
+                    fullyQualified=False)['name']
             else:
                 openVectorMap = None
             dlg = CreateNewVector(self.parent,
@@ -792,19 +814,19 @@
                                   cmd=(('v.edit',
                                         {'tool': 'create'},
                                         'map')),
-                                  disableAdd = True)
-            
+                                  disableAdd=True)
+
             if dlg and dlg.GetName():
                 # add layer to map layer tree
                 if self._giface.GetLayerTree():
                     mapName = dlg.GetName() + '@' + grass.gisenv()['MAPSET']
-                    self._giface.GetLayerList().AddLayer(ltype='vector',
-                                                         name=mapName, checked=True,
-                                                         cmd=['d.vect', 'map=%s' % mapName])
-                    
-                    vectLayers = self.UpdateListOfLayers(updateTool = True)
+                    self._giface.GetLayerList().AddLayer(
+                        ltype='vector', name=mapName, checked=True,
+                        cmd=['d.vect', 'map=%s' % mapName])
+
+                    vectLayers = self.UpdateListOfLayers(updateTool=True)
                     selection = vectLayers.index(mapName)
-                
+
                 # create table ?
                 if dlg.IsChecked('table'):
                     # TODO: replace this by signal
@@ -813,7 +835,7 @@
                     # than starting randomly from mapdisp and lmgr
                     lmgr = self.parent.GetLayerManager()
                     if lmgr:
-                        lmgr.OnShowAttributeTable(None, selection = 'table')
+                        lmgr.OnShowAttributeTable(None, selection='table')
                 dlg.Destroy()
             else:
                 self.combo.SetValue(_('Select vector map'))
@@ -821,21 +843,21 @@
                     dlg.Destroy()
                 return
         else:
-            selection = event.GetSelection() - 1 # first option is 'New vector map'
-        
+            selection = event.GetSelection() - 1  # first option is 'New vector map'
+
         # skip currently selected map
         if self.layers[selection] == self.mapLayer:
             return
-        
+
         if self.mapLayer:
             # deactive map layer for editing
             self.StopEditing()
-        
+
         # select the given map layer for editing
         self.StartEditing(self.layers[selection])
-        
+
         event.Skip()
-        
+
     def StartEditing(self, mapLayer):
         """Start editing selected vector map layer.
 
@@ -843,55 +865,68 @@
         """
         # check if topology is available (skip for hidden - temporary
         # maps, see iclass for details)
-        if not mapLayer.IsHidden() and grass.vector_info(mapLayer.GetName())['level'] != 2:
-            dlg = wx.MessageDialog(parent = self.MapWindow,
-                                   message = _("Topology for vector map <%s> is not available. "
-                                               "Topology is required by digitizer.\nDo you want to "
-                                               "rebuild topology (takes some time) and open the vector map "
-                                               "for editing?") % mapLayer.GetName(),
-                                   caption=_("Digitizer error"),
-                                   style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
+        if not mapLayer.IsHidden() and grass.vector_info(
+                mapLayer.GetName())['level'] != 2:
+            dlg = wx.MessageDialog(
+                parent=self.MapWindow,
+                message=_(
+                    "Topology for vector map <%s> is not available. "
+                    "Topology is required by digitizer.\nDo you want to "
+                    "rebuild topology (takes some time) and open the vector map "
+                    "for editing?") %
+                mapLayer.GetName(),
+                caption=_("Digitizer error"),
+                style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
             if dlg.ShowModal() == wx.ID_YES:
                 RunCommand('v.build', map=mapLayer.GetName())
             else:
                 return
-        
+
         # deactive layer
         self.Map.ChangeLayerActive(mapLayer, False)
-        
+
         # clean map canvas
         self.MapWindow.EraseMap()
-        
+
         # unset background map if needed
         if mapLayer:
-            if UserSettings.Get(group = 'vdigit', key = 'bgmap',
-                                subkey = 'value', settings_type='internal') == mapLayer.GetName():
-                UserSettings.Set(group = 'vdigit', key = 'bgmap',
-                                 subkey='value', value='', settings_type='internal')
-            
+            if UserSettings.Get(
+                    group='vdigit', key='bgmap', subkey='value',
+                    settings_type='internal') == mapLayer.GetName():
+                UserSettings.Set(
+                    group='vdigit',
+                    key='bgmap',
+                    subkey='value',
+                    value='',
+                    settings_type='internal')
+
             self.parent.SetStatusText(_("Please wait, "
-                                        "opening vector map <%s> for editing...") % mapLayer.GetName(),
-                                        0)
-        
+                                        "opening vector map <%s> for editing...") %
+                                      mapLayer.GetName(), 0)
+
         self.MapWindow.pdcVector = wx.PseudoDC()
-        self.digit = self.MapWindow.digit = self.digitClass(mapwindow = self.MapWindow)
-        
+        self.digit = self.MapWindow.digit = self.digitClass(
+            mapwindow=self.MapWindow)
+
         self.mapLayer = mapLayer
-        # open vector map (assume that 'hidden' map layer is temporary vector map)
-        if self.digit.OpenMap(mapLayer.GetName(), tmp = mapLayer.IsHidden()) is None:
+        # open vector map (assume that 'hidden' map layer is temporary vector
+        # map)
+        if self.digit.OpenMap(
+                mapLayer.GetName(),
+                tmp=mapLayer.IsHidden()) is None:
             self.mapLayer = None
             self.StopEditing()
             return False
-        
+
         # check feature type (only for OGR layers)
         self.fType = self.digit.GetFeatureType()
         self.EnableAll()
         self.EnableUndo(False)
         self.EnableRedo(False)
-        
+
         if self.fType == 'point':
-            for tool in (self.addLine, self.addArea, self.moveVertex, self.addVertex,
-                         self.removeVertex, self.editLine):
+            for tool in (self.addLine, self.addArea, self.moveVertex,
+                         self.addVertex, self.removeVertex, self.editLine):
                 self.EnableTool(tool, False)
         elif self.fType == 'linestring':
             for tool in (self.addPoint, self.addArea):
@@ -900,40 +935,44 @@
             for tool in (self.addPoint, self.addLine):
                 self.EnableTool(tool, False)
         elif self.fType:
-            GError(parent = self,
-                   message = _("Unsupported feature type '%(type)s'. Unable to edit "
-                               "OGR layer <%(layer)s>.") % { 'type' : self.fType,
-                                                             'layer' : mapLayer.GetName() })
+            GError(
+                parent=self,
+                message=_(
+                    "Unsupported feature type '%(type)s'. Unable to edit "
+                    "OGR layer <%(layer)s>.") %
+                {'type': self.fType, 'layer': mapLayer.GetName()})
             self.digit.CloseMap()
             self.mapLayer = None
             self.StopEditing()
             return False
-        
+
         # update toolbar
         if self.combo:
             self.combo.SetValue(mapLayer.GetName())
         if 'map' in self.parent.toolbars:
-            self.parent.toolbars['map'].combo.SetValue (_('Vector digitizer'))
-        
+            self.parent.toolbars['map'].combo.SetValue(_('Vector digitizer'))
+
         # here was dead code to enable vdigit button in toolbar
         # with if to ignore iclass
         # some signal (DigitizerStarted) can be emitted here
-        
-        Debug.msg (4, "VDigitToolbar.StartEditing(): layer=%s" % mapLayer.GetName())
-        
+
+        Debug.msg(
+            4, "VDigitToolbar.StartEditing(): layer=%s" %
+            mapLayer.GetName())
+
         # change cursor
         if self.MapWindow.mouse['use'] == 'pointer':
             self.MapWindow.SetNamedCursor('cross')
-        
+
         if not self.MapWindow.resize:
-            self.MapWindow.UpdateMap(render = True)
-        
+            self.MapWindow.UpdateMap(render=True)
+
         # respect opacity
         opacity = mapLayer.GetOpacity()
-        
+
         if opacity < 1.0:
             alpha = int(opacity * 255)
-            self.digit.GetDisplay().UpdateSettings(alpha = alpha)
+            self.digit.GetDisplay().UpdateSettings(alpha=alpha)
 
         # emit signal
         layerTree = self._giface.GetLayerTree()
@@ -941,7 +980,9 @@
             item = layerTree.FindItemByData('maplayer', self.mapLayer)
         else:
             item = None
-        self.editingStarted.emit(vectMap = mapLayer.GetName(), digit = self.digit, layerItem = item)
+        self.editingStarted.emit(
+            vectMap=mapLayer.GetName(),
+            digit=self.digit, layerItem=item)
 
         return True
 
@@ -952,115 +993,127 @@
         :return: False on failure
         """
         item = None
-        
+
         if self.combo:
-            self.combo.SetValue (_('Select vector map'))
-        
+            self.combo.SetValue(_('Select vector map'))
+
         # save changes
         if self.mapLayer:
-            Debug.msg (4, "VDigitToolbar.StopEditing(): layer=%s" % self.mapLayer.GetName())
-            if UserSettings.Get(group = 'vdigit', key = 'saveOnExit', subkey = 'enabled') is False:
+            Debug.msg(
+                4, "VDigitToolbar.StopEditing(): layer=%s" %
+                self.mapLayer.GetName())
+            if UserSettings.Get(group='vdigit', key='saveOnExit',
+                                subkey='enabled') is False:
                 if self.digit.GetUndoLevel() > -1:
-                    dlg = wx.MessageDialog(parent = self.parent,
-                                           message = _("Do you want to save changes "
-                                                     "in vector map <%s>?") % self.mapLayer.GetName(),
-                                           caption = _("Save changes?"),
-                                           style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+                    dlg = wx.MessageDialog(
+                        parent=self.parent,
+                        message=_(
+                            "Do you want to save changes "
+                            "in vector map <%s>?") %
+                        self.mapLayer.GetName(),
+                        caption=_("Save changes?"),
+                        style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
                     if dlg.ShowModal() == wx.ID_NO:
                         # revert changes
                         self.digit.Undo(0)
                     dlg.Destroy()
-            
+
             self.parent.SetStatusText(_("Please wait, "
                                         "closing and rebuilding topology of "
-                                        "vector map <%s>...") % self.mapLayer.GetName(),
-                                      0)
+                                        "vector map <%s>...") %
+                                      self.mapLayer.GetName(), 0)
             self.digit.CloseMap()
 
             # close open background map if any
-            bgMap = UserSettings.Get(group = 'vdigit', key = 'bgmap', subkey = 'value',
-                                     settings_type='internal')
+            bgMap = UserSettings.Get(
+                group='vdigit',
+                key='bgmap',
+                subkey='value',
+                settings_type='internal')
             if bgMap:
                 self.digit.CloseBackgroundMap()
-                self.editingBgMap.emit(mapName = bgMap, unset=True)
-            
+                self.editingBgMap.emit(mapName=bgMap, unset=True)
+
             self._giface.GetProgress().SetValue(0)
-            self._giface.WriteCmdLog(_("Editing of vector map <%s> successfully finished") % \
-                                         self.mapLayer.GetName(),
-                                     notification=Notification.HIGHLIGHT)
+            self._giface.WriteCmdLog(
+                _("Editing of vector map <%s> successfully finished") %
+                self.mapLayer.GetName(),
+                notification=Notification.HIGHLIGHT)
             # re-active layer
             layerTree = self._giface.GetLayerTree()
             if layerTree:
                 item = layerTree.FindItemByData('maplayer', self.mapLayer)
                 if item and layerTree.IsItemChecked(item):
                     self.Map.ChangeLayerActive(self.mapLayer, True)
-        
+
         # change cursor
         self.MapWindow.SetNamedCursor('default')
         self.MapWindow.pdcVector = None
-        
+
         # close dialogs
         for dialog in ('attributes', 'category'):
             if self.parent.dialogs[dialog]:
                 self.parent.dialogs[dialog].Close()
                 self.parent.dialogs[dialog] = None
-        
+
         self.digit = None
         self.MapWindow.digit = None
 
-        self.editingStopped.emit(layerItem = item)
-        
+        self.editingStopped.emit(layerItem=item)
+
         self.mapLayer = None
-        
+
         self.MapWindow.redrawAll = True
 
         return True
-    
-    def UpdateListOfLayers (self, updateTool = False):
+
+    def UpdateListOfLayers(self, updateTool=False):
         """Update list of available vector map layers.
         This list consists only editable layers (in the current mapset)
 
         :param updateTool: True to update also toolbar
         :type updateTool: bool
         """
-        Debug.msg (4, "VDigitToolbar.UpdateListOfLayers(): updateTool=%d" % \
-                   updateTool)
-        
+        Debug.msg(4, "VDigitToolbar.UpdateListOfLayers(): updateTool=%d" %
+                  updateTool)
+
         layerNameSelected = None
-         # name of currently selected layer
+        # name of currently selected layer
         if self.mapLayer:
             layerNameSelected = self.mapLayer.GetName()
-        
+
         # select vector map layer in the current mapset
         layerNameList = []
-        self.layers = self.Map.GetListOfLayers(ltype = "vector",
-                                               mapset = grass.gisenv()['MAPSET'])
-        
+        self.layers = self.Map.GetListOfLayers(ltype="vector",
+                                               mapset=grass.gisenv()['MAPSET'])
+
         for layer in self.layers:
-            if not layer.name in layerNameList: # do not duplicate layer
-                layerNameList.append (layer.GetName())
-        
-        if updateTool: # update toolbar
+            if not layer.name in layerNameList:  # do not duplicate layer
+                layerNameList.append(layer.GetName())
+
+        if updateTool:  # update toolbar
             if not self.mapLayer:
                 value = _('Select vector map')
             else:
                 value = layerNameSelected
-            
+
             if not self.comboid:
                 if not self.tools or 'selector' in self.tools:
-                    self.combo = wx.ComboBox(self, id = wx.ID_ANY, value = value,
-                                             choices = [_('New vector map'), ] + layerNameList, size = (80, -1),
-                                             style = wx.CB_READONLY)
+                    self.combo = wx.ComboBox(
+                        self, id=wx.ID_ANY, value=value,
+                        choices=[_('New vector map'), ] + layerNameList,
+                        size=(80, -1),
+                        style=wx.CB_READONLY)
                     self.comboid = self.InsertControl(0, self.combo)
-                    self.parent.Bind(wx.EVT_COMBOBOX, self.OnSelectMap, self.comboid)
+                    self.parent.Bind(
+                        wx.EVT_COMBOBOX, self.OnSelectMap, self.comboid)
             else:
                 self.combo.SetItems([_('New vector map'), ] + layerNameList)
-            
+
             self.Realize()
-        
+
         return layerNameList
 
     def GetLayer(self):
         """Get selected layer for editing -- MapLayer instance"""
         return self.mapLayer
-

Modified: grass/trunk/gui/wxpython/vdigit/wxdigit.py
===================================================================
--- grass/trunk/gui/wxpython/vdigit/wxdigit.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/vdigit/wxdigit.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -44,149 +44,156 @@
 except ImportError:
     pass
 
+
 class VDigitError:
+
     def __init__(self, parent):
         """Class for managing error messages of vector digitizer
 
         :param parent: parent window for dialogs
         """
-        self.parent  = parent
+        self.parent = parent
         self.caption = _('Digitization Error')
-    
-    def NoMap(self, name = None):
+
+    def NoMap(self, name=None):
         """No map for editing"""
         if name:
             message = _('Unable to open vector map <%s>.') % name
         else:
-            message =  _('No vector map open for editing.')
+            message = _('No vector map open for editing.')
         GError(message + ' ' + _('Operation canceled.'),
-               parent  = self.parent,
-               caption = self.caption)
+               parent=self.parent,
+               caption=self.caption)
 
     def WriteLine(self):
         """Writing line failed
         """
-        GError(message = _('Writing new feature failed. '
-                           'Operation canceled.\n\n'
-                           'Reason: %s') % GetLastError(),
-               parent  = self.parent,
-               caption = self.caption)
+        GError(message=_('Writing new feature failed. '
+                         'Operation canceled.\n\n'
+                         'Reason: %s') % GetLastError(),
+               parent=self.parent,
+               caption=self.caption)
 
     def ReadLine(self, line):
         """Reading line failed
         """
-        GError(message = _('Reading feature id %d failed. '
-                           'Operation canceled.') % line,
-               parent  = self.parent,
-               caption = self.caption)
+        GError(message=_('Reading feature id %d failed. '
+                         'Operation canceled.') % line,
+               parent=self.parent,
+               caption=self.caption)
 
     def DbLink(self, dblink):
         """No dblink available
         """
-        GError(message = _('Database link %d not available. '
-                           'Operation canceled.') % dblink,
-               parent  = self.parent,
-               caption = self.caption)
+        GError(message=_('Database link %d not available. '
+                         'Operation canceled.') % dblink,
+               parent=self.parent,
+               caption=self.caption)
 
     def Driver(self, driver):
         """Staring driver failed
         """
-        GError(message = _('Unable to start database driver <%s>. '
-                           'Operation canceled.') % driver,
-               parent  = self.parent,
-               caption = self.caption)
+        GError(message=_('Unable to start database driver <%s>. '
+                         'Operation canceled.') % driver,
+               parent=self.parent,
+               caption=self.caption)
 
     def Database(self, driver, database):
         """Opening database failed
         """
-        GError(message = _('Unable to open database <%(db)s> by driver <%(driver)s>. '
-                           'Operation canceled.') % { 'db' : database, 'driver' : driver},
-               parent  = self.parent,
-               caption = self.caption)
+        GError(
+            message=_(
+                'Unable to open database <%(db)s> by driver <%(driver)s>. '
+                'Operation canceled.') %
+            {'db': database, 'driver': driver},
+            parent=self.parent, caption=self.caption)
 
     def DbExecute(self, sql):
         """Sql query failed
         """
-        GError(message = _("Unable to execute SQL query '%s'. "
-                           "Operation canceled.") % sql,
-               parent  = self.parent,
-               caption = self.caption)
+        GError(message=_("Unable to execute SQL query '%s'. "
+                         "Operation canceled.") % sql,
+               parent=self.parent,
+               caption=self.caption)
 
     def DeadLine(self, line):
         """Dead line
         """
-        GError(message = _("Feature id %d is marked as dead. "
-                           "Operation canceled.") % line,
-               parent  = self.parent,
-               caption = self.caption)
+        GError(message=_("Feature id %d is marked as dead. "
+                         "Operation canceled.") % line,
+               parent=self.parent,
+               caption=self.caption)
 
     def FeatureType(self, ftype):
         """Unknown feature type
         """
-        GError(message = _("Unsupported feature type %d. "
-                           "Operation canceled.") % ftype,
-               parent  = self.parent,
-               caption = self.caption)
-        
+        GError(message=_("Unsupported feature type %d. "
+                         "Operation canceled.") % ftype,
+               parent=self.parent,
+               caption=self.caption)
+
+
 class IVDigit:
-    def __init__(self, mapwindow, driver = DisplayDriver):
+
+    def __init__(self, mapwindow, driver=DisplayDriver):
         """Base class for vector digitizer (ctypes interface)
-        
+
         :param mapwindow: reference to a map window
         """
-        self.poMapInfo   = None      # pointer to Map_info
+        self.poMapInfo = None      # pointer to Map_info
         self.mapWindow = mapwindow
 
         # background map
-        self.bgMapInfo   = Map_info()
+        self.bgMapInfo = Map_info()
         self.poBgMapInfo = self.popoBgMapInfo = None
-        
+
         # TODO: replace this by using giface
         if not mapwindow.parent.IsStandalone():
             goutput = mapwindow.parent.GetLayerManager().GetLogWindow()
-            log = goutput.GetLog(err = True)
+            log = goutput.GetLog(err=True)
             progress = mapwindow.parent._giface.GetProgress()
         else:
             log = sys.stderr
             progress = None
-        
+
         self.toolbar = mapwindow.parent.toolbars['vdigit']
-        
-        self._error   = VDigitError(parent = self.mapWindow)
-        
-        self._display = driver(device    = mapwindow.pdcVector,
-                               deviceTmp = mapwindow.pdcTmp,
-                               mapObj    = mapwindow.Map,
-                               window    = mapwindow,
-                               glog      = log,
-                               gprogress = progress)
-        
+
+        self._error = VDigitError(parent=self.mapWindow)
+
+        self._display = driver(device=mapwindow.pdcVector,
+                               deviceTmp=mapwindow.pdcTmp,
+                               mapObj=mapwindow.Map,
+                               window=mapwindow,
+                               glog=log,
+                               gprogress=progress)
+
         # GRASS lib
         self.poPoints = Vect_new_line_struct()
-        self.poCats   = Vect_new_cats_struct()
-        
+        self.poCats = Vect_new_cats_struct()
+
         # self.SetCategory()
-        
+
         # layer / max category
         self.cats = dict()
-        
+
         self._settings = dict()
-        self.UpdateSettings() # -> self._settings
-        
+        self.UpdateSettings()  # -> self._settings
+
         # undo/redo
         self.changesets = list()
-        self.changesetCurrent = -1 # first changeset to apply
-        
+        self.changesetCurrent = -1  # first changeset to apply
+
         if self.poMapInfo:
             self.InitCats()
 
         self.emit_signals = False
 
-        # signals which describes features changes during digitization, 
-        # activate them using EmitSignals method 
+        # signals which describes features changes during digitization,
+        # activate them using EmitSignals method
 
-        # currently implemented for functionality used by wx.iclass (for scatter plot)
-        
+        # currently implemented for functionality used by wx.iclass (for
+        # scatter plot)
+
         # signals parameter description:
         # old_bboxs - list of bboxes of boundary features, which covers changed areas
         # it is bbox of old state (before edit)
@@ -197,13 +204,14 @@
         # new_areas_cats list of areas cats of created features / after edit
         # same position in both lists corresponds to same features
 
-        # for description of items in bbox and area_cats lists see return value of _getaAreaBboxCats
+        # for description of items in bbox and area_cats lists see return value
+        # of _getaAreaBboxCats
 
         # TODO currently it is not possible to identify corresponded features
         # in old and new lists (requires changed to vector updated format)
         # TODO return feature type
-        
-        #TODO handle errors?
+
+        # TODO handle errors?
         self.featureAdded = Signal('IVDigit.featureAdded')
         self.areasDeleted = Signal('IVDigit.areasDeleted')
         self.vertexMoved = Signal('IVDigit.vertexMoved')
@@ -219,12 +227,12 @@
         self.poPoints = None
         Vect_destroy_cats_struct(self.poCats)
         self.poCats = None
-        
+
         if self.poBgMapInfo:
             Vect_close(self.poBgMapInfo)
             self.poBgMapInfo = self.popoBgMapInfo = None
             del self.bgMapInfo
-     
+
     def EmitSignals(self, emit):
         """Activate/deactivate signals which describes features changes during digitization.
         """
@@ -234,94 +242,98 @@
         """Close background vector map"""
         if not self.poBgMapInfo:
             return
-        
+
         Vect_close(self.poBgMapInfo)
         self.poBgMapInfo = self.popoBgMapInfo = None
-        
+
     def OpenBackgroundMap(self, bgmap):
         """Open background vector map
 
         .. todo::
             support more background maps then only one
-        
+
         :param bgmap: name of vector map to be opened
         :type bgmap: str
 
         :return: pointer to map_info
         :return: None on error
         """
-        name   = create_string_buffer(GNAME_MAX)
+        name = create_string_buffer(GNAME_MAX)
         mapset = create_string_buffer(GMAPSET_MAX)
         if not G_name_is_fully_qualified(bgmap, name, mapset):
-            name   = str(bgmap)
+            name = str(bgmap)
             mapset = str(G_find_vector2(bgmap, ''))
         else:
-            name   = str(name.value)
+            name = str(name.value)
             mapset = str(mapset.value)
-        
-        if (name == Vect_get_name(self.poMapInfo) and \
+
+        if (name == Vect_get_name(self.poMapInfo) and
                 mapset == Vect_get_mapset(self.poMapInfo)):
             self.poBgMapInfo = self.popoBgMapInfo = None
             self._error.NoMap(bgmap)
             return
-        
+
         self.poBgMapInfo = pointer(self.bgMapInfo)
         self.popoBgMapInfo = pointer(self.poBgMapInfo)
         if Vect_open_old(self.poBgMapInfo, name, mapset) == -1:
             self.poBgMapInfo = self.popoBgMapInfo = None
             self._error.NoMap(bgmap)
             return
-        
+
     def _getSnapMode(self):
         """Get snapping mode
 
          - snap to vertex
          - snap to nodes
          - no snapping
-        
+
         :return: snap mode
         """
         threshold = self._display.GetThreshold()
         if threshold > 0.0:
-            if UserSettings.Get(group = 'vdigit', key = 'snapToVertex', subkey = 'enabled'):
+            if UserSettings.Get(
+                    group='vdigit', key='snapToVertex', subkey='enabled'):
                 return SNAPVERTEX
             else:
                 return SNAP
         else:
             return NO_SNAP
-    
+
     def _getNewFeaturesLayer(self):
         """Returns layer of new feature (from settings)"""
-        if UserSettings.Get(group = 'vdigit', key = "categoryMode", subkey = 'selection') == 2:
-            layer = -1 # -> no category
+        if UserSettings.Get(group='vdigit', key="categoryMode",
+                            subkey='selection') == 2:
+            layer = -1  # -> no category
         else:
-            layer = UserSettings.Get(group = 'vdigit', key = "layer", subkey = 'value')
-        
+            layer = UserSettings.Get(
+                group='vdigit', key="layer", subkey='value')
+
         return layer
-        
+
     def _getNewFeaturesCat(self):
         """Returns category of new feature (from settings)"""
-        if UserSettings.Get(group = 'vdigit', key = "categoryMode", subkey = 'selection') == 2:
-            cat   = -1
+        if UserSettings.Get(group='vdigit', key="categoryMode",
+                            subkey='selection') == 2:
+            cat = -1
         else:
-            cat   = self.SetCategory()
-        
+            cat = self.SetCategory()
+
         return cat
-        
+
     def _breakLineAtIntersection(self, line, pointsLine):
         """Break given line at intersection
 
         :param line: line id
         :param pointsLine: line geometry
-        
+
         :return: number of modified lines
         """
         if not self._checkMap():
             return -1
-        
+
         if not Vect_line_alive(self.poMapInfo, line):
             return 0
-        
+
         if not pointsLine:
             if Vect_read_line(self.poMapInfo, self.poPoints, None, line) < 0:
                 self._error.ReadLine(line)
@@ -329,19 +341,19 @@
             points = self.poPoints
         else:
             points = pointsLine
-        
-        listLine  = Vect_new_boxlist(0)
-        listRef   = Vect_new_list()
+
+        listLine = Vect_new_boxlist(0)
+        listRef = Vect_new_list()
         listBreak = Vect_new_list()
-    
+
         pointsCheck = Vect_new_line_struct()
-    
+
         lineBox = bound_box()
         # find all relevant lines
         Vect_get_line_box(self.poMapInfo, line, byref(lineBox))
         Vect_select_lines_by_box(self.poMapInfo, byref(lineBox),
                                  GV_LINES, listLine)
-    
+
         # check for intersection
         Vect_list_append(listBreak, line)
         Vect_list_append(listRef, line)
@@ -349,26 +361,27 @@
             lineBreak = listLine.contents.id[i]
             if lineBreak == line:
                 continue
-            
-            ltype = Vect_read_line(self.poMapInfo, pointsCheck, None, lineBreak)
+
+            ltype = Vect_read_line(
+                self.poMapInfo, pointsCheck, None, lineBreak)
             if not (ltype & GV_LINES):
                 continue
-            
+
             if Vect_line_check_intersection(self.poPoints, pointsCheck,
                                             WITHOUT_Z):
                 Vect_list_append(listBreak, lineBreak)
-        
+
         ret = Vect_break_lines_list(self.poMapInfo, listBreak, listRef,
                                     GV_LINES, None)
-        
+
         Vect_destroy_line_struct(pointsCheck)
 
         Vect_destroy_boxlist(listLine)
         Vect_destroy_list(listBreak)
         Vect_destroy_list(listRef)
-        
+
         return ret
-    
+
     def _addChangeset(self):
 
         # disable redo
@@ -381,17 +394,17 @@
         for i in range(Vect_get_num_updated_lines(self.poMapInfo) - 1, -1, -1):
             line = Vect_get_updated_line(self.poMapInfo, i)
             offset = Vect_get_updated_line_offset(self.poMapInfo, i)
-            data.append({ 'line'   : line,
-                          'offset' : offset })
-        
+            data.append({'line': line,
+                         'offset': offset})
+
         self.changesetCurrent += 1
         self.changesets.insert(self.changesetCurrent, data)
-        
+
         Vect_reset_updated(self.poMapInfo)
-                
+
     def _applyChangeset(self, changeset, undo):
         """Apply changeset (undo/redo changeset)
-        
+
         :param changeset: changeset id
         :param undo: True for undo otherwise redo
         :type undo: bool
@@ -402,10 +415,10 @@
         """
         if changeset < 0 or changeset >= len(self.changesets):
             return -1
-        
+
         ret = 0
         actions = self.changesets[changeset]
-        
+
         if undo:
             firstaction = 0
             lastaction = len(actions)
@@ -421,45 +434,57 @@
             if action['offset'] > 0:
                 # feature previously added -> to be deleted
                 if Vect_line_alive(self.poMapInfo, line):
-                    Debug.msg(3, "IVDigit._applyChangeset(): changeset=%d, action=add, line=%d -> deleted",
-                              changeset, line)
-                    
+                    Debug.msg(
+                        3,
+                        "IVDigit._applyChangeset(): changeset=%d, action=add, line=%d -> deleted",
+                        changeset,
+                        line)
+
                     Vect_delete_line(self.poMapInfo, line)
                     ret = 1
                 else:
-                    Debug.msg(3, "Digit.ApplyChangeset(): changeset=%d, action=add, line=%d dead",
-                              changeset, line)
+                    Debug.msg(
+                        3,
+                        "Digit.ApplyChangeset(): changeset=%d, action=add, line=%d dead",
+                        changeset,
+                        line)
             else:
                 # feature previously deleted -> to be added
                 offset = abs(action['offset'])
-                
+
                 if not Vect_line_alive(self.poMapInfo, line):
-                    Debug.msg(3, "Digit.ApplyChangeset(): changeset=%d, action=delete, line=%d -> added",
-                              changeset, line)
-                    
+                    Debug.msg(
+                        3,
+                        "Digit.ApplyChangeset(): changeset=%d, action=delete, line=%d -> added",
+                        changeset,
+                        line)
+
                     if Vect_restore_line(self.poMapInfo, offset, line) < 0:
                         return -1
                     ret = 1
                 else:
-                    Debug.msg(3, "Digit.ApplyChangeset(): changeset=%d, action=delete, line=%d alive",
-                              changeset, line)
+                    Debug.msg(
+                        3,
+                        "Digit.ApplyChangeset(): changeset=%d, action=delete, line=%d alive",
+                        changeset,
+                        line)
 
             action['offset'] *= -1
         Vect_reset_updated(self.poMapInfo)
-        
+
         return ret
-    
+
     def AddFeature(self, ftype, points):
         """Add new feature
-        
+
         :param ftype: feature type (point, line, centroid, boundary)
         :param points: tuple of points ((x, y), (x, y), ...)
-        
+
         :return: tuple (number of added features, feature ids)
         """
         layer = self._getNewFeaturesLayer()
         cat = self._getNewFeaturesCat()
-        
+
         if ftype == 'point':
             vtype = GV_POINT
         elif ftype == 'line':
@@ -471,22 +496,23 @@
         elif ftype == 'area':
             vtype = GV_AREA
         else:
-            GError(parent = self.mapWindow,
-                   message = _("Unknown feature type '%s'") % ftype)
+            GError(parent=self.mapWindow,
+                   message=_("Unknown feature type '%s'") % ftype)
             return (-1, None)
-        
+
         if vtype & GV_LINES and len(points) < 2:
-            GError(parent = self.mapWindow,
-                   message = _("Not enough points for line"))
+            GError(parent=self.mapWindow,
+                   message=_("Not enough points for line"))
             return (-1, None)
-        
+
         self.toolbar.EnableUndo()
 
-        ret = self._addFeature(vtype, points, layer, cat,
-                               self._getSnapMode(), self._display.GetThreshold())
+        ret = self._addFeature(
+            vtype, points, layer, cat, self._getSnapMode(),
+            self._display.GetThreshold())
         if ret[0] > -1 and self.emit_signals:
-            self.featureAdded.emit(new_bboxs=[self._createBbox(points)], 
-                                   new_areas_cats=[[{layer : [cat]}, None]])
+            self.featureAdded.emit(new_bboxs=[self._createBbox(points)],
+                                   new_areas_cats=[[{layer: [cat]}, None]])
 
         return ret
 
@@ -497,38 +523,41 @@
         """
         if not self._checkMap():
             return -1
-        
+
         # collect categories for deleting if requested
-        deleteRec = UserSettings.Get(group = 'vdigit', key = 'delRecord', subkey = 'enabled')
+        deleteRec = UserSettings.Get(
+            group='vdigit',
+            key='delRecord',
+            subkey='enabled')
         catDict = dict()
 
         old_bboxs = []
         old_areas_cats = []
         if deleteRec:
             for i in self._display.selected['ids']:
-                
+
                 if Vect_read_line(self.poMapInfo, None, self.poCats, i) < 0:
                     self._error.ReadLine(i)
-                
+
                 if self.emit_signals:
                     ret = self._getLineAreaBboxCats(i)
                     if ret:
                         old_bboxs += ret[0]
                         old_areas_cats += ret[1]
-                
+
                 # catDict was not used -> put into comment
                 #cats = self.poCats.contents
-                #for j in range(cats.n_cats):
+                # for j in range(cats.n_cats):
                 #    if cats.field[j] not in catDict.keys():
                 #        catDict[cats.field[j]] = list()
                 #    catDict[cats.field[j]].append(cats.cat[j])
-        
+
         poList = self._display.GetSelectedIList()
         nlines = Vedit_delete_lines(self.poMapInfo, poList)
-        
+
         Vect_destroy_list(poList)
         self._display.selected['ids'] = list()
-        
+
         if nlines > 0:
             if deleteRec:
                 self._deleteRecords(catDict)
@@ -536,97 +565,99 @@
             self.toolbar.EnableUndo()
 
             if self.emit_signals:
-                self.featuresDeleted.emit(old_bboxs=old_bboxs, 
+                self.featuresDeleted.emit(old_bboxs=old_bboxs,
                                           old_areas_cats=old_areas_cats)
 
         return nlines
-            
+
     def _deleteRecords(self, cats):
         """Delete records from attribute table
-        
+
         :param cats: directory field/list of cats
         """
-        handle   = dbHandle()
+        handle = dbHandle()
         poHandle = pointer(handle)
-        stmt     = dbString()
-        poStmt   = pointer(stmt)
-        
+        stmt = dbString()
+        poStmt = pointer(stmt)
+
         for dblink in range(Vect_get_num_dblinks(self.poMapInfo)):
             poFi = Vect_get_dblink(self.poMapInfo, dblink)
             if poFi is None:
                 self._error.DbLink(dblink)
                 return -1
-            
+
             Fi = poFi.contents
             if Fi.number not in cats.keys():
                 continue
-            
+
             poDriver = db_start_driver(Fi.driver)
             if poDriver is None:
                 self._error.Driver(Fi.driver)
                 return -1
-            
+
             db_init_handle(poHandle)
             db_set_handle(poHandle, Fi.database, None)
             if db_open_database(poDriver, poHandle) != DB_OK:
                 self._error.Database(Fi.driver, Fi.database)
                 return -1
-            
+
             db_init_string(poStmt)
             db_set_string(poStmt, "DELETE FROM %s WHERE" % Fi.table)
             n_cats = 0
             for cat in cats[Fi.number]:
                 if n_cats > 0:
                     db_append_string(poStmt, " or")
-                    
+
                 db_append_string(poStmt, " %s = %d" % (Fi.key, cat))
                 n_cats += 1
-            
+
             if n_cats > 0 and \
                     db_execute_immediate(poDriver, poStmt) != DB_OK:
                 self._error.DbExecute(db_get_string(poStmt))
                 return -1
-            
+
             db_close_database_shutdown_driver(poDriver)
-        
+
     def DeleteSelectedAreas(self):
         """Delete selected areas (centroid+boundaries)
 
-        :return: number of deleted 
+        :return: number of deleted
         """
         if len(self._display.selected['ids']) < 1:
             return 0
-        
+
         poList = self._display.GetSelectedIList()
-        cList  = poList.contents
-        
+        cList = poList.contents
+
         nareas = 0
         old_bboxs = []
         old_areas_cats = []
 
         for i in range(cList.n_values):
 
-            if Vect_get_line_type(self.poMapInfo, cList.value[i]) != GV_CENTROID:
+            if Vect_get_line_type(self.poMapInfo, cList.value[
+                                  i]) != GV_CENTROID:
                 continue
 
             if self.emit_signals:
-                area = Vect_get_centroid_area(self.poMapInfo, cList.value[i]);
-                if area > 0: 
+                area = Vect_get_centroid_area(self.poMapInfo, cList.value[i])
+                if area > 0:
                     bbox, cats = self._getaAreaBboxCats(area)
                     old_bboxs += bbox
                     old_areas_cats += cats
 
-            nareas += Vedit_delete_area_centroid(self.poMapInfo, cList.value[i])
-        
+            nareas += Vedit_delete_area_centroid(
+                self.poMapInfo, cList.value[i])
+
         if nareas > 0:
             self._addChangeset()
             self.toolbar.EnableUndo()
             if self.emit_signals:
-                self.areasDeleted.emit(old_bboxs=old_bboxs, 
-                                       old_areas_cats=old_areas_cats)        
+                self.areasDeleted.emit(old_bboxs=old_bboxs,
+                                       old_areas_cats=old_areas_cats)
 
         return nareas
-   
+
     def _getLineAreaBboxCats(self, ln_id):
         """Helper function
 
@@ -637,23 +668,24 @@
         ltype = Vect_read_line(self.poMapInfo, None, None, ln_id)
 
         if ltype == GV_CENTROID:
-            #TODO centroid opttimization, can be edited also its area -> it will appear two times in new_ lists
+            # TODO centroid opttimization, can be edited also its area -> it
+            # will appear two times in new_ lists
             return self._getCentroidAreaBboxCats(ln_id)
-        else: 
-            return [self._getBbox(ln_id)], [self._getLineAreasCategories(ln_id)]
+        else:
+            return [self._getBbox(ln_id)], [
+                self._getLineAreasCategories(ln_id)]
 
-
     def _getCentroidAreaBboxCats(self, centroid):
         """Helper function
 
-        :param centroid: id of an centroid 
+        :param centroid: id of an centroid
         :return: None if area does not exists
         :return: see return of :func:`_getaAreaBboxCats`
         """
         if not Vect_line_alive(self.poMapInfo, centroid):
             return None
 
-        area = Vect_get_centroid_area(self.poMapInfo, centroid)  
+        area = Vect_get_centroid_area(self.poMapInfo, centroid)
         if area > 0:
             return self._getaAreaBboxCats(area)
         else:
@@ -663,12 +695,12 @@
         """Helper function
 
         :param area: area id
-        :return: list of categories :func:`_getLineAreasCategories` and 
+        :return: list of categories :func:`_getLineAreasCategories` and
                  list of bboxes :func:`_getBbox` of area boundary
                  features
         """
         po_b_list = Vect_new_list()
-        Vect_get_area_boundaries(self.poMapInfo, area, po_b_list);
+        Vect_get_area_boundaries(self.poMapInfo, area, po_b_list)
         b_list = po_b_list.contents
 
         geoms = []
@@ -677,26 +709,26 @@
         if b_list.n_values > 0:
             for i_line in range(b_list.n_values):
 
-                line = b_list.value[i_line];
+                line = b_list.value[i_line]
 
                 geoms.append(self._getBbox(abs(line)))
                 areas_cats.append(self._getLineAreasCategories(abs(line)))
-        
-        Vect_destroy_list(po_b_list);
 
+        Vect_destroy_list(po_b_list)
+
         return geoms, areas_cats
 
     def _getLineAreasCategories(self, ln_id):
         """Helper function
 
-        :param line_id: id of boundary feature 
+        :param line_id: id of boundary feature
         :return: categories of areas on the left, right side of the feature
         :return: format: [[{layer : [cat]}, None]] means:
-                area to the left (list of layers which has cats list as values), 
-                area to the right (no area there in this case (None)) 
+                area to the left (list of layers which has cats list as values),
+                area to the right (no area there in this case (None))
         :return: [] the feature is not boundary or does not exists
         """
-        if not Vect_line_alive (self.poMapInfo, ln_id):
+        if not Vect_line_alive(self.poMapInfo, ln_id):
             return []
 
         ltype = Vect_read_line(self.poMapInfo, None, None, ln_id)
@@ -708,11 +740,13 @@
         left = c_int()
         right = c_int()
 
-        if Vect_get_line_areas(self.poMapInfo, ln_id, pointer(left), pointer(right)) == 1:
+        if Vect_get_line_areas(
+                self.poMapInfo, ln_id, pointer(left),
+                pointer(right)) == 1:
             areas = [left.value, right.value]
 
             for i, a in enumerate(areas):
-                if a > 0: 
+                if a > 0:
                     centroid = Vect_get_area_centroid(self.poMapInfo, a)
                     if centroid <= 0:
                         continue
@@ -729,7 +763,7 @@
         :return: list of the feature categories [{layer : cats}, next layer...]
         :return: None feature does not exist
         """
-        if not Vect_line_alive (self.poMapInfo, ln_id):
+        if not Vect_line_alive(self.poMapInfo, ln_id):
             return none
 
         poCats = Vect_new_cats_struct()
@@ -741,11 +775,11 @@
 
         cats = {}
         for j in range(cCats.n_cats):
-            if cats.has_key(cCats.field[j]):
+            if cCats.field[j] in cats:
                 cats[cCats.field[j]].append(cCats.cat[j])
             else:
                 cats[cCats.field[j]] = [cCats.cat[j]]
-    
+
         Vect_destroy_cats_struct(poCats)
         return cats
 
@@ -756,7 +790,7 @@
         :return: bbox bounding box of the feature
         :return: None feature does not exist
         """
-        if not Vect_line_alive (self.poMapInfo, ln_id):
+        if not Vect_line_alive(self.poMapInfo, ln_id):
             return None
 
         poPoints = Vect_new_line_struct()
@@ -777,19 +811,19 @@
         """
         bbox = {}
         for pt in points:
-            if not bbox.has_key('maxy'):
+            if 'maxy' not in bbox:
                 bbox['maxy'] = pt[1]
                 bbox['miny'] = pt[1]
                 bbox['maxx'] = pt[0]
                 bbox['minx'] = pt[0]
                 continue
-                
-            if   bbox['maxy'] < pt[1]:
+
+            if bbox['maxy'] < pt[1]:
                 bbox['maxy'] = pt[1]
             elif bbox['miny'] > pt[1]:
                 bbox['miny'] = pt[1]
-                
-            if   bbox['maxx'] < pt[0]:
+
+            if bbox['maxx'] < pt[0]:
                 bbox['maxx'] = pt[0]
             elif bbox['minx'] > pt[0]:
                 bbox['minx'] = pt[0]
@@ -799,7 +833,7 @@
         """Helper function convert geom from ctypes line_pts to python
         list
 
-        :return: coords in python list [(x, y),...] 
+        :return: coords in python list [(x, y),...]
         """
         Points = poPoints.contents
 
@@ -816,14 +850,14 @@
         """
         if not self._checkMap():
             return -1
-        
+
         nsel = len(self._display.selected['ids'])
         if nsel < 1:
-            return -1   
-        
+            return -1
+
         thresh = self._display.GetThreshold()
-        snap   = self._getSnapMode()
-        
+        snap = self._getSnapMode()
+
         poList = self._display.GetSelectedIList()
 
         if self.emit_signals:
@@ -834,15 +868,17 @@
                 if ret:
                     old_bboxs += ret[0]
                     old_areas_cats += ret[1]
-        
+
             Vect_set_updated(self.poMapInfo, 1)
             n_up_lines_old = Vect_get_num_updated_lines(self.poMapInfo)
-        
-        nlines = Vedit_move_lines(self.poMapInfo, self.popoBgMapInfo, int(self.poBgMapInfo is not None),
-                                  poList,
-                                  move[0], move[1], 0,
-                                  snap, thresh)
 
+        nlines = Vedit_move_lines(
+            self.poMapInfo, self.popoBgMapInfo,
+            int(self.poBgMapInfo is not None),
+            poList, move[0],
+            move[1],
+            0, snap, thresh)
+
         Vect_destroy_list(poList)
 
         if nlines > 0 and self.emit_signals:
@@ -859,15 +895,15 @@
         if nlines > 0 and self._settings['breakLines']:
             for i in range(1, nlines):
                 self._breakLineAtIntersection(nlines + i, None, changeset)
-        
+
         if nlines > 0:
             self._addChangeset()
             self.toolbar.EnableUndo()
-            
+
             if self.emit_signals:
                 self.featuresMoved.emit(new_bboxs=new_bboxs,
-                                        old_bboxs=old_bboxs, 
-                                        old_areas_cats=old_areas_cats, 
+                                        old_bboxs=old_bboxs,
+                                        old_areas_cats=old_areas_cats,
                                         new_areas_cats=new_areas_cats)
 
         return nlines
@@ -877,18 +913,18 @@
 
         :param point: location point
         :param move:  x,y direction
-        
+
         :return: id of new feature
         :return: 0 vertex not moved (not found, line is not selected)
         :return: -1 on error
         """
         if not self._checkMap():
             return -1
-        
+
         if len(self._display.selected['ids']) != 1:
             return -1
 
-        # move only first found vertex in bbox 
+        # move only first found vertex in bbox
         poList = self._display.GetSelectedIList()
 
         if self.emit_signals:
@@ -902,12 +938,15 @@
         Vect_reset_line(self.poPoints)
         Vect_append_point(self.poPoints, point[0], point[1], 0.0)
 
-        moved = Vedit_move_vertex(self.poMapInfo, self.popoBgMapInfo, int(self.poBgMapInfo is not None),
-                                  poList, self.poPoints,
-                                  self._display.GetThreshold(type = 'selectThresh'),
-                                  self._display.GetThreshold(),
-                                  move[0], move[1], 0.0,
-                                  1, self._getSnapMode())
+        moved = Vedit_move_vertex(
+            self.poMapInfo, self.popoBgMapInfo,
+            int(self.poBgMapInfo is not None),
+            poList, self.poPoints, self._display.GetThreshold(
+                type='selectThresh'),
+            self._display.GetThreshold(),
+            move[0],
+            move[1],
+            0.0, 1, self._getSnapMode())
         Vect_destroy_list(poList)
 
         if moved > 0 and self.emit_signals:
@@ -923,15 +962,15 @@
         if moved > 0 and self._settings['breakLines']:
             self._breakLineAtIntersection(Vect_get_num_lines(self.poMapInfo),
                                           None)
-        
+
         if moved > 0:
             self._addChangeset()
             self.toolbar.EnableUndo()
 
             if self.emit_signals:
-                self.vertexMoved.emit(new_bboxs=new_bboxs,  
-                                      new_areas_cats=new_areas_cats, 
-                                      old_areas_cats=old_areas_cats, 
+                self.vertexMoved.emit(new_bboxs=new_bboxs,
+                                      new_areas_cats=new_areas_cats,
+                                      old_areas_cats=old_areas_cats,
                                       old_bboxs=old_bboxs)
 
         return moved
@@ -945,8 +984,8 @@
         :return: 0 nothing changed
         :return: -1 on failure
         """
-        added = self._ModifyLineVertex(coords, add = True)
-        
+        added = self._ModifyLineVertex(coords, add=True)
+
         if added > 0:
             self.toolbar.EnableUndo()
 
@@ -961,19 +1000,18 @@
         :return: 0 nothing changed
         :return: -1 on failure
         """
-        deleted = self._ModifyLineVertex(coords, add = False)
-        
+        deleted = self._ModifyLineVertex(coords, add=False)
+
         if deleted > 0:
             self.toolbar.EnableUndo()
 
         return deleted
 
-
     def SplitLine(self, point):
         """Split/break selected line/boundary on given position
 
         :param point: point where to split line
-        
+
         :return: 1 line modified
         :return: 0 nothing changed
         :return: -1 error
@@ -981,19 +1019,19 @@
         thresh = self._display.GetThreshold('selectThresh')
         if not self._checkMap():
             return -1
-        
-        poList  = self._display.GetSelectedIList()
+
+        poList = self._display.GetSelectedIList()
         Vect_reset_line(self.poPoints)
         Vect_append_point(self.poPoints, point[0], point[1], 0.0)
-        
+
         ret = Vedit_split_lines(self.poMapInfo, poList,
                                 self.poPoints, thresh, None)
         Vect_destroy_list(poList)
-        
+
         if ret > 0:
             self._addChangeset()
             self.toolbar.EnableUndo()
-        
+
         return ret
 
     def EditLine(self, line, coords):
@@ -1007,21 +1045,21 @@
         """
         if not self._checkMap():
             return -1
-        
+
         if len(coords) < 2:
             self.DeleteSelectedLines()
             return 0
-        
+
         if not Vect_line_alive(self.poMapInfo, line):
             self._error.DeadLine(line)
             return -1
-        
+
         # read original feature
         ltype = Vect_read_line(self.poMapInfo, None, self.poCats, line)
         if ltype < 0:
             self._error.ReadLine(line)
             return -1
-        
+
         if self.emit_signals:
             old_bboxs = [self._getBbox(line)]
             old_areas_cats = [self._getLineAreasCategories(line)]
@@ -1037,25 +1075,25 @@
             modeSnap = not (snap == SNAP)
             Vedit_snap_line(self.poMapInfo, self.popoBgMapInfo,
                             int(self.poBgMapInfo is not None),
-                           -1, self.poPoints, self._display.GetThreshold(), modeSnap)
-        
+                            -1, self.poPoints, self._display.GetThreshold(), modeSnap)
+
         newline = Vect_rewrite_line(self.poMapInfo, line, ltype,
                                     self.poPoints, self.poCats)
         if newline > 0 and self.emit_signals:
             new_geom = [self._getBbox(newline)]
             new_areas_cats = [self._getLineAreasCategories(newline)]
-        
+
         if newline > 0 and self._settings['breakLines']:
             self._breakLineAtIntersection(newline, None)
-        
+
         if newline > 0:
             self._addChangeset()
             self.toolbar.EnableUndo()
-    
+
             if self.emit_signals:
-                self.lineEdited.emit(old_bboxs=old_bboxs, 
-                                     old_areas_cats=old_areas_cats, 
-                                     new_bboxs=new_bboxs, 
+                self.lineEdited.emit(old_bboxs=old_bboxs,
+                                     old_areas_cats=old_areas_cats,
+                                     new_bboxs=new_bboxs,
                                      new_areas_cats=new_areas_cats)
 
         return newline
@@ -1068,17 +1106,17 @@
         """
         if not self._checkMap():
             return -1
-        
+
         nlines = Vect_get_num_lines(self.poMapInfo)
-        
+
         poList = self._display.GetSelectedIList()
         ret = Vedit_flip_lines(self.poMapInfo, poList)
         Vect_destroy_list(poList)
-        
+
         if ret > 0:
             self._addChangeset()
             self.toolbar.EnableUndo()
-        
+
         return ret
 
     def MergeLine(self):
@@ -1089,15 +1127,15 @@
         """
         if not self._checkMap():
             return -1
-        
+
         poList = self._display.GetSelectedIList()
         ret = Vedit_merge_lines(self.poMapInfo, poList)
         Vect_destroy_list(poList)
-        
+
         if ret > 0:
             self._addChangeset()
             self.toolbar.EnableUndo()
-        
+
         return ret
 
     def BreakLine(self):
@@ -1108,16 +1146,16 @@
         """
         if not self._checkMap():
             return -1
-        
+
         poList = self._display.GetSelectedIList()
         ret = Vect_break_lines_list(self.poMapInfo, poList, None,
                                     GV_LINES, None)
         Vect_destroy_list(poList)
-        
+
         if ret > 0:
             self._addChangeset()
             self.toolbar.EnableUndo()
-        
+
         return ret
 
     def SnapLine(self):
@@ -1128,17 +1166,17 @@
         """
         if not self._checkMap():
             return -1
-        
+
         nlines = Vect_get_num_lines(self.poMapInfo)
         poList = self._display.GetSelectedIList()
         Vect_snap_lines_list(self.poMapInfo, poList,
                              self._display.GetThreshold(), None)
         Vect_destroy_list(poList)
-        
+
         if nlines < Vect_get_num_lines(self.poMapInfo):
             self._addChangeset()
             self.toolbar.EnableUndo()
-        
+
     def ConnectLine(self):
         """Connect selected lines/boundaries
 
@@ -1148,19 +1186,19 @@
         """
         if not self._checkMap():
             return -1
-        
+
         poList = self._display.GetSelectedIList()
         ret = Vedit_connect_lines(self.poMapInfo, poList,
                                   self._display.GetThreshold())
         Vect_destroy_list(poList)
-        
+
         if ret > 0:
             self._addChangeset()
             self.toolbar.EnableUndo()
-        
+
         return ret
-        
-    def CopyLine(self, ids = []):
+
+    def CopyLine(self, ids=[]):
         """Copy features from (background) vector map
 
         :param ids: list of line ids to be copied
@@ -1170,25 +1208,25 @@
         """
         if not self._checkMap():
             return -1
-        
+
         nlines = Vect_get_num_lines(self.poMapInfo)
-        
+
         poList = self._display.GetSelectedIList(ids)
         ret = Vedit_copy_lines(self.poMapInfo, self.poBgMapInfo,
                                poList)
         Vect_destroy_list(poList)
-        
+
         if ret > 0 and self.poBgMapInfo and self._settings['breakLines']:
             for i in range(1, ret):
                 self._breakLineAtIntersection(nlines + i, None)
-        
+
         if ret > 0:
             self._addChangeset()
             self.toolbar.EnableUndo()
-        
+
         return ret
 
-    def CopyCats(self, fromId, toId, copyAttrb = False):
+    def CopyCats(self, fromId, toId, copyAttrb=False):
         """Copy given categories to objects with id listed in ids
 
         :param cats: ids of 'from' feature
@@ -1199,29 +1237,30 @@
         """
         if len(fromId) < 1 or len(toId) < 1:
             return 0
-        
+
         poCatsFrom = self.poCats
-        poCatsTo = Vect_new_cats_struct();
-        
+        poCatsTo = Vect_new_cats_struct()
+
         nlines = 0
-        
+
         for fline in fromId:
             if not Vect_line_alive(self.poMapInfo, fline):
                 continue
-            
+
             if Vect_read_line(self.poMapInfo, None, poCatsFrom, fline) < 0:
                 self._error.ReadLine(fline)
                 return -1
-            
+
             for tline in toId:
                 if not Vect_line_alive(self.poMapInfo, tline):
                     continue
-                
-                ltype = Vect_read_line(self.poMapInfo, self.poPoints, poCatsTo, tline)
+
+                ltype = Vect_read_line(
+                    self.poMapInfo, self.poPoints, poCatsTo, tline)
                 if ltype < 0:
                     self._error.ReadLine(fline)
                     return -1
-                
+
                 catsFrom = poCatsFrom.contents
                 for i in range(catsFrom.n_cats):
                     if not copyAttrb:
@@ -1231,17 +1270,18 @@
                         # duplicate attributes
                         cat = self.cats[catsFrom.field[i]] + 1
                         self.cats[catsFrom.field[i]] = cat
-                        poFi = Vect_get_field(self.poMapInfo, catsFrom.field[i])
+                        poFi = Vect_get_field(
+                            self.poMapInfo, catsFrom.field[i])
                         if not poFi:
                             self._error.DbLink(i)
                             return -1
-                        
+
                         fi = poFi.contents
                         driver = db_start_driver(fi.driver)
                         if not driver:
                             self._error.Driver(fi.driver)
                             return -1
-                        
+
                         handle = dbHandle()
                         db_init_handle(byref(handle))
                         db_set_handle(byref(handle), fi.database, None)
@@ -1249,146 +1289,159 @@
                             db_shutdown_driver(driver)
                             self._error.Database(fi.driver, fi.database)
                             return -1
-                        
+
                         stmt = dbString()
                         db_init_string(byref(stmt))
-                        db_set_string(byref(stmt),
-                                      "SELECT * FROM %s WHERE %s=%d" % (fi.table, fi.key,
-                                                                        catsFrom.cat[i]))
-                        
+                        db_set_string(
+                            byref(stmt), "SELECT * FROM %s WHERE %s=%d" %
+                            (fi.table, fi.key, catsFrom.cat[i]))
+
                         cursor = dbCursor()
-                        if db_open_select_cursor(driver, byref(stmt), byref(cursor),
-                                                 DB_SEQUENTIAL) != DB_OK:
-                                db_close_database_shutdown_driver(driver)
-                                return -1
-                        
+                        if db_open_select_cursor(
+                                driver, byref(stmt),
+                                byref(cursor),
+                                DB_SEQUENTIAL) != DB_OK:
+                            db_close_database_shutdown_driver(driver)
+                            return -1
+
                         table = db_get_cursor_table(byref(cursor))
                         ncols = db_get_table_number_of_columns(table)
-                        
+
                         sql = "INSERT INTO %s VALUES (" % fi.table
                         # fetch the data
                         more = c_int()
                         while True:
-                            if db_fetch(byref(cursor), DB_NEXT, byref(more)) != DB_OK:
+                            if db_fetch(byref(cursor), DB_NEXT,
+                                        byref(more)) != DB_OK:
                                 db_close_database_shutdown_driver(driver)
                                 return -1
                             if not more.value:
                                 break
-                            
+
                             value_string = dbString()
                             for col in range(ncols):
                                 if col > 0:
                                     sql += ","
-                                    
+
                                 column = db_get_table_column(table, col)
                                 if db_get_column_name(column) == fi.key:
                                     sql += "%d" % cat
                                     continue
-                                
+
                                 value = db_get_column_value(column)
-                                db_convert_column_value_to_string(column, byref(value_string))
+                                db_convert_column_value_to_string(
+                                    column, byref(value_string))
                                 if db_test_value_isnull(value):
                                     sql += "NULL"
                                 else:
-                                    ctype = db_sqltype_to_Ctype(db_get_column_sqltype(column))
+                                    ctype = db_sqltype_to_Ctype(
+                                        db_get_column_sqltype(column))
                                     if ctype != DB_C_TYPE_STRING:
                                         sql += db_get_string(byref(value_string))
                                     else:
-                                        sql += "'%s'" % db_get_string(byref(value_string))
-                        
+                                        sql += "'%s'" % db_get_string(
+                                            byref(value_string))
+
                         sql += ")"
                         db_set_string(byref(stmt), sql)
                         if db_execute_immediate(driver, byref(stmt)) != DB_OK:
                             db_close_database_shutdown_driver(driver)
                             return -1
-                        
+
                         db_close_database_shutdown_driver(driver)
                         G_free(poFi)
-                
+
                 if Vect_cat_set(poCatsTo, catsFrom.field[i], cat) < 1:
                     continue
-                
-                if Vect_rewrite_line(self.poMapInfo, tline, ltype, self.poPoints, poCatsTo) < 0:
+
+                if Vect_rewrite_line(self.poMapInfo, tline,
+                                     ltype, self.poPoints, poCatsTo) < 0:
                     self._error.WriteLine()
                     return -1
-                
-                nlines +=1
-        
+
+                nlines += 1
+
         Vect_destroy_cats_struct(poCatsTo)
-        
+
         if nlines > 0:
             self.toolbar.EnableUndo()
-        
+
         return nlines
 
     def _selectLinesByQueryThresh(self):
         """Generic method used for SelectLinesByQuery() -- to get
         threshold value"""
         thresh = 0.0
-        if UserSettings.Get(group = 'vdigit', key = 'query', subkey = 'selection') == 0:
-            thresh = UserSettings.Get(group = 'vdigit', key = 'queryLength', subkey = 'thresh')
-            if UserSettings.Get(group = 'vdigit', key = "queryLength", subkey = 'than-selection') == 0:
+        if UserSettings.Get(group='vdigit', key='query',
+                            subkey='selection') == 0:
+            thresh = UserSettings.Get(
+                group='vdigit', key='queryLength', subkey='thresh')
+            if UserSettings.Get(group='vdigit', key="queryLength",
+                                subkey='than-selection') == 0:
                 thresh = -1 * thresh
         else:
-            thresh = UserSettings.Get(group = 'vdigit', key = 'queryDangle', subkey = 'thresh')
-            if UserSettings.Get(group = 'vdigit', key = "queryDangle", subkey = 'than-selection') == 0:
+            thresh = UserSettings.Get(
+                group='vdigit', key='queryDangle', subkey='thresh')
+            if UserSettings.Get(group='vdigit', key="queryDangle",
+                                subkey='than-selection') == 0:
                 thresh = -1 * thresh
-        
+
         return thresh
 
     def SelectLinesByQuery(self, bbox):
         """Select features by query
-        
+
         .. todo::
             layer / 3D
-        
+
         :param bbox: bounding box definition
         """
         if not self._checkMap():
             return -1
-        
+
         thresh = self._selectLinesByQueryThresh()
-        
+
         query = QUERY_UNKNOWN
-        if UserSettings.Get(group = 'vdigit', key = 'query', subkey = 'selection') == 0:
+        if UserSettings.Get(group='vdigit', key='query',
+                            subkey='selection') == 0:
             query = QUERY_LENGTH
         else:
             query = QUERY_DANGLE
-        
-        ftype = GV_POINTS | GV_LINES # TODO: 3D
-        layer = 1 # TODO
-        
+
+        ftype = GV_POINTS | GV_LINES  # TODO: 3D
+        layer = 1  # TODO
+
         ids = list()
         poList = Vect_new_list()
         coList = poList.contents
-        if UserSettings.Get(group = 'vdigit', key = 'query', subkey = 'box'):
+        if UserSettings.Get(group='vdigit', key='query', subkey='box'):
             Vect_reset_line(self.poPoints)
             x1, y1 = bbox[0]
             x2, y2 = bbox[1]
             z1 = z2 = 0.0
-            
+
             Vect_append_point(self.poPoints, x1, y1, z1)
             Vect_append_point(self.poPoints, x2, y1, z2)
             Vect_append_point(self.poPoints, x2, y2, z1)
             Vect_append_point(self.poPoints, x1, y2, z2)
             Vect_append_point(self.poPoints, x1, y1, z1)
 
-            Vect_select_lines_by_polygon(self.poMapInfo, self.poPoints, 0, None,
-                                         ftype, poList)
-            
+            Vect_select_lines_by_polygon(
+                self.poMapInfo, self.poPoints, 0, None, ftype, poList)
+
             if coList.n_values == 0:
                 return ids
-        
+
         Vedit_select_by_query(self.poMapInfo,
                               ftype, layer, thresh, query,
                               poList)
-        
+
         for i in range(coList.n_values):
             ids.append(int(coList.value[i]))
-            
-        Debug.msg(3, "IVDigit.SelectLinesByQuery(): lines=%d", coList.n_values)    
+
+        Debug.msg(3, "IVDigit.SelectLinesByQuery(): lines=%d", coList.n_values)
         Vect_destroy_list(poList)
-        
+
         return ids
 
     def IsVector3D(self):
@@ -1396,9 +1449,9 @@
         """
         if not self._checkMap():
             return False
-        
+
         return Vect_is_3d(self.poMapInfo)
-    
+
     def GetLineLength(self, line):
         """Get line length
 
@@ -1409,19 +1462,19 @@
         """
         if not self._checkMap():
             return -1
-        
+
         if not Vect_line_alive(self.poMapInfo, line):
             return -1
-    
+
         ltype = Vect_read_line(self.poMapInfo, self.poPoints, None, line)
         if ltype < 0:
             self._error.ReadLine(line)
             return ret
-        
+
         length = -1
-        if ltype & GV_LINES: # lines & boundaries
+        if ltype & GV_LINES:  # lines & boundaries
             length = Vect_line_length(self.poPoints)
-        
+
         return length
 
     def GetAreaSize(self, centroid):
@@ -1434,56 +1487,56 @@
         """
         if not self._checkMap():
             return -1
-        
+
         ltype = Vect_read_line(self.poMapInfo, None, None, centroid)
         if ltype < 0:
             self._error.ReadLine(line)
             return ret
-        
+
         if ltype != GV_CENTROID:
             return -1
-        
+
         area = Vect_get_centroid_area(self.poMapInfo, centroid)
         size = -1
         if area > 0:
             if not Vect_area_alive(self.poMapInfo, area):
                 return size
-            
+
             size = Vect_get_area_area(self.poMapInfo, area)
-        
+
         return size
-        
+
     def GetAreaPerimeter(self, centroid):
         """Get area perimeter
-        
+
         :param centroid: centroid id
-        
+
         :return: area size
         :return: -1 on error
         """
         if not self._checkMap():
             return -1
-        
+
         ltype = Vect_read_line(self.poMapInfo, None, None, centroid)
         if ltype < 0:
             self._error.ReadLine(line)
             return ret
-        
+
         if ltype != GV_CENTROID:
             return -1
-        
+
         area = Vect_get_centroid_area(self.poMapInfo, centroid)
         perimeter = -1
         if area > 0:
             if not Vect_area_alive(self.poMapInfo, area):
                 return -1
-            
+
             Vect_get_area_points(self.poMapInfo, area, self.poPoints)
             perimeter = Vect_area_perimeter(self.poPoints)
-        
+
         return perimeter
-    
-    def SetLineCats(self, line, layer, cats, add = True):
+
+    def SetLineCats(self, line, layer, cats, add=True):
         """Set categories for given line and layer
 
         :param line: feature id
@@ -1496,10 +1549,10 @@
         """
         if not self._checkMap():
             return -1
-        
+
         if line < 1 and len(self._display.selected['ids']) < 1:
             return -1
-        
+
         update = False
         if line == -1:
             update = True
@@ -1507,29 +1560,33 @@
 
         if not Vect_line_alive(self.poMapInfo, line):
             return -1
-        
-        ltype = Vect_read_line(self.poMapInfo, self.poPoints, self.poCats, line)
+
+        ltype = Vect_read_line(
+            self.poMapInfo,
+            self.poPoints,
+            self.poCats,
+            line)
         if ltype < 0:
             self._error.ReadLine(line)
             return -1
-        
+
         for c in cats:
             if add:
                 Vect_cat_set(self.poCats, layer, c)
             else:
                 Vect_field_cat_del(self.poCats, layer, c)
-        
+
         newline = Vect_rewrite_line(self.poMapInfo, line, ltype,
                                     self.poPoints, self.poCats)
-        
+
         if newline > 0:
             self._addChangeset()
             self.toolbar.EnableUndo()
-        
+
         if update:
             # update line id since the line was rewritten
-            self._display.selected['ids'][0] =  newline
-        
+            self._display.selected['ids'][0] = newline
+
         return newline
 
     def TypeConvForSelectedLines(self):
@@ -1544,18 +1601,18 @@
         """
         if not self._checkMap():
             return -1
-        
+
         poList = self._display.GetSelectedIList()
         ret = Vedit_chtype_lines(self.poMapInfo, poList)
         Vect_destroy_list(poList)
-        
+
         if ret > 0:
             self._addChangeset()
             self.toolbar.EnableUndo()
-        
+
         return ret
 
-    def Undo(self, level = -1):
+    def Undo(self, level=-1):
         """Undo action
 
         :param level: levels to undo (0 to revert all)
@@ -1563,47 +1620,53 @@
         :return: id of current changeset
         """
         changesetLast = len(self.changesets) - 1
-        
+
         if changesetLast < 0:
             return changesetLast
-        
+
         if level < 0 and self.changesetCurrent > changesetLast:
             self.changesetCurrent = changesetLast
         elif level == 0:
             # 0 -> undo all
             level = -1 * self.changesetCurrent - 1
-        
-        Debug.msg(2, "Digit.Undo(): changeset_last=%d, changeset_current=%d, level=%d",
-                  changesetLast, self.changesetCurrent, level)
-        
-        if level < 0: # undo
+
+        Debug.msg(
+            2,
+            "Digit.Undo(): changeset_last=%d, changeset_current=%d, level=%d",
+            changesetLast,
+            self.changesetCurrent,
+            level)
+
+        if level < 0:  # undo
             if self.changesetCurrent + level < -1:
                 return self.changesetCurrent
-            for changeset in range(self.changesetCurrent, self.changesetCurrent + level, -1):
-                self._applyChangeset(changeset, undo = True)
-        elif level > 0: # redo 
+            for changeset in range(self.changesetCurrent,
+                                   self.changesetCurrent + level, -1):
+                self._applyChangeset(changeset, undo=True)
+        elif level > 0:  # redo
             if self.changesetCurrent + 1 > changesetLast:
                 return self.changesetCurrent
-            for changeset in range(self.changesetCurrent + 1, self.changesetCurrent + 1 + level):
-                self._applyChangeset(changeset, undo = False)
-        
+            for changeset in range(self.changesetCurrent + 1,
+                                   self.changesetCurrent + 1 + level):
+                self._applyChangeset(changeset, undo=False)
+
         self.changesetCurrent += level
-        
+
         Debug.msg(2, "Digit.Undo(): changeset_current=%d, changeset_last=%d",
                   self.changesetCurrent, changesetLast)
-        
-        self.mapWindow.UpdateMap(render = False)
-        
-        if self.changesetCurrent < 0: # disable undo tool
+
+        self.mapWindow.UpdateMap(render=False)
+
+        if self.changesetCurrent < 0:  # disable undo tool
             self.toolbar.EnableUndo(False)
         else:
             self.toolbar.EnableUndo(True)
-        
+
         if self.changesetCurrent < changesetLast:
             self.toolbar.EnableRedo(True)
         else:
             self.toolbar.EnableRedo(False)
-        
+
     def ZBulkLines(self, pos1, pos2, start, step):
         """Z-bulk labeling
 
@@ -1617,50 +1680,51 @@
         """
         if not self._checkMap():
             return -1
-        
+
         poList = self._display.GetSelectedIList()
         ret = Vedit_bulk_labeling(self.poMapInfo, poList,
                                   pos1[0], pos1[1], pos2[0], pos2[1],
                                   start, step)
         Vect_destroy_list(poList)
-        
+
         if ret > 0:
             self._addChangeset()
             self.toolbar.EnableUndo()
-        
+
         return ret
-    
+
     def GetDisplay(self):
         """Get display driver instance"""
         return self._display
-    
-    def OpenMap(self, name, update=True, tmp = False):
+
+    def OpenMap(self, name, update=True, tmp=False):
         """Open vector map for editing
-        
+
         :param map: name of vector map to be set up
         :type map: str
         :param tmp: True to open temporary vector map
         """
-        Debug.msg (3, "AbstractDigit.SetMapName map=%s" % name)
+        Debug.msg(3, "AbstractDigit.SetMapName map=%s" % name)
 
         if '@' in name:
             name, mapset = name.split('@')
         else:
             mapset = grass.gisenv()['MAPSET']
-        
-        self.poMapInfo = self._display.OpenMap(str(name), str(mapset), update, tmp)
-        
+
+        self.poMapInfo = self._display.OpenMap(
+            str(name), str(mapset), update, tmp)
+
         if self.poMapInfo:
             self.InitCats()
-        
+
         return self.poMapInfo
-    
+
     def CloseMap(self):
         """Close currently open vector map
         """
         if not self._checkMap():
             return
-        
+
         # print extra line before building message
         sys.stdout.write(os.linesep)
         # build topology, close map
@@ -1668,24 +1732,24 @@
 
     def InitCats(self):
         """Initialize categories information
-        
+
         :return: 0 on success
         :return: -1 on error
         """
         self.cats.clear()
         if not self._checkMap():
             return -1
-        
+
         ndblinks = Vect_get_num_dblinks(self.poMapInfo)
         for i in range(ndblinks):
             fi = Vect_get_dblink(self.poMapInfo, i).contents
             if fi:
                 self.cats[fi.number] = None
-        
+
         # find max category
         nfields = Vect_cidx_get_num_fields(self.poMapInfo)
         Debug.msg(2, "wxDigit.InitCats(): nfields=%d", nfields)
-        
+
         for i in range(nfields):
             field = Vect_cidx_get_field_number(self.poMapInfo, i)
             ncats = Vect_cidx_get_num_cats_by_index(self.poMapInfo, i)
@@ -1702,21 +1766,29 @@
                         self.cats[field] = cat.value
                 else:
                     self.cats[field] = cat.value
-            Debug.msg(3, "wxDigit.InitCats(): layer=%d, cat=%d", field, self.cats[field])
-            
+            Debug.msg(
+                3,
+                "wxDigit.InitCats(): layer=%d, cat=%d",
+                field,
+                self.cats[field])
+
         # set default values
         for field, cat in self.cats.iteritems():
-            if cat == None:
-                self.cats[field] = 0 # first category 1
-            Debug.msg(3, "wxDigit.InitCats(): layer=%d, cat=%d", field, self.cats[field])
-        
+            if cat is None:
+                self.cats[field] = 0  # first category 1
+            Debug.msg(
+                3,
+                "wxDigit.InitCats(): layer=%d, cat=%d",
+                field,
+                self.cats[field])
+
     def _checkMap(self):
         """Check if map is open
         """
         if not self.poMapInfo:
             self._error.NoMap()
             return False
-        
+
         return True
 
     def _addFeature(self, ftype, coords, layer, cat, snap, threshold):
@@ -1728,116 +1800,132 @@
         :param cat: category number
         :param snap: snap to node/vertex
         :param threshold: threshold for snapping
-        
+
         :return: tuple (number of added features, list of fids)
         :return: number of features -1 on error
         """
         fids = list()
         if not self._checkMap():
             return (-1, None)
-        
+
         is3D = bool(Vect_is_3d(self.poMapInfo))
-        
-        Debug.msg(2, "IVDigit._addFeature(): npoints=%d, layer=%d, cat=%d, snap=%d",
-                  len(coords), layer, cat, snap)
-        
-        if not (ftype & (GV_POINTS | GV_LINES | GV_AREA)): # TODO: 3D
+
+        Debug.msg(
+            2,
+            "IVDigit._addFeature(): npoints=%d, layer=%d, cat=%d, snap=%d",
+            len(coords),
+            layer,
+            cat,
+            snap)
+
+        if not (ftype & (GV_POINTS | GV_LINES | GV_AREA)):  # TODO: 3D
             self._error.FeatureType(ftype)
             return (-1, None)
-        
+
         # set category
         Vect_reset_cats(self.poCats)
         if layer > 0 and ftype != GV_AREA:
             Vect_cat_set(self.poCats, layer, cat)
             self.cats[layer] = max(cat, self.cats.get(layer, 1))
-        
+
         # append points
         Vect_reset_line(self.poPoints)
         for c in coords:
             Vect_append_point(self.poPoints, c[0], c[1], 0.0)
-        
+
         if ftype & (GV_BOUNDARY | GV_AREA):
             # close boundary
             points = self.poPoints.contents
             last = points.n_points - 1
             if self._settings['closeBoundary']:
-                Vect_append_point(self.poPoints, points.x[0], points.y[0], points.z[0])
+                Vect_append_point(
+                    self.poPoints, points.x[0],
+                    points.y[0],
+                    points.z[0])
             elif Vect_points_distance(points.x[0], points.y[0], points.z[0],
                                       points.x[last], points.y[last], points.z[last],
                                       is3D) <= threshold:
                 points.x[last] = points.x[0]
                 points.y[last] = points.y[0]
                 points.z[last] = points.z[0]
-        
+
         if snap != NO_SNAP:
             # apply snapping (node or vertex)
             modeSnap = not (snap == SNAP)
-            Vedit_snap_line(self.poMapInfo, self.popoBgMapInfo, int(self.poBgMapInfo is not None),
-                            -1, self.poPoints, threshold, modeSnap)
-        
+            Vedit_snap_line(self.poMapInfo, self.popoBgMapInfo, int(
+                self.poBgMapInfo is not None), -1, self.poPoints, threshold, modeSnap)
+
         if ftype == GV_AREA:
             ltype = GV_BOUNDARY
         else:
             ltype = ftype
-        newline = Vect_write_line(self.poMapInfo, ltype, self.poPoints, self.poCats)
+        newline = Vect_write_line(
+            self.poMapInfo,
+            ltype,
+            self.poPoints,
+            self.poCats)
         if newline < 0:
             self._error.WriteLine()
             return (-1, None)
 
         fids.append(newline)
-        
+
         # add centroids for left/right area
         if ftype & GV_AREA:
             left = right = -1
             bpoints = Vect_new_line_struct()
             cleft = c_int()
             cright = c_int()
-            
+
             Vect_get_line_areas(self.poMapInfo, newline,
                                 byref(cleft), byref(cright))
             left = cleft.value
             right = cright.value
-            
+
             Debug.msg(3, "IVDigit._addFeature(): area - left=%d right=%d",
                       left, right)
-            
+
             # check if area exists and has no centroid inside
             if layer > 0 and (left > 0 or right > 0):
                 Vect_cat_set(self.poCats, layer, cat)
                 self.cats[layer] = max(cat, self.cats.get(layer, 0))
-            
+
             x = c_double()
             y = c_double()
             if left > 0 and \
                     Vect_get_area_centroid(self.poMapInfo, left) == 0:
                 # if Vect_get_area_points(self.poMapInfo, left, bpoints) > 0 and
                 # Vect_find_poly_centroid(bpoints, byref(x), byref(y)) == 0:
-                if Vect_get_point_in_area(self.poMapInfo, left, byref(x), byref(y)) == 0:
+                if Vect_get_point_in_area(
+                        self.poMapInfo, left, byref(x),
+                        byref(y)) == 0:
                     Vect_reset_line(bpoints)
                     Vect_append_point(bpoints, x.value, y.value, 0.0)
                     newc = Vect_write_line(self.poMapInfo, GV_CENTROID,
-                                              bpoints, self.poCats)
+                                           bpoints, self.poCats)
                     if newc < 0:
                         self._error.WriteLine()
                         return (len(fids), fids)
                     else:
                         fids.append(newc)
-                    
+
             if right > 0 and \
                     Vect_get_area_centroid(self.poMapInfo, right) == 0:
-                # if Vect_get_area_points(byref(self.poMapInfo), right, bpoints) > 0 and 
+                # if Vect_get_area_points(byref(self.poMapInfo), right, bpoints) > 0 and
                 # Vect_find_poly_centroid(bpoints, byref(x), byref(y)) == 0:
-                if Vect_get_point_in_area(self.poMapInfo, right, byref(x), byref(y)) == 0:
+                if Vect_get_point_in_area(
+                        self.poMapInfo, right, byref(x),
+                        byref(y)) == 0:
                     Vect_reset_line(bpoints)
                     Vect_append_point(bpoints, x.value, y.value, 0.0)
-                    newc =  Vect_write_line(self.poMapInfo, GV_CENTROID,
-                                               bpoints, self.poCats)
+                    newc = Vect_write_line(self.poMapInfo, GV_CENTROID,
+                                           bpoints, self.poCats)
                     if newc < 0:
                         self._error.WriteLine()
                         return (len(fids, fids))
                     else:
                         fids.append(newc)
-                    
+
             Vect_destroy_line_struct(bpoints)
 
         # break line or boundary at intersection
@@ -1845,38 +1933,38 @@
             self._breakLineAtIntersection(newline, self.poPoints)
 
         self._addChangeset()
-        
+
         if ftype & GV_AREA:
             # len(fids) == 1 -> no new area
-            return (len(fids)-1, fids)
-        
+            return (len(fids) - 1, fids)
+
         return (len(fids), fids)
-    
-    def _ModifyLineVertex(self, coords, add = True):
+
+    def _ModifyLineVertex(self, coords, add=True):
         """Add or remove vertex
-        
+
         Shape of line/boundary is not changed when adding new vertex.
-        
+
         :param coords: coordinates of point
         :param add: True to add, False to remove
         :type add: bool
-        
+
         :return: 1 on success
         :return: 0 nothing changed
         :return: -1 error
         """
         if not self._checkMap():
             return -1
-        
+
         selected = self._display.selected
         if len(selected['ids']) != 1:
             return 0
-        
-        poList  = self._display.GetSelectedIList()
 
+        poList = self._display.GetSelectedIList()
+
         if self.emit_signals:
             cList = poList.contents
-            
+
             old_bboxs = [self._getBbox(cList.value[0])]
             old_areas_cats = [self._getLineAreasCategories(cList.value[0])]
 
@@ -1885,9 +1973,9 @@
 
         Vect_reset_line(self.poPoints)
         Vect_append_point(self.poPoints, coords[0], coords[1], 0.0)
-        
-        thresh = self._display.GetThreshold(type = 'selectThresh')
-        
+
+        thresh = self._display.GetThreshold(type='selectThresh')
+
         if add:
             ret = Vedit_add_vertex(self.poMapInfo, poList,
                                    self.poPoints, thresh)
@@ -1906,7 +1994,7 @@
                 new_id = Vect_get_updated_line(self.poMapInfo, i)
                 new_areas_cats.append(self._getLineAreasCategories(new_id))
                 new_bboxs.append(self._getBbox(new_id))
-        
+
         if not add and ret > 0 and self._settings['breakLines']:
             self._breakLineAtIntersection(Vect_get_num_lines(self.poMapInfo),
                                           None)
@@ -1918,13 +2006,13 @@
             if add:
                 self.vertexAdded.emit(old_bboxs=old_bboxs, new_bboxs=new_bboxs)
             else:
-                self.vertexRemoved.emit(old_bboxs=old_bboxs, 
+                self.vertexRemoved.emit(old_bboxs=old_bboxs,
                                         new_bboxs=new_bboxs,
                                         old_areas_cats=old_areas_cats,
                                         new_areas_cats=new_areas_cats)
 
         return 1
-    
+
     def GetLineCats(self, line):
         """Get list of layer/category(ies) for selected feature.
 
@@ -1935,64 +2023,77 @@
         ret = dict()
         if not self._checkMap():
             return ret
-        
+
         if line == -1 and len(self._display.selected['ids']) < 1:
             return ret
-        
+
         if line == -1:
             line = self._display.selected['ids'][0]
-            
+
         if not Vect_line_alive(self.poMapInfo, line):
             self._error.DeadLine(line)
             return ret
-        
+
         if Vect_read_line(self.poMapInfo, None, self.poCats, line) < 0:
             self._error.ReadLine(line)
             return ret
-        
+
         cats = self.poCats.contents
         for i in range(cats.n_cats):
             field = cats.field[i]
             if field not in ret:
                 ret[field] = list()
             ret[field].append(cats.cat[i])
-        
+
         return ret
 
     def GetLayers(self):
         """Get list of layers
-        
+
         Requires self.InitCats() to be called.
 
         :return: list of layers
         """
         return self.cats.keys()
-    
+
     def UpdateSettings(self):
         """Update digit (and display) settings
         """
         self._display.UpdateSettings()
-        
-        self._settings['breakLines']   = bool(UserSettings.Get(group = 'vdigit', key = "breakLines",
-                                                              subkey = 'enabled'))
-        self._settings['closeBoundary'] = bool(UserSettings.Get(group = 'vdigit', key = "closeBoundary",
-                                                                subkey = 'enabled'))
-        
+
+        self._settings['breakLines'] = bool(
+            UserSettings.Get(
+                group='vdigit',
+                key="breakLines",
+                subkey='enabled'))
+        self._settings['closeBoundary'] = bool(
+            UserSettings.Get(
+                group='vdigit',
+                key="closeBoundary",
+                subkey='enabled'))
+
     def SetCategory(self):
         """Update self.cats based on settings"""
-        sel = UserSettings.Get(group = 'vdigit', key = 'categoryMode', subkey = 'selection')
+        sel = UserSettings.Get(
+            group='vdigit',
+            key='categoryMode',
+            subkey='selection')
         cat = None
-        if sel == 0: # next to usep
+        if sel == 0:  # next to usep
             cat = self._setCategoryNextToUse()
         elif sel == 1:
-            cat = UserSettings.Get(group = 'vdigit', key = 'category', subkey = 'value')
-        
+            cat = UserSettings.Get(
+                group='vdigit',
+                key='category',
+                subkey='value')
+
         if cat:
-            layer = UserSettings.Get(group = 'vdigit', key = 'layer', subkey = 'value')
+            layer = UserSettings.Get(
+                group='vdigit', key='layer', subkey='value')
             self.cats[layer] = cat
-        
+
         return cat
-    
+
     def _setCategoryNextToUse(self):
         """Find maximum category number for the given layer and
         update the settings
@@ -2000,43 +2101,45 @@
         :return: category to be used
         """
         # get max category number for given layer and update the settings
-        layer = UserSettings.Get(group = 'vdigit', key = 'layer', subkey = 'value')
+        layer = UserSettings.Get(group='vdigit', key='layer', subkey='value')
         cat = self.cats.get(layer, 0) + 1
-        UserSettings.Set(group = 'vdigit', key = 'category', subkey = 'value',
-                         value = cat)
+        UserSettings.Set(group='vdigit', key='category', subkey='value',
+                         value=cat)
         Debug.msg(1, "IVDigit._setCategoryNextToUse(): cat=%d", cat)
-        
+
         return cat
 
     def SelectLinesFromBackgroundMap(self, bbox):
         """Select features from background map
 
         :param bbox: bounding box definition
-        
+
         :return: list of selected feature ids
         """
         # try select features by box first
-        if self._display.SelectLinesByBox(bbox, poMapInfo = self.poBgMapInfo) < 1:
-            self._display.SelectLineByPoint(bbox[0], poMapInfo = self.poBgMapInfo)['line']
-            
+        if self._display.SelectLinesByBox(
+                bbox, poMapInfo=self.poBgMapInfo) < 1:
+            self._display.SelectLineByPoint(
+                bbox[0], poMapInfo=self.poBgMapInfo)['line']
+
         return self._display.selected['ids']
-        
+
     def GetUndoLevel(self):
         """Get undo level (number of active changesets)
-        
+
         Note: Changesets starts wiht 0
         """
         return self.changesetCurrent
-    
+
     def GetFeatureType(self):
         """Get feature type for OGR layers
 
         :return: feature type as string (point, linestring, polygon)
         :return: None for native format
         """
-        topoFormat = Vect_get_finfo_topology_info(self.poMapInfo, None, None, None)
+        topoFormat = Vect_get_finfo_topology_info(
+            self.poMapInfo, None, None, None)
         if topoFormat == GV_TOPO_PSEUDO:
             return Vect_get_finfo_geometry_type(self.poMapInfo)
-        
+
         return ''
-        

Modified: grass/trunk/gui/wxpython/vdigit/wxdisplay.py
===================================================================
--- grass/trunk/gui/wxpython/vdigit/wxdisplay.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/vdigit/wxdisplay.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -21,21 +21,22 @@
 
 import wx
 
-from core.debug    import Debug
+from core.debug import Debug
 from core.settings import UserSettings
 from core.utils import _
 
 try:
-    from grass.lib.gis    import *
+    from grass.lib.gis import *
     from grass.lib.vector import *
-    from grass.lib.vedit  import *
+    from grass.lib.vedit import *
 except ImportError:
     pass
 
-log       = None
-progress  = None
+log = None
+progress = None
 last_error = ''
 
+
 def print_error(msg, type):
     """Redirect stderr"""
     global log
@@ -48,24 +49,26 @@
 
     return 0
 
+
 def print_progress(value):
     """Redirect progress info"""
     global progress
     if progress:
         progress.SetValue(value)
     else:
-        pass # discard progress info
-    
+        pass  # discard progress info
+
     return 0
 
+
 def GetLastError():
     global last_error
     ret = last_error
     if ret[-1] != '.':
         ret += '.'
-    
-    last_error = '' # reset
-    
+
+    last_error = ''  # reset
+
     return ret
 
 try:
@@ -75,11 +78,13 @@
     perfunc = pertype(print_progress)
 except NameError:
     pass
-    
+
+
 class DisplayDriver:
+
     def __init__(self, device, deviceTmp, mapObj, window, glog, gprogress):
         """Display driver used by vector digitizer
-        
+
         :param device: wx.PseudoDC device where to draw vector objects
         :param deviceTmp: wx.PseudoDC device where to draw temporary vector objects
         :param mapOng: Map Object (render.Map)
@@ -90,89 +95,89 @@
         global errfunc, perfunc, log, progress
         log = glog
         progress = gprogress
-        
+
         G_gisinit('wxvdigit')
         locale.setlocale(locale.LC_NUMERIC, 'C')
-        G_set_error_routine(errfunc) 
+        G_set_error_routine(errfunc)
         G_set_percent_routine(perfunc)
         # G_set_fatal_error(FATAL_RETURN)
-        
-        self.mapInfo   = None     # open vector map (Map_Info structure)
+
+        self.mapInfo = None     # open vector map (Map_Info structure)
         self.poMapInfo = None     # pointer to self.mapInfo
-        self.is3D      = False    # is open vector map 3D
-        
-        self.dc      = device     # PseudoDC devices
-        self.dcTmp   = deviceTmp
-        self.mapObj  = mapObj
-        self.region  = mapObj.GetCurrentRegion()
-        self.window  = window
-        self.log     = log        # log device
+        self.is3D = False    # is open vector map 3D
 
+        self.dc = device     # PseudoDC devices
+        self.dcTmp = deviceTmp
+        self.mapObj = mapObj
+        self.region = mapObj.GetCurrentRegion()
+        self.window = window
+        self.log = log        # log device
+
         self.firstNode = True     # track PseudoDC Id of selected features
         self.lastNodeId = -1
-        
+
         # GRASS lib
         self.poPoints = Vect_new_line_struct()
-        self.poCats   = Vect_new_cats_struct()
-        
+        self.poCats = Vect_new_cats_struct()
+
         # selected objects
         self.selected = {
-            'field'   : -1,      # field number
-            'cats'    : list(),  # list of cats
-            'ids'     : list(),  # list of ids
-            'idsDupl' : list(),  # list of duplicated features
-            }
-        
+            'field': -1,      # field number
+            'cats': list(),  # list of cats
+            'ids': list(),  # list of ids
+            'idsDupl': list(),  # list of duplicated features
+        }
+
         # digitizer settings
         self.settings = {
-            'highlight'     : None,
-            'highlightDupl' : { 'enabled' : False,
-                                'color'   : None },
-            'point'         : { 'enabled' : False,
-                                'color'   : None },
-            'line'          : { 'enabled' : False,
-                                'color'   : None },
-            'boundaryNo'    : { 'enabled' : False,
-                                'color'   : None },
-            'boundaryOne'   : { 'enabled' : False,
-                                'color'   : None },
-            'boundaryTwo'   : { 'enabled' : False,
-                                'color'   : None },
-            'centroidIn'    : { 'enabled' : False,
-                                'color'   : None },
-            'centroidOut'   : { 'enabled' : False,
-                                'color'   : None },
-            'centroidDup'   : { 'enabled' : False,
-                                'color'   : None },
-            'nodeOne'       : { 'enabled' : False,
-                                'color'   : None },
-            'nodeTwo'       : { 'enabled' : False,
-                                'color'   : None },
-            'vertex'        : { 'enabled' : False,
-                                'color'   : None },
-            'area'          : { 'enabled' : False,
-                                'color'   : None },
-            'direction'     : { 'enabled' : False,
-                                'color'   : None },
-            'lineWidth'     : -1,    # screen units 
-            }
-        
+            'highlight': None,
+            'highlightDupl': {'enabled': False,
+                              'color': None},
+            'point': {'enabled': False,
+                      'color': None},
+            'line': {'enabled': False,
+                     'color': None},
+            'boundaryNo': {'enabled': False,
+                           'color': None},
+            'boundaryOne': {'enabled': False,
+                            'color': None},
+            'boundaryTwo': {'enabled': False,
+                            'color': None},
+            'centroidIn': {'enabled': False,
+                           'color': None},
+            'centroidOut': {'enabled': False,
+                            'color': None},
+            'centroidDup': {'enabled': False,
+                            'color': None},
+            'nodeOne': {'enabled': False,
+                        'color': None},
+            'nodeTwo': {'enabled': False,
+                        'color': None},
+            'vertex': {'enabled': False,
+                       'color': None},
+            'area': {'enabled': False,
+                     'color': None},
+            'direction': {'enabled': False,
+                          'color': None},
+            'lineWidth': -1,    # screen units
+        }
+
         # topology
         self._resetTopology()
-        
+
         self._drawSelected = False
         self._drawSegments = False
-        
+
         self.UpdateSettings()
-        
+
     def __del__(self):
         """Close currently open vector map"""
         G_unset_error_routine()
         G_unset_percent_routine()
-        
+
         if self.poMapInfo:
             self.CloseMap()
-        
+
         Vect_destroy_line_struct(self.poPoints)
         Vect_destroy_cats_struct(self.poCats)
 
@@ -180,24 +185,24 @@
         """Reset topology dict
         """
         self.topology = {
-            'highlight'   : 0,
-            'point'       : 0,
-            'line'        : 0,
-            'boundaryNo'  : 0,
-            'boundaryOne' : 0,
-            'boundaryTwo' : 0,
-            'centroidIn'  : 0,
-            'centroidOut' : 0,
-            'centroidDup' : 0,
-            'nodeOne'     : 0,
-            'nodeTwo'     : 0,
-            'vertex'      : 0,
-            }
-        
+            'highlight': 0,
+            'point': 0,
+            'line': 0,
+            'boundaryNo': 0,
+            'boundaryOne': 0,
+            'boundaryTwo': 0,
+            'centroidIn': 0,
+            'centroidOut': 0,
+            'centroidDup': 0,
+            'nodeOne': 0,
+            'nodeTwo': 0,
+            'vertex': 0,
+        }
+
     def _cell2Pixel(self, east, north, elev):
         """Conversion from geographic coordinates (east, north)
         to screen (x, y)
-  
+
         .. todo::
             3D stuff...
 
@@ -208,64 +213,76 @@
         :return: x, y screen coordinates (integer)
         """
         map_res = max(self.region['ewres'], self.region['nsres'])
-        w = self.region['center_easting']  - (self.mapObj.width  / 2) * map_res
+        w = self.region['center_easting'] - (self.mapObj.width / 2) * map_res
         n = self.region['center_northing'] + (self.mapObj.height / 2) * map_res
-        
+
         return int((east - w) / map_res), int((n - north) / map_res)
-    
-    def _drawCross(self, pdc, point, size = 5):
+
+    def _drawCross(self, pdc, point, size=5):
         """Draw cross symbol of given size to device content
-   
+
         Used for points, nodes, vertices
 
         :param pdc: PseudoDC where to draw
         :param point: coordinates of center
         :param size: size of the cross symbol
-   
+
         :return: 0 on success
         :return: -1 on failure
         """
         if not pdc or not point:
             return -1
-        
+
         pdc.DrawLine(point.x - size, point.y, point.x + size, point.y)
         pdc.DrawLine(point.x, point.y - size, point.x, point.y + size)
-        
+
         return 0
-    
+
     def _drawObject(self, robj):
         """Draw given object to the device
-        
+
         The object is defined as robject() from vedit.h.
-        
+
         :param robj: object to be rendered
-        
+
         :return:  1 on success
         :return: -1 on failure (vector feature marked as dead, etc.)
         """
         if not self.dc or not self.dcTmp:
             return -1
-        
-        Debug.msg(4, "_drawObject(): line=%d type=%d npoints=%d", robj.fid, robj.type, robj.npoints)
+
+        Debug.msg(
+            4,
+            "_drawObject(): line=%d type=%d npoints=%d",
+            robj.fid,
+            robj.type,
+            robj.npoints)
         brush = None
-        if robj.type == TYPE_AREA and \
-                self._isSelected(Vect_get_area_centroid(self.poMapInfo, robj.fid)):
+        if robj.type == TYPE_AREA and self._isSelected(
+                Vect_get_area_centroid(self.poMapInfo, robj.fid)):
             pdc = self.dcTmp
 
             pen = wx.TRANSPARENT_PEN
             brush = wx.TRANSPARENT_BRUSH
-            
+
             dcId = 1
             self.topology['highlight'] += 1
             if not self._drawSelected:
                 return
         elif robj.type != TYPE_AREA and self._isSelected(robj.fid):
             pdc = self.dcTmp
-            if self.settings['highlightDupl']['enabled'] and self._isDuplicated(robj.fid):
-                pen = wx.Pen(self.settings['highlightDupl']['color'], self.settings['lineWidth'], wx.SOLID)
-            else:            
-                pen = wx.Pen(self.settings['highlight'], self.settings['lineWidth'], wx.SOLID)
-                    
+            if self.settings['highlightDupl'][
+                    'enabled'] and self._isDuplicated(robj.fid):
+                pen = wx.Pen(
+                    self.settings['highlightDupl']['color'],
+                    self.settings['lineWidth'],
+                    wx.SOLID)
+            else:
+                pen = wx.Pen(
+                    self.settings['highlight'],
+                    self.settings['lineWidth'],
+                    wx.SOLID)
+
             dcId = 1
             self.topology['highlight'] += 1
             if not self._drawSelected:
@@ -275,23 +292,24 @@
             pen, brush = self._definePen(robj.type)
 
             dcId = 0
-        
-        pdc.SetPen(pen)        
+
+        pdc.SetPen(pen)
         if brush:
             pdc.SetBrush(brush)
-        
-        if robj.type & (TYPE_POINT | TYPE_CENTROIDIN | TYPE_CENTROIDOUT | TYPE_CENTROIDDUP |
-                        TYPE_NODEONE | TYPE_NODETWO | TYPE_VERTEX): # -> point
+
+        if robj.type & (
+                TYPE_POINT | TYPE_CENTROIDIN | TYPE_CENTROIDOUT | TYPE_CENTROIDDUP |
+                TYPE_NODEONE | TYPE_NODETWO | TYPE_VERTEX):  # -> point
             if dcId > 0:
                 if robj.type == TYPE_VERTEX:
-                    dcId = 3 # first vertex
+                    dcId = 3  # first vertex
                 elif robj.type & (TYPE_NODEONE | TYPE_NODETWO):
                     if self.firstNode:
                         dcId = 1
                         self.firstNode = False
                     else:
                         dcId = self.lastNodeId
-            
+
             for i in range(robj.npoints):
                 p = robj.point[i]
                 if dcId > 0:
@@ -302,36 +320,53 @@
             if dcId > 0 and self._drawSegments:
                 self.fisrtNode = True
                 self.lastNodeId = robj.npoints * 2 - 1
-                dcId = 2 # first segment
+                dcId = 2  # first segment
                 i = 0
                 while i < robj.npoints - 1:
                     point_beg = wx.Point(robj.point[i].x, robj.point[i].y)
-                    point_end = wx.Point(robj.point[i+1].x, robj.point[i+1].y)
-                    pdc.SetId(dcId) # set unique id & set bbox for each segment
+                    point_end = wx.Point(
+                        robj.point[
+                            i + 1].x,
+                        robj.point[
+                            i + 1].y)
+                    # set unique id & set bbox for each segment
+                    pdc.SetId(dcId)
                     pdc.SetPen(pen)
-                    pdc.SetIdBounds(dcId - 1, wx.Rect(point_beg.x, point_beg.y, 0, 0))
+                    pdc.SetIdBounds(
+                        dcId - 1,
+                        wx.Rect(
+                            point_beg.x,
+                            point_beg.y,
+                            0,
+                            0))
                     pdc.SetIdBounds(dcId, wx.RectPP(point_beg, point_end))
                     pdc.DrawLine(point_beg.x, point_beg.y,
                                  point_end.x, point_end.y)
-                    i    += 1
+                    i += 1
                     dcId += 2
-                pdc.SetIdBounds(dcId - 1, wx.Rect(robj.point[robj.npoints - 1].x,
-                                                  robj.point[robj.npoints - 1].y,
-                                                  0, 0))
+                pdc.SetIdBounds(
+                    dcId - 1,
+                    wx.Rect(
+                        robj.point[
+                            robj.npoints - 1].x,
+                        robj.point[
+                            robj.npoints - 1].y,
+                        0,
+                        0))
             else:
                 points = list()
                 for i in range(robj.npoints):
                     p = robj.point[i]
                     points.append(wx.Point(p.x, p.y))
-                    
+
                 if robj.type == TYPE_AREA:
                     pdc.DrawPolygon(points)
                 else:
                     pdc.DrawLines(points)
-        
+
     def _definePen(self, rtype):
         """Define pen/brush based on rendered object)
-        
+
         Updates also self.topology dict
 
         :return: pen, brush
@@ -359,15 +394,15 @@
         elif rtype == TYPE_VERTEX:
             key = 'vertex'
         elif rtype == TYPE_AREA:
-            key = 'area' 
+            key = 'area'
         elif rtype == TYPE_ISLE:
             key = 'isle'
         elif rtype == TYPE_DIRECTION:
             key = 'direction'
-        
+
         if key not in ('direction', 'area', 'isle'):
             self.topology[key] += 1
-        
+
         if key in ('area', 'isle'):
             pen = wx.TRANSPARENT_PEN
             if key == 'area':
@@ -375,16 +410,19 @@
             else:
                 brush = wx.TRANSPARENT_BRUSH
         else:
-            pen = wx.Pen(self.settings[key]['color'], self.settings['lineWidth'], wx.SOLID)
+            pen = wx.Pen(
+                self.settings[key]['color'],
+                self.settings['lineWidth'],
+                wx.SOLID)
             brush = None
-        
+
         return pen, brush
-        
+
     def _getDrawFlag(self):
         """Get draw flag from the settings
-        
+
         See vedit.h for list of draw flags.
-        
+
         :return: draw flag (int)
         """
         ret = 0
@@ -414,12 +452,12 @@
             ret |= DRAW_AREA
         if self.settings['direction']['enabled']:
             ret |= DRAW_DIRECTION
-        
+
         return ret
-        
-    def _isSelected(self, line, force = False):
+
+    def _isSelected(self, line, force=False):
         """Check if vector object selected?
-   
+
         :param line: feature id
 
         :return: True if vector object is selected
@@ -427,85 +465,89 @@
         """
         if line in self.selected['ids']:
             return True
-        
+
         return False
 
     def _isDuplicated(self, line):
         """Check for already marked duplicates
-        
+
         :param line: feature id
 
         :return: True line already marked as duplicated
         :return: False not duplicated
         """
         return line in self.selected['idsDupl']
-    
+
     def _getRegionBox(self):
         """Get bound_box() from current region
 
         :return: bound_box
         """
         box = bound_box()
-        
+
         box.N = self.region['n']
         box.S = self.region['s']
         box.E = self.region['e']
         box.W = self.region['w']
         box.T = PORT_DOUBLE_MAX
         box.B = -PORT_DOUBLE_MAX
-        
+
         return box
 
-    def DrawMap(self, force = False):
+    def DrawMap(self, force=False):
         """Draw content of the vector map to the device
-        
+
         :param force: force drawing
         :type force: bool
         :return: number of drawn features
         :return: -1 on error
         """
         Debug.msg(1, "DisplayDriver.DrawMap(): force=%d", force)
-        
+
         if not self.poMapInfo or not self.dc or not self.dcTmp:
             return -1
-        
-        rlist = Vedit_render_map(self.poMapInfo, byref(self._getRegionBox()), self._getDrawFlag(),
-                                 self.region['center_easting'], self.region['center_northing'],
-                                 self.mapObj.width, self.mapObj.height,
-                                 max(self.region['nsres'], self.region['ewres'])).contents
-        
+
+        rlist = Vedit_render_map(
+            self.poMapInfo, byref(self._getRegionBox()),
+            self._getDrawFlag(),
+            self.region['center_easting'],
+            self.region['center_northing'],
+            self.mapObj.width, self.mapObj.height,
+            max(self.region['nsres'],
+                self.region['ewres'])).contents
+
         self._resetTopology()
-        
+
         self.dc.BeginDrawing()
         self.dcTmp.BeginDrawing()
-        
+
         # draw objects
         for i in range(rlist.nitems):
             robj = rlist.item[i].contents
             self._drawObject(robj)
-        
+
         self.dc.EndDrawing()
         self.dcTmp.EndDrawing()
-        
-        # reset list of selected features by cat 
+
+        # reset list of selected features by cat
         # list of ids - see IsSelected()
         self.selected['field'] = -1
         self.selected['cats'] = list()
-        
+
     def _getSelectType(self):
         """Get type(s) to be selected
 
         Used by SelectLinesByBox() and SelectLineByPoint()
         """
         ftype = 0
-        for feature in (('point',    GV_POINT),
-                        ('line',     GV_LINE),
+        for feature in (('point', GV_POINT),
+                        ('line', GV_LINE),
                         ('centroid', GV_CENTROID),
                         ('boundary', GV_BOUNDARY)):
-            if UserSettings.Get(group = 'vdigit', key = 'selectType',
-                                subkey = [feature[0], 'enabled']):
+            if UserSettings.Get(group='vdigit', key='selectType',
+                                subkey=[feature[0], 'enabled']):
                 ftype |= feature[1]
-        
+
         return ftype
 
     def _validLine(self, line):
@@ -518,15 +560,16 @@
         """
         if line > 0 and line <= Vect_get_num_lines(self.poMapInfo):
             return True
-        
+
         return False
-    
-    def SelectLinesByBox(self, bbox, ltype = None, drawSeg = False, poMapInfo = None):
+
+    def SelectLinesByBox(self, bbox, ltype=None,
+                         drawSeg=False, poMapInfo=None):
         """Select vector objects by given bounding box
-        
+
         If line id is already in the list of selected lines, then it will
         be excluded from this list.
-        
+
         :param bbox: bounding box definition
         :param ltype: feature type or None for default
         :param drawSeg: True to draw segments of line
@@ -538,17 +581,17 @@
         thisMapInfo = poMapInfo is None
         if not poMapInfo:
             poMapInfo = self.poMapInfo
-        
+
         if not poMapInfo:
             return None
-        
+
         if thisMapInfo:
             self._drawSegments = drawSeg
             self._drawSelected = True
-        
+
             # select by ids
             self.selected['cats'] = list()
-        
+
         poList = Vect_new_list()
         x1, y1 = bbox[0]
         x2, y2 = bbox[1]
@@ -558,20 +601,20 @@
         Vect_append_point(poBbox, x2, y2, 0.0)
         Vect_append_point(poBbox, x1, y2, 0.0)
         Vect_append_point(poBbox, x1, y1, 0.0)
-        
+
         if not ltype:
             ltype = self._getSelectType()
         Vect_select_lines_by_polygon(poMapInfo, poBbox,
-                                     0, None, # isles
+                                     0, None,  # isles
                                      ltype, poList)
-        
+
         flist = poList.contents
         nlines = flist.n_values
         Debug.msg(1, "DisplayDriver.SelectLinesByBox() num = %d", nlines)
         for i in range(nlines):
             line = flist.value[i]
-            if UserSettings.Get(group = 'vdigit', key = 'selectInside',
-                                subkey = 'enabled'):
+            if UserSettings.Get(group='vdigit', key='selectInside',
+                                subkey='enabled'):
                 inside = True
                 if not self._validLine(line):
                     return None
@@ -582,52 +625,55 @@
                                               poBbox):
                         inside = False
                         break
-                    
+
                 if not inside:
-                    continue # skip lines just overlapping bbox
-            
+                    continue  # skip lines just overlapping bbox
+
             if not self._isSelected(line):
                 self.selected['ids'].append(line)
             else:
                 self.selected['ids'].remove(line)
-        
+
         Vect_destroy_line_struct(poBbox)
         Vect_destroy_list(poList)
-        
+
         return nlines
 
-    def SelectAreaByPoint(self, point, poMapInfo = None):
+    def SelectAreaByPoint(self, point, poMapInfo=None):
         thisMapInfo = poMapInfo is None
         if not poMapInfo:
             poMapInfo = self.poMapInfo
-        
+
         if not poMapInfo:
-            return { 'area' : -1, 'centroid': -1 }
-        
+            return {'area': -1, 'centroid': -1}
+
         if thisMapInfo:
             self._drawSelected = True
 
         box = bound_box()
-        for area in range(1, Vect_get_num_areas(poMapInfo)+1):
+        for area in range(1, Vect_get_num_areas(poMapInfo) + 1):
             Vect_get_area_box(poMapInfo, area, byref(box))
-            if Vect_point_in_area(point[0], point[1], poMapInfo, area, byref(box)) == 1:
+            if Vect_point_in_area(
+                    point[0],
+                    point[1],
+                    poMapInfo, area, byref(box)) == 1:
                 centroid = Vect_get_area_centroid(poMapInfo, area)
                 if not self._isSelected(centroid):
                     self.selected['ids'].append(centroid)
                 else:
                     self.selected['ids'].remove(centroid)
-                
-                return { 'area' : area, 'centroid' : centroid}
-        
-        return { 'area' : -1, 'centroid': -1 }
-            
-    def SelectLineByPoint(self, point, ltype = None, poMapInfo = None):
+
+                return {'area': area, 'centroid': centroid}
+
+        return {'area': -1, 'centroid': -1}
+
+    def SelectLineByPoint(self, point, ltype=None, poMapInfo=None):
         """Select vector feature by given point in given
         threshold
-   
+
         Only one vector object can be selected. Bounding boxes of
         all segments are stores.
-        
+
         :param point: points coordinates (x, y)
         :param ltype: feature type or None for default
         :param poMapInfo: use external Map_info, None for self.poMapInfo
@@ -637,36 +683,45 @@
         thisMapInfo = poMapInfo is None
         if not poMapInfo:
             poMapInfo = self.poMapInfo
-        
+
         if not poMapInfo:
-            return { 'line' : -1, 'point': None }
-        
+            return {'line': -1, 'point': None}
+
         if thisMapInfo:
             self._drawSelected = True
-            # select by ids 
+            # select by ids
             self.selected['cats'] = list()
-        
+
         poFound = Vect_new_list()
-        
+
         if ltype is None:
-            ltype  = self._getSelectType()
-        lineNearest = Vect_find_line_list(poMapInfo, point[0], point[1], 0,
-                                          ltype, self.GetThreshold(), self.is3D,
-                                          None, poFound)
-        Debug.msg(1, "DisplayDriver.SelectLineByPoint() found = %d", lineNearest)
-        
+            ltype = self._getSelectType()
+        lineNearest = Vect_find_line_list(
+            poMapInfo, point[0],
+            point[1],
+            0, ltype, self.GetThreshold(),
+            self.is3D, None, poFound)
+        Debug.msg(
+            1,
+            "DisplayDriver.SelectLineByPoint() found = %d",
+            lineNearest)
+
         if lineNearest > 0:
             if not self._isSelected(lineNearest):
                 self.selected['ids'].append(lineNearest)
             else:
                 self.selected['ids'].remove(lineNearest)
-        
+
         px = c_double()
         py = c_double()
         pz = c_double()
         if not self._validLine(lineNearest):
-            return { 'line' : -1, 'point': None }
-        ftype = Vect_read_line(poMapInfo, self.poPoints, self.poCats, lineNearest)
+            return {'line': -1, 'point': None}
+        ftype = Vect_read_line(
+            poMapInfo,
+            self.poPoints,
+            self.poCats,
+            lineNearest)
         Vect_line_distance(self.poPoints, point[0], point[1], 0.0, self.is3D,
                            byref(px), byref(py), byref(pz),
                            None, None, None)
@@ -685,50 +740,50 @@
                 line = found.value[i]
                 if line != lineNearest and not self._isDuplicated(line):
                     self.selected['ids'].remove(line)
-        
+
         Vect_destroy_list(poFound)
-        
+
         if thisMapInfo:
             # drawing segments can be very expensive
             # only one features selected
             self._drawSegments = True
-        
-        return { 'line'  : lineNearest,
-                 'point' : (px.value, py.value, pz.value) }
-    
+
+        return {'line': lineNearest,
+                'point': (px.value, py.value, pz.value)}
+
     def _listToIList(self, plist):
         """Generate from list struct_ilist
         """
         ilist = Vect_new_list()
         for val in plist:
             Vect_list_append(ilist, val)
-        
+
         return ilist
-        
-    def GetSelectedIList(self, ilist = None):
+
+    def GetSelectedIList(self, ilist=None):
         """Get list of selected objects as struct_ilist
 
         Returned IList must be freed by Vect_destroy_list().
-        
+
         :return: struct_ilist
         """
         if ilist:
             return self._listToIList(ilist)
-        
+
         return self._listToIList(self.selected['ids'])
-        
-    def GetSelected(self, grassId = True):
+
+    def GetSelected(self, grassId=True):
         """Get ids of selected objects
-        
+
         :param grassId: True for feature id, False for PseudoDC id
-        
+
         :return: list of ids of selected vector objects
         """
         if grassId:
             return self.selected['ids']
-        
+
         dc_ids = list()
-        
+
         if not self._drawSegments:
             dc_ids.append(1)
         elif len(self.selected['ids']) > 0:
@@ -739,10 +794,10 @@
             # node - segment - vertex - segment - node
             for i in range(1, 2 * points.n_points):
                 dc_ids.append(i)
-        
+
         return dc_ids
-        
-    def SetSelected(self, ids, layer = -1):
+
+    def SetSelected(self, ids, layer=-1):
         """Set selected vector objects
 
         :param list: of ids (None to unselect features)
@@ -753,21 +808,21 @@
         else:
             self._drawSelected = False
 
-        self.selected['field'] = layer        
+        self.selected['field'] = layer
         if layer > 0:
-            self.selected['cats']  = ids
-            self.selected['ids']   = list()
+            self.selected['cats'] = ids
+            self.selected['ids'] = list()
             ### cidx is not up-to-date
             # Vect_cidx_find_all(self.poMapInfo, layer, GV_POINTS | GV_LINES, lid, ilist)
             nlines = Vect_get_num_lines(self.poMapInfo)
             for line in range(1, nlines + 1):
                 if not Vect_line_alive(self.poMapInfo, line):
                     continue
-                
-                ltype = Vect_read_line (self.poMapInfo, None, self.poCats, line)
+
+                ltype = Vect_read_line(self.poMapInfo, None, self.poCats, line)
                 if not (ltype & (GV_POINTS | GV_LINES)):
                     continue
-                
+
                 found = False
                 cats = self.poCats.contents
                 for i in range(0, cats.n_cats):
@@ -778,16 +833,16 @@
                 if found:
                     self.selected['ids'].append(line)
         else:
-            self.selected['ids']   = ids
-            self.selected['cats']  = []
-        
+            self.selected['ids'] = ids
+            self.selected['cats'] = []
+
     def GetSelectedVertex(self, pos):
         """Get PseudoDC vertex id of selected line
 
         Set bounding box for vertices of line.
-        
+
         :param pos: position
-        
+
         :return: id of center, left and right vertex
         :return: 0 no line found
         :return: -1 on error
@@ -796,42 +851,54 @@
         # only one object can be selected
         if len(self.selected['ids']) != 1 or not self._drawSegments:
             return returnId
-        
+
         startId = 1
         line = self.selected['ids'][0]
-        
+
         if not self._validLine(line):
             return -1
-        ftype = Vect_read_line(self.poMapInfo, self.poPoints, self.poCats, line)
-        
+        ftype = Vect_read_line(
+            self.poMapInfo,
+            self.poPoints,
+            self.poCats,
+            line)
+
         minDist = 0.0
         Gid = -1
         # find the closest vertex (x, y)
         DCid = 1
         points = self.poPoints.contents
         for idx in range(points.n_points):
-            dist = Vect_points_distance(pos[0], pos[1], 0.0,
-                                        points.x[idx], points.y[idx], points.z[idx], 0)
-            
+            dist = Vect_points_distance(
+                pos[0],
+                pos[1],
+                0.0, points.x[idx],
+                points.y[idx],
+                points.z[idx],
+                0)
+
             if idx == 0:
                 minDist = dist
-                Gid     = idx
+                Gid = idx
             else:
                 if minDist > dist:
                     minDist = dist
                     Gid = idx
-            
-            vx, vy = self._cell2Pixel(points.x[idx], points.y[idx], points.z[idx])
+
+            vx, vy = self._cell2Pixel(
+                points.x[idx],
+                points.y[idx],
+                points.z[idx])
             rect = wx.Rect(vx, vy, 0, 0)
             self.dc.SetIdBounds(DCid, rect)
             DCid += 2
-        
+
         if minDist > self.GetThreshold():
             return returnId
-        
+
         # translate id
         DCid = Gid * 2 + 1
-        
+
         # add selected vertex
         returnId.append(DCid)
         # left vertex
@@ -844,7 +911,7 @@
             returnId.append(-1)
         else:
             returnId.append(DCid + 2)
-        
+
         return returnId
 
     def GetRegionSelected(self):
@@ -855,37 +922,37 @@
         regionBox = bound_box()
         lineBox = bound_box()
         setRegion = True
-        
+
         nareas = Vect_get_num_areas(self.poMapInfo)
         for line in self.selected['ids']:
             area = Vect_get_centroid_area(self.poMapInfo, line)
-            
+
             if area > 0 and area <= nareas:
                 if not Vect_get_area_box(self.poMapInfo, area, byref(lineBox)):
                     continue
             else:
                 if not Vect_get_line_box(self.poMapInfo, line, byref(lineBox)):
                     continue
-                
+
             if setRegion:
                 Vect_box_copy(byref(regionBox), byref(lineBox))
                 setRegion = False
             else:
                 Vect_box_extend(byref(regionBox), byref(lineBox))
-        
+
         return regionBox.N, regionBox.S, regionBox.W, regionBox.E
 
     def DrawSelected(self, flag):
         """Draw selected features
-        
+
         :param flag: True to draw selected features
         :type flag: bool
         """
         self._drawSelected = bool(flag)
-        
+
     def CloseMap(self):
         """Close vector map
-        
+
         :return: 0 on success
         :return: non-zero on error
         """
@@ -901,12 +968,12 @@
         ret = Vect_close(self.poMapInfo)
         del self.mapInfo
         self.poMapInfo = self.mapInfo = None
-        
+
         return ret
-    
-    def OpenMap(self, name, mapset, update = True, tmp = False):
+
+    def OpenMap(self, name, mapset, update=True, tmp=False):
         """Open vector map by the driver
-        
+
         :param name: name of vector map to be open
         :type name: str
         :param mapset: name of mapset where the vector map lives
@@ -923,7 +990,7 @@
         if not self.mapInfo:
             self.mapInfo = Map_info()
             self.poMapInfo = pointer(self.mapInfo)
-        
+
         # open existing map
         if update:
             if tmp:
@@ -935,34 +1002,38 @@
                 open_fn = Vect_open_tmp_old
             else:
                 open_fn = Vect_open_old
-        
+
         ret = open_fn(self.poMapInfo, name, mapset)
-        
+
         if ret == -1:
              # fatal error detected
             del self.mapInfo
             self.poMapInfo = self.mapInfo = None
         elif ret < 2:
             # map open at level 1, try to build topology
-            dlg = wx.MessageDialog(parent = self.window,
-                                   message = _("Topology for vector map <%s> is not available. "
-                                               "Topology is required by digitizer. Do you want to "
-                                               "rebuild topology (takes some time) and open the vector map "
-                                               "for editing?") % name,
-                                   caption=_("Topology missing"),
-                                   style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
+            dlg = wx.MessageDialog(
+                parent=self.window,
+                message=_(
+                    "Topology for vector map <%s> is not available. "
+                    "Topology is required by digitizer. Do you want to "
+                    "rebuild topology (takes some time) and open the vector map "
+                    "for editing?") %
+                name,
+                caption=_("Topology missing"),
+                style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
             ret = dlg.ShowModal()
             if ret != wx.ID_YES:
                 del self.mapInfo
                 self.poMapInfo = self.mapInfo = None
             else:
                 Vect_build(self.poMapInfo)
-        
+
         if update:
-            Vect_set_updated(self.poMapInfo, True) # track updated lines at update mode
-        
+            # track updated lines at update mode
+            Vect_set_updated(self.poMapInfo, True)
+
         self.is3D = Vect_is_3d(self.poMapInfo)
-        
+
         return self.poMapInfo
 
     def GetMapBoundingBox(self):
@@ -972,57 +1043,60 @@
         """
         if not self.poMapInfo:
             return None
-        
+
         bbox = bound_box()
         Vect_get_map_box(self.poMapInfo, byref(bbox))
 
         return bbox.W, bbox.S, bbox.B, \
             bbox.E, bbox.N, bbox.T
-    
-    def UpdateSettings(self, alpha = 255):
+
+    def UpdateSettings(self, alpha=255):
         """Update display driver settings
 
         .. todo::
             map units
-        
+
         :param alpha: color value for aplha channel
         """
         color = dict()
         for key in self.settings.keys():
             if key == 'lineWidth':
-                self.settings[key] = int(UserSettings.Get(group = 'vdigit', key = 'lineWidth',
-                                                          subkey = 'value'))
+                self.settings[key] = int(
+                    UserSettings.Get(
+                        group='vdigit',
+                        key='lineWidth',
+                        subkey='value'))
                 continue
-            
-            color = wx.Colour(UserSettings.Get(group = 'vdigit', key = 'symbol',
-                                              subkey = [key, 'color'])[0],
-                             UserSettings.Get(group = 'vdigit', key = 'symbol',
-                                              subkey = [key, 'color'])[1],
-                             UserSettings.Get(group = 'vdigit', key = 'symbol',
-                                              subkey = [key, 'color'])[2],
-                             alpha)
-            
+
+            color = wx.Colour(UserSettings.Get(group='vdigit', key='symbol',
+                                               subkey=[key, 'color'])[0],
+                              UserSettings.Get(group='vdigit', key='symbol',
+                                               subkey=[key, 'color'])[1],
+                              UserSettings.Get(group='vdigit', key='symbol',
+                                               subkey=[key, 'color'])[2],
+                              alpha)
+
             if key == 'highlight':
                 self.settings[key] = color
                 continue
-            
+
             if key == 'highlightDupl':
-                self.settings[key]['enabled'] = bool(UserSettings.Get(group = 'vdigit', key = 'checkForDupl',
-                                                                      subkey = 'enabled'))
+                self.settings[key]['enabled'] = bool(UserSettings.Get(
+                    group='vdigit', key='checkForDupl', subkey='enabled'))
             else:
-                self.settings[key]['enabled'] = bool(UserSettings.Get(group = 'vdigit', key = 'symbol',
-                                                                      subkey = [key, 'enabled']))
-            
+                self.settings[key]['enabled'] = bool(UserSettings.Get(
+                    group='vdigit', key='symbol', subkey=[key, 'enabled']))
+
             self.settings[key]['color'] = color
-        
+
     def UpdateRegion(self):
         """Update geographical region used by display driver
         """
         self.region = self.mapObj.GetCurrentRegion()
-        
-    def GetThreshold(self, type = 'snapping', value = None, units = None):
+
+    def GetThreshold(self, type='snapping', value=None, units=None):
         """Return threshold value in map units
-        
+
         :param type: snapping mode (node, vertex)
         :param value: threshold to be set up
         :param units: units (map, screen)
@@ -1030,44 +1104,44 @@
         :return: threshold value
         """
         if value is None:
-            value = UserSettings.Get(group = 'vdigit', key = type, subkey = 'value')
-        
+            value = UserSettings.Get(group='vdigit', key=type, subkey='value')
+
         if units is None:
-            units = UserSettings.Get(group = 'vdigit', key = type, subkey = 'units')
-        
+            units = UserSettings.Get(group='vdigit', key=type, subkey='units')
+
         if value < 0:
             value = (self.region['nsres'] + self.region['ewres']) / 2.0
-        
+
         if units == "screen pixels":
             # pixel -> cell
             res = max(self.region['nsres'], self.region['ewres'])
             return value * res
-        
+
         return value
-    
+
     def GetDuplicates(self):
         """Return ids of (selected) duplicated vector features
         """
         if not self.poMapInfo:
             return
-        
+
         ids = dict()
         APoints = Vect_new_line_struct()
         BPoints = Vect_new_line_struct()
-        
+
         self.selected['idsDupl'] = list()
-        
+
         for i in range(len(self.selected['ids'])):
             line1 = self.selected['ids'][i]
             if self._isDuplicated(line1):
                 continue
-            
+
             Vect_read_line(self.poMapInfo, APoints, None, line1)
-            
+
             for line2 in self.selected['ids']:
                 if line1 == line2 or self._isDuplicated(line2):
                     continue
-                
+
                 Vect_read_line(self.poMapInfo, BPoints, None, line2)
 
                 if Vect_line_check_duplicate(APoints, BPoints, WITHOUT_Z):
@@ -1075,18 +1149,18 @@
                         ids[i] = list()
                         ids[i].append((line1, self._getCatString(line1)))
                         self.selected['idsDupl'].append(line1)
-                    
+
                     ids[i].append((line2, self._getCatString(line2)))
                     self.selected['idsDupl'].append(line2)
-        
+
         Vect_destroy_line_struct(APoints)
         Vect_destroy_line_struct(BPoints)
 
         return ids
-    
+
     def _getCatString(self, line):
         Vect_read_line(self.poMapInfo, None, self.poCats, line)
-        
+
         cats = self.poCats.contents
         catsDict = dict()
         for i in range(cats.n_cats):
@@ -1094,11 +1168,11 @@
             if layer not in catsDict:
                 catsDict[layer] = list()
             catsDict[layer].append(cats.cat[i])
-        
+
         catsStr = ''
         for l, c in catsDict.iteritems():
             catsStr = '%d: (%s)' % (l, ','.join(map(str, c)))
-        
+
         return catsStr
 
     def UnSelect(self, lines):
@@ -1111,12 +1185,11 @@
         for line in lines:
             if self._isSelected(line):
                 self.selected['ids'].remove(line)
-            if self.settings['highlightDupl']['enabled'] and self._isDuplicated(line):
+            if self.settings['highlightDupl'][
+                    'enabled'] and self._isDuplicated(line):
                 checkForDupl = True
 
         if checkForDupl:
             self.GetDuplicates()
-        
+
         return len(self.selected['ids'])
-    
-

Modified: grass/trunk/gui/wxpython/vnet/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/vnet/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/vnet/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -5,4 +5,4 @@
     'vnet_core',
     'vnet_data',
     'vnet_utils'
-    ]
+]

Modified: grass/trunk/gui/wxpython/vnet/dialogs.py
===================================================================
--- grass/trunk/gui/wxpython/vnet/dialogs.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/vnet/dialogs.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -29,61 +29,75 @@
 import types
 
 from copy import copy
-from grass.script     import core as grass
+from grass.script import core as grass
 
 import wx
 import wx.aui
-import wx.lib.flatnotebook  as FN
+import wx.lib.flatnotebook as FN
 import wx.lib.colourselect as csel
-import wx.lib.mixins.listctrl  as  listmix
-import wx.lib.scrolledpanel    as scrolled
+import wx.lib.mixins.listctrl as listmix
+import wx.lib.scrolledpanel as scrolled
 
-from core             import globalvar, utils
-from core.gcmd        import RunCommand, GMessage
-from core.settings    import UserSettings
+from core import globalvar, utils
+from core.gcmd import RunCommand, GMessage
+from core.settings import UserSettings
 from core.utils import _
 
-from dbmgr.base       import DbMgrBase 
-from dbmgr.vinfo      import VectorDBInfo
+from dbmgr.base import DbMgrBase
+from dbmgr.vinfo import VectorDBInfo
 
 from gui_core.widgets import GNotebook
 from gui_core.goutput import GConsoleWindow
 from gui_core.gselect import Select, LayerSelect, ColumnSelect
 
-from vnet.widgets     import PointsList
-from vnet.toolbars    import MainToolbar, PointListToolbar, AnalysisToolbar
-from vnet.vnet_core   import VNETManager
-from vnet.vnet_utils  import DegreesToRadians, RadiansToDegrees, GetNearestNodeCat, ParseMapStr
+from vnet.widgets import PointsList
+from vnet.toolbars import MainToolbar, PointListToolbar, AnalysisToolbar
+from vnet.vnet_core import VNETManager
+from vnet.vnet_utils import DegreesToRadians, RadiansToDegrees, GetNearestNodeCat, ParseMapStr
 
-#Main TODOs
-# - when layer tree of is changed, tmp result map is removed from render list 
-# - optimization of map drawing 
+# Main TODOs
+# - when layer tree of is changed, tmp result map is removed from render list
+# - optimization of map drawing
 # - tmp maps - add number of process
 # - destructor problem - when GRASS GIS is closed with open VNETDialog,
 #   it's destructor is not called
 
+
 class VNETDialog(wx.Dialog):
-    def __init__(self, parent, giface,
-                 id = wx.ID_ANY, title = _("GRASS GIS Vector Network Analysis Tool"),
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
+
+    def __init__(self, parent, giface, id=wx.ID_ANY,
+                 title=_("GRASS GIS Vector Network Analysis Tool"),
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
         """Dialog for vector network analysis"""
 
-        wx.Dialog.__init__(self, parent, id, style=style, title = title, **kwargs)
-        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
+        wx.Dialog.__init__(
+            self,
+            parent,
+            id,
+            style=style,
+            title=title,
+            **kwargs)
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    globalvar.ICONDIR,
+                    'grass.ico'),
+                wx.BITMAP_TYPE_ICO))
 
-        self.parent  = parent
+        self.parent = parent
         self.mapWin = giface.GetMapWindow()
         self.giface = giface
 
-        # contains current analysis result (do not have to be last one, when history is browsed), 
+        # contains current analysis result (do not have to be last one, when history is browsed),
         # it is instance of VectMap class
-        self.tmp_result = None 
+        self.tmp_result = None
 
         self.defIsecTurnsHndlrReg = False
-        
-        # get attribute table columns only with numbers (for cost columns in vnet analysis)
-        self.columnTypes = ['integer', 'double precision'] 
-        
+
+        # get attribute table columns only with numbers (for cost columns in
+        # vnet analysis)
+        self.columnTypes = ['integer', 'double precision']
+
         self.vnet_mgr = VNETManager(self, giface)
 
         self.vnet_mgr.analysisDone.connect(self.AnalysisDone)
@@ -95,33 +109,36 @@
 
         # toobars
         self.toolbars = {}
-        self.toolbars['mainToolbar'] = MainToolbar(parent = self, vnet_mgr = self.vnet_mgr)
-        self.toolbars['analysisToolbar'] = AnalysisToolbar(parent = self, vnet_mgr = self.vnet_mgr)
+        self.toolbars['mainToolbar'] = MainToolbar(
+            parent=self, vnet_mgr=self.vnet_mgr)
+        self.toolbars['analysisToolbar'] = AnalysisToolbar(
+            parent=self, vnet_mgr=self.vnet_mgr)
         #
         # Fancy gui
         #
         self._mgr = wx.aui.AuiManager(self)
 
         self.mainPanel = wx.Panel(parent=self)
-        self.notebook = GNotebook(parent = self.mainPanel,
-                                  style = FN.FNB_FANCY_TABS | FN.FNB_BOTTOM |
-                                          FN.FNB_NO_X_BUTTON)
+        self.notebook = GNotebook(parent=self.mainPanel,
+                                  style=FN.FNB_FANCY_TABS | FN.FNB_BOTTOM |
+                                  FN.FNB_NO_X_BUTTON)
 
         # statusbar
-        self.stPriorities = {'important' : 5, 'iformation' : 1}
-        self.stBar = VnetStatusbar(parent = self.mainPanel, style = 0)
-        self.stBar.SetFieldsCount(number = 1)
-    
+        self.stPriorities = {'important': 5, 'iformation': 1}
+        self.stBar = VnetStatusbar(parent=self.mainPanel, style=0)
+        self.stBar.SetFieldsCount(number=1)
+
         self.def_isec_turns = None
 
         # Create tabs
-        
-        # Stores widgets which sets some of analysis parameters (e. g. v.ne.iso -> iso lines)
-        self.anSettings = {} 
 
+        # Stores widgets which sets some of analysis parameters (e. g. v.ne.iso
+        # -> iso lines)
+        self.anSettings = {}
+
         self._createPointsPage()
 
-        # stores widgets which are shown on parameters page 
+        # stores widgets which are shown on parameters page
         # they set data, on which analysis will be done
         self.inputData = {}
         self._createParametersPage()
@@ -129,15 +146,19 @@
         # Output console for analysis
         self._createOutputPage()
 
-        # Stores data which are needed for attribute table browser of analysis input map layers
+        # Stores data which are needed for attribute table browser of analysis
+        # input map layers
         self.inpDbMgrData = {}
         self._createInputDbMgrPage()
 
-        # Stores data which are need for attribute table browser of analysis result map layers
+        # Stores data which are need for attribute table browser of analysis
+        # result map layers
         self.resultDbMgrData = {}
         self._createResultDbMgrPage()
 
-        self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
+        self.notebook.Bind(
+            FN.EVT_FLATNOTEBOOK_PAGE_CHANGED,
+            self.OnPageChanged)
         self.Bind(wx.EVT_CLOSE, self.OnCloseDialog)
 
         self._addPanes()
@@ -147,137 +168,160 @@
         self.SetSize((370, 550))
         self.SetMinSize((370, 420))
 
-        #fix goutput's pane size (required for Mac OSX)
-        if self.gwindow:         
+        # fix goutput's pane size (required for Mac OSX)
+        if self.gwindow:
             self.gwindow.SetSashPosition(int(self.GetSize()[1] * .75))
 
         self.OnAnalysisChanged(None)
         self.notebook.SetSelectionByName("parameters")
-        self.toolbars['analysisToolbar'].SetMinSize((-1, self.toolbars['mainToolbar'].GetSize()[1]))
+        self.toolbars['analysisToolbar'].SetMinSize(
+            (-1, self.toolbars['mainToolbar'].GetSize()[1]))
 
         self.toolbars['mainToolbar'].UpdateUndoRedo(0, 0)
 
-
     def _addPanes(self):
         """Adds toolbar pane and pane with tabs"""
         self._mgr.AddPane(self.toolbars['mainToolbar'],
-                              wx.aui.AuiPaneInfo().
-                              Name("pointlisttools").Caption(_("Point list toolbar")).
-                              ToolbarPane().Top().Row(0).
-                              Dockable(False).
-                              CloseButton(False).Layer(0))
- 
+                          wx.aui.AuiPaneInfo().
+                          Name("pointlisttools").Caption(_("Point list toolbar")).
+                          ToolbarPane().Top().Row(0).
+                          Dockable(False).
+                          CloseButton(False).Layer(0))
+
         self._mgr.AddPane(self.toolbars['analysisToolbar'],
-                              wx.aui.AuiPaneInfo().
-                              Name("analysisTools").Caption(_("Analysis toolbar")).
-                              ToolbarPane().Top().Row(1).
-                              Dockable(False).
-                              CloseButton(False).Layer(0))
+                          wx.aui.AuiPaneInfo().
+                          Name("analysisTools").Caption(_("Analysis toolbar")).
+                          ToolbarPane().Top().Row(1).
+                          Dockable(False).
+                          CloseButton(False).Layer(0))
 
         self._mgr.AddPane(self.mainPanel,
-                              wx.aui.AuiPaneInfo().
-                              Name("tabs").CaptionVisible(visible = False).
-                              Center().
-                              Dockable(False).
-                              CloseButton(False).Layer(0))
+                          wx.aui.AuiPaneInfo().
+                          Name("tabs").CaptionVisible(visible=False).
+                          Center().
+                          Dockable(False).
+                          CloseButton(False).Layer(0))
+
     def _doVnetDialogLayout(self):
 
         sizer = wx.BoxSizer(wx.VERTICAL)
 
-        sizer.Add(item = self.notebook, proportion = 1,
-                  flag = wx.EXPAND)
+        sizer.Add(item=self.notebook, proportion=1,
+                  flag=wx.EXPAND)
 
-        sizer.Add(item = self.stBar, proportion = 0, flag = wx.EXPAND)
+        sizer.Add(item=self.stBar, proportion=0, flag=wx.EXPAND)
 
         self.mainPanel.SetSizer(sizer)
 
         sizer.Fit(self)
-        self.Layout() 
+        self.Layout()
 
     def _createPointsPage(self):
         """Tab with points list and analysis settings"""
-        pointsPanel = wx.Panel(parent = self)
-        anSettingsPanel = wx.Panel(parent = pointsPanel)
-        maxDistPanel =  wx.Panel(parent = anSettingsPanel)
+        pointsPanel = wx.Panel(parent=self)
+        anSettingsPanel = wx.Panel(parent=pointsPanel)
+        maxDistPanel = wx.Panel(parent=anSettingsPanel)
         maxValue = 1e8
 
-        listBox = wx.StaticBox(parent = pointsPanel, id = wx.ID_ANY,
-                                label =" %s " % _("Points for analysis:"))
+        listBox = wx.StaticBox(parent=pointsPanel, id=wx.ID_ANY,
+                               label=" %s " % _("Points for analysis:"))
         listSizer = wx.StaticBoxSizer(listBox, wx.VERTICAL)
-        anSettingsBox = wx.StaticBox(parent = anSettingsPanel, id = wx.ID_ANY,
-                                label =" %s " % _("Analysis settings:"))
+        anSettingsBox = wx.StaticBox(parent=anSettingsPanel, id=wx.ID_ANY,
+                                     label=" %s " % _("Analysis settings:"))
         anSettingsSizer = wx.StaticBoxSizer(anSettingsBox, wx.VERTICAL)
 
-        self.notebook.AddPage(page = pointsPanel, 
-                              text=_('Points'), 
-                              name = 'points')
+        self.notebook.AddPage(page=pointsPanel,
+                              text=_('Points'),
+                              name='points')
 
-        self.list = PtsList(parent = pointsPanel, vnet_mgr = self.vnet_mgr)
-        toolSwitcher=self.giface.GetMapDisplay().GetToolSwitcher()
-        self.toolbars['pointsList'] = PointListToolbar(parent=pointsPanel,
-                                                       toolSwitcher=toolSwitcher,
-                                                       dialog=self, 
-                                                       vnet_mgr=self.vnet_mgr)
+        self.list = PtsList(parent=pointsPanel, vnet_mgr=self.vnet_mgr)
+        toolSwitcher = self.giface.GetMapDisplay().GetToolSwitcher()
+        self.toolbars['pointsList'] = PointListToolbar(
+            parent=pointsPanel,
+            toolSwitcher=toolSwitcher,
+            dialog=self,
+            vnet_mgr=self.vnet_mgr)
 
-        maxDistLabel = wx.StaticText(parent = maxDistPanel, id = wx.ID_ANY, label = _("Maximum distance of point to the network:"))
-        self.anSettings["max_dist"] = wx.SpinCtrl(parent = maxDistPanel, id = wx.ID_ANY, min = 0, max = maxValue)
-        self.anSettings["max_dist"].Bind(wx.EVT_SPINCTRL, lambda event : self.MaxDist())
-        self.anSettings["max_dist"].SetValue(100000) #TODO init val
+        maxDistLabel = wx.StaticText(
+            parent=maxDistPanel, id=wx.ID_ANY,
+            label=_("Maximum distance of point to the network:"))
+        self.anSettings["max_dist"] = wx.SpinCtrl(
+            parent=maxDistPanel, id=wx.ID_ANY, min=0, max=maxValue)
+        self.anSettings["max_dist"].Bind(
+            wx.EVT_SPINCTRL, lambda event: self.MaxDist())
+        self.anSettings["max_dist"].SetValue(100000)  # TODO init val
         self.MaxDist()
 
         #showCutPanel =  wx.Panel(parent = anSettingsPanel)
-        #self.anSettings["show_cut"] = wx.CheckBox(parent = showCutPanel, id=wx.ID_ANY,
+        # self.anSettings["show_cut"] = wx.CheckBox(parent = showCutPanel, id=wx.ID_ANY,
         #                                          label = _("Show minimal cut"))
         #self.anSettings["show_cut"].Bind(wx.EVT_CHECKBOX, self.OnShowCut)
 
-        isoLinesPanel =  wx.Panel(parent = anSettingsPanel)
-        isoLineslabel = wx.StaticText(parent = isoLinesPanel, id = wx.ID_ANY, label = _("Iso lines:"))
-        self.anSettings["iso_lines"] = wx.TextCtrl(parent = isoLinesPanel, id = wx.ID_ANY) 
-        self.anSettings["iso_lines"].Bind(wx.EVT_TEXT, lambda event : self.IsoLines())
+        isoLinesPanel = wx.Panel(parent=anSettingsPanel)
+        isoLineslabel = wx.StaticText(
+            parent=isoLinesPanel,
+            id=wx.ID_ANY,
+            label=_("Iso lines:"))
+        self.anSettings["iso_lines"] = wx.TextCtrl(
+            parent=isoLinesPanel, id=wx.ID_ANY)
+        self.anSettings["iso_lines"].Bind(
+            wx.EVT_TEXT, lambda event: self.IsoLines())
         self.anSettings["iso_lines"].SetValue("1000,2000,3000")
         self.IsoLines()
 
         # Layout
         AnalysisSizer = wx.BoxSizer(wx.VERTICAL)
 
+        listSizer.Add(item=self.toolbars['pointsList'], proportion=0)
+        listSizer.Add(item=self.list, proportion=1, flag=wx.EXPAND)
 
-        listSizer.Add(item = self.toolbars['pointsList'], proportion = 0)
-        listSizer.Add(item = self.list, proportion = 1, flag = wx.EXPAND)
-
-
         maxDistSizer = wx.BoxSizer(wx.HORIZONTAL)
-        maxDistSizer.Add(item = maxDistLabel, flag = wx.ALIGN_CENTER_VERTICAL, proportion = 1)
-        maxDistSizer.Add(item = self.anSettings["max_dist"],
-                         flag = wx.EXPAND | wx.ALL, border = 5, proportion = 0)
+        maxDistSizer.Add(
+            item=maxDistLabel,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            proportion=1)
+        maxDistSizer.Add(item=self.anSettings["max_dist"],
+                         flag=wx.EXPAND | wx.ALL, border=5, proportion=0)
         maxDistPanel.SetSizer(maxDistSizer)
-        anSettingsSizer.Add(item = maxDistPanel, proportion = 1, flag = wx.EXPAND)
+        anSettingsSizer.Add(item=maxDistPanel, proportion=1, flag=wx.EXPAND)
 
         #showCutSizer = wx.BoxSizer(wx.HORIZONTAL)
-        #showCutPanel.SetSizer(showCutSizer)
-        #showCutSizer.Add(item = self.anSettings["show_cut"],
+        # showCutPanel.SetSizer(showCutSizer)
+        # showCutSizer.Add(item = self.anSettings["show_cut"],
         #                 flag = wx.EXPAND | wx.ALL, border = 5, proportion = 0)
         #anSettingsSizer.Add(item = showCutPanel, proportion = 1, flag = wx.EXPAND)
 
         isoLinesSizer = wx.BoxSizer(wx.HORIZONTAL)
-        isoLinesSizer.Add(item = isoLineslabel, flag = wx.ALIGN_CENTER_VERTICAL, proportion = 1)
-        isoLinesSizer.Add(item = self.anSettings["iso_lines"],
-                        flag = wx.EXPAND | wx.ALL, border = 5, proportion = 1)
+        isoLinesSizer.Add(
+            item=isoLineslabel,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            proportion=1)
+        isoLinesSizer.Add(item=self.anSettings["iso_lines"],
+                          flag=wx.EXPAND | wx.ALL, border=5, proportion=1)
         isoLinesPanel.SetSizer(isoLinesSizer)
-        anSettingsSizer.Add(item = isoLinesPanel, proportion = 1, flag = wx.EXPAND)
+        anSettingsSizer.Add(item=isoLinesPanel, proportion=1, flag=wx.EXPAND)
 
-        AnalysisSizer.Add(item = listSizer, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
-        AnalysisSizer.Add(item = anSettingsPanel, proportion = 0, flag = wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM, border = 5)
+        AnalysisSizer.Add(
+            item=listSizer,
+            proportion=1,
+            flag=wx.EXPAND | wx.ALL,
+            border=5)
+        AnalysisSizer.Add(
+            item=anSettingsPanel,
+            proportion=0,
+            flag=wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM,
+            border=5)
 
         anSettingsPanel.SetSizer(anSettingsSizer)
         pointsPanel.SetSizer(AnalysisSizer)
 
     def MaxDist(self):
         val = self.anSettings["max_dist"].GetValue()
-        self.vnet_mgr.SetParams({"max_dist" : val}, {})
+        self.vnet_mgr.SetParams({"max_dist": val}, {})
 
     def IsoLines(self):
         val = self.anSettings["iso_lines"].GetValue()
-        self.vnet_mgr.SetParams({"iso_lines" : val}, {})
+        self.vnet_mgr.SetParams({"iso_lines": val}, {})
 
     def OnShowCut(self, event):
         """Shows vector map with minimal cut (v.net.flow) - not yet implemented"""
@@ -295,150 +339,162 @@
 
     def _createOutputPage(self):
         """Tab with output console"""
-        outputPanel = wx.Panel(parent = self)
-        self.notebook.AddPage(page = outputPanel, 
-                              text = _("Output"), 
-                              name = 'output')
+        outputPanel = wx.Panel(parent=self)
+        self.notebook.AddPage(page=outputPanel,
+                              text=_("Output"),
+                              name='output')
 
-        goutput = self.vnet_mgr.goutput #TODO make interface
-        self.gwindow = GConsoleWindow(parent = outputPanel, gconsole = goutput)
+        goutput = self.vnet_mgr.goutput  # TODO make interface
+        self.gwindow = GConsoleWindow(parent=outputPanel, gconsole=goutput)
 
-        #Layout
+        # Layout
         outputSizer = wx.BoxSizer(wx.VERTICAL)
-        outputSizer.Add(item = self.gwindow, proportion = 1, flag = wx.EXPAND)
-        self.gwindow.SetMinSize((-1,-1))
+        outputSizer.Add(item=self.gwindow, proportion=1, flag=wx.EXPAND)
+        self.gwindow.SetMinSize((-1, -1))
 
         outputPanel.SetSizer(outputSizer)
 
     def _createParametersPage(self):
         """Tab for selection of data for analysis"""
         dataPanel = scrolled.ScrolledPanel(parent=self)
-        self.notebook.AddPage(page = dataPanel,
-                              text=_('Parameters'), 
-                              name = 'parameters')
+        self.notebook.AddPage(page=dataPanel,
+                              text=_('Parameters'),
+                              name='parameters')
         label = {}
         dataSelects = [
-                        ['input', "Choose vector map for analysis:", Select],
-                        ['arc_layer', "Arc layer number or name:", LayerSelect],
-                        ['node_layer', "Node layer number or name:", LayerSelect],
-                        #['turn_layer', "Layer with turntable:", LayerSelect],
-                        #['turn_cat_layer', "Layer with unique categories for turntable:", LayerSelect],
-                        ['arc_column', "", ColumnSelect],
-                        ['arc_backward_column', "", ColumnSelect],
-                        ['node_column',  "", ColumnSelect],
-                      ]
+            ['input', "Choose vector map for analysis:", Select],
+            ['arc_layer', "Arc layer number or name:", LayerSelect],
+            ['node_layer', "Node layer number or name:", LayerSelect],
+            #['turn_layer', "Layer with turntable:", LayerSelect],
+            #['turn_cat_layer', "Layer with unique categories for turntable:", LayerSelect],
+            ['arc_column', "", ColumnSelect],
+            ['arc_backward_column', "", ColumnSelect],
+            ['node_column', "", ColumnSelect],
+        ]
 
-        #self.useTurns = wx.CheckBox(parent = dataPanel, id=wx.ID_ANY,
+        # self.useTurns = wx.CheckBox(parent = dataPanel, id=wx.ID_ANY,
         #                            label = _('Use turns'))
-        
+
         box = wx.StaticBox(dataPanel, -1, "Vector map and layers for analysis")
         bsizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        box2 = wx.StaticBox(dataPanel, -1, "Costs")    
+        box2 = wx.StaticBox(dataPanel, -1, "Costs")
         bsizer2 = wx.StaticBoxSizer(box2, wx.VERTICAL)
         selPanels = {}
 
         for dataSel in dataSelects:
-            selPanels[dataSel[0]] = wx.Panel(parent = dataPanel)
+            selPanels[dataSel[0]] = wx.Panel(parent=dataPanel)
             if dataSel[0] == 'input':
-                self.inputData[dataSel[0]] = dataSel[2](parent = selPanels[dataSel[0]],
-                                                        size = (-1, -1), 
-                                                        type = 'vector')
-                icon = wx.Image(os.path.join(globalvar.ICONDIR, "grass", "layer-vector-add.png"))
+                self.inputData[
+                    dataSel[0]] = dataSel[2](
+                    parent=selPanels[dataSel[0]],
+                    size=(-1, -1),
+                    type='vector')
+                icon = wx.Image(
+                    os.path.join(
+                        globalvar.ICONDIR,
+                        "grass",
+                        "layer-vector-add.png"))
                 icon.Rescale(18, 18)
-                icon = wx.BitmapFromImage(icon) 
-                self.addToTreeBtn = wx.BitmapButton(parent = selPanels[dataSel[0]], 
-                                                    bitmap = icon, 
-                                                    size = globalvar.DIALOG_COLOR_SIZE) 
-                self.addToTreeBtn.SetToolTipString(_("Add vector map into layer tree"))
+                icon = wx.BitmapFromImage(icon)
+                self.addToTreeBtn = wx.BitmapButton(
+                    parent=selPanels[dataSel[0]],
+                    bitmap=icon, size=globalvar.DIALOG_COLOR_SIZE)
+                self.addToTreeBtn.SetToolTipString(
+                    _("Add vector map into layer tree"))
                 self.addToTreeBtn.Disable()
                 self.addToTreeBtn.Bind(wx.EVT_BUTTON, self.OnToTreeBtn)
             elif dataSel[0] != 'input':
-                #if dataSel[0] == "turn_layer":
-                #    self.createTtbBtn = wx.Button(parent = selPanels[dataSel[0]], 
-                #                                 label = _("Create turntable")) 
+                # if dataSel[0] == "turn_layer":
+                #    self.createTtbBtn = wx.Button(parent = selPanels[dataSel[0]],
+                #                                 label = _("Create turntable"))
                 #    self.createTtbBtn.Bind(wx.EVT_BUTTON, self.OnCreateTtbBtn)
 
-                self.inputData[dataSel[0]] = dataSel[2](parent = selPanels[dataSel[0]],  
-                                                        size = (-1, -1))
-            label[dataSel[0]] =  wx.StaticText(parent =  selPanels[dataSel[0]], 
-                                               name = dataSel[0])
+                self.inputData[dataSel[0]] = dataSel[2](
+                    parent=selPanels[dataSel[0]], size=(-1, -1))
+            label[dataSel[0]] = wx.StaticText(parent=selPanels[dataSel[0]],
+                                              name=dataSel[0])
             label[dataSel[0]].SetLabel(dataSel[1])
 
-        self.inputData['input'].Bind(wx.EVT_TEXT, self.OnVectSel) 
+        self.inputData['input'].Bind(wx.EVT_TEXT, self.OnVectSel)
         self.inputData['arc_layer'].Bind(wx.EVT_TEXT, self.OnALayerSel)
         self.inputData['node_layer'].Bind(wx.EVT_TEXT, self.OnNLayerSel)
 
-        for params in ["arc_column", "arc_backward_column", "node_column"]:#, "turn_layer", "turn_cat_layer"]:
-            self.inputData[params].Bind(wx.EVT_TEXT, lambda event : self._setInputData())
+        # , "turn_layer", "turn_cat_layer"]:
+        for params in ["arc_column", "arc_backward_column", "node_column"]:
+            self.inputData[params].Bind(
+                wx.EVT_TEXT, lambda event: self._setInputData())
 
-        #self.useTurns.Bind(wx.EVT_CHECKBOX,
+        # self.useTurns.Bind(wx.EVT_CHECKBOX,
         #                    lambda event: self.UseTurns())
-        #self.UseTurns()
+        # self.UseTurns()
 
         # Layout
         mainSizer = wx.BoxSizer(wx.VERTICAL)
 
-        mainSizer.Add(item = bsizer, proportion = 0,
-                      flag = wx.EXPAND  | wx.TOP | wx.LEFT | wx.RIGHT, border = 5) 
+        mainSizer.Add(item=bsizer, proportion=0,
+                      flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=5)
 
-        for sel in ['input', 'arc_layer', 'node_layer']:#, 'turn_layer', 'turn_cat_layer']:
+        # , 'turn_layer', 'turn_cat_layer']:
+        for sel in ['input', 'arc_layer', 'node_layer']:
             if sel == 'input':
                 btn = self.addToTreeBtn
-            #elif sel == "turn_layer":
+            # elif sel == "turn_layer":
             #    btn = self.createTtbBtn
             else:
                 btn = None
-            #if sel == 'turn_layer':
+            # if sel == 'turn_layer':
             #    bsizer.Add(item = self.useTurns, proportion = 0,
-            #                flag = wx.TOP | wx.LEFT | wx.RIGHT, border = 5)                       
+            #                flag = wx.TOP | wx.LEFT | wx.RIGHT, border = 5)
 
-            selPanels[sel].SetSizer(self._doSelLayout(title = label[sel], 
-                                                      sel = self.inputData[sel], 
-                                                      btn = btn))
-            bsizer.Add(item = selPanels[sel], proportion = 0,
-                       flag = wx.EXPAND)
+            selPanels[sel].SetSizer(self._doSelLayout(title=label[sel],
+                                                      sel=self.inputData[sel],
+                                                      btn=btn))
+            bsizer.Add(item=selPanels[sel], proportion=0,
+                       flag=wx.EXPAND)
 
+        mainSizer.Add(item=bsizer2, proportion=0,
+                      flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=5)
 
-        mainSizer.Add(item = bsizer2, proportion = 0,
-                                 flag = wx.EXPAND  | wx.TOP | wx.LEFT | wx.RIGHT, border = 5)       
-
         for sel in ['arc_column', 'arc_backward_column', 'node_column']:
-            selPanels[sel].SetSizer(self._doSelLayout(title = label[sel], sel = self.inputData[sel]))
-            bsizer2.Add(item = selPanels[sel], proportion = 0,
-                       flag = wx.EXPAND)
+            selPanels[sel].SetSizer(
+                self._doSelLayout(
+                    title=label[sel],
+                    sel=self.inputData[sel]))
+            bsizer2.Add(item=selPanels[sel], proportion=0,
+                        flag=wx.EXPAND)
 
-
         dataPanel.SetSizer(mainSizer)
         dataPanel.SetupScrolling()
 
         dataPanel.SetAutoLayout(1)
 
-    def _doSelLayout(self, title, sel, btn = None): 
-        # helper function for layout of self.inputData widgets initialized in _createParametersPage
-        selSizer = wx.BoxSizer(orient = wx.VERTICAL)
+    def _doSelLayout(self, title, sel, btn=None):
+        # helper function for layout of self.inputData widgets initialized in
+        # _createParametersPage
+        selSizer = wx.BoxSizer(orient=wx.VERTICAL)
 
         selTitleSizer = wx.BoxSizer(wx.HORIZONTAL)
-        selTitleSizer.Add(item = title, proportion = 1,
-                          flag = wx.LEFT | wx.TOP | wx.EXPAND, border = 5)
+        selTitleSizer.Add(item=title, proportion=1,
+                          flag=wx.LEFT | wx.TOP | wx.EXPAND, border=5)
 
-        selSizer.Add(item = selTitleSizer, proportion = 0,
-                                 flag = wx.EXPAND)
+        selSizer.Add(item=selTitleSizer, proportion=0,
+                     flag=wx.EXPAND)
 
         if btn:
-                selFiledSizer = wx.BoxSizer(orient = wx.HORIZONTAL)
-                selFiledSizer.Add(item = sel, proportion = 1,
-                             flag = wx.EXPAND | wx.ALL)
+            selFiledSizer = wx.BoxSizer(orient=wx.HORIZONTAL)
+            selFiledSizer.Add(item=sel, proportion=1,
+                              flag=wx.EXPAND | wx.ALL)
 
-                selFiledSizer.Add(item = btn, proportion = 0,
-                             flag = wx.EXPAND | wx.ALL)
+            selFiledSizer.Add(item=btn, proportion=0,
+                              flag=wx.EXPAND | wx.ALL)
 
-                selSizer.Add(item = selFiledSizer, proportion = 0,
-                             flag = wx.EXPAND | wx.ALL| wx.ALIGN_CENTER_VERTICAL,
-                             border = 5)
+            selSizer.Add(item=selFiledSizer, proportion=0,
+                         flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER_VERTICAL,
+                         border=5)
         else:
-                selSizer.Add(item = sel, proportion = 1,
-                             flag = wx.EXPAND | wx.ALL| wx.ALIGN_CENTER_VERTICAL,
-                             border = 5)
+            selSizer.Add(item=sel, proportion=1,
+                         flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER_VERTICAL,
+                         border=5)
         return selSizer
 
     def _createInputDbMgrPage(self):
@@ -451,8 +507,8 @@
         if layer is not None and layer.type == 'vector':
             selMapName = layer.maplayer.name
 
-        self.inpDbMgrData['browse'] = self.inpDbMgrData['dbMgr'].CreateDbMgrPage(parent = self.notebook,
-                                                                                 pageName = 'browse')
+        self.inpDbMgrData['browse'] = self.inpDbMgrData[
+            'dbMgr'].CreateDbMgrPage(parent=self.notebook, pageName='browse')
         self.inpDbMgrData['browse'].SetTabAreaColour(globalvar.FNPageColor)
 
         self.inpDbMgrData['input'] = None
@@ -463,20 +519,20 @@
     def _updateInputDbMgrPage(self, show):
         """Show or hide input tables tab"""
         if show and self.notebook.GetPageIndexByName('inputDbMgr') == -1:
-            self.notebook.AddPage(page = self.inpDbMgrData['browse'],
-                                  text=_('Input tables'), 
-                                  name = 'inputDbMgr')
+            self.notebook.AddPage(page=self.inpDbMgrData['browse'],
+                                  text=_('Input tables'),
+                                  name='inputDbMgr')
         elif not show:
-            self.notebook.RemovePage(page = 'inputDbMgr')
+            self.notebook.RemovePage(page='inputDbMgr')
 
     def _createResultDbMgrPage(self):
         """Tab with attribute tables of analysis result layers"""
-        self.resultDbMgrData['dbMgr'] = DbMgrBase() 
-        self.resultDbMgrData['browse'] = self.resultDbMgrData['dbMgr'].CreateDbMgrPage(parent = self.notebook,
-                                                                                       pageName = 'browse')
+        self.resultDbMgrData['dbMgr'] = DbMgrBase()
+        self.resultDbMgrData['browse'] = self.resultDbMgrData[
+            'dbMgr'].CreateDbMgrPage(parent=self.notebook, pageName='browse')
         self.resultDbMgrData['browse'].SetTabAreaColour(globalvar.FNPageColor)
 
-        if  self.tmp_result:
+        if self.tmp_result:
             self.resultDbMgrData['input'] = self.tmp_result.GetVectMapName()
         else:
             self.resultDbMgrData['input'] = None
@@ -485,15 +541,17 @@
         """Show or Hide Result tables tab"""
         # analysis, which created result
         analysis = self.resultDbMgrData['analysis']
-        #TODO maybe no need to store this information, just check it has attribute table, if so show it
-        haveDbMgr = self.vnet_mgr.GetAnalysisProperties(analysis)["resultProps"]["dbMgr"]
+        # TODO maybe no need to store this information, just check it has
+        # attribute table, if so show it
+        haveDbMgr = self.vnet_mgr.GetAnalysisProperties(
+            analysis)["resultProps"]["dbMgr"]
 
         if haveDbMgr and self.notebook.GetPageIndexByName('resultDbMgr') == -1:
-            self.notebook.AddPage(page = self.resultDbMgrData['browse'],
-                                  text=_('Result tables'), 
-                                  name = 'resultDbMgr')
+            self.notebook.AddPage(page=self.resultDbMgrData['browse'],
+                                  text=_('Result tables'),
+                                  name='resultDbMgr')
         elif not haveDbMgr:
-            self.notebook.RemovePage(page = 'resultDbMgr')
+            self.notebook.RemovePage(page='resultDbMgr')
 
     def OnPageChanged(self, event):
         """Tab switched"""
@@ -502,27 +560,28 @@
             dbMgrIndxs.append(self.notebook.GetPageIndexByName('inputDbMgr'))
             dbMgrIndxs.append(self.notebook.GetPageIndexByName('resultDbMgr'))
             if self.notebook.GetSelection() in dbMgrIndxs:
-                self.stBar.AddStatusItem(text = _('Loading tables...'), 
-                                         key = 'dbMgr',
-                                         priority = self.stPriorities['important'])
+                self.stBar.AddStatusItem(
+                    text=_('Loading tables...'),
+                    key='dbMgr',
+                    priority=self.stPriorities['important'])
                 self._updateDbMgrData()
-                self.stBar.RemoveStatusItem(key = 'dbMgr')
-            # update columns (when some is added in input tables browser), TODO needs optimization  
-            elif  self.notebook.GetSelection() == self.notebook.GetPageIndexByName('parameters'):
-                self.OnALayerSel(None) 
+                self.stBar.RemoveStatusItem(key='dbMgr')
+            # update columns (when some is added in input tables browser), TODO
+            # needs optimization
+            elif self.notebook.GetSelection() == self.notebook.GetPageIndexByName('parameters'):
+                self.OnALayerSel(None)
                 self.OnNLayerSel(None)
- 
+
         self.Layout()
 
-       
     def _updateDbMgrData(self):
-            """Updates input/result tables page """
-            if self.notebook.GetSelection() == self.notebook.GetPageIndexByName('inputDbMgr'):
-                self._updateInputDbMgrData()
-            elif self.notebook.GetSelection() == self.notebook.GetPageIndexByName('resultDbMgr'):
-                self._updateResultDbMgrData()
-            else:
-                self.stBar.RemoveStatusItem('manager')   
+        """Updates input/result tables page """
+        if self.notebook.GetSelection() == self.notebook.GetPageIndexByName('inputDbMgr'):
+            self._updateInputDbMgrData()
+        elif self.notebook.GetSelection() == self.notebook.GetPageIndexByName('resultDbMgr'):
+            self._updateResultDbMgrData()
+        else:
+            self.stBar.RemoveStatusItem('manager')
 
     def _updateInputDbMgrData(self):
         """Loads data according to selected layers in Parameters tab"""
@@ -530,7 +589,7 @@
         # changed vector map
         if self.inpDbMgrData['input'] != inpSel:
             wx.BeginBusyCursor()
-            self.inpDbMgrData['dbMgr'].ChangeVectorMap(vectorName = inpSel)
+            self.inpDbMgrData['dbMgr'].ChangeVectorMap(vectorName=inpSel)
             self.inpDbMgrData['input'] = inpSel
             for layerName in ['arc_layer', 'node_layer']:
                 try:
@@ -544,7 +603,7 @@
             needLayers = []
             browseLayers = self.inpDbMgrData['browse'].GetAddedLayers()
             for layerName in ['arc_layer', 'node_layer']:
-                try:                
+                try:
                     inpLayer = int(self.inputData[layerName].GetValue())
                 except ValueError:
                     continue
@@ -571,7 +630,7 @@
         if self.resultDbMgrData['input'] != vectName:
             wx.BeginBusyCursor()
             dbMgr = self.resultDbMgrData['dbMgr']
-            dbMgr.ChangeVectorMap(vectorName = vectName)
+            dbMgr.ChangeVectorMap(vectorName=vectName)
 
             for layer in dbMgr.GetVectorLayers():
                 self.resultDbMgrData['browse'].AddLayer(layer)
@@ -584,13 +643,13 @@
         vectorMap = self.inputData['input'].GetValue()
         vectMapName, mapSet = ParseMapStr(vectorMap)
         vectorMap = vectMapName + '@' + mapSet
-        existsMap = grass.find_file(name = vectMapName, 
-                                    element = 'vector', 
-                                    mapset = mapSet)
+        existsMap = grass.find_file(name=vectMapName,
+                                    element='vector',
+                                    mapset=mapSet)
         if not existsMap["name"]:
             return
 
-        cmd = ['d.vect', 
+        cmd = ['d.vect',
                'map=' + vectorMap]
 
         if True:
@@ -605,12 +664,12 @@
             self.inputData["turn_layer"].GetParent().Show()
             self.inputData["turn_cat_layer"].GetParent().Show()
 
-            self.vnet_mgr.SetParams(params = {}, flags = {"t" : True})
+            self.vnet_mgr.SetParams(params={}, flags={"t": True})
         else:
             self.inputData["turn_layer"].GetParent().Hide()
             self.inputData["turn_cat_layer"].GetParent().Hide()
 
-            self.vnet_mgr.SetParams(params = {}, flags = {"t" : False})
+            self.vnet_mgr.SetParams(params={}, flags={"t": False})
 
         self.Layout()
 
@@ -619,59 +678,61 @@
         if method == "EditMode" and not kwargs["activated"]:
             ptListToolbar = self.toolbars['pointsList']
             if ptListToolbar:
-                ptListToolbar.ToggleTool(id = ptListToolbar.GetToolId("insertPoint"),
-                                         toggle = False)
+                ptListToolbar.ToggleTool(
+                    id=ptListToolbar.GetToolId("insertPoint"), toggle=False)
 
         if method == "EditMode" and kwargs["activated"]:
             ptListToolbar = self.toolbars['pointsList']
             if ptListToolbar:
-                ptListToolbar.ToggleTool(id = ptListToolbar.GetToolId("insertPoint"),
-                                         toggle = True)
+                ptListToolbar.ToggleTool(
+                    id=ptListToolbar.GetToolId("insertPoint"), toggle=True)
 
-        if method == "SetPointData" and ("e" in kwargs.keys() or "n" in kwargs.keys()):
-          self.notebook.SetSelectionByName("points")
+        if method == "SetPointData" and (
+                "e" in kwargs.keys() or "n" in kwargs.keys()):
+            self.notebook.SetSelectionByName("points")
 
-
     def OnCreateTtbBtn(self, event):
 
         params, err_params, flags = self.vnet_mgr.GetParams()
-        dlg = CreateTtbDialog(parent = self, init_data = params)
+        dlg = CreateTtbDialog(parent=self, init_data=params)
 
         if dlg.ShowModal() == wx.ID_OK:
-            self.stBar.AddStatusItem(text = _('Creating turntable...'),
-                                     key = 'ttb',
-                                     priority =  self.stPriorities['important'])
+            self.stBar.AddStatusItem(text=_('Creating turntable...'),
+                                     key='ttb',
+                                     priority=self.stPriorities['important'])
 
             params = dlg.GetData()
             if not self.vnet_mgr.CreateTttb(params):
-                self.stBar.RemoveStatusItem('ttb')    
-        dlg.Destroy()              
+                self.stBar.RemoveStatusItem('ttb')
+        dlg.Destroy()
 
     def TtbCreated(self):
 
         params, err_params, flags = self.vnet_mgr.GetParams()
         self._updateParamsTab(params, flags)
-        
-        self.stBar.RemoveStatusItem('ttb')  
 
+        self.stBar.RemoveStatusItem('ttb')
+
     def OnVectSel(self, event):
         """When vector map is selected it populates other comboboxes in Parameters tab (layer selects, columns selects)"""
-        if self.vnet_mgr.IsSnappingActive(): #TODO should be in vnet_mgr
-            self.vnet_mgr.Snapping(activate = True)
+        if self.vnet_mgr.IsSnappingActive():  # TODO should be in vnet_mgr
+            self.vnet_mgr.Snapping(activate=True)
 
-        vectMapName, mapSet = self._parseMapStr(self.inputData['input'].GetValue())
+        vectMapName, mapSet = self._parseMapStr(
+            self.inputData['input'].GetValue())
         vectorMap = vectMapName + '@' + mapSet
 
-        for sel in ['arc_layer', 'node_layer']:#, 'turn_layer', 'turn_cat_layer']:
+        # , 'turn_layer', 'turn_cat_layer']:
+        for sel in ['arc_layer', 'node_layer']:
             self.inputData[sel].Clear()
-            self.inputData[sel].InsertLayers(vector = vectorMap)
+            self.inputData[sel].InsertLayers(vector=vectorMap)
 
         items = self.inputData['arc_layer'].GetItems()
         itemsLen = len(items)
         if itemsLen < 1:
             self.addToTreeBtn.Disable()
             if hasattr(self, 'inpDbMgrData'):
-                self._updateInputDbMgrPage(show = False)
+                self._updateInputDbMgrPage(show=False)
             self.inputData['arc_layer'].SetValue("")
             self.inputData['node_layer'].SetValue("")
             for sel in ['arc_column', 'arc_backward_column', 'node_column']:
@@ -682,48 +743,52 @@
             self.inputData['node_layer'].SetSelection(0)
         elif itemsLen >= 1:
             if unicode("1") in items:
-                iItem = items.index(unicode("1")) 
+                iItem = items.index(unicode("1"))
                 self.inputData['arc_layer'].SetSelection(iItem)
             if unicode("2") in items:
-                iItem = items.index(unicode("2")) 
+                iItem = items.index(unicode("2"))
                 self.inputData['node_layer'].SetSelection(iItem)
 
         self.addToTreeBtn.Enable()
         if hasattr(self, 'inpDbMgrData'):
-            self._updateInputDbMgrPage(show = True)
+            self._updateInputDbMgrPage(show=True)
 
-        self.OnALayerSel(event) 
+        self.OnALayerSel(event)
         self.OnNLayerSel(event)
 
         self._setInputData()
 
     def _updateParamsTab(self, params, flags):
-        #TODO flag
+        # TODO flag
 
-                #'turn_layer', 'turn_cat_layer', 
-        for k in ['input', 'arc_layer', 'node_layer', 'arc_column', 'arc_backward_column', 'node_column']:
+                #'turn_layer', 'turn_cat_layer',
+        for k in ['input', 'arc_layer', 'node_layer',
+                  'arc_column', 'arc_backward_column', 'node_column']:
             self.inputData[k].SetValue(params[k])
 
     def OnALayerSel(self, event):
         """When arc layer from vector map is selected, populates corespondent columns selects"""
-        self.inputData['arc_column'].InsertColumns(vector = self.inputData['input'].GetValue(), 
-                                                 layer = self.inputData['arc_layer'].GetValue(), 
-                                                 type = self.columnTypes)
-        self.inputData['arc_backward_column'].InsertColumns(vector = self.inputData['input'].GetValue(), 
-                                                 layer = self.inputData['arc_layer'].GetValue(), 
-                                                 type = self.columnTypes)
+        self.inputData['arc_column'].InsertColumns(
+            vector=self.inputData['input'].GetValue(),
+            layer=self.inputData['arc_layer'].GetValue(),
+            type=self.columnTypes)
+        self.inputData['arc_backward_column'].InsertColumns(
+            vector=self.inputData['input'].GetValue(),
+            layer=self.inputData['arc_layer'].GetValue(),
+            type=self.columnTypes)
 
         self._setInputData()
 
     def OnNLayerSel(self, event):
         """When node layer from vector map is selected, populates corespondent column select"""
         if self.vnet_mgr.IsSnappingActive():
-            self.vnet_mgr.Snapping(activate = True)
+            self.vnet_mgr.Snapping(activate=True)
 
-        self.inputData['node_column'].InsertColumns(vector = self.inputData['input'].GetValue(), 
-                                                layer = self.inputData['node_layer'].GetValue(), 
-                                                type = self.columnTypes)
- 
+        self.inputData['node_column'].InsertColumns(
+            vector=self.inputData['input'].GetValue(),
+            layer=self.inputData['node_layer'].GetValue(),
+            type=self.columnTypes)
+
         self._setInputData()
 
     def _setInputData(self):
@@ -740,68 +805,77 @@
             mapSet = mapValSpl[1]
         else:
             mapSet = grass.gisenv()['MAPSET']
-        mapName = mapValSpl[0] 
-        
-        return mapName, mapSet      
+        mapName = mapValSpl[0]
 
+        return mapName, mapSet
+
     def OnCloseDialog(self, event):
         """Cancel dialog"""
         self.vnet_mgr.CleanUp()
         toolSwitcher = self.giface.GetMapDisplay().GetToolSwitcher()
-        toolSwitcher.RemoveToolbarFromGroup('mouseUse', self.toolbars['pointsList'])
+        toolSwitcher.RemoveToolbarFromGroup(
+            'mouseUse', self.toolbars['pointsList'])
         self.parent.dialogs['vnet'] = None
         self.Destroy()
 
     def OnDefIsecTurnCosts(self, event):
         """Registers/unregisters mouse handler into map window"""
         if self.defIsecTurnsHndlrReg == False:
-            self.mapWin.RegisterMouseEventHandler(wx.EVT_LEFT_DOWN, 
+            self.mapWin.RegisterMouseEventHandler(wx.EVT_LEFT_DOWN,
                                                   self.OnDefIsecTurnCost,
                                                   'cross')
             self.defIsecTurnsHndlrReg = True
         else:
-            self.mapWin.UnregisterMouseEventHandler(wx.EVT_LEFT_DOWN, 
+            self.mapWin.UnregisterMouseEventHandler(wx.EVT_LEFT_DOWN,
                                                     self.OnDefIsecTurnCost)
 
             self.defIsecTurnsHndlrReg = False
 
     def OnDefGlobalTurnCosts(self, event):
 
-        dialog = DefGlobalTurnsDialog(self, data = self.vnet_mgr.GetGlobalTurnsData())
+        dialog = DefGlobalTurnsDialog(
+            self, data=self.vnet_mgr.GetGlobalTurnsData())
         dialog.Show()
 
-    def OnDefIsecTurnCost(self, event): #TODO move to vnet mgr?
+    def OnDefIsecTurnCost(self, event):  # TODO move to vnet mgr?
         """Take coordinates from map window"""
         if event == 'unregistered':
             ptListToolbar = self.toolbars['pointsList']
             if ptListToolbar:
-                ptListToolbar.ToggleTool( id = ptListToolbar.GetToolId("isec_turn_edit"),
-                                          toggle = False)  
+                ptListToolbar.ToggleTool(
+                    id=ptListToolbar.GetToolId("isec_turn_edit"), toggle=False)
             self.handlerRegistered = False
             return
 
         e, n = self.mapWin.GetLastEN()
 
         # compute threshold
-        snapTreshPix = int(UserSettings.Get(group ='vnet', 
-                                            key = 'other', 
-                                            subkey = 'snap_tresh'))
-        res = max(self.mapWin.Map.region['nsres'], self.mapWin.Map.region['ewres'])
+        snapTreshPix = int(UserSettings.Get(group='vnet',
+                                            key='other',
+                                            subkey='snap_tresh'))
+        res = max(
+            self.mapWin.Map.region['nsres'],
+            self.mapWin.Map.region['ewres'])
         snapTreshDist = snapTreshPix * res
 
         params, err_params, flags = self.vnet_mgr.GetParams()
 
         if "input" in err_params:
-            GMessage(parent = self,
-                     message = _("Input vector map does not exist."))
+            GMessage(parent=self,
+                     message=_("Input vector map does not exist."))
 
         if ["turn_layer", "turn_cat_layer"] in err_params:
-            GMessage(parent = self, message = "Please choose existing turntable layer and unique categories layer in Parameters tab.")
+            GMessage(
+                parent=self,
+                message="Please choose existing turntable layer and unique categories layer in Parameters tab.")
 
-        cat = GetNearestNodeCat(e, n, int(params['turn_cat_layer']), snapTreshDist, params["input"])
+        cat = GetNearestNodeCat(
+            e, n, int(params['turn_cat_layer']),
+            snapTreshDist, params["input"])
 
         if not self.def_isec_turns:
-            self.def_isec_turns = DefIntesectionTurnCostDialog(self, self.parent)
+            self.def_isec_turns = DefIntesectionTurnCostDialog(
+                self, self.parent)
             self.def_isec_turns.SetSize((500, 400))
 
         self.def_isec_turns.SetData(params["input"], params["turn_layer"])
@@ -811,17 +885,17 @@
     def OnAnalyze(self, event):
         """Called when network analysis is started"""
 
-        self.stBar.AddStatusItem(text = _('Analysing...'),
-                                 key = 'analyze',
-                                 priority =  self.stPriorities['important'])
+        self.stBar.AddStatusItem(text=_('Analysing...'),
+                                 key='analyze',
+                                 priority=self.stPriorities['important'])
 
         ret = self.vnet_mgr.RunAnalysis()
 
-        #TODO
+        # TODO
         self.resultDbMgrData['analysis'] = self.currAnModule
 
         if ret < 0:
-            self.stBar.RemoveStatusItem(key = 'analyze')
+            self.stBar.RemoveStatusItem(key='analyze')
             if ret == -2:
                 self.notebook.SetSelectionByName("parameters")
 
@@ -830,14 +904,14 @@
         curr_step, steps_num = self.vnet_mgr.GetHistStep()
         self.toolbars['mainToolbar'].UpdateUndoRedo(curr_step, steps_num)
 
-        self.tmp_result = self.vnet_mgr.GetResults() 
+        self.tmp_result = self.vnet_mgr.GetResults()
 
         mainToolbar = self.toolbars['mainToolbar']
         id = vars(mainToolbar)['showResult']
-        mainToolbar.ToggleTool(id =id,
-                               toggle = True)
+        mainToolbar.ToggleTool(id=id,
+                               toggle=True)
 
-        self.stBar.RemoveStatusItem(key = 'analyze')
+        self.stBar.RemoveStatusItem(key='analyze')
 
         self._updateResultDbMgrPage()
         self._updateDbMgrData()
@@ -851,33 +925,33 @@
         toggleState = mainToolbar.GetToolState(id)
 
         if not self.tmp_result:
-            mainToolbar.ToggleTool(id =id,
-                                   toggle = False)
+            mainToolbar.ToggleTool(id=id,
+                                   toggle=False)
         elif toggleState:
             self.vnet_mgr.ShowResult(True)
         else:
             self.vnet_mgr.ShowResult(False)
 
     def OnSaveTmpLayer(self, event):
-        dlg = OutputVectorDialog(parent = self)
+        dlg = OutputVectorDialog(parent=self)
         dlg.ShowModal()
         self.vnet_mgr.SaveTmpLayer(dlg.vectSel.GetValue())
         dlg.Destroy()
 
     def OnSettings(self, event):
         """Displays vnet settings dialog"""
-        dlg = SettingsDialog(parent=self, id=wx.ID_ANY, 
-                             title=_('Settings'), vnet_mgr = self.vnet_mgr)
-        
+        dlg = SettingsDialog(parent=self, id=wx.ID_ANY,
+                             title=_('Settings'), vnet_mgr=self.vnet_mgr)
+
         dlg.ShowModal()
         dlg.Destroy()
 
     def OnAnalysisChanged(self, event):
         """Updates dialog when analysis is changed"""
         # set chosen analysis
-        iAn = self.toolbars['analysisToolbar'].anChoice.GetSelection() 
+        iAn = self.toolbars['analysisToolbar'].anChoice.GetSelection()
         self.currAnModule = self.vnet_mgr.GetAnalyses()[iAn]
-        self.vnet_mgr.SetParams({"analysis" : self.currAnModule}, {})
+        self.vnet_mgr.SetParams({"analysis": self.currAnModule}, {})
 
         # update dialog for particular analysis
         if self.currAnModule == "v.net.iso":
@@ -885,9 +959,9 @@
         else:
             self.anSettings['iso_lines'].GetParent().Hide()
 
-        #if self.currAnModule == "v.net.flow": TODO not implemented
+        # if self.currAnModule == "v.net.flow": TODO not implemented
         #    self.anSettings['show_cut'].GetParent().Show()
-        #else:
+        # else:
         #    self.anSettings['show_cut'].GetParent().Hide()
 
         # show only corresponding selects for chosen v.net module
@@ -898,7 +972,6 @@
         used_cols = []
         attrCols = an_props["cmdParams"]["cols"]
 
-
         for col in attrCols.iterkeys():
 
             if "inputField" in attrCols[col]:
@@ -911,10 +984,11 @@
 
             inputPanel = self.inputData[colInptF].GetParent()
             inputPanel.Show()
-            inputPanel.FindWindowByName(colInptF).SetLabel(attrCols[col]["label"])
+            inputPanel.FindWindowByName(
+                colInptF).SetLabel(attrCols[col]["label"])
 
             if col != colInptF:
-               skip.append(colInptF)
+                skip.append(colInptF)
             used_cols.append(colInptF)
 
         for col in ["arc_backward_column", "arc_column", "node_column"]:
@@ -928,22 +1002,22 @@
         """Start/stop snapping mode"""
 
         if evt == "deactivated":
-            self.stBar.RemoveStatusItem(key = 'snap')
+            self.stBar.RemoveStatusItem(key='snap')
             ptListToolbar = self.toolbars['pointsList']
-            ptListToolbar.ToggleTool(id = ptListToolbar.GetToolId("snapping"),
-                                     toggle = False)
+            ptListToolbar.ToggleTool(id=ptListToolbar.GetToolId("snapping"),
+                                     toggle=False)
 
         elif evt == "computing_points":
-            self.stBar.AddStatusItem(text = _('Computing nodes...'),
-                                     key = 'snap',
-                                     priority = self.stPriorities['important'])
+            self.stBar.AddStatusItem(text=_('Computing nodes...'),
+                                     key='snap',
+                                     priority=self.stPriorities['important'])
 
         elif evt == "computing_points_done":
-            self.stBar.RemoveStatusItem(key = 'snap')
+            self.stBar.RemoveStatusItem(key='snap')
 
     def SnapPointsDone(self):
         """Update map window, when map with nodes to snap is created"""
-        self.stBar.RemoveStatusItem(key = 'snap')
+        self.stBar.RemoveStatusItem(key='snap')
 
     def OnUndo(self, event):
         """Step back in history"""
@@ -964,36 +1038,42 @@
         self._updateParamsTab(params, flags)
 
         anChoice = self.toolbars['analysisToolbar'].anChoice
-        anChoice.SetSelection(self.vnet_mgr.GetAnalyses().index(params["analysis"]))
-        self.currAnModule = params["analysis"] 
+        anChoice.SetSelection(
+            self.vnet_mgr.GetAnalyses().index(
+                params["analysis"]))
+        self.currAnModule = params["analysis"]
         self.resultDbMgrData['analysis'] = params["analysis"]
 
         # set analysis combobox
         anChoice = self.toolbars['analysisToolbar'].anChoice
-        anChoice.SetSelection(self.vnet_mgr.GetAnalyses().index(params["analysis"]))
+        anChoice.SetSelection(
+            self.vnet_mgr.GetAnalyses().index(
+                params["analysis"]))
 
         self._updateResultDbMgrPage()
         self._updateDbMgrData()
 
         self.OnAnalysisChanged(None)
 
+
 class PtsList(PointsList):
+
     def __init__(self, parent, vnet_mgr, id=wx.ID_ANY):
         """ List with points for analysis"""
         self.updateMap = True
         self.vnet_mgr = vnet_mgr
         self.pts_data = self.vnet_mgr.GetPointsManager()
 
-        pts_data_cols = self.pts_data.GetColumns(only_relevant = False)
+        pts_data_cols = self.pts_data.GetColumns(only_relevant=False)
 
         cols = []
-        for i_col, name in enumerate(pts_data_cols["name"]): 
+        for i_col, name in enumerate(pts_data_cols["name"]):
             if i_col == 0:
                 continue
-            cols.append([name, pts_data_cols["label"][i_col], 
-                              pts_data_cols["type"][i_col], pts_data_cols["def_vals"][i_col]])
+            cols.append([name, pts_data_cols["label"][i_col], pts_data_cols[
+                        "type"][i_col], pts_data_cols["def_vals"][i_col]])
 
-        PointsList.__init__(self, parent = parent, cols = cols, id =  id)      
+        PointsList.__init__(self, parent=parent, cols=cols, id=id)
 
         self.vnet_mgr.pointsChanged.connect(self.PointsChanged)
         self.vnet_mgr.parametersChanged.connect(self.ParametersChanged)
@@ -1020,10 +1100,10 @@
             self.ChangeColEditable('type', type_labels)
             colNum = self._getColumnNum('type')
 
-            for iItem, item in enumerate(self.itemDataMap): 
+            for iItem, item in enumerate(self.itemDataMap):
                 self.EditCellKey(iItem, 'type', self.selIdxs[iItem][colNum])
 
-                if not item[1]:               
+                if not item[1]:
                     self.CheckItem(iItem, False)
 
         else:
@@ -1031,12 +1111,12 @@
                 self.HideColumn('type')
 
     def ParametersChanged(self, method, kwargs):
-            if "analysis" in kwargs["changed_params"].keys():
-                self.AnalysisChanged(analysis = kwargs["changed_params"]["analysis"])
+        if "analysis" in kwargs["changed_params"].keys():
+            self.AnalysisChanged(analysis=kwargs["changed_params"]["analysis"])
 
     def OnItemActivated(self, event):
         changed, key = PointsList.OnItemActivated(self, event)
-        
+
         if not changed:
             return
 
@@ -1075,29 +1155,28 @@
         idx = self._findIndex(key)
         for k, v in data.iteritems():
             if k == "use":
-                
+
                 if v and not self.IsChecked(idx):
                     self.CheckItem(idx, True)
                 elif not v and self.IsChecked(idx):
-                    self.CheckItem(idx, False) 
+                    self.CheckItem(idx, False)
             else:
                 found = 0
                 for col in self.colsData:
                     if k == col[0]:
-                      found = 1
-                      break
+                        found = 1
+                        break
 
                 if found:
-                    self.EditCellKey(key, k, v)    
+                    self.EditCellKey(key, k, v)
 
-
     def OnItemSelected(self, event):
         """Item selected"""
         PointsList.OnItemSelected(self, event)
         self.selectedkey = self.GetItemData(self.selected)
 
         if self.selectedkey == self.pts_data.GetSelected():
-          return
+            return
 
         if self.selectedkey == wx.NOT_FOUND:
             self.pts_data.SetSelected(None)
@@ -1106,13 +1185,16 @@
 
     def OnCheckItem(self, index, flag):
         "flag is True if the item was checked, False if unchecked"
-        key =  self.GetItemData(index)
-        if self.pts_data.GetPointData(key)["use"]!= flag:
-            self.pts_data.SetPointData(key, {"use" : flag})
+        key = self.GetItemData(index)
+        if self.pts_data.GetPointData(key)["use"] != flag:
+            self.pts_data.SetPointData(key, {"use": flag})
 
+
 class SettingsDialog(wx.Dialog):
-    def __init__(self, parent, id, title, vnet_mgr, pos=wx.DefaultPosition, size=wx.DefaultSize,
-                 style=wx.DEFAULT_DIALOG_STYLE):
+
+    def __init__(
+            self, parent, id, title, vnet_mgr, pos=wx.DefaultPosition,
+            size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE):
         """Settings dialog"""
         wx.Dialog.__init__(self, parent, id, title, pos, size, style)
 
@@ -1123,70 +1205,95 @@
         self.settings = {}
 
         # create all staticboxes before creating widgets, needed for Mac
-        otherBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                                label =" %s " % _("Other settings"))
+        otherBox = wx.StaticBox(parent=self, id=wx.ID_ANY,
+                                label=" %s " % _("Other settings"))
         otherBoxSizer = wx.StaticBoxSizer(otherBox, wx.VERTICAL)
-        ptsStyleBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                                   label =" %s " % _("Point style:"))
+        ptsStyleBox = wx.StaticBox(parent=self, id=wx.ID_ANY,
+                                   label=" %s " % _("Point style:"))
         ptsStyleBoxSizer = wx.StaticBoxSizer(ptsStyleBox, wx.VERTICAL)
-        styleBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                                label =" %s " % _("Analysis result style:"))
+        styleBox = wx.StaticBox(parent=self, id=wx.ID_ANY,
+                                label=" %s " % _("Analysis result style:"))
         styleBoxSizer = wx.StaticBoxSizer(styleBox, wx.VERTICAL)
 
-        rules = RunCommand('v.colors', 
-                           read = True,
-                           flags = 'l')
+        rules = RunCommand('v.colors',
+                           read=True,
+                           flags='l')
 
-        settsLabels = {} 
+        settsLabels = {}
 
-        settsLabels['color_table'] = wx.StaticText(parent = self, id = wx.ID_ANY, 
-                                                   label = _('Color table style %s:') % '(v.net.flow)')
-        self.settings['color_table'] = wx.ComboBox(parent = self, id = wx.ID_ANY,
-                                                   choices = rules.split(),
-                                                   style = wx.CB_READONLY, size = (180, -1))
+        settsLabels['color_table'] = wx.StaticText(
+            parent=self,
+            id=wx.ID_ANY,
+            label=_('Color table style %s:') %
+            '(v.net.flow)')
+        self.settings['color_table'] = wx.ComboBox(
+            parent=self, id=wx.ID_ANY, choices=rules.split(),
+            style=wx.CB_READONLY, size=(180, -1))
 
-        setStyle = UserSettings.Get(group ='vnet', key = "res_style", subkey = "color_table")
+        setStyle = UserSettings.Get(
+            group='vnet',
+            key="res_style",
+            subkey="color_table")
         i = self.settings['color_table'].FindString(setStyle)
-        if i != wx.NOT_FOUND: 
+        if i != wx.NOT_FOUND:
             self.settings['color_table'].Select(i)
 
-        self.settings["invert_colors"] = wx.CheckBox(parent = self, id=wx.ID_ANY,
-                                                       label = _('Invert colors %s:') % '(v.net.flow)')
-        setInvert = UserSettings.Get(group ='vnet', key = "res_style", subkey = "invert_colors")
+        self.settings["invert_colors"] = wx.CheckBox(
+            parent=self,
+            id=wx.ID_ANY,
+            label=_('Invert colors %s:') %
+            '(v.net.flow)')
+        setInvert = UserSettings.Get(
+            group='vnet',
+            key="res_style",
+            subkey="invert_colors")
         self.settings["invert_colors"].SetValue(setInvert)
 
         self.colorsSetts = {
-                            "line_color" : ["res_style", _("Line color:")],
-                            "unused" : ["point_colors", _("Color for unused point:")], 
-                            "used1cat" : ["point_colors", _("Color for Start/From/Source/Used point:")],
-                            "used2cat" : ["point_colors", _("Color for End/To/Sink point:")],
-                            "selected" : ["point_colors", _("Color for selected point:")]
-                           }
+            "line_color": [
+                "res_style",
+                _("Line color:")],
+            "unused": [
+                "point_colors",
+                _("Color for unused point:")],
+            "used1cat": [
+                "point_colors",
+                _("Color for Start/From/Source/Used point:")],
+            "used2cat": [
+                "point_colors",
+                _("Color for End/To/Sink point:")],
+            "selected": [
+                "point_colors",
+                _("Color for selected point:")]}
 
         for settKey, sett in self.colorsSetts.iteritems():
-            settsLabels[settKey] = wx.StaticText(parent = self, id = wx.ID_ANY, label = sett[1])
-            col = UserSettings.Get(group ='vnet', key = sett[0], subkey = settKey)        
-            self.settings[settKey] = csel.ColourSelect(parent = self, id = wx.ID_ANY,
-                                            colour = wx.Colour(col[0],
-                                                               col[1],
-                                                               col[2], 
-                                                               255))
+            settsLabels[settKey] = wx.StaticText(
+                parent=self, id=wx.ID_ANY, label=sett[1])
+            col = UserSettings.Get(group='vnet', key=sett[0], subkey=settKey)
+            self.settings[settKey] = csel.ColourSelect(
+                parent=self, id=wx.ID_ANY, colour=wx.Colour(
+                    col[0], col[1], col[2], 255))
 
         self.sizeSetts = {
-                          "line_width" : ["res_style", _("Line width:")],
-                          "point_size" : ["point_symbol", _("Point size:")], 
-                          "point_width" : ["point_symbol", _("Point width:")],
-                          "snap_tresh" : ["other", _("Snapping treshold in pixels:")],
-                          "max_hist_steps" : ["other", _("Maximum number of results in history:")]
-                         }
+            "line_width": ["res_style", _("Line width:")],
+            "point_size": ["point_symbol", _("Point size:")],
+            "point_width": ["point_symbol", _("Point width:")],
+            "snap_tresh": ["other", _("Snapping treshold in pixels:")],
+            "max_hist_steps": ["other", _("Maximum number of results in history:")]
+        }
 
         for settKey, sett in self.sizeSetts.iteritems():
-            settsLabels[settKey] = wx.StaticText(parent = self, id = wx.ID_ANY, label = sett[1])
-            self.settings[settKey] = wx.SpinCtrl(parent = self, id = wx.ID_ANY, min = 1, max = 50)
-            size = int(UserSettings.Get(group = 'vnet', key = sett[0], subkey = settKey))
+            settsLabels[settKey] = wx.StaticText(
+                parent=self, id=wx.ID_ANY, label=sett[1])
+            self.settings[settKey] = wx.SpinCtrl(
+                parent=self, id=wx.ID_ANY, min=1, max=50)
+            size = int(
+                UserSettings.Get(
+                    group='vnet',
+                    key=sett[0],
+                    subkey=settKey))
             self.settings[settKey].SetValue(size)
 
-
         # buttons
         self.btnSave = wx.Button(self, wx.ID_SAVE)
         self.btnApply = wx.Button(self, wx.ID_APPLY)
@@ -1195,90 +1302,131 @@
 
         # bindings
         self.btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
-        self.btnApply.SetToolTipString(_("Apply changes for the current session"))
+        self.btnApply.SetToolTipString(
+            _("Apply changes for the current session"))
         self.btnSave.Bind(wx.EVT_BUTTON, self.OnSave)
-        self.btnSave.SetToolTipString(_("Apply and save changes to user settings file (default for next sessions)"))
+        self.btnSave.SetToolTipString(
+            _("Apply and save changes to user settings file (default for next sessions)"))
         self.btnClose.Bind(wx.EVT_BUTTON, self.OnClose)
         self.btnClose.SetToolTipString(_("Close dialog"))
 
-        #Layout
+        # Layout
 
         # Analysis result style layout
         self.SetMinSize(self.GetBestSize())
 
         sizer = wx.BoxSizer(wx.VERTICAL)
 
+        gridSizer = wx.GridBagSizer(vgap=1, hgap=1)
 
-        gridSizer = wx.GridBagSizer(vgap = 1, hgap = 1)
+        row = 0
+        gridSizer.Add(
+            item=settsLabels["line_color"],
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                row,
+                0))
+        gridSizer.Add(item=self.settings["line_color"],
+                      flag=wx.ALIGN_RIGHT | wx.ALL, border=5,
+                      pos=(row, 1))
 
-        row = 0
-        gridSizer.Add(item =  settsLabels["line_color"], flag = wx.ALIGN_CENTER_VERTICAL, pos =(row, 0))
-        gridSizer.Add(item = self.settings["line_color"],
-                      flag = wx.ALIGN_RIGHT | wx.ALL, border = 5,
-                      pos =(row, 1))
- 
         row += 1
-        gridSizer.Add(item =  settsLabels["line_width"], flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
-        gridSizer.Add(item = self.settings["line_width"],
-                      flag = wx.ALIGN_RIGHT | wx.ALL, border = 5,
-                      pos = (row, 1))
+        gridSizer.Add(
+            item=settsLabels["line_width"],
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                row,
+                0))
+        gridSizer.Add(item=self.settings["line_width"],
+                      flag=wx.ALIGN_RIGHT | wx.ALL, border=5,
+                      pos=(row, 1))
         row += 1
-        gridSizer.Add(item = settsLabels['color_table'], flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
-        gridSizer.Add(item = self.settings['color_table'],
-                      flag = wx.ALIGN_RIGHT | wx.ALL, border = 5,
-                      pos = (row, 1))
+        gridSizer.Add(
+            item=settsLabels['color_table'],
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                row,
+                0))
+        gridSizer.Add(item=self.settings['color_table'],
+                      flag=wx.ALIGN_RIGHT | wx.ALL, border=5,
+                      pos=(row, 1))
 
         row += 1
-        gridSizer.Add(item = self.settings["invert_colors"], flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
+        gridSizer.Add(
+            item=self.settings["invert_colors"],
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                row,
+                0))
 
         gridSizer.AddGrowableCol(1)
-        styleBoxSizer.Add(item = gridSizer, flag = wx.EXPAND)
+        styleBoxSizer.Add(item=gridSizer, flag=wx.EXPAND)
 
         # Point style layout
-        gridSizer = wx.GridBagSizer(vgap = 1, hgap = 1)
+        gridSizer = wx.GridBagSizer(vgap=1, hgap=1)
 
         row = 0
         setts = dict(self.colorsSetts.items() + self.sizeSetts.items())
 
-        settsOrder = ["selected", "used1cat", "used2cat", "unused", "point_size", "point_width"]
+        settsOrder = [
+            "selected",
+            "used1cat",
+            "used2cat",
+            "unused",
+            "point_size",
+            "point_width"]
         for settKey in settsOrder:
             sett = setts[settKey]
-            gridSizer.Add(item = settsLabels[settKey], flag = wx.ALIGN_CENTER_VERTICAL, pos =(row, 0))
-            gridSizer.Add(item = self.settings[settKey],
-                          flag = wx.ALIGN_RIGHT | wx.ALL, border = 5,
-                          pos =(row, 1))  
+            gridSizer.Add(
+                item=settsLabels[settKey],
+                flag=wx.ALIGN_CENTER_VERTICAL,
+                pos=(
+                    row,
+                    0))
+            gridSizer.Add(item=self.settings[settKey],
+                          flag=wx.ALIGN_RIGHT | wx.ALL, border=5,
+                          pos=(row, 1))
             row += 1
 
         gridSizer.AddGrowableCol(1)
-        ptsStyleBoxSizer.Add(item = gridSizer, flag = wx.EXPAND)
+        ptsStyleBoxSizer.Add(item=gridSizer, flag=wx.EXPAND)
 
         # Other settings layout
-        gridSizer = wx.GridBagSizer(vgap = 1, hgap = 1)
+        gridSizer = wx.GridBagSizer(vgap=1, hgap=1)
 
-        row = 0 
+        row = 0
         for otherSettName in ["snap_tresh", "max_hist_steps"]:
-            gridSizer.Add(item = settsLabels[otherSettName], flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
-            gridSizer.Add(item = self.settings[otherSettName],
-                          flag = wx.ALIGN_RIGHT | wx.ALL, border = 5,
-                          pos = (row, 1))
+            gridSizer.Add(
+                item=settsLabels[otherSettName],
+                flag=wx.ALIGN_CENTER_VERTICAL,
+                pos=(
+                    row,
+                    0))
+            gridSizer.Add(item=self.settings[otherSettName],
+                          flag=wx.ALIGN_RIGHT | wx.ALL, border=5,
+                          pos=(row, 1))
             row += 1
 
         gridSizer.AddGrowableCol(1)
-        otherBoxSizer.Add(item = gridSizer, flag = wx.EXPAND)
+        otherBoxSizer.Add(item=gridSizer, flag=wx.EXPAND)
 
         btnSizer = wx.BoxSizer(wx.HORIZONTAL)
-        btnSizer.Add(self.btnApply, flag = wx.LEFT | wx.RIGHT, border = 5)
+        btnSizer.Add(self.btnApply, flag=wx.LEFT | wx.RIGHT, border=5)
         btnSizer.Add(self.btnSave, flag=wx.LEFT | wx.RIGHT, border=5)
-        btnSizer.Add(self.btnClose, flag = wx.LEFT | wx.RIGHT, border = 5)
+        btnSizer.Add(self.btnClose, flag=wx.LEFT | wx.RIGHT, border=5)
 
-        sizer.Add(item = styleBoxSizer, flag = wx.EXPAND | wx.ALL, border = 5)
-        sizer.Add(item = ptsStyleBoxSizer, flag = wx.EXPAND | wx.ALL, border = 5)
-        sizer.Add(item = otherBoxSizer, flag = wx.EXPAND | wx.ALL, border = 5)
-        sizer.Add(item = btnSizer, flag = wx.EXPAND | wx.ALL, border = 5, proportion = 0)    
+        sizer.Add(item=styleBoxSizer, flag=wx.EXPAND | wx.ALL, border=5)
+        sizer.Add(item=ptsStyleBoxSizer, flag=wx.EXPAND | wx.ALL, border=5)
+        sizer.Add(item=otherBoxSizer, flag=wx.EXPAND | wx.ALL, border=5)
+        sizer.Add(
+            item=btnSizer,
+            flag=wx.EXPAND | wx.ALL,
+            border=5,
+            proportion=0)
 
         self.SetSizer(sizer)
         sizer.Fit(self)
-     
+
     def OnSave(self, event):
         """Button 'Save' pressed"""
         self.UpdateSettings()
@@ -1291,74 +1439,81 @@
         self.Close()
 
     def UpdateSettings(self):
-        UserSettings.Set(group ='vnet', key = "res_style", subkey ='line_width',
-                         value = self.settings["line_width"].GetValue())
+        UserSettings.Set(group='vnet', key="res_style", subkey='line_width',
+                         value=self.settings["line_width"].GetValue())
 
         for settKey, sett in self.colorsSetts.iteritems():
             col = tuple(self.settings[settKey].GetColour())
-            UserSettings.Set(group = 'vnet', 
-                             key = sett[0], 
-                             subkey = settKey,
-                             value = col)
+            UserSettings.Set(group='vnet',
+                             key=sett[0],
+                             subkey=settKey,
+                             value=col)
 
         for settKey, sett in self.sizeSetts.iteritems():
-            UserSettings.Set(group = 'vnet', key = sett[0], subkey = settKey, 
-                             value = self.settings[settKey].GetValue())
+            UserSettings.Set(group='vnet', key=sett[0], subkey=settKey,
+                             value=self.settings[settKey].GetValue())
 
-        UserSettings.Set(group = 'vnet', key = 'res_style', subkey = 'color_table', 
-                        value = self.settings['color_table'].GetStringSelection())
+        UserSettings.Set(
+            group='vnet',
+            key='res_style',
+            subkey='color_table',
+            value=self.settings['color_table'].GetStringSelection())
 
-        UserSettings.Set(group = 'vnet', key = 'res_style', subkey = 'invert_colors', 
-                        value = self.settings['invert_colors'].IsChecked())
+        UserSettings.Set(group='vnet', key='res_style', subkey='invert_colors',
+                         value=self.settings['invert_colors'].IsChecked())
 
         self.vnet_mgr.SettingsUpdated()
 
     def OnApply(self, event):
         """Button 'Apply' pressed"""
         self.UpdateSettings()
-        #self.Close()
+        # self.Close()
 
     def OnClose(self, event):
         """Button 'Cancel' pressed"""
         self.Close()
 
+
 class CreateTtbDialog(wx.Dialog):
 
     def __init__(self, parent, init_data, id=wx.ID_ANY,
-                 title = _("New vector map with turntable"), style=wx.DEFAULT_DIALOG_STYLE):
+                 title=_("New vector map with turntable"),
+                 style=wx.DEFAULT_DIALOG_STYLE):
         """Create turntable dialog."""
-        wx.Dialog.__init__(self, parent, id, title = _(title), style = style)
+        wx.Dialog.__init__(self, parent, id, title=_(title), style=style)
 
         box = wx.StaticBox(self, -1, "Vector map and layers for analysis")
         bsizer = wx.StaticBoxSizer(box, wx.VERTICAL)
         label = {}
         dataSelects = [
-                        ['input', "Choose vector map for analysis:", Select],
-                        ['output', "Name of vector map with turntable:", Select],
-                        ['arc_layer', "Arc layer which will be expanded by turntable:", LayerSelect],
-                        ['turn_layer', "Layer with turntable:", LayerSelect],
-                        ['turn_cat_layer', "Layer with unique categories for turntable:", LayerSelect],
-                      ]
+            ['input', "Choose vector map for analysis:", Select],
+            ['output', "Name of vector map with turntable:", Select],
+            ['arc_layer', "Arc layer which will be expanded by turntable:", LayerSelect],
+            ['turn_layer', "Layer with turntable:", LayerSelect],
+            ['turn_cat_layer', "Layer with unique categories for turntable:", LayerSelect],
+        ]
 
         self.inputData = {}
 
         selPanels = {}
 
         for dataSel in dataSelects:
-            selPanels[dataSel[0]] = wx.Panel(parent = self)
-            if dataSel[0] in  ['input', 'output']:
-                self.inputData[dataSel[0]] = dataSel[2](parent = selPanels[dataSel[0]],
-                                                        size = (-1, -1), 
-                                                        type = 'vector')
+            selPanels[dataSel[0]] = wx.Panel(parent=self)
+            if dataSel[0] in ['input', 'output']:
+                self.inputData[
+                    dataSel[0]] = dataSel[2](
+                    parent=selPanels[dataSel[0]],
+                    size=(-1, -1),
+                    type='vector')
             elif dataSel[0] != 'input':
-                self.inputData[dataSel[0]] = dataSel[2](parent = selPanels[dataSel[0]],  
-                                                        size = (-1, -1))
+                self.inputData[dataSel[0]] = dataSel[2](
+                    parent=selPanels[dataSel[0]], size=(-1, -1))
 
-            label[dataSel[0]] =  wx.StaticText(parent =  selPanels[dataSel[0]], 
-                                               name = dataSel[0])
+            label[dataSel[0]] = wx.StaticText(parent=selPanels[dataSel[0]],
+                                              name=dataSel[0])
             label[dataSel[0]].SetLabel(dataSel[1])
 
-        self.inputData['input'].Bind(wx.EVT_TEXT, lambda event : self.InputSel) 
+        self.inputData['input'].Bind(wx.EVT_TEXT, lambda event: self.InputSel)
 
         # buttons
         self.btnCancel = wx.Button(self, wx.ID_CANCEL)
@@ -1368,20 +1523,21 @@
         # Layout
         mainSizer = wx.BoxSizer(wx.VERTICAL)
 
-        mainSizer.Add(item = bsizer, proportion = 0,
-                      flag = wx.EXPAND  | wx.TOP | wx.LEFT | wx.RIGHT, border = 5) 
+        mainSizer.Add(item=bsizer, proportion=0,
+                      flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=5)
 
         btn = None
-        for sel in ['input', 'output', 'arc_layer', 'turn_layer', 'turn_cat_layer']:                      
+        for sel in ['input', 'output', 'arc_layer',
+                    'turn_layer', 'turn_cat_layer']:
 
-            selPanels[sel].SetSizer(self._doSelLayout(title = label[sel], 
-                                                      sel = self.inputData[sel], 
-                                                      btn = btn))
-            bsizer.Add(item = selPanels[sel], proportion = 0,
-                       flag = wx.EXPAND)
-  
+            selPanels[sel].SetSizer(self._doSelLayout(title=label[sel],
+                                                      sel=self.inputData[sel],
+                                                      btn=btn))
+            bsizer.Add(item=selPanels[sel], proportion=0,
+                       flag=wx.EXPAND)
+
         for k, v in init_data.iteritems():
-            if self.inputData.has_key(k):
+            if k in self.inputData:
                 self.inputData[k].SetValue(v)
 
         inp_vect_map = self.inputData["input"].GetValue().split("@")[0]
@@ -1392,67 +1548,68 @@
         btnSizer.AddButton(self.btnOk)
         btnSizer.Realize()
 
-        mainSizer.Add(item = btnSizer, proportion = 0,
-                      flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
+        mainSizer.Add(item=btnSizer, proportion=0,
+                      flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
 
-
         self.SetSizer(mainSizer)
         self.Fit()
 
-    def _doSelLayout(self, title, sel, btn = None): 
-        # helper function for layout of self.inputData widgets initialized in _createParametersPage
-        selSizer = wx.BoxSizer(orient = wx.VERTICAL)
+    def _doSelLayout(self, title, sel, btn=None):
+        # helper function for layout of self.inputData widgets initialized in
+        # _createParametersPage
+        selSizer = wx.BoxSizer(orient=wx.VERTICAL)
 
         selTitleSizer = wx.BoxSizer(wx.HORIZONTAL)
-        selTitleSizer.Add(item = title, proportion = 1,
-                          flag = wx.LEFT | wx.TOP | wx.EXPAND, border = 5)
+        selTitleSizer.Add(item=title, proportion=1,
+                          flag=wx.LEFT | wx.TOP | wx.EXPAND, border=5)
 
-        selSizer.Add(item = selTitleSizer, proportion = 0,
-                                 flag = wx.EXPAND)
+        selSizer.Add(item=selTitleSizer, proportion=0,
+                     flag=wx.EXPAND)
 
         if btn:
-                selFiledSizer = wx.BoxSizer(orient = wx.HORIZONTAL)
-                selFiledSizer.Add(item = sel, proportion = 1,
-                             flag = wx.EXPAND | wx.ALL)
+            selFiledSizer = wx.BoxSizer(orient=wx.HORIZONTAL)
+            selFiledSizer.Add(item=sel, proportion=1,
+                              flag=wx.EXPAND | wx.ALL)
 
-                selFiledSizer.Add(item = btn, proportion = 0,
-                             flag = wx.EXPAND | wx.ALL)
+            selFiledSizer.Add(item=btn, proportion=0,
+                              flag=wx.EXPAND | wx.ALL)
 
-                selSizer.Add(item = selFiledSizer, proportion = 0,
-                             flag = wx.EXPAND | wx.ALL| wx.ALIGN_CENTER_VERTICAL,
-                             border = 5)
+            selSizer.Add(item=selFiledSizer, proportion=0,
+                         flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER_VERTICAL,
+                         border=5)
         else:
-                selSizer.Add(item = sel, proportion = 1,
-                             flag = wx.EXPAND | wx.ALL| wx.ALIGN_CENTER_VERTICAL,
-                             border = 5)
+            selSizer.Add(item=sel, proportion=1,
+                         flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER_VERTICAL,
+                         border=5)
         return selSizer
 
     def InputSel(self):
         """When vector map is selected it populates other comboboxes in Parameters tab (layer selects, columns selects)"""
-        vectMapName, mapSet = self._parseMapStr(self.inputData['input'].GetValue())
+        vectMapName, mapSet = self._parseMapStr(
+            self.inputData['input'].GetValue())
         vectorMap = vectMapName + '@' + mapSet
 
         for sel in ['arc_layer', 'turn_layer', 'turn_cat_layer']:
             self.inputData[sel].Clear()
-            self.inputData[sel].InsertLayers(vector = vectorMap)
+            self.inputData[sel].InsertLayers(vector=vectorMap)
 
         items = self.inputData['arc_layer'].GetItems()
         itemsLen = len(items)
         if itemsLen < 1:
             self.addToTreeBtn.Disable()
             if hasattr(self, 'inpDbMgrData'):
-                self._updateInputDbMgrPage(show = False)
+                self._updateInputDbMgrPage(show=False)
             self.inputData['arc_layer'].SetValue("")
             return
         elif itemsLen == 1:
             self.inputData['arc_layer'].SetSelection(0)
         elif itemsLen >= 1:
             if unicode("1") in items:
-                iItem = items.index(unicode("1")) 
+                iItem = items.index(unicode("1"))
                 self.inputData['arc_layer'].SetSelection(iItem)
         self.addToTreeBtn.Enable()
         if hasattr(self, 'inpDbMgrData'):
-            self._updateInputDbMgrPage(show = True)
+            self._updateInputDbMgrPage(show=True)
 
     def GetData(self):
 
@@ -1462,23 +1619,27 @@
 
         return params
 
+
 class OutputVectorDialog(wx.Dialog):
-    def __init__(self, parent,id=wx.ID_ANY,
-                 title =_("Save analysis result"), style=wx.DEFAULT_DIALOG_STYLE):
+
+    def __init__(self, parent, id=wx.ID_ANY, title=_(
+            "Save analysis result"), style=wx.DEFAULT_DIALOG_STYLE):
         """Save analysis result"""
-        wx.Dialog.__init__(self, parent, id, title = _(title), style = style)
+        wx.Dialog.__init__(self, parent, id, title=_(title), style=style)
 
-        self.panel = wx.Panel(parent = self)
-        box = wx.StaticBox (parent = self.panel, id = wx.ID_ANY,
-                            label = "Vector map")
+        self.panel = wx.Panel(parent=self)
+        box = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
+                           label="Vector map")
 
         self.boxSizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
-       
+
         # text fields and it's captions
-        self.vectSel = Select(parent = self.panel, type = 'vector', 
-                              mapsets = [grass.gisenv()['MAPSET']],size = (-1, -1))
-        self.vectSellabel = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                          label = _("Name:")) 
+        self.vectSel = Select(
+            parent=self.panel, type='vector',
+            mapsets=[grass.gisenv()['MAPSET']],
+            size=(-1, -1))
+        self.vectSellabel = wx.StaticText(parent=self.panel, id=wx.ID_ANY,
+                                          label=_("Name:"))
 
         # buttons
         self.btnCancel = wx.Button(self.panel, wx.ID_CANCEL)
@@ -1492,32 +1653,33 @@
 
         sizer = wx.BoxSizer(wx.VERTICAL)
 
+        self.boxSizer.Add(item=self.vectSellabel,
+                          flag=wx.ALIGN_CENTER_VERTICAL,
+                          proportion=0)
 
-        self.boxSizer.Add(item = self.vectSellabel, 
-                     flag = wx.ALIGN_CENTER_VERTICAL,
-                     proportion = 0)
+        self.boxSizer.Add(item=self.vectSel, proportion=1,
+                          flag=wx.EXPAND | wx.ALL, border=5)
 
-        self.boxSizer.Add(item = self.vectSel, proportion = 1,
-                     flag = wx.EXPAND | wx.ALL, border = 5)
+        sizer.Add(item=self.boxSizer, proportion=1,
+                  flag=wx.EXPAND | wx.ALL, border=5)
 
-        sizer.Add(item = self.boxSizer, proportion = 1,
-                  flag = wx.EXPAND | wx.ALL, border = 5)
-
         btnSizer = wx.StdDialogButtonSizer()
         btnSizer.AddButton(self.btnCancel)
         btnSizer.AddButton(self.btnOk)
         btnSizer.Realize()
 
-        sizer.Add(item = btnSizer, proportion = 0,
-                  flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
+        sizer.Add(item=btnSizer, proportion=0,
+                  flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
 
         self.panel.SetSizer(sizer)
         sizer.Fit(self)
 
+
 class VnetStatusbar(wx.StatusBar):
-    """Extends wx.StatusBar class with functionality to show multiple messages with the highest priority"""       
-    def __init__(self, parent, style, id = wx.ID_ANY, **kwargs):
+    """Extends wx.StatusBar class with functionality to show multiple messages with the highest priority"""
 
+    def __init__(self, parent, style, id=wx.ID_ANY, **kwargs):
+
         wx.StatusBar.__init__(self, parent, id, style, **kwargs)
 
         self.maxPriority = 0
@@ -1527,22 +1689,22 @@
         """Add new item to show
 
         :param text: string to show
-        :param key: item identifier, if already contains 
+        :param key: item identifier, if already contains
                     item with same identifier, overwrites this item
-        :param priority: only items with highest priority are showed 
-        """       
+        :param priority: only items with highest priority are showed
+        """
         statusTextItem = {
-                            'text' : text, 
-                            'key' : key,
-                            'priority' : priority
-                         }
+            'text': text,
+            'key': key,
+            'priority': priority
+        }
 
         for item in self.statusItems:
             if item['key'] == statusTextItem['key']:
                 self.statusItems.remove(item)
         self.statusItems.append(statusTextItem)
         if self.maxPriority < statusTextItem['priority']:
-            self.maxPriority =  statusTextItem['priority']
+            self.maxPriority = statusTextItem['priority']
         self._updateStatus()
 
     def _updateStatus(self):
@@ -1556,7 +1718,7 @@
         wx.StatusBar.SetStatusText(self, currStatusText)
 
     def RemoveStatusItem(self, key):
-        """Remove item 
+        """Remove item
 
         :param key: item identifier
         """
@@ -1570,97 +1732,133 @@
             for item in self.statusItems:
                 self.maxPriority = 0
                 if self.maxPriority < item['priority']:
-                    self.maxPriority =  item['priority']
+                    self.maxPriority = item['priority']
             self._updateStatus()
 
+
 class DefIntesectionTurnCostDialog(wx.Dialog):
 
-    def __init__(self, parent, mapWin, style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, id = wx.ID_ANY, title = _("Edit intersection turns costs"), **kwargs):
-        wx.Dialog.__init__(self, parent, id, style=style, title = title, **kwargs)
+    def __init__(self, parent, mapWin, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
+                 id=wx.ID_ANY, title=_("Edit intersection turns costs"), **kwargs):
+        wx.Dialog.__init__(
+            self,
+            parent,
+            id,
+            style=style,
+            title=title,
+            **kwargs)
 
-        self.dbMgr = DbMgrBase(mapdisplay = mapWin)
-        self.browsePage = self.dbMgr.CreateDbMgrPage(parent = self, pageName = 'browse')
+        self.dbMgr = DbMgrBase(mapdisplay=mapWin)
+        self.browsePage = self.dbMgr.CreateDbMgrPage(
+            parent=self, pageName='browse')
 
     def layout(self):
         sizer = wx.BoxSizer(wx.VERTICAL)
 
-        sizer.Add(item = self.browsePage, proportion = 1,
-                  flag = wx.EXPAND)
-        
+        sizer.Add(item=self.browsePage, proportion=1,
+                  flag=wx.EXPAND)
+
         self.SetSizer(sizer)
 
     def SetData(self, vectMapName, layer):
         if vectMapName != self.dbMgr.GetVectorName():
-            self.dbMgr.ChangeVectorMap(vectorName = vectMapName)
+            self.dbMgr.ChangeVectorMap(vectorName=vectMapName)
         else:
-            self.browsePage.DeleteAllPages() 
-        
+            self.browsePage.DeleteAllPages()
+
         self.browsePage.AddLayer(int(layer))
         self.layer = int(layer)
 
         # TODO HACK!!!
-        self.browsePage.FindWindowById(self.browsePage.layerPage[int(layer)]['sqlNtb']).GetParent().Hide()
+        self.browsePage.FindWindowById(
+            self.browsePage.layerPage[int(layer)]
+            ['sqlNtb']).GetParent().Hide()
 
     def SetIntersection(self, isec):
 
-        self.browsePage.LoadData(self.layer, where = "isec = %d" % (isec))
+        self.browsePage.LoadData(self.layer, where="isec = %d" % (isec))
 
+
 class DefGlobalTurnsDialog(wx.Dialog):
-    def __init__(self, parent, data, style= wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, 
-                 id= wx.ID_ANY, title= _("Define Global Turn Costs"), **kwargs): # v Gassu dopln preklad
 
-        wx.Dialog.__init__(self, parent, id, title, style = style, **kwargs)
+    def __init__(self, parent, data, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
+                 id=wx.ID_ANY, title=_("Define Global Turn Costs"), **kwargs):  # v Gassu dopln preklad
 
+        wx.Dialog.__init__(self, parent, id, title, style=style, **kwargs)
+
         self.data = data
 
-        self.angle_list = TurnAnglesList(parent= self, data= self.data) 
+        self.angle_list = TurnAnglesList(parent=self, data=self.data)
 
-        self.btnAdd = wx.Button(parent=self, id=wx.ID_ANY, label = "Add" )
-        self.btnRemove = wx.Button(parent=self, id=wx.ID_ANY, label = "Remove" )
-        self.btnClose = wx.Button(parent = self, id = wx.ID_CLOSE)
-        self.useUTurns = wx.CheckBox(parent = self, id = wx.ID_ANY, label = "Use U-turns")
+        self.btnAdd = wx.Button(parent=self, id=wx.ID_ANY, label="Add")
+        self.btnRemove = wx.Button(parent=self, id=wx.ID_ANY, label="Remove")
+        self.btnClose = wx.Button(parent=self, id=wx.ID_CLOSE)
+        self.useUTurns = wx.CheckBox(
+            parent=self, id=wx.ID_ANY, label="Use U-turns")
 
         self.btnAdd.Bind(wx.EVT_BUTTON, self.OnAddButtonClick)
         self.btnRemove.Bind(wx.EVT_BUTTON, self.OnRemoveButtonClick)
         self.Bind(wx.EVT_CLOSE, self.OnCloseDialog)
         self.useUTurns.Bind(wx.EVT_CHECKBOX, self.OnCheckedUTurns)
-                
+
         self.btnClose.SetDefault()
         self.useUTurns.SetValue(True)
         self.OnCheckedUTurns(None)
         self.layout()
         self.SetInitialSize((500, 200))
 
-
-
     def layout(self):
         sizer = wx.BoxSizer(wx.VERTICAL)
         labelSizer = wx.BoxSizer(wx.HORIZONTAL)
         addRemoveSizer = wx.BoxSizer(wx.VERTICAL)
-        closeSizer = wx.BoxSizer(wx.HORIZONTAL)  
+        closeSizer = wx.BoxSizer(wx.HORIZONTAL)
 
-        addRemoveSizer.Add(item= self.btnAdd, proportion= 0, flag= wx.ALIGN_RIGHT, border = 10)
-        addRemoveSizer.Add(item= self.btnRemove, proportion= 0, flag= wx.ALIGN_RIGHT, border = 10)
+        addRemoveSizer.Add(
+            item=self.btnAdd,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT,
+            border=10)
+        addRemoveSizer.Add(
+            item=self.btnRemove,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT,
+            border=10)
 
-        labelSizer.Add(item= self.angle_list, proportion= 1, flag= wx.EXPAND, border = 10)
-        labelSizer.Add(item=addRemoveSizer, proportion = 0, flag = wx.ALIGN_RIGHT, border = 10)       
+        labelSizer.Add(
+            item=self.angle_list,
+            proportion=1,
+            flag=wx.EXPAND,
+            border=10)
+        labelSizer.Add(
+            item=addRemoveSizer,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT,
+            border=10)
 
-        closeSizer.Add(item=self.useUTurns, proportion = 1, flag = wx.ALIGN_LEFT, border = 10 )
-        closeSizer.Add(item=self.btnClose, proportion = 0, flag = wx.ALIGN_RIGHT, border = 10)        
+        closeSizer.Add(
+            item=self.useUTurns,
+            proportion=1,
+            flag=wx.ALIGN_LEFT,
+            border=10)
+        closeSizer.Add(
+            item=self.btnClose,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT,
+            border=10)
 
-        sizer.Add(item=labelSizer, proportion = 1, flag = wx.EXPAND)
-        sizer.Add(item=closeSizer, proportion = 0, flag = wx.EXPAND)
+        sizer.Add(item=labelSizer, proportion=1, flag=wx.EXPAND)
+        sizer.Add(item=closeSizer, proportion=0, flag=wx.EXPAND)
 
         self.SetSizer(sizer)
-     
 
     def OnAddButtonClick(self, event):
         """Add new direction over selected row"""
         selected_indices = self.angle_list.GetSelectedIndices()
- 
+
         if not selected_indices:
-            from_value = self.turn_data.GetValue(self.turn_data.GetLinesCount()-1,2)
-            to_value = self.turn_data.GetValue(0,1)
+            from_value = self.turn_data.GetValue(
+                self.turn_data.GetLinesCount() - 1, 2)
+            to_value = self.turn_data.GetValue(0, 1)
             default_row = ["new", from_value, to_value, 0.0]
             self.angle_list.AppendRow(default_row)
 
@@ -1668,17 +1866,16 @@
         i_addition = 0
         for i in selected_indices:
             i += i_addition
-            from_value = self.turn_data.GetValue(i-1,2)
-            to_value = self.turn_data.GetValue(i,1)
+            from_value = self.turn_data.GetValue(i - 1, 2)
+            to_value = self.turn_data.GetValue(i, 1)
             default_row = ["new", from_value, to_value, 0.0]
-            self.angle_list.InsertRow(i,default_row)
+            self.angle_list.InsertRow(i, default_row)
             i_addition += 1
 
-
     def OnRemoveButtonClick(self, event):
         """Delete one or more selected directions"""
         selected_indices = self.angle_list.GetSelectedIndices()
-  
+
         i_reduction = 0
         for i in selected_indices:
             i -= i_reduction
@@ -1692,48 +1889,58 @@
     def OnCheckedUTurns(self, event):
         """Use U-turns in analyse"""
         self.data.SetUTurns(self.useUTurns.GetValue())
-       
+
     def SetData(self, data):
         self.angle_list.SetData(data)
         self.data = data
 
 
+class TurnAnglesList(
+        wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.TextEditMixin):
+    """Virtual editable table with global turns"""
 
-class TurnAnglesList(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.TextEditMixin):
-    """Virtual editable table with global turns"""
-    def __init__(self, parent, data, id= wx.ID_ANY, style= wx.LC_REPORT | wx.LC_VIRTUAL, **kwargs):
-        wx.ListCtrl.__init__(self, parent, id,style= style, **kwargs)
+    def __init__(self, parent, data, id=wx.ID_ANY,
+                 style=wx.LC_REPORT | wx.LC_VIRTUAL, **kwargs):
+        wx.ListCtrl.__init__(self, parent, id, style=style, **kwargs)
         listmix.ListCtrlAutoWidthMixin.__init__(self)
         listmix.TextEditMixin.__init__(self)
-        
+
         self.Populate()
         self.data = data
         self.SetItemCount(self.data.GetLinesCount())
-        
 
     def Populate(self):
         """Columns definition"""
-        self.InsertColumn(col= 0, heading= "Direction", format= wx.LIST_FORMAT_LEFT) # v Gassu dopln preklad 
-        self.InsertColumn(col= 1, heading= "From Angle", format= wx.LIST_FORMAT_RIGHT)
-        self.InsertColumn(col= 2, heading= "To Angle", format= wx.LIST_FORMAT_RIGHT)
-        self.InsertColumn(col= 3, heading= "Cost", format= wx.LIST_FORMAT_RIGHT)
+        self.InsertColumn(
+            col=0,
+            heading="Direction",
+            format=wx.LIST_FORMAT_LEFT)  # v Gassu dopln preklad
+        self.InsertColumn(
+            col=1,
+            heading="From Angle",
+            format=wx.LIST_FORMAT_RIGHT)
+        self.InsertColumn(
+            col=2,
+            heading="To Angle",
+            format=wx.LIST_FORMAT_RIGHT)
+        self.InsertColumn(col=3, heading="Cost", format=wx.LIST_FORMAT_RIGHT)
 
     def OnGetItemText(self, item, col):
         val = self.data.GetValue(item, col)
-        if col in [1,2]:
-            val = RadiansToDegrees(val)            
+        if col in [1, 2]:
+            val = RadiansToDegrees(val)
         return str(val)
 
     def SetVirtualData(self, row, column, text):
         """Set data to table"""
-        if column in [1,2,3]:
+        if column in [1, 2, 3]:
             try:
                 text = float(text)
             except:
                 return
-        if column in [1,2]:
+        if column in [1, 2]:
             text = DegreesToRadians(text)
-            
+
             # Tested allowed range of values
             if text > math.pi:
                 text = 0.0
@@ -1743,15 +1950,14 @@
         self.data.SetValue(text, row, column)
 
         self.edited_row = row
-        self.RefreshItems(0,self.data.GetLinesCount()-1)
+        self.RefreshItems(0, self.data.GetLinesCount() - 1)
 
-
     def AppendRow(self, values):
         self.data.AppendRow(values)
         self.SetItemCount(self.data.GetLinesCount())
 
     def InsertRow(self, line, values):
-        self.data.InsertRow(line,values)
+        self.data.InsertRow(line, values)
         self.SetItemCount(self.data.GetLinesCount())
 
     def DeleteRow(self, row):
@@ -1761,10 +1967,9 @@
     def SetData(self, data):
         self.data = data
         self.SetItemCount(self.data.GetLinesCount())
-        self.RefreshItems(0, self.data.GetLinesCount()-1)
+        self.RefreshItems(0, self.data.GetLinesCount() - 1)
 
-
-    def GetSelectedIndices(self, state =  wx.LIST_STATE_SELECTED):
+    def GetSelectedIndices(self, state=wx.LIST_STATE_SELECTED):
         """Get numbers of selected rows"""
         indices = []
         lastFound = -1

Modified: grass/trunk/gui/wxpython/vnet/toolbars.py
===================================================================
--- grass/trunk/gui/wxpython/vnet/toolbars.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/vnet/toolbars.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -19,16 +19,18 @@
 
 import wx
 
-from icons.icon        import MetaIcon
+from icons.icon import MetaIcon
 from gui_core.toolbars import BaseToolbar, BaseIcons
-from core.gcmd         import RunCommand
+from core.gcmd import RunCommand
 from core.utils import _
 
+
 class PointListToolbar(BaseToolbar):
     """Toolbar for managing list of points
 
     :param parent: reference to VNETDialog
     """
+
     def __init__(self, parent, toolSwitcher, dialog, vnet_mgr):
         BaseToolbar.__init__(self, parent, toolSwitcher)
         self.vnet_mgr = vnet_mgr
@@ -38,52 +40,58 @@
 
         self.InitToolbar(self._toolbarData())
         self.toolSwitcher.AddToolToGroup('mouseUse', self, self.insertPoint)
-        
+
         # realize the toolbar
         self.Realize()
 
-
     def _toolbarData(self):
 
         icons = {
-            'insertPoint'  : MetaIcon(img = 'pointer',
-                                    label = _('Insert points from Map Display')),
-            'snapping'  : MetaIcon(img = 'move',
-                                    label = _('Activate snapping to nodes')),
-            'isec_turn_edit'  : MetaIcon(img = 'line-edit',
-                                    label = _('Activate mode for turns editing')),
-            'global_turn_edit'  : MetaIcon(img = 'vector-tools',
-                                          label = _('Activate mode for global turns editing')),
-            'pointAdd'     : MetaIcon(img = 'point-create',
-                                    label = _('Add new point')),
-            'pointDelete'  : MetaIcon(img = 'gcp-delete',
-                                    label = _('Delete selected point'))
-            }
+            'insertPoint': MetaIcon(
+                img='pointer',
+                label=_('Insert points from Map Display')),
+            'snapping': MetaIcon(
+                img='move',
+                label=_('Activate snapping to nodes')),
+            'isec_turn_edit': MetaIcon(
+                img='line-edit',
+                label=_('Activate mode for turns editing')),
+            'global_turn_edit': MetaIcon(
+                img='vector-tools',
+                label=_('Activate mode for global turns editing')),
+            'pointAdd': MetaIcon(
+                img='point-create',
+                label=_('Add new point')),
+            'pointDelete': MetaIcon(
+                img='gcp-delete',
+                label=_('Delete selected point'))}
 
-        return  self._getToolbarData((('insertPoint', icons['insertPoint'],
-                                      self.OnEditPointMode,#TODO self.list.dialog
+        return self._getToolbarData((('insertPoint', icons['insertPoint'],
+                                      self.OnEditPointMode,  # TODO self.list.dialog
                                       wx.ITEM_CHECK),
-                                      ('snapping', icons['snapping'],
-                                      lambda event : self.vnet_mgr.Snapping(event.IsChecked()),
+                                     ('snapping', icons['snapping'],
+                                      lambda event: self.vnet_mgr.Snapping(
+                                          event.IsChecked()),
                                       wx.ITEM_CHECK),
-                                      (None, ),
+                                     (None, ),
                                      ('pointAdd', icons["pointAdd"],
-                                        lambda event : self.vnet_pts_mgr.AddPoint()),
+                                      lambda event: self.vnet_pts_mgr.AddPoint()),
                                      ('pointDelete', icons["pointDelete"],
-                                       self.OnDeletePoint),
-                                      (None, )#,
-                                      #('isec_turn_edit', icons['isec_turn_edit'],
-                                      #self.dialog.OnDefIsecTurnCosts,
-                                      #wx.ITEM_CHECK),
-                                      #('global_turn_edit', icons['global_turn_edit'],
-                                      #self.dialog.OnDefGlobalTurnCosts)
-                                      ))
-                                    
-    def GetToolId(self, toolName): #TODO can be useful in base
+                                      self.OnDeletePoint),
+                                     (None, )  # ,
+                                     #('isec_turn_edit', icons['isec_turn_edit'],
+                                     # self.dialog.OnDefIsecTurnCosts,
+                                     # wx.ITEM_CHECK),
+                                     #('global_turn_edit', icons['global_turn_edit'],
+                                     # self.dialog.OnDefGlobalTurnCosts)
+                                     ))
+
+    def GetToolId(self, toolName):  # TODO can be useful in base
         return vars(self)[toolName]
 
     def OnEditPointMode(self, event):
-        self.vnet_pts_mgr.EditPointMode(not self.vnet_pts_mgr.IsEditPointModeActive())
+        self.vnet_pts_mgr.EditPointMode(
+            not self.vnet_pts_mgr.IsEditPointModeActive())
 
     def OnDeletePoint(self, event):
         pt_id = self.vnet_pts_mgr.GetSelected()
@@ -93,9 +101,10 @@
 class MainToolbar(BaseToolbar):
     """Main toolbar
     """
+
     def __init__(self, parent, vnet_mgr):
         BaseToolbar.__init__(self, parent)
-        
+
         self.InitToolbar(self._toolbarData())
 
         self.vnet_mgr = vnet_mgr
@@ -106,87 +115,103 @@
     def _toolbarData(self):
 
         icons = {
-                 'run' : MetaIcon(img = 'execute',
-                                  label = _('Execute analysis')),
-                 'undo' : MetaIcon(img = 'undo',
-                                  label = _('Go to previous analysis result')),
-                 'redo' : MetaIcon(img = 'redo',
-                                  label = _('Go to next analysis result')),
-                 'showResult'   : MetaIcon(img = 'layer-add',
-                                    label = _("Show analysis result")),
-                 'saveTempLayer' : MetaIcon(img = 'map-export',
-                                             label = _('Save temporary result')),
-                 'settings' : BaseIcons['settings'].SetLabel( _('Vector network analysis settings')),
-                 'help'       : MetaIcon(img = 'help',
-                                         label = _('Show manual'))
-                }
+            'run': MetaIcon(
+                img='execute',
+                label=_('Execute analysis')),
+            'undo': MetaIcon(
+                img='undo',
+                label=_('Go to previous analysis result')),
+            'redo': MetaIcon(
+                img='redo',
+                label=_('Go to next analysis result')),
+            'showResult': MetaIcon(
+                img='layer-add',
+                label=_("Show analysis result")),
+            'saveTempLayer': MetaIcon(
+                img='map-export',
+                label=_('Save temporary result')),
+            'settings': BaseIcons['settings'].SetLabel(
+                _('Vector network analysis settings')),
+            'help': MetaIcon(
+                img='help',
+                label=_('Show manual'))}
 
         return self._getToolbarData((
-                                     ("run", icons['run'],
-                                      self.parent.OnAnalyze),
-                                     (None, ),     
-                                     ("undo", icons['undo'], 
-                                      self.parent.OnUndo), 
-                                     ("redo", icons['redo'], 
-                                      self.parent.OnRedo),
-                                     (None, ),
-                                     ("showResult", icons['showResult'], 
-                                      self.parent.OnShowResult, wx.ITEM_CHECK), 
-                                     ("saveTempLayer", icons['saveTempLayer'],
-                                      self.parent.OnSaveTmpLayer),
-                                     (None, ),
-                                     ('settings', icons["settings"],
-                                      self.parent.OnSettings),  
-                                     ('help', icons["help"],
-                                      self.OnHelp),                                     
-                                     ("quit", BaseIcons['quit'],
-                                      self.parent.OnCloseDialog)
-                                    ))
+            ("run", icons['run'],
+             self.parent.OnAnalyze),
+            (None, ),
+            ("undo", icons['undo'],
+             self.parent.OnUndo),
+            ("redo", icons['redo'],
+             self.parent.OnRedo),
+            (None, ),
+            ("showResult", icons['showResult'],
+             self.parent.OnShowResult, wx.ITEM_CHECK),
+            ("saveTempLayer", icons['saveTempLayer'],
+             self.parent.OnSaveTmpLayer),
+            (None, ),
+            ('settings', icons["settings"],
+             self.parent.OnSettings),
+            ('help', icons["help"],
+             self.OnHelp),
+            ("quit", BaseIcons['quit'],
+             self.parent.OnCloseDialog)
+        ))
 
-
     def UpdateUndoRedo(self, curr_step, steps_num):
 
         id = vars(self)['showResult']
-        self.ToggleTool(id =id,
-                        toggle = True)
+        self.ToggleTool(id=id,
+                        toggle=True)
 
         if curr_step >= steps_num:
-           self.Enable("undo", False)
+            self.Enable("undo", False)
         else:
-           self.Enable("undo", True)
+            self.Enable("undo", True)
 
         if curr_step <= 0:
-           self.Enable("redo", False)
+            self.Enable("redo", False)
         else:
-           self.Enable("redo", True)  
+            self.Enable("redo", True)
 
-    def OnHelp(self, event) :
-            RunCommand('g.manual',
-                       entry = 'wxGUI.vnet')
+    def OnHelp(self, event):
+        RunCommand('g.manual',
+                   entry='wxGUI.vnet')
 
+
 class AnalysisToolbar(BaseToolbar):
     """Main toolbar
     """
+
     def __init__(self, parent, vnet_mgr):
         BaseToolbar.__init__(self, parent)
-        
+
         self.vnet_mgr = vnet_mgr
         self.InitToolbar(self._toolbarData())
 
         choices = []
 
         for moduleName in self.vnet_mgr.GetAnalyses():
-            choices.append(self.vnet_mgr.GetAnalysisProperties(moduleName)['label'])
+            choices.append(
+                self.vnet_mgr.GetAnalysisProperties(moduleName)['label'])
 
-        self.anChoice = wx.ComboBox(parent = self, id = wx.ID_ANY,
-                                    choices = choices,
-                                    style = wx.CB_READONLY, size = (350, 30))#FIXME
+        self.anChoice = wx.ComboBox(
+            parent=self,
+            id=wx.ID_ANY,
+            choices=choices,
+            style=wx.CB_READONLY,
+            size=(
+                350,
+                30))  # FIXME
         self.anChoice.SetToolTipString(_('Availiable analyses'))
         self.anChoice.SetSelection(0)
-               
+
         self.anChoiceId = self.AddControl(self.anChoice)
-        self.parent.Bind(wx.EVT_COMBOBOX, self.parent.OnAnalysisChanged, self.anChoiceId)
-                
+        self.parent.Bind(
+            wx.EVT_COMBOBOX,
+            self.parent.OnAnalysisChanged,
+            self.anChoiceId)
+
         # workaround for Mac bug. May be fixed by 2.8.8, but not before then.
         self.anChoice.Hide()
         self.anChoice.Show()

Modified: grass/trunk/gui/wxpython/vnet/vnet_core.py
===================================================================
--- grass/trunk/gui/wxpython/vnet/vnet_core.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/vnet/vnet_core.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -21,24 +21,26 @@
 
 import os
 from grass.script.utils import try_remove
-from grass.script     import core as grass
+from grass.script import core as grass
 from grass.script.task import cmdlist_to_tuple
 
 import wx
 
-from core             import utils
-from core.gcmd        import RunCommand, GMessage
-from core.gconsole    import CmdThread, EVT_CMD_DONE, GConsole
+from core import utils
+from core.gcmd import RunCommand, GMessage
+from core.gconsole import CmdThread, EVT_CMD_DONE, GConsole
 from core.utils import _
 
 from gui_core.gselect import VectorDBInfo
 
-from vnet.vnet_data   import VNETData, VNETTmpVectMaps, VectMap, History
-from vnet.vnet_utils  import ParseMapStr, haveCtypes, GetNearestNodeCat
+from vnet.vnet_data import VNETData, VNETTmpVectMaps, VectMap, History
+from vnet.vnet_utils import ParseMapStr, haveCtypes, GetNearestNodeCat
 
 from grass.pydispatch.signal import Signal
- 
+
+
 class VNETManager:
+
     def __init__(self, guiparent, giface):
 
         self.data = {}
@@ -47,22 +49,29 @@
         self.giface = giface
         self.mapWin = giface.GetMapWindow()
 
-        self.goutput = GConsole(guiparent = guiparent) 
+        self.goutput = GConsole(guiparent=guiparent)
 
-        self.vnet_data = VNETData(guiparent = guiparent, mapWin = self.mapWin)
+        self.vnet_data = VNETData(guiparent=guiparent, mapWin=self.mapWin)
 
-        self.results = {"analysis" : None,
-                        "vect_map" : None} #TODO more results
+        self.results = {"analysis": None,
+                        "vect_map": None}  # TODO more results
 
-        # this class instance manages all temporary vector maps created during life of VNETDialog  
-        self.tmp_maps = VNETTmpVectMaps(parent = guiparent, mapWin = self.mapWin)
+        # this class instance manages all temporary vector maps created during
+        # life of VNETDialog
+        self.tmp_maps = VNETTmpVectMaps(parent=guiparent, mapWin=self.mapWin)
 
         # initialization of History class used for saving and reading data from file
         # it is used for browsing analysis results
-        self.history = VNETHistory(self.guiparent, self.vnet_data, self.tmp_maps)
-        self.analyses = VNETAnalyses(self.vnet_data, self.RunAnDone, self.goutput, self.tmp_maps)
+        self.history = VNETHistory(
+            self.guiparent, self.vnet_data, self.tmp_maps)
+        self.analyses = VNETAnalyses(
+            self.vnet_data,
+            self.RunAnDone,
+            self.goutput,
+            self.tmp_maps)
 
-        self.snap_nodes = SnappingNodes(self.giface, self.vnet_data, self.tmp_maps, self.mapWin)
+        self.snap_nodes = SnappingNodes(
+            self.giface, self.vnet_data, self.tmp_maps, self.mapWin)
 
         self.ttbCreated = Signal('VNETManager.ttbCreated')
         self.analysisDone = Signal('VNETManager.analysisDone')
@@ -72,8 +81,7 @@
         self.snapping = self.snap_nodes.snapping
         self.pointsChanged.connect(self.PointsChanged)
 
-
-    def  __del__(self):
+    def __del__(self):
         self.CleanUp()
 
     def CleanUp(self):
@@ -82,7 +90,7 @@
         update = self.tmp_maps.DeleteAllTmpMaps()
 
         self.vnet_data.CleanUp()
-        
+
         if update:
             self.giface.updateMap.emit(render=True, renderVector=True)
         else:
@@ -95,40 +103,43 @@
         return self.vnet_data.GetGlobalTurnsData()
 
     def RunAnalysis(self):
-        
+
         analysis, valid = self.vnet_data.GetParam("analysis")
 
         params, err_params, flags = self.vnet_data.GetParams()
         relevant_params = self.vnet_data.GetRelevantParams(analysis)
-        
+
         if not relevant_params:
             return -1
 
-        if not self.vnet_data.InputsErrorMsgs(_("Unable to perform analysis."), 
-                                              analysis, params, flags, err_params, relevant_params):
+        if not self.vnet_data.InputsErrorMsgs(
+                _("Unable to perform analysis."),
+                analysis, params, flags, err_params, relevant_params):
             return -2
 
         if self.results["vect_map"]:
             self.results["vect_map"].DeleteRenderLayer()
 
-        # history - delete data in buffer for hist step  
+        # history - delete data in buffer for hist step
         self.history.DeleteNewHistStepData()
 
         # create new map (included to history) for result of analysis
-        self.results["vect_map"] = self.history.NewTmpVectMapToHist('vnet_tmp_result')
+        self.results["vect_map"] = self.history.NewTmpVectMapToHist(
+            'vnet_tmp_result')
 
         if not self.results["vect_map"]:
-                return False         
+            return False
 
-        # for case there is some map with same name 
-        # (when analysis does not produce any map, this map would have been shown as result) 
-        RunCommand('g.remove', flags = 'f', type = 'vector',
-                    name = self.results["vect_map"].GetVectMapName())
+        # for case there is some map with same name
+        # (when analysis does not produce any map, this map would have been shown as result)
+        RunCommand('g.remove', flags='f', type='vector',
+                   name=self.results["vect_map"].GetVectMapName())
 
-        # save data from 
+        # save data from
         self.history._saveAnInputToHist(analysis, params, flags)
 
-        ret = self.analyses.RunAnalysis(self.results["vect_map"].GetVectMapName(), params, flags)
+        ret = self.analyses.RunAnalysis(
+            self.results["vect_map"].GetVectMapName(), params, flags)
         if not ret:
             return -3
         else:
@@ -137,10 +148,10 @@
     def RunAnDone(self, cmd, returncode, results):
 
         self.results["analysis"] = cmd[0]
-       
+
         self.results["vect_map"].SaveVectMapState()
 
-        cmd, cmd_colors =  self.vnet_data.GetLayerStyle()
+        cmd, cmd_colors = self.vnet_data.GetLayerStyle()
         self.results["vect_map"].AddRenderLayer(cmd, cmd_colors)
 
         self.history.SaveHistStep()
@@ -148,7 +159,7 @@
         self.analysisDone.emit()
 
     def ShowResult(self, show):
-        #TODO can be more results e. g. smallest cut
+        # TODO can be more results e. g. smallest cut
 
         if show:
             self._checkResultMapChanged(self.results["vect_map"])
@@ -159,19 +170,20 @@
 
         self.giface.updateMap.emit(render=True, renderVector=True)
 
-    def GetAnalysisProperties(self, analysis = None):
-        return self.vnet_data.GetAnalysisProperties(analysis = analysis)
+    def GetAnalysisProperties(self, analysis=None):
+        return self.vnet_data.GetAnalysisProperties(analysis=analysis)
 
     def GetResults(self):
         return self.results["vect_map"]
 
     def Undo(self):
         self._updateDataForHistStep(self.history.Undo())
-        #SetUpdateMap TODO
+        # SetUpdateMap TODO
         return self.history.GetHistStep()
+
     def Redo(self):
         self._updateDataForHistStep(self.history.Redo())
-        #SetUpdateMap
+        # SetUpdateMap
         return self.history.GetHistStep()
 
     def _updateDataForHistStep(self, data):
@@ -184,7 +196,7 @@
         self.vnet_data.SetParams(params, flags)
 
         self.results["vect_map"].DeleteRenderLayer()
-        self.results["vect_map"]  = self.tmp_maps.GetTmpVectMap(resultMapName)
+        self.results["vect_map"] = self.tmp_maps.GetTmpVectMap(resultMapName)
         self._checkResultMapChanged(self.results["vect_map"])
 
         cmd, cmd_colors = self.vnet_data.GetLayerStyle()
@@ -208,14 +220,16 @@
     def _checkResultMapChanged(self, resultVectMap):
         """Check if map was modified outside"""
         if resultVectMap.VectMapState() == 0:
-            dlg = wx.MessageDialog(parent = self,
-                                   message = _("Temporary map '%s' with result " + 
-                                               "was changed outside vector network analysis tool.\n" +
-                                               "Showed result may not correspond " +
-                                               "original analysis result.") %\
-                                               resultVectMap.GetVectMapName(),
-                                   caption = _("Result changed outside"),
-                                   style =  wx.ICON_INFORMATION| wx.CENTRE)
+            dlg = wx.MessageDialog(
+                parent=self,
+                message=_(
+                    "Temporary map '%s' with result " +
+                    "was changed outside vector network analysis tool.\n" +
+                    "Showed result may not correspond " +
+                    "original analysis result.") %
+                resultVectMap.GetVectMapName(),
+                caption=_("Result changed outside"),
+                style=wx.ICON_INFORMATION | wx.CENTRE)
             dlg.ShowModal()
             dlg.Destroy()
 
@@ -230,15 +244,15 @@
 
     def SettingsUpdated(self):
         self.vnet_data.GetPointsData().SetPointDrawSettings()
-        if not self.results["vect_map"]  or \
-           not self.tmp_maps.HasTmpVectMap(self.results["vect_map"].GetVectMapName()):
+        if not self.results["vect_map"] or not self.tmp_maps.HasTmpVectMap(
+                self.results["vect_map"].GetVectMapName()):
             self.giface.updateMap.emit(render=False, renderVector=False)
         elif self.results["vect_map"].GetRenderLayer():
             cmd, cmd_colors = self.vnet_data.GetLayerStyle()
             self.results["vect_map"].AddRenderLayer(cmd, cmd_colors)
-            
+
             self.giface.updateMap.emit(render=True, renderVector=True)
-            #TODO optimization
+            # TODO optimization
         else:
             self.giface.updateMap.emit(render=False, renderVector=False)
 
@@ -249,45 +263,45 @@
 
         outputMap = params["output"]
         mapName, mapSet = ParseMapStr(outputMap)
-        if mapSet !=  grass.gisenv()['MAPSET']:
-            GMessage(parent = self,
-                     message = _("Map can be created only in current mapset"))
+        if mapSet != grass.gisenv()['MAPSET']:
+            GMessage(parent=self,
+                     message=_("Map can be created only in current mapset"))
             return False
-        existsMap = grass.find_file(name = mapName, 
-                                    element = 'vector', 
-                                    mapset = grass.gisenv()['MAPSET'])
+        existsMap = grass.find_file(name=mapName,
+                                    element='vector',
+                                    mapset=grass.gisenv()['MAPSET'])
         if existsMap["name"]:
-            dlg = wx.MessageDialog(parent = self.guiparent,
-                                   message = _("Vector map %s already exists. " +
-                                                "Do you want to overwrite it?") % 
-                                                (existsMap["fullname"]),
-                                   caption = _("Overwrite vector map"),
-                                   style = wx.YES_NO | wx.NO_DEFAULT |
-                                               wx.ICON_QUESTION | wx.CENTRE) 
+            dlg = wx.MessageDialog(parent=self.guiparent,
+                                   message=_("Vector map %s already exists. " +
+                                             "Do you want to overwrite it?") %
+                                   (existsMap["fullname"]),
+                                   caption=_("Overwrite vector map"),
+                                   style=wx.YES_NO | wx.NO_DEFAULT |
+                                   wx.ICON_QUESTION | wx.CENTRE)
             ret = dlg.ShowModal()
             dlg.Destroy()
             if ret == wx.ID_NO:
                 return False
 
-            cmdTtb = [ 
-                        "v.net.turntable",
-                        "input=" + params["input"], 
-                        "output=" + params["output"],
-                        "arc_layer=" + params["arc_layer"],
-                        "turn_layer=" + params["turn_layer"],
-                        "turn_cat_layer=" + params["turn_cat_layer"],
-                        "--overwrite", 
-                       ]
+            cmdTtb = [
+                "v.net.turntable",
+                "input=" + params["input"],
+                "output=" + params["output"],
+                "arc_layer=" + params["arc_layer"],
+                "turn_layer=" + params["turn_layer"],
+                "turn_cat_layer=" + params["turn_cat_layer"],
+                "--overwrite",
+            ]
 
-            self.goutput.RunCmd(command = cmdTtb, onDone = self._createTtbDone)
+            self.goutput.RunCmd(command=cmdTtb, onDone=self._createTtbDone)
 
         return True
 
     def _createTtbDone(self, event):
 
         if event.returncode != 0:
-            GMessage(parent = self.guiparent,
-                     message = _("Creation of turntable failed."))
+            GMessage(parent=self.guiparent,
+                     message=_("Creation of turntable failed."))
             return
         else:
             params = {}
@@ -303,44 +317,44 @@
 
             self.vnet_data.SetParams(params, {})
 
-        self.ttbCreated.emit(returncode = event.returncode)
+        self.ttbCreated.emit(returncode=event.returncode)
 
     def SaveTmpLayer(self, layer_name):
         """Permanently saves temporary map of analysis result"""
         msg = _("Vector map with analysis result does not exist.")
 
         if not hasattr(self.results["vect_map"], "GetVectMapName"):
-            GMessage(parent = self.guiparent,
-                     message = msg)
+            GMessage(parent=self.guiparent,
+                     message=msg)
             return
 
         mapToAdd = self.results["vect_map"].GetVectMapName()
-        mapToAddEx = grass.find_file(name = mapToAdd, 
-                                        element = 'vector', 
-                                        mapset = grass.gisenv()['MAPSET'])
+        mapToAddEx = grass.find_file(name=mapToAdd,
+                                     element='vector',
+                                     mapset=grass.gisenv()['MAPSET'])
 
-        if not mapToAddEx["name"]: 
-            GMessage(parent = self.guiparent,
-                    message = msg)
+        if not mapToAddEx["name"]:
+            GMessage(parent=self.guiparent,
+                     message=msg)
             return
 
         addedMap = layer_name
         mapName, mapSet = ParseMapStr(addedMap)
-        if mapSet !=  grass.gisenv()['MAPSET']:
-            GMessage(parent = self.guiparent,
-                     message = _("Map can be saved only to currently set mapset"))
+        if mapSet != grass.gisenv()['MAPSET']:
+            GMessage(parent=self.guiparent, message=_(
+                "Map can be saved only to currently set mapset"))
             return
-        existsMap = grass.find_file(name = mapName, 
-                                    element = 'vector', 
-                                    mapset = grass.gisenv()['MAPSET'])
+        existsMap = grass.find_file(name=mapName,
+                                    element='vector',
+                                    mapset=grass.gisenv()['MAPSET'])
         if existsMap["name"]:
-            dlg = wx.MessageDialog(parent = self.guiparent,
-                                    message = _("Vector map %s already exists. " +
-                                            "Do you want to overwrite it?") % 
-                                            (existsMap["fullname"]),
-                                   caption = _("Overwrite vector map"),
-                                   style = wx.YES_NO | wx.NO_DEFAULT |
-                                           wx.ICON_QUESTION | wx.CENTRE)            
+            dlg = wx.MessageDialog(parent=self.guiparent,
+                                   message=_("Vector map %s already exists. " +
+                                             "Do you want to overwrite it?") %
+                                   (existsMap["fullname"]),
+                                   caption=_("Overwrite vector map"),
+                                   style=wx.YES_NO | wx.NO_DEFAULT |
+                                   wx.ICON_QUESTION | wx.CENTRE)
             ret = dlg.ShowModal()
             if ret == wx.ID_NO:
                 dlg.Destroy()
@@ -348,8 +362,8 @@
             dlg.Destroy()
 
         RunCommand("g.copy",
-                    overwrite = True,
-                    vector = [self.results["vect_map"].GetVectMapName(), mapName])
+                   overwrite=True,
+                   vector=[self.results["vect_map"].GetVectMapName(), mapName])
 
         if len(self.giface.GetLayerList().GetLayersByName(mapName)) == 0:
             # TODO: get rid of insert
@@ -365,11 +379,13 @@
                 layerStyleVnetColors = cmdlist_to_tuple(cmd_colors)
 
                 RunCommand(layerStyleVnetColors[0],
-                        **layerStyleVnetColors[1])
+                           **layerStyleVnetColors[1])
         else:
             self.giface.updateMap.emit(render=True, renderVector=True)
 
+
 class VNETAnalyses:
+
     def __init__(self, data, onAnDone, goutput, tmp_maps):
         self.data = data
 
@@ -406,14 +422,16 @@
 
         cmdPts = []
         for cat in cats:
-            if  len(catPts[cat[0]]) < 1:#TODO
-                GMessage(message=_("Please choose '%s' and '%s' point.") % (cats[0][1], cats[1][1]))
+            if len(catPts[cat[0]]) < 1:  # TODO
+                GMessage(
+                    message=_("Please choose '%s' and '%s' point.") %
+                    (cats[0][1], cats[1][1]))
                 return False
             cmdPts.append(catPts[cat[0]][0])
 
         resId = 1
-        inpPoints = str(resId) + " " + str(cmdPts[0][0]) + " " + str(cmdPts[0][1]) + \
-                                 " " + str(cmdPts[1][0]) + " " + str(cmdPts[1][1])
+        inpPoints = str(resId) + " " + str(cmdPts[0][0]) + " " + str(
+            cmdPts[0][1]) + " " + str(cmdPts[1][0]) + " " + str(cmdPts[1][1])
 
         self.coordsTmpFile = grass.tempfile()
         coordsTmpFileOpened = open(self.coordsTmpFile, 'w')
@@ -423,28 +441,27 @@
         if flags["t"]:
             cmdParams.append("-t")
 
-            self.tmpTurnAn = AddTmpMapAnalysisMsg("vnet_tunr_an_tmp", self.tmp_maps)
+            self.tmpTurnAn = AddTmpMapAnalysisMsg(
+                "vnet_tunr_an_tmp", self.tmp_maps)
             if not self.tmpTurnAn:
                 return False
 
             mapName, mapSet = ParseMapStr(self.tmpTurnAn.GetVectMapName())
-            cmdCopy = [ 
-                        "g.copy",
-                        "vector=%s,%s" % (params["input"], mapName), 
-                        "--overwrite",                             
-                       ]
+            cmdCopy = [
+                "g.copy",
+                "vector=%s,%s" % (params["input"], mapName),
+                "--overwrite",
+            ]
             cmdParams.append("input=" + self.tmpTurnAn.GetVectMapName())
 
-            ret, msg, err = RunCommand('g.copy',
-                                        getErrorMsg = True,
-                                        vector = "%s,%s" % (params['input'], mapName),
-                                        read = True,
-                                        overwrite = True)
+            ret, msg, err = RunCommand(
+                'g.copy', getErrorMsg=True, vector="%s,%s" %
+                (params['input'], mapName), read=True, overwrite=True)
 
-            self._updateTtbByGlobalCosts(self.tmpTurnAn.GetVectMapName(), 
+            self._updateTtbByGlobalCosts(self.tmpTurnAn.GetVectMapName(),
                                          int(params["turn_layer"]))
-            
-            #self._prepareCmd(cmdCopy)
+
+            # self._prepareCmd(cmdCopy)
             #self.goutput.RunCmd(command = cmdCopy)
         else:
             cmdParams.append("input=" + params["input"])
@@ -454,16 +471,20 @@
         cmdParams.append("dmax=" + str(params["max_dist"]))
 
         cmdParams.append("--overwrite")
-        self._prepareCmd(cmd = cmdParams)
-        
+        self._prepareCmd(cmd=cmdParams)
+
         if flags["t"]:
-            self.goutput.RunCmd(command = cmdParams, onDone = self._vnetPathRunTurnsAnDone)
+            self.goutput.RunCmd(
+                command=cmdParams,
+                onDone=self._vnetPathRunTurnsAnDone)
         else:
-            self.goutput.RunCmd(command = cmdParams, onDone = self._vnetPathRunAnDone)
+            self.goutput.RunCmd(
+                command=cmdParams,
+                onDone=self._vnetPathRunAnDone)
 
     def _vnetPathRunTurnsAnDone(self, event):
-        #TODO
-        #self.tmp_maps.DeleteTmpMap(self.tmpTurnAn)
+        # TODO
+        # self.tmp_maps.DeleteTmpMap(self.tmpTurnAn)
         self._vnetPathRunAnDone(event)
 
     def _vnetPathRunAnDone(self, event):
@@ -476,7 +497,7 @@
         for c in event.cmd:
             if "output=" in c:
                 output = c.split("=")[1]
-                break  
+                break
 
         self.onAnDone(event.cmd, event.returncode, output)
 
@@ -491,14 +512,17 @@
         for cat_name, pts_coor in catPts.iteritems():
 
             for coor in pts_coor:
-                cat_num = str(GetNearestNodeCat(e = coor[0], 
-                                                n = coor[1], 
-                                                field = int(params["turn_cat_layer"],
-                                                tresh = params["max_dist"]), 
-                                                vectMap = params["input"]))
+                cat_num = str(
+                    GetNearestNodeCat(
+                        e=coor[0],
+                        n=coor[1],
+                        field=int(
+                            params["turn_cat_layer"],
+                            tresh=params["max_dist"]),
+                        vectMap=params["input"]))
                 if cat_num < 0:
                     continue
-                if cats.has_key(cat_name):
+                if cat_name in cats:
                     cats[cat_name].append(cat_num)
                 else:
                     cats[cat_name] = [cat_num]
@@ -506,53 +530,52 @@
         for cat_name, cat_nums in cats.iteritems():
             cmdParams.append(cat_name + "=" + ",".join(cat_nums))
 
-        self.tmpTurnAn = AddTmpMapAnalysisMsg("vnet_tunr_an_tmp", self.tmp_maps)
+        self.tmpTurnAn = AddTmpMapAnalysisMsg(
+            "vnet_tunr_an_tmp", self.tmp_maps)
         if not self.tmpTurnAn:
             return False
 
         # create and run commands which goes to analysis thread
 
         mapName, mapSet = ParseMapStr(self.tmpTurnAn.GetVectMapName())
-        cmdCopy = [ 
-                    "g.copy",
-                    "vector=%s,%s" % (params['input'], mapName), 
-                    "--overwrite",                             
-                   ]
+        cmdCopy = [
+            "g.copy",
+            "vector=%s,%s" % (params['input'], mapName),
+            "--overwrite",
+        ]
         cmdParams.append("input=" + self.tmpTurnAn.GetVectMapName())
 
         ret, msg, err = RunCommand('g.copy',
-                                    getErrorMsg = True,
-                                    vector = "%s,%s" % (params['input'], mapName),
-                                    read = True,
-                                    overwrite = True)
+                                   getErrorMsg=True,
+                                   vector="%s,%s" % (params['input'], mapName),
+                                   read=True,
+                                   overwrite=True)
 
-        self._updateTtbByGlobalCosts(self.tmpTurnAn.GetVectMapName(), 
+        self._updateTtbByGlobalCosts(self.tmpTurnAn.GetVectMapName(),
                                      int(params["turn_layer"]))
 
-
         self._setCmdForSpecificAn(cmdParams)
 
         cmdParams.append("-t")
 
         self._prepareCmd(cmdParams)
-        self.goutput.RunCmd(command = cmdParams, onDone = self._runTurnsAnDone)
+        self.goutput.RunCmd(command=cmdParams, onDone=self._runTurnsAnDone)
 
     def _updateTtbByGlobalCosts(self, vectMapName, tlayer):
-        #TODO get layer number do not use it directly
+        # TODO get layer number do not use it directly
         intervals = self.turnsData["global"].GetData()
 
-        cmdUpdGlob = [ 
-                      "v.db.update",
-                      "map=", self.inputData["input"].GetValue(), 
-                      "layer=%d" % tlayer,
-                      "column=cost",
-                    ]
+        cmdUpdGlob = [
+            "v.db.update",
+            "map=", self.inputData["input"].GetValue(),
+            "layer=%d" % tlayer,
+            "column=cost",
+        ]
 
         dbInfo = VectorDBInfo(vectMapName)
         table = dbInfo.GetTable(tlayer)
-        driver,  database = dbInfo.GetDbSettings(tlayer)
+        driver, database = dbInfo.GetDbSettings(tlayer)
 
-
         sqlFile = grass.tempfile()
         sqlFile_f = open(sqlFile, 'w')
 
@@ -562,37 +585,36 @@
             cost = ival[2]
 
             if to_angle < from_angle:
-                to_angle = math.pi * 2  + to_angle
-            #if angle < from_angle:
+                to_angle = math.pi * 2 + to_angle
+            # if angle < from_angle:
             #    angle = math.pi * 2  + angle
 
             where = " WHERE (((angle < {0}) AND ({2} + angle >= {0} AND {2} + angle < {1})) OR \
                             ((angle >= {0}) AND (angle >= {0} AND angle < {1}))) AND cost==0.0 ".format(str(from_angle), str(to_angle), str(math.pi * 2))
 
-            stm = ("UPDATE %s SET cost=%f " % (table, cost)) + where + ";\n";
+            stm = ("UPDATE %s SET cost=%f " % (table, cost)) + where + ";\n"
             sqlFile_f.write(stm)
 
         sqlFile_f.close()
 
-            #TODO imporve parser and run in thread
+        # TODO imporve parser and run in thread
 
-   
         ret, msg, err = RunCommand('db.execute',
-                               getErrorMsg = True,
-                               input = sqlFile,
-                               read = True,
-                               driver = driver,
-                               database = database)
+                                   getErrorMsg=True,
+                                   input=sqlFile,
+                                   read=True,
+                                   driver=driver,
+                                   database=database)
 
         try_remove(sqlFile)
 
     def _runTurnsAnDone(self, event):
         """Called when analysis is done"""
-        #self.tmp_maps.DeleteTmpMap(self.tmpTurnAn) #TODO remove earlier (OnDone lambda?)
- 
+        # self.tmp_maps.DeleteTmpMap(self.tmpTurnAn) #TODO remove earlier
+        # (OnDone lambda?)
+
         self._onDone(event)
 
-
     def _runAn(self, analysis, output, params, flags, catPts):
         """Called for all v.net.* analysis (except v.net.path)"""
 
@@ -605,27 +627,27 @@
 
         if len(cats) > 1:
             for cat in cats:
-                if  len(catPts[cat[0]]) < 1:
-                    GMessage(parent = self, 
-                            message = _("Please choose '%s' and '%s' point.") \
-                                        % (cats[0][1], cats[1][1]))
+                if len(catPts[cat[0]]) < 1:
+                    GMessage(parent=self,
+                             message=_("Please choose '%s' and '%s' point.")
+                             % (cats[0][1], cats[1][1]))
                     return False
         else:
             for cat in cats:
-                if  len(catPts[cat[0]]) < 2:
-                    GMessage(parent = self, 
-                             message = _("Please choose at least two points."))
-                    return False      
+                if len(catPts[cat[0]]) < 2:
+                    GMessage(parent=self,
+                             message=_("Please choose at least two points."))
+                    return False
 
         # TODO add also to thread for analysis?
         vcatResult = RunCommand("v.category",
-                           input = params['input'],
-                           option = "report",
-                           flags = "g",
-                           read = True)     
+                                input=params['input'],
+                                option="report",
+                                flags="g",
+                                read=True)
 
         vcatResult = vcatResult.splitlines()
-        for cat in vcatResult:#TODO
+        for cat in vcatResult:  # TODO
             cat = cat.split()
             if "all" in cat:
                 maxCat = int(cat[4])
@@ -633,11 +655,12 @@
 
         layerNum = params["node_layer"]
 
-        pt_ascii, catsNums = self._getAsciiPts (catPts = catPts, 
-                                                maxCat = maxCat, 
-                                                layerNum = layerNum)
+        pt_ascii, catsNums = self._getAsciiPts(catPts=catPts,
+                                               maxCat=maxCat,
+                                               layerNum=layerNum)
 
-        self.tmpPtsAsciiFile = grass.tempfile()#TODO better tmp files cleanup (make class for managing tmp files)
+        # TODO better tmp files cleanup (make class for managing tmp files)
+        self.tmpPtsAsciiFile = grass.tempfile()
         tmpPtsAsciiFileOpened = open(self.tmpPtsAsciiFile, 'w')
         tmpPtsAsciiFileOpened.write(pt_ascii)
         tmpPtsAsciiFileOpened.close()
@@ -646,55 +669,58 @@
         if not self.tmpInPts:
             return False
 
-        self.tmpInPtsConnected = AddTmpMapAnalysisMsg("vnet_tmp_in_pts_connected", self.tmp_maps)
+        self.tmpInPtsConnected = AddTmpMapAnalysisMsg(
+            "vnet_tmp_in_pts_connected", self.tmp_maps)
         if not self.tmpInPtsConnected:
             return False
 
         cmdParams.append("input=" + self.tmpInPtsConnected.GetVectMapName())
-        cmdParams.append("--overwrite")  
-        
+        cmdParams.append("--overwrite")
+
         self._setCmdForSpecificAn(cmdParams)
-        
+
         for catName, catNum in catsNums.iteritems():
             if catNum[0] == catNum[1]:
                 cmdParams.append(catName + "=" + str(catNum[0]))
             else:
-                cmdParams.append(catName + "=" + str(catNum[0]) + "-" + str(catNum[1]))
+                cmdParams.append(
+                    catName + "=" + str(catNum[0]) + "-" + str(catNum[1]))
 
         # create and run commands which goes to analysis thread
-        cmdVEdit = [ 
-                    "v.edit",
-                    "map=" + self.tmpInPts.GetVectMapName(), 
-                    "input=" + self.tmpPtsAsciiFile,
-                    "tool=create",
-                    "--overwrite", 
-                    "-n"                              
-                   ]
+        cmdVEdit = [
+            "v.edit",
+            "map=" + self.tmpInPts.GetVectMapName(),
+            "input=" + self.tmpPtsAsciiFile,
+            "tool=create",
+            "--overwrite",
+            "-n"
+        ]
 
         self._prepareCmd(cmdVEdit)
-        self.goutput.RunCmd(command = cmdVEdit)
+        self.goutput.RunCmd(command=cmdVEdit)
 
         cmdVNet = [
-                    "v.net",
-                    "points=" + self.tmpInPts.GetVectMapName(), 
-                    "input=" + params['input'],
-                    "output=" + self.tmpInPtsConnected.GetVectMapName(),
-                    "arc_layer=" +  params["arc_layer"],
-                    "node_layer=" +  params["node_layer"], 
-                    "operation=connect",
-                    "thresh=" + str(params["max_dist"]),             
-                    "--overwrite"                         
-                  ] #TODO snapping to nodes optimization
+            "v.net",
+            "points=" + self.tmpInPts.GetVectMapName(),
+            "input=" + params['input'],
+            "output=" + self.tmpInPtsConnected.GetVectMapName(),
+            "arc_layer=" + params["arc_layer"],
+            "node_layer=" + params["node_layer"],
+            "operation=connect",
+            "thresh=" + str(params["max_dist"]),
+            "--overwrite"
+        ]  # TODO snapping to nodes optimization
 
         self._prepareCmd(cmdVNet)
-        self.goutput.RunCmd(command = cmdVNet)
+        self.goutput.RunCmd(command=cmdVNet)
 
         self._prepareCmd(cmdParams)
-        self.goutput.RunCmd(command = cmdParams, onDone = self._runAnDone)
+        self.goutput.RunCmd(command=cmdParams, onDone=self._runAnDone)
 
     def _runAnDone(self, event):
         """Called when analysis is done"""
-        self.tmp_maps.DeleteTmpMap(self.tmpInPts) #TODO remove earlier (OnDone lambda?)
+        self.tmp_maps.DeleteTmpMap(
+            self.tmpInPts)  # TODO remove earlier (OnDone lambda?)
         self.tmp_maps.DeleteTmpMap(self.tmpInPtsConnected)
         try_remove(self.tmpPtsAsciiFile)
 
@@ -704,13 +730,14 @@
         self._onDone(event)
 
     def _setInputParams(self, analysis, params, flags):
-        """Return list of chosen values (vector map, layers). 
+        """Return list of chosen values (vector map, layers).
 
-        The list items are in form to be used in command for analysis e.g. 'arc_layer=1'.    
+        The list items are in form to be used in command for analysis e.g. 'arc_layer=1'.
         """
 
         inParams = []
-        for col, v in self.data.GetAnalysisProperties()["cmdParams"]["cols"].iteritems():
+        for col, v in self.data.GetAnalysisProperties()["cmdParams"][
+                "cols"].iteritems():
 
             if "inputField" in v:
                 colInptF = v["inputField"]
@@ -719,7 +746,8 @@
 
             inParams.append(col + '=' + params[colInptF])
 
-        for layer in ['arc_layer', 'node_layer', 'turn_layer', 'turn_cat_layer']:
+        for layer in ['arc_layer', 'node_layer',
+                      'turn_layer', 'turn_cat_layer']:
             if not flags["t"] and layer in ['turn_layer', 'turn_cat_layer']:
                 continue
             # TODO
@@ -739,19 +767,20 @@
         ptByCats = {}
         for cat in anProps["cmdParams"]["cats"]:
             ptByCats[cat[0]] = []
- 
+
         for i in range(self.pts_data.GetPointsCount()):
             pt_data = self.pts_data.GetPointData(i)
             if pt_data["use"]:
                 for i_cat, cat in enumerate(cats):
-                    #i_cat + 1 - we ave to increment it because pt_data["type"] includes "" in first place
-                    if (i_cat + 1) == pt_data["type"] or len(ptByCats) == 1: 
+                    # i_cat + 1 - we ave to increment it because
+                    # pt_data["type"] includes "" in first place
+                    if (i_cat + 1) == pt_data["type"] or len(ptByCats) == 1:
                         coords = (pt_data['e'], pt_data['n'])
                         ptByCats[cat[0]].append(coords)
 
         return ptByCats
 
-    def _getAsciiPts (self, catPts, maxCat, layerNum):
+    def _getAsciiPts(self, catPts, maxCat, layerNum):
         """Return points separated by categories in GRASS ASCII vector representation"""
         catsNums = {}
         pt_ascii = ""
@@ -763,7 +792,7 @@
             for pt in pts:
                 catNum += 1
                 pt_ascii += "P 1 1\n"
-                pt_ascii += str(pt[0]) + " " + str(pt[1]) +  "\n"
+                pt_ascii += str(pt[0]) + " " + str(pt[1]) + "\n"
                 pt_ascii += str(layerNum) + " " + str(catNum) + "\n"
 
             catsNums[catName].append(catNum)
@@ -787,27 +816,32 @@
             cmdParams.append("from_layer=1")
             cmdParams.append("to_layer=1")
         elif cmdParams[0] == "v.net.flow":
-            #self.vnetFlowTmpCut = self.NewTmpVectMapToHist('vnet_tmp_flow_cut') TODO
-            self.vnetFlowTmpCut = AddTmpMapAnalysisMsg('vnet_tmp_flow_cut', self.tmp_maps)
+            # self.vnetFlowTmpCut =
+            # self.NewTmpVectMapToHist('vnet_tmp_flow_cut') TODO
+            self.vnetFlowTmpCut = AddTmpMapAnalysisMsg(
+                'vnet_tmp_flow_cut', self.tmp_maps)
             if not self.vnetFlowTmpCut:
-                return          
-            cmdParams.append("cut=" +  self.vnetFlowTmpCut.GetVectMapName())         
+                return
+            cmdParams.append("cut=" + self.vnetFlowTmpCut.GetVectMapName())
         elif cmdParams[0] == "v.net.iso":
-            costs, valid = self.data.GetParam("iso_lines") #TODO valid
+            costs, valid = self.data.GetParam("iso_lines")  # TODO valid
             cmdParams.append("costs=" + costs)
 
+
 class VNETHistory():
+
     def __init__(self, guiparent, data, tmp_maps):
         self.history = History()
         self.guiparent = guiparent
 
         self.tmp_maps = tmp_maps
 
-        # variable, which appends  unique number to every name of map, which is saved into history
+        # variable, which appends  unique number to every name of map, which is
+        # saved into history
         self.histTmpVectMapNum = 0
-        
+
         self.data = data
-    
+
     def Undo(self):
         """Step back in history"""
         histStepData = self.history.GetPrev()
@@ -836,7 +870,7 @@
         if not removedHistData:
             return
 
-        # delete temporary maps in history steps which were deleted 
+        # delete temporary maps in history steps which were deleted
         for removedStep in removedHistData.itervalues():
             mapsNames = removedStep["tmp_data"]["maps"]
             for vectMapName in mapsNames:
@@ -844,24 +878,24 @@
                 self.tmp_maps.DeleteTmpMap(tmpMap)
 
     def DeleteNewHistStepData(self):
-        # history - delete data in buffer for hist step  
+        # history - delete data in buffer for hist step
         self.history.DeleteNewHistStepData()
         # empty list for maps to be saved to history
-        self.tmpVectMapsToHist= []
+        self.tmpVectMapsToHist = []
 
     def _updateHistStepData(self, histStepData):
         """Updates dialog according to chosen history step"""
         # set analysis module
         analysis = histStepData["vnet_modules"]["curr_module"]
-        self.data.SetParams({"analysis" : analysis}, {})
+        self.data.SetParams({"analysis": analysis}, {})
 
         pts = []
         # add points to list
         for iPt in range(len(histStepData["points"])):
             ptDataHist = histStepData["points"]["pt" + str(iPt)]
-            
+
             e, n = ptDataHist["coords"]
-            pt_data = {"e" : e, "n" : n}
+            pt_data = {"e": e, "n": n}
 
             pt_data['type'] = int(ptDataHist["catIdx"])
 
@@ -873,7 +907,7 @@
 
         self.data.GetPointsData().SetPoints(pts)
 
-        # update analysis result maps 
+        # update analysis result maps
         mapsNames = histStepData["tmp_data"]["maps"]
         for m in mapsNames:
             if "vnet_tmp_result" in m:
@@ -884,28 +918,30 @@
         params = {}
         histInputData = histStepData["an_params"]
         for inpName, inp in histInputData.iteritems():
-            params[inpName] = str(inp) 
+            params[inpName] = str(inp)
             if inpName == "input":
                 inpMap = inp
 
         prevInpModTime = str(histStepData["other"]["input_modified"])
         currInpModTime = VectMap(None, inpMap).GetLastModified()
 
-        if currInpModTime.strip()!= prevInpModTime.strip():
-            dlg = wx.MessageDialog(parent = self.guiparent,
-                                   message = _("Input map '%s' for analysis was changed outside " + 
-                                               "vector network analysis tool.\n" +
-                                               "Topology column may not " +
-                                               "correspond to changed situation.") %\
-                                                inpMap,
-                                   caption = _("Input changed outside"),
-                                   style =  wx.ICON_INFORMATION| wx.CENTRE)
+        if currInpModTime.strip() != prevInpModTime.strip():
+            dlg = wx.MessageDialog(
+                parent=self.guiparent,
+                message=_(
+                    "Input map '%s' for analysis was changed outside " +
+                    "vector network analysis tool.\n" +
+                    "Topology column may not " +
+                    "correspond to changed situation.") %
+                inpMap,
+                caption=_("Input changed outside"),
+                style=wx.ICON_INFORMATION | wx.CENTRE)
             dlg.ShowModal()
             dlg.Destroy()
-    
-        #TODO 
+
+        # TODO
         flags = {}
-        return analysis, resultMapName, params, flags 
+        return analysis, resultMapName, params, flags
 
     def _saveAnInputToHist(self, analysis, params, flags):
         """Save all data needed for analysis into history buffer"""
@@ -917,43 +953,41 @@
             ptName = "pt" + str(pt_id)
 
             coords = [data["e"], data["n"]]
-            self.history.Add(key = "points", 
-                             subkey = [ptName, "coords"], 
-                             value = coords)
+            self.history.Add(key="points",
+                             subkey=[ptName, "coords"],
+                             value=coords)
 
-            self.history.Add(key = "points", 
-                             subkey = [ptName, "catIdx"], 
-                             value = data['type'])
+            self.history.Add(key="points",
+                             subkey=[ptName, "catIdx"],
+                             value=data['type'])
 
-            self.history.Add(key = "points", 
-                             subkey = [ptName, "topology"], 
-                             value = data['topology'])
+            self.history.Add(key="points",
+                             subkey=[ptName, "topology"],
+                             value=data['topology'])
 
+            self.history.Add(key="points",
+                             subkey=[ptName, "checked"],
+                             value=data["use"])
 
-            self.history.Add(key = "points", 
-                             subkey = [ptName, "checked"], 
-                             value = data["use"])
-
             for param, value in params.iteritems():
 
                 if param == "input":
                     inpMap = VectMap(self, value)
-                    self.history.Add(key = "other", 
-                                     subkey = "input_modified", 
-                                     value = inpMap.GetLastModified())  
-                    param_val =  value
+                    self.history.Add(key="other",
+                                     subkey="input_modified",
+                                     value=inpMap.GetLastModified())
+                    param_val = value
                 else:
-                    param_val =  value
-                 
-                self.history.Add(key = "an_params", 
-                                 subkey = param, 
-                                 value = param_val)
-            
-        self.history.Add(key = "vnet_modules", 
-                         subkey = "curr_module", 
-                         value =  analysis)
+                    param_val = value
 
+                self.history.Add(key="an_params",
+                                 subkey=param,
+                                 value=param_val)
 
+        self.history.Add(key="vnet_modules",
+                         subkey="curr_module",
+                         value=analysis)
+
     def NewTmpVectMapToHist(self, prefMapName):
         """Add new vector map, which will be saved into history step"""
 
@@ -963,33 +997,35 @@
         tmpMap = AddTmpMapAnalysisMsg(mapName, self.tmp_maps)
         if not tmpMap:
             return tmpMap
-           
+
         self.tmpVectMapsToHist.append(tmpMap.GetVectMapName())
-        self.history.Add(key = "tmp_data", 
-                         subkey = "maps",
-                         value = self.tmpVectMapsToHist)
+        self.history.Add(key="tmp_data",
+                         subkey="maps",
+                         value=self.tmpVectMapsToHist)
 
         return tmpMap
 
-def AddTmpMapAnalysisMsg(mapName, tmp_maps): #TODO 
-        """Wraped AddTmpVectMap"""
-        msg = _("Temporary map %s  already exists.\n"  + 
-                "Do you want to continue in analysis and overwrite it?") \
-                 % (mapName +'@' + grass.gisenv()['MAPSET'])
-        tmpMap = tmp_maps.AddTmpVectMap(mapName, msg)
-        return tmpMap
 
+def AddTmpMapAnalysisMsg(mapName, tmp_maps):  # TODO
+    """Wraped AddTmpVectMap"""
+    msg = _("Temporary map %s  already exists.\n" +
+            "Do you want to continue in analysis and overwrite it?") \
+        % (mapName + '@' + grass.gisenv()['MAPSET'])
+    tmpMap = tmp_maps.AddTmpVectMap(mapName, msg)
+    return tmpMap
 
+
 class SnappingNodes(wx.EvtHandler):
+
     def __init__(self, giface, data, tmp_maps, mapWin):
 
-        self.giface = giface        
+        self.giface = giface
         self.data = data
         self.tmp_maps = tmp_maps
         self.mapWin = mapWin
 
         wx.EvtHandler.__init__(self)
-        self.snapping= Signal('VNETManager.snapping')
+        self.snapping = Signal('VNETManager.snapping')
 
         # Stores all data related to snapping
         self.snapData = {}
@@ -998,83 +1034,84 @@
         """Start/stop snapping mode"""
 
         if not haveCtypes:
-            GMessage(parent = self,
-                     message = _("Unable to use ctypes. \n") + \
-                               _("Snapping mode can not be activated."))
+            GMessage(parent=self,
+                     message=_("Unable to use ctypes. \n") +
+                     _("Snapping mode can not be activated."))
             return -1
 
         if not activate:
 
             if self.tmp_maps.HasTmpVectMap("vnet_snap_points"):
-                self.snapPts.DeleteRenderLayer() 
-                
+                self.snapPts.DeleteRenderLayer()
+
                 self.giface.updateMap.emit(render=False, renderVector=False)
 
-            if self.snapData.has_key('cmdThread'):
+            if 'cmdThread' in self.snapData:
                 self.snapData['cmdThread'].abort()
 
             self.data.SetSnapping(False)
-            
-            self.snapping.emit(evt = "deactivated")
 
-            return  -1
+            self.snapping.emit(evt="deactivated")
 
+            return -1
+
         self.data.SetSnapping(activate)
 
         params, inv_params, flags = self.data.GetParams()
-        if not self.data.InputsErrorMsgs(msg = _("Snapping mode can not be activated."),
-                                     analysis = None,
-                                     params = params,
-                                     inv_params = inv_params,
-                                     flags = flags,
-                                     relevant_params = ["input", "node_layer"]):
+        if not self.data.InputsErrorMsgs(
+                msg=_("Snapping mode can not be activated."),
+                analysis=None, params=params, inv_params=inv_params, flags=flags,
+                relevant_params=["input", "node_layer"]):
             return -1
 
         if not self.tmp_maps.HasTmpVectMap("vnet_snap_points"):
-            endStr = _("Do you really want to activate snapping and overwrite it?")
-            self.snapPts = self.tmp_maps.AddTmpVectMap("vnet_snap_points", endStr)
+            endStr = _(
+                "Do you really want to activate snapping and overwrite it?")
+            self.snapPts = self.tmp_maps.AddTmpVectMap(
+                "vnet_snap_points", endStr)
 
             if not self.snapPts:
-                return -1 
+                return -1
 
         elif self.snapPts.VectMapState() == 0:
-                dlg = wx.MessageDialog(message = _("Temporary map '%s' was changed outside " +
-                                                    "vector analysis tool.\n" 
-                                                    "Do you really want to activate " + 
-                                                    "snapping and overwrite it? ") % \
-                                                    self.snapPts.GetVectMapName(),
-                                        caption = _("Overwrite map"),
-                                        style = wx.YES_NO | wx.NO_DEFAULT |
-                                                wx.ICON_QUESTION | wx.CENTRE)
+            dlg = wx.MessageDialog(
+                message=_(
+                    "Temporary map '%s' was changed outside " +
+                    "vector analysis tool.\n"
+                    "Do you really want to activate " +
+                    "snapping and overwrite it? ") %
+                self.snapPts.GetVectMapName(),
+                caption=_("Overwrite map"),
+                style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
 
-                ret = dlg.ShowModal()
-                dlg.Destroy()
-                
-                if ret == wx.ID_NO:
-                    self.tmp_maps.DeleteTmpMap(self.snapPts)
-                    return -1
+            ret = dlg.ShowModal()
+            dlg.Destroy()
 
+            if ret == wx.ID_NO:
+                self.tmp_maps.DeleteTmpMap(self.snapPts)
+                return -1
+
         self.data.SetSnapping(True)
 
         inpFullName = params["input"]
         inpName, mapSet = inpFullName.split("@")
         computeNodes = True
 
-        if not self.snapData.has_key("inputMap"):
+        if "inputMap" not in self.snapData:
             pass
         elif inpFullName != self.snapData["inputMap"].GetVectMapName():
             self.snapData["inputMap"] = VectMap(None, inpFullName)
         elif self.snapData["inputMap"].VectMapState() == 1:
-                computeNodes = False
-    
+            computeNodes = False
+
         # new map needed
         if computeNodes:
-            if not self.snapData.has_key('cmdThread'):
+            if 'cmdThread' not in self.snapData:
                 self.snapData['cmdThread'] = CmdThread(self)
             else:
                 self.snapData['cmdThread'].abort()
 
-            cmd = ["v.to.points", "input=" + params['input'], 
+            cmd = ["v.to.points", "input=" + params['input'],
                                   "output=" + self.snapPts.GetVectMapName(),
                                   "use=node", "--overwrite"]
             # process GRASS command with argument
@@ -1084,16 +1121,16 @@
             self.Bind(EVT_CMD_DONE, self._onNodesDone)
             self.snapData['cmdThread'].RunCmd(cmd)
 
-            self.snapping.emit(evt = "computing_points")
+            self.snapping.emit(evt="computing_points")
 
             return 0
         # map is already created and up to date for input data
         else:
             self.snapPts.AddRenderLayer()
-            
+
             self.giface.updateMap.emit(render=True, renderVector=True)
 
-            self.snapping.emit(evt = "computing_points_done")
+            self.snapping.emit(evt="computing_points_done")
 
             return 1
 
@@ -1101,8 +1138,8 @@
         """Update map window, when map with nodes to snap is created"""
         if not event.aborted:
             self.snapPts.SaveVectMapState()
-            self.snapPts.AddRenderLayer() 
+            self.snapPts.AddRenderLayer()
 
             self.giface.updateMap.emit(render=True, renderVector=True)
 
-            self.snapping.emit(evt = "computing_points_done")
+            self.snapping.emit(evt="computing_points_done")

Modified: grass/trunk/gui/wxpython/vnet/vnet_data.py
===================================================================
--- grass/trunk/gui/wxpython/vnet/vnet_data.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/vnet/vnet_data.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -27,25 +27,27 @@
 from copy import deepcopy
 
 from grass.script.utils import try_remove
-from grass.script     import core as grass
+from grass.script import core as grass
 from grass.script.task import cmdlist_to_tuple
 
 import wx
 
 
-from core             import utils
-from core.gcmd        import RunCommand, GMessage
-from core.settings    import UserSettings
+from core import utils
+from core.gcmd import RunCommand, GMessage
+from core.settings import UserSettings
 from core.utils import _
 
-from vnet.vnet_utils  import ParseMapStr, SnapToNode
+from vnet.vnet_utils import ParseMapStr, SnapToNode
 
-from gui_core.gselect        import VectorDBInfo
+from gui_core.gselect import VectorDBInfo
 from grass.pydispatch.signal import Signal
 
-from vnet.vnet_utils  import DegreesToRadians, RadiansToDegrees
+from vnet.vnet_utils import DegreesToRadians, RadiansToDegrees
 
+
 class VNETData:
+
     def __init__(self, guiparent, mapWin):
 
         # setting initialization
@@ -75,14 +77,14 @@
     def GetGlobalTurnsData(self):
         return self.global_turns
 
-    def GetRelevantParams(self, analysis = None):
+    def GetRelevantParams(self, analysis=None):
         if analysis:
             return self.an_props.GetRelevantParams(analysis)
         else:
             analysis, valid = self.an_params.GetParam("analysis")
             return self.an_props.GetRelevantParams(analysis)
 
-    def GetAnalysisProperties(self, analysis = None):
+    def GetAnalysisProperties(self, analysis=None):
         if analysis:
             return self.an_props[analysis]
         else:
@@ -97,97 +99,113 @@
 
     def SetParams(self, params, flags):
         return self.an_params.SetParams(params, flags)
-    
+
     def SetSnapping(self, activate):
         self.an_points.SetSnapping(activate)
 
     def GetSnapping(self):
         return self.an_points.GetSnapping()
-    
+
     def GetLayerStyle(self):
         """Returns cmd for d.vect, with set style for analysis result"""
         analysis, valid = self.an_params.GetParam("analysis")
 
         resProps = self.an_props[analysis]["resultProps"]
 
-        width = UserSettings.Get(group='vnet', key='res_style', subkey= "line_width")
-        layerStyleCmd = ["layer=1",'width=' + str(width)]
+        width = UserSettings.Get(
+            group='vnet',
+            key='res_style',
+            subkey="line_width")
+        layerStyleCmd = ["layer=1", 'width=' + str(width)]
 
         if "catColor" in resProps:
             layerStyleCmd.append('flags=c')
         elif "singleColor" in resProps:
-            col = UserSettings.Get(group='vnet', key='res_style', subkey= "line_color")
-            layerStyleCmd.append('color=' + str(col[0]) + ':' + str(col[1]) + ':' + str(col[2]))        
+            col = UserSettings.Get(
+                group='vnet',
+                key='res_style',
+                subkey="line_color")
+            layerStyleCmd.append(
+                'color=' + str(col[0]) + ':' + str(col[1]) + ':' + str(col[2]))
 
         layerStyleVnetColors = []
         if "attrColColor" in resProps:
-            colorStyle = UserSettings.Get(group='vnet', key='res_style', subkey= "color_table")
-            invert = UserSettings.Get(group='vnet', key='res_style', subkey= "invert_colors")
+            colorStyle = UserSettings.Get(
+                group='vnet', key='res_style', subkey="color_table")
+            invert = UserSettings.Get(
+                group='vnet',
+                key='res_style',
+                subkey="invert_colors")
 
             layerStyleVnetColors = [
-                                    "v.colors",
-                                    "color=" + colorStyle,
-                                    "column=" + resProps["attrColColor"],
-                                   ]
+                "v.colors",
+                "color=" + colorStyle,
+                "column=" + resProps["attrColColor"],
+            ]
             if invert:
                 layerStyleVnetColors.append("-n")
 
         return layerStyleCmd, layerStyleVnetColors
 
-    def InputsErrorMsgs(self, msg, analysis, params, flags, inv_params, relevant_params):
+    def InputsErrorMsgs(self, msg, analysis, params, flags,
+                        inv_params, relevant_params):
         """Checks input data in Parameters tab and shows messages if some value is not valid
 
-            :param str msg: message added to start of message string 
+            :param str msg: message added to start of message string
             :return: True if checked inputs are OK
             :return: False if some of checked inputs is not ok
         """
 
-        if flags["t"] and  "turn_layer" not in relevant_params:
-            GMessage(parent = self.guiparent, message = _("Module <%s> does not support turns costs." % analysis))
+        if flags["t"] and "turn_layer" not in relevant_params:
+            GMessage(
+                parent=self.guiparent, message=_(
+                    "Module <%s> does not support turns costs." %
+                    analysis))
             return False
 
         errMapStr = ""
         if 'input' in inv_params:
             if params['input']:
-                errMapStr = _("Vector map '%s' does not exist.") %  (params['input'])
+                errMapStr = _("Vector map '%s' does not exist.") % (
+                    params['input'])
             else:
                 errMapStr = _("Vector map was not chosen.")
 
-
         if errMapStr:
-            GMessage(parent = self.guiparent,
-                     message = msg + "\n" + errMapStr)
+            GMessage(parent=self.guiparent,
+                     message=msg + "\n" + errMapStr)
             return False
 
         errLayerStr = ""
-        for layer, layerLabel in {'arc_layer' : _("arc layer"), 
-                                  'node_layer' : _("node layer"),
-                                  'turn_layer' : _("turntable layer"),
-                                  'turn_cat_layer' : _("unique categories layer")}.iteritems():
+        for layer, layerLabel in {
+                'arc_layer': _("arc layer"),
+                'node_layer': _("node layer"),
+                'turn_layer': _("turntable layer"),
+                'turn_cat_layer': _("unique categories layer")}.iteritems():
 
             if layer in ["turn_layer", "turn_cat_layer"] and not flags["t"]:
                 continue
             if layer in inv_params:
                 if params[layer]:
-                    errLayerStr += _("Chosen %s '%s' does not exist in vector map '%s'.\n") % \
-                                   (layerLabel, params[layer], params['input'])
+                    errLayerStr += _("Chosen %s '%s' does not exist in vector map '%s'.\n") % (
+                        layerLabel, params[layer], params['input'])
                 else:
                     errLayerStr += _("Choose existing %s.\n") % \
-                                   (layerLabel)
+                        (layerLabel)
         if errLayerStr:
-            GMessage(parent = self.guiparent,
-                     message = msg + "\n" + errLayerStr)
+            GMessage(parent=self.guiparent,
+                     message=msg + "\n" + errLayerStr)
             return False
 
         errColStr = ""
         for col in ["arc_column", "arc_backward_column", "node_column"]:
             if params[col] and col in inv_params and col in relevant_params:
-                errColStr += _("Chosen column '%s' does not exist in attribute table of layer '%s' of vector map '%s'.\n") % \
-                             (params[col], params[layer], params['input'])
+                errColStr += _("Chosen column '%s' does not exist in attribute table of layer '%s' of vector map '%s'.\n") % (
+                    params[col], params[layer], params['input'])
 
         if errColStr:
-            GMessage(parent = self.guiparent,
-                     message = msg + "\n" + errColStr)
+            GMessage(parent=self.guiparent,
+                     message=msg + "\n" + errColStr)
             return False
 
         return True
@@ -196,30 +214,32 @@
         """Initialization of settings (if not already defined)"""
         # initializes default settings
         initSettings = [
-                        ['res_style', 'line_width', 5],
-                        ['res_style', 'line_color', (192,0,0)],
-                        ['res_style', 'color_table', 'byr'],
-                        ['res_style', 'invert_colors', False],
-                        ['point_symbol', 'point_size', 10],             
-                        ['point_symbol', 'point_width', 2],
-                        ['point_colors', "unused", (131,139,139)],
-                        ['point_colors', "used1cat", (192,0,0)],
-                        ['point_colors', "used2cat", (0,0,255)],
-                        ['point_colors', "selected", (9,249,17)],
-                        ['other', "snap_tresh", 10],
-                        ['other', "max_hist_steps", 5]
-                       ]
+            ['res_style', 'line_width', 5],
+            ['res_style', 'line_color', (192, 0, 0)],
+            ['res_style', 'color_table', 'byr'],
+            ['res_style', 'invert_colors', False],
+            ['point_symbol', 'point_size', 10],
+            ['point_symbol', 'point_width', 2],
+            ['point_colors', "unused", (131, 139, 139)],
+            ['point_colors', "used1cat", (192, 0, 0)],
+            ['point_colors', "used2cat", (0, 0, 255)],
+            ['point_colors', "selected", (9, 249, 17)],
+            ['other', "snap_tresh", 10],
+            ['other', "max_hist_steps", 5]
+        ]
 
-        for init in initSettings: 
+        for init in initSettings:
             UserSettings.ReadSettingsFile()
-            UserSettings.Append(dict = UserSettings.userSettings, 
-                                    group ='vnet',
-                                    key = init[0],
-                                    subkey =init[1],
-                                    value = init[2],
-                                    overwrite = False)
+            UserSettings.Append(dict=UserSettings.userSettings,
+                                group='vnet',
+                                key=init[0],
+                                subkey=init[1],
+                                value=init[2],
+                                overwrite=False)
 
+
 class VNETPointsData:
+
     def __init__(self, mapWin, an_data, an_params):
 
         self.mapWin = mapWin
@@ -235,36 +255,36 @@
         self.snapping = False
 
         self.data = []
-        self.cols = { "name" : ['use', 'type', 'topology', 'e', 'n'],
-                      "label" : [_('use'), _('type'), _('topology'), 'e', 'n'],
-                      "type" :  [None, ["", _("Start point"), _("End Point")], None, float, float],#TDO
-                      "def_vals" : [False, 0, "new point", 0, 0]  
-                    }
+        self.cols = {"name": ['use', 'type', 'topology', 'e', 'n'],
+                     "label": [_('use'), _('type'), _('topology'), 'e', 'n'],
+                     # TDO
+                     "type": [None, ["", _("Start point"), _("End Point")], None, float, float],
+                     "def_vals": [False, 0, "new point", 0, 0]
+                     }
 
-
         # registration graphics for drawing
-        self.pointsToDraw = self.mapWin.RegisterGraphicsToDraw(graphicsType = "point", 
-                                                               setStatusFunc = self.SetPointStatus)
+        self.pointsToDraw = self.mapWin.RegisterGraphicsToDraw(
+            graphicsType="point", setStatusFunc=self.SetPointStatus)
 
         self.SetPointDrawSettings()
 
         self.AddPoint()
         self.AddPoint()
 
-        self.SetPointData(0, {'use' : True, 'type' : 1})
-        self.SetPointData(1, {'use' : True, 'type' : 2})
+        self.SetPointData(0, {'use': True, 'type': 1})
+        self.SetPointData(1, {'use': True, 'type': 2})
 
         self.selected = 0
 
-    def  __del__(self):
+    def __del__(self):
         self.CleanUp()
 
     def CleanUp(self):
         self.mapWin.UnregisterGraphicsToDraw(self.pointsToDraw)
 
         if self.handlerRegistered:
-            self.mapWin.UnregisterMouseEventHandler(wx.EVT_LEFT_DOWN, 
-                                                  self.OnMapClickHandler)
+            self.mapWin.UnregisterMouseEventHandler(wx.EVT_LEFT_DOWN,
+                                                    self.OnMapClickHandler)
 
     def SetSnapping(self, activate):
         self.snapping = activate
@@ -274,18 +294,21 @@
 
     def AddPoint(self):
 
-        self.pointsToDraw.AddItem(coords = (self.cols["def_vals"][3], self.cols["def_vals"][4]))
+        self.pointsToDraw.AddItem(
+            coords=(
+                self.cols["def_vals"][3],
+                self.cols["def_vals"][4]))
         self.data.append(self.cols["def_vals"][:])
-        
-        self.pointsChanged.emit(method = "AddPoint", kwargs = {})
 
+        self.pointsChanged.emit(method="AddPoint", kwargs={})
+
     def DeletePoint(self, pt_id):
         item = self.pointsToDraw.GetItem(pt_id)
         if item:
             self.pointsToDraw.DeleteItem(item)
             self.data.pop(pt_id)
 
-        self.pointsChanged.emit(method = "DeletePoint", kwargs = {"pt_id" : pt_id})
+        self.pointsChanged.emit(method="DeletePoint", kwargs={"pt_id": pt_id})
 
     def SetPoints(self, pts_data):
 
@@ -296,9 +319,12 @@
         for pt_data in pts_data:
             pt_data_list = self._ptDataToList(pt_data)
             self.data.append(pt_data_list)
-            self.pointsToDraw.AddItem(coords = (pt_data_list[3], pt_data_list[4]))
+            self.pointsToDraw.AddItem(
+                coords=(pt_data_list[3], pt_data_list[4]))
 
-        self.pointsChanged.emit(method = "SetPoints", kwargs = {"pts_data" : pts_data})
+        self.pointsChanged.emit(
+            method="SetPoints", kwargs={
+                "pts_data": pts_data})
 
     def SetPointData(self, pt_id, data):
         for col, v in data.iteritems():
@@ -309,16 +335,18 @@
             self.data[pt_id][idx] = v
 
         # if type is changed checked columns must be recalculated by _usePoint
-        if data.has_key('type') and not data.has_key('use'):
+        if 'type' in data and 'use' not in data:
             data["use"] = self.GetPointData(pt_id)['use']
 
-        if data.has_key('use'):
+        if 'use' in data:
             if self._usePoint(pt_id, data["use"]) == -1:
-                data["use"] =  False
+                data["use"] = False
             idx = self.cols["name"].index("use")
             self.data[pt_id][idx] = data["use"]
 
-        self.pointsChanged.emit(method = "SetPointData", kwargs = {"pt_id" : pt_id, "data" : data})
+        self.pointsChanged.emit(
+            method="SetPointData", kwargs={
+                "pt_id": pt_id, "data": data})
 
     def GetPointData(self, pt_id):
         return self._ptListDataToPtData(self.data[pt_id])
@@ -334,45 +362,61 @@
         if itemIndex == self.selected:
             wxPen = "selected"
         elif not self.data[itemIndex][0]:
-                wxPen = "unused"
-                item.hide = False
+            wxPen = "unused"
+            item.hide = False
         elif len(cats) > 1:
-            idx = self.data[itemIndex][1] 
-            if idx == 2: #End/To/Sink point
+            idx = self.data[itemIndex][1]
+            if idx == 2:  # End/To/Sink point
                 wxPen = "used2cat"
             else:
-                wxPen = "used1cat"              
+                wxPen = "used1cat"
         else:
-            wxPen = "used1cat"       
+            wxPen = "used1cat"
 
         item.SetPropertyVal('label', str(itemIndex + 1))
-        item.SetPropertyVal('penName', wxPen)  
+        item.SetPropertyVal('penName', wxPen)
 
     def SetSelected(self, pt_id):
         self.selected = pt_id
-        self.pointsChanged.emit(method = "SetSelected", kwargs = {"pt_id" : pt_id})
+        self.pointsChanged.emit(method="SetSelected", kwargs={"pt_id": pt_id})
 
     def GetSelected(self):
         return self.selected
 
     def SetPointDrawSettings(self):
         """Set settings for drawing of points"""
-        ptSize = int(UserSettings.Get(group='vnet', key='point_symbol', subkey = 'point_size'))
+        ptSize = int(
+            UserSettings.Get(
+                group='vnet',
+                key='point_symbol',
+                subkey='point_size'))
         self.pointsToDraw.SetPropertyVal("size", ptSize)
 
         colors = UserSettings.Get(group='vnet', key='point_colors')
-        ptWidth = int(UserSettings.Get(group='vnet', key='point_symbol', subkey = 'point_width'))
+        ptWidth = int(
+            UserSettings.Get(
+                group='vnet',
+                key='point_symbol',
+                subkey='point_width'))
 
         textProp = self.pointsToDraw.GetPropertyVal("text")
         textProp["font"].SetPointSize(ptSize + 2)
-    
+
         for colKey, col in colors.iteritems():
             pen = self.pointsToDraw.GetPen(colKey)
             if pen:
                 pen.SetColour(wx.Colour(col[0], col[1], col[2], 255))
                 pen.SetWidth(ptWidth)
             else:
-                self.pointsToDraw.AddPen(colKey, wx.Pen(colour = wx.Colour(col[0], col[1], col[2], 255), width = ptWidth))
+                self.pointsToDraw.AddPen(
+                    colKey,
+                    wx.Pen(
+                        colour=wx.Colour(
+                            col[0],
+                            col[1],
+                            col[2],
+                            255),
+                        width=ptWidth))
 
     def ParametersChanged(self, method, kwargs):
         if "analysis" in kwargs["changed_params"].keys():
@@ -400,7 +444,7 @@
         for k, val in pt_data.iteritems():
             pt_list_data[self.cols["name"].index(k)] = val
 
-        return pt_list_data 
+        return pt_list_data
 
     def _ptListDataToPtData(self, pt_list_data):
 
@@ -414,8 +458,8 @@
         """Item is checked/unchecked"""
         analysis, valid = self.an_params.GetParam("analysis")
         cats = self.an_data[analysis]["cmdParams"]["cats"]
-        ##TODO move
-        #if self.updateMap:
+        # TODO move
+        # if self.updateMap:
         #    up_map_evt = gUpdateMap(render = False, renderVector = False)
         #    wx.PostEvent(self.dialog.mapWin, up_map_evt)
 
@@ -428,7 +472,10 @@
         # point without given type cannot be selected
         if checkedVal == 0:
             self.data[pt_id][use_idx] = False
-            self.pointsChanged.emit(method = "SetPointData", kwargs = {"pt_id" : pt_id, "data" : {"use" : False}})
+            self.pointsChanged.emit(
+                method="SetPointData", kwargs={
+                    "pt_id": pt_id, "data": {
+                        "use": False}})
             return -1
 
         if analysis == "v.net.path" and use:
@@ -436,28 +483,30 @@
 
     def _vnetPathUpdateUsePoints(self, checked_pt_id):
 
-            alreadyChecked = []
+        alreadyChecked = []
 
-            type_idx = self.cols["name"].index("type")
-            use_idx = self.cols["name"].index("use")
+        type_idx = self.cols["name"].index("type")
+        use_idx = self.cols["name"].index("use")
 
-            if checked_pt_id is not None:
-                checkedKey = checked_pt_id
-                alreadyChecked.append(self.data[checked_pt_id][type_idx])
-            else:
-                checkedKey = -1
+        if checked_pt_id is not None:
+            checkedKey = checked_pt_id
+            alreadyChecked.append(self.data[checked_pt_id][type_idx])
+        else:
+            checkedKey = -1
 
-            for iKey, dt in enumerate(self.data):
-                pt_type = dt[type_idx]
+        for iKey, dt in enumerate(self.data):
+            pt_type = dt[type_idx]
 
-                if ((pt_type in alreadyChecked and checkedKey != iKey) \
-                   or pt_type == 0) and self.data[iKey][use_idx]:
-                    self.data[iKey][use_idx] = False
-                    self.pointsChanged.emit(method = "SetPointData", kwargs = {"pt_id" : iKey, "data": {"use" : False}})
-                elif self.data[iKey][use_idx]:
-                    alreadyChecked.append(pt_type)
+            if ((pt_type in alreadyChecked and checkedKey != iKey)
+                    or pt_type == 0) and self.data[iKey][use_idx]:
+                self.data[iKey][use_idx] = False
+                self.pointsChanged.emit(
+                    method="SetPointData", kwargs={
+                        "pt_id": iKey, "data": {
+                            "use": False}})
+            elif self.data[iKey][use_idx]:
+                alreadyChecked.append(pt_type)
 
-
     def EditPointMode(self, activate):
         """Registers/unregisters mouse handler into map window"""
 
@@ -465,23 +514,25 @@
             return
 
         if activate:
-            self.mapWin.RegisterMouseEventHandler(wx.EVT_LEFT_DOWN, 
+            self.mapWin.RegisterMouseEventHandler(wx.EVT_LEFT_DOWN,
                                                   self.OnMapClickHandler,
                                                   'cross')
             self.handlerRegistered = True
         else:
-            self.mapWin.UnregisterMouseEventHandler(wx.EVT_LEFT_DOWN, 
-                                                  self.OnMapClickHandler)
+            self.mapWin.UnregisterMouseEventHandler(wx.EVT_LEFT_DOWN,
+                                                    self.OnMapClickHandler)
             self.handlerRegistered = False
 
-        self.pointsChanged.emit(method = "EditMode", kwargs = {"activated" : activate})
+        self.pointsChanged.emit(
+            method="EditMode", kwargs={
+                "activated": activate})
 
     def IsEditPointModeActive(self):
         return self.handlerRegistered
 
     def OnMapClickHandler(self, event):
         """Take coordinates from map window"""
-        #TODO update snapping after input change
+        # TODO update snapping after input change
         if event == 'unregistered':
             self.handlerRegistered = False
             return
@@ -490,14 +541,16 @@
             self.AddPoint()
 
         e, n = self.mapWin.GetLastEN()
-        
+
         if self.snapping:
 
             # compute threshold
-            snapTreshPix = int(UserSettings.Get(group ='vnet', 
-                                                key = 'other', 
-                                                subkey = 'snap_tresh'))
-            res = max(self.mapWin.Map.region['nsres'], self.mapWin.Map.region['ewres'])
+            snapTreshPix = int(UserSettings.Get(group='vnet',
+                                                key='other',
+                                                subkey='snap_tresh'))
+            res = max(
+                self.mapWin.Map.region['nsres'],
+                self.mapWin.Map.region['ewres'])
             snapTreshDist = snapTreshPix * res
 
             params, err_params, flags = self.an_params.GetParams()
@@ -506,7 +559,7 @@
             if "input" in err_params:
                 msg = _("new point")
 
-            coords = SnapToNode(e, n, snapTreshDist, vectMap)     
+            coords = SnapToNode(e, n, snapTreshDist, vectMap)
             if coords:
                 e = coords[0]
                 n = coords[1]
@@ -518,10 +571,10 @@
         else:
             msg = _("new point")
 
-        self.SetPointData(self.selected, 
-                         {'topology' : msg,
-                          'e' : e,
-                          'n' : n})
+        self.SetPointData(self.selected,
+                          {'topology': msg,
+                           'e': e,
+                           'n': n})
 
         self.pointsToDraw.GetItem(self.selected).SetCoords([e, n])
 
@@ -530,8 +583,8 @@
         else:
             self.SetSelected(self.GetSelected() + 1)
 
-    def GetColumns(self, only_relevant  = True):
-        
+    def GetColumns(self, only_relevant=True):
+
         cols_data = deepcopy(self.cols)
 
         hidden_cols = []
@@ -539,7 +592,8 @@
         hidden_cols.append(self.cols["name"].index("n"))
 
         analysis, valid = self.an_params.GetParam("analysis")
-        if only_relevant and len(self.an_data[analysis]["cmdParams"]["cats"]) <= 1:
+        if only_relevant and len(self.an_data[analysis][
+                                 "cmdParams"]["cats"]) <= 1:
             hidden_cols.append(self.cols["name"].index("type"))
 
         i_red = 0
@@ -547,86 +601,95 @@
         for idx in hidden_cols:
             for dt in cols_data.itervalues():
                 dt.pop(idx - i_red)
-            i_red +=1
+            i_red += 1
 
         return cols_data
 
+
 class VNETAnalysisParameters:
+
     def __init__(self, an_props):
 
         self.an_props = an_props
 
-        self.params = {"analysis"   : self.an_props.used_an[0],
-                       "input"      : "",
-                       "arc_layer"     : "",
-                       "node_layer"     : "",
-                       "arc_column"   : "",
-                       "arc_backward_column"   : "",
-                       "node_column"    : "",
-                       "turn_layer"     : "",
-                       "turn_cat_layer"   : "",
-                       "iso_lines"  : "", #TODO check validity
-                       "max_dist"   : 0} #TODO check validity
+        self.params = {"analysis": self.an_props.used_an[0],
+                       "input": "",
+                       "arc_layer": "",
+                       "node_layer": "",
+                       "arc_column": "",
+                       "arc_backward_column": "",
+                       "node_column": "",
+                       "turn_layer": "",
+                       "turn_cat_layer": "",
+                       "iso_lines": "",  # TODO check validity
+                       "max_dist": 0}  # TODO check validity
 
-        self.flags = {"t" : False}
+        self.flags = {"t": False}
 
-        self.parametersChanged = Signal('VNETAnalysisParameters.parametersChanged')
+        self.parametersChanged = Signal(
+            'VNETAnalysisParameters.parametersChanged')
 
     def SetParams(self, params, flags):
-        
-        changed_params = {} 
+
+        changed_params = {}
         for p, v in params.iteritems():
-            if p == "analysis" and  v not in self.an_props.used_an:
+            if p == "analysis" and v not in self.an_props.used_an:
                 continue
 
             if p == "input":
                 mapName, mapSet = ParseMapStr(v)
                 v = mapName + "@" + mapSet
 
-            if self.params.has_key(p):
+            if p in self.params:
                 if isinstance(v, str):
                     v = v.strip()
-            
+
                 self.params[p] = v
                 changed_params[p] = v
 
         changed_flags = {}
         for p, v in flags.iteritems():
-            if self.flags.has_key(p):
+            if p in self.flags:
                 self.flags[p] = v
                 changed_flags[p] = v
 
-        self.parametersChanged.emit(method = "SetParams", 
-                                    kwargs = {"changed_params" : changed_params , "changed_flags" : changed_flags})
+        self.parametersChanged.emit(
+            method="SetParams",
+            kwargs={
+                "changed_params": changed_params,
+                "changed_flags": changed_flags})
 
         return changed_params, changed_flags
 
     def GetParam(self, param):
 
         invParams = []
-        if param in ["input", "arc_layer", "node_layer", "arc_column", 
-                     "arc_backward_column", "node_column", "turn_layer", "turn_cat_layer"]:
+        if param in [
+                "input", "arc_layer", "node_layer", "arc_column",
+                "arc_backward_column", "node_column", "turn_layer",
+                "turn_cat_layer"]:
             invParams = self._getInvalidParams(self.params)
 
-        if invParams: 
+        if invParams:
             return self.params[param], False
 
         return self.params[param], True
 
     def GetParams(self):
-        
+
         invParams = self._getInvalidParams(self.params)
-        return self.params, invParams, self.flags 
+        return self.params, invParams, self.flags
 
     def _getInvalidParams(self, params):
         """Check of analysis input data for invalid values (Parameters tab)"""
-        # dict of invalid values {key from self.itemData (comboboxes from Parameters tab) : invalid value}
+        # dict of invalid values {key from self.itemData (comboboxes from
+        # Parameters tab) : invalid value}
         invParams = []
 
         # check vector map
         if params["input"]:
             mapName, mapSet = params["input"].split("@")
-            if grass.list_grouped('vector').has_key(mapSet):
+            if mapSet in grass.list_grouped('vector'):
                 vectMaps = grass.list_grouped('vector')[mapSet]
 
         if not params["input"] or mapName not in vectMaps:
@@ -634,8 +697,8 @@
             return invParams
 
         # check arc/node layer
-        layers = utils.GetVectorNumberOfLayers(params["input"])    
-        
+        layers = utils.GetVectorNumberOfLayers(params["input"])
+
         for l in ['arc_layer', 'node_layer', 'turn_layer', 'turn_cat_layer']:
             if not layers or params[l] not in layers:
                 invParams.append(l)
@@ -650,7 +713,7 @@
 
         # check costs columns
         for col in ["arc_column", "arc_backward_column", "node_column"]:
-        
+
             if col == "node_column":
                 try:
                     table = dbInfo.GetTable(int(params["node_layer"]))
@@ -658,192 +721,198 @@
                 except (KeyError, ValueError):
                     table = None
 
-            if not table or  not params[col]  in columnchoices.keys():
+            if not table or not params[col] in columnchoices.keys():
                 invParams.append(col)
                 continue
-            
-            if columnchoices[params[col]]['type'] not in ['integer', 'double precision']:
+
+            if columnchoices[
+                    params[col]]['type'] not in [
+                    'integer', 'double precision']:
                 invParams.append(col)
                 continue
-     
-        return invParams  
 
+        return invParams
+
+
 class VNETAnalysesProperties:
+
     def __init__(self):
         """Initializes parameters for different v.net.* modules """
-        # initialization of v.net.* analysis parameters (data which characterizes particular analysis)
+        # initialization of v.net.* analysis parameters (data which
+        # characterizes particular analysis)
 
         self.attrCols = {
-                          'arc_column' : {
-                                        "label" : _("Arc forward/both direction(s) cost column:"),
-                                        "name" : _("arc forward/both")
-                                       },
-                          'arc_backward_column' : {
-                                        "label" : _("Arc backward direction cost column:"),
-                                        "name" : _("arc backward")
-                                       },
-                          'acolumn' : {
-                                       "label" : _("Arcs' cost column (for both directions):"),
-                                       "name" : _("arc"),
-                                       "inputField" : 'arc_column',
-                                      },
-                          'node_column' : {
-                                       "label" : _("Node cost column:"),
-                                        "name" : _("node")                                      
-                                      }
-                        }
+            'arc_column': {
+                "label": _("Arc forward/both direction(s) cost column:"),
+                "name": _("arc forward/both")
+            },
+            'arc_backward_column': {
+                "label": _("Arc backward direction cost column:"),
+                "name": _("arc backward")
+            },
+            'acolumn': {
+                "label": _("Arcs' cost column (for both directions):"),
+                "name": _("arc"),
+                "inputField": 'arc_column',
+            },
+            'node_column': {
+                "label": _("Node cost column:"),
+                "name": _("node")
+            }
+        }
 
         self.vnetProperties = {
-                                   "v.net.path" : {
-                                                     "label" : _("Shortest path %s") % "(v.net.path)",  
-                                                     "cmdParams" : {
-                                                                      "cats" :  [
-                                                                                    ["st_pt", _("Start point")], 
-                                                                                    ["end_pt", _("End point")] 
-                                                                                ],
-                                                                      "cols" :  [
-                                                                                 'arc_column',
-                                                                                 'arc_backward_column',
-                                                                                 'node_column'
-                                                                                ],
-                                                                   },
-                                                     "resultProps" : {
-                                                                      "singleColor" : None,
-                                                                      "dbMgr" : True  #TODO delete this property, this information can be get from result
-                                                                     },
-                                                     "turns_support" : True
-                                                  },
+            "v.net.path": {
+                "label": _("Shortest path %s") % "(v.net.path)",
+                "cmdParams": {
+                    "cats": [
+                        ["st_pt", _("Start point")],
+                        ["end_pt", _("End point")]
+                    ],
+                    "cols": [
+                        'arc_column',
+                        'arc_backward_column',
+                        'node_column'
+                    ],
+                },
+                "resultProps": {
+                    "singleColor": None,
+                    "dbMgr": True  # TODO delete this property, this information can be get from result
+                },
+                "turns_support": True
+            },
 
-                                    "v.net.salesman" : {
-                                                        "label" : _("Traveling salesman %s") % "(v.net.salesman)",  
-                                                        "cmdParams" : {
-                                                                        "cats" : [["center_cats", None]],
-                                                                        "cols" : [
-                                                                                  'arc_column',
-                                                                                  'arc_backward_column'
-                                                                                 ],
-                                                                      },
-                                                        "resultProps" : {
-                                                                         "singleColor" : None,
-                                                                         "dbMgr" : False
-                                                                        },
-                                                     "turns_support" : True
+            "v.net.salesman": {
+                "label": _("Traveling salesman %s") % "(v.net.salesman)",
+                "cmdParams": {
+                    "cats": [["center_cats", None]],
+                    "cols": [
+                        'arc_column',
+                        'arc_backward_column'
+                    ],
+                },
+                "resultProps": {
+                    "singleColor": None,
+                    "dbMgr": False
+                },
+                "turns_support": True
 
-                                                       },
-                                    "v.net.flow" : {
-                                                     "label" : _("Maximum flow %s") % "(v.net.flow)",  
-                                                     "cmdParams" : {
-                                                                      "cats" : [
-                                                                                ["source_cats", _("Source point")], 
-                                                                                ["sink_cats", _("Sink point")]
-                                                                               ],                                                   
-                                                                      "cols" : [
-                                                                                'arc_column',
-                                                                                'arc_backward_column',
-                                                                                'node_column'
-                                                                               ]
-                                                                  },
-                                                     "resultProps" : {
-                                                                      "attrColColor": "flow",
-                                                                      "dbMgr" : True
-                                                                     },
-                                                     "turns_support" : False
-                                                   },
-                                    "v.net.alloc" : {
-                                                     "label" : _("Subnets for nearest centers %s") % "(v.net.alloc)",  
-                                                     "cmdParams" : {
-                                                                      "cats" : [["center_cats", None]],                           
-                                                                      "cols" : [
-                                                                                 'arc_column',
-                                                                                 'arc_backward_column',
-                                                                                 'node_column'
-                                                                               ]
-                                                                  },
-                                                     "resultProps" :  {
-                                                                       "catColor" : None, 
-                                                                       "dbMgr" : False
-                                                                      },
-                                                     "turns_support" : True
-                                                   },
-                                    "v.net.steiner" : {
-                                                     "label" : _("Steiner tree for the network and given terminals %s") % "(v.net.steiner)",  
-                                                     "cmdParams" : {
-                                                                      "cats" : [["terminal_cats", None]],                           
-                                                                      "cols" : [
-                                                                                 'acolumn',
-                                                                               ]
-                                                                  },
-                                                     "resultProps" : {
-                                                                      "singleColor" : None,
-                                                                      "dbMgr" : False 
-                                                                     },
-                                                     "turns_support" : True
-                                                   },
-                                   "v.net.distance" : {
-                                                       "label" : _("Shortest distance via the network %s") % "(v.net.distance)",  
-                                                       "cmdParams" : {
-                                                                        "cats" : [
-                                                                                  ["from_cats", "From point"],
-                                                                                  ["to_cats", "To point"]
-                                                                                 ],
-                                                                        "cols" : [
-                                                                                  'arc_column',
-                                                                                  'arc_backward_column',
-                                                                                  'node_column'
-                                                                                 ],
-                                                                  },
-                                                      "resultProps" : {
-                                                                        "catColor" : None,
-                                                                        "dbMgr" : True
-                                                                      },
-                                                     "turns_support" : False
-                                                     },
-                                    "v.net.iso" :  {
-                                                     "label" : _("Cost isolines %s") % "(v.net.iso)",  
-                                                     "cmdParams" : {
-                                                                      "cats" : [["center_cats", None]],                           
-                                                                      "cols" : [
-                                                                                 'arc_column',
-                                                                                 'arc_backward_column',
-                                                                                 'node_column'
-                                                                               ]
-                                                                  },
-                                                     "resultProps" : {
-                                                                      "catColor" : None,
-                                                                      "dbMgr" : False
-                                                                     },
-                                                     "turns_support" : True
-                                                   }
-                                }
+            },
+            "v.net.flow": {
+                "label": _("Maximum flow %s") % "(v.net.flow)",
+                "cmdParams": {
+                    "cats": [
+                        ["source_cats", _("Source point")],
+                        ["sink_cats", _("Sink point")]
+                    ],
+                    "cols": [
+                        'arc_column',
+                        'arc_backward_column',
+                        'node_column'
+                    ]
+                },
+                "resultProps": {
+                    "attrColColor": "flow",
+                    "dbMgr": True
+                },
+                "turns_support": False
+            },
+            "v.net.alloc": {
+                "label": _("Subnets for nearest centers %s") % "(v.net.alloc)",
+                "cmdParams": {
+                    "cats": [["center_cats", None]],
+                    "cols": [
+                        'arc_column',
+                        'arc_backward_column',
+                        'node_column'
+                    ]
+                },
+                "resultProps": {
+                    "catColor": None,
+                    "dbMgr": False
+                },
+                "turns_support": True
+            },
+            "v.net.steiner": {
+                "label": _("Steiner tree for the network and given terminals %s") % "(v.net.steiner)",
+                "cmdParams": {
+                    "cats": [["terminal_cats", None]],
+                    "cols": [
+                        'acolumn',
+                    ]
+                },
+                "resultProps": {
+                    "singleColor": None,
+                    "dbMgr": False
+                },
+                "turns_support": True
+            },
+            "v.net.distance": {
+                "label": _("Shortest distance via the network %s") % "(v.net.distance)",
+                "cmdParams": {
+                    "cats": [
+                        ["from_cats", "From point"],
+                        ["to_cats", "To point"]
+                    ],
+                    "cols": [
+                        'arc_column',
+                        'arc_backward_column',
+                        'node_column'
+                    ],
+                },
+                "resultProps": {
+                    "catColor": None,
+                    "dbMgr": True
+                },
+                "turns_support": False
+            },
+            "v.net.iso": {
+                "label": _("Cost isolines %s") % "(v.net.iso)",
+                "cmdParams": {
+                    "cats": [["center_cats", None]],
+                    "cols": [
+                        'arc_column',
+                        'arc_backward_column',
+                        'node_column'
+                    ]
+                },
+                "resultProps": {
+                    "catColor": None,
+                    "dbMgr": False
+                },
+                "turns_support": True
+            }
+        }
 
-        self.used_an = ["v.net.path", 
-                         "v.net.salesman",
-                         "v.net.flow",
-                         "v.net.alloc",
-                         "v.net.distance",
-                         "v.net.iso",
-                         #"v.net.steiner"
-                        ] 
+        self.used_an = ["v.net.path",
+                        "v.net.salesman",
+                        "v.net.flow",
+                        "v.net.alloc",
+                        "v.net.distance",
+                        "v.net.iso",
+                        #"v.net.steiner"
+                        ]
 
         for an in self.vnetProperties.keys():
             if an not in self.used_an:
                 del self.vnetProperties[an]
                 continue
 
-            cols = self.vnetProperties[an]["cmdParams"]["cols"] 
+            cols = self.vnetProperties[an]["cmdParams"]["cols"]
             self.vnetProperties[an]["cmdParams"]["cols"] = {}
-            for c in  cols:
-                self.vnetProperties[an]["cmdParams"]["cols"][c] = self.attrCols[c]
+            for c in cols:
+                self.vnetProperties[an]["cmdParams"][
+                    "cols"][c] = self.attrCols[c]
 
     def has_key(self, key):
-        return self.vnetProperties.has_key(key)
+        return key in self.vnetProperties
 
     def __getitem__(self, key):
         return self.vnetProperties[key]
 
     def GetRelevantParams(self, analysis):
 
-        if not self.vnetProperties.has_key(analysis):
+        if analysis not in self.vnetProperties:
             return None
 
         relevant_params = ["input", "arc_layer", "node_layer"]
@@ -862,36 +931,39 @@
 
         return relevant_params
 
+
 class VNETTmpVectMaps:
     """Class which creates, stores and destroys all tmp maps created during analysis"""
+
     def __init__(self, parent, mapWin):
-        self.tmpMaps = [] # temporary maps 
+        self.tmpMaps = []  # temporary maps
         self.parent = parent
         self.mapWin = mapWin
 
     def AddTmpVectMap(self, mapName, msg):
         """New temporary map
 
-        :return: instance of VectMap representing temporary map 
+        :return: instance of VectMap representing temporary map
         """
         currMapSet = grass.gisenv()['MAPSET']
-        tmpMap = grass.find_file(name = mapName, 
-                                 element = 'vector', 
-                                 mapset = currMapSet)
+        tmpMap = grass.find_file(name=mapName,
+                                 element='vector',
+                                 mapset=currMapSet)
 
         fullName = tmpMap["fullname"]
         # map already exists
         if fullName:
-            #TODO move dialog out of class, AddTmpVectMap(self, mapName, overvrite = False)
-            dlg = wx.MessageDialog(parent = self.parent, 
-                                   message = msg,
-                                   caption = _("Overwrite map layer"),
-                                   style = wx.YES_NO | wx.NO_DEFAULT |
+            # TODO move dialog out of class, AddTmpVectMap(self, mapName,
+            # overvrite = False)
+            dlg = wx.MessageDialog(parent=self.parent,
+                                   message=msg,
+                                   caption=_("Overwrite map layer"),
+                                   style=wx.YES_NO | wx.NO_DEFAULT |
                                    wx.ICON_QUESTION | wx.CENTRE)
-                
+
             ret = dlg.ShowModal()
             dlg.Destroy()
-                
+
             if ret == wx.ID_NO:
                 return None
         else:
@@ -907,7 +979,7 @@
         :param: vectMapName name of vector map
 
         :return: True if it contains the map
-        :return: False if not 
+        :return: False if not
         """
 
         mapValSpl = vectMapName.strip().split("@")
@@ -915,7 +987,7 @@
             mapSet = mapValSpl[1]
         else:
             mapSet = grass.gisenv()['MAPSET']
-        mapName = mapValSpl[0] 
+        mapName = mapValSpl[0]
         fullName = mapName + "@" + mapSet
 
         for vectTmpMap in self.tmpMaps:
@@ -933,7 +1005,7 @@
     def RemoveFromTmpMaps(self, vectMap):
         """Temporary map is removed from the class instance however it is not deleted
 
-        :param vectMap: instance of VectMap class to be removed 
+        :param vectMap: instance of VectMap class to be removed
 
         :return: True if was removed
         :return: False if does not contain the map
@@ -946,16 +1018,16 @@
 
     def DeleteTmpMap(self, vectMap):
         """Temporary map is removed from the class and it is deleted
-        
-        :param vectMap: instance of VectMap class to be deleted 
 
+        :param vectMap: instance of VectMap class to be deleted
+
         :return: True if was removed
         :return: False if does not contain the map
         """
         if vectMap:
             vectMap.DeleteRenderLayer()
-            RunCommand('g.remove', flags = 'f', type = 'vector',
-                        name = vectMap.GetVectMapName())
+            RunCommand('g.remove', flags='f', type='vector',
+                       name=vectMap.GetVectMapName())
             self.RemoveFromTmpMaps(vectMap)
             return True
         return False
@@ -964,60 +1036,60 @@
         """Delete all temporary maps in the class"""
         update = False
         for tmpMap in self.tmpMaps:
-            RunCommand('g.remove', flags = 'f', type = 'vector',
-                        name = tmpMap.GetVectMapName())
+            RunCommand('g.remove', flags='f', type='vector',
+                       name=tmpMap.GetVectMapName())
             if tmpMap.DeleteRenderLayer():
                 update = True
         return update
 
+
 class VectMap:
-    """Represents map 
+    """Represents map
         It can check if it was modified or render it
     """
+
     def __init__(self, mapWin, fullName):
         self.fullName = fullName
         self.mapWin = mapWin
         self.renderLayer = None
-        self.modifTime = None # time, for modification check
+        self.modifTime = None  # time, for modification check
 
     def __del__(self):
 
         self.DeleteRenderLayer()
-   
-    def AddRenderLayer(self, cmd = None, colorsCmd = None):
+
+    def AddRenderLayer(self, cmd=None, colorsCmd=None):
         """Add map from map window layers to render """
 
         if not self.mapWin:
             return False
 
-        existsMap = grass.find_file(name = self.fullName, 
-                                    element = 'vector', 
-                                    mapset = grass.gisenv()['MAPSET'])
+        existsMap = grass.find_file(name=self.fullName,
+                                    element='vector',
+                                    mapset=grass.gisenv()['MAPSET'])
 
         if not existsMap["name"]:
             self.DeleteRenderLayer()
             return False
 
         if not cmd:
-            cmd = []    
+            cmd = []
         cmd.insert(0, 'd.vect')
         cmd.append('map=%s' % self.fullName)
 
-        if self.renderLayer:       
-             self.DeleteRenderLayer()
+        if self.renderLayer:
+            self.DeleteRenderLayer()
 
         if colorsCmd:
             colorsCmd.append('map=%s' % self.fullName)
             layerStyleVnetColors = cmdlist_to_tuple(colorsCmd)
 
             RunCommand(layerStyleVnetColors[0],
-                        **layerStyleVnetColors[1])
+                       **layerStyleVnetColors[1])
 
-
-        self.renderLayer = self.mapWin.Map.AddLayer(ltype = "vector",     command = cmd,
-                                                    name = self.fullName, active = True,
-                                                    opacity = 1.0,        render = False,       
-                                                    pos = -1)
+        self.renderLayer = self.mapWin.Map.AddLayer(
+            ltype="vector", command=cmd, name=self.fullName, active=True,
+            opacity=1.0, render=False, pos=-1)
         return True
 
     def DeleteRenderLayer(self):
@@ -1025,10 +1097,10 @@
         if not self.mapWin:
             return False
 
-        if self.renderLayer: 
-             self.mapWin.Map.DeleteLayer(self.renderLayer)
-             self.renderLayer = None
-             return True
+        if self.renderLayer:
+            self.mapWin.Map.DeleteLayer(self.renderLayer)
+            self.renderLayer = None
+            return True
         return False
 
     def GetRenderLayer(self):
@@ -1049,27 +1121,27 @@
         :return:  1 - if map was not modified
         """
         if self.modifTime is None:
-            return -1       
+            return -1
         if self.modifTime != self.GetLastModified():
-            return 0  
+            return 0
         return 1
 
     def GetLastModified(self):
-        """Get modification time 
+        """Get modification time
 
-        :return: MAP DATE time string from vector map head file 
+        :return: MAP DATE time string from vector map head file
         """
 
         mapValSpl = self.fullName.split("@")
         mapSet = mapValSpl[1]
-        mapName = mapValSpl[0] 
+        mapName = mapValSpl[0]
 
-        headPath =  os.path.join(grass.gisenv()['GISDBASE'],
-                                 grass.gisenv()['LOCATION_NAME'],
-                                 mapSet,
-                                 "vector",
-                                 mapName,
-                                 "head")
+        headPath = os.path.join(grass.gisenv()['GISDBASE'],
+                                grass.gisenv()['LOCATION_NAME'],
+                                mapSet,
+                                "vector",
+                                mapName,
+                                "head")
         try:
             head = open(headPath, 'r')
             for line in head.readlines():
@@ -1083,26 +1155,28 @@
         except IOError:
             return ""
 
-class History: 
+
+class History:
     """Class which reads and saves history data (based on gui.core.settings Settings class file save/load)
 
     .. todo::
         Maybe it could be useful for other GRASS wxGUI tools.
-    """  
+    """
+
     def __init__(self):
 
         # max number of steps in history (zero based)
-        self.maxHistSteps = 3 
-        # current history step 
+        self.maxHistSteps = 3
+        # current history step
         self.currHistStep = 0
         # number of steps saved in history
         self.histStepsNum = 0
 
-        # dict contains data saved in history for current history step 
-        self.currHistStepData = {} 
+        # dict contains data saved in history for current history step
+        self.currHistStepData = {}
 
-        # buffer for data to be saved into history 
-        self.newHistStepData = {} 
+        # buffer for data to be saved into history
+        self.newHistStepData = {}
 
         self.histFile = grass.tempfile()
 
@@ -1122,7 +1196,7 @@
 
     def GetPrev(self):
         """Go one step back in history"""
-        self.currHistStep += 1 
+        self.currHistStep += 1
         self.currHistStepData.clear()
         self.currHistStepData = self._getHistStepData(self.currHistStep)
 
@@ -1141,7 +1215,7 @@
         if key not in self.newHistStepData:
             self.newHistStepData[key] = {}
 
-        if type(subkey) == types.ListType:
+        if isinstance(subkey, types.ListType):
             if subkey[0] not in self.newHistStepData[key]:
                 self.newHistStepData[key][subkey[0]] = {}
             self.newHistStepData[key][subkey[0]][subkey[1]] = value
@@ -1150,10 +1224,10 @@
 
     def SaveHistStep(self):
         """Create new history step with data in buffer"""
-        self.maxHistSteps = UserSettings.Get(group ='vnet',
-                                             key = 'other',
-                                             subkey = 'max_hist_steps')
-        self.currHistStep = 0 
+        self.maxHistSteps = UserSettings.Get(group='vnet',
+                                             key='other',
+                                             subkey='max_hist_steps')
+        self.currHistStep = 0
 
         newHistFile = grass.tempfile()
         newHist = open(newHistFile, "w")
@@ -1168,11 +1242,11 @@
         try_remove(self.histFile)
         self.histFile = newHistFile
 
-        self.newHistStepData.clear() 
+        self.newHistStepData.clear()
 
         return removedHistData
 
-    def _savePreviousHist(self, newHist, oldHist):          
+    def _savePreviousHist(self, newHist, oldHist):
         """Save previous history into new file"""
         newHistStep = False
         removedHistData = {}
@@ -1201,47 +1275,56 @@
                 if newHistStepsNum >= self.maxHistSteps:
                     self._parseLine(line, removedHistStep)
                 else:
-                    newHist.write('%s' % line)                
+                    newHist.write('%s' % line)
 
         return removedHistData
-            
+
     def _saveNewHistStep(self, newHist):
         """Save buffer (new step) data into file"""
-        newHist.write('%s%s%s' % (os.linesep, "history step=0", os.linesep))  
+        newHist.write('%s%s%s' % (os.linesep, "history step=0", os.linesep))
         for key in self.newHistStepData.keys():
-            subkeys =  self.newHistStepData[key].keys()
+            subkeys = self.newHistStepData[key].keys()
             newHist.write('%s%s' % (key, self.sep))
             for idx in range(len(subkeys)):
-                value =  self.newHistStepData[key][subkeys[idx]]
-                if type(value) == types.DictType:
+                value = self.newHistStepData[key][subkeys[idx]]
+                if isinstance(value, types.DictType):
                     if idx > 0:
                         newHist.write('%s%s%s' % (os.linesep, key, self.sep))
                     newHist.write('%s%s' % (subkeys[idx], self.sep))
-                    kvalues =  self.newHistStepData[key][subkeys[idx]].keys()
+                    kvalues = self.newHistStepData[key][subkeys[idx]].keys()
                     srange = range(len(kvalues))
                     for sidx in srange:
-                        svalue = self._parseValue(self.newHistStepData[key][subkeys[idx]][kvalues[sidx]])
-                        newHist.write('%s%s%s' % (kvalues[sidx], self.sep, svalue))
+                        svalue = self._parseValue(
+                            self.newHistStepData[key][
+                                subkeys[idx]][
+                                kvalues[sidx]])
+                        newHist.write(
+                            '%s%s%s' %
+                            (kvalues[sidx], self.sep, svalue))
                         if sidx < len(kvalues) - 1:
                             newHist.write('%s' % self.sep)
                 else:
-                    if idx > 0 and \
-                            type( self.newHistStepData[key][subkeys[idx - 1]]) == types.DictType:
+                    if idx > 0 and isinstance(
+                            self.newHistStepData[key][subkeys[idx - 1]],
+                            types.DictType):
                         newHist.write('%s%s%s' % (os.linesep, key, self.sep))
-                    value = self._parseValue(self.newHistStepData[key][subkeys[idx]])
+                    value = self._parseValue(
+                        self.newHistStepData[key][subkeys[idx]])
                     newHist.write('%s%s%s' % (subkeys[idx], self.sep, value))
-                    if idx < len(subkeys) - 1 and \
-                            type(self.newHistStepData[key][subkeys[idx + 1]]) != types.DictType:
+                    if idx < len(subkeys) - 1 and not isinstance(
+                            self.newHistStepData[key][subkeys[idx + 1]],
+                            types.DictType):
                         newHist.write('%s' % self.sep)
             newHist.write(os.linesep)
         self.histStepsNum = 0
 
-    def _parseValue(self, value, read = False):
+    def _parseValue(self, value, read=False):
         """Parse value"""
-        if read: # -> read data (cast values)
+        if read:  # -> read data (cast values)
 
             if value:
-                if value[0] == '[' and value[-1] == ']':# TODO, possible wrong interpretation
+                if value[
+                        0] == '[' and value[-1] == ']':  # TODO, possible wrong interpretation
                     value = value[1:-1].split(',')
                     value = map(self._castValue, value)
                     return value
@@ -1252,10 +1335,10 @@
                 value = False
             elif value == 'None':
                 value = None
-            elif ':' in value: # -> color
+            elif ':' in value:  # -> color
                 try:
                     value = tuple(map(int, value.split(':')))
-                except ValueError: # -> string
+                except ValueError:  # -> string
                     pass
             else:
                 try:
@@ -1265,12 +1348,12 @@
                         value = float(value)
                     except ValueError:
                         pass
-        else: # -> write data
-            if type(value) == type(()): # -> color
+        else:  # -> write data
+            if isinstance(value, type(())):  # -> color
                 value = str(value[0]) + ':' +\
                     str(value[1]) + ':' + \
                     str(value[2])
-                
+
         return value
 
     def _castValue(self, value):
@@ -1285,8 +1368,8 @@
 
         return value
 
-    def _getHistStepData(self, histStep):          
-        """Load data saved in history step"""       
+    def _getHistStepData(self, histStep):
+        """Load data saved in history step"""
         hist = open(self.histFile)
         histStepData = {}
 
@@ -1294,8 +1377,8 @@
         isSearchedHistStep = False
         for line in hist.readlines():
 
-            if  not line.strip() and isSearchedHistStep:
-                 break
+            if not line.strip() and isSearchedHistStep:
+                break
             elif not line.strip():
                 newHistStep = True
                 continue
@@ -1312,13 +1395,13 @@
         return histStepData
 
     def _parseLine(self, line, histStepData):
-        """Parse line in file with history"""       
+        """Parse line in file with history"""
         line = line.rstrip('%s' % os.linesep).split(self.sep)
         key = line[0]
         kv = line[1:]
         idx = 0
         subkeyMaster = None
-        if len(kv) % 2 != 0: # multiple (e.g. nviz)
+        if len(kv) % 2 != 0:  # multiple (e.g. nviz)
             subkeyMaster = kv[0]
             del kv[0]
         idx = 0
@@ -1327,12 +1410,12 @@
                 subkey = [subkeyMaster, kv[idx]]
             else:
                 subkey = kv[idx]
-            value = kv[idx+1]
-            value = self._parseValue(value, read = True)
+            value = kv[idx + 1]
+            value = self._parseValue(value, read=True)
             if key not in histStepData:
                 histStepData[key] = {}
 
-            if type(subkey) == types.ListType:
+            if isinstance(subkey, types.ListType):
                 if subkey[0] not in histStepData[key]:
                     histStepData[key][subkey[0]] = {}
                 histStepData[key][subkey[0]][subkey[1]] = value
@@ -1341,19 +1424,22 @@
             idx += 2
 
     def DeleteNewHistStepData(self):
-        """Delete buffer data for new history step"""       
-        self.newHistStepData.clear() 
+        """Delete buffer data for new history step"""
+        self.newHistStepData.clear()
 
+
 class VNETGlobalTurnsData:
     """Turn Data"""
+
     def __init__(self):
         # Definition of four basic directions
         self.turn_data = [
-                            ["Straight", DegreesToRadians(-30), DegreesToRadians(+30), 0.0],
-                            ["Right Turn", DegreesToRadians(+30), DegreesToRadians(+150), 0.0],
-                            ["Reverse",  DegreesToRadians(+150), DegreesToRadians(-150), 0.0],
-                            ["Left Turn",  DegreesToRadians(-150), DegreesToRadians(-30), 0.0]  
-                            ]   
+            ["Straight", DegreesToRadians(-30), DegreesToRadians(+30), 0.0],
+            ["Right Turn", DegreesToRadians(+30), DegreesToRadians(+150), 0.0],
+            ["Reverse", DegreesToRadians(+150), DegreesToRadians(-150), 0.0],
+            ["Left Turn", DegreesToRadians(-150), DegreesToRadians(-30), 0.0]
+        ]
+
     def GetData(self):
         data = []
         for ival in self.turn_data:
@@ -1378,32 +1464,32 @@
     def AppendRow(self, values):
         self.turn_data.append(values)
 
-    def InsertRow(self,line,values):
-        self.turn_data.insert(line,values)
+    def InsertRow(self, line, values):
+        self.turn_data.insert(line, values)
 
     def PopRow(self, values):
         self.RemoveDataValidator(values)
         self.turn_data.pop(values)
-             
+
     def DataValidator(self, row, col, value):
         """Angle recalculation due to value changing"""
 
-        if col not in [1,2]:
+        if col not in [1, 2]:
             return
 
         if col == 1:
             new_from_angle = value
             old_from_angle = self.turn_data[row][1]
-            new_to_angle  = self.turn_data[row][2]
+            new_to_angle = self.turn_data[row][2]
             if self.IsInInterval(old_from_angle, new_to_angle, new_from_angle):
 
                 prev_row = row - 1
-                if  prev_row == -1:
+                if prev_row == -1:
                     prev_row = len(self.turn_data) - 1
                 self.turn_data[prev_row][2] = new_from_angle
                 return
-        
-        if col ==2:
+
+        if col == 2:
             new_to_angle = value
             old_to_angle = self.turn_data[row][2]
             new_from_angle = self.turn_data[row][1]
@@ -1412,9 +1498,8 @@
                 next_row = row + 1
                 if len(self.turn_data) == next_row:
                     next_row = 0
-                self.turn_data[next_row][1] = new_to_angle 
-                return     
-                   
+                self.turn_data[next_row][1] = new_to_angle
+                return
 
         inside_new = []
         overlap_new_from = []
@@ -1424,12 +1509,13 @@
             if i == row:
                 continue
             from_angle = self.turn_data[i][1]
-            is_in_from = self.IsInInterval(new_from_angle, new_to_angle, from_angle)
+            is_in_from = self.IsInInterval(
+                new_from_angle, new_to_angle, from_angle)
 
             to_angle = self.turn_data[i][2]
-            is_in_to = self.IsInInterval(new_from_angle, new_to_angle, to_angle)
+            is_in_to = self.IsInInterval(
+                new_from_angle, new_to_angle, to_angle)
 
-
             if is_in_from and is_in_to:
                 inside_new.append(i)
             if is_in_from:
@@ -1445,7 +1531,7 @@
 
         for i_row in inside_new:
             if col == 1:
-                angle = new_from_angle            
+                angle = new_from_angle
             else:
                 angle = new_to_angle
 
@@ -1459,17 +1545,16 @@
         else:
             prev_row = row - 1
 
-        remove_to_angle = self.turn_data[row][2]        
+        remove_to_angle = self.turn_data[row][2]
         self.turn_data[prev_row][2] = remove_to_angle
 
-
     def IsInInterval(self, from_angle, to_angle, angle):
-        """Test if a direction includes or not includes a value""" 
+        """Test if a direction includes or not includes a value"""
         if to_angle < from_angle:
-            to_angle = math.pi * 2  + to_angle
+            to_angle = math.pi * 2 + to_angle
         if angle < from_angle:
-                angle = math.pi * 2  + angle
-            
+            angle = math.pi * 2 + angle
+
         if angle > from_angle and angle < to_angle:
             return True
         return False

Modified: grass/trunk/gui/wxpython/vnet/vnet_utils.py
===================================================================
--- grass/trunk/gui/wxpython/vnet/vnet_utils.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/vnet/vnet_utils.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -18,8 +18,8 @@
 @author Eliska Kyzlikova <eliska.kyzlikova gmail.com> (turn costs support)
 """
 
-import  math
-from grass.script     import core as grass
+import math
+from grass.script import core as grass
 from core.utils import _
 
 try:
@@ -29,6 +29,7 @@
 except ImportError:
     haveCtypes = False
 
+
 def ParseMapStr(mapStr):
     """Create full map name (add current mapset if it is not present in name)"""
     mapValSpl = mapStr.strip().split("@")
@@ -36,16 +37,19 @@
         mapSet = mapValSpl[1]
     else:
         mapSet = grass.gisenv()['MAPSET']
-    mapName = mapValSpl[0] 
-        
+    mapName = mapValSpl[0]
+
     return mapName, mapSet
 
+
 def DegreesToRadians(degrees):
     return degrees * math.pi / 180
 
+
 def RadiansToDegrees(radians):
-    return radians * 180 / math.pi   
+    return radians * 180 / math.pi
 
+
 def SnapToNode(e, n, tresh, vectMap):
     """Find nearest node to click coordinates (within given threshold)"""
     if not haveCtypes:
@@ -54,29 +58,29 @@
     vectMap, mapSet = ParseMapStr(vectMap)
 
     openedMap = pointer(vectlib.Map_info())
-    ret = vectlib.Vect_open_old(openedMap, 
-                                     c_char_p(vectMap),
-                                     c_char_p(mapSet))
+    ret = vectlib.Vect_open_old(openedMap,
+                                c_char_p(vectMap),
+                                c_char_p(mapSet))
     if ret == 1:
         vectlib.Vect_close(openedMap)
-    if ret != 2: 
+    if ret != 2:
         return None
 
-    nodeNum =  vectlib.Vect_find_node(openedMap,     
-                                      c_double(e), 
-                                      c_double(n), 
-                                      c_double(0), 
-                                      c_double(tresh),
-                                      vectlib.WITHOUT_Z)
+    nodeNum = vectlib.Vect_find_node(openedMap,
+                                     c_double(e),
+                                     c_double(n),
+                                     c_double(0),
+                                     c_double(tresh),
+                                     vectlib.WITHOUT_Z)
 
     if nodeNum > 0:
         e = c_double(0)
         n = c_double(0)
-        vectlib.Vect_get_node_coor(openedMap, 
-                                   nodeNum, 
-                                   byref(e), 
-                                   byref(n), 
-                                   None); # z
+        vectlib.Vect_get_node_coor(openedMap,
+                                   nodeNum,
+                                   byref(e),
+                                   byref(n),
+                                   None)  # z
         e = e.value
         n = n.value
     else:
@@ -85,67 +89,70 @@
 
     return e, n
 
+
 def GetNearestNodeCat(e, n, layer, tresh, vectMap):
 
-    if  not haveCtypes:
+    if not haveCtypes:
         return -2
 
     vectMapName, mapSet = ParseMapStr(vectMap)
 
     openedMap = pointer(vectlib.Map_info())
-    ret = vectlib.Vect_open_old(openedMap, 
-                                     c_char_p(vectMapName),
-                                     c_char_p(mapSet))
+    ret = vectlib.Vect_open_old(openedMap,
+                                c_char_p(vectMapName),
+                                c_char_p(mapSet))
     if ret == 1:
         vectlib.Vect_close(openedMap)
-    if ret != 2: 
+    if ret != 2:
         return -1
 
-    nodeNum = vectlib.Vect_find_node(openedMap,     
-                                     c_double(e), 
-                                     c_double(n), 
-                                     c_double(0), 
+    nodeNum = vectlib.Vect_find_node(openedMap,
+                                     c_double(e),
+                                     c_double(n),
+                                     c_double(0),
                                      c_double(tresh),
                                      vectlib.WITHOUT_Z)
 
     if nodeNum > 0:
         e = c_double(0)
         n = c_double(0)
-        vectlib.Vect_get_node_coor(openedMap, 
-                                   nodeNum, 
-                                   byref(e), 
-                                   byref(n), 
-                                   None); # z
+        vectlib.Vect_get_node_coor(openedMap,
+                                   nodeNum,
+                                   byref(e),
+                                   byref(n),
+                                   None)  # z
         e = e.value
         n = n.value
     else:
         vectlib.Vect_close(openedMap)
         return -1
 
-    box = vectlib.bound_box();
-    List = POINTER(vectlib.boxlist);
-    List = vectlib.Vect_new_boxlist(c_int(0));
+    box = vectlib.bound_box()
+    List = POINTER(vectlib.boxlist)
+    List = vectlib.Vect_new_boxlist(c_int(0))
 
-    box.E = box.W = e;
-    box.N = box.S = n;
-    box.T = box.B = 0;
-    vectlib.Vect_select_lines_by_box(openedMap, byref(box), vectlib.GV_POINT, List);
+    box.E = box.W = e
+    box.N = box.S = n
+    box.T = box.B = 0
+    vectlib.Vect_select_lines_by_box(
+        openedMap, byref(box),
+        vectlib.GV_POINT, List)
 
-    found = 0;
-    dcost = 0;
+    found = 0
+    dcost = 0
 
     Cats = POINTER(vectlib.line_cats)
     Cats = vectlib.Vect_new_cats_struct()
- 
+
     cat = c_int(0)
 
-    for j in range(List.contents.n_values): 
+    for j in range(List.contents.n_values):
         line = List.contents.id[j]
         type = vectlib.Vect_read_line(openedMap, None, Cats, line)
         if type != vectlib.GV_POINT:
             continue
 
-        if vectlib.Vect_cat_get(Cats, c_int(layer), byref(cat)): 
+        if vectlib.Vect_cat_get(Cats, c_int(layer), byref(cat)):
             found = 1
             break
     if found:

Modified: grass/trunk/gui/wxpython/vnet/widgets.py
===================================================================
--- grass/trunk/gui/wxpython/vnet/widgets.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/vnet/widgets.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -1,7 +1,7 @@
 """
 @package vnet.widgets
 
- at brief Base class for list of points. 
+ at brief Base class for list of points.
 
 Classes:
  - widgets::PointsList
@@ -38,26 +38,26 @@
                  pos=wx.DefaultPosition, size=wx.DefaultSize,
                  style=wx.LC_REPORT | wx.SUNKEN_BORDER | wx.LC_HRULES |
                  wx.LC_SINGLE_SEL):
-        """Creates list for points. 
+        """Creates list for points.
 
-        PointsList class was created from GCPList class in GCP manager. It is possible 
+        PointsList class was created from GCPList class in GCP manager. It is possible
         to be shared by GCP and VNET front end.
 
         Important parameters:
         :param cols: is list containing list items. which represents columns.
-                This columns will be added in order as they are in list. 
+                This columns will be added in order as they are in list.
                 Class will add as first column "use" with number of point and checkbox.
                 Structure of list item must be this:
-               -1. item: column name 
-               -2. item: column label                
+               -1. item: column name
+               -2. item: column label
                -3. item: If column is editable by user, it must contain convert function to convert
-                         inserted string to it's type for sorting. Use None for not editable 
+                         inserted string to it's type for sorting. Use None for not editable
                          columns. Values for insertion can be in list. This allows insert
-                         just values in the list. 
-               -4. item: Default value for column cell. Value should be given in it's  type 
+                         just values in the list.
+               -4. item: Default value for column cell. Value should be given in it's  type
                          in order to sorting would work properly. If 3. item is list, it must be index
                          of some item in the list.
-  
+
         Example of cols parameter:
                  column name, column label, convert function, default val
         @code
@@ -68,10 +68,10 @@
                    ['N', _('target N'), float, 0.0],
                    ['F_Err', _('Forward error'), None, 0],
                    ['B_Err', _(Backward error'), None, 0]
-                   ['type', _('type'), [_(""), _("Start point"), _("End point")], 0] # Select from 3 choices ("Start point", "End point"), 
+                   ['type', _('type'), [_(""), _("Start point"), _("End point")], 0] # Select from 3 choices ("Start point", "End point"),
                                                                                      # Choice with index 0 ("") is default.
                   ]
-        @endcode 
+        @endcode
         """
 
         wx.ListCtrl.__init__(self, parent, id, pos, size, style)
@@ -85,13 +85,14 @@
         cols.insert(0, ['use', _('use'), False, 0])
 
         self.colsData = cols
-        self.dataTypes = {"colName" : 0,
-                          "colLabel" : 1,
-                          "colEditable" : 2,
-                          "itemDefaultValue" : 3} # just for better understanding
+        self.dataTypes = {
+            "colName": 0,
+            "colLabel": 1,
+            "colEditable": 2,
+            "itemDefaultValue": 3}  # just for better understanding
 
         # information whether list items are checked or not
-        self.CheckList = [] 
+        self.CheckList = []
 
         self._createCols()
         self.hiddenCols = {}
@@ -103,18 +104,17 @@
         self.selected = wx.NOT_FOUND
         self.selectedkey = -1
 
-
         # CheckListCtrlMixin must set an ImageList first
         self.il = self.GetImageList(wx.IMAGE_LIST_SMALL)
 
         # images for column sorting
-        SmallUpArrow = wx.BitmapFromImage(self.getSmallUpArrowImage())            
-        SmallDnArrow = wx.BitmapFromImage(self.getSmallDnArrowImage())            
+        SmallUpArrow = wx.BitmapFromImage(self.getSmallUpArrowImage())
+        SmallDnArrow = wx.BitmapFromImage(self.getSmallDnArrowImage())
         self.sm_dn = self.il.Add(SmallDnArrow)
         self.sm_up = self.il.Add(SmallUpArrow)
 
         # initialize column sorter
-        self.itemDataMap = [] 
+        self.itemDataMap = []
         ncols = self.GetColumnCount()
         ColumnSorterMixin.__init__(self, ncols)
 
@@ -122,7 +122,7 @@
         self._colSortFlag = [1] * ncols
 
         # same structure as itemDataMap, information about choice index selected
-        # if cell is in column without values to choose then is -1 
+        # if cell is in column without values to choose then is -1
         self.selIdxs = []
 
         self.ResizeColumns()
@@ -138,13 +138,14 @@
         else:
             # the hard way: we want images on the column header
             info = wx.ListItem()
-            info.SetMask(wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT)
+            info.SetMask(
+                wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT)
             info.SetImage(-1)
             info.m_format = wx.LIST_FORMAT_LEFT
 
             for col in enumerate(self.colsData):
                 iLabel = self.dataTypes["colLabel"]
-                info.SetText(col[1][iLabel]) 
+                info.SetText(col[1][iLabel])
                 self.InsertColumnInfo(col[0], info)
 
     def AddItem(self):
@@ -159,10 +160,9 @@
                 itemIndexes.append(col[iDefVal])
             else:
                 itemData.append(col[iDefVal])
-                itemIndexes.append(-1)# not a choise column 
+                itemIndexes.append(-1)  # not a choise column
 
-                
-        self.selIdxs.append(itemIndexes) 
+        self.selIdxs.append(itemIndexes)
 
         for hCol in self.hiddenCols.itervalues():
             defVal = hCol['colsData'][iDefVal]
@@ -178,7 +178,7 @@
         itemData[0] = self.selectedkey + 1
         self.itemDataMap.append(copy(itemData))
 
-        self.Append(map(str, itemData))             
+        self.Append(map(str, itemData))
 
         self.selected = self.GetItemCount() - 1
         self.SetItemData(self.selected, self.selectedkey)
@@ -215,7 +215,7 @@
 
     def EditCellIndex(self, index, colName, cellData):
         """Changes value in list using key (same regardless of sorting)"""
-        colNum = self._getColumnNum(colName) 
+        colNum = self._getColumnNum(colName)
         key = self.GetItemData(index)
 
         iColEd = self.dataTypes["colEditable"]
@@ -223,7 +223,7 @@
             cellVal = self.colsData[colNum][iColEd][cellData]
             self.selIdxs[key][colNum] = cellData
         else:
-            cellVal = cellData  
+            cellVal = cellData
             self.selIdxs[key][colNum] = -1
 
         self.itemDataMap[key][colNum] = cellVal
@@ -233,14 +233,14 @@
 
     def EditCellKey(self, key, colName, cellData):
         """Changes value in list using index (changes during sorting)"""
-        colNum = self._getColumnNum(colName)   
+        colNum = self._getColumnNum(colName)
 
         iColEd = self.dataTypes["colEditable"]
         if type(self.colsData[colNum][iColEd]).__name__ == "list":
             cellVal = self.colsData[colNum][iColEd][cellData]
             self.selIdxs[key][colNum] = cellData
         else:
-            cellVal = cellData  
+            cellVal = cellData
             self.selIdxs[key][colNum] = -1
 
         self.itemDataMap[key][colNum] = cellVal
@@ -264,7 +264,7 @@
         return -1
 
     def ChangeColEditable(self, colName, colType):
-        """Change 3. item in constructor parameter cols (see the class constructor hint)"""    
+        """Change 3. item in constructor parameter cols (see the class constructor hint)"""
         colNum = self._getColumnNum(colName)
         iColEd = self.dataTypes["colEditable"]
         self.colsData[colNum][iColEd] = colType
@@ -281,8 +281,8 @@
         self.selIdxs.pop(key)
 
         # update hidden columns
-        for hCol in self.hiddenCols.itervalues():    
-            hCol['itemDataMap'].pop(key) 
+        for hCol in self.hiddenCols.itervalues():
+            hCol['itemDataMap'].pop(key)
             hCol['selIdxs'].pop(key)
 
         # update key and point number
@@ -299,7 +299,7 @@
             else:
                 self.selected = self.GetItemCount() - 1
                 self.selectedkey = self.GetItemData(self.selected)
-                
+
             self.SetItemState(self.selected,
                               wx.LIST_STATE_SELECTED,
                               wx.LIST_STATE_SELECTED)
@@ -319,16 +319,16 @@
         i = 0
         for col in self.colsData:
             if i == 0:
-                i  += 1
+                i += 1
                 continue
             if type(col[iColEd]).__name__ == "list":
                 self.EditCell(index, i, col[iColEd][col[iDefVal]])
             else:
                 self.EditCell(index, i, col[iDefVal])
-            i  += 1
+            i += 1
         self.CheckItem(index, False)
 
-    def ResizeColumns(self, minWidth = [90, 120]):
+    def ResizeColumns(self, minWidth=[90, 120]):
         """Resize columns"""
         for i in range(self.GetColumnCount()):
             self.SetColumnWidth(i, wx.LIST_AUTOSIZE)
@@ -355,26 +355,27 @@
         data = []
 
         index = event.GetIndex()
-        key = self.GetItemData(index)       
+        key = self.GetItemData(index)
         changed = False
         iColEd = self.dataTypes["colEditable"]
 
-        for col in  enumerate(self.colsData):
+        for col in enumerate(self.colsData):
             if col[1][iColEd]:
-                data.append([col[0], #culumn number
-                             self.GetItem(index, col[0]).GetText(), #cell value 
-                             col[1][iColEd]]) #convert function for type check
+                data.append([col[0],  # culumn number
+                             self.GetItem(
+                    index, col[0]).GetText(),  # cell value
+                    col[1][iColEd]])  # convert function for type check
 
         if not data:
             return
-        dlg = self.CreateEditDialog(data = data, pointNo = key)
+        dlg = self.CreateEditDialog(data=data, pointNo=key)
 
         if dlg.ShowModal() == wx.ID_OK:
-            editedData = dlg.GetValues() # string
-            
+            editedData = dlg.GetValues()  # string
+
             if len(editedData) == 0:
-                GError(parent = self,
-                       message=_("Invalid value inserted. Operation canceled."))
+                GError(parent=self, message=_(
+                    "Invalid value inserted. Operation canceled."))
             else:
                 i = 0
                 for editedCell in editedData:
@@ -385,19 +386,19 @@
                         self.SetStringItem(index, editedCell[0], value)
                         self.itemDataMap[key][editedCell[0]] = editedCell[1]
                         changed = True
-                    i += 1 
+                    i += 1
 
                 self.selIdxs[key] = dlg.GetSelectionIndexes()
         dlg.Destroy()
         return changed, key
-        
+
     def CreateEditDialog(self, data, pointNo):
         """Helper function
         It is possible to define in child derived class
-        and adapt created dialog (e. g. it's title...) 
+        and adapt created dialog (e. g. it's title...)
         """
 
-        return  EditItem(parent=self, id=wx.ID_ANY, data = data, pointNo=pointNo)
+        return EditItem(parent=self, id=wx.ID_ANY, data=data, pointNo=pointNo)
 
     def OnColClick(self, event):
         """ListCtrl forgets selected item..."""
@@ -417,7 +418,11 @@
 
     def getSmallUpArrowImage(self):
         """Get arrow up symbol for indication of sorting"""
-        stream = open(os.path.join(globalvar.IMGDIR, 'small_up_arrow.png'), 'rb')
+        stream = open(
+            os.path.join(
+                globalvar.IMGDIR,
+                'small_up_arrow.png'),
+            'rb')
         try:
             img = wx.ImageFromStream(stream)
         finally:
@@ -426,7 +431,11 @@
 
     def getSmallDnArrowImage(self):
         """Get arrow down symbol for indication of sorting"""
-        stream = open(os.path.join(globalvar.IMGDIR, 'small_down_arrow.png'), 'rb')
+        stream = open(
+            os.path.join(
+                globalvar.IMGDIR,
+                'small_down_arrow.png'),
+            'rb')
         try:
             img = wx.ImageFromStream(stream)
         finally:
@@ -434,7 +443,7 @@
         return img
 
     def _getColumnNum(self, colName):
-        """Get position of column among showed columns 
+        """Get position of column among showed columns
 
         :param colName: name of column
         :type colName: str
@@ -442,9 +451,9 @@
         """
 
         for iCol, col in enumerate(self.colsData):
-             if colName == col[0]:
-                 return iCol
- 
+            if colName == col[0]:
+                return iCol
+
         return -1
 
     def HideColumn(self, colName):
@@ -460,7 +469,7 @@
             return False
 
         hiddenCol = self.GetColumn(colNum)
-        self.DeleteColumn(colNum) 
+        self.DeleteColumn(colNum)
 
         self.hiddenCols[colName] = {}
         self.hiddenCols[colName]['wxCol'] = hiddenCol
@@ -490,7 +499,7 @@
         """
         if pos < 0 and pos >= self.self.GetColumnCount():
             return False
-        if self.hiddenCols.has_key(colName):
+        if colName in self.hiddenCols:
             col = self.hiddenCols[colName]
 
             for item in enumerate(self.itemDataMap):
@@ -502,7 +511,7 @@
 
             self.InsertColumnItem(pos, col['wxCol'])
             self.ResizeColumns()
-            del self.hiddenCols[colName]  
+            del self.hiddenCols[colName]
             return True
 
         return False
@@ -522,10 +531,13 @@
         else:
             return True
 
+
 class EditItem(wx.Dialog):
-    
-    def __init__(self, parent, data, pointNo, itemCap = "Point No." ,id=wx.ID_ANY,
-                 title =_("Edit point"), style=wx.DEFAULT_DIALOG_STYLE):
+
+    def __init__(
+            self, parent, data, pointNo, itemCap="Point No.", id=wx.ID_ANY,
+            title=_("Edit point"),
+            style=wx.DEFAULT_DIALOG_STYLE):
         """Dialog for editing item cells in list"""
 
         wx.Dialog.__init__(self, parent, id, title=_(title), style=style)
@@ -534,17 +546,16 @@
         panel = wx.Panel(parent=self)
         sizer = wx.BoxSizer(wx.VERTICAL)
 
-        box = wx.StaticBox (parent=panel, id=wx.ID_ANY,
-                            label=" %s %s " % (_(itemCap), str(pointNo + 1)))
+        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+                           label=" %s %s " % (_(itemCap), str(pointNo + 1)))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
 
         # source coordinates
         gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
-       
-        self.fields = [] 
+
+        self.fields = []
         self.data = deepcopy(data)
 
-
         col = 0
         row = 0
         iField = 0
@@ -552,10 +563,10 @@
 
             # Select
             if type(cell[2]).__name__ == "list":
-                self.fields.append(wx.ComboBox(parent = panel, id = wx.ID_ANY,
-                                               choices = cell[2],
-                                               style = wx.CB_READONLY, 
-                                               size = (110, -1)))
+                self.fields.append(wx.ComboBox(parent=panel, id=wx.ID_ANY,
+                                               choices=cell[2],
+                                               style=wx.CB_READONLY,
+                                               size=(110, -1)))
             # Text field
             else:
                 if cell[2] == float:
@@ -566,18 +577,25 @@
                     validator = None
 
                 if validator:
-                    self.fields.append(wx.TextCtrl(parent=panel, id=wx.ID_ANY, 
-                                                   validator = validator, size=(150, -1)))
+                    self.fields.append(
+                        wx.TextCtrl(
+                            parent=panel, id=wx.ID_ANY, validator=validator,
+                            size=(150, -1)))
                 else:
-                    self.fields.append(wx.TextCtrl(parent=panel, id=wx.ID_ANY, 
+                    self.fields.append(wx.TextCtrl(parent=panel, id=wx.ID_ANY,
                                                    size=(150, -1)))
                     value = cell[1]
                     if not isinstance(cell[1], basestring):
                         value = str(cell[1])
                     self.fields[iField].SetValue(value)
 
-            label = wx.StaticText(parent = panel, id=wx.ID_ANY,
-                                  label = _(parent.GetColumn(cell[0]).GetText()) + ":") # name of column)
+            label = wx.StaticText(
+                parent=panel,
+                id=wx.ID_ANY,
+                label=_(
+                    parent.GetColumn(
+                        cell[0]).GetText()) +
+                ":")  # name of column)
 
             gridSizer.Add(item=label,
                           flag=wx.ALIGN_CENTER_VERTICAL,
@@ -588,8 +606,7 @@
             gridSizer.Add(item=self.fields[iField],
                           pos=(row, col))
 
-
-            if col%3 == 0:
+            if col % 3 == 0:
                 col = 0
                 row += 1
             else:
@@ -598,7 +615,7 @@
             iField += 1
 
         boxSizer.Add(item=gridSizer, proportion=1,
-                  flag=wx.EXPAND | wx.ALL, border=5)
+                     flag=wx.EXPAND | wx.ALL, border=5)
 
         sizer.Add(item=boxSizer, proportion=1,
                   flag=wx.EXPAND | wx.ALL, border=5)
@@ -628,9 +645,9 @@
         iField = 0
         for cell in self.data:
             value = self.fields[iField].GetValue()
-            
+
             if type(cell[2]).__name__ == "list":
-                    cell[1] = value
+                cell[1] = value
             else:
                 try:
                     cell[1] = cell[2](value)
@@ -646,15 +663,12 @@
         """
         iField = 0
         itemIndexes = []
-        for cell in self.parent.colsData:            
+        for cell in self.parent.colsData:
             if type(cell[2]).__name__ == "list":
                 itemIndexes.append(self.fields[iField].GetSelection())
             else:
-                itemIndexes.append(-1) # not a choise column 
-            if cell[2]:   
+                itemIndexes.append(-1)  # not a choise column
+            if cell[2]:
                 iField += 1
 
         return itemIndexes
-
-
-

Modified: grass/trunk/gui/wxpython/web_services/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/web_services/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/web_services/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -2,4 +2,4 @@
     'widgets',
     'cap_interface',
     'dialogs',
-    ]
+]

Modified: grass/trunk/gui/wxpython/web_services/cap_interface.py
===================================================================
--- grass/trunk/gui/wxpython/web_services/cap_interface.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/web_services/cap_interface.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -29,10 +29,12 @@
     sys.path.append(WMSLibPath)
 
 from wms_cap_parsers import WMSCapabilitiesTree, \
-                            WMTSCapabilitiesTree, \
-                            OnEarthCapabilitiesTree
+    WMTSCapabilitiesTree, \
+    OnEarthCapabilitiesTree
 
+
 class CapabilitiesBase:
+
     def GetLayerByName(self, name):
         """Find layer by name
         """
@@ -49,7 +51,9 @@
         else:
             return None
 
+
 class LayerBase:
+
     def GetId(self):
         """Get layer id
         """
@@ -70,8 +74,10 @@
         """
         self.child_layers.append(layer)
 
+
 class WMSCapabilities(CapabilitiesBase, WMSCapabilitiesTree):
-    def __init__(self, cap_file, force_version = None):
+
+    def __init__(self, cap_file, force_version=None):
         """Create common interface for web_services.widgets to WMS
         capabilities data
         """
@@ -85,39 +91,41 @@
         self.layers_by_id = {}
         self._initializeLayerTree(self.root_layer)
 
-    def _initializeLayerTree(self, parent_layer, id = 0):
+    def _initializeLayerTree(self, parent_layer, id=0):
         """Build tree, which represents layers
         """
         if id == 0:
             parent_layer = WMSLayer(parent_layer, id, self)
             self.layers_by_id[id] = parent_layer
             id += 1
-        
+
         layer_nodes = parent_layer.GetLayerNode().findall((self.xml_ns.Ns("Layer")))
-        
+
         for l in layer_nodes:
             layer = WMSLayer(l, id, self)
             parent_layer.AddChildLayer(layer)
             self.layers_by_id[id] = layer
             id += 1
             id = self._initializeLayerTree(layer, id)
-        
+
         return id
 
     def GetFormats(self):
         """Get supported formats
-        """      
+        """
         request_node = self.cap_node.find(self.xml_ns.Ns("Request"))
         get_map_node = request_node.find(self.xml_ns.Ns("GetMap"))
         format_nodes = get_map_node.findall(self.xml_ns.Ns("Format"))
- 
+
         formats = []
         for node in format_nodes:
             formats.append(node.text)
 
         return formats
 
+
 class WMSLayer(LayerBase):
+
     def __init__(self, layer_node, id, cap):
         """Common interface for web_services.widgets to WMS
         capabilities <Layer> element
@@ -136,14 +144,14 @@
         if param == 'title':
             title_node = self.layer_node.find(title)
             if title_node is not None:
-                return title_node.text 
+                return title_node.text
             else:
                 return None
 
         if param == 'name':
             name_node = self.layer_node.find(name)
             if name_node is not None:
-                return name_node.text 
+                return name_node.text
             else:
                 return None
 
@@ -154,7 +162,7 @@
             styles = []
             style = self.xml_ns.Ns("Style")
             for style_node in self.layer_node.findall(style):
-                style_name = '' 
+                style_name = ''
                 style_title = ''
 
                 if style_node.find(title) is not None:
@@ -162,13 +170,14 @@
                 if style_node.find(name) is not None:
                     style_name = style_node.find(name).text
 
-                styles.append({'title' : style_title, 
-                               'name' : style_name,
-                               'isDefault' : False})
+                styles.append({'title': style_title,
+                               'name': style_name,
+                               'isDefault': False})
             return styles
 
         if param == 'srs':
-            projs_nodes = self.layer_node.findall(self.xml_ns.Ns(self.cap.getprojtag()))
+            projs_nodes = self.layer_node.findall(
+                self.xml_ns.Ns(self.cap.getprojtag()))
 
             projs = []
             if projs_nodes is None:
@@ -188,7 +197,9 @@
         else:
             return False
 
+
 class WMTSCapabilities(CapabilitiesBase, WMTSCapabilitiesTree):
+
     def __init__(self, cap_file):
         """Create common interface for web_services.widgets to WMTS
         capabilities data
@@ -201,7 +212,7 @@
         layers = self._findall(contents, 'Layer', self.xml_ns.NsWmts)
 
         self.layers_by_id = {}
-        
+
         id = 0
         root_layer = WMTSLayer(None, id, self)
         self.layers_by_id[id] = root_layer
@@ -210,8 +221,10 @@
             id += 1
             self.layers_by_id[id] = WMTSLayer(layer_node, id, self)
             root_layer.child_layers.append(self.layers_by_id[id])
-    
+
+
 class WMTSLayer(LayerBase):
+
     def __init__(self, layer_node, id, cap):
         """Common interface for web_services.widgets to WMTS
         capabilities <Layer> element
@@ -237,22 +250,23 @@
         if param == 'title':
             title_node = self.layer_node.find(title)
             if title_node is not None:
-                return title_node.text 
+                return title_node.text
             else:
                 return None
 
         if param == 'name':
             name_node = self.layer_node.find(name)
             if name_node is not None:
-                return name_node.text 
+                return name_node.text
             else:
                 return None
 
         if param == 'styles':
             styles = []
-            for style_node in self.layer_node.findall(self.xml_ns.NsWmts("Style")):
+            for style_node in self.layer_node.findall(
+                    self.xml_ns.NsWmts("Style")):
 
-                style_name = '' 
+                style_name = ''
                 style_title = ''
 
                 if style_node.find(title) is not None:
@@ -262,13 +276,13 @@
 
                 is_def = False
                 if 'isDefault' in style_node.attrib and\
-                    style_node.attrib['isDefault'] == 'true':
+                        style_node.attrib['isDefault'] == 'true':
                     is_def = True
 
-                styles.append({'title' : style_title, 
-                               'name' : style_name,
-                               'isDefault' : is_def})
-            
+                styles.append({'title': style_title,
+                               'name': style_name,
+                               'isDefault': is_def})
+
             return styles
 
         if param == 'format':
@@ -287,21 +301,24 @@
         if self.layer_node is None:
             return layer_projs
 
-        mat_set_links = self.layer_node.findall(self.xml_ns.NsWmts('TileMatrixSetLink'))
+        mat_set_links = self.layer_node.findall(
+            self.xml_ns.NsWmts('TileMatrixSetLink'))
 
         contents = self.cap.getroot().find(self.xml_ns.NsWmts('Contents'))
         tileMatrixSets = contents.findall(self.xml_ns.NsWmts('TileMatrixSet'))
 
-        for link in  mat_set_links:
-            mat_set_link_id = link.find(self.xml_ns.NsWmts('TileMatrixSet')).text
+        for link in mat_set_links:
+            mat_set_link_id = link.find(
+                self.xml_ns.NsWmts('TileMatrixSet')).text
             if not mat_set_link_id:
                 continue
 
             for mat_set in tileMatrixSets:
-                mat_set_id = mat_set.find(self.xml_ns.NsOws('Identifier')).text 
+                mat_set_id = mat_set.find(self.xml_ns.NsOws('Identifier')).text
                 if mat_set_id and mat_set_id != mat_set_link_id:
                     continue
-                mat_set_srs = mat_set.find(self.xml_ns.NsOws('SupportedCRS')).text.strip()
+                mat_set_srs = mat_set.find(
+                    self.xml_ns.NsOws('SupportedCRS')).text.strip()
                 layer_projs.append(mat_set_srs)
         return layer_projs
 
@@ -313,7 +330,9 @@
         else:
             return True
 
+
 class OnEarthCapabilities(CapabilitiesBase, OnEarthCapabilitiesTree):
+
     def __init__(self, cap_file):
         """Create Common interface for web_services.widgets to
         NASA OnEarth tile service data (equivalent to  WMS, WMTS
@@ -325,8 +344,8 @@
 
         self.layers_by_id = {}
         self._initializeLayerTree(self.getroot())
-        
-    def _initializeLayerTree(self, parent_layer, id = 0):
+
+    def _initializeLayerTree(self, parent_layer, id=0):
         """Build tree, which represents layers
         """
         if id == 0:
@@ -346,14 +365,16 @@
             id += 1
             parent_layer.child_layers.append(layer)
             if layer_node.tag == 'TiledGroups':
-               id = self._initializeLayerTree(layer, id)
+                id = self._initializeLayerTree(layer, id)
 
         return id
 
+
 class OnEarthLayer(LayerBase):
+
     def __init__(self, layer_node, parent_layer, id, cap):
         """Common interface for web_services.widgets to NASA Earth
-            capabilities <TiledGroup>\<TiledGroups> element 
+            capabilities <TiledGroup>\<TiledGroups> element
             (equivalent to  WMS, WMTS <Layer> element)
         """
         self.id = id
@@ -367,7 +388,7 @@
         """
         if self.layer_node is None or \
            self.layer_node.tag == 'TiledGroups':
-           return False
+            return False
         else:
             return True
 
@@ -382,14 +403,14 @@
         if param == 'title':
             title_node = self.layer_node.find("Title")
             if title_node is not None:
-                return title_node.text 
+                return title_node.text
             else:
                 return None
 
         if param == 'name':
             name_node = self.layer_node.find("Name")
             if name_node is not None:
-                return name_node.text 
+                return name_node.text
             else:
                 return None
 

Modified: grass/trunk/gui/wxpython/web_services/dialogs.py
===================================================================
--- grass/trunk/gui/wxpython/web_services/dialogs.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/web_services/dialogs.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -24,47 +24,50 @@
 import sys
 import shutil
 
-from copy      import deepcopy
+from copy import deepcopy
 
 import grass.script as grass
 from grass.script.task import cmdlist_to_tuple, cmdtuple_to_list
 
-from core             import globalvar
-from core.debug       import Debug
-from core.gcmd        import GMessage, GWarning, GError, RunCommand
-from core.utils       import GetSettingsPath, _
-from core.gconsole    import CmdThread, GStderr, EVT_CMD_DONE, EVT_CMD_OUTPUT
+from core import globalvar
+from core.debug import Debug
+from core.gcmd import GMessage, GWarning, GError, RunCommand
+from core.utils import GetSettingsPath, _
+from core.gconsole import CmdThread, GStderr, EVT_CMD_DONE, EVT_CMD_OUTPUT
 
 from gui_core.gselect import Select
 
 from web_services.widgets import WSPanel, WSManageSettingsWidget
 
+
 class WSDialogBase(wx.Dialog):
-    """Base class for web service dialogs. 
+    """Base class for web service dialogs.
     """
-    def __init__(self, parent, id = wx.ID_ANY,
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
 
-        wx.Dialog.__init__(self, parent, id, style = style, **kwargs)
+    def __init__(self, parent, id=wx.ID_ANY,
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
 
-        self.parent = parent 
+        wx.Dialog.__init__(self, parent, id, style=style, **kwargs)
 
+        self.parent = parent
+
         # contains panel for every web service on server
-        self.ws_panels =  {'WMS_1.1.1'  : {'panel' : None,
-                                           'label' : 'WMS 1.1.1'},
-                           'WMS_1.3.0' : {'panel' : None,
-                                          'label' : 'WMS 1.3.0'},
-                           'WMTS' : {'panel' : None,
-                                     'label' : 'WMTS'},
-                           'OnEarth' : {'panel' : None,
-                                        'label' : 'OnEarth'},
+        self.ws_panels = {'WMS_1.1.1': {'panel': None,
+                                        'label': 'WMS 1.1.1'},
+                          'WMS_1.3.0': {'panel': None,
+                                        'label': 'WMS 1.3.0'},
+                          'WMTS': {'panel': None,
+                                   'label': 'WMTS'},
+                          'OnEarth': {'panel': None,
+                                      'label': 'OnEarth'},
                           }
 
-        #TODO: should be in file
-        self.default_servers = { 'OSM-WMS-EUROPE' : ['http://watzmann-geog.urz.uni-heidelberg.de/cached/osm', '', ''],
-                                 'irs.gis-lab.info (OSM)' : ['http://irs.gis-lab.info', '', ''],
-                                 'NASA OnEarth' : ['http://onearth.jpl.nasa.gov/wms.cgi', '', '']
-                               }
+        # TODO: should be in file
+        self.default_servers = {
+            'OSM-WMS-EUROPE':
+            ['http://watzmann-geog.urz.uni-heidelberg.de/cached/osm', '', ''],
+            'irs.gis-lab.info (OSM)': ['http://irs.gis-lab.info', '', ''],
+            'NASA OnEarth': ['http://onearth.jpl.nasa.gov/wms.cgi', '', '']}
 
         # holds reference to web service panel which is showed
         self.active_ws_panel = None
@@ -72,7 +75,8 @@
         # buttons which are disabled when the dialog is not connected
         self.run_btns = []
 
-        # stores error messages for GError dialog showed when all web service connections were unsuccessful
+        # stores error messages for GError dialog showed when all web service
+        # connections were unsuccessful
         self.error_msgs = ''
 
         self._createWidgets()
@@ -82,20 +86,20 @@
 
         settingsFile = os.path.join(GetSettingsPath(), 'wxWS')
 
-        self.settsManager = WSManageSettingsWidget(parent=self,
-                                                 settingsFile=settingsFile,
-                                                 default_servers=self.default_servers)
+        self.settsManager = WSManageSettingsWidget(
+            parent=self, settingsFile=settingsFile,
+            default_servers=self.default_servers)
 
-        self.settingsBox = wx.StaticBox(parent = self, 
-                                        id = wx.ID_ANY,
-                                        label = _(" Server settings "))
-        
-        self.serverText = wx.StaticText(parent = self, 
-                                        id = wx.ID_ANY, label = _("Server:"))
-        self.server  = wx.TextCtrl(parent = self, id = wx.ID_ANY)
+        self.settingsBox = wx.StaticBox(parent=self,
+                                        id=wx.ID_ANY,
+                                        label=_(" Server settings "))
 
-        self.btn_connect = wx.Button(parent = self, 
-                                     id = wx.ID_ANY, label = _("&Connect"))
+        self.serverText = wx.StaticText(parent=self,
+                                        id=wx.ID_ANY, label=_("Server:"))
+        self.server = wx.TextCtrl(parent=self, id=wx.ID_ANY)
+
+        self.btn_connect = wx.Button(parent=self,
+                                     id=wx.ID_ANY, label=_("&Connect"))
         self.btn_connect.SetToolTipString(_("Connect to the server"))
         if not self.server.GetValue():
             self.btn_connect.Enable(False)
@@ -103,38 +107,44 @@
         self.infoCollapseLabelExp = _('Show advanced connection settings')
         self.infoCollapseLabelCol = _('Hide advanced connection settings')
 
-        self.adv_conn = wx.CollapsiblePane(parent = self,
-                                           label = self.infoCollapseLabelExp,
-                                           style = wx.CP_DEFAULT_STYLE |
-                                                   wx.CP_NO_TLW_RESIZE | wx.EXPAND)
+        self.adv_conn = wx.CollapsiblePane(parent=self,
+                                           label=self.infoCollapseLabelExp,
+                                           style=wx.CP_DEFAULT_STYLE |
+                                           wx.CP_NO_TLW_RESIZE | wx.EXPAND)
 
-        self.MakeAdvConnPane(pane = self.adv_conn.GetPane())
+        self.MakeAdvConnPane(pane=self.adv_conn.GetPane())
         self.adv_conn.Collapse(True)
-        self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnAdvConnPaneChanged, self.adv_conn) 
+        self.Bind(
+            wx.EVT_COLLAPSIBLEPANE_CHANGED,
+            self.OnAdvConnPaneChanged,
+            self.adv_conn)
 
-        self.reqDataPanel = wx.Panel(parent = self, id = wx.ID_ANY)
+        self.reqDataPanel = wx.Panel(parent=self, id=wx.ID_ANY)
 
-        self.layerNameBox = wx.StaticBox(parent = self.reqDataPanel, 
-                                         id = wx.ID_ANY,
-                                         label = _(" Layer Manager Settings "))
+        self.layerNameBox = wx.StaticBox(parent=self.reqDataPanel,
+                                         id=wx.ID_ANY,
+                                         label=_(" Layer Manager Settings "))
 
-        self.layerNameText = wx.StaticText(parent = self.reqDataPanel, id = wx.ID_ANY, 
-                                           label = _("Output layer name:"))
-        self.layerName = wx.TextCtrl(parent = self.reqDataPanel, id = wx.ID_ANY)
+        self.layerNameText = wx.StaticText(
+            parent=self.reqDataPanel, id=wx.ID_ANY,
+            label=_("Output layer name:"))
+        self.layerName = wx.TextCtrl(parent=self.reqDataPanel, id=wx.ID_ANY)
 
         for ws in self.ws_panels.iterkeys():
             # set class WSPanel argument layerNameTxtCtrl
-            self.ws_panels[ws]['panel'] =  WSPanel(parent = self.reqDataPanel,
-                                                   web_service = ws)
-            self.ws_panels[ws]['panel'].capParsed.connect(self.OnPanelCapParsed)
-            self.ws_panels[ws]['panel'].layerSelected.connect(self.OnLayerSelected)
+            self.ws_panels[ws]['panel'] = WSPanel(parent=self.reqDataPanel,
+                                                  web_service=ws)
+            self.ws_panels[ws]['panel'].capParsed.connect(
+                self.OnPanelCapParsed)
+            self.ws_panels[ws]['panel'].layerSelected.connect(
+                self.OnLayerSelected)
 
         # buttons
-        self.btn_close = wx.Button(parent = self, id = wx.ID_CLOSE)
+        self.btn_close = wx.Button(parent=self, id=wx.ID_CLOSE)
         self.btn_close.SetToolTipString(_("Close dialog"))
-        
+
         # statusbar
-        self.statusbar = wx.StatusBar(parent = self, id = wx.ID_ANY)
+        self.statusbar = wx.StatusBar(parent=self, id=wx.ID_ANY)
 
         # bindings
         self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
@@ -156,72 +166,75 @@
 
         dialogSizer = wx.BoxSizer(wx.VERTICAL)
 
-        dialogSizer.Add(item = self.settsManager, proportion = 0,
-                        flag = wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border = 5)
-        
+        dialogSizer.Add(item=self.settsManager, proportion=0,
+                        flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=5)
+
         # connectin settings
         settingsSizer = wx.StaticBoxSizer(self.settingsBox, wx.VERTICAL)
-        
-        serverSizer = wx.FlexGridSizer(cols = 3, vgap = 5, hgap = 5)
 
-        serverSizer.Add(item = self.serverText,
-                      flag = wx.ALIGN_CENTER_VERTICAL)
+        serverSizer = wx.FlexGridSizer(cols=3, vgap=5, hgap=5)
+
+        serverSizer.Add(item=self.serverText,
+                        flag=wx.ALIGN_CENTER_VERTICAL)
         serverSizer.AddGrowableCol(1)
-        serverSizer.Add(item = self.server,
-                      flag = wx.EXPAND | wx.ALL)
+        serverSizer.Add(item=self.server,
+                        flag=wx.EXPAND | wx.ALL)
 
-        serverSizer.Add(item = self.btn_connect)
+        serverSizer.Add(item=self.btn_connect)
 
-        settingsSizer.Add(item = serverSizer, proportion = 0,
-                          flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
-        
-        settingsSizer.Add(item = self.adv_conn,
-                          flag = wx.ALL | wx.EXPAND, border = 5)
+        settingsSizer.Add(item=serverSizer, proportion=0,
+                          flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5)
 
-        dialogSizer.Add(item = settingsSizer, proportion = 0,
-                        flag = wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border = 5)
+        settingsSizer.Add(item=self.adv_conn,
+                          flag=wx.ALL | wx.EXPAND, border=5)
 
+        dialogSizer.Add(item=settingsSizer, proportion=0,
+                        flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=5)
+
         # layer name, parsed capabilites
 
         reqDataSizer = wx.BoxSizer(wx.VERTICAL)
 
         layerNameSizer = wx.StaticBoxSizer(self.layerNameBox, wx.HORIZONTAL)
 
-        layerNameSizer.Add(item = self.layerNameText,
-                           flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
+        layerNameSizer.Add(item=self.layerNameText,
+                           flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
 
-        layerNameSizer.Add(item = self.layerName, 
-                           flag = wx.EXPAND, proportion = 1)
- 
-        reqDataSizer.Add(item = layerNameSizer,
-                         flag = wx.TOP | wx.LEFT | wx.RIGHT | wx.EXPAND, border = 5)
+        layerNameSizer.Add(item=self.layerName,
+                           flag=wx.EXPAND, proportion=1)
 
+        reqDataSizer.Add(item=layerNameSizer, flag=wx.TOP |
+                         wx.LEFT | wx.RIGHT | wx.EXPAND, border=5)
+
         self.ch_ws_sizer = wx.BoxSizer(wx.VERTICAL)
 
-        reqDataSizer.Add(item = self.ch_ws_sizer, proportion = 0,
-                         flag = wx.TOP | wx.EXPAND, border = 5)
+        reqDataSizer.Add(item=self.ch_ws_sizer, proportion=0,
+                         flag=wx.TOP | wx.EXPAND, border=5)
 
         for ws in self.ws_panels.iterkeys():
-            reqDataSizer.Add(item = self.ws_panels[ws]['panel'], proportion = 1,
-                             flag = wx.TOP | wx.LEFT | wx.RIGHT | wx.EXPAND, border = 5)
+            reqDataSizer.Add(
+                item=self.ws_panels[ws]['panel'],
+                proportion=1,
+                flag=wx.TOP | wx.LEFT | wx.RIGHT | wx.EXPAND,
+                border=5)
             self.ws_panels[ws]['panel'].Hide()
 
-        dialogSizer.Add(item = self.reqDataPanel, proportion = 1,
-                        flag = wx.EXPAND)
+        dialogSizer.Add(item=self.reqDataPanel, proportion=1,
+                        flag=wx.EXPAND)
 
         self.reqDataPanel.SetSizer(reqDataSizer)
         self.reqDataPanel.Hide()
 
         # buttons
-        self.btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
+        self.btnsizer = wx.BoxSizer(orient=wx.HORIZONTAL)
 
-        self.btnsizer.Add(item = self.btn_close, proportion = 0,
-                          flag = wx.ALL | wx.ALIGN_CENTER,
-                          border = 10)
-        
-        dialogSizer.Add(item = self.btnsizer, proportion = 0,
-                        flag = wx.ALIGN_CENTER)
+        self.btnsizer.Add(item=self.btn_close, proportion=0,
+                          flag=wx.ALL | wx.ALIGN_CENTER,
+                          border=10)
 
+        dialogSizer.Add(item=self.btnsizer, proportion=0,
+                        flag=wx.ALIGN_CENTER)
+
         # expand wxWidget wx.StatusBar
         statusbarSizer = wx.BoxSizer(wx.HORIZONTAL)
         statusbarSizer.Add(item=self.statusbar, proportion=1, flag=wx.EXPAND)
@@ -239,40 +252,40 @@
     def MakeAdvConnPane(self, pane):
         """Create advanced connection settings pane
         """
-        self.usernameText = wx.StaticText(parent = pane,
-                                          id = wx.ID_ANY, label = _("Username:"))
-        self.username  = wx.TextCtrl(parent = pane, id = wx.ID_ANY)
+        self.usernameText = wx.StaticText(parent=pane,
+                                          id=wx.ID_ANY, label=_("Username:"))
+        self.username = wx.TextCtrl(parent=pane, id=wx.ID_ANY)
 
-        self.passwText = wx.StaticText(parent = pane, 
-                                        id = wx.ID_ANY, label = _("Password:"))
-        self.password  = wx.TextCtrl(parent = pane, id = wx.ID_ANY,
-                                     style = wx.TE_PASSWORD)
+        self.passwText = wx.StaticText(parent=pane,
+                                       id=wx.ID_ANY, label=_("Password:"))
+        self.password = wx.TextCtrl(parent=pane, id=wx.ID_ANY,
+                                    style=wx.TE_PASSWORD)
 
         # pane layout
         adv_conn_sizer = wx.BoxSizer(wx.VERTICAL)
 
         usernameSizer = wx.BoxSizer(wx.HORIZONTAL)
 
-        usernameSizer.Add(item = self.usernameText,
-                          flag = wx.ALIGN_CENTER_VERTICAL, border = 5)
+        usernameSizer.Add(item=self.usernameText,
+                          flag=wx.ALIGN_CENTER_VERTICAL, border=5)
 
-        usernameSizer.Add(item = self.username, proportion = 1, 
-                          flag = wx.EXPAND, border = 5)
+        usernameSizer.Add(item=self.username, proportion=1,
+                          flag=wx.EXPAND, border=5)
 
-        adv_conn_sizer.Add(item = usernameSizer,
-                           flag = wx.ALL | wx.EXPAND, border = 5)
+        adv_conn_sizer.Add(item=usernameSizer,
+                           flag=wx.ALL | wx.EXPAND, border=5)
 
         passwSizer = wx.BoxSizer(wx.HORIZONTAL)
 
-        passwSizer.Add(item = self.passwText,
-                       flag = wx.ALIGN_CENTER_VERTICAL, border = 5)
+        passwSizer.Add(item=self.passwText,
+                       flag=wx.ALIGN_CENTER_VERTICAL, border=5)
 
-        passwSizer.Add(item = self.password, proportion = 1, 
-                       flag = wx.EXPAND, border = 5)
+        passwSizer.Add(item=self.password, proportion=1,
+                       flag=wx.EXPAND, border=5)
 
-        adv_conn_sizer.Add(item = passwSizer,
-                           flag = wx.ALL | wx.EXPAND, border = 5)
-        
+        adv_conn_sizer.Add(item=passwSizer,
+                           flag=wx.ALL | wx.EXPAND, border=5)
+
         pane.SetSizer(adv_conn_sizer)
         adv_conn_sizer.Fit(pane)
 
@@ -284,8 +297,8 @@
         """
         server = self.server.GetValue().strip()
         if not server:
-            GMessage(parent = self,
-                     message = _("No data source defined, settings are not saved."))
+            GMessage(parent=self, message=_(
+                "No data source defined, settings are not saved."))
             return
 
         self.settsManager.SetDataToSave((server,
@@ -338,7 +351,7 @@
             self.btn_connect.Enable(True)
         else:
             self.btn_connect.Enable(False)
-        
+
         # clear content of the wxWidget wx.TextCtrl (Output Layer
         # name:), based on changing content of the wxWidget
         # wx.TextCtrl (Server:)
@@ -358,7 +371,7 @@
         """
         server = self.server.GetValue().strip()
 
-        self.ch_ws_sizer.Clear(deleteWindows = True)
+        self.ch_ws_sizer.Clear(deleteWindows=True)
 
         if self.active_ws_panel is not None:
             self.reqDataPanel.Hide()
@@ -369,21 +382,22 @@
             self.Layout()
             self.Fit()
 
-        self.statusbar.SetStatusText(_("Connecting to <%s>..." % self.server.GetValue().strip()))
+        self.statusbar.SetStatusText(
+            _("Connecting to <%s>..." % self.server.GetValue().strip()))
 
         # number of panels already connected
         self.finished_panels_num = 0
         for ws in self.ws_panels.iterkeys():
-            self.ws_panels[ws]['panel'].ConnectToServer(url = server,
-                                                        username = self.username.GetValue(),
-                                                        password = self.password.GetValue())
+            self.ws_panels[ws]['panel'].ConnectToServer(
+                url=server, username=self.username.GetValue(),
+                password=self.password.GetValue())
             self.ws_panels[ws]['panel'].Hide()
-        
+
     def OnPanelCapParsed(self, error_msg):
         """Called when panel has downloaded and parsed capabilities file.
         """
         # how many web service panels are finished
-        self.finished_panels_num +=  1
+        self.finished_panels_num += 1
 
         if error_msg:
             self.error_msgs += '\n' + error_msg
@@ -392,9 +406,10 @@
         if self.finished_panels_num == len(self.ws_panels):
             self.UpdateDialogAfterConnection()
 
-            # show error dialog only if connections to all web services were unsuccessful
+            # show error dialog only if connections to all web services were
+            # unsuccessful
             if not self._getConnectedWS() and self.error_msgs:
-                GError(self.error_msgs, parent = self)
+                GError(self.error_msgs, parent=self)
             self.error_msgs = ''
 
             self.Layout()
@@ -402,7 +417,7 @@
 
     def _getConnectedWS(self):
         """
-        :return: list of found web services on server (identified as keys in self.ws_panels) 
+        :return: list of found web services on server (identified as keys in self.ws_panels)
         """
         conn_ws = []
         for ws, data in self.ws_panels.iteritems():
@@ -414,7 +429,7 @@
     def UpdateDialogAfterConnection(self):
         """Update dialog after all web service panels downloaded and parsed capabilities data.
         """
-        avail_ws = {}        
+        avail_ws = {}
         conn_ws = self._getConnectedWS()
 
         for ws in conn_ws:
@@ -434,21 +449,28 @@
                     self.web_service_sel.append(ws)
                     self.rb_choices.append(avail_ws[ws]['label'])
 
-            self.choose_ws_rb = wx.RadioBox(parent = self.reqDataPanel, id = wx.ID_ANY, 
-                                            label = _("Available web services"), 
-                                            pos = wx.DefaultPosition, choices = self.rb_choices, 
-                                            majorDimension = 1, style = wx.RA_SPECIFY_ROWS)
-        
+            self.choose_ws_rb = wx.RadioBox(
+                parent=self.reqDataPanel, id=wx.ID_ANY,
+                label=_("Available web services"),
+                pos=wx.DefaultPosition, choices=self.rb_choices,
+                majorDimension=1, style=wx.RA_SPECIFY_ROWS)
+
             self.Bind(wx.EVT_RADIOBOX, self.OnChooseWs, self.choose_ws_rb)
-            self.ch_ws_sizer.Add(item = self.choose_ws_rb,
-                                 flag = wx.TOP | wx.LEFT | wx.RIGHT | wx.EXPAND, border = 5)
-            self._showWsPanel(self.web_service_sel[self.choose_ws_rb.GetSelection()])
-            self.statusbar.SetStatusText(_("Connected to <%s>" % self.server.GetValue().strip()))
+            self.ch_ws_sizer.Add(
+                item=self.choose_ws_rb,
+                flag=wx.TOP | wx.LEFT | wx.RIGHT | wx.EXPAND,
+                border=5)
+            self._showWsPanel(
+                self.web_service_sel[
+                    self.choose_ws_rb.GetSelection()])
+            self.statusbar.SetStatusText(
+                _("Connected to <%s>" % self.server.GetValue().strip()))
             for btn in self.run_btns:
                 btn.Enable(True)
         # no web service found on server
         else:
-            self.statusbar.SetStatusText(_("Unable to connect to <%s>" % self.server.GetValue().strip()))
+            self.statusbar.SetStatusText(
+                _("Unable to connect to <%s>" % self.server.GetValue().strip()))
             for btn in self.run_btns:
                 btn.Enable(False)
             self.reqDataPanel.Hide()
@@ -457,7 +479,7 @@
     def OnChooseWs(self, event):
         """Show panel corresponding to selected web service.
         """
-        choosen_r = event.GetInt() 
+        choosen_r = event.GetInt()
         self._showWsPanel(self.web_service_sel[choosen_r])
 
     def _showWsPanel(self, ws):
@@ -484,14 +506,20 @@
         self.SendSizeEvent()
         self.Fit()
 
+
 class AddWSDialog(WSDialogBase):
     """Dialog for adding web service layer."""
-    def __init__(self, parent, giface, id = wx.ID_ANY,
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
 
-        WSDialogBase.__init__(self, parent, id = wx.ID_ANY,
-                              style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs)
+    def __init__(self, parent, giface, id=wx.ID_ANY,
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
 
+        WSDialogBase.__init__(
+            self,
+            parent,
+            id=wx.ID_ANY,
+            style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
+            **kwargs)
+
         self.SetTitle(_("Add web service layer"))
 
         self.parent = parent
@@ -502,19 +530,23 @@
 
         WSDialogBase._createWidgets(self)
 
-        self.btn_add = wx.Button(parent = self, id = wx.ID_ANY, label = _("&Add layer"))
-        self.btn_add.SetToolTipString(_("Add selected web service layers as map layer into layer tree"))        
+        self.btn_add = wx.Button(
+            parent=self,
+            id=wx.ID_ANY,
+            label=_("&Add layer"))
+        self.btn_add.SetToolTipString(
+            _("Add selected web service layers as map layer into layer tree"))
         self.btn_add.Enable(False)
-        
+
         self.run_btns.append(self.btn_add)
 
     def _doLayout(self):
 
         WSDialogBase._doLayout(self)
 
-        self.btnsizer.Add(item = self.btn_add, proportion = 0,
-                          flag = wx.ALL | wx.ALIGN_CENTER,
-                          border = 10)
+        self.btnsizer.Add(item=self.btn_add, proportion=0,
+                          flag=wx.ALL | wx.ALIGN_CENTER,
+                          border=10)
 
         # bindings
         self.btn_add.Bind(wx.EVT_BUTTON, self.OnAddLayer)
@@ -534,7 +566,7 @@
         """
         # add layer
         if self.active_ws_panel is None:
-            return 
+            return
 
         lcmd = self.active_ws_panel.CreateCmd()
         if not lcmd:
@@ -554,36 +586,37 @@
 
         active_ws = self.active_ws_panel.GetWebService()
         if 'WMS' not in active_ws:
-            cap_file =  self.active_ws_panel.GetCapFile()
+            cap_file = self.active_ws_panel.GetCapFile()
             cmd_cap_file = grass.tempfile()
             shutil.copyfile(cap_file, cmd_cap_file)
             lcmd.append('capfile=' + cmd_cap_file)
 
-        layer = ltree.AddLayer(ltype = 'wms',
-                               lname = self.active_ws_panel.GetOutputLayerName(), 
-                               lchecked = True, lcmd = lcmd)
+        layer = ltree.AddLayer(ltype='wms',
+                               lname=self.active_ws_panel.GetOutputLayerName(),
+                               lchecked=True, lcmd=lcmd)
 
-
         ws_cap_files = self._getCapFiles()
         # create properties dialog
-        cmd_list = ltree.GetLayerInfo(layer,'cmd')
+        cmd_list = ltree.GetLayerInfo(layer, 'cmd')
         cmd = cmdlist_to_tuple(cmd_list)
 
-        prop_win = WSPropertiesDialog(parent = self.parent,
-                                      giface = self.giface,
-                                      id = wx.ID_ANY,
-                                      layer = layer,
-                                      ws_cap_files = ws_cap_files,
-                                      cmd = cmd)
+        prop_win = WSPropertiesDialog(parent=self.parent,
+                                      giface=self.giface,
+                                      id=wx.ID_ANY,
+                                      layer=layer,
+                                      ws_cap_files=ws_cap_files,
+                                      cmd=cmd)
 
         prop_win.Hide()
-        ltree.GetOptData(dcmd = None, layer = layer, 
-                         params = None, propwin = prop_win)
+        ltree.GetOptData(dcmd=None, layer=layer,
+                         params=None, propwin=prop_win)
 
+
 class WSPropertiesDialog(WSDialogBase):
     """Dialog for editing web service properties."""
-    def __init__(self, parent, giface, layer, ws_cap_files, cmd, id = wx.ID_ANY,
-                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
+
+    def __init__(self, parent, giface, layer, ws_cap_files, cmd, id=wx.ID_ANY,
+                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
         """
         :param giface: grass interface
         :param layer: layer tree item
@@ -593,8 +626,12 @@
         it is possible (cmp parameters exists in parsed web service cap_file)
         """
 
-        WSDialogBase.__init__(self, parent, id = wx.ID_ANY,
-                               style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs)
+        WSDialogBase.__init__(
+            self,
+            parent,
+            id=wx.ID_ANY,
+            style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
+            **kwargs)
 
         self.SetTitle(_("Web service layer properties"))
 
@@ -602,7 +639,7 @@
         self.giface = giface
 
         # after web service panels are connected, set dialog widgets
-        # according to cmd in this variable (if it is not None) 
+        # according to cmd in this variable (if it is not None)
         self.cmd_to_set = None
 
         # store data needed for reverting
@@ -611,8 +648,9 @@
 
         ws_cap = self._getWSfromCmd(cmd)
         for ws in self.ws_panels.iterkeys():
-            # cap file used in cmd will be deleted, thnaks to the dialogs destructor
-            if ws == ws_cap and cmd[1].has_key('capfile'):
+            # cap file used in cmd will be deleted, thnaks to the dialogs
+            # destructor
+            if ws == ws_cap and 'capfile' in cmd[1]:
                 self.revert_ws_cap_files[ws] = cmd[1]['capfile']
                 del ws_cap_files[ws]
             else:
@@ -620,7 +658,7 @@
 
         self._setRevertCapFiles(ws_cap_files)
 
-        self.LoadCapFiles(ws_cap_files = self.revert_ws_cap_files, cmd = cmd)
+        self.LoadCapFiles(ws_cap_files=self.revert_ws_cap_files, cmd=cmd)
         self.btn_ok.SetDefault()
 
     def __del__(self):
@@ -641,12 +679,13 @@
 
         WSDialogBase._createWidgets(self)
 
-        self.btn_apply = wx.Button(parent = self, id = wx.ID_ANY, label = _("&Apply"))
-        self.btn_apply.SetToolTipString(_("Apply changes"))        
+        self.btn_apply = wx.Button(
+            parent=self, id=wx.ID_ANY, label=_("&Apply"))
+        self.btn_apply.SetToolTipString(_("Apply changes"))
         self.btn_apply.Enable(False)
         self.run_btns.append(self.btn_apply)
 
-        self.btn_ok = wx.Button(parent = self, id = wx.ID_ANY, label = _("&OK"))
+        self.btn_ok = wx.Button(parent=self, id=wx.ID_ANY, label=_("&OK"))
         self.btn_ok.SetToolTipString(_("Apply changes and close dialog"))
         self.btn_ok.Enable(False)
         self.run_btns.append(self.btn_ok)
@@ -655,13 +694,13 @@
 
         WSDialogBase._doLayout(self)
 
-        self.btnsizer.Add(item = self.btn_apply, proportion = 0,
-                          flag = wx.ALL | wx.ALIGN_CENTER,
-                          border = 10)
+        self.btnsizer.Add(item=self.btn_apply, proportion=0,
+                          flag=wx.ALL | wx.ALIGN_CENTER,
+                          border=10)
 
-        self.btnsizer.Add(item = self.btn_ok, proportion = 0,
-                          flag = wx.ALL | wx.ALIGN_CENTER,
-                          border = 10)
+        self.btnsizer.Add(item=self.btn_ok, proportion=0,
+                          flag=wx.ALL | wx.ALIGN_CENTER,
+                          border=10)
 
         # bindings
         self.btn_apply.Bind(wx.EVT_BUTTON, self.OnApply)
@@ -672,7 +711,7 @@
 
         For parameters description, see the constructor.
         """
-        self.ch_ws_sizer.Clear(deleteWindows = True)
+        self.ch_ws_sizer.Clear(deleteWindows=True)
 
         self.cmd_to_set = cmd
 
@@ -689,21 +728,21 @@
         for ws, data in self.ws_panels.iteritems():
             cap_file = None
 
-            if ws_cap_files.has_key(ws):
+            if ws in ws_cap_files:
                 cap_file = ws_cap_files[ws]
 
-            data['panel'].ParseCapFile(url = conn['url'], 
-                                       username = conn['password'], 
-                                       password = conn['username'], 
-                                       cap_file = cap_file)
+            data['panel'].ParseCapFile(url=conn['url'],
+                                       username=conn['password'],
+                                       password=conn['username'],
+                                       cap_file=cap_file)
 
     def _getServerConnFromCmd(self, cmd):
-        """Get url/server/passwod from cmd tuple 
+        """Get url/server/passwod from cmd tuple
         """
-        conn = { 'url' : '', 'username' : '', 'password' : ''}
-        
+        conn = {'url': '', 'username': '', 'password': ''}
+
         for k in conn.iterkeys():
-            if cmd[1].has_key(k):
+            if k in cmd[1]:
                 conn[k] = cmd[1][k]
         return conn
 
@@ -717,12 +756,12 @@
         if 'WMS' not in active_ws:
             lcmd.append('capfile=' + self.revert_ws_cap_files[active_ws])
 
-        self.giface.GetLayerTree().GetOptData(dcmd = lcmd, 
-                                              layer = self.layer, 
-                                              params = None,
-                                              propwin = self)
+        self.giface.GetLayerTree().GetOptData(dcmd=lcmd,
+                                              layer=self.layer,
+                                              params=None,
+                                              propwin=self)
 
-        #TODO use just list or tuple
+        # TODO use just list or tuple
         cmd = cmdlist_to_tuple(lcmd)
         self.revert_cmd = cmd
         self._setRevertCapFiles(self._getCapFiles())
@@ -738,7 +777,7 @@
         else:
             self.btn_connect.SetDefault()
 
-    def OnApply(self, event):   
+    def OnApply(self, event):
         self._apply()
 
     def OnSave(self, event):
@@ -752,8 +791,8 @@
     def _close(self):
         """Hide dialog"""
         self.Hide()
-        self.LoadCapFiles(cmd = self.revert_cmd,
-                          ws_cap_files = self.revert_ws_cap_files)
+        self.LoadCapFiles(cmd=self.revert_cmd,
+                          ws_cap_files=self.revert_ws_cap_files)
 
     def OnPanelCapParsed(self, error_msg):
         """Called when panel has downloaded and parsed capabilities file.
@@ -778,21 +817,26 @@
     def _getWSfromCmd(self, cmd):
         driver = cmd[1]['driver']
         ws = driver.split('_')[0]
-        
+
         if ws == 'WMS':
             ws += '_' + cmd[1]['wms_version']
         return ws
 
+
 class SaveWMSLayerDialog(wx.Dialog):
     """Dialog for saving web service layer into GRASS vector/raster layer.
 
     .. todo::
         Implement saving data in region of map display.
     """
+
     def __init__(self, parent, layer, giface):
-        
-        wx.Dialog.__init__(self, parent = parent, title = ("Save web service layer as raster map"), id = wx.ID_ANY)
 
+        wx.Dialog.__init__(
+            self, parent=parent,
+            title=("Save web service layer as raster map"),
+            id=wx.ID_ANY)
+
         self.layer = layer
         self._giface = giface
 
@@ -808,47 +852,60 @@
         self.labels = {}
         self.params = {}
 
-        self.labels['output'] = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Name for output raster map:"))
+        self.labels['output'] = wx.StaticText(
+            parent=self, id=wx.ID_ANY, label=_("Name for output raster map:"))
 
-        self.params['output'] = Select(parent = self, type = 'raster', mapsets = [grass.gisenv()['MAPSET']],
-                                       size = globalvar.DIALOG_GSELECT_SIZE)
+        self.params['output'] = Select(
+            parent=self,
+            type='raster',
+            mapsets=[
+                grass.gisenv()['MAPSET']],
+            size=globalvar.DIALOG_GSELECT_SIZE)
 
-        self.regionStBoxLabel = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                                             label = " %s " % _("Export region"))
+        self.regionStBoxLabel = wx.StaticBox(parent=self, id=wx.ID_ANY,
+                                             label=" %s " % _("Export region"))
 
         self.region_types_order = ['display', 'comp', 'named']
-        self.region_types =  {}
-        self.region_types['display'] = wx.RadioButton(parent=self, label=_("Map display"),
-                                                      style=wx.RB_GROUP)
-        self.region_types['comp'] = wx.RadioButton(parent=self, label=_("Computational region"))
-        self.region_types['named'] = wx.RadioButton(parent=self, label=_("Named region"))
-        self.region_types['display'].SetToolTipString(_("Extent and resolution"
-                                                        " are based on Map Display geometry."))
-        self.region_types['comp'].SetToolTipString(_("Extent and resolution"
-                                                     " are based on computational region."))
-        self.region_types['named'].SetToolTipString(_("Extent and resolution"
-                                                      " are based on named region."))
-        self.region_types['display'].SetValue(True)  # set default as map display
+        self.region_types = {}
+        self.region_types['display'] = wx.RadioButton(
+            parent=self, label=_("Map display"), style=wx.RB_GROUP)
+        self.region_types['comp'] = wx.RadioButton(
+            parent=self, label=_("Computational region"))
+        self.region_types['named'] = wx.RadioButton(
+            parent=self, label=_("Named region"))
+        self.region_types['display'].SetToolTipString(
+            _("Extent and resolution" " are based on Map Display geometry."))
+        self.region_types['comp'].SetToolTipString(
+            _("Extent and resolution" " are based on computational region."))
+        self.region_types['named'].SetToolTipString(
+            _("Extent and resolution" " are based on named region."))
+        self.region_types['display'].SetValue(
+            True)  # set default as map display
 
-        self.overwrite  = wx.CheckBox(parent = self, id = wx.ID_ANY,
-                                      label = _("Overwrite existing raster map"))
+        self.overwrite = wx.CheckBox(parent=self, id=wx.ID_ANY,
+                                     label=_("Overwrite existing raster map"))
 
-        self.named_reg_panel = wx.Panel(parent = self, id = wx.ID_ANY)
-        self.labels['region'] = wx.StaticText(parent = self.named_reg_panel, id = wx.ID_ANY, 
-                                             label = _("Choose named region:"))
+        self.named_reg_panel = wx.Panel(parent=self, id=wx.ID_ANY)
+        self.labels['region'] = wx.StaticText(
+            parent=self.named_reg_panel, id=wx.ID_ANY,
+            label=_("Choose named region:"))
 
-        self.params['region'] = Select(parent = self.named_reg_panel, type = 'region',
-                                       size = globalvar.DIALOG_GSELECT_SIZE)
+        self.params['region'] = Select(
+            parent=self.named_reg_panel, type='region',
+            size=globalvar.DIALOG_GSELECT_SIZE)
 
         # buttons
-        self.btn_close = wx.Button(parent = self, id = wx.ID_CLOSE)
+        self.btn_close = wx.Button(parent=self, id=wx.ID_CLOSE)
         self.btn_close.SetToolTipString(_("Close dialog"))
 
-        self.btn_ok = wx.Button(parent=self, id=wx.ID_OK, label=_("&Save layer"))
+        self.btn_ok = wx.Button(
+            parent=self,
+            id=wx.ID_OK,
+            label=_("&Save layer"))
         self.btn_ok.SetToolTipString(_("Save web service layer as raster map"))
 
         # statusbar
-        self.statusbar = wx.StatusBar(parent = self, id = wx.ID_ANY)
+        self.statusbar = wx.StatusBar(parent=self, id=wx.ID_ANY)
 
         self._layout()
 
@@ -859,40 +916,44 @@
 
         regionSizer = wx.BoxSizer(wx.HORIZONTAL)
 
-        dialogSizer.Add(item = self._addSelectSizer(title = self.labels['output'], 
-                                                    sel = self.params['output']))
+        dialogSizer.Add(item=self._addSelectSizer(title=self.labels['output'],
+                                                  sel=self.params['output']))
 
         regionSizer = wx.StaticBoxSizer(self.regionStBoxLabel, wx.VERTICAL)
 
         regionTypeSizer = wx.BoxSizer(wx.HORIZONTAL)
         for r_type in self.region_types_order:
-            regionTypeSizer.Add(item=self.region_types[r_type], flag=wx.RIGHT, border=8)
+            regionTypeSizer.Add(
+                item=self.region_types[r_type],
+                flag=wx.RIGHT, border=8)
 
-        regionSizer.Add(item = regionTypeSizer)
+        regionSizer.Add(item=regionTypeSizer)
 
-        self.named_reg_panel.SetSizer(self._addSelectSizer(title = self.labels['region'],
-                                                            sel = self.params['region']))
-        regionSizer.Add(item = self.named_reg_panel)
+        self.named_reg_panel.SetSizer(
+            self._addSelectSizer(
+                title=self.labels['region'],
+                sel=self.params['region']))
+        regionSizer.Add(item=self.named_reg_panel)
         self.named_reg_panel.Hide()
 
-        dialogSizer.Add(item = regionSizer, flag = wx.EXPAND)
+        dialogSizer.Add(item=regionSizer, flag=wx.EXPAND)
 
         dialogSizer.Add(item=self.overwrite, flag=wx.TOP, border=10)
 
         # buttons
-        self.btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
+        self.btnsizer = wx.BoxSizer(orient=wx.HORIZONTAL)
 
-        self.btnsizer.Add(item = self.btn_close, proportion = 0,
-                          flag = wx.ALL | wx.ALIGN_CENTER,
-                          border = 10)
-        
-        self.btnsizer.Add(item = self.btn_ok, proportion = 0,
-                          flag = wx.ALL | wx.ALIGN_CENTER,
-                          border = 10)
+        self.btnsizer.Add(item=self.btn_close, proportion=0,
+                          flag=wx.ALL | wx.ALIGN_CENTER,
+                          border=10)
 
-        dialogSizer.Add(item = self.btnsizer, proportion = 0,
-                        flag = wx.ALIGN_CENTER)
+        self.btnsizer.Add(item=self.btn_ok, proportion=0,
+                          flag=wx.ALL | wx.ALIGN_CENTER,
+                          border=10)
 
+        dialogSizer.Add(item=self.btnsizer, proportion=0,
+                        flag=wx.ALIGN_CENTER)
+
         self._border.Add(item=dialogSizer, proportion=0,
                          flag=wx.ALL, border=5)
 
@@ -906,27 +967,30 @@
         self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
         self.btn_ok.Bind(wx.EVT_BUTTON, self.OnSave)
 
-        self.Bind(EVT_CMD_DONE,   self.OnCmdDone)
+        self.Bind(EVT_CMD_DONE, self.OnCmdDone)
         self.Bind(EVT_CMD_OUTPUT, self.OnCmdOutput)
 
         for r_type in self.region_types_order:
-            self.Bind(wx.EVT_RADIOBUTTON, self.OnRegionType, self.region_types[r_type])
+            self.Bind(
+                wx.EVT_RADIOBUTTON,
+                self.OnRegionType,
+                self.region_types[r_type])
 
-    def _addSelectSizer(self, title, sel): 
+    def _addSelectSizer(self, title, sel):
         """Helper layout function.
         """
-        selSizer = wx.BoxSizer(orient = wx.VERTICAL)
+        selSizer = wx.BoxSizer(orient=wx.VERTICAL)
 
         selTitleSizer = wx.BoxSizer(wx.HORIZONTAL)
-        selTitleSizer.Add(item = title, proportion = 1,
-                          flag = wx.LEFT | wx.TOP | wx.EXPAND, border = 5)
+        selTitleSizer.Add(item=title, proportion=1,
+                          flag=wx.LEFT | wx.TOP | wx.EXPAND, border=5)
 
-        selSizer.Add(item = selTitleSizer, proportion = 0,
-                     flag = wx.EXPAND)
+        selSizer.Add(item=selTitleSizer, proportion=0,
+                     flag=wx.EXPAND)
 
-        selSizer.Add(item = sel, proportion = 1,
-                     flag = wx.EXPAND | wx.ALL| wx.ALIGN_CENTER_VERTICAL,
-                     border = 5)
+        selSizer.Add(item=sel, proportion=1,
+                     flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER_VERTICAL,
+                     border=5)
 
         return selSizer
 
@@ -950,9 +1014,9 @@
     def OnSave(self, event):
         """Import WMS raster data into GRASS as raster layer.
         """
-        self.thread.abort(abortall = True)
+        self.thread.abort(abortall=True)
         currmapset = grass.gisenv()['MAPSET']
-        
+
         self.output = self.params['output'].GetValue().strip()
         l_spl = self.output.strip().split("@")
 
@@ -962,21 +1026,20 @@
             msg = _('Missing output raster.')
 
         elif len(l_spl) > 1 and \
-             l_spl[1] != currmapset:
-                msg = _('Output map can be added only to current mapset.')
+                l_spl[1] != currmapset:
+            msg = _('Output map can be added only to current mapset.')
 
         elif not self.overwrite.IsChecked() and\
-            grass.find_file(self.output, 'cell', '.')['fullname']:
+                grass.find_file(self.output, 'cell', '.')['fullname']:
             msg = _('Output map <%s> already exists' % self.output)
 
         if msg:
-            GMessage(parent = self,
-                     message = msg)
+            GMessage(parent=self,
+                     message=msg)
             return
 
         self.output = l_spl[0]
 
-
         # check region
         region = self.params['region'].GetValue().strip()
         reg_spl = region.strip().split("@")
@@ -986,8 +1049,11 @@
             reg_mapset = reg_spl[1]
 
         if self.region_types['named'].GetValue():
-            if not grass.find_file(reg_spl[0], 'windows', reg_mapset)['fullname']:
-                msg = _('Region <%s> does not exist.' % self.params['region'].GetValue())
+            if not grass.find_file(reg_spl[0], 'windows', reg_mapset)[
+                    'fullname']:
+                msg = _(
+                    'Region <%s> does not exist.' %
+                    self.params['region'].GetValue())
                 GWarning(parent=self,
                          message=msg)
                 return
@@ -995,7 +1061,7 @@
         # create r.in.wms command
         cmd = ('r.in.wms', deepcopy(self.cmd[1]))
 
-        if cmd[1].has_key('map'):
+        if 'map' in cmd[1]:
             del cmd[1]['map']
 
         cmd[1]['output'] = self.output
@@ -1044,7 +1110,7 @@
             if event.type == 'error':
                 msg = _('Unable to fetch data.\n')
                 msg += event.text
-                GWarning(parent = self,
-                         message = msg)
+                GWarning(parent=self,
+                         message=msg)
         else:
             Debug.msg(1, event.text)

Modified: grass/trunk/gui/wxpython/web_services/widgets.py
===================================================================
--- grass/trunk/gui/wxpython/web_services/widgets.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/web_services/widgets.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -23,25 +23,25 @@
 from copy import deepcopy
 try:
     from xml.etree.ElementTree import ParseError
-except ImportError: # < Python 2.7
+except ImportError:  # < Python 2.7
     from xml.parsers.expat import ExpatError as ParseError
 
 import wx
-import wx.lib.flatnotebook    as FN
-import wx.lib.colourselect    as csel
+import wx.lib.flatnotebook as FN
+import wx.lib.colourselect as csel
 import wx.lib.mixins.listctrl as listmix
-from   wx.lib.newevent        import NewEvent
-from   wx.gizmos              import TreeListCtrl
+from wx.lib.newevent import NewEvent
+from wx.gizmos import TreeListCtrl
 
-from core              import globalvar
-from core.debug        import Debug
-from core.gcmd         import GWarning, GMessage
-from core.gconsole     import CmdThread, GStderr, EVT_CMD_DONE, EVT_CMD_OUTPUT
+from core import globalvar
+from core.debug import Debug
+from core.gcmd import GWarning, GMessage
+from core.gconsole import CmdThread, GStderr, EVT_CMD_DONE, EVT_CMD_OUTPUT
 from core.utils import _
 
 from web_services.cap_interface import WMSCapabilities, WMTSCapabilities, OnEarthCapabilities
 
-from gui_core.widgets  import GNotebook
+from gui_core.widgets import GNotebook
 from gui_core.widgets import ManageSettingsWidget
 
 import grass.script as grass
@@ -51,11 +51,13 @@
     sys.path.append(rinwms_path)
 
 from wms_base import WMSDriversInfo
-from srs import Srs 
+from srs import Srs
 
 from grass.pydispatch.signal import Signal
 
+
 class WSPanel(wx.Panel):
+
     def __init__(self, parent, web_service, **kwargs):
         """Show data from capabilities file.
 
@@ -65,7 +67,7 @@
         :param parent:  parent widget
         :param web_service:  web service to be panel generated for
         """
-        wx.Panel.__init__(self, parent = parent, id = wx.ID_ANY)
+        wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)
 
         self.parent = parent
         self.ws = web_service
@@ -95,34 +97,40 @@
         self.drv_props = self.drv_info.GetDrvProperties(self.ws)
 
         self.ws_drvs = {
-                        'WMS_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',
-                                                 'driver=WMS_GRASS'],
-                                        'cap_parser' : lambda temp_file : WMSCapabilities(temp_file, '1.3.0'),
-                                      },
-                        'WMTS' :      {
-                                        'cmd' : ['driver=WMTS_GRASS'],
-                                        'cap_parser' : WMTSCapabilities,
-                                      },
-                        'OnEarth' : {
-                                        'cmd' : ['driver=OnEarth_GRASS'],
-                                        'cap_parser' : OnEarthCapabilities,
-                                      }
-                      }
+            'WMS_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',
+                    'driver=WMS_GRASS'],
+                'cap_parser': lambda temp_file: WMSCapabilities(
+                    temp_file,
+                    '1.3.0'),
+            },
+            'WMTS': {
+                'cmd': ['driver=WMTS_GRASS'],
+                'cap_parser': WMTSCapabilities,
+            },
+            'OnEarth': {
+                'cmd': ['driver=OnEarth_GRASS'],
+                'cap_parser': OnEarthCapabilities,
+            }}
 
         self.cmdStdErr = GStderr(self)
         self.cmd_thread = CmdThread(self)
         self.cap_file = grass.tempfile()
 
-        reqDataBox = wx.StaticBox(parent=self, label=_(" Requested data settings "))
+        reqDataBox = wx.StaticBox(
+            parent=self, label=_(" Requested data settings "))
         self._nb_sizer = wx.StaticBoxSizer(reqDataBox, wx.VERTICAL)
-        self.notebook = GNotebook(parent = self,
-                                  style = FN.FNB_FANCY_TABS | FN.FNB_NO_X_BUTTON)
+        self.notebook = GNotebook(parent=self,
+                                  style=FN.FNB_FANCY_TABS | FN.FNB_NO_X_BUTTON)
 
         self._requestPage()
         self._advancedSettsPage()
@@ -135,7 +143,7 @@
         self.Bind(EVT_CMD_OUTPUT, self.OnCmdOutput)
 
     def __del__(self):
-        self.cmd_thread.abort(abortall =True)
+        self.cmd_thread.abort(abortall=True)
         grass.try_remove(self.cap_file)
 
     def _layout(self):
@@ -144,13 +152,13 @@
 
     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,
+        self.req_page_panel = wx.Panel(parent=self, id=wx.ID_ANY)
+        self.notebook.AddPage(page=self.req_page_panel,
                               text=_('Request'),
-                              name = 'request')
+                              name='request')
 
         # list of layers
-        self.layersBox = wx.StaticBox(parent = self.req_page_panel, id = wx.ID_ANY,
+        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
@@ -159,16 +167,19 @@
         if 'WMS' not in self.ws:
             style = style | wx.TR_HIDE_ROOT
 
-        self.list = LayersList(parent = self.req_page_panel,
-                               web_service = self.ws,
-                               style = style)
+        self.list = LayersList(parent=self.req_page_panel,
+                               web_service=self.ws,
+                               style=style)
 
         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)
+        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)
 
@@ -177,29 +188,44 @@
 
         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)
+        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)
+        self.req_page_sizer.Add(
+            item=layersSizer,
+            proportion=1,
+            flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
+            border=5)
 
         self.source_sizer = wx.BoxSizer(wx.HORIZONTAL)
 
         if self.params['format'] is not None:
-            self.source_sizer.Add(item = self.params['format'],
-                                  flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
+            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.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_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):
+    def enableButtons(self, enable=True):
         """Enable/disable up, down, buttons
         """
         self.btnUp.Enable(enable)
@@ -208,46 +234,59 @@
     def _advancedSettsPage(self):
         """Create advanced settings page
         """
-        #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,
+        # 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'),
-                              name = 'adv_req_setts')
+                              name='adv_req_setts')
 
         labels = {}
         self.l_odrder_list = None
         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 = [],
-                                                                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"))
+            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=[],
+                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"))
 
             self.btnUp.Bind(wx.EVT_BUTTON, self.OnUp)
             self.btnDown.Bind(wx.EVT_BUTTON, self.OnDown)
 
-        labels['method'] = wx.StaticText(parent = adv_setts_panel, id = wx.ID_ANY,
-                                         label = _("Reprojection method:"))
+        labels['method'] = wx.StaticText(parent=adv_setts_panel, id=wx.ID_ANY,
+                                         label=_("Reprojection method:"))
 
         self.reproj_methods = ['nearest', 'linear', 'cubic', 'cubicspline']
-        self.params['method'] = wx.Choice(parent = adv_setts_panel, id = wx.ID_ANY,
-                                          choices = [_('Nearest neighbor'), _('Linear interpolation'),
-                                                     _('Cubic interpolation'), _('Cubic spline interpolation')])
+        self.params['method'] = wx.Choice(
+            parent=adv_setts_panel,
+            id=wx.ID_ANY,
+            choices=[
+                _('Nearest neighbor'),
+                _('Linear interpolation'),
+                _('Cubic interpolation'),
+                _('Cubic spline interpolation')])
 
-        labels['maxcols'] = wx.StaticText(parent = adv_setts_panel, id = wx.ID_ANY,
-                                          label = _("Maximum columns to request from server at time:"))
-        self.params['maxcols'] = wx.SpinCtrl(parent = adv_setts_panel, id = wx.ID_ANY, size = (100, -1))
+        labels['maxcols'] = wx.StaticText(
+            parent=adv_setts_panel, id=wx.ID_ANY,
+            label=_("Maximum columns to request from server at time:"))
+        self.params['maxcols'] = wx.SpinCtrl(
+            parent=adv_setts_panel, id=wx.ID_ANY, size=(100, -1))
 
-        labels['maxrows'] = wx.StaticText(parent = adv_setts_panel, id = wx.ID_ANY,
-                                          label = _("Maximum rows to request from server at time:"))
-        self.params['maxrows'] = wx.SpinCtrl(parent = adv_setts_panel, id = wx.ID_ANY, size = (100, -1))
+        labels['maxrows'] = wx.StaticText(
+            parent=adv_setts_panel, id=wx.ID_ANY,
+            label=_("Maximum rows to request from server at time:"))
+        self.params['maxrows'] = wx.SpinCtrl(
+            parent=adv_setts_panel, id=wx.ID_ANY, size=(100, -1))
 
         min = 100
         max = 10000
-        self.params['maxcols'].SetRange(min,max)
-        self.params['maxrows'].SetRange(min,max)
+        self.params['maxcols'].SetRange(min, max)
+        self.params['maxrows'].SetRange(min, max)
 
         val = 500
         self.params['maxcols'].SetValue(val)
@@ -255,22 +294,26 @@
 
         self.flags['o'] = self.params['bgcolor'] = None
         if not 'o' in self.drv_props['ignored_flags']:
-            self.flags['o']  = wx.CheckBox(parent = adv_setts_panel, id = wx.ID_ANY,
-                                           label = _("Do not request transparent data"))
+            self.flags['o'] = wx.CheckBox(
+                parent=adv_setts_panel, id=wx.ID_ANY,
+                label=_("Do not request transparent data"))
 
             self.flags['o'].Bind(wx.EVT_CHECKBOX, self.OnTransparent)
-            labels['bgcolor'] = wx.StaticText(parent = adv_setts_panel, id = wx.ID_ANY,
-                                              label = _("Background color:"))
-            self.params['bgcolor'] = csel.ColourSelect(parent = adv_setts_panel, id = wx.ID_ANY,
-                                                       colour = (255, 255, 255),
-                                                       size = globalvar.DIALOG_COLOR_SIZE)
+            labels['bgcolor'] = wx.StaticText(
+                parent=adv_setts_panel, id=wx.ID_ANY,
+                label=_("Background color:"))
+            self.params['bgcolor'] = csel.ColourSelect(
+                parent=adv_setts_panel, id=wx.ID_ANY, colour=(
+                    255, 255, 255), size=globalvar.DIALOG_COLOR_SIZE)
             self.params['bgcolor'].Enable(False)
 
         self.params['urlparams'] = None
         if self.params['urlparams'] not in self.drv_props['ignored_params']:
-            labels['urlparams'] = wx.StaticText(parent = adv_setts_panel, id = wx.ID_ANY,
-                                                label = _("Additional query parameters for server:"))
-            self.params['urlparams'] = wx.TextCtrl(parent = adv_setts_panel, id = wx.ID_ANY)
+            labels['urlparams'] = wx.StaticText(
+                parent=adv_setts_panel, id=wx.ID_ANY,
+                label=_("Additional query parameters for server:"))
+            self.params['urlparams'] = wx.TextCtrl(
+                parent=adv_setts_panel, id=wx.ID_ANY)
 
         # layout
 
@@ -279,89 +322,89 @@
         if 'WMS' in self.ws:
 
             boxSizer = wx.StaticBoxSizer(labels['l_order'], wx.VERTICAL)
-            gridSizer  =  wx.GridBagSizer (hgap = 3, vgap = 3)
+            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,
-                          border = 0)
+                          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,
-                          border = 0)
+                          pos=(0, 1),
+                          flag=wx.ALIGN_CENTER_VERTICAL,
+                          border=0)
 
             gridSizer.Add(self.btnDown,
-                          pos = (1,1),
-                          flag = wx.ALIGN_CENTER_VERTICAL,
-                          border = 0)
+                          pos=(1, 1),
+                          flag=wx.ALIGN_CENTER_VERTICAL,
+                          border=0)
 
             gridSizer.AddGrowableCol(0)
             boxSizer.Add(gridSizer,
-                         flag = wx.EXPAND | wx.ALL,
-                         border = 5)
+                         flag=wx.EXPAND | wx.ALL,
+                         border=5)
 
-            border.Add(item = boxSizer,
-                       flag = wx.LEFT | wx.RIGHT | wx.UP | wx.EXPAND,
-                       border = 5)
+            border.Add(item=boxSizer,
+                       flag=wx.LEFT | wx.RIGHT | wx.UP | wx.EXPAND,
+                       border=5)
 
-        gridSizer  =  wx.GridBagSizer (hgap = 3, vgap = 3)
+        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
 
         row = 0
         for k in ['method', 'maxcols', 'maxrows', 'o', 'bgcolor']:
 
-            if self.params.has_key(k):
+            if k in self.params:
                 param = self.params[k]
-            elif self.flags.has_key(k):
+            elif k in self.flags:
                 param = self.flags[k]
 
             if param is None:
                 continue
 
-            if labels.has_key(k) or k == 'o':
+            if k in labels or k == 'o':
                 if k != 'o':
                     label = labels[k]
                 else:
                     label = param
 
                 gridSizer.Add(label,
-                              flag = wx.ALIGN_LEFT |
+                              flag=wx.ALIGN_LEFT |
                               wx.ALIGN_CENTER_VERTICAL,
-                              pos = (row, 0))
+                              pos=(row, 0))
 
             if k != 'o':
-                gridSizer.Add(item = param,
-                              flag = wx.ALIGN_RIGHT |
+                gridSizer.Add(item=param,
+                              flag=wx.ALIGN_RIGHT |
                               wx.ALIGN_CENTER_VERTICAL,
-                              pos = (row, 1))
+                              pos=(row, 1))
             row += 1
 
         gridSizer.AddGrowableCol(0)
-        border.Add(item = gridSizer,
-                   flag = wx.LEFT | wx.RIGHT | wx.TOP | wx.EXPAND,
-                   border = 5)
+        border.Add(item=gridSizer,
+                   flag=wx.LEFT | wx.RIGHT | wx.TOP | wx.EXPAND,
+                   border=5)
 
         if self.params['urlparams']:
-            gridSizer  =  wx.GridBagSizer (hgap = 3, vgap = 3)
-            
+            gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
+
             row = 0
             gridSizer.Add(labels['urlparams'],
-                          flag = wx.ALIGN_LEFT |
+                          flag=wx.ALIGN_LEFT |
                           wx.ALIGN_CENTER_VERTICAL,
-                          pos = (row, 0))
-            
-            gridSizer.Add(item = self.params['urlparams'],
-                          flag = wx.ALIGN_RIGHT |
+                          pos=(row, 0))
+
+            gridSizer.Add(item=self.params['urlparams'],
+                          flag=wx.ALIGN_RIGHT |
                           wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
-                          pos = (row, 1))
-            
+                          pos=(row, 1))
+
             gridSizer.AddGrowableCol(1)
-            
-            border.Add(item = gridSizer,
-                       flag = wx.LEFT | wx.RIGHT | wx.TOP | wx.EXPAND,
-                       border = 5)
 
+            border.Add(item=gridSizer,
+                       flag=wx.LEFT | wx.RIGHT | wx.TOP | wx.EXPAND,
+                       border=5)
+
         adv_setts_panel.SetSizer(border)
 
     def OnUp(self, event):
@@ -372,9 +415,9 @@
             if 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)
+                self._updateLayerOrderList(selected=0)
 
     def OnDown(self, event):
         """Move selected to down
@@ -383,12 +426,12 @@
             pos = self.l_odrder_list.GetSelection()
             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))
+            if pos < len(self.sel_layers) - 1:
+                self._updateLayerOrderList(selected=(pos + 1))
             else:
-                self._updateLayerOrderList(selected = len(self.sel_layers) -1)
+                self._updateLayerOrderList(selected=len(self.sel_layers) - 1)
 
-    def _updateLayerOrderList(self, selected = None):
+    def _updateLayerOrderList(self, selected=None):
         """Update order in list.
         """
         def getlayercaption(layer):
@@ -432,10 +475,14 @@
         :type password: str
         """
         self._prepareForNewConn(url, username, password)
-        cap_cmd = ['r.in.wms', '-c', ('capfile_output=%s' % self.cap_file), '--overwrite'] + self.ws_cmdl
+        cap_cmd = [
+            'r.in.wms',
+            '-c',
+            ('capfile_output=%s' % self.cap_file),
+            '--overwrite'] + self.ws_cmdl
 
         self.currentPid = self.cmd_thread.GetId()
-        self.cmd_thread.RunCmd(cap_cmd, stderr = self.cmdStdErr)
+        self.cmd_thread.RunCmd(cap_cmd, stderr=self.cmdStdErr)
 
     def OnCmdOutput(self, event):
         """Manage cmd output.
@@ -455,15 +502,15 @@
         self.projs_list = []
 
         self.conn = {
-                        'url' : url,
-                        'password' : password,
-                        'username' : username
-                    }
+            'url': url,
+            'password': password,
+            'username': username
+        }
 
         conn_cmd = []
         for k, v in self.conn.iteritems():
             if v:
-                conn_cmd.append("%s=%s" % (k,v))
+                conn_cmd.append("%s=%s" % (k, v))
 
         self.ws_cmdl = self.ws_drvs[self.ws]['cmd'] + conn_cmd
 
@@ -476,9 +523,11 @@
 
         if event.returncode != 0:
             if self.cmd_err_str:
-                self.cmd_err_str = _("Unable to download %s capabilities file\nfrom <%s>:\n" %  \
-                                         (self.ws.replace('_', ' '), self.conn['url'])) + self.cmd_err_str
-            self._postCapParsedEvt(error_msg = self.cmd_err_str)
+                self.cmd_err_str = _(
+                    "Unable to download %s capabilities file\nfrom <%s>:\n" %
+                    (self.ws.replace('_', ' '),
+                     self.conn['url'])) + self.cmd_err_str
+            self._postCapParsedEvt(error_msg=self.cmd_err_str)
             self.cmd_err_str = ''
             return
 
@@ -491,13 +540,14 @@
         try:
             self.cap = self.ws_drvs[self.ws]['cap_parser'](cap_file)
         except (IOError, ParseError) as error:
-            error_msg = _("%s web service was not found in fetched capabilities file from <%s>:\n%s\n" % \
-                        (self.ws, self.conn['url'], str(error)))
+            error_msg = _(
+                "%s web service was not found in fetched capabilities file from <%s>:\n%s\n" %
+                (self.ws, self.conn['url'], str(error)))
             if Debug.GetLevel() != 0:
-              Debug.msg(1, error_msg)
-              self._postCapParsedEvt(None)
+                Debug.msg(1, error_msg)
+                self._postCapParsedEvt(None)
             else:
-              self._postCapParsedEvt(error_msg = error_msg)
+                self._postCapParsedEvt(error_msg=error_msg)
             return
 
         self.is_connected = True
@@ -509,11 +559,11 @@
             self._setDefaultFormatVal()
 
         self.list.LoadData(self.cap)
-        self.OnListSelChanged(event = None)
+        self.OnListSelChanged(event=None)
 
         self._postCapParsedEvt(None)
 
-    def ParseCapFile(self, url, username, password, cap_file = None,):
+    def ParseCapFile(self, url, username, password, cap_file=None,):
         """Parse capabilities data and emits capParsed signal
         (see class constructor).
         """
@@ -537,11 +587,11 @@
 
         layers = []
 
-        if dcmd.has_key('layers'):
+        if 'layers' in dcmd:
             layers = dcmd['layers']
 
         styles = []
-        if dcmd.has_key('styles'):
+        if 'styles' in dcmd:
             styles = dcmd['styles']
 
         if 'WMS' in self.ws:
@@ -556,8 +606,8 @@
 
         l_st_list = []
         for i in range(len(layers)):
-            l_st_list.append({'style' : styles[i],
-                              'layer' : layers[i]})
+            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
@@ -565,30 +615,33 @@
         self.list.SelectLayers(l_st_list)
 
         params = {}
-        if  dcmd.has_key('format'):
+        if 'format' in dcmd:
             params['format'] = dcmd['format']
-        if  dcmd.has_key('srs'):
+        if 'srs' in dcmd:
             params['srs'] = 'EPSG:' + dcmd['srs']
-        if  dcmd.has_key('method'):
+        if 'method' in dcmd:
             params['method'] = dcmd['method']
 
         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):
+        for p, conv_f in [
+                ('urlparams', None),
+                ('maxcols', int),
+                ('maxrows', int)]:
+            if p in dcmd:
                 v = dcmd[p]
                 if conv_f:
                     v = conv_f(v)
                 self.params[p].SetValue(v)
 
-        if dcmd.has_key('flags') and \
+        if 'flags' in dcmd and \
            'o' in dcmd['flags']:
-           self.flags['o'].SetValue(1)
-           self.params['bgcolor'].Enable(True)
+            self.flags['o'].SetValue(1)
+            self.params['bgcolor'].Enable(True)
 
-        if dcmd.has_key('bgcolor') and \
+        if 'bgcolor' in dcmd and \
            self.params['bgcolor']:
             bgcolor = dcmd['bgcolor'].strip().lower()
             if len(bgcolor) == 8 and \
@@ -656,11 +709,15 @@
         lcmd.append('method=' + self.reproj_methods[i_method])
 
         if not 'o' in self.drv_props['ignored_flags'] and \
-            self.flags['o'].IsChecked():
+                self.flags['o'].IsChecked():
             lcmd.append('-o')
 
             c = self.params['bgcolor'].GetColour()
-            hex_color = wx.Colour(c[0], c[1], c[2]).GetAsString(wx.C2S_HTML_SYNTAX)
+            hex_color = wx.Colour(
+                c[0],
+                c[1],
+                c[2]).GetAsString(
+                wx.C2S_HTML_SYNTAX)
             lcmd.append("bgcolor=" + '0x' + hex_color[1:])
 
         lcmd.append("map=" + self.o_layer_name)
@@ -710,7 +767,7 @@
                     try:
                         int(proj_spl[1])
                         self.projs_list.append(proj_code)
-                    except ValueError, IndexError:
+                    except ValueError as IndexError:
                         continue
 
             cur_sel = self.params['srs'].GetStringSelection()
@@ -739,7 +796,9 @@
                 cur_sel = self.params['format'].GetStringSelection()
 
             if len(curr_sel_ls) > 0:
-                self.formats_list  = sorted(self._getFormats(curr_sel_ls[0]['cap_intf_l']))
+                self.formats_list = sorted(
+                    self._getFormats(
+                        curr_sel_ls[0]['cap_intf_l']))
                 self._updateFormatRadioBox(self.formats_list)
 
                 if cur_sel:
@@ -765,10 +824,14 @@
             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,
-                                                 style = wx.RA_SPECIFY_COLS)
+            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)
@@ -843,13 +906,14 @@
 
 
 class LayersList(TreeListCtrl, listmix.ListCtrlAutoWidthMixin):
+
     def __init__(self, parent, web_service, style, pos=wx.DefaultPosition):
         """List of layers and styles available in capabilities file
         """
         self.parent = parent
         self.ws = web_service
 
-        TreeListCtrl.__init__(self, parent = parent, id = wx.ID_ANY, style = style)
+        TreeListCtrl.__init__(self, parent=parent, id=wx.ID_ANY, style=style)
 
         # setup mixins
         listmix.ListCtrlAutoWidthMixin.__init__(self)
@@ -859,7 +923,7 @@
         else:
             self.AddColumn(_('Layer name'))
 
-        self.SetMainColumn(0) # column with the tree
+        self.SetMainColumn(0)  # column with the tree
         self.setResizeColumn(0)
 
         self.root = None
@@ -867,7 +931,7 @@
 
         self.layerSelected = Signal('LayersList.layerSelected')
 
-    def LoadData(self, cap = None):
+    def LoadData(self, cap=None):
         """Load data into list
         """
         # detete first all items
@@ -916,13 +980,13 @@
                     if self.ws != 'OnEarth':
                         self.SetItemText(style_item, _('style'), 1)
 
-                    self.SetPyData(style_item, {'type' : 'style',
-                                                'layer' : layer, # it is parent layer of style
-                                                'style' : st})
+                    self.SetPyData(style_item, {'type': '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
+                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
 
             if parent_layer is None:
                 parent_layer = cap.GetRootLayer()
@@ -936,7 +1000,7 @@
                 AddLayerChildrenToTree(layer, item)
 
         AddLayerChildrenToTree(None, None)
-        #self.ExpandAll(self.GetRootItem())
+        # self.ExpandAll(self.GetRootItem())
 
     def GetSelectedLayers(self):
         """Get selected layers/styles in LayersList
@@ -956,11 +1020,11 @@
             except ValueError:
                 continue
             sel_layers_dict.append({
-                                    'name' : layer.GetLayerData('name'),
-                                    'title' : layer.GetLayerData('title'),
-                                    'style' : self.GetPyData(s)['style'],
-                                    'cap_intf_l' : layer
-                                    })
+                'name': layer.GetLayerData('name'),
+                'title': layer.GetLayerData('title'),
+                'style': self.GetPyData(s)['style'],
+                'cap_intf_l': layer
+            })
         return sel_layers_dict
 
     def OnListSelChanging(self, event):
@@ -968,7 +1032,7 @@
         """
         def _emitSelected(layer):
             title = layer.GetLayerData('title')
-            self.layerSelected.emit(title = title)
+            self.layerSelected.emit(title=title)
 
         def _selectRequestableChildren(item, list_to_check, items_to_sel):
 
@@ -976,7 +1040,7 @@
             child_item, cookie = self.GetFirstChild(item)
             while child_item.IsOk():
                 if  self.GetPyData(child_item)['layer'].IsRequestable() \
-                    and not self.IsSelected(child_item):
+                        and not self.IsSelected(child_item):
                     items_to_sel.append(child_item)
                 elif not self.GetPyData(child_item)['layer'].IsRequestable():
                     list_to_check.append(child_item)
@@ -997,7 +1061,8 @@
             chck_item = cur_item
 
             while True:
-                _selectRequestableChildren(chck_item, items_to_chck, items_to_sel)
+                _selectRequestableChildren(
+                    chck_item, items_to_chck, items_to_sel)
                 if items_to_chck:
                     chck_item = items_to_chck.pop()
                 else:
@@ -1027,12 +1092,11 @@
         def checknext(item, l_st_list, items_to_sel):
             def compare(item, l_name, st_name):
                 it_l_name = self.GetPyData(item)['layer'].GetLayerData('name')
-                it_st  = self.GetPyData(item)['style']
+                it_st = self.GetPyData(item)['style']
                 it_type = self.GetPyData(item)['type']
 
-                if it_l_name == l_name and \
-                 (   (not it_st and not st_name) or \
-                     (it_st and it_st['name'] == st_name and it_type == 'style')):
+                if it_l_name == l_name and ((not it_st and not st_name) or (
+                        it_st and it_st['name'] == st_name and it_type == 'style')):
 
                     return True
 
@@ -1076,7 +1140,9 @@
 
         return l_st_list
 
+
 class WSManageSettingsWidget(ManageSettingsWidget):
+
     def __init__(self, parent, settingsFile, default_servers):
 
         ManageSettingsWidget.__init__(self, parent, settingsFile)
@@ -1085,7 +1151,7 @@
     def _layout(self):
 
         self.btnAddDefaultServers = wx.Button(parent=self, id=wx.ID_ANY,
-                                             label=_("Add default"))
+                                              label=_("Add default"))
         self.btnAddDefaultServers.Bind(wx.EVT_BUTTON, self.OnAddDefaultServers)
 
         ManageSettingsWidget._layout(self)

Modified: grass/trunk/gui/wxpython/wxgui.py
===================================================================
--- grass/trunk/gui/wxpython/wxgui.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/wxgui.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -36,17 +36,18 @@
 
 
 class GMApp(wx.App):
+
     def __init__(self, workspace=None):
         """ Main GUI class.
 
         :param workspace: path to the workspace file
         """
         self.workspaceFile = workspace
-        
+
         # call parent class initializer
         wx.App.__init__(self, False)
 
-        self.locale = wx.Locale(language = wx.LANGUAGE_DEFAULT)
+        self.locale = wx.Locale(language=wx.LANGUAGE_DEFAULT)
 
     def OnInit(self):
         """ Initialize all available image handlers
@@ -58,21 +59,30 @@
 
         # create splash screen
         introImagePath = os.path.join(globalvar.IMGDIR, "splash_screen.png")
-        introImage     = wx.Image(introImagePath, wx.BITMAP_TYPE_PNG)
-        introBmp       = introImage.ConvertToBitmap()
+        introImage = wx.Image(introImagePath, wx.BITMAP_TYPE_PNG)
+        introBmp = introImage.ConvertToBitmap()
         if SC and sys.platform != 'darwin':
             # AdvancedSplash is buggy on the Mac as of 2.8.12.1
-            # and raises annoying (though seemingly harmless) errors everytime the GUI is started
-            splash = SC.AdvancedSplash(bitmap = introBmp,
-                                       timeout = 2000, parent = None, id = wx.ID_ANY)
+            # and raises annoying (though seemingly harmless) errors everytime
+            # the GUI is started
+            splash = SC.AdvancedSplash(bitmap=introBmp,
+                                       timeout=2000, parent=None, id=wx.ID_ANY)
             splash.SetText(_('Starting GRASS GUI...'))
             splash.SetTextColour(wx.Colour(45, 52, 27))
-            splash.SetTextFont(wx.Font(pointSize = 15, family = wx.DEFAULT, style = wx.NORMAL,
-                                       weight = wx.BOLD))
+            splash.SetTextFont(
+                wx.Font(
+                    pointSize=15,
+                    family=wx.DEFAULT,
+                    style=wx.NORMAL,
+                    weight=wx.BOLD))
             splash.SetTextPosition((150, 430))
         else:
-            wx.SplashScreen (bitmap = introBmp, splashStyle = wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT,
-                             milliseconds = 2000, parent = None, id = wx.ID_ANY)
+            wx.SplashScreen(
+                bitmap=introBmp,
+                splashStyle=wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT,
+                milliseconds=2000,
+                parent=None,
+                id=wx.ID_ANY)
 
         wx.Yield()
 
@@ -111,11 +121,13 @@
 
     return workspaceFile
 
+
 def cleanup():
     unregisterPid(os.getpid())
-        
-def main(argv = None):
 
+
+def main(argv=None):
+
     if argv is None:
         argv = sys.argv
     try:
@@ -128,17 +140,17 @@
         print >> sys.stderr, err.msg
         print >> sys.stderr, "for help use --help"
         printHelp()
-    
+
     workspaceFile = process_opt(opts, args)
     app = GMApp(workspaceFile)
-    
+
     # suppress wxPython logs
     q = wx.LogNull()
     set_raise_on_error(True)
 
     # register GUI PID
     registerPid(os.getpid())
-    
+
     app.MainLoop()
 
 if __name__ == "__main__":

Modified: grass/trunk/gui/wxpython/wxplot/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/wxplot/__init__.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/wxplot/__init__.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -4,4 +4,4 @@
     'dialogs',
     'profile',
     'histogram',
-    ]
+]

Modified: grass/trunk/gui/wxpython/wxplot/base.py
===================================================================
--- grass/trunk/gui/wxpython/wxplot/base.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/wxplot/base.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -24,70 +24,89 @@
 except ImportError as e:
     print >> sys.stderr, e
 
-from core.globalvar    import ICONDIR
-from core.settings     import UserSettings
-from wxplot.dialogs    import TextDialog, OptDialog
-from core.render       import Map
-from icons.icon        import MetaIcon
+from core.globalvar import ICONDIR
+from core.settings import UserSettings
+from wxplot.dialogs import TextDialog, OptDialog
+from core.render import Map
+from icons.icon import MetaIcon
 from gui_core.toolbars import BaseIcons
 from core.utils import _
 
 import grass.script as grass
 
 PlotIcons = {
-    'draw'         : MetaIcon(img = 'show',
-                              label = _('Draw/re-draw plot')),
-    'transect'     : MetaIcon(img = 'layer-raster-profile',
-                              label = _('Draw transect in map display window to profile')),
-    'options'      : MetaIcon(img = 'settings',
-                              label = _('Plot options')),
-    'statistics'   : MetaIcon(img = 'stats',
-                              label = _('Plot statistics')),
-    'save'         : MetaIcon(img = 'save',
-                              label = _('Save profile data to CSV file')),
-    'quit'         : BaseIcons['quit'].SetLabel(_('Quit plot tool')),
-    }
+    'draw': MetaIcon(
+        img='show',
+        label=_('Draw/re-draw plot')),
+    'transect': MetaIcon(
+        img='layer-raster-profile',
+        label=_('Draw transect in map display window to profile')),
+    'options': MetaIcon(
+        img='settings',
+        label=_('Plot options')),
+    'statistics': MetaIcon(
+        img='stats',
+        label=_('Plot statistics')),
+    'save': MetaIcon(
+        img='save',
+        label=_('Save profile data to CSV file')),
+    'quit': BaseIcons['quit'].SetLabel(
+        _('Quit plot tool')),
+}
 
+
 class BasePlotFrame(wx.Frame):
     """Abstract PyPlot display frame class"""
+
     def __init__(self, parent=None, size=wx.Size(700, 400),
-                 style=wx.DEFAULT_FRAME_STYLE, rasterList=[],  **kwargs):
+                 style=wx.DEFAULT_FRAME_STYLE, rasterList=[], **kwargs):
 
-        wx.Frame.__init__(self, parent, id=wx.ID_ANY, size = size, style = style, **kwargs)
-        
-        self.parent = parent # MapFrame for a plot type
-        self.Map    = Map()             # instance of render.Map to be associated with display
-        self.rasterList = rasterList    #list of rasters to plot
+        wx.Frame.__init__(
+            self,
+            parent,
+            id=wx.ID_ANY,
+            size=size,
+            style=style,
+            **kwargs)
+
+        self.parent = parent  # MapFrame for a plot type
+        self.Map = Map()             # instance of render.Map to be associated with display
+        self.rasterList = rasterList  # list of rasters to plot
         self.raster = {}    # dictionary of raster maps and their plotting parameters
         self.plottype = ''
-        
-        self.linestyledict = { 'solid' : wx.SOLID,
-                            'dot' : wx.DOT,
-                            'long-dash' : wx.LONG_DASH,
-                            'short-dash' : wx.SHORT_DASH,
-                            'dot-dash' : wx.DOT_DASH }
 
-        self.ptfilldict = { 'transparent' : wx.TRANSPARENT,
-                            'solid' : wx.SOLID }
+        self.linestyledict = {'solid': wx.SOLID,
+                              'dot': wx.DOT,
+                              'long-dash': wx.LONG_DASH,
+                              'short-dash': wx.SHORT_DASH,
+                              'dot-dash': wx.DOT_DASH}
 
+        self.ptfilldict = {'transparent': wx.TRANSPARENT,
+                           'solid': wx.SOLID}
+
         #
         # Icon
         #
-        self.SetIcon(wx.Icon(os.path.join(ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
-                
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    ICONDIR,
+                    'grass.ico'),
+                wx.BITMAP_TYPE_ICO))
+
         #
         # Add statusbar
         #
-        self.statusbar = self.CreateStatusBar(number = 2, style = 0)
+        self.statusbar = self.CreateStatusBar(number=2, style=0)
         self.statusbar.SetStatusWidths([-2, -1])
 
         #
         # Define canvas and settings
         #
-        # 
+        #
         self.client = plot.PlotCanvas(self)
 
-        #define the function for drawing pointLabels
+        # define the function for drawing pointLabels
         self.client.SetPointLabelFunc(self.DrawPointLabel)
 
         # Create mouse event for showing cursor coords in status bar
@@ -103,62 +122,74 @@
         self.ylabel = ""        # default Y-axis label
 
         self.CentreOnScreen()
-        
+
         self._createColorDict()
 
     def _createColorDict(self):
         """Create color dictionary to return wx.Colour tuples
         for assigning colors to images in imagery groups"""
-                
+
         self.colorDict = {}
         for clr in grass.named_colors.iterkeys():
-            if clr == 'white': continue
+            if clr == 'white':
+                continue
             r = grass.named_colors[clr][0] * 255
             g = grass.named_colors[clr][1] * 255
             b = grass.named_colors[clr][2] * 255
-            self.colorDict[clr] = (r,g,b,255)
+            self.colorDict[clr] = (r, g, b, 255)
 
     def InitPlotOpts(self, plottype):
         """Initialize options for entire plot
-        """       
+        """
         self.plottype = plottype                # histogram, profile, or scatter
 
         self.properties = {}                    # plot properties
         self.properties['font'] = {}
-        self.properties['font']['prop'] = UserSettings.Get(group = self.plottype, key = 'font')
+        self.properties['font']['prop'] = UserSettings.Get(
+            group=self.plottype, key='font')
         self.properties['font']['wxfont'] = wx.Font(11, wx.FONTFAMILY_SWISS,
                                                     wx.FONTSTYLE_NORMAL,
                                                     wx.FONTWEIGHT_NORMAL)
-        
+
         self.properties['raster'] = {}
-        self.properties['raster'] = UserSettings.Get(group = self.plottype, key = 'raster')
+        self.properties['raster'] = UserSettings.Get(
+            group=self.plottype, key='raster')
         colstr = str(self.properties['raster']['pcolor'])
-        self.properties['raster']['pcolor'] = tuple(int(colval) for colval in colstr.strip('()').split(','))
+        self.properties['raster']['pcolor'] = tuple(
+            int(colval) for colval in colstr.strip('()').split(','))
 
         if self.plottype == 'profile':
-            self.properties['marker'] = UserSettings.Get(group = self.plottype, key = 'marker')
+            self.properties['marker'] = UserSettings.Get(
+                group=self.plottype, key='marker')
             # changing color string to tuple for markers/points
             colstr = str(self.properties['marker']['color'])
-            self.properties['marker']['color'] = tuple(int(colval) for colval in colstr.strip('()').split(','))
- 
+            self.properties['marker']['color'] = tuple(
+                int(colval) for colval in colstr.strip('()').split(','))
 
-        self.properties['grid'] = UserSettings.Get(group = self.plottype, key = 'grid')        
-        colstr = str(self.properties['grid']['color']) # changing color string to tuple        
-        self.properties['grid']['color'] = tuple(int(colval) for colval in colstr.strip('()').split(','))
-                
+        self.properties['grid'] = UserSettings.Get(
+            group=self.plottype, key='grid')
+        # changing color string to tuple
+        colstr = str(self.properties['grid']['color'])
+        self.properties['grid']['color'] = tuple(
+            int(colval) for colval in colstr.strip('()').split(','))
+
         self.properties['x-axis'] = {}
-        self.properties['x-axis']['prop'] = UserSettings.Get(group = self.plottype, key = 'x-axis')
+        self.properties[
+            'x-axis']['prop'] = UserSettings.Get(group=self.plottype, key='x-axis')
         self.properties['x-axis']['axis'] = None
 
         self.properties['y-axis'] = {}
-        self.properties['y-axis']['prop'] = UserSettings.Get(group = self.plottype, key = 'y-axis')
+        self.properties[
+            'y-axis']['prop'] = UserSettings.Get(group=self.plottype, key='y-axis')
         self.properties['y-axis']['axis'] = None
-        
-        self.properties['legend'] = UserSettings.Get(group = self.plottype, key = 'legend')
 
+        self.properties['legend'] = UserSettings.Get(
+            group=self.plottype, key='legend')
+
         self.zoom = False  # zooming disabled
         self.drag = False  # draging disabled
-        self.client.SetShowScrollbars(True) # vertical and horizontal scrollbars
+        # vertical and horizontal scrollbars
+        self.client.SetShowScrollbars(True)
 
         # x and y axis set to normal (non-log)
         self.client.setLogScale((False, False))
@@ -166,82 +197,87 @@
             self.client.SetXSpec(self.properties['x-axis']['prop']['type'])
         else:
             self.client.SetXSpec('auto')
-        
+
         if self.properties['y-axis']['prop']['type']:
             self.client.SetYSpec(self.properties['y-axis']['prop']['type'])
         else:
             self.client.SetYSpec('auto')
-        
+
     def InitRasterOpts(self, rasterList, plottype):
         """Initialize or update raster dictionary for plotting
         """
 
-        rdict = {} # initialize a dictionary
-        self.properties['raster'] = UserSettings.Get(group = self.plottype, key = 'raster')
+        rdict = {}  # initialize a dictionary
+        self.properties['raster'] = UserSettings.Get(
+            group=self.plottype, key='raster')
 
         for r in rasterList:
             idx = rasterList.index(r)
-            
+
             try:
                 ret = grass.raster_info(r)
             except:
                 continue
                 # if r.info cannot parse map, skip it
-               
-            self.raster[r] = self.properties['raster'] # some default settings
-            rdict[r] = {} # initialize sub-dictionaries for each raster in the list
-            
+
+            self.raster[r] = self.properties['raster']  # some default settings
+            rdict[r] = {}  # initialize sub-dictionaries for each raster in the list
+
             rdict[r]['units'] = ''
             if ret['units'] not in ('(none)', '"none"', '', None):
                 rdict[r]['units'] = ret['units']
-            
+
             rdict[r]['plegend'] = r   # use fully-qualified names
-            rdict[r]['datalist'] = [] # list of cell value,frequency pairs for plotting histogram
+            # list of cell value,frequency pairs for plotting histogram
+            rdict[r]['datalist'] = []
             rdict[r]['pline'] = None
             rdict[r]['datatype'] = ret['datatype']
 
-            #    
-            #initialize with saved values
             #
-            if self.properties['raster']['pwidth'] != None:
+            # initialize with saved values
+            #
+            if self.properties['raster']['pwidth'] is not None:
                 rdict[r]['pwidth'] = self.properties['raster']['pwidth']
             else:
                 rdict[r]['pwidth'] = 1
-                
-            if self.properties['raster']['pstyle'] != None and \
-                self.properties['raster']['pstyle'] != '':
+
+            if self.properties['raster']['pstyle'] is not None and \
+                    self.properties['raster']['pstyle'] != '':
                 rdict[r]['pstyle'] = self.properties['raster']['pstyle']
             else:
                 rdict[r]['pstyle'] = 'solid'
-                        
+
             if idx < len(self.colorList):
                 if idx == 0:
                     # use saved color for first plot
-                    if self.properties['raster']['pcolor'] != None:
-                        rdict[r]['pcolor'] = self.properties['raster']['pcolor'] 
+                    if self.properties['raster']['pcolor'] is not None:
+                        rdict[r]['pcolor'] = self.properties[
+                            'raster']['pcolor']
                     else:
-                        rdict[r]['pcolor'] = self.colorDict[self.colorList[idx]]
+                        rdict[r]['pcolor'] = self.colorDict[
+                            self.colorList[idx]]
                 else:
                     rdict[r]['pcolor'] = self.colorDict[self.colorList[idx]]
             else:
                 r = randint(0, 255)
                 b = randint(0, 255)
                 g = randint(0, 255)
-                rdict[r]['pcolor'] = ((r,g,b,255))
-        
+                rdict[r]['pcolor'] = ((r, g, b, 255))
+
         return rdict
-            
+
     def InitRasterPairs(self, rasterList, plottype):
         """Initialize or update raster dictionary with raster pairs for
             bivariate scatterplots
         """
-        
-        if len(rasterList) == 0: return
-        
-        rdict = {} # initialize a dictionary
+
+        if len(rasterList) == 0:
+            return
+
+        rdict = {}  # initialize a dictionary
         for rpair in rasterList:
             idx = rasterList.index(rpair)
-            
+
             try:
                 ret0 = grass.raster_info(rpair[0])
                 ret1 = grass.raster_info(rpair[1])
@@ -250,8 +286,10 @@
                 continue
                 # if r.info cannot parse map, skip it
 
-            self.raster[rpair] = UserSettings.Get(group = plottype, key = 'rasters') # some default settings
-            rdict[rpair] = {} # initialize sub-dictionaries for each raster in the list
+            self.raster[rpair] = UserSettings.Get(
+                group=plottype, key='rasters')  # some default settings
+            # initialize sub-dictionaries for each raster in the list
+            rdict[rpair] = {}
             rdict[rpair][0] = {}
             rdict[rpair][1] = {}
             rdict[rpair][0]['units'] = ''
@@ -261,50 +299,54 @@
                 rdict[rpair][0]['units'] = ret0['units']
             if ret1['units'] not in ('(none)', '"none"', '', None):
                 rdict[rpair][1]['units'] = ret1['units']
-                
-            rdict[rpair]['plegend'] = rpair[0].split('@')[0] + ' vs ' + rpair[1].split('@')[0]
-            rdict[rpair]['datalist'] = [] # list of cell value,frequency pairs for plotting histogram
+
+            rdict[rpair]['plegend'] = rpair[0].split(
+                '@')[0] + ' vs ' + rpair[1].split('@')[0]
+            # list of cell value,frequency pairs for plotting histogram
+            rdict[rpair]['datalist'] = []
             rdict[rpair][0]['datatype'] = ret0['datatype']
             rdict[rpair][1]['datatype'] = ret1['datatype']
-                 
-            #    
-            #initialize with saved values
+
             #
-            if self.properties['raster']['ptype'] != None and \
-                self.properties['raster']['ptype'] != '':
+            # initialize with saved values
+            #
+            if self.properties['raster']['ptype'] is not None and \
+                    self.properties['raster']['ptype'] != '':
                 rdict[rpair]['ptype'] = self.properties['raster']['ptype']
             else:
                 rdict[rpair]['ptype'] = 'dot'
-            if self.properties['raster']['psize'] != None:
+            if self.properties['raster']['psize'] is not None:
                 rdict[rpair]['psize'] = self.properties['raster']['psize']
             else:
-                 rdict[rpair]['psize'] = 1
-            if self.properties['raster']['pfill'] != None and \
-                self.properties['raster']['pfill'] != '':
+                rdict[rpair]['psize'] = 1
+            if self.properties['raster']['pfill'] is not None and \
+                    self.properties['raster']['pfill'] != '':
                 rdict[rpair]['pfill'] = self.properties['raster']['pfill']
             else:
-                 rdict[rpair]['pfill'] = 'solid'
-            
+                rdict[rpair]['pfill'] = 'solid'
+
             if idx <= len(self.colorList):
                 rdict[rpair]['pcolor'] = self.colorDict[self.colorList[idx]]
             else:
                 r = randint(0, 255)
                 b = randint(0, 255)
                 g = randint(0, 255)
-                rdict[rpair]['pcolor'] = ((r,g,b,255))
-            
+                rdict[rpair]['pcolor'] = ((r, g, b, 255))
+
         return rdict
 
     def SetGraphStyle(self):
         """Set plot and text options
         """
         self.client.SetFont(self.properties['font']['wxfont'])
-        self.client.SetFontSizeTitle(self.properties['font']['prop']['titleSize'])
-        self.client.SetFontSizeAxis(self.properties['font']['prop']['axisSize'])
+        self.client.SetFontSizeTitle(
+            self.properties['font']['prop']['titleSize'])
+        self.client.SetFontSizeAxis(
+            self.properties['font']['prop']['axisSize'])
 
         self.client.SetEnableZoom(self.zoom)
         self.client.SetEnableDrag(self.drag)
-        
+
         #
         # axis settings
         #
@@ -318,44 +360,49 @@
         else:
             self.client.SetYSpec(self.properties['y-axis']['prop'])
 
-        if self.properties['x-axis']['prop']['type'] == 'custom' and \
-               self.properties['x-axis']['prop']['min'] < self.properties['x-axis']['prop']['max']:
-            self.properties['x-axis']['axis'] = (self.properties['x-axis']['prop']['min'],
-                                                 self.properties['x-axis']['prop']['max'])
+        if self.properties['x-axis']['prop']['type'] == 'custom' and self.properties[
+                'x-axis']['prop']['min'] < self.properties['x-axis']['prop']['max']:
+            self.properties['x-axis']['axis'] = (
+                self.properties['x-axis']['prop']['min'],
+                self.properties['x-axis']['prop']['max'])
         else:
             self.properties['x-axis']['axis'] = None
 
-        if self.properties['y-axis']['prop']['type'] == 'custom' and \
-                self.properties['y-axis']['prop']['min'] < self.properties['y-axis']['prop']['max']:
-            self.properties['y-axis']['axis'] = (self.properties['y-axis']['prop']['min'],
-                                                 self.properties['y-axis']['prop']['max'])
+        if self.properties['y-axis']['prop']['type'] == 'custom' and self.properties[
+                'y-axis']['prop']['min'] < self.properties['y-axis']['prop']['max']:
+            self.properties['y-axis']['axis'] = (
+                self.properties['y-axis']['prop']['min'],
+                self.properties['y-axis']['prop']['max'])
         else:
             self.properties['y-axis']['axis'] = None
-            
+
         if self.properties['x-axis']['prop']['log'] == True:
             self.properties['x-axis']['axis'] = None
             self.client.SetXSpec('min')
         if self.properties['y-axis']['prop']['log'] == True:
             self.properties['y-axis']['axis'] = None
             self.client.SetYSpec('min')
-                        
+
         self.client.setLogScale((self.properties['x-axis']['prop']['log'],
                                  self.properties['y-axis']['prop']['log']))
-        
+
         #
         # grid settings
         #
         self.client.SetEnableGrid(self.properties['grid']['enabled'])
-                
-        self.client.SetGridColour(wx.Colour(self.properties['grid']['color'][0],
-                                           self.properties['grid']['color'][1],
-                                           self.properties['grid']['color'][2],
-                                           255))
-        
+
+        self.client.SetGridColour(
+            wx.Colour(
+                self.properties['grid']['color'][0],
+                self.properties['grid']['color'][1],
+                self.properties['grid']['color'][2],
+                255))
+
         #
         # legend settings
         #
-        self.client.SetFontSizeLegend(self.properties['font']['prop']['legendSize'])
+        self.client.SetFontSizeLegend(
+            self.properties['font']['prop']['legendSize'])
         self.client.SetEnableLegend(self.properties['legend']['enabled'])
 
     def DrawPlot(self, plotlist):
@@ -379,7 +426,7 @@
 
         self.client.Draw(self.plot, self.properties['x-axis']['axis'],
                          self.properties['y-axis']['axis'])
-                
+
     def DrawPointLabel(self, dc, mDataDict):
         """This is the fuction that defines how the pointLabels are
             plotted dc - DC that will be passed mDataDict - Dictionary
@@ -390,17 +437,19 @@
             below.  Any wxDC method can be used.
         """
         dc.SetPen(wx.Pen(wx.BLACK))
-        dc.SetBrush(wx.Brush( wx.BLACK, wx.SOLID ) )
+        dc.SetBrush(wx.Brush(wx.BLACK, wx.SOLID))
 
-        sx, sy = mDataDict["scaledXY"] #scaled x,y of closest point
-        dc.DrawRectangle( sx-5,sy-5, 10, 10)  #10by10 square centered on point
-        px,py = mDataDict["pointXY"]
+        sx, sy = mDataDict["scaledXY"]  # scaled x,y of closest point
+        # 10by10 square centered on point
+        dc.DrawRectangle(sx - 5, sy - 5, 10, 10)
+        px, py = mDataDict["pointXY"]
         cNum = mDataDict["curveNum"]
         pntIn = mDataDict["pIndex"]
         legend = mDataDict["legend"]
-        #make a string to display
-        s = "Crv# %i, '%s', Pt. (%.2f,%.2f), PtInd %i" %(cNum, legend, px, py, pntIn)
-        dc.DrawText(s, sx , sy + 1)
+        # make a string to display
+        s = "Crv# %i, '%s', Pt. (%.2f,%.2f), PtInd %i" % (
+            cNum, legend, px, py, pntIn)
+        dc.DrawText(s, sx, sy + 1)
 
     def OnZoom(self, event):
         """Enable zooming and disable dragging
@@ -424,7 +473,7 @@
         self.UpdateLabels()
         self.client.Reset()
         self.client.Redraw()
-       
+
     def OnErase(self, event):
         """Erase the plot window
         """
@@ -435,28 +484,33 @@
         """
         self.client.SaveFile()
 
-    def OnMouseLeftDown(self,event):
-        self.SetStatusText(_("Left Mouse Down at Point:") + \
-                               " (%.4f, %.4f)" % self.client._getXY(event))
-        event.Skip() # allows plotCanvas OnMouseLeftDown to be called
+    def OnMouseLeftDown(self, event):
+        self.SetStatusText(_("Left Mouse Down at Point:") +
+                           " (%.4f, %.4f)" % self.client._getXY(event))
+        event.Skip()  # allows plotCanvas OnMouseLeftDown to be called
 
     def OnMotion(self, event):
         """Indicate when mouse is outside the plot area
         """
         if self.client.GetEnablePointLabel() is True:
-            #make up dict with info for the pointLabel
-            #I've decided to mark the closest point on the closest curve
-            dlst = self.client.GetClosestPoint(self.client._getXY(event), pointScaled=True)
-            if dlst != []:      #returns [] if none
+            # make up dict with info for the pointLabel
+            # I've decided to mark the closest point on the closest curve
+            dlst = self.client.GetClosestPoint(
+                self.client._getXY(event), pointScaled=True)
+            if dlst != []:  # returns [] if none
                 curveNum, legend, pIndex, pointXY, scaledXY, distance = dlst
-                #make up dictionary to pass to my user function (see DrawPointLabel)
-                mDataDict =  {"curveNum":curveNum, "legend":legend, "pIndex":pIndex,\
-                    "pointXY":pointXY, "scaledXY":scaledXY}
-                #pass dict to update the pointLabel
+                # make up dictionary to pass to my user function (see
+                # DrawPointLabel)
+                mDataDict = {
+                    "curveNum": curveNum,
+                    "legend": legend,
+                    "pIndex": pIndex,
+                    "pointXY": pointXY,
+                    "scaledXY": scaledXY}
+                # pass dict to update the pointLabel
                 self.client.UpdatePointLabel(mDataDict)
-        event.Skip()           #go to next handler        
- 
- 
+        event.Skip()  # go to next handler
+
     def PlotOptionsMenu(self, event):
         """Popup menu for plot and text options
         """
@@ -479,17 +533,16 @@
     def NotFunctional(self):
         """Creates a 'not functional' message dialog
         """
-        dlg = wx.MessageDialog(parent = self,
-                               message = _('This feature is not yet functional'),
-                               caption = _('Under Construction'),
-                               style = wx.OK | wx.ICON_INFORMATION)
+        dlg = wx.MessageDialog(parent=self,
+                               message=_('This feature is not yet functional'),
+                               caption=_('Under Construction'),
+                               style=wx.OK | wx.ICON_INFORMATION)
         dlg.ShowModal()
         dlg.Destroy()
 
-
     def _getPlotLabels(self):
         def log(txt):
-            return "log( " + txt  + " )" 
+            return "log( " + txt + " )"
 
         x = self.xlabel
         if self.properties['x-axis']['prop']['log']:
@@ -510,15 +563,17 @@
 
         if self.plot:
             self.plot.setTitle(dlg.ptitle)
-            
-        self.OnRedraw(event = None)
-    
+
+        self.OnRedraw(event=None)
+
     def UpdateLabels(self):
         x, y = self._getPlotLabels()
 
         self.client.SetFont(self.properties['font']['wxfont'])
-        self.client.SetFontSizeTitle(self.properties['font']['prop']['titleSize'])
-        self.client.SetFontSizeAxis(self.properties['font']['prop']['axisSize'])
+        self.client.SetFontSizeTitle(
+            self.properties['font']['prop']['titleSize'])
+        self.client.SetFontSizeAxis(
+            self.properties['font']['prop']['axisSize'])
 
         if self.plot:
             self.plot.setXLabel(x)
@@ -527,27 +582,27 @@
     def PlotText(self, event):
         """Set custom text values for profile title and axis labels.
         """
-        dlg = TextDialog(parent = self, id = wx.ID_ANY, 
-                         plottype = self.plottype, 
-                         title = _('Text settings'))
-        
+        dlg = TextDialog(parent=self, id=wx.ID_ANY,
+                         plottype=self.plottype,
+                         title=_('Text settings'))
+
         btnval = dlg.ShowModal()
         if btnval == wx.ID_SAVE or btnval == wx.ID_OK or btnval == wx.ID_CANCEL:
-            dlg.Destroy()            
-        
+            dlg.Destroy()
+
     def PlotOptions(self, event):
         """Set various profile options, including: line width, color,
         style; marker size, color, fill, and style; grid and legend
         options.  Calls OptDialog class.
         """
-       
-        dlg = OptDialog(parent = self, id = wx.ID_ANY, 
-                        plottype = self.plottype, 
-                        title = _('Plot settings'))
+
+        dlg = OptDialog(parent=self, id=wx.ID_ANY,
+                        plottype=self.plottype,
+                        title=_('Plot settings'))
         btnval = dlg.ShowModal()
 
         if btnval == wx.ID_SAVE or btnval == wx.ID_OK or btnval == wx.ID_CANCEL:
-            dlg.Destroy() 
+            dlg.Destroy()
         self.Update()
 
     def PrintMenu(self, event):
@@ -561,7 +616,7 @@
             item = wx.MenuItem(printmenu, wx.ID_ANY, title)
             printmenu.AppendItem(item)
             self.Bind(wx.EVT_MENU, handler, item)
-        
+
         # Popup the menu.  If an item is selected then its handler
         # will be called before PopupMenu returns.
         self.PopupMenu(printmenu)
@@ -577,4 +632,4 @@
         self.client.Printout()
 
     def OnQuit(self, event):
-        self.Close(True)        
+        self.Close(True)

Modified: grass/trunk/gui/wxpython/wxplot/dialogs.py
===================================================================
--- grass/trunk/gui/wxpython/wxplot/dialogs.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/wxplot/dialogs.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -22,68 +22,83 @@
 import os
 
 import wx
-import wx.lib.colourselect  as csel
+import wx.lib.colourselect as csel
 import wx.lib.scrolledpanel as scrolled
 
-from core             import globalvar
-from core.settings    import UserSettings
-from core.globalvar   import ICONDIR
+from core import globalvar
+from core.settings import UserSettings
+from core.globalvar import ICONDIR
 from core.utils import _
 from gui_core.gselect import Select
 
-from grass.script import core  as grass
+from grass.script import core as grass
 
+
 class ProfileRasterDialog(wx.Dialog):
-    def __init__(self, parent, id = wx.ID_ANY, 
-                 title = _("Select raster maps to profile"),
-                 style = wx.DEFAULT_DIALOG_STYLE, **kwargs):
+
+    def __init__(self, parent, id=wx.ID_ANY,
+                 title=_("Select raster maps to profile"),
+                 style=wx.DEFAULT_DIALOG_STYLE, **kwargs):
         """Dialog to select raster maps to profile.
         """
 
-        wx.Dialog.__init__(self, parent, id, title, style = style, **kwargs)
+        wx.Dialog.__init__(self, parent, id, title, style=style, **kwargs)
 
-
         self.parent = parent
-        self.colorList = ["blue", "red", "green", "yellow", "magenta", "cyan", \
-                    "aqua", "black", "grey", "orange", "brown", "purple", "violet", \
-                    "indigo"]
+        self.colorList = [
+            "blue",
+            "red",
+            "green",
+            "yellow",
+            "magenta",
+            "cyan",
+            "aqua",
+            "black",
+            "grey",
+            "orange",
+            "brown",
+            "purple",
+            "violet",
+            "indigo"]
 
         self.rasterList = self.parent.rasterList
-        
+
         self._do_layout()
-        
+
     def _do_layout(self):
 
         sizer = wx.BoxSizer(wx.VERTICAL)
 
-        box = wx.GridBagSizer (hgap = 3, vgap = 3)
-        
+        box = wx.GridBagSizer(hgap=3, vgap=3)
+
         rastText = ''
         for r in self.rasterList:
             rastText += '%s,' % r
-            
+
         rastText = rastText.rstrip(',')
-        
+
         txt = _("Select raster map(s) to profile:")
-        label = wx.StaticText(parent = self, id = wx.ID_ANY, label = txt)
-        box.Add(item = label,
-                flag = wx.ALIGN_CENTER_VERTICAL, pos = (0, 0))
-        
-        selection = Select(self, id = wx.ID_ANY,
-                           size = globalvar.DIALOG_GSELECT_SIZE,
-                           type = 'cell', multiple=True)
+        label = wx.StaticText(parent=self, id=wx.ID_ANY, label=txt)
+        box.Add(item=label,
+                flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 0))
+
+        selection = Select(self, id=wx.ID_ANY,
+                           size=globalvar.DIALOG_GSELECT_SIZE,
+                           type='cell', multiple=True)
         selection.SetValue(rastText)
         selection.Bind(wx.EVT_TEXT, self.OnSelection)
-        
-        box.Add(item = selection, pos = (0, 1))
-            
-        sizer.Add(item = box, proportion = 0,
-                  flag = wx.ALL, border = 10)
 
-        line = wx.StaticLine(parent = self, id = wx.ID_ANY, size = (20, -1), style = wx.LI_HORIZONTAL)
-        sizer.Add(item = line, proportion = 0,
-                  flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, border = 5)
+        box.Add(item=selection, pos=(0, 1))
 
+        sizer.Add(item=box, proportion=0,
+                  flag=wx.ALL, border=10)
+
+        line = wx.StaticLine(
+            parent=self, id=wx.ID_ANY, size=(
+                20, -1), style=wx.LI_HORIZONTAL)
+        sizer.Add(item=line, proportion=0, flag=wx.GROW |
+                  wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, border=5)
+
         btnsizer = wx.StdDialogButtonSizer()
 
         btn = wx.Button(self, wx.ID_OK)
@@ -94,7 +109,11 @@
         btnsizer.AddButton(btn)
         btnsizer.Realize()
 
-        sizer.Add(item = btnsizer, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
+        sizer.Add(
+            item=btnsizer,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT | wx.ALL,
+            border=5)
 
         self.SetSizer(sizer)
         sizer.Fit(self)
@@ -102,36 +121,51 @@
     def OnSelection(self, event):
         """Choose maps to profile. Convert these into a list
         """
-        self.rasterList = self.FindWindowById(event.GetId()).GetValue().split(',')
+        self.rasterList = self.FindWindowById(
+            event.GetId()).GetValue().split(',')
 
+
 class ScatterRasterDialog(wx.Dialog):
-    def __init__(self, parent, id = wx.ID_ANY, 
-                 title = _("Select pairs of raster maps for scatterplots"),
-                 style = wx.DEFAULT_DIALOG_STYLE, **kwargs):
+
+    def __init__(self, parent, id=wx.ID_ANY,
+                 title=_("Select pairs of raster maps for scatterplots"),
+                 style=wx.DEFAULT_DIALOG_STYLE, **kwargs):
         """Dialog to select raster maps to profile.
         """
 
-        wx.Dialog.__init__(self, parent, id, title, style = style, **kwargs)
+        wx.Dialog.__init__(self, parent, id, title, style=style, **kwargs)
 
-        self.parent = parent 
+        self.parent = parent
         self.rasterList = self.parent.rasterList
         self.bins = self.parent.bins
         self.scattertype = self.parent.scattertype
         self.maptype = self.parent.maptype
-        self.spinbins = ''        
-        self.colorList = ["blue", "red", "green", "yellow", "magenta", "cyan", \
-                    "aqua", "black", "grey", "orange", "brown", "purple", "violet", \
-                    "indigo"]
-        
+        self.spinbins = ''
+        self.colorList = [
+            "blue",
+            "red",
+            "green",
+            "yellow",
+            "magenta",
+            "cyan",
+            "aqua",
+            "black",
+            "grey",
+            "orange",
+            "brown",
+            "purple",
+            "violet",
+            "indigo"]
+
         self._do_layout()
-        
+
     def _do_layout(self):
 
         sizer = wx.BoxSizer(wx.VERTICAL)
 
-        box = wx.GridBagSizer (hgap = 3, vgap = 3)
-        
-        # parse raster pair tuples 
+        box = wx.GridBagSizer(hgap=3, vgap=3)
+
+        # parse raster pair tuples
         rastText = ''
         if len(self.rasterList) > 0:
             for r in self.rasterList:
@@ -140,36 +174,38 @@
                 else:
                     rastText += '%s,' % r
             rastText = rastText.rstrip(',')
-        
+
         # select rasters
         txt = _("Select pairs of raster maps for bivariate scatterplots:")
-        label = wx.StaticText(parent = self, id = wx.ID_ANY, label = txt)
-        box.Add(item = label,
-                flag = wx.ALIGN_CENTER_VERTICAL, pos = (0, 0))
-        
-        selection = Select(self, id = wx.ID_ANY,
-                           size = globalvar.DIALOG_GSELECT_SIZE,
-                           type = 'cell', multiple=True)
+        label = wx.StaticText(parent=self, id=wx.ID_ANY, label=txt)
+        box.Add(item=label,
+                flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 0))
+
+        selection = Select(self, id=wx.ID_ANY,
+                           size=globalvar.DIALOG_GSELECT_SIZE,
+                           type='cell', multiple=True)
         selection.SetValue(rastText)
         selection.Bind(wx.EVT_TEXT, self.OnSelection)
-        
-        box.Add(item = selection, pos = (0, 1))
-            
-        # Nsteps for FP maps 
-        label = wx.StaticText(parent = self, id = wx.ID_ANY, 
-                              label = _("Number of bins (for FP maps)"))
-        box.Add(item = label,
-                flag = wx.ALIGN_CENTER_VERTICAL, pos = (1, 0))
-        self.spinbins = wx.SpinCtrl(parent = self, id = wx.ID_ANY, value = "", pos = (30, 50),
-                                      size = (100,-1), style = wx.SP_ARROW_KEYS)
-        self.spinbins.SetRange(1,1000)
+
+        box.Add(item=selection, pos=(0, 1))
+
+        # Nsteps for FP maps
+        label = wx.StaticText(parent=self, id=wx.ID_ANY,
+                              label=_("Number of bins (for FP maps)"))
+        box.Add(item=label,
+                flag=wx.ALIGN_CENTER_VERTICAL, pos=(1, 0))
+        self.spinbins = wx.SpinCtrl(
+            parent=self, id=wx.ID_ANY, value="", pos=(
+                30, 50), size=(
+                100, -1), style=wx.SP_ARROW_KEYS)
+        self.spinbins.SetRange(1, 1000)
         self.spinbins.SetValue(self.bins)
-        box.Add(item = self.spinbins,
-                flag = wx.ALIGN_CENTER_VERTICAL, pos = (1, 1))
+        box.Add(item=self.spinbins,
+                flag=wx.ALIGN_CENTER_VERTICAL, pos=(1, 1))
 
-#### TODO possibly make bubble plots with marker size proportional to cell counts
-#        # scatterplot type 
-#        label = wx.StaticText(parent = self, id = wx.ID_ANY, 
+# TODO possibly make bubble plots with marker size proportional to cell counts
+#        # scatterplot type
+#        label = wx.StaticText(parent = self, id = wx.ID_ANY,
 #                              label = _("Scatterplot type"))
 #        box.Add(item = label,
 #                flag = wx.ALIGN_CENTER_VERTICAL, pos = (2, 0))
@@ -179,14 +215,16 @@
 #        scattertype.SetStringSelection(self.scattertype)
 #        box.Add(item = scattertype,
 #                flag = wx.ALIGN_CENTER_VERTICAL, pos = (2, 1))
-          
-        sizer.Add(item = box, proportion = 0,
-                  flag = wx.ALL, border = 10)
 
-        line = wx.StaticLine(parent = self, id = wx.ID_ANY, size = (20, -1), style = wx.LI_HORIZONTAL)
-        sizer.Add(item = line, proportion = 0,
-                  flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, border = 5)
+        sizer.Add(item=box, proportion=0,
+                  flag=wx.ALL, border=10)
 
+        line = wx.StaticLine(
+            parent=self, id=wx.ID_ANY, size=(
+                20, -1), style=wx.LI_HORIZONTAL)
+        sizer.Add(item=line, proportion=0, flag=wx.GROW |
+                  wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, border=5)
+
         btnsizer = wx.StdDialogButtonSizer()
 
         btn = wx.Button(self, wx.ID_OK)
@@ -197,7 +235,11 @@
         btnsizer.AddButton(btn)
         btnsizer.Realize()
 
-        sizer.Add(item = btnsizer, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
+        sizer.Add(
+            item=btnsizer,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT | wx.ALL,
+            border=5)
 
         self.spinbins.Bind(wx.EVT_TEXT, self.OnSetBins)
         self.spinbins.Bind(wx.EVT_SPINCTRL, self.OnSetBins)
@@ -209,16 +251,17 @@
     def OnSelection(self, event):
         """Select raster maps for scatterplot. Must select maps in pairs.
         """
-        self.rasterList = self.FindWindowById(event.GetId()).GetValue().split(',', 1)
-        
+        self.rasterList = self.FindWindowById(
+            event.GetId()).GetValue().split(',', 1)
+
     def OnSetBins(self, event):
         """Bins for histogramming FP maps (=nsteps in r.stats)
         """
         self.bins = self.spinbins.GetValue()
-        
+
     def OnSetScattertypes(self, event):
         self.scattertype = event.GetString()
-        
+
     def GetRasterPairs(self):
         """Get raster pairs"""
         pairsList = list()
@@ -228,86 +271,118 @@
             if len(pair) == 2:
                 pairsList.append(tuple(pair))
                 pair = list()
-        
+
         return list(pairsList)
-    
+
     def GetSettings(self):
         """Get type and bins"""
         return self.scattertype, self.bins
-    
+
+
 class PlotStatsFrame(wx.Frame):
-    def __init__(self, parent, id, message = '', title = '',
-                 style = wx.DEFAULT_FRAME_STYLE, **kwargs):
+
+    def __init__(self, parent, id, message='', title='',
+                 style=wx.DEFAULT_FRAME_STYLE, **kwargs):
         """Dialog to display and save statistics for plots
         """
-        wx.Frame.__init__(self, parent, id, style = style, **kwargs)
+        wx.Frame.__init__(self, parent, id, style=style, **kwargs)
         self.SetLabel(_("Statistics"))
-        self.SetIcon(wx.Icon(os.path.join(ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
+        self.SetIcon(
+            wx.Icon(
+                os.path.join(
+                    ICONDIR,
+                    'grass.ico'),
+                wx.BITMAP_TYPE_ICO))
         self.panel = wx.Panel(self)
-        
-        sp = scrolled.ScrolledPanel(self.panel, -1, size=(400, 400),
-                                    style = wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER, name="Statistics" )
-                
 
+        sp = scrolled.ScrolledPanel(
+            self.panel, -1, size=(400, 400),
+            style=wx.TAB_TRAVERSAL | wx.SUNKEN_BORDER, name="Statistics")
+
         #
         # initialize variables
         #
         self.parent = parent
-        self.message = message 
-        self.title = title   
-        self.CenterOnParent()  
-        
+        self.message = message
+        self.title = title
+        self.CenterOnParent()
+
         #
         # Display statistics
         #
         sizer = wx.BoxSizer(wx.VERTICAL)
         txtSizer = wx.BoxSizer(wx.VERTICAL)
 
-        statstitle = wx.StaticText(parent = self.panel, id = wx.ID_ANY, label = self.title)
-        sizer.Add(item = statstitle, proportion = 0,
-                  flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 3)
-        line = wx.StaticLine(parent = self.panel, id = wx.ID_ANY, size = (20, -1), style = wx.LI_HORIZONTAL)
-        sizer.Add(item = line, proportion = 0,
-                  flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 3)
+        statstitle = wx.StaticText(
+            parent=self.panel,
+            id=wx.ID_ANY,
+            label=self.title)
+        sizer.Add(item=statstitle, proportion=0,
+                  flag=wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=3)
+        line = wx.StaticLine(
+            parent=self.panel, id=wx.ID_ANY, size=(
+                20, -1), style=wx.LI_HORIZONTAL)
+        sizer.Add(item=line, proportion=0,
+                  flag=wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=3)
         for stats in self.message:
-            statstxt = wx.StaticText(parent = sp, id = wx.ID_ANY, label = stats)
+            statstxt = wx.StaticText(parent=sp, id=wx.ID_ANY, label=stats)
             statstxt.SetBackgroundColour("WHITE")
-            txtSizer.Add(item = statstxt, proportion = 1, 
-                         flag = wx.EXPAND|wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, border = 3)
-            line = wx.StaticLine(parent = sp, id = wx.ID_ANY, size = (20, -1), style = wx.LI_HORIZONTAL) 
-            txtSizer.Add(item = line, proportion = 0,
-                         flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 3)      
+            txtSizer.Add(
+                item=statstxt,
+                proportion=1,
+                flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+                border=3)
+            line = wx.StaticLine(
+                parent=sp, id=wx.ID_ANY, size=(
+                    20, -1), style=wx.LI_HORIZONTAL)
+            txtSizer.Add(item=line, proportion=0, flag=wx.GROW |
+                         wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=3)
 
         sp.SetSizer(txtSizer)
         sp.SetAutoLayout(1)
-        sp.SetupScrolling() 
+        sp.SetupScrolling()
 
-        sizer.Add(item = sp, proportion = 1, 
-                  flag = wx.GROW | wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 3)
+        sizer.Add(item=sp, proportion=1,
+                  flag=wx.GROW | wx.LEFT | wx.RIGHT | wx.BOTTOM, border=3)
 
-        line = wx.StaticLine(parent = self.panel, id = wx.ID_ANY, size = (20, -1), style = wx.LI_HORIZONTAL)
-        sizer.Add(item = line, proportion = 0,
-                  flag = wx.GROW |wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, border = 3)
+        line = wx.StaticLine(
+            parent=self.panel, id=wx.ID_ANY, size=(
+                20, -1), style=wx.LI_HORIZONTAL)
+        sizer.Add(item=line, proportion=0, flag=wx.GROW |
+                  wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, border=3)
 
         #
         # buttons
         #
         btnSizer = wx.BoxSizer(wx.HORIZONTAL)
 
-        btn_clipboard = wx.Button(self.panel, id = wx.ID_COPY, label = _('C&opy'))
-        btn_clipboard.SetToolTipString(_("Copy regression statistics the clipboard (Ctrl+C)"))
-        btnSizer.Add(item = btn_clipboard, proportion = 0, flag = wx.ALIGN_LEFT | wx.ALL, border = 5)
-        
+        btn_clipboard = wx.Button(self.panel, id=wx.ID_COPY, label=_('C&opy'))
+        btn_clipboard.SetToolTipString(
+            _("Copy regression statistics the clipboard (Ctrl+C)"))
+        btnSizer.Add(
+            item=btn_clipboard,
+            proportion=0,
+            flag=wx.ALIGN_LEFT | wx.ALL,
+            border=5)
+
         btnCancel = wx.Button(self.panel, wx.ID_CLOSE)
         btnCancel.SetDefault()
-        btnSizer.Add(item = btnCancel, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)        
+        btnSizer.Add(
+            item=btnCancel,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT | wx.ALL,
+            border=5)
 
-        sizer.Add(item = btnSizer, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
+        sizer.Add(
+            item=btnSizer,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT | wx.ALL,
+            border=5)
 
         # bindings
         btnCancel.Bind(wx.EVT_BUTTON, self.OnClose)
         btn_clipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
-        
+
         self.panel.SetSizer(sizer)
         sizer.Fit(self)
 
@@ -317,28 +392,30 @@
         str = self.title + '\n'
         for item in self.message:
             str += item
-            
+
         rdata = wx.TextDataObject()
         rdata.SetText(str)
-        
+
         if wx.TheClipboard.Open():
             wx.TheClipboard.SetData(rdata)
             wx.TheClipboard.Close()
             wx.MessageBox(_("Regression statistics copied to clipboard"))
-        
+
     def OnClose(self, event):
         """Button 'Close' pressed
         """
         self.Close(True)
 
+
 class HistRasterDialog(wx.Dialog):
-    def __init__(self, parent, id = wx.ID_ANY, 
-                 title = _("Select raster map or imagery group to histogram"),
-                 style = wx.DEFAULT_DIALOG_STYLE, **kwargs):
+
+    def __init__(self, parent, id=wx.ID_ANY,
+                 title=_("Select raster map or imagery group to histogram"),
+                 style=wx.DEFAULT_DIALOG_STYLE, **kwargs):
         """Dialog to select raster maps to histogram.
         """
 
-        wx.Dialog.__init__(self, parent, id, title, style = style, **kwargs)
+        wx.Dialog.__init__(self, parent, id, title, style=style, **kwargs)
 
         self.parent = parent
         self.rasterList = self.parent.rasterList
@@ -347,37 +424,51 @@
         self.histtype = self.parent.histtype
         self.maptype = self.parent.maptype
         self.spinbins = ''
-        
+
         self._do_layout()
-        
+
     def _do_layout(self):
 
         sizer = wx.BoxSizer(wx.VERTICAL)
 
-        box = wx.GridBagSizer (hgap = 3, vgap = 3)
-        
+        box = wx.GridBagSizer(hgap=3, vgap=3)
+
         #
         # select single raster or image group to histogram radio buttons
         #
-        self.rasterRadio = wx.RadioButton(self, id = wx.ID_ANY, label = " %s " % _("Histogram single raster"), style = wx.RB_GROUP)
-        self.groupRadio = wx.RadioButton(self, id = wx.ID_ANY, label = " %s " % _("Histogram imagery group"))
-        if self.maptype == 'raster': 
+        self.rasterRadio = wx.RadioButton(
+            self, id=wx.ID_ANY, label=" %s " %
+            _("Histogram single raster"), style=wx.RB_GROUP)
+        self.groupRadio = wx.RadioButton(
+            self, id=wx.ID_ANY, label=" %s " %
+            _("Histogram imagery group"))
+        if self.maptype == 'raster':
             self.rasterRadio.SetValue(True)
-        elif self.maptype == 'group': 
+        elif self.maptype == 'group':
             self.groupRadio.SetValue(True)
-        box.Add(item = self.rasterRadio, flag = wx.ALIGN_CENTER_VERTICAL, pos = (0, 0))
-        box.Add(item = self.groupRadio, flag = wx.ALIGN_CENTER_VERTICAL, pos = (0, 1))
-        
+        box.Add(
+            item=self.rasterRadio,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                0,
+                0))
+        box.Add(
+            item=self.groupRadio,
+            flag=wx.ALIGN_CENTER_VERTICAL,
+            pos=(
+                0,
+                1))
+
         #
         # Select a raster to histogram
         #
-        label = wx.StaticText(parent = self, id = wx.ID_ANY, 
-                              label = _("Select raster map:"))
-        box.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (1, 0))
-        self.rselection = Select(self, id = wx.ID_ANY,
-                                 size = globalvar.DIALOG_GSELECT_SIZE,
-                                 type = 'cell')
-        if self.groupRadio.GetValue() == True: 
+        label = wx.StaticText(parent=self, id=wx.ID_ANY,
+                              label=_("Select raster map:"))
+        box.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(1, 0))
+        self.rselection = Select(self, id=wx.ID_ANY,
+                                 size=globalvar.DIALOG_GSELECT_SIZE,
+                                 type='cell')
+        if self.groupRadio.GetValue() == True:
             self.rselection.Disable()
         else:
             rastText = ''
@@ -385,55 +476,60 @@
                 rastText += '%s,' % r
             rastText = rastText.rstrip(',')
             self.rselection.SetValue(rastText)
-        box.Add(item = self.rselection, pos = (1, 1))       
+        box.Add(item=self.rselection, pos=(1, 1))
 
         #
         # Select an image group to histogram
         #
-        label = wx.StaticText(parent = self, id = wx.ID_ANY, 
-                              label = _("Select image group:"))
-        box.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (2, 0))
-        self.gselection = Select(self, id = wx.ID_ANY,
-                                 size = globalvar.DIALOG_GSELECT_SIZE,
-                                 type = 'group')
-        if self.rasterRadio.GetValue() == True: 
+        label = wx.StaticText(parent=self, id=wx.ID_ANY,
+                              label=_("Select image group:"))
+        box.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(2, 0))
+        self.gselection = Select(self, id=wx.ID_ANY,
+                                 size=globalvar.DIALOG_GSELECT_SIZE,
+                                 type='group')
+        if self.rasterRadio.GetValue() == True:
             self.gselection.Disable()
         else:
-            if self.group != None: self.gselection.SetValue(self.group)
-        box.Add(item = self.gselection, pos = (2, 1))
-            
+            if self.group is not None:
+                self.gselection.SetValue(self.group)
+        box.Add(item=self.gselection, pos=(2, 1))
+
         #
         # Nsteps for FP maps and histogram type selection
         #
-        label = wx.StaticText(parent = self, id = wx.ID_ANY, 
-                              label = _("Number of bins (for FP maps)"))
-        box.Add(item = label,
-                flag = wx.ALIGN_CENTER_VERTICAL, pos = (3, 0))
-        self.spinbins = wx.SpinCtrl(parent = self, id = wx.ID_ANY, value = "", pos = (30, 50),
-                                      size = (100,-1), style = wx.SP_ARROW_KEYS)
-        self.spinbins.SetRange(1,1000)
+        label = wx.StaticText(parent=self, id=wx.ID_ANY,
+                              label=_("Number of bins (for FP maps)"))
+        box.Add(item=label,
+                flag=wx.ALIGN_CENTER_VERTICAL, pos=(3, 0))
+        self.spinbins = wx.SpinCtrl(
+            parent=self, id=wx.ID_ANY, value="", pos=(
+                30, 50), size=(
+                100, -1), style=wx.SP_ARROW_KEYS)
+        self.spinbins.SetRange(1, 1000)
         self.spinbins.SetValue(self.bins)
-        box.Add(item = self.spinbins,
-                flag = wx.ALIGN_CENTER_VERTICAL, pos = (3, 1))
+        box.Add(item=self.spinbins,
+                flag=wx.ALIGN_CENTER_VERTICAL, pos=(3, 1))
 
-        label = wx.StaticText(parent = self, id = wx.ID_ANY, 
-                              label = _("Histogram type"))
-        box.Add(item = label,
-                flag = wx.ALIGN_CENTER_VERTICAL, pos = (4, 0))
+        label = wx.StaticText(parent=self, id=wx.ID_ANY,
+                              label=_("Histogram type"))
+        box.Add(item=label,
+                flag=wx.ALIGN_CENTER_VERTICAL, pos=(4, 0))
         types = ['count', 'percent', 'area']
-        histtype = wx.ComboBox(parent = self, id = wx.ID_ANY, size = (250, -1),
-                                choices = types, style = wx.CB_DROPDOWN)
+        histtype = wx.ComboBox(parent=self, id=wx.ID_ANY, size=(250, -1),
+                               choices=types, style=wx.CB_DROPDOWN)
         histtype.SetStringSelection(self.histtype)
-        box.Add(item = histtype,
-                flag = wx.ALIGN_CENTER_VERTICAL, pos = (4, 1))
-          
-        sizer.Add(item = box, proportion = 0,
-                  flag = wx.ALL, border = 10)
+        box.Add(item=histtype,
+                flag=wx.ALIGN_CENTER_VERTICAL, pos=(4, 1))
 
-        line = wx.StaticLine(parent = self, id = wx.ID_ANY, size = (20, -1), style = wx.LI_HORIZONTAL)
-        sizer.Add(item = line, proportion = 0,
-                  flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, border = 5)
+        sizer.Add(item=box, proportion=0,
+                  flag=wx.ALL, border=10)
 
+        line = wx.StaticLine(
+            parent=self, id=wx.ID_ANY, size=(
+                20, -1), style=wx.LI_HORIZONTAL)
+        sizer.Add(item=line, proportion=0, flag=wx.GROW |
+                  wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, border=5)
+
         btnsizer = wx.StdDialogButtonSizer()
 
         btn = wx.Button(self, wx.ID_OK)
@@ -444,7 +540,11 @@
         btnsizer.AddButton(btn)
         btnsizer.Realize()
 
-        sizer.Add(item = btnsizer, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
+        sizer.Add(
+            item=btnsizer,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT | wx.ALL,
+            border=5)
 
         #
         # bindings
@@ -476,7 +576,7 @@
             self.rselection.SetValue('')
         else:
             pass
-        
+
     def OnRasterSelection(self, event):
         """Handler for selecting a single raster map
         """
@@ -488,53 +588,55 @@
         """
         self.rasterList = []
         self.group = event.GetString()
-        ret = grass.read_command('i.group', 
-                                  group = '%s' % self.group, 
-                                  quiet = True,
-                                  flags = 'g').strip().splitlines()
+        ret = grass.read_command('i.group',
+                                 group='%s' % self.group,
+                                 quiet=True,
+                                 flags='g').strip().splitlines()
 
         if ret not in [None, '', ['']]:
             self.rasterList = ret
         else:
-            wx.MessageBox(message = _("Selected group must be in current mapset"), 
-                          caption = _('Invalid input'), 
-                          style = wx.OK | wx.ICON_ERROR)
-                                                                                            
+            wx.MessageBox(
+                message=_("Selected group must be in current mapset"),
+                caption=_('Invalid input'),
+                style=wx.OK | wx.ICON_ERROR)
+
     def OnSetBins(self, event):
         """Bins for histogramming FP maps (=nsteps in r.stats)
         """
         self.bins = self.spinbins.GetValue()
-        
+
     def OnSetHisttypes(self, event):
         self.histtype = event.GetString()
-        
 
+
 class TextDialog(wx.Dialog):
-    def __init__(self, parent, id, title, plottype = '', 
-                 style = wx.DEFAULT_DIALOG_STYLE, **kwargs):
+
+    def __init__(self, parent, id, title, plottype='',
+                 style=wx.DEFAULT_DIALOG_STYLE, **kwargs):
         """Dialog to set histogram text options: font, title
         and font size, axis labels and font size
         """
-        wx.Dialog.__init__(self, parent, id, title, style = style, **kwargs)
+        wx.Dialog.__init__(self, parent, id, title, style=style, **kwargs)
         #
         # initialize variables
         #
         # combo box entry lists
-        self.ffamilydict = { 'default' : wx.FONTFAMILY_DEFAULT,
-                             'decorative' : wx.FONTFAMILY_DECORATIVE,
-                             'roman' : wx.FONTFAMILY_ROMAN,
-                             'script' : wx.FONTFAMILY_SCRIPT,
-                             'swiss' : wx.FONTFAMILY_SWISS,
-                             'modern' : wx.FONTFAMILY_MODERN,
-                             'teletype' : wx.FONTFAMILY_TELETYPE }
+        self.ffamilydict = {'default': wx.FONTFAMILY_DEFAULT,
+                            'decorative': wx.FONTFAMILY_DECORATIVE,
+                            'roman': wx.FONTFAMILY_ROMAN,
+                            'script': wx.FONTFAMILY_SCRIPT,
+                            'swiss': wx.FONTFAMILY_SWISS,
+                            'modern': wx.FONTFAMILY_MODERN,
+                            'teletype': wx.FONTFAMILY_TELETYPE}
 
-        self.fstyledict = { 'normal' : wx.FONTSTYLE_NORMAL,
-                            'slant' : wx.FONTSTYLE_SLANT,
-                            'italic' : wx.FONTSTYLE_ITALIC }
+        self.fstyledict = {'normal': wx.FONTSTYLE_NORMAL,
+                           'slant': wx.FONTSTYLE_SLANT,
+                           'italic': wx.FONTSTYLE_ITALIC}
 
-        self.fwtdict = { 'normal' : wx.FONTWEIGHT_NORMAL,
-                         'light' : wx.FONTWEIGHT_LIGHT,
-                         'bold' : wx.FONTWEIGHT_BOLD }
+        self.fwtdict = {'normal': wx.FONTWEIGHT_NORMAL,
+                        'light': wx.FONTWEIGHT_LIGHT,
+                        'bold': wx.FONTWEIGHT_BOLD}
 
         self.parent = parent
         self.plottype = plottype
@@ -543,138 +645,174 @@
         self.xlabel = self.parent.xlabel
         self.ylabel = self.parent.ylabel
 
-        self.properties = self.parent.properties # read-only
-        
+        self.properties = self.parent.properties  # read-only
+
         # font size
         self.fontfamily = self.properties['font']['wxfont'].GetFamily()
         self.fontstyle = self.properties['font']['wxfont'].GetStyle()
         self.fontweight = self.properties['font']['wxfont'].GetWeight()
 
         self._do_layout()
-                
+
     def _do_layout(self):
         """Do layout"""
         # dialog layout
         sizer = wx.BoxSizer(wx.VERTICAL)
 
-        box = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                           label = " %s " % _("Text settings"))
+        box = wx.StaticBox(parent=self, id=wx.ID_ANY,
+                           label=" %s " % _("Text settings"))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 5, hgap = 5)
+        gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
 
         #
         # profile title
         #
-        label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Profile title:"))
-        gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (0, 0))
-        self.ptitleentry = wx.TextCtrl(parent = self, id = wx.ID_ANY, value = "", size = (250,-1))
+        label = wx.StaticText(
+            parent=self,
+            id=wx.ID_ANY,
+            label=_("Profile title:"))
+        gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 0))
+        self.ptitleentry = wx.TextCtrl(
+            parent=self, id=wx.ID_ANY, value="", size=(250, -1))
         # self.ptitleentry.SetFont(self.font)
         self.ptitleentry.SetValue(self.ptitle)
-        gridSizer.Add(item = self.ptitleentry, pos = (0, 1))
+        gridSizer.Add(item=self.ptitleentry, pos=(0, 1))
 
         #
         # title font
         #
-        tlabel = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Title font size (pts):"))
-        gridSizer.Add(item = tlabel, flag = wx.ALIGN_CENTER_VERTICAL, pos = (1, 0))
-        self.ptitlesize = wx.SpinCtrl(parent = self, id = wx.ID_ANY, value = "", pos = (30, 50),
-                                      size = (50,-1), style = wx.SP_ARROW_KEYS)
-        self.ptitlesize.SetRange(5,100)
-        self.ptitlesize.SetValue(int(self.properties['font']['prop']['titleSize']))
-        gridSizer.Add(item = self.ptitlesize, pos = (1, 1))
+        tlabel = wx.StaticText(
+            parent=self,
+            id=wx.ID_ANY,
+            label=_("Title font size (pts):"))
+        gridSizer.Add(item=tlabel, flag=wx.ALIGN_CENTER_VERTICAL, pos=(1, 0))
+        self.ptitlesize = wx.SpinCtrl(
+            parent=self, id=wx.ID_ANY, value="", pos=(
+                30, 50), size=(
+                50, -1), style=wx.SP_ARROW_KEYS)
+        self.ptitlesize.SetRange(5, 100)
+        self.ptitlesize.SetValue(
+            int(self.properties['font']['prop']['titleSize']))
+        gridSizer.Add(item=self.ptitlesize, pos=(1, 1))
 
         #
         # x-axis label
         #
-        label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("X-axis label:"))
-        gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (2, 0))
-        self.xlabelentry = wx.TextCtrl(parent = self, id = wx.ID_ANY, value = "", size = (250,-1))
+        label = wx.StaticText(
+            parent=self,
+            id=wx.ID_ANY,
+            label=_("X-axis label:"))
+        gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(2, 0))
+        self.xlabelentry = wx.TextCtrl(
+            parent=self, id=wx.ID_ANY, value="", size=(250, -1))
         # self.xlabelentry.SetFont(self.font)
         self.xlabelentry.SetValue(self.xlabel)
-        gridSizer.Add(item = self.xlabelentry, pos = (2, 1))
+        gridSizer.Add(item=self.xlabelentry, pos=(2, 1))
 
         #
         # y-axis label
         #
-        label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Y-axis label:"))
-        gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (3, 0))
-        self.ylabelentry = wx.TextCtrl(parent = self, id = wx.ID_ANY, value = "", size = (250,-1))
+        label = wx.StaticText(
+            parent=self,
+            id=wx.ID_ANY,
+            label=_("Y-axis label:"))
+        gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(3, 0))
+        self.ylabelentry = wx.TextCtrl(
+            parent=self, id=wx.ID_ANY, value="", size=(250, -1))
         # self.ylabelentry.SetFont(self.font)
         self.ylabelentry.SetValue(self.ylabel)
-        gridSizer.Add(item = self.ylabelentry, pos = (3, 1))
+        gridSizer.Add(item=self.ylabelentry, pos=(3, 1))
 
         #
         # font size
         #
-        llabel = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Label font size (pts):"))
-        gridSizer.Add(item = llabel, flag = wx.ALIGN_CENTER_VERTICAL, pos = (4, 0))
-        self.axislabelsize = wx.SpinCtrl(parent = self, id = wx.ID_ANY, value = "", pos = (30, 50),
-                                         size = (50, -1), style = wx.SP_ARROW_KEYS)
-        self.axislabelsize.SetRange(5, 100) 
-        self.axislabelsize.SetValue(int(self.properties['font']['prop']['axisSize']))
-        gridSizer.Add(item = self.axislabelsize, pos = (4,1))
+        llabel = wx.StaticText(
+            parent=self,
+            id=wx.ID_ANY,
+            label=_("Label font size (pts):"))
+        gridSizer.Add(item=llabel, flag=wx.ALIGN_CENTER_VERTICAL, pos=(4, 0))
+        self.axislabelsize = wx.SpinCtrl(
+            parent=self, id=wx.ID_ANY, value="", pos=(
+                30, 50), size=(
+                50, -1), style=wx.SP_ARROW_KEYS)
+        self.axislabelsize.SetRange(5, 100)
+        self.axislabelsize.SetValue(
+            int(self.properties['font']['prop']['axisSize']))
+        gridSizer.Add(item=self.axislabelsize, pos=(4, 1))
 
-        boxSizer.Add(item = gridSizer)
-        sizer.Add(item = boxSizer, flag = wx.ALL | wx.EXPAND, border = 3)
+        boxSizer.Add(item=gridSizer)
+        sizer.Add(item=boxSizer, flag=wx.ALL | wx.EXPAND, border=3)
 
         #
         # font settings
         #
-        box = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                           label = " %s " % _("Font settings"))
+        box = wx.StaticBox(parent=self, id=wx.ID_ANY,
+                           label=" %s " % _("Font settings"))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        gridSizer = wx.GridBagSizer(vgap = 5, hgap = 5)
+        gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
 
         #
         # font family
         #
-        label1 = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Font family:"))
-        gridSizer.Add(item = label1, flag = wx.ALIGN_CENTER_VERTICAL, pos = (0, 0))
-        self.ffamilycb = wx.ComboBox(parent = self, id = wx.ID_ANY, size = (250, -1),
-                                choices = self.ffamilydict.keys(), style = wx.CB_DROPDOWN)
+        label1 = wx.StaticText(
+            parent=self,
+            id=wx.ID_ANY,
+            label=_("Font family:"))
+        gridSizer.Add(item=label1, flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 0))
+        self.ffamilycb = wx.ComboBox(
+            parent=self, id=wx.ID_ANY, size=(250, -1),
+            choices=self.ffamilydict.keys(),
+            style=wx.CB_DROPDOWN)
         self.ffamilycb.SetStringSelection('swiss')
         for item in self.ffamilydict.items():
             if self.fontfamily == item[1]:
                 self.ffamilycb.SetStringSelection(item[0])
                 break
-        gridSizer.Add(item = self.ffamilycb, pos = (0, 1), flag = wx.ALIGN_RIGHT)
+        gridSizer.Add(item=self.ffamilycb, pos=(0, 1), flag=wx.ALIGN_RIGHT)
 
         #
         # font style
         #
-        label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Style:"))
-        gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (1, 0))
-        self.fstylecb = wx.ComboBox(parent = self, id = wx.ID_ANY, size = (250, -1),
-                                    choices = self.fstyledict.keys(), style = wx.CB_DROPDOWN)
+        label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Style:"))
+        gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(1, 0))
+        self.fstylecb = wx.ComboBox(
+            parent=self, id=wx.ID_ANY, size=(250, -1),
+            choices=self.fstyledict.keys(),
+            style=wx.CB_DROPDOWN)
         self.fstylecb.SetStringSelection('normal')
         for item in self.fstyledict.items():
             if self.fontstyle == item[1]:
                 self.fstylecb.SetStringSelection(item[0])
                 break
-        gridSizer.Add(item = self.fstylecb, pos = (1, 1), flag = wx.ALIGN_RIGHT)
+        gridSizer.Add(item=self.fstylecb, pos=(1, 1), flag=wx.ALIGN_RIGHT)
 
         #
         # font weight
         #
-        label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Weight:"))
-        gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (2, 0))
-        self.fwtcb = wx.ComboBox(parent = self, size = (250, -1),
-                                 choices = self.fwtdict.keys(), style = wx.CB_DROPDOWN)
+        label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Weight:"))
+        gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(2, 0))
+        self.fwtcb = wx.ComboBox(
+            parent=self, size=(250, -1),
+            choices=self.fwtdict.keys(),
+            style=wx.CB_DROPDOWN)
         self.fwtcb.SetStringSelection('normal')
         for item in self.fwtdict.items():
             if self.fontweight == item[1]:
                 self.fwtcb.SetStringSelection(item[0])
                 break
 
-        gridSizer.Add(item = self.fwtcb, pos = (2, 1), flag = wx.ALIGN_RIGHT)
-                      
+        gridSizer.Add(item=self.fwtcb, pos=(2, 1), flag=wx.ALIGN_RIGHT)
+
         gridSizer.AddGrowableCol(1)
-        boxSizer.Add(item = gridSizer, flag = wx.EXPAND)
-        sizer.Add(item = boxSizer, flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
+        boxSizer.Add(item=gridSizer, flag=wx.EXPAND)
+        sizer.Add(item=boxSizer, flag=wx.LEFT | wx.RIGHT |
+                  wx.BOTTOM | wx.EXPAND, border=3)
 
-        line = wx.StaticLine(parent = self, id = wx.ID_ANY, size = (20, -1), style = wx.LI_HORIZONTAL)
-        sizer.Add(item = line, proportion = 0,
-                  flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, border = 3)
+        line = wx.StaticLine(
+            parent=self, id=wx.ID_ANY, size=(
+                20, -1), style=wx.LI_HORIZONTAL)
+        sizer.Add(item=line, proportion=0, flag=wx.GROW |
+                  wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, border=3)
 
         #
         # buttons
@@ -689,10 +827,12 @@
         btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
         btnApply.SetToolTipString(_("Apply changes for the current session"))
         btnOk.Bind(wx.EVT_BUTTON, self.OnOk)
-        btnOk.SetToolTipString(_("Apply changes for the current session and close dialog"))
+        btnOk.SetToolTipString(
+            _("Apply changes for the current session and close dialog"))
         btnOk.SetDefault()
         btnSave.Bind(wx.EVT_BUTTON, self.OnSave)
-        btnSave.SetToolTipString(_("Apply and save changes to user settings file (default for next sessions)"))
+        btnSave.SetToolTipString(
+            _("Apply and save changes to user settings file (default for next sessions)"))
         btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel)
         btnCancel.SetToolTipString(_("Close dialog and ignore changes"))
 
@@ -702,11 +842,23 @@
         btnStdSizer.AddButton(btnApply)
         btnStdSizer.AddButton(btnCancel)
         btnStdSizer.Realize()
-        
+
         btnSizer = wx.BoxSizer(wx.HORIZONTAL)
-        btnSizer.Add(item = btnSave, proportion = 0, flag = wx.ALIGN_LEFT | wx.ALL, border = 5)
-        btnSizer.Add(item = btnStdSizer, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
-        sizer.Add(item = btnSizer, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
+        btnSizer.Add(
+            item=btnSave,
+            proportion=0,
+            flag=wx.ALIGN_LEFT | wx.ALL,
+            border=5)
+        btnSizer.Add(
+            item=btnStdSizer,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT | wx.ALL,
+            border=5)
+        sizer.Add(
+            item=btnSizer,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT | wx.ALL,
+            border=5)
 
         #
         # bindings
@@ -728,8 +880,10 @@
         self.ylabel = event.GetString()
 
     def UpdateSettings(self):
-        self.properties['font']['prop']['titleSize'] = self.ptitlesize.GetValue()
-        self.properties['font']['prop']['axisSize'] = self.axislabelsize.GetValue()
+        self.properties['font']['prop'][
+            'titleSize'] = self.ptitlesize.GetValue()
+        self.properties['font']['prop'][
+            'axisSize'] = self.axislabelsize.GetValue()
 
         family = self.ffamilydict[self.ffamilycb.GetStringSelection()]
         self.properties['font']['wxfont'].SetFamily(family)
@@ -742,17 +896,18 @@
         """Button 'Save' pressed"""
         self.OnApply(None)
         fileSettings = {}
-        UserSettings.ReadSettingsFile(settings = fileSettings)
-        fileSettings[self.plottype] = UserSettings.Get(group = self.plottype)
+        UserSettings.ReadSettingsFile(settings=fileSettings)
+        fileSettings[self.plottype] = UserSettings.Get(group=self.plottype)
         UserSettings.SaveToFile(fileSettings)
-        self.parent.parent.GetLayerManager().GetLogWindow().WriteLog(_('Plot text sizes saved to file \'%s\'.') % UserSettings.filePath)
+        self.parent.parent.GetLayerManager().GetLogWindow().WriteLog(
+            _('Plot text sizes saved to file \'%s\'.') % UserSettings.filePath)
         self.EndModal(wx.ID_OK)
 
     def OnApply(self, event):
         """Button 'Apply' pressed"""
         self.UpdateSettings()
         self.parent.OnPlotText(self)
-        
+
     def OnOk(self, event):
         """Button 'OK' pressed"""
         self.OnApply(None)
@@ -761,15 +916,17 @@
     def OnCancel(self, event):
         """Button 'Cancel' pressed"""
         self.EndModal(wx.ID_CANCEL)
-        
+
+
 class OptDialog(wx.Dialog):
-    def __init__(self, parent, id, title, plottype = '', 
-                 style = wx.DEFAULT_DIALOG_STYLE, **kwargs): 
+
+    def __init__(self, parent, id, title, plottype='',
+                 style=wx.DEFAULT_DIALOG_STYLE, **kwargs):
         """Dialog to set various options for data plotted, including: line
         width, color, style; marker size, color, fill, and style; grid
         and legend options.
         """
-        wx.Dialog.__init__(self, parent, id, title, style = style, **kwargs)
+        wx.Dialog.__init__(self, parent, id, title, style=style, **kwargs)
 
         # init variables
         self.parent = parent
@@ -777,7 +934,7 @@
         self.ptfilldict = parent.ptfilldict
         self.parent = parent
         self.plottype = plottype
-        
+
         self.pttypelist = ['circle',
                            'dot',
                            'square',
@@ -785,14 +942,14 @@
                            'triangle_down',
                            'cross',
                            'plus']
-        
+
         self.axislist = ['min',
                          'auto',
                          'custom']
 
         # widgets ids
         self.wxId = {}
-        
+
         self.parent = parent
 
         # read-only
@@ -800,14 +957,14 @@
         self.rasterList = self.parent.rasterList
         self.properties = self.parent.properties
         self.map = ''
-        
+
         if len(self.rasterList) == 0:
-            wx.MessageBox(parent = self,
-                              message = _("No map or image group selected to plot."),
-                              caption = _("Warning"), style = wx.OK | wx.ICON_ERROR)
-            
+            wx.MessageBox(parent=self,
+                          message=_("No map or image group selected to plot."),
+                          caption=_("Warning"), style=wx.OK | wx.ICON_ERROR)
+
         self._do_layout()
-        
+
     def ConvertTuples(self, tlist):
         """Converts tuples to strings when rasterList contains raster
         pairs for scatterplot
@@ -816,7 +973,7 @@
         for i in tlist:
             i = str(i).strip('()')
             list.append(i)
-            
+
         return list
 
     def _do_layout(self):
@@ -824,13 +981,13 @@
         """
         sizer = wx.BoxSizer(wx.VERTICAL)
 
-        box = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                           label = " %s " % _("Plot settings")) 
+        box = wx.StaticBox(parent=self, id=wx.ID_ANY,
+                           label=" %s " % _("Plot settings"))
         boxMainSizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
 
-        self.wxId['pcolor']  = 0
-        self.wxId['pwidth']  = 0
-        self.wxId['pstyle']  = 0
+        self.wxId['pcolor'] = 0
+        self.wxId['pwidth'] = 0
+        self.wxId['pstyle'] = 0
         self.wxId['psize'] = 0
         self.wxId['ptype'] = 0
         self.wxId['pfill'] = 0
@@ -838,293 +995,424 @@
         self.wxId['marker'] = {}
         self.wxId['x-axis'] = {}
         self.wxId['y-axis'] = {}
-        
+
         #
         # plot line settings and point settings
         #
-        if len(self.rasterList) == 0: return
-        
-        box = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                           label = _("Map/image plotted"))
+        if len(self.rasterList) == 0:
+            return
+
+        box = wx.StaticBox(parent=self, id=wx.ID_ANY,
+                           label=_("Map/image plotted"))
         boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-        
-        gridSizer = wx.GridBagSizer(vgap = 5, hgap = 5)
-        
+
+        gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
+
         row = 0
         choicelist = []
         for i in self.rasterList:
             choicelist.append(str(i))
 
-        self.mapchoice = wx.Choice(parent = self, id = wx.ID_ANY, size = (300, -1),
-                                   choices = choicelist)        
+        self.mapchoice = wx.Choice(parent=self, id=wx.ID_ANY, size=(300, -1),
+                                   choices=choicelist)
         self.mapchoice.SetToolTipString(_("Settings for selected map"))
 
         if not self.map:
             self.map = self.rasterList[self.mapchoice.GetCurrentSelection()]
         else:
             self.mapchoice.SetStringSelection(str(self.map))
-            
-                
-        gridSizer.Add(item = self.mapchoice, flag = wx.ALIGN_CENTER_VERTICAL, 
-                      pos = (row, 0), span = (1, 2))
-        
+
+        gridSizer.Add(item=self.mapchoice, flag=wx.ALIGN_CENTER_VERTICAL,
+                      pos=(row, 0), span=(1, 2))
+
         #
         # options for line plots (profiles and histograms)
         #
         if self.plottype != 'scatter':
-            row +=1            
-            label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Line color"))
-            gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (row, 0))
-            color = csel.ColourSelect(parent = self, id = wx.ID_ANY, colour = self.raster[self.map]['pcolor'])
+            row += 1
+            label = wx.StaticText(
+                parent=self,
+                id=wx.ID_ANY,
+                label=_("Line color"))
+            gridSizer.Add(
+                item=label,
+                flag=wx.ALIGN_CENTER_VERTICAL,
+                pos=(
+                    row,
+                    0))
+            color = csel.ColourSelect(
+                parent=self, id=wx.ID_ANY, colour=self.raster[
+                    self.map]['pcolor'])
             self.wxId['pcolor'] = color.GetId()
-            gridSizer.Add(item = color, pos = (row, 1))
+            gridSizer.Add(item=color, pos=(row, 1))
 
             row += 1
-            label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Line width"))
-            gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (row, 0))
-            width = wx.SpinCtrl(parent = self, id = wx.ID_ANY, value = "",
-                                 size = (50,-1), style = wx.SP_ARROW_KEYS)
+            label = wx.StaticText(
+                parent=self,
+                id=wx.ID_ANY,
+                label=_("Line width"))
+            gridSizer.Add(
+                item=label,
+                flag=wx.ALIGN_CENTER_VERTICAL,
+                pos=(
+                    row,
+                    0))
+            width = wx.SpinCtrl(parent=self, id=wx.ID_ANY, value="",
+                                size=(50, -1), style=wx.SP_ARROW_KEYS)
             width.SetRange(1, 10)
             width.SetValue(self.raster[self.map]['pwidth'])
             self.wxId['pwidth'] = width.GetId()
-            gridSizer.Add(item = width, pos = (row, 1))
+            gridSizer.Add(item=width, pos=(row, 1))
 
-            row +=1
-            label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Line style"))
-            gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (row, 0))
-            style = wx.Choice(parent = self, id = wx.ID_ANY, 
-                                 size = (120, -1), choices = self.linestyledict.keys())
+            row += 1
+            label = wx.StaticText(
+                parent=self,
+                id=wx.ID_ANY,
+                label=_("Line style"))
+            gridSizer.Add(
+                item=label,
+                flag=wx.ALIGN_CENTER_VERTICAL,
+                pos=(
+                    row,
+                    0))
+            style = wx.Choice(
+                parent=self, id=wx.ID_ANY, size=(
+                    120, -1), choices=self.linestyledict.keys())
             style.SetStringSelection(self.raster[self.map]['pstyle'])
             self.wxId['pstyle'] = style.GetId()
-            gridSizer.Add(item = style, pos = (row, 1))
+            gridSizer.Add(item=style, pos=(row, 1))
 
         row += 1
-        label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Legend"))
-        gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (row, 0))
-        legend = wx.TextCtrl(parent = self, id = wx.ID_ANY, value = "", size = (200,-1))
+        label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Legend"))
+        gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
+        legend = wx.TextCtrl(parent=self, id=wx.ID_ANY,
+                             value="", size=(200, -1))
         legend.SetValue(self.raster[self.map]['plegend'])
-        gridSizer.Add(item = legend, pos = (row, 1))
+        gridSizer.Add(item=legend, pos=(row, 1))
         self.wxId['plegend'] = legend.GetId()
-        
-        boxSizer.Add(item = gridSizer)
-        boxMainSizer.Add(item = boxSizer, flag = wx.ALL, border = 3)
 
+        boxSizer.Add(item=gridSizer)
+        boxMainSizer.Add(item=boxSizer, flag=wx.ALL, border=3)
+
         #
         # segment marker settings for profiles only
-        #       
+        #
         if self.plottype == 'profile':
-            box = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                               label = " %s " % _("Transect segment marker settings"))
-            
+            box = wx.StaticBox(
+                parent=self, id=wx.ID_ANY, label=" %s " %
+                _("Transect segment marker settings"))
+
             boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-            
-            gridSizer = wx.GridBagSizer(vgap = 5, hgap = 5)
-            label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Color"))
-            gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (0, 0))
-            ptcolor = csel.ColourSelect(parent = self, id = wx.ID_ANY, colour = self.properties['marker']['color'])
+
+            gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
+            label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Color"))
+            gridSizer.Add(
+                item=label,
+                flag=wx.ALIGN_CENTER_VERTICAL,
+                pos=(
+                    0,
+                    0))
+            ptcolor = csel.ColourSelect(
+                parent=self,
+                id=wx.ID_ANY,
+                colour=self.properties['marker']['color'])
             self.wxId['marker']['color'] = ptcolor.GetId()
-            gridSizer.Add(item = ptcolor, pos = (0, 1))
+            gridSizer.Add(item=ptcolor, pos=(0, 1))
 
-            label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Size"))
-            gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (1, 0))
-            ptsize = wx.SpinCtrl(parent = self, id = wx.ID_ANY, value = "",
-                                 size = (50, -1), style = wx.SP_ARROW_KEYS)
+            label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Size"))
+            gridSizer.Add(
+                item=label,
+                flag=wx.ALIGN_CENTER_VERTICAL,
+                pos=(
+                    1,
+                    0))
+            ptsize = wx.SpinCtrl(parent=self, id=wx.ID_ANY, value="",
+                                 size=(50, -1), style=wx.SP_ARROW_KEYS)
             ptsize.SetRange(1, 10)
             ptsize.SetValue(self.properties['marker']['size'])
             self.wxId['marker']['size'] = ptsize.GetId()
-            gridSizer.Add(item = ptsize, pos = (1, 1))
-            
-            label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Fill"))
-            gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (2, 0))
-            ptfill = wx.Choice(parent = self, id = wx.ID_ANY,
-                                 size = (120, -1), choices = self.ptfilldict.keys())
+            gridSizer.Add(item=ptsize, pos=(1, 1))
+
+            label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Fill"))
+            gridSizer.Add(
+                item=label,
+                flag=wx.ALIGN_CENTER_VERTICAL,
+                pos=(
+                    2,
+                    0))
+            ptfill = wx.Choice(parent=self, id=wx.ID_ANY,
+                               size=(120, -1), choices=self.ptfilldict.keys())
             ptfill.SetStringSelection(self.properties['marker']['fill'])
             self.wxId['marker']['fill'] = ptfill.GetId()
-            gridSizer.Add(item = ptfill, pos = (2, 1))
-            
-            label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Legend"))
-            gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (3, 0))
-            ptlegend = wx.TextCtrl(parent = self, id = wx.ID_ANY, value = "", size = (200,-1))
+            gridSizer.Add(item=ptfill, pos=(2, 1))
+
+            label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Legend"))
+            gridSizer.Add(
+                item=label,
+                flag=wx.ALIGN_CENTER_VERTICAL,
+                pos=(
+                    3,
+                    0))
+            ptlegend = wx.TextCtrl(
+                parent=self, id=wx.ID_ANY, value="", size=(
+                    200, -1))
             ptlegend.SetValue(self.properties['marker']['legend'])
             self.wxId['marker']['legend'] = ptlegend.GetId()
-            gridSizer.Add(item = ptlegend, pos = (3, 1))
-                    
-            label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Style"))
-            gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (4, 0))
-            pttype = wx.Choice(parent = self, size = (200, -1), choices = self.pttypelist)
+            gridSizer.Add(item=ptlegend, pos=(3, 1))
+
+            label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Style"))
+            gridSizer.Add(
+                item=label,
+                flag=wx.ALIGN_CENTER_VERTICAL,
+                pos=(
+                    4,
+                    0))
+            pttype = wx.Choice(
+                parent=self, size=(200, -1),
+                choices=self.pttypelist)
             pttype.SetStringSelection(self.properties['marker']['type'])
             self.wxId['marker']['type'] = pttype.GetId()
-            gridSizer.Add(item = pttype, pos = (4, 1))
+            gridSizer.Add(item=pttype, pos=(4, 1))
 
-            boxSizer.Add(item = gridSizer)
-            boxMainSizer.Add(item = boxSizer, flag = wx.ALL, border = 3)
-            
+            boxSizer.Add(item=gridSizer)
+            boxMainSizer.Add(item=boxSizer, flag=wx.ALL, border=3)
+
         #
         # point options for scatterplots
         #
         elif self.plottype == 'scatter':
-            box = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                               label = " %s " % _("Scatterplot points"))
-            
+            box = wx.StaticBox(parent=self, id=wx.ID_ANY,
+                               label=" %s " % _("Scatterplot points"))
+
             boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
-            
-            gridSizer = wx.GridBagSizer(vgap = 5, hgap = 5)
-            label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Color"))
-            gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (0, 0))
-            ptcolor = csel.ColourSelect(parent = self, id = wx.ID_ANY, colour = self.raster[self.map]['pcolor'])
+
+            gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
+            label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Color"))
+            gridSizer.Add(
+                item=label,
+                flag=wx.ALIGN_CENTER_VERTICAL,
+                pos=(
+                    0,
+                    0))
+            ptcolor = csel.ColourSelect(
+                parent=self, id=wx.ID_ANY, colour=self.raster[
+                    self.map]['pcolor'])
             self.wxId['pcolor'] = ptcolor.GetId()
-            gridSizer.Add(item = ptcolor, pos = (0, 1))
+            gridSizer.Add(item=ptcolor, pos=(0, 1))
 
-            label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Size"))
-            gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (1, 0))
-            ptsize = wx.SpinCtrl(parent = self, id = wx.ID_ANY, value = "",
-                                 size = (50, -1), style = wx.SP_ARROW_KEYS)
+            label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Size"))
+            gridSizer.Add(
+                item=label,
+                flag=wx.ALIGN_CENTER_VERTICAL,
+                pos=(
+                    1,
+                    0))
+            ptsize = wx.SpinCtrl(parent=self, id=wx.ID_ANY, value="",
+                                 size=(50, -1), style=wx.SP_ARROW_KEYS)
             ptsize.SetRange(1, 10)
             ptsize.SetValue(self.raster[self.map]['psize'])
             self.wxId['psize'] = ptsize.GetId()
-            gridSizer.Add(item = ptsize, pos = (1, 1))
-            
-            label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Fill"))
-            gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (2, 0))
-            ptfill = wx.Choice(parent = self, id = wx.ID_ANY,
-                               size = (120, -1), choices = self.ptfilldict.keys())
+            gridSizer.Add(item=ptsize, pos=(1, 1))
+
+            label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Fill"))
+            gridSizer.Add(
+                item=label,
+                flag=wx.ALIGN_CENTER_VERTICAL,
+                pos=(
+                    2,
+                    0))
+            ptfill = wx.Choice(parent=self, id=wx.ID_ANY,
+                               size=(120, -1), choices=self.ptfilldict.keys())
             ptfill.SetStringSelection(self.raster[self.map]['pfill'])
             self.wxId['pfill'] = ptfill.GetId()
-            gridSizer.Add(item = ptfill, pos = (2, 1))
-            
-            label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Legend"))
-            gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (3, 0))
-            ptlegend = wx.TextCtrl(parent = self, id = wx.ID_ANY, value = "", size = (200,-1))
+            gridSizer.Add(item=ptfill, pos=(2, 1))
+
+            label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Legend"))
+            gridSizer.Add(
+                item=label,
+                flag=wx.ALIGN_CENTER_VERTICAL,
+                pos=(
+                    3,
+                    0))
+            ptlegend = wx.TextCtrl(
+                parent=self, id=wx.ID_ANY, value="", size=(
+                    200, -1))
             ptlegend.SetValue(self.raster[self.map]['plegend'])
             self.wxId['plegend'] = ptlegend.GetId()
-            gridSizer.Add(item = ptlegend, pos = (3, 1))
-                    
-            label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Style"))
-            gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (4, 0))
-            pttype = wx.Choice(parent = self, size = (200, -1), choices = self.pttypelist)
+            gridSizer.Add(item=ptlegend, pos=(3, 1))
+
+            label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Style"))
+            gridSizer.Add(
+                item=label,
+                flag=wx.ALIGN_CENTER_VERTICAL,
+                pos=(
+                    4,
+                    0))
+            pttype = wx.Choice(
+                parent=self, size=(200, -1),
+                choices=self.pttypelist)
             pttype.SetStringSelection(self.raster[self.map]['ptype'])
             self.wxId['ptype'] = pttype.GetId()
-            gridSizer.Add(item = pttype, pos = (4, 1))
+            gridSizer.Add(item=pttype, pos=(4, 1))
 
-            boxSizer.Add(item = gridSizer)
-            boxMainSizer.Add(item = boxSizer, flag = wx.ALL, border = 3)
-            
-        sizer.Add(item = boxMainSizer, flag = wx.ALL | wx.EXPAND, border = 3)
+            boxSizer.Add(item=gridSizer)
+            boxMainSizer.Add(item=boxSizer, flag=wx.ALL, border=3)
 
+        sizer.Add(item=boxMainSizer, flag=wx.ALL | wx.EXPAND, border=3)
+
         #
         # axis options for all plots
         #
-        box = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                           label = " %s " % _("Axis settings"))
+        box = wx.StaticBox(parent=self, id=wx.ID_ANY,
+                           label=" %s " % _("Axis settings"))
         boxMainSizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
 
         middleSizer = wx.BoxSizer(wx.HORIZONTAL)
 
         idx = 0
         for axis, atype in [(_("X-Axis"), 'x-axis'),
-                     (_("Y-Axis"), 'y-axis')]:
-            box = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                               label = " %s " % axis)
+                            (_("Y-Axis"), 'y-axis')]:
+            box = wx.StaticBox(parent=self, id=wx.ID_ANY,
+                               label=" %s " % axis)
             boxSizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
-            gridSizer = wx.GridBagSizer(vgap = 5, hgap = 5)
+            gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
 
             prop = self.properties[atype]['prop']
-            
+
             row = 0
-            label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Scale"))
-            gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (row, 0))
-            type = wx.Choice(parent = self, id = wx.ID_ANY, size = (100, -1), choices = self.axislist)
-            type.SetStringSelection(prop['type']) 
-            type.SetToolTipString(_("Automatic axis scaling, custom max and min, or scale matches data range (min)" ))
+            label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Scale"))
+            gridSizer.Add(
+                item=label,
+                flag=wx.ALIGN_CENTER_VERTICAL,
+                pos=(
+                    row,
+                    0))
+            type = wx.Choice(
+                parent=self, id=wx.ID_ANY, size=(
+                    100, -1), choices=self.axislist)
+            type.SetStringSelection(prop['type'])
+            type.SetToolTipString(
+                _("Automatic axis scaling, custom max and min, or scale matches data range (min)"))
             self.wxId[atype]['type'] = type.GetId()
-            gridSizer.Add(item = type, pos = (row, 1))
-                        
+            gridSizer.Add(item=type, pos=(row, 1))
+
             row += 1
-            label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Custom min"))
-            gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (row, 0))
-            min = wx.TextCtrl(parent = self, id = wx.ID_ANY, value = "", size = (70, -1))
+            label = wx.StaticText(
+                parent=self,
+                id=wx.ID_ANY,
+                label=_("Custom min"))
+            gridSizer.Add(
+                item=label,
+                flag=wx.ALIGN_CENTER_VERTICAL,
+                pos=(
+                    row,
+                    0))
+            min = wx.TextCtrl(parent=self, id=wx.ID_ANY,
+                              value="", size=(70, -1))
             min.SetValue(str(prop['min']))
             self.wxId[atype]['min'] = min.GetId()
-            gridSizer.Add(item = min, pos = (row, 1))
+            gridSizer.Add(item=min, pos=(row, 1))
 
             row += 1
-            label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Custom max"))
-            gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (row, 0))
-            max = wx.TextCtrl(parent = self, id = wx.ID_ANY, value = "", size = (70, -1))
+            label = wx.StaticText(
+                parent=self,
+                id=wx.ID_ANY,
+                label=_("Custom max"))
+            gridSizer.Add(
+                item=label,
+                flag=wx.ALIGN_CENTER_VERTICAL,
+                pos=(
+                    row,
+                    0))
+            max = wx.TextCtrl(parent=self, id=wx.ID_ANY,
+                              value="", size=(70, -1))
             max.SetValue(str(prop['max']))
             self.wxId[atype]['max'] = max.GetId()
-            gridSizer.Add(item = max, pos = (row, 1))
-            
+            gridSizer.Add(item=max, pos=(row, 1))
+
             row += 1
-            log = wx.CheckBox(parent = self, id = wx.ID_ANY, label = _("Log scale"))
+            log = wx.CheckBox(parent=self, id=wx.ID_ANY, label=_("Log scale"))
             log.SetValue(prop['log'])
             self.wxId[atype]['log'] = log.GetId()
-            gridSizer.Add(item = log, pos = (row, 0), span = (1, 2))
+            gridSizer.Add(item=log, pos=(row, 0), span=(1, 2))
 
             if idx == 0:
                 flag = wx.ALL | wx.EXPAND
             else:
                 flag = wx.TOP | wx.BOTTOM | wx.RIGHT | wx.EXPAND
 
-            boxSizer.Add(item = gridSizer, flag = wx.ALL, border = 3)
-            boxMainSizer.Add(item = boxSizer, flag = flag, border = 3)
+            boxSizer.Add(item=gridSizer, flag=wx.ALL, border=3)
+            boxMainSizer.Add(item=boxSizer, flag=flag, border=3)
 
             idx += 1
-            
-        middleSizer.Add(item = boxMainSizer, flag = wx.ALL | wx.EXPAND, border = 3)
 
+        middleSizer.Add(item=boxMainSizer, flag=wx.ALL | wx.EXPAND, border=3)
+
         #
         # grid & legend options for all plots
         #
         self.wxId['grid'] = {}
         self.wxId['legend'] = {}
         self.wxId['font'] = {}
-        box = wx.StaticBox(parent = self, id = wx.ID_ANY,
-                           label = " %s " % _("Grid and Legend settings"))
+        box = wx.StaticBox(parent=self, id=wx.ID_ANY,
+                           label=" %s " % _("Grid and Legend settings"))
         boxMainSizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
-        gridSizer = wx.GridBagSizer(vgap = 5, hgap = 5)
+        gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
 
         row = 0
-        label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Grid color"))
-        gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (row, 0))
-        gridcolor = csel.ColourSelect(parent = self, id = wx.ID_ANY, colour = self.properties['grid']['color'])
+        label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Grid color"))
+        gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
+        gridcolor = csel.ColourSelect(
+            parent=self,
+            id=wx.ID_ANY,
+            colour=self.properties['grid']['color'])
         self.wxId['grid']['color'] = gridcolor.GetId()
-        gridSizer.Add(item = gridcolor, pos = (row, 1))
+        gridSizer.Add(item=gridcolor, pos=(row, 1))
 
-        row +=1
-        gridshow = wx.CheckBox(parent = self, id = wx.ID_ANY, label = _("Show grid"))
+        row += 1
+        gridshow = wx.CheckBox(parent=self, id=wx.ID_ANY, label=_("Show grid"))
         gridshow.SetValue(self.properties['grid']['enabled'])
         self.wxId['grid']['enabled'] = gridshow.GetId()
-        gridSizer.Add(item = gridshow, pos = (row, 0), span = (1, 2))
+        gridSizer.Add(item=gridshow, pos=(row, 0), span=(1, 2))
 
-        row +=1
-        label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Legend font size"))
-        gridSizer.Add(item = label, flag = wx.ALIGN_CENTER_VERTICAL, pos = (row, 0))
-        legendfontsize = wx.SpinCtrl(parent = self, id = wx.ID_ANY, value = "", 
-                                     size = (50, -1), style = wx.SP_ARROW_KEYS)
-        legendfontsize.SetRange(5,100)
-        legendfontsize.SetValue(int(self.properties['font']['prop']['legendSize']))
+        row += 1
+        label = wx.StaticText(
+            parent=self,
+            id=wx.ID_ANY,
+            label=_("Legend font size"))
+        gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
+        legendfontsize = wx.SpinCtrl(parent=self, id=wx.ID_ANY, value="",
+                                     size=(50, -1), style=wx.SP_ARROW_KEYS)
+        legendfontsize.SetRange(5, 100)
+        legendfontsize.SetValue(
+            int(self.properties['font']['prop']['legendSize']))
         self.wxId['font']['legendSize'] = legendfontsize.GetId()
-        gridSizer.Add(item = legendfontsize, pos = (row, 1))
+        gridSizer.Add(item=legendfontsize, pos=(row, 1))
 
         row += 1
-        legendshow = wx.CheckBox(parent = self, id = wx.ID_ANY, label = _("Show legend"))
+        legendshow = wx.CheckBox(
+            parent=self,
+            id=wx.ID_ANY,
+            label=_("Show legend"))
         legendshow.SetValue(self.properties['legend']['enabled'])
         self.wxId['legend']['enabled'] = legendshow.GetId()
-        gridSizer.Add(item = legendshow, pos = (row, 0), span = (1, 2))
+        gridSizer.Add(item=legendshow, pos=(row, 0), span=(1, 2))
 
-        boxMainSizer.Add(item = gridSizer, flag = flag, border = 3)
+        boxMainSizer.Add(item=gridSizer, flag=flag, border=3)
 
-        middleSizer.Add(item = boxMainSizer, flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
+        middleSizer.Add(item=boxMainSizer, flag=wx.LEFT |
+                        wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
 
-        sizer.Add(item = middleSizer, flag = wx.ALL, border = 0)
-        
+        sizer.Add(item=middleSizer, flag=wx.ALL, border=0)
+
         #
         # line & buttons
         #
-        line = wx.StaticLine(parent = self, id = wx.ID_ANY, size = (20, -1), style = wx.LI_HORIZONTAL)
-        sizer.Add(item = line, proportion = 0,
-                  flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, border = 3)
+        line = wx.StaticLine(
+            parent=self, id=wx.ID_ANY, size=(
+                20, -1), style=wx.LI_HORIZONTAL)
+        sizer.Add(item=line, proportion=0, flag=wx.GROW |
+                  wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, border=3)
 
         #
         # buttons
@@ -1137,8 +1425,10 @@
 
         # tooltips for buttons
         btnApply.SetToolTipString(_("Apply changes for the current session"))
-        btnOk.SetToolTipString(_("Apply changes for the current session and close dialog"))
-        btnSave.SetToolTipString(_("Apply and save changes to user settings file (default for next sessions)"))
+        btnOk.SetToolTipString(
+            _("Apply changes for the current session and close dialog"))
+        btnSave.SetToolTipString(
+            _("Apply and save changes to user settings file (default for next sessions)"))
         btnCancel.SetToolTipString(_("Close dialog and ignore changes"))
 
         # sizers
@@ -1147,11 +1437,23 @@
         btnStdSizer.AddButton(btnApply)
         btnStdSizer.AddButton(btnCancel)
         btnStdSizer.Realize()
-        
+
         btnSizer = wx.BoxSizer(wx.HORIZONTAL)
-        btnSizer.Add(item = btnSave, proportion = 0, flag = wx.ALIGN_LEFT | wx.ALL, border = 5)
-        btnSizer.Add(item = btnStdSizer, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
-        sizer.Add(item = btnSizer, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
+        btnSizer.Add(
+            item=btnSave,
+            proportion=0,
+            flag=wx.ALIGN_LEFT | wx.ALL,
+            border=5)
+        btnSizer.Add(
+            item=btnStdSizer,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT | wx.ALL,
+            border=5)
+        sizer.Add(
+            item=btnSizer,
+            proportion=0,
+            flag=wx.ALIGN_RIGHT | wx.ALL,
+            border=5)
 
         #
         # bindings for buttons and map plot settings controls
@@ -1170,24 +1472,41 @@
         """Handler for changing map selection"""
         idx = event.GetSelection()
         self.map = self.rasterList[idx]
-        
+
         # update settings controls for all plots
-        self.FindWindowById(self.wxId['pcolor']).SetColour(self.raster[self.map]['pcolor'])
-        self.FindWindowById(self.wxId['plegend']).SetValue(self.raster[self.map]['plegend'])
+        self.FindWindowById(
+            self.wxId['pcolor']).SetColour(
+            self.raster[self.map]['pcolor'])
+        self.FindWindowById(
+            self.wxId['plegend']).SetValue(
+            self.raster[self.map]['plegend'])
 
         # update settings controls for histograms and profiles
         if self.plottype != 'scatter':
-            self.FindWindowById(self.wxId['pwidth']).SetValue(self.raster[self.map]['pwidth'])
-            self.FindWindowById(self.wxId['pstyle']).SetStringSelection(self.raster[self.map]['pstyle'])
+            self.FindWindowById(
+                self.wxId['pwidth']).SetValue(
+                self.raster[self.map]['pwidth'])
+            self.FindWindowById(
+                self.wxId['pstyle']).SetStringSelection(
+                self.raster[
+                    self.map]['pstyle'])
 
         # update settings controls for scatterplots
         elif self.plottype == 'scatter':
-            self.FindWindowById(self.wxId['psize']).SetValue(self.raster[self.map]['psize'])
-            self.FindWindowById(self.wxId['ptype']).SetStringSelection(self.raster[self.map]['ptype'])
-            self.FindWindowById(self.wxId['pfill']).SetStringSelection(self.raster[self.map]['pfill'])
-            
+            self.FindWindowById(
+                self.wxId['psize']).SetValue(
+                self.raster[self.map]['psize'])
+            self.FindWindowById(
+                self.wxId['ptype']).SetStringSelection(
+                self.raster[
+                    self.map]['ptype'])
+            self.FindWindowById(
+                self.wxId['pfill']).SetStringSelection(
+                self.raster[
+                    self.map]['pfill'])
+
         self.Refresh()
-        
+
     def OnSetOpt(self, event):
         """Handler for changing any other option"""
         self.map = self.rasterList[self.mapchoice.GetCurrentSelection()]
@@ -1198,46 +1517,71 @@
 
     def UpdateSettings(self):
         """Apply settings to each map and to entire plot"""
-        self.raster[self.map]['pcolor'] = self.FindWindowById(self.wxId['pcolor']).GetColour()
+        self.raster[self.map]['pcolor'] = self.FindWindowById(
+            self.wxId['pcolor']).GetColour()
         self.properties['raster']['pcolor'] = self.raster[self.map]['pcolor']
-        
-        self.raster[self.map]['plegend'] = self.FindWindowById(self.wxId['plegend']).GetValue()
-        
+
+        self.raster[self.map]['plegend'] = self.FindWindowById(
+            self.wxId['plegend']).GetValue()
+
         if self.plottype != 'scatter':
-            self.raster[self.map]['pwidth'] = int(self.FindWindowById(self.wxId['pwidth']).GetValue())
-            self.properties['raster']['pwidth'] = self.raster[self.map]['pwidth']
-            self.raster[self.map]['pstyle'] = self.FindWindowById(self.wxId['pstyle']).GetStringSelection()
-            self.properties['raster']['pstyle'] = self.raster[self.map]['pstyle']
-            
+            self.raster[
+                self.map]['pwidth'] = int(
+                self.FindWindowById(
+                    self.wxId['pwidth']).GetValue())
+            self.properties['raster'][
+                'pwidth'] = self.raster[self.map]['pwidth']
+            self.raster[self.map]['pstyle'] = self.FindWindowById(
+                self.wxId['pstyle']).GetStringSelection()
+            self.properties['raster'][
+                'pstyle'] = self.raster[self.map]['pstyle']
+
         elif self.plottype == 'scatter':
-            self.raster[self.map]['psize'] = self.FindWindowById(self.wxId['psize']).GetValue()
+            self.raster[
+                self.map]['psize'] = self.FindWindowById(
+                self.wxId['psize']).GetValue()
             self.properties['raster']['psize'] = self.raster[self.map]['psize']
-            self.raster[self.map]['ptype'] = self.FindWindowById(self.wxId['ptype']).GetStringSelection()
+            self.raster[self.map]['ptype'] = self.FindWindowById(
+                self.wxId['ptype']).GetStringSelection()
             self.properties['raster']['ptype'] = self.raster[self.map]['ptype']
-            self.raster[self.map]['pfill'] = self.FindWindowById(self.wxId['pfill']).GetStringSelection()
+            self.raster[self.map]['pfill'] = self.FindWindowById(
+                self.wxId['pfill']).GetStringSelection()
             self.properties['raster']['pfill'] = self.raster[self.map]['pfill']
 
         # update settings for entire plot
         for axis in ('x-axis', 'y-axis'):
-            self.properties[axis]['prop']['type'] = self.FindWindowById(self.wxId[axis]['type']).GetStringSelection()
-            self.properties[axis]['prop']['min'] = float(self.FindWindowById(self.wxId[axis]['min']).GetValue())
-            self.properties[axis]['prop']['max'] = float(self.FindWindowById(self.wxId[axis]['max']).GetValue())
-            self.properties[axis]['prop']['log'] = self.FindWindowById(self.wxId[axis]['log']).IsChecked()
+            self.properties[axis]['prop']['type'] = self.FindWindowById(
+                self.wxId[axis]['type']).GetStringSelection()
+            self.properties[axis]['prop']['min'] = float(
+                self.FindWindowById(self.wxId[axis]['min']).GetValue())
+            self.properties[axis]['prop']['max'] = float(
+                self.FindWindowById(self.wxId[axis]['max']).GetValue())
+            self.properties[axis]['prop']['log'] = self.FindWindowById(
+                self.wxId[axis]['log']).IsChecked()
 
         if self.plottype == 'profile':
-            self.properties['marker']['color'] = self.FindWindowById(self.wxId['marker']['color']).GetColour()
-            self.properties['marker']['fill'] = self.FindWindowById(self.wxId['marker']['fill']).GetStringSelection()
-            self.properties['marker']['size'] = self.FindWindowById(self.wxId['marker']['size']).GetValue()
-            self.properties['marker']['type'] = self.FindWindowById(self.wxId['marker']['type']).GetStringSelection()
-            self.properties['marker']['legend'] = self.FindWindowById(self.wxId['marker']['legend']).GetValue()
+            self.properties['marker']['color'] = self.FindWindowById(
+                self.wxId['marker']['color']).GetColour()
+            self.properties['marker']['fill'] = self.FindWindowById(
+                self.wxId['marker']['fill']).GetStringSelection()
+            self.properties['marker']['size'] = self.FindWindowById(
+                self.wxId['marker']['size']).GetValue()
+            self.properties['marker']['type'] = self.FindWindowById(
+                self.wxId['marker']['type']).GetStringSelection()
+            self.properties['marker']['legend'] = self.FindWindowById(
+                self.wxId['marker']['legend']).GetValue()
 
-        self.properties['grid']['color'] = self.FindWindowById(self.wxId['grid']['color']).GetColour()
-        self.properties['grid']['enabled'] = self.FindWindowById(self.wxId['grid']['enabled']).IsChecked()
+        self.properties['grid']['color'] = self.FindWindowById(
+            self.wxId['grid']['color']).GetColour()
+        self.properties['grid']['enabled'] = self.FindWindowById(
+            self.wxId['grid']['enabled']).IsChecked()
 
         # this makes more sense in the text properties, including for settings update. But will need to change
         # layout for controls to text dialog too.
-        self.properties['font']['prop']['legendSize'] = self.FindWindowById(self.wxId['font']['legendSize']).GetValue()
-        self.properties['legend']['enabled'] = self.FindWindowById(self.wxId['legend']['enabled']).IsChecked()
+        self.properties['font']['prop']['legendSize'] = self.FindWindowById(
+            self.wxId['font']['legendSize']).GetValue()
+        self.properties['legend']['enabled'] = self.FindWindowById(
+            self.wxId['legend']['enabled']).IsChecked()
 
         self.parent.UpdateLabels()
 
@@ -1245,10 +1589,11 @@
         """Button 'Save' pressed"""
         self.OnApply(None)
         fileSettings = {}
-        UserSettings.ReadSettingsFile(settings = fileSettings)
-        fileSettings[self.plottype] = UserSettings.Get(group = self.plottype)
+        UserSettings.ReadSettingsFile(settings=fileSettings)
+        fileSettings[self.plottype] = UserSettings.Get(group=self.plottype)
         UserSettings.SaveToFile(fileSettings)
-        self.parent.parent.GetLayerManager().GetLogWindow().WriteLog(_('Plot settings saved to file \'%s\'.') % UserSettings.filePath)
+        self.parent.parent.GetLayerManager().GetLogWindow().WriteLog(
+            _('Plot settings saved to file \'%s\'.') % UserSettings.filePath)
         self.Close()
 
     def OnApply(self, event):
@@ -1262,7 +1607,7 @@
         """Button 'OK' pressed"""
         self.OnApply(None)
         self.EndModal(wx.ID_OK)
-        
+
     def OnCancel(self, event):
         """Button 'Cancel' pressed"""
         self.Close()

Modified: grass/trunk/gui/wxpython/wxplot/histogram.py
===================================================================
--- grass/trunk/gui/wxpython/wxplot/histogram.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/wxplot/histogram.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -26,43 +26,58 @@
 import grass.script as grass
 
 from gui_core.toolbars import BaseToolbar, BaseIcons
-from wxplot.base       import BasePlotFrame, PlotIcons
-from wxplot.dialogs    import HistRasterDialog, PlotStatsFrame
-from core.gcmd         import RunCommand, GException, GError
+from wxplot.base import BasePlotFrame, PlotIcons
+from wxplot.dialogs import HistRasterDialog, PlotStatsFrame
+from core.gcmd import RunCommand, GException, GError
 from core.utils import _
 
+
 class HistogramPlotFrame(BasePlotFrame):
     """Mainframe for displaying histogram of raster map. Uses wx.lib.plot.
     """
-    def __init__(self, parent, id = wx.ID_ANY, style = wx.DEFAULT_FRAME_STYLE, 
-                 size = wx.Size(700, 400), rasterList = [], **kwargs):
-        BasePlotFrame.__init__(self, parent, size = size, **kwargs)
-        
-        self.toolbar = HistogramPlotToolbar(parent = self)
+
+    def __init__(self, parent, id=wx.ID_ANY, style=wx.DEFAULT_FRAME_STYLE,
+                 size=wx.Size(700, 400), rasterList=[], **kwargs):
+        BasePlotFrame.__init__(self, parent, size=size, **kwargs)
+
+        self.toolbar = HistogramPlotToolbar(parent=self)
         # workaround for http://trac.wxwidgets.org/ticket/13888
         if sys.platform != 'darwin':
             self.SetToolBar(self.toolbar)
         self.SetTitle(_("GRASS GIS Histogramming Tool"))
-        
+
         #
         # Init variables
         #
         self.rasterList = rasterList
         self.plottype = 'histogram'
-        self.group = '' 
+        self.group = ''
         self.ptitle = _('Histogram of')         # title of window
         self.xlabel = _("Raster cell values")   # default X-axis label
         self.ylabel = _("Cell counts")          # default Y-axis label
         self.maptype = 'raster'                 # default type of histogram to plot
-        self.histtype = 'count' 
+        self.histtype = 'count'
         self.bins = 255
-        self.colorList = ["blue", "green", "red", "yellow", "magenta", "cyan", 
-                          "aqua", "black", "grey", "orange", "brown", "purple", "violet",
-                          "indigo"]
-        
+        self.colorList = [
+            "blue",
+            "green",
+            "red",
+            "yellow",
+            "magenta",
+            "cyan",
+            "aqua",
+            "black",
+            "grey",
+            "orange",
+            "brown",
+            "purple",
+            "violet",
+            "indigo"]
+
         self._initOpts()
-        
-        if len(self.rasterList) > 0: # set raster name(s) from layer manager if a map is selected
+
+        if len(
+                self.rasterList) > 0:  # set raster name(s) from layer manager if a map is selected
             self.raster = self.InitRasterOpts(self.rasterList, self.plottype)
             wx.CallAfter(self.OnCreateHist, None)
         else:
@@ -71,7 +86,7 @@
     def _initOpts(self):
         """Initialize plot options
         """
-        self.InitPlotOpts('histogram')            
+        self.InitPlotOpts('histogram')
 
     def OnCreateHist(self, event):
         """Main routine for creating a histogram. Uses r.stats to
@@ -82,7 +97,7 @@
             self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
         except:
             pass
-        
+
         self.SetGraphStyle()
         wx.BeginBusyCursor()
         wx.SafeYield()
@@ -94,8 +109,8 @@
     def OnSelectRaster(self, event):
         """Select raster map(s) to profile
         """
-        dlg = HistRasterDialog(parent = self)
-        
+        dlg = HistRasterDialog(parent=self)
+
         if dlg.ShowModal() == wx.ID_OK:
             self.rasterList = dlg.rasterList
             self.group = dlg.group
@@ -106,8 +121,8 @@
 
             # plot histogram
             if len(self.rasterList) > 0:
-                self.OnCreateHist(event = None)
-        
+                self.OnCreateHist(event=None)
+
         dlg.Destroy()
 
     def SetupHistogram(self):
@@ -117,61 +132,69 @@
         #
         # populate raster dictionary
         #
-        if len(self.rasterList) == 0: return  # nothing selected
-        
+        if len(self.rasterList) == 0:
+            return  # nothing selected
+
         for r in self.rasterList:
             self.raster[r]['datalist'] = self.CreateDatalist(r)
-            
+
         #
         # update title
         #
         if self.maptype == 'group':
             self.ptitle = _('Histogram of image group <%s>') % self.group
-        else: 
+        else:
             if len(self.rasterList) == 1:
-                self.ptitle = _('Histogram of raster map <%s>') % self.rasterList[0]
+                self.ptitle = _(
+                    'Histogram of raster map <%s>') % self.rasterList[0]
             else:
                 self.ptitle = _('Histogram of selected raster maps')
-        
+
         #
         # set xlabel based on first raster map in list to be histogrammed
         #
         units = self.raster[self.rasterList[0]]['units']
-        if units != '' and units != '(none)' and units != None:
+        if units != '' and units != '(none)' and units is not None:
             self.xlabel = _('Raster cell values %s') % units
         else:
-            self.xlabel = _('Raster cell values') 
+            self.xlabel = _('Raster cell values')
 
         #
         # set ylabel from self.histtype
         #
-        if self.histtype == 'count': self.ylabel = _('Cell counts')
-        if self.histtype == 'percent': self.ylabel = _('Percent of total cells')
-        if self.histtype == 'area': self.ylabel = _('Area')
+        if self.histtype == 'count':
+            self.ylabel = _('Cell counts')
+        if self.histtype == 'percent':
+            self.ylabel = _('Percent of total cells')
+        if self.histtype == 'area':
+            self.ylabel = _('Area')
 
     def CreateDatalist(self, raster):
         """Build a list of cell value, frequency pairs for histogram
             frequency can be in cell counts, percents, or area
         """
         datalist = []
-        
-        if self.histtype == 'count': freqflag = 'cn'
-        if self.histtype == 'percent': freqflag = 'pn'
-        if self.histtype == 'area': freqflag = 'an'
-                
+
+        if self.histtype == 'count':
+            freqflag = 'cn'
+        if self.histtype == 'percent':
+            freqflag = 'pn'
+        if self.histtype == 'area':
+            freqflag = 'an'
+
         try:
             ret = RunCommand("r.stats",
-                             parent = self,
-                             input = raster,
-                             flags = freqflag,
-                             nsteps = self.bins,
-                             sep = ',',
-                             quiet = True,
-                             read = True)
-            
+                             parent=self,
+                             input=raster,
+                             flags=freqflag,
+                             nsteps=self.bins,
+                             sep=',',
+                             quiet=True,
+                             read=True)
+
             if not ret:
                 return datalist
-            
+
             for line in ret.splitlines():
                 cellval, histval = line.strip().split(',')
                 histval = histval.strip()
@@ -180,41 +203,41 @@
                         cellval = '-' + cellval.split('-')[1]
                     else:
                         cellval = cellval.split('-')[0]
-                    
+
                 if self.histtype == 'percent':
                     histval = histval.rstrip('%')
-                    
-                datalist.append((cellval,histval))
 
+                datalist.append((cellval, histval))
+
             return datalist
         except GException as e:
-            GError(parent = self,
-                   message = e.value)
+            GError(parent=self,
+                   message=e.value)
             return None
-        
+
     def CreatePlotList(self):
         """Make list of elements to plot
         """
-        
+
         # graph the cell value, frequency pairs for the histogram
         self.plotlist = []
 
         for r in self.rasterList:
             if len(self.raster[r]['datalist']) > 0:
                 col = wx.Colour(self.raster[r]['pcolor'][0],
-                               self.raster[r]['pcolor'][1],
-                               self.raster[r]['pcolor'][2],
-                               255)
-                
-                self.raster[r]['pline'] = plot.PolyLine(self.raster[r]['datalist'],
-                                                        colour = col,
-                                                        width = self.raster[r]['pwidth'],
-                                                        style = self.linestyledict[self.raster[r]['pstyle']],
-                                                        legend = self.raster[r]['plegend'])
+                                self.raster[r]['pcolor'][1],
+                                self.raster[r]['pcolor'][2],
+                                255)
 
+                self.raster[r]['pline'] = plot.PolyLine(
+                    self.raster[r]['datalist'],
+                    colour=col, width=self.raster[r]['pwidth'],
+                    style=self.linestyledict[self.raster[r]['pstyle']],
+                    legend=self.raster[r]['plegend'])
+
                 self.plotlist.append(self.raster[r]['pline'])
-          
-        if len(self.plotlist) > 0:        
+
+        if len(self.plotlist) > 0:
             return self.plotlist
         else:
             return None
@@ -225,7 +248,7 @@
         self.SetGraphStyle()
         p = self.CreatePlotList()
         self.DrawPlot(p)
- 
+
     def OnStats(self, event):
         """Displays regression information in messagebox
         """
@@ -233,19 +256,22 @@
         title = _('Statistics for Map(s) Histogrammed')
 
         for rast in self.rasterList:
-            ret = grass.read_command('r.univar', map = rast, flags = 'e', quiet = True)
+            ret = grass.read_command(
+                'r.univar', map=rast, flags='e', quiet=True)
             stats = _('Statistics for raster map <%s>') % rast + ':\n%s\n' % ret
             message.append(stats)
-        
-        stats = PlotStatsFrame(self, id = wx.ID_ANY, message = message, 
-                               title = title)
 
+        stats = PlotStatsFrame(self, id=wx.ID_ANY, message=message,
+                               title=title)
+
         if stats.Show() == wx.ID_CLOSE:
-            stats.Destroy()       
+            stats.Destroy()
 
+
 class HistogramPlotToolbar(BaseToolbar):
     """Toolbar for histogramming raster map
     """
+
     def __init__(self, parent):
         BaseToolbar.__init__(self, parent)
 
@@ -254,10 +280,10 @@
             parent.SetToolBar(self)
 
         self.InitToolbar(self._toolbarData())
-        
+
         # realize the toolbar
         self.Realize()
-        
+
     def _toolbarData(self):
         """Toolbar data"""
         return self._getToolbarData((('addraster', BaseIcons["addRast"],
@@ -286,4 +312,4 @@
                                      ('quit', PlotIcons["quit"],
                                       self.parent.OnQuit),
                                      )
-)
+                                    )

Modified: grass/trunk/gui/wxpython/wxplot/profile.py
===================================================================
--- grass/trunk/gui/wxpython/wxplot/profile.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/wxplot/profile.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -31,30 +31,32 @@
 try:
     import numpy
 except ImportError:
-    msg = _("This module requires the NumPy module, which could not be "
-            "imported. It probably is not installed (it's not part of the "
-            "standard Python distribution). See the Numeric Python site "
-            "(http://numpy.scipy.org) for information on downloading source or "
-            "binaries.")
+    msg = _(
+        "This module requires the NumPy module, which could not be "
+        "imported. It probably is not installed (it's not part of the "
+        "standard Python distribution). See the Numeric Python site "
+        "(http://numpy.scipy.org) for information on downloading source or "
+        "binaries.")
     print >> sys.stderr, "wxplot.py: " + msg
 
-from wxplot.base       import BasePlotFrame, PlotIcons
+from wxplot.base import BasePlotFrame, PlotIcons
 from gui_core.toolbars import BaseToolbar, BaseIcons
-from wxplot.dialogs    import ProfileRasterDialog, PlotStatsFrame
-from core.gcmd         import RunCommand, GWarning, GError, GMessage
+from wxplot.dialogs import ProfileRasterDialog, PlotStatsFrame
+from core.gcmd import RunCommand, GWarning, GError, GMessage
 
 
 class ProfileFrame(BasePlotFrame):
     """Mainframe for displaying profile of one or more raster maps. Uses wx.lib.plot.
     """
+
     def __init__(self, parent, controller, units, size=wx.Size(700, 400),
-                 rasterList = None, **kwargs):
+                 rasterList=None, **kwargs):
         BasePlotFrame.__init__(self, parent=parent, size=size, **kwargs)
 
         self.controller = controller
         self.controller.transectChanged.connect(self.SetTransect)
         self.transect = []
-        self.toolbar = ProfileToolbar(parent = self)
+        self.toolbar = ProfileToolbar(parent=self)
         # workaround for http://trac.wxwidgets.org/ticket/13888
         if sys.platform != 'darwin':
             self.SetToolBar(self.toolbar)
@@ -72,20 +74,33 @@
         self.plottype = 'profile'
         self.coordstr = ''              # string of coordinates for r.profile
         self.seglist = []               # segment endpoint list
-        self.ppoints = ''               # segment endpoints data         
-        self.transect_length = 0.0      # total transect length        
+        self.ppoints = ''               # segment endpoints data
+        self.transect_length = 0.0      # total transect length
         self.ptitle = _('Profile of')   # title of window
-        self.colorList =  ["blue", "red", "green", "yellow", "magenta", "cyan",
-                           "aqua", "black", "grey", "orange", "brown", "purple", "violet",
-                           "indigo"]
-        
+        self.colorList = [
+            "blue",
+            "red",
+            "green",
+            "yellow",
+            "magenta",
+            "cyan",
+            "aqua",
+            "black",
+            "grey",
+            "orange",
+            "brown",
+            "purple",
+            "violet",
+            "indigo"]
+
         self._initOpts()
 
-        if len(self.rasterList) > 0: # set raster name(s) from layer manager if a map is selected
+        if len(
+                self.rasterList) > 0:  # set raster name(s) from layer manager if a map is selected
             self.raster = self.InitRasterOpts(self.rasterList, self.plottype)
         else:
             self.raster = {}
-                
+
         # determine units (axis labels)
         # maybe, we should not accept these invalid units
         # but ok, trying to handle it here
@@ -97,7 +112,7 @@
 
         # Bind events
         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
-        
+
     def _initOpts(self):
         """Initialize plot options
         """
@@ -123,15 +138,15 @@
     def OnSelectRaster(self, event):
         """Select raster map(s) to profile
         """
-        dlg = ProfileRasterDialog(parent = self)
+        dlg = ProfileRasterDialog(parent=self)
         dlg.CenterOnParent()
         if dlg.ShowModal() == wx.ID_OK:
             self.rasterList = dlg.rasterList
             self.raster = self.InitRasterOpts(self.rasterList, self.plottype)
-            
+
             # plot profile
             if len(self.transect) > 0 and len(self.rasterList) > 0:
-                self.OnCreateProfile(event = None)
+                self.OnCreateProfile(event=None)
 
         dlg.Destroy()
 
@@ -144,58 +159,66 @@
         cumdist = 0
         self.coordstr = ''
         lasteast = lastnorth = None
-        
+
         region = grass.region()
         insideRegion = True
         if len(self.transect) > 0:
             for point in self.transect:
-                if not (region['w'] <= point[0] <= region['e'] and region['s'] <= point[1] <= region['n']):
+                if not (region['w'] <= point[0] <= region['e']
+                        and region['s'] <= point[1] <= region['n']):
                     insideRegion = False
                 # build string of coordinate points for r.profile
                 if self.coordstr == '':
                     self.coordstr = '%f,%f' % (point[0], point[1])
                 else:
-                    self.coordstr = '%s,%f,%f' % (self.coordstr, point[0], point[1])
-        
+                    self.coordstr = '%s,%f,%f' % (
+                        self.coordstr, point[0], point[1])
+
         if not insideRegion:
-            GWarning(message = _("Not all points of profile lie inside computational region."),
-                     parent = self)
-        
+            GWarning(
+                message=_(
+                    "Not all points of profile lie inside computational region."),
+                parent=self)
+
         if len(self.rasterList) == 0:
             return
-        
+
         # title of window
         self.ptitle = _('Profile of')
-        
+
         # create list of coordinates for transect segment markers
         if len(self.transect) > 0:
             self.seglist = []
             for point in self.transect:
                 # get value of raster cell at coordinate point
                 ret = RunCommand('r.what',
-                                 parent = self,
-                                 read = True,
-                                 map = self.rasterList[0],
-                                 coordinates = '%f,%f' % (point[0], point[1]))
-                
+                                 parent=self,
+                                 read=True,
+                                 map=self.rasterList[0],
+                                 coordinates='%f,%f' % (point[0], point[1]))
+
                 val = ret.splitlines()[0].split('|')[3]
-                if val == None or val == '*':
+                if val is None or val == '*':
                     continue
                 val = float(val)
-                
+
                 # calculate distance between coordinate points
                 if lasteast and lastnorth:
-                    dist = math.sqrt(math.pow((lasteast-point[0]),2) + math.pow((lastnorth-point[1]),2))
+                    dist = math.sqrt(
+                        math.pow((lasteast - point[0]),
+                                 2) + math.pow((lastnorth - point[1]),
+                                               2))
                 cumdist += dist
-                
+
                 # store total transect length
                 self.transect_length = cumdist
-                
-                # build a list of distance,value pairs for each segment of transect
-                self.seglist.append((cumdist,val))
+
+                # build a list of distance,value pairs for each segment of
+                # transect
+                self.seglist.append((cumdist, val))
                 lasteast = point[0]
                 lastnorth = point[1]
-            
+
             # delete extra first segment point
             try:
                 self.seglist.pop(0)
@@ -204,17 +227,17 @@
 
         #
         # create datalist of dist/value pairs and y labels for each raster map
-        #    
+        #
         self.ylabel = ''
         i = 0
-        
+
         for r in self.raster.iterkeys():
             self.raster[r]['datalist'] = []
             datalist = self.CreateDatalist(r, self.coordstr)
-            if len(datalist) > 0:   
+            if len(datalist) > 0:
                 self.raster[r]['datalist'] = datalist
 
-                # update ylabel to match units if they exist           
+                # update ylabel to match units if they exist
                 if self.raster[r]['units'] != '':
                     self.ylabel += '%s (%d),' % (self.raster[r]['units'], i)
                 i += 1
@@ -223,7 +246,7 @@
                 self.ptitle += ' %s ,' % r.split('@')[0]
 
         self.ptitle = self.ptitle.rstrip(',')
-            
+
         if self.ylabel == '':
             self.ylabel = _('Raster values')
         else:
@@ -233,36 +256,37 @@
         """Build a list of distance, value pairs for points along transect using r.profile
         """
         datalist = []
-        
-        # keep total number of transect points to 500 or less to avoid 
+
+        # keep total number of transect points to 500 or less to avoid
         # freezing with large, high resolution maps
         region = grass.region()
-        curr_res = min(float(region['nsres']),float(region['ewres']))
+        curr_res = min(float(region['nsres']), float(region['ewres']))
         transect_rec = 0
         if self.transect_length / curr_res > 500:
             transect_res = self.transect_length / 500
-        else: transect_res = curr_res
-        
+        else:
+            transect_res = curr_res
+
         ret = RunCommand("r.profile",
-                         parent = self,
-                         input = raster,
-                         coordinates = coords,
-                         resolution = transect_res,
-                         null = "nan",
-                         quiet = True,
-                         read = True)
-        
+                         parent=self,
+                         input=raster,
+                         coordinates=coords,
+                         resolution=transect_res,
+                         null="nan",
+                         quiet=True,
+                         read=True)
+
         if not ret:
             return []
-            
+
         for line in ret.splitlines():
             dist, elev = line.strip().split(' ')
-            if dist == None or dist == '' or dist == 'nan' or \
-                elev == None or elev == '' or elev == 'nan':
+            if dist is None or dist == '' or dist == 'nan' or \
+                    elev is None or elev == '' or elev == 'nan':
                 continue
             dist = float(dist)
             elev = float(elev)
-            datalist.append((dist,elev))
+            datalist.append((dist, elev))
 
         return datalist
 
@@ -273,12 +297,13 @@
         transect is in multiple segments, these are drawn as
         points. Profile transect is drawn, using methods in mapdisp.py
         """
-            
+
         if len(self.transect) == 0 or len(self.rasterList) == 0:
-            dlg = wx.MessageDialog(parent = self,
-                                   message = _('You must draw a transect to profile in the map display window.'),
-                                   caption = _('Nothing to profile'),
-                                   style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
+            dlg = wx.MessageDialog(
+                parent=self,
+                message=_('You must draw a transect to profile in the map display window.'),
+                caption=_('Nothing to profile'),
+                style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
             dlg.ShowModal()
             dlg.Destroy()
             return
@@ -297,33 +322,37 @@
         self.plotlist = []
 
         # Add segment marker points to plot data list
-        if len(self.seglist) > 0 :
-            self.ppoints = plot.PolyMarker(self.seglist,
-                                           legend = ' ' + self.properties['marker']['legend'],
-                                           colour = wx.Colour(self.properties['marker']['color'][0],
-                                                           self.properties['marker']['color'][1],
-                                                           self.properties['marker']['color'][2],
-                                                           255),
-                                           size = self.properties['marker']['size'],
-                                           fillstyle = self.ptfilldict[self.properties['marker']['fill']],
-                                           marker = self.properties['marker']['type'])
+        if len(self.seglist) > 0:
+            self.ppoints = plot.PolyMarker(
+                self.seglist,
+                legend=' ' + self.properties['marker']['legend'],
+                colour=wx.Colour(
+                    self.properties['marker']['color'][0],
+                    self.properties['marker']['color'][1],
+                    self.properties['marker']['color'][2],
+                    255),
+                size=self.properties['marker']['size'],
+                fillstyle=self.ptfilldict[
+                    self.properties['marker']['fill']],
+                marker=self.properties['marker']['type'])
             self.plotlist.append(self.ppoints)
 
-        # Add profile distance/elevation pairs to plot data list for each raster profiled
+        # Add profile distance/elevation pairs to plot data list for each
+        # raster profiled
         for r in self.rasterList:
             col = wx.Colour(self.raster[r]['pcolor'][0],
-                           self.raster[r]['pcolor'][1],
-                           self.raster[r]['pcolor'][2],
-                           255)
-            self.raster[r]['pline'] = plot.PolyLine(self.raster[r]['datalist'],
-                                                    colour = col,
-                                                    width = self.raster[r]['pwidth'],
-                                                    style = self.linestyledict[self.raster[r]['pstyle']],
-                                                    legend = self.raster[r]['plegend'])
+                            self.raster[r]['pcolor'][1],
+                            self.raster[r]['pcolor'][2],
+                            255)
+            self.raster[r]['pline'] = plot.PolyLine(
+                self.raster[r]['datalist'],
+                colour=col, width=self.raster[r]['pwidth'],
+                style=self.linestyledict[self.raster[r]['pstyle']],
+                legend=self.raster[r]['plegend'])
 
             self.plotlist.append(self.raster[r]['pline'])
 
-        if len(self.plotlist) > 0:        
+        if len(self.plotlist) > 0:
             return self.plotlist
         else:
             return None
@@ -337,49 +366,60 @@
 
     def SaveProfileToFile(self, event):
         """Save r.profile data to a csv file
-        """   
-        dlg = wx.FileDialog(parent = self,
-                            message = _("Choose prefix for file(s) where to save profile values..."),
-                            defaultDir = os.getcwd(), 
-                            wildcard = _("Comma separated value (*.csv)|*.csv"), style = wx.FD_SAVE)
+        """
+        dlg = wx.FileDialog(
+            parent=self,
+            message=_(
+                "Choose prefix for file(s) where to save profile values..."),
+            defaultDir=os.getcwd(),
+            wildcard=_("Comma separated value (*.csv)|*.csv"),
+            style=wx.FD_SAVE)
         pfile = []
         if dlg.ShowModal() == wx.ID_OK:
             path = dlg.GetPath()
             for r in self.rasterList:
                 pfile.append(path + '_' + str(r.replace('@', '_')) + '.csv')
                 if os.path.exists(pfile[-1]):
-                    dlgOv = wx.MessageDialog(self,
-                                             message = _("File <%s> already exists. "
-                                                         "Do you want to overwrite this file?") % pfile[-1],
-                                             caption = _("Overwrite file?"),
-                                             style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+                    dlgOv = wx.MessageDialog(
+                        self,
+                        message=_(
+                            "File <%s> already exists. "
+                            "Do you want to overwrite this file?") % pfile
+                        [-1],
+                        caption=_("Overwrite file?"),
+                        style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
                     if dlgOv.ShowModal() != wx.ID_YES:
                         pfile.pop()
                         dlgOv.Destroy()
                         continue
-                
+
                 try:
                     fd = open(pfile[-1], "w")
                 except IOError as e:
-                    GError(parent = self,
-                           message = _("Unable to open file <%s> for writing.\n"
-                                       "Reason: %s") % (pfile[-1], e))
+                    GError(parent=self,
+                           message=_("Unable to open file <%s> for writing.\n"
+                                     "Reason: %s") % (pfile[-1], e))
                     dlg.Destroy()
                     return
-                
+
                 for datapair in self.raster[r]['datalist']:
-                    fd.write('%.6f,%.6f\n' % (float(datapair[0]),float(datapair[1])))
-                
+                    fd.write(
+                        '%.6f,%.6f\n' %
+                        (float(
+                            datapair[0]), float(
+                            datapair[1])))
+
                 fd.close()
-        
+
         dlg.Destroy()
         if pfile:
-            message = _("%d files created:\n%s") % (len(pfile), '\n'.join(pfile))
+            message = _("%d files created:\n%s") % (
+                len(pfile), '\n'.join(pfile))
         else:
             message = _("No files generated.")
-        
-        GMessage(parent = self, message = message)
-                        
+
+        GMessage(parent=self, message=message)
+
     def OnStats(self, event):
         """Displays regression information in messagebox
         """
@@ -388,12 +428,12 @@
 
         for r in self.raster.iterkeys():
             try:
-                rast = r.split('@')[0] 
+                rast = r.split('@')[0]
                 statstr = 'Profile of %s\n\n' % rast
 
-                iterable = (i[1] for i in self.raster[r]['datalist'])            
+                iterable = (i[1] for i in self.raster[r]['datalist'])
                 a = numpy.fromiter(iterable, numpy.float)
-                
+
                 statstr += 'n: %f\n' % a.size
                 statstr += 'minimum: %f\n' % numpy.amin(a)
                 statstr += 'maximum: %f\n' % numpy.amax(a)
@@ -401,29 +441,31 @@
                 statstr += 'mean: %f\n' % numpy.mean(a)
                 statstr += 'standard deviation: %f\n' % numpy.std(a)
                 statstr += 'variance: %f\n' % numpy.var(a)
-                cv = numpy.std(a)/numpy.mean(a)
+                cv = numpy.std(a) / numpy.mean(a)
                 statstr += 'coefficient of variation: %f\n' % cv
                 statstr += 'sum: %f\n' % numpy.sum(a)
                 statstr += 'median: %f\n' % numpy.median(a)
-                statstr += 'distance along transect: %f\n\n' % self.transect_length       
+                statstr += 'distance along transect: %f\n\n' % self.transect_length
                 message.append(statstr)
             except:
                 pass
-            
-        stats = PlotStatsFrame(self, id = wx.ID_ANY, message = message, 
-                               title = title)
 
+        stats = PlotStatsFrame(self, id=wx.ID_ANY, message=message,
+                               title=title)
+
         if stats.Show() == wx.ID_CLOSE:
-            stats.Destroy()       
+            stats.Destroy()
 
     def OnCloseWindow(self, event):
         if self.controller.IsActive():
             self.controller.Stop()
         self.Destroy()
-    
+
+
 class ProfileToolbar(BaseToolbar):
     """Toolbar for profiling raster map
     """
+
     def __init__(self, parent):
         BaseToolbar.__init__(self, parent)
 
@@ -432,10 +474,10 @@
             parent.SetToolBar(self)
 
         self.InitToolbar(self._toolbarData())
-        
+
         # realize the toolbar
         self.Realize()
-        
+
     def _toolbarData(self):
         """Toolbar data"""
         return self._getToolbarData((('addraster', BaseIcons["addRast"],

Modified: grass/trunk/gui/wxpython/wxplot/scatter.py
===================================================================
--- grass/trunk/gui/wxpython/wxplot/scatter.py	2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/wxplot/scatter.py	2016-05-03 19:04:42 UTC (rev 68374)
@@ -25,21 +25,23 @@
 
 import grass.script as grass
 
-from wxplot.base       import BasePlotFrame, PlotIcons
+from wxplot.base import BasePlotFrame, PlotIcons
 from gui_core.toolbars import BaseToolbar, BaseIcons
-from wxplot.dialogs    import ScatterRasterDialog, PlotStatsFrame
-from core.gcmd         import RunCommand, GException, GError, GMessage
+from wxplot.dialogs import ScatterRasterDialog, PlotStatsFrame
+from core.gcmd import RunCommand, GException, GError, GMessage
 from core.utils import _
 
+
 class ScatterFrame(BasePlotFrame):
     """Mainframe for displaying bivariate scatter plot of two raster maps. Uses wx.lib.plot.
     """
-    def __init__(self, parent, id = wx.ID_ANY, style = wx.DEFAULT_FRAME_STYLE, 
-                 size = wx.Size(700, 400),
-                 rasterList = [], **kwargs):
-        BasePlotFrame.__init__(self, parent, size = size, **kwargs)
-        
-        self.toolbar = ScatterToolbar(parent = self)
+
+    def __init__(self, parent, id=wx.ID_ANY, style=wx.DEFAULT_FRAME_STYLE,
+                 size=wx.Size(700, 400),
+                 rasterList=[], **kwargs):
+        BasePlotFrame.__init__(self, parent, size=size, **kwargs)
+
+        self.toolbar = ScatterToolbar(parent=self)
         # workaround for http://trac.wxwidgets.org/ticket/13888
         if sys.platform != 'darwin':
             self.SetToolBar(self.toolbar)
@@ -54,15 +56,28 @@
         self.xlabel = _("Raster cell values")           # default X-axis label
         self.ylabel = _("Raster cell values")           # default Y-axis label
         self.maptype = 'raster'                         # default type of scatterplot
-        self.scattertype = 'normal' 
+        self.scattertype = 'normal'
         self.bins = 255
-        self.colorList = ["blue", "red", "black", "green", "yellow", "magenta", "cyan", \
-                    "aqua", "grey", "orange", "brown", "purple", "violet", \
-                    "indigo"]
-        
+        self.colorList = [
+            "blue",
+            "red",
+            "black",
+            "green",
+            "yellow",
+            "magenta",
+            "cyan",
+            "aqua",
+            "grey",
+            "orange",
+            "brown",
+            "purple",
+            "violet",
+            "indigo"]
+
         self._initOpts()
 
-        if len(self.rasterList) > 1: # set raster name(s) from layer manager if a map is selected
+        if len(
+                self.rasterList) > 1:  # set raster name(s) from layer manager if a map is selected
             self.InitRasterOpts(self.rasterList, 'scatter')
         else:
             self.raster = {}
@@ -70,7 +85,7 @@
     def _initOpts(self):
         """Initialize plot options
         """
-        self.InitPlotOpts('scatter')            
+        self.InitPlotOpts('scatter')
 
     def OnCreateScatter(self, event):
         """Main routine for creating a scatterplot. Uses r.stats to
@@ -88,30 +103,33 @@
             wx.EndBusyCursor()
         else:
             wx.EndBusyCursor()
-            GMessage(_("Nothing to plot."), parent = self)
+            GMessage(_("Nothing to plot."), parent=self)
 
     def OnSelectRaster(self, event):
         """Select raster map(s) to profile
         """
-        dlg = ScatterRasterDialog(parent = self)
+        dlg = ScatterRasterDialog(parent=self)
         dlg.CenterOnParent()
         if dlg.ShowModal() == wx.ID_OK:
             self.rasterList = dlg.GetRasterPairs()
             if not self.rasterList:
-                GMessage(_("At least 2 raster maps must be specified"), parent = dlg)
+                GMessage(
+                    _("At least 2 raster maps must be specified"),
+                    parent=dlg)
                 return
-            
+
             # scatterplot or bubbleplot
             # bins for r.stats with float and dcell maps
             self.scattertype, self.bins = dlg.GetSettings()
-            self.raster = self.InitRasterPairs(self.rasterList, 'scatter') # dictionary of raster pairs
-            
+            self.raster = self.InitRasterPairs(
+                self.rasterList, 'scatter')  # dictionary of raster pairs
+
             # plot histogram
             if self.rasterList:
-                self.OnCreateScatter(event = None)
-        
+                self.OnCreateScatter(event=None)
+
         dlg.Destroy()
-        
+
     def SetupScatterplot(self):
         """Build data list for ploting each raster
         """
@@ -119,27 +137,30 @@
         #
         # initialize title string
         #
-        self.ptitle = _('Bivariate Scatterplot of ')        
+        self.ptitle = _('Bivariate Scatterplot of ')
 
         #
         # create a datalist for plotting for each raster pair
         #
-        if len(self.rasterList) == 0: return  # at least 1 pair of maps needed to plot        
-        
+        if len(self.rasterList) == 0:
+            return  # at least 1 pair of maps needed to plot
+
         for rpair in self.rasterList:
             self.raster[rpair]['datalist'] = self.CreateDatalist(rpair)
-            
+
             # update title
-            self.ptitle += '%s vs %s, ' % (rpair[0].split('@')[0], rpair[1].split('@')[0])
+            self.ptitle += '%s vs %s, ' % (
+                rpair[0].split('@')[0],
+                rpair[1].split('@')[0])
 
         self.ptitle = self.ptitle.strip(', ')
-        
+
         #
         # set xlabel & ylabel based on raster maps of first pair to be plotted
         #
         self.xlabel = _('Raster <%s> cell values') % rpair[0].split('@')[0]
         self.ylabel = _('Raster <%s> cell values') % rpair[1].split('@')[0]
-        
+
         units = self.raster[self.rasterList[0]][0]['units']
         if units != '':
             self.xlabel += _(': %s') % units
@@ -147,31 +168,31 @@
         units = self.raster[self.rasterList[0]][1]['units']
         if units != '':
             self.ylabel += _(': %s') % units
-            
+
     def CreateDatalist(self, rpair):
         """Build a list of cell value, frequency pairs for histogram
             frequency can be in cell counts, percents, or area
         """
         datalist = []
-        
-        if self.scattertype == 'bubble': 
+
+        if self.scattertype == 'bubble':
             freqflag = 'cn'
         else:
             freqflag = 'n'
-                
+
         try:
             ret = RunCommand("r.stats",
-                             parent = self,
-                             input = '%s,%s' % rpair,
-                             flags = freqflag,
-                             nsteps = self.bins,
-                             sep = ',',
-                             quiet = True,
-                             read = True)
-            
+                             parent=self,
+                             input='%s,%s' % rpair,
+                             flags=freqflag,
+                             nsteps=self.bins,
+                             sep=',',
+                             quiet=True,
+                             read=True)
+
             if not ret:
                 return datalist
-            
+
             for line in ret.splitlines():
                 rast1, rast2 = line.strip().split(',')
                 rast1 = rast1.strip()
@@ -187,44 +208,45 @@
                         rast2 = '-' + rast2.split('-')[1]
                     else:
                         rast2 = rast2.split('-')[0]
-                
+
                 rast1 = rast1.encode('ascii', 'ignore')
                 rast2 = rast2.encode('ascii', 'ignore')
-                    
-                datalist.append((rast1,rast2))
 
+                datalist.append((rast1, rast2))
+
             return datalist
         except GException as e:
-            GError(parent = self,
-                   message = e.value)
+            GError(parent=self,
+                   message=e.value)
             return None
-        
+
     def CreatePlotList(self):
         """Make list of elements to plot
         """
         # graph the cell value, frequency pairs for the histogram
         self.plotlist = []
-        
+
         for rpair in self.rasterList:
             if 'datalist' not in self.raster[rpair] or \
-                self.raster[rpair]['datalist'] is None:
+                    self.raster[rpair]['datalist'] is None:
                 continue
-            
+
             if len(self.raster[rpair]['datalist']) > 0:
                 col = wx.Colour(self.raster[rpair]['pcolor'][0],
                                 self.raster[rpair]['pcolor'][1],
                                 self.raster[rpair]['pcolor'][2],
                                 255)
-                scatterpoints = plot.PolyMarker(self.raster[rpair]['datalist'],
-                                                legend = ' ' + self.raster[rpair]['plegend'],
-                                                colour = col,size = self.raster[rpair]['psize'],
-                                                fillstyle = self.ptfilldict[self.raster[rpair]['pfill']],
-                                                marker = self.raster[rpair]['ptype'])
+                scatterpoints = plot.PolyMarker(
+                    self.raster[rpair]['datalist'],
+                    legend=' ' + self.raster[rpair]['plegend'],
+                    colour=col, size=self.raster[rpair]['psize'],
+                    fillstyle=self.ptfilldict[self.raster[rpair]['pfill']],
+                    marker=self.raster[rpair]['ptype'])
 
                 self.plotlist.append(scatterpoints)
-        
+
         return self.plotlist
-    
+
     def Update(self):
         """Update histogram after changing options
         """
@@ -233,8 +255,8 @@
         if p:
             self.DrawPlot(p)
         else:
-            GMessage(_("Nothing to plot."), parent = self)
-    
+            GMessage(_("Nothing to plot."), parent=self)
+
     def OnRegression(self, event):
         """Displays regression information in messagebox
         """
@@ -242,18 +264,16 @@
         title = _('Regression Statistics for Scatterplot(s)')
 
         for rpair in self.rasterList:
-            if isinstance(rpair, tuple) == False: continue
+            if isinstance(rpair, tuple) == False:
+                continue
             rast1, rast2 = rpair
-            rast1 = rast1.split('@')[0] 
-            rast2 = rast2.split('@')[0] 
-            ret = grass.parse_command('r.regression.line', 
-                                      mapx = rast1, 
-                                      mapy = rast2, 
-                                      flags = 'g', quiet = True,
-                                      parse = (grass.parse_key_val, { 'sep' : '=' }))
-            eqtitle = _('Regression equation for raster map <%(rast1)s> vs. <%(rast2)s>:\n\n') % \
-                { 'rast1' : rast1,
-                  'rast2' : rast2 }
+            rast1 = rast1.split('@')[0]
+            rast2 = rast2.split('@')[0]
+            ret = grass.parse_command(
+                'r.regression.line', mapx=rast1, mapy=rast2, flags='g',
+                quiet=True, parse=(grass.parse_key_val, {'sep': '='}))
+            eqtitle = _('Regression equation for raster map <%(rast1)s> vs. <%(rast2)s>:\n\n') % {
+                'rast1': rast1, 'rast2': rast2}
             eq = '   %s = %s + %s(%s)\n\n' % (rast2, ret['a'], ret['b'], rast1)
             num = 'N = %s\n' % ret['N']
             rval = 'R = %s\n' % ret['R']
@@ -261,16 +281,18 @@
             ftest = 'F = %s\n' % ret['F']
             str = eqtitle + eq + num + rval + rsq + ftest
             message.append(str)
-            
-        stats = PlotStatsFrame(self, id = wx.ID_ANY, message = message, 
-                                      title = title)
 
+        stats = PlotStatsFrame(self, id=wx.ID_ANY, message=message,
+                               title=title)
+
         if stats.Show() == wx.ID_CLOSE:
-            stats.Destroy()       
+            stats.Destroy()
 
+
 class ScatterToolbar(BaseToolbar):
     """Toolbar for bivariate scatterplots of raster map pairs
     """
+
     def __init__(self, parent):
         BaseToolbar.__init__(self, parent)
 
@@ -279,10 +301,10 @@
             parent.SetToolBar(self)
 
         self.InitToolbar(self._toolbarData())
-        
+
         # realize the toolbar
         self.Realize()
-        
+
     def _toolbarData(self):
         """Toolbar data"""
         return self._getToolbarData((('addraster', BaseIcons["addRast"],



More information about the grass-commit mailing list