[GRASS-SVN] r57416 - in grass/trunk/gui/wxpython: mapdisp wxplot

svn_grass at osgeo.org svn_grass at osgeo.org
Mon Aug 5 08:10:55 PDT 2013


Author: annakrat
Date: 2013-08-05 08:10:55 -0700 (Mon, 05 Aug 2013)
New Revision: 57416

Added:
   grass/trunk/gui/wxpython/mapdisp/analysis.py
Modified:
   grass/trunk/gui/wxpython/mapdisp/frame.py
   grass/trunk/gui/wxpython/mapdisp/mapwindow.py
   grass/trunk/gui/wxpython/wxplot/base.py
   grass/trunk/gui/wxpython/wxplot/profile.py
Log:
wxGUI: base class for profile and measure tool

Added: grass/trunk/gui/wxpython/mapdisp/analysis.py
===================================================================
--- grass/trunk/gui/wxpython/mapdisp/analysis.py	                        (rev 0)
+++ grass/trunk/gui/wxpython/mapdisp/analysis.py	2013-08-05 15:10:55 UTC (rev 57416)
@@ -0,0 +1,284 @@
+# -*- coding: utf-8 -*-
+"""!
+ at package mapdisp.analysis
+
+ at brief Map display controllers for analyses (profiling, measuring)
+
+Classes:
+ - analysis::AnalysisControllerBase
+ - analysis::ProfileController
+ - analysis::MeasureDistanceController
+
+(C) 2013 by the GRASS Development Team
+
+This program is free software under the GNU General Public License
+(>=v2). Read the file COPYING that comes with GRASS for details.
+
+ at author Anna Petrasova <kratochanna gmail.com>
+"""
+
+import os
+import math
+import wx
+
+from core.utils import _
+import core.units as units
+
+from grass.pydispatch.signal import Signal
+
+
+class AnalysisControllerBase:
+    """!Base class for analysis which require drawing line in map display."""
+    def __init__(self, giface, mapWindow):
+        """!
+
+        @param giface grass interface
+        @param mapWindow instance of BufferedWindow
+        """
+        self._giface = giface
+        self._mapWindow = mapWindow
+
+        self._registeredGraphics = None
+
+        self._oldMouseUse = None
+        self._oldCursor = None
+
+    def IsActive(self):
+        """!Returns True if analysis mode is activated."""
+        return bool(self._registeredGraphics)
+
+    def _start(self, x, y):
+        """!Handles the actual start of drawing line
+        and adding each new point.
+
+        @param x,y east north coordinates
+        """
+        if not self._registeredGraphics.GetAllItems():
+            item = self._registeredGraphics.AddItem(coords=[[x, y]])
+            item.SetPropertyVal('penName', 'analysisPen')
+        else:
+            # 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)
+
+    def _addPoint(self, x, y):
+        """!New point added.
+
+        @param x,y east north coordinates
+        """
+        # add new point and calculate distance
+        item = self._registeredGraphics.GetItem(0)
+        coords = item.GetCoords() + [[x, y]]
+        item.SetCoords(coords)
+        # draw
+        self._mapWindow.ClearLines()
+        self._registeredGraphics.Draw(pdc=self._mapWindow.pdcTmp)
+        wx.Yield()
+
+        self._doAnalysis(coords)
+
+    def _doAnalysis(self, coords):
+        """!Perform the required analysis
+        (compute distnace, update profile)
+
+        @param coords EN coordinates
+        """
+        raise NotImplementedError()
+
+    def _disconnectAll(self):
+        """!Disconnect all mouse signals
+        to stop drawing."""
+        raise NotImplementedError()
+
+    def _connectAll(self):
+        """!Connect all mouse signals to draw."""
+        raise NotImplementedError()
+
+    def _getPen(self):
+        """!Returns wx.Pen instance."""
+        raise NotImplementedError()
+
+    def Stop(self, restore=True):
+        """!Analysis mode is stopped.
+
+        @param restore if restore previous cursor, mouse['use']
+        """
+        self._mapWindow.ClearLines(pdc=self._mapWindow.pdcTmp)
+        self._mapWindow.mouse['end'] = self._mapWindow.mouse['begin']
+        # disconnect mouse events
+        self._disconnectAll()
+        # unregister
+        self._mapWindow.UnregisterGraphicsToDraw(self._registeredGraphics)
+        self._registeredGraphics = None
+        self._mapWindow.Refresh()
+
+        if restore:
+            # restore mouse['use'] and cursor to the state before measuring starts
+            self._mapWindow.SetNamedCursor(self._oldCursor)
+            self._mapWindow.mouse['use'] = self._oldMouseUse
+
+    def Start(self):
+        """!Init analysis: register graphics to map window,
+        connect required mouse signals.
+        """
+        self._oldMouseUse = self._mapWindow.mouse['use']
+        self._oldCursor = self._mapWindow.GetNamedCursor()
+
+        self._registeredGraphics = self._mapWindow.RegisterGraphicsToDraw(graphicsType='line')
+
+        self._connectAll()
+
+        # change mouse['box'] and pen to draw line during dragging
+        # 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._registeredGraphics.AddPen('analysisPen', self._getPen())
+
+        # change the cursor
+        self._mapWindow.SetNamedCursor('pencil')
+
+
+class ProfileController(AnalysisControllerBase):
+    """!Class controls profiling in map display.
+    It should be used inside ProfileFrame
+    """
+    def __init__(self, giface, mapWindow):
+        AnalysisControllerBase.__init__(self, giface=giface, mapWindow=mapWindow)
+
+        self.transectChanged = Signal('ProfileController.transectChanged')
+
+    def _doAnalysis(self, coords):
+        """!Informs profile dialog that profile changed.
+
+        @param coords EN coordinates
+        """
+        self.transectChanged.emit(coords=coords)
+
+    def _disconnectAll(self):
+        self._mapWindow.mouseLeftDown.disconnect(self._start)
+        self._mapWindow.mouseLeftUp.disconnect(self._addPoint)
+
+    def _connectAll(self):
+        self._mapWindow.mouseLeftDown.connect(self._start)
+        self._mapWindow.mouseLeftUp.connect(self._addPoint)
+
+    def _getPen(self):
+        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)
+
+        self.transectChanged.emit(coords=[])
+
+
+class MeasureDistanceController(AnalysisControllerBase):
+    """!Class controls measuring distance in map display."""
+    def __init__(self, giface, mapWindow):
+        AnalysisControllerBase.__init__(self, giface=giface, mapWindow=mapWindow)
+
+        self._projInfo = self._mapWindow.Map.projinfo
+        self._totaldist = 0.0  # total measured distance
+        self._useCtypes = False
+
+    def _doAnalysis(self, coords):
+        """!New point added.
+
+        @param x,y east north coordinates
+        """
+        self.MeasureDist(coords[-2], coords[-1])
+
+    def _disconnectAll(self):
+        self._mapWindow.mouseLeftDown.disconnect(self._start)
+        self._mapWindow.mouseLeftUp.disconnect(self._addPoint)
+        self._mapWindow.mouseDClick.disconnect(self.Stop)
+
+    def _connectAll(self):
+        self._mapWindow.mouseLeftDown.connect(self._start)
+        self._mapWindow.mouseLeftUp.connect(self._addPoint)
+        self._mapWindow.mouseDClick.connect(self.Stop)
+
+    def _getPen(self):
+        return wx.Pen(colour='green', width=2, style=wx.SHORT_DASH)
+
+    def Stop(self, restore=True):
+        AnalysisControllerBase.Stop(self, restore=restore)
+
+        self._giface.WriteCmdLog(_('Measuring finished'))
+
+    def Start(self):
+        """!Init measurement routine that calculates map distance
+        along transect drawn on map display
+        """
+        AnalysisControllerBase.Start(self)
+        self._totaldist = 0.0  # total measured distance
+
+        # 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))
+        if self._projInfo['proj'] != 'xy':
+            mapunits = self._projInfo['units']
+            self._giface.WriteCmdLog(_('Measuring distance') + ' ('
+                                      + mapunits + '):')
+        else:
+            self._giface.WriteCmdLog(_('Measuring distance:'))
+
+        if self._projInfo['proj'] == 'll':
+            try:
+                import grass.lib.gis as gislib
+                gislib.G_begin_distance_calculations()
+                self._useCtypes = True
+            except ImportError, e:
+                self._giface.WriteWarning(_('Geodesic distance calculation '
+                                            'is not available.\n'
+                                            'Reason: %s' % e))
+
+    def MeasureDist(self, beginpt, endpt):
+        """!Calculate distance and print to output window.
+
+        @param beginpt,endpt EN coordinates
+        """
+        # move also Distance method?
+        dist, (north, east) = self._mapWindow.Distance(beginpt, endpt, screen=False)
+
+        dist = round(dist, 3)
+        mapunits = self._projInfo['units']
+        if mapunits == 'degrees' and self._useCtypes:
+            mapunits = 'meters'
+        d, dunits = units.formatDist(dist, mapunits)
+
+        self._totaldist += dist
+        td, tdunits = units.formatDist(self._totaldist,
+                                       mapunits)
+
+        strdist = str(d)
+        strtotdist = str(td)
+
+        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)
+            #angle = 90 - angle
+            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)
+        else:
+            mstring = '%s = %s %s\n%s = %s %s\n%s' \
+                % (_('segment'), strdist, dunits,
+                   _('total distance'), strtotdist, tdunits,
+                   '-' * 60)
+
+        self._giface.WriteLog(mstring, priority=2)
+
+        return dist


Property changes on: grass/trunk/gui/wxpython/mapdisp/analysis.py
___________________________________________________________________
Added: svn:mime-type
   + text/x-python
Added: svn:eol-style
   + native

Modified: grass/trunk/gui/wxpython/mapdisp/frame.py
===================================================================
--- grass/trunk/gui/wxpython/mapdisp/frame.py	2013-08-05 11:07:37 UTC (rev 57415)
+++ grass/trunk/gui/wxpython/mapdisp/frame.py	2013-08-05 15:10:55 UTC (rev 57416)
@@ -24,7 +24,6 @@
 
 import os
 import sys
-import math
 import copy
 
 from core import globalvar
@@ -37,7 +36,6 @@
     sys.path.append(os.path.join(globalvar.ETCDIR, "python"))
 
 from core               import globalvar
-import core.units as units
 from core.render        import Map
 from vdigit.toolbars    import VDigitToolbar
 from mapdisp.toolbars   import MapToolbar, NvizIcons
@@ -58,6 +56,7 @@
 from wxplot.histogram   import HistogramPlotFrame
 from wxplot.profile     import ProfileFrame
 from wxplot.scatter     import ScatterFrame
+from mapdisp.analysis import ProfileController, MeasureDistanceController
 
 from mapdisp import statusbar as sb
 
@@ -218,7 +217,7 @@
 
         self.decorationDialog = None # decoration/overlays
         
-        self.measureController = None
+        self.measureDistController = None
 
     def GetMapWindow(self):
         return self.MapWindow
@@ -489,12 +488,6 @@
         """
         self.RemoveQueryLayer()
         
-        # delete tmp lines
-        if self.MapWindow.mouse["use"] in ("measure",
-                                           "profile"):
-            self.MapWindow.polycoords = []
-            self.MapWindow.ClearLines()
-        
         # deselect features in vdigit
         if self.GetToolbar('vdigit'):
             if self.MapWindow.digit:
@@ -865,20 +858,23 @@
             return cmd
 
     def OnMeasure(self, event):
-        if not self.measureController:
-            self.measureController = MeasureController(self._giface)
-        self.measureController.StartMeasurement()
+        if not self.measureDistController:
+            self.measureDistController = MeasureDistanceController(self._giface,
+                                                                   mapWindow=self.GetMapWindow())
+        self.measureDistController.Start()
 
     def OnProfile(self, event):
         """!Launch profile tool
         """
+        self.profileController = ProfileController(self._giface, mapWindow=self.GetMapWindow())
         rasters = []
         layers = self._giface.GetLayerList().GetSelectedLayers()
         for layer in layers:
             if layer.type == 'raster':
                 rasters.append(layer.maplayer.name)
 
-        win = ProfileFrame(parent = self, mapwindow = self.GetMapWindow(), rasterList = rasters)
+        win = ProfileFrame(parent=self, rasterList=rasters,
+                           controller=self.profileController)
         
         win.CentreOnParent()
         win.Show()
@@ -1202,8 +1198,8 @@
             if btn.GetValue():
                 btn.SetValue(0)
                 self.dialogs['legend'].DisconnectResizing()
-        if self.measureController and self.measureController.IsMeasuring():
-            self.measureController.StopMeasurement(restore=False)
+        if self.measureDistController and self.measureDistController.IsActive():
+            self.measureDistController.Stop(restore=False)
 
     def ResetPointer(self):
         """Sets pointer mode.
@@ -1217,166 +1213,3 @@
         toolbar.action['id'] = vars(toolbar)["pointer"]
         toolbar.OnTool(None)
         self.OnPointer(event=None)
-
-
-class MeasureController:
-    """!Class controls measuring in map display."""
-    def __init__(self, giface):
-        self._giface = giface
-        self._mapWindow = self._giface.GetMapWindow()
-        self._projInfo = self._mapWindow.Map.projinfo
-        self._measureGraphics = None
-
-        self._totaldist = 0.0 # total measured distance
-
-        self._oldMouseUse = None
-        self._oldCursor = None
-
-        self._useCtypes = False
-
-    def IsMeasuring(self):
-        """!Returns True if measuring mode is enabled, otherwise False"""
-        return bool(self._measureGraphics)
-
-    def _startMeasurement(self, x, y):
-        """!Handles the actual start of measuring
-        and adding each new point.
-        
-        @param x,y east north coordinates
-        """
-        if not self._measureGraphics.GetAllItems():
-            item = self._measureGraphics.AddItem(coords=[[x, y]])
-            item.SetPropertyVal('penName', 'measure')
-        else:
-            # needed to switch mouse begin and end to draw intermediate line properly
-            coords = self._measureGraphics.GetItem(0).GetCoords()[-1]
-            self._mapWindow.mouse['begin'] = self._mapWindow.Cell2Pixel(coords)
-
-    def _addMeasurement(self, x, y):
-        """!New point added.
-
-        @param x,y east north coordinates
-        """
-        # add new point and calculate distance
-        item = self._measureGraphics.GetItem(0)
-        coords = item.GetCoords() + [[x, y]]
-        item.SetCoords(coords)
-        self.MeasureDist(coords[-2], coords[-1])
-        # draw
-        self._mapWindow.ClearLines()
-        self._measureGraphics.Draw(pdc=self._mapWindow.pdcTmp)
-        
-    def StopMeasurement(self, restore=True):
-        """!Measure mode is stopped."""
-        self._mapWindow.ClearLines(pdc=self._mapWindow.pdcTmp)
-        self._mapWindow.mouse['end'] = self._mapWindow.mouse['begin']
-        # disconnect mouse events
-        self._mapWindow.mouseLeftUp.disconnect(self._addMeasurement)
-        self._mapWindow.mouseDClick.disconnect(self.StopMeasurement)
-        self._mapWindow.mouseLeftDown.disconnect(self._startMeasurement)
-        # unregister
-        self._mapWindow.UnregisterGraphicsToDraw(self._measureGraphics)
-        self._measureGraphics = None
-        self._mapWindow.Refresh()
-
-        if restore:
-            # restore mouse['use'] and cursor to the state before measuring starts
-            self._mapWindow.SetNamedCursor(self._oldCursor)
-            self._mapWindow.mouse['use'] = self._oldMouseUse
-        
-        self._giface.WriteCmdLog(_('Measuring finished'))
-
-    def StartMeasurement(self):
-        """!Init measurement routine that calculates map distance
-        along transect drawn on map display
-        """
-        self._totaldist = 0.0 # total measured distance
-        
-        self._oldMouseUse = self._mapWindow.mouse['use']
-        self._oldCursor = self._mapWindow.GetNamedCursor()
-
-        self._measureGraphics = self._mapWindow.RegisterGraphicsToDraw(graphicsType='line')
-
-        self._mapWindow.mouseLeftDown.connect(self._startMeasurement)
-        self._mapWindow.mouseDClick.connect(self.StopMeasurement)
-        self._mapWindow.mouseLeftUp.connect(self._addMeasurement)
-
-        # change mouse['box'] and pen to draw line during dragging
-        # TODO: better soluyion 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._measureGraphics.AddPen('measure', wx.Pen(colour='green', width=2, style=wx.SHORT_DASH) )
-        
-        # change the cursor
-        self._mapWindow.SetNamedCursor('pencil')
-        
-        # 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))
-        if self._projInfo['proj'] != 'xy':
-            mapunits = self._projInfo['units']
-            self._giface.WriteCmdLog(_('Measuring distance') + ' ('
-                                      + mapunits + '):')
-        else:
-            self._giface.WriteCmdLog(_('Measuring distance:'))
-        
-        if self._projInfo['proj'] == 'll':
-            try:
-                import grass.lib.gis as gislib
-                gislib.G_begin_distance_calculations()
-                self._useCtypes = True
-            except ImportError, e:
-                self._giface.WriteWarning(_('Geodesic distance calculation '
-                                            'is not available.\n'
-                                            'Reason: %s' % e))
-        
-    def MeasureDist(self, beginpt, endpt):
-        """!Calculate distance and print to output window.
-        
-        @param beginpt,endpt EN coordinates
-        """
-        # move also Distance method?
-        dist, (north, east) = self._mapWindow.Distance(beginpt, endpt, screen=False)
-        
-        dist = round(dist, 3)
-        mapunits = self._projInfo['units']
-        if mapunits == 'degrees' and self._useCtypes:
-            mapunits = 'meters'
-        d, dunits = units.formatDist(dist, mapunits)
-        
-        self._totaldist += dist
-        td, tdunits = units.formatDist(self._totaldist,
-                                       mapunits)
-        
-        strdist = str(d)
-        strtotdist = str(td)
-        
-        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)
-            #angle = 90 - angle
-            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)
-        else:
-            mstring = '%s = %s %s\n%s = %s %s\n%s' \
-                % (_('segment'), strdist, dunits,
-                   _('total distance'), strtotdist, tdunits,
-                   '-' * 60)
-        
-        self._giface.WriteLog(mstring, priority=2)
-        
-        return dist

Modified: grass/trunk/gui/wxpython/mapdisp/mapwindow.py
===================================================================
--- grass/trunk/gui/wxpython/mapdisp/mapwindow.py	2013-08-05 11:07:37 UTC (rev 57415)
+++ grass/trunk/gui/wxpython/mapdisp/mapwindow.py	2013-08-05 15:10:55 UTC (rev 57416)
@@ -1111,19 +1111,11 @@
         """
         Debug.msg (5, "BufferedWindow.OnLeftDown(): use=%s" % \
                    self.mouse["use"])
-        
+
         self.mouse['begin'] = event.GetPositionTuple()[:]
-        
-        if self.mouse["use"] in ["profile"]:
-            if len(self.polycoords) == 0:
-                self.mouse['end'] = self.mouse['begin']
-                self.polycoords.append(self.Pixel2Cell(self.mouse['begin']))
-                self.ClearLines(pdc=self.pdcTmp)
-            else:
-                self.mouse['begin'] = self.mouse['end']
-        
+
         # vector digizer
-        elif self.mouse["use"] == "pointer" and \
+        if self.mouse["use"] == "pointer" and \
                 hasattr(self, "digit"):
             if event.ControlDown():
                 self.OnLeftDownUndo(event)
@@ -1177,11 +1169,6 @@
         elif self.mouse["use"] == "query":
             self.mapQueried.emit(x=self.mouse['end'][0], y=self.mouse['end'][1])
 
-        elif self.mouse["use"] in ["profile"]:            
-            self.polycoords.append(self.Pixel2Cell(self.mouse['end']))
-            self.ClearLines(pdc = self.pdcTmp)
-            self.DrawLines(pdc = self.pdcTmp)
-
         elif self.mouse["use"] == "pointer" and \
                 hasattr(self, "digit"):
             self._onLeftUp(event)
@@ -1212,9 +1199,8 @@
         
         screenCoords = event.GetPosition()
 
-        if self.mouse["use"] != "profile" or \
-                (self.mouse['use'] != 'pointer' and \
-                     hasattr(self, "digit")):
+        if self.mouse['use'] != 'pointer' and \
+                     hasattr(self, "digit"):
                # select overlay decoration options dialog
             idlist  = self.pdc.FindObjects(screenCoords[0], screenCoords[1], self.hitradius)
             if idlist:

Modified: grass/trunk/gui/wxpython/wxplot/base.py
===================================================================
--- grass/trunk/gui/wxpython/wxplot/base.py	2013-08-05 11:07:37 UTC (rev 57415)
+++ grass/trunk/gui/wxpython/wxplot/base.py	2013-08-05 15:10:55 UTC (rev 57416)
@@ -47,13 +47,12 @@
 
 class BasePlotFrame(wx.Frame):
     """!Abstract PyPlot display frame class"""
-    def __init__(self, parent = None, mapwindow = None, id = wx.ID_ANY, size = wx.Size(700, 400),
-                 style = wx.DEFAULT_FRAME_STYLE, rasterList = [],  **kwargs):
+    def __init__(self, parent=None, size=wx.Size(700, 400),
+                 style=wx.DEFAULT_FRAME_STYLE, rasterList=[],  **kwargs):
 
-        wx.Frame.__init__(self, parent, id, size = size, style = style, **kwargs)
+        wx.Frame.__init__(self, parent, id=wx.ID_ANY, size = size, style = style, **kwargs)
         
         self.parent = parent # MapFrame for a plot type
-        self.mapwin = mapwindow
         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
@@ -100,11 +99,6 @@
         self.xlabel = ""        # default X-axis label
         self.ylabel = ""        # default Y-axis label
 
-        #
-        # Bind various events
-        #
-        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
-        
         self.CentreOnScreen()
         
         self._createColorDict()
@@ -431,10 +425,6 @@
         """!Erase the plot window
         """
         self.client.Clear()
-        self.mapwin.ClearLines(self.mapwin.pdc)
-        self.mapwin.ClearLines(self.mapwin.pdcTmp)
-        self.mapwin.polycoords = []
-        self.mapwin.Refresh()
 
     def SaveToFile(self, event):
         """!Save plot to graphics file
@@ -535,7 +525,8 @@
         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):
         """!Print options and output menu
@@ -564,22 +555,4 @@
         self.client.Printout()
 
     def OnQuit(self, event):
-        self.Close(True)
-
-    def OnCloseWindow(self, event):
-        """!Close plot window and clean up
-        """
-        try:
-            self.mapwin.ClearLines()
-            self.mapwin.mouse['begin'] = self.mapwin.mouse['end'] = (0.0, 0.0)
-            self.mapwin.mouse['use'] = 'pointer'
-            self.mapwin.mouse['box'] = 'point'
-            self.mapwin.polycoords = []
-            self.mapwin.UpdateMap(render = False, renderVector = False)
-        except:
-            pass
-
-        if self.mapwin:
-            self.mapwin.SetNamedCursor('default')
-        self.Destroy()
-        
+        self.Close(True)        

Modified: grass/trunk/gui/wxpython/wxplot/profile.py
===================================================================
--- grass/trunk/gui/wxpython/wxplot/profile.py	2013-08-05 11:07:37 UTC (rev 57415)
+++ grass/trunk/gui/wxpython/wxplot/profile.py	2013-08-05 15:10:55 UTC (rev 57416)
@@ -43,11 +43,13 @@
 class ProfileFrame(BasePlotFrame):
     """!Mainframe for displaying profile of one or more raster maps. Uses wx.lib.plot.
     """
-    def __init__(self, parent, mapwindow, id = wx.ID_ANY, style = wx.DEFAULT_FRAME_STYLE, 
-                 size = wx.Size(700, 400),
+    def __init__(self, parent, controller, size=wx.Size(700, 400),
                  rasterList = [], **kwargs):
-        BasePlotFrame.__init__(self, parent, mapwindow = mapwindow, size = size, **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.SetToolBar(self.toolbar)
         self.SetTitle(_("GRASS Profile Analysis Tool"))
@@ -79,29 +81,31 @@
         else:
             self.xlabel = _("Distance along transect")
         self.ylabel = _("Cell values")
+
+        # Bind events
+        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
         
     def _initOpts(self):
         """!Initialize plot options
         """
         self.InitPlotOpts('profile')
 
+    def SetTransect(self, coords):
+        self.transect = coords
+        if coords:
+            self.OnCreateProfile(None)
+        else:
+            self.OnErase(None)
+
     def OnDrawTransect(self, event):
         """!Draws transect to profile in map display
         """
-        self.parent.SwitchTool(self.parent.toolbars['map'], event)
-        self.mapwin.polycoords = []
-        self.seglist = []
-        self.mapwin.ClearLines(self.mapwin.pdc)
-        self.ppoints = ''
+        if self.controller.IsActive():
+            self.controller.Stop()
+        self.controller.Start()
 
         self.parent.SetFocus()
         self.parent.Raise()
-        
-        self.mapwin.mouse['use'] = 'profile'
-        self.mapwin.mouse['box'] = 'line'
-        self.mapwin.pen = wx.Pen(colour = 'Red', width = 2, style = wx.SHORT_DASH)
-        self.mapwin.polypen = wx.Pen(colour = 'dark green', width = 2, style = wx.SHORT_DASH)
-        self.mapwin.SetNamedCursor('cross')
 
     def OnSelectRaster(self, event):
         """!Select raster map(s) to profile
@@ -113,7 +117,7 @@
             self.raster = self.InitRasterOpts(self.rasterList, self.plottype)
             
             # plot profile
-            if len(self.mapwin.polycoords) > 0 and len(self.rasterList) > 0:
+            if len(self.transect) > 0 and len(self.rasterList) > 0:
                 self.OnCreateProfile(event = None)
 
         dlg.Destroy()
@@ -130,8 +134,8 @@
         
         region = grass.region()
         insideRegion = True
-        if len(self.mapwin.polycoords) > 0:
-            for point in self.mapwin.polycoords:
+        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']):
                     insideRegion = False
                 # build string of coordinate points for r.profile
@@ -151,9 +155,9 @@
         self.ptitle = _('Profile of')
         
         # create list of coordinates for transect segment markers
-        if len(self.mapwin.polycoords) > 0:
+        if len(self.transect) > 0:
             self.seglist = []
-            for point in self.mapwin.polycoords:
+            for point in self.transect:
                 # get value of raster cell at coordinate point
                 ret = RunCommand('r.what',
                                  parent = self,
@@ -257,7 +261,7 @@
         points. Profile transect is drawn, using methods in mapdisp.py
         """
             
-        if len(self.mapwin.polycoords) == 0 or len(self.rasterList) == 0:
+        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'),
@@ -266,18 +270,12 @@
             dlg.Destroy()
             return
 
-        self.mapwin.SetNamedCursor('default')
         self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
-        self.SetGraphStyle()
+
         self.SetupProfile()
         p = self.CreatePlotList()
         self.DrawPlot(p)
 
-        # reset transect
-        self.mapwin.mouse['begin'] = self.mapwin.mouse['end'] = (0.0,0.0)
-        self.mapwin.mouse['use'] = 'pointer'
-        self.mapwin.mouse['box'] = 'point'
-
     def CreatePlotList(self):
         """!Create a plot data list from transect datalist and
             transect segment endpoint coordinates.
@@ -405,6 +403,10 @@
         if stats.Show() == wx.ID_CLOSE:
             stats.Destroy()       
 
+    def OnCloseWindow(self, event):
+        if self.controller.IsActive():
+            self.controller.Stop()
+        self.Destroy()
     
 class ProfileToolbar(BaseToolbar):
     """!Toolbar for profiling raster map



More information about the grass-commit mailing list