Sfoglia il codice sorgente

g.gui.rlisetup: a lot of improvements, thanks also to Mohammed Rashad

git-svn-id: https://svn.osgeo.org/grass/grass/trunk@59197 15284696-431f-4ddb-bdfa-cd5b030d7da7
Luca Delucchi 11 anni fa
parent
commit
a4a9ecf544

+ 1 - 0
gui/wxpython/rlisetup/__init__.py

@@ -3,4 +3,5 @@ all = [
     'wizard',
     'functions',
     'frame',
+    'sampling_frame'
     ]

+ 138 - 23
gui/wxpython/rlisetup/frame.py

@@ -13,16 +13,101 @@ from core.utils import _
 from grass.script import core as grass
 from rlisetup.functions import retRLiPath
 from rlisetup.wizard import RLIWizard
+import locale
+import codecs
 
 
+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
+        self.parent = parent
+        self.rlipath = retRLiPath()
+        self.confile = conf
+        self.pathfile = os.path.join(self.rlipath, conf)
+        wx.Frame.__init__(self, parent=parent, id=id, title=title,
+                          **kwargs)
+        self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, '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.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
+        self.btn_close = wx.Button(parent=self, id=wx.ID_CLOSE)
+        self.btn_ok = wx.Button(parent=self, id=wx.ID_OK)
+        self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
+        self.btn_ok.Bind(wx.EVT_BUTTON, self.OnOk)
+        self._layout()
+        self.enc = locale.getdefaultlocale()[1]
+
+    def _layout(self):
+        """Set the layout"""
+        panelsizer = wx.GridBagSizer(1, 1)
+        mainsizer = wx.BoxSizer(wx.VERTICAL)
+        ###CONFILES
+        confilesSizer = wx.StaticBoxSizer(self.confilesBox, wx.HORIZONTAL)
+        confilesSizer.Add(item=self.textCtrl, proportion=1, flag=wx.EXPAND)
+        ###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
+        panelsizer.Add(item=confilesSizer, pos=(0, 0), flag=wx.EXPAND,
+                       border=3)
+        #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)
+        panelsizer.AddGrowableCol(0)
+        self.panel.SetAutoLayout(True)
+        self.panel.SetSizerAndFit(panelsizer)
+        self.SetSizer(mainsizer)
+        self.Layout()
+
+    def OnClose(self, event):
+        """!Close window"""
+        self.Destroy()
+
+    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)
+
+        if dlg.ShowModal() == wx.ID_YES:
+            f = codecs.open(self.pathfile, encoding=self.enc, mode='w',
+                            errors='replace')
+            f.write(self.text + os.linesep)
+            f.close()
+        dlg.Destroy()
+        self.Destroy()
+
+    def OnFileText(self, event):
+        """File input interactively entered"""
+        self.text = event.GetString()
+
 class RLiSetupFrame(wx.Frame):
 
-    def __init__(self, parent, giface = None, id=wx.ID_ANY, title=_("GRASS" \
+    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.cmd = "r.li.setup"
         self.rlipath = retRLiPath()
         self.listfiles = self.ListFiles()
         ###END VARIABLES
@@ -37,25 +122,29 @@ class RLiSetupFrame(wx.Frame):
                                         label=_('Available sampling area configuration files'))
         self.listfileBox = wx.ListBox(parent=self.panel,  id=wx.ID_ANY,
                     choices=self.listfiles)
-        ###BUTTONS
-        #definition
-        self.btn_close = wx.Button(parent=self.panel, id=wx.ID_CLOSE)
-        self.btn_help = wx.Button(parent=self.panel, id=wx.ID_HELP)
-        self.btn_remove = wx.Button(parent=self.panel, id=wx.ID_ANY,
+
+        ###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,
                                     label=_("Remove"))
         self.btn_remove.SetToolTipString(_('Remove a configuration file'))
-        self.btn_new = wx.Button(parent=self.panel, id=wx.ID_ANY,
+        self.btn_new = wx.Button(parent=self, id=wx.ID_ANY,
                                  label=_("Create"))
         self.btn_new.SetToolTipString(_('Create a new configuration file'))
-        self.btn_rename = wx.Button(parent=self.panel, id=wx.ID_ANY,
+        self.btn_rename = wx.Button(parent=self, id=wx.ID_ANY,
                                     label=_("Rename"))
         self.btn_rename.SetToolTipString(_('Rename a configuration file'))
+        self.btn_view = wx.Button(parent=self, id=wx.ID_ANY,
+                                    label=_("View"))
+        self.btn_view.SetToolTipString(_('View a configuration file'))
         #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)
         self.btn_new.Bind(wx.EVT_BUTTON, self.OnNew)
         self.btn_rename.Bind(wx.EVT_BUTTON, self.OnRename)
+        self.btn_view.Bind(wx.EVT_BUTTON, self.OnView)
         self._layout()
         ###END BUTTONS
 
@@ -67,7 +156,8 @@ class RLiSetupFrame(wx.Frame):
 
     def _layout(self):
         """Set the layout"""
-        sizer = wx.BoxSizer(wx.VERTICAL)
+        panelsizer = wx.GridBagSizer(1, 1)
+        mainsizer = wx.BoxSizer(wx.VERTICAL)
         ###CONFILES
         confilesSizer = wx.StaticBoxSizer(self.confilesBox, wx.HORIZONTAL)
         confilesSizer.Add(item=self.listfileBox, proportion=1,
@@ -77,19 +167,25 @@ class RLiSetupFrame(wx.Frame):
         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)
+        buttonSizer.Add(item=self.btn_view, flag=wx.ALL, border=5)
         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 to sizer
-        sizer.Add(item=confilesSizer, proportion=0,
-                  flag=wx.ALIGN_LEFT | wx.EXPAND | wx.ALL, border=3)
-        sizer.Add(item=buttonSizer, proportion=0,
-                  flag=wx.ALIGN_RIGHT | wx.ALL, border=3)
-        #set dimension
+        #add listbox to staticbox
+        panelsizer.Add(item=confilesSizer, pos=(0, 0), flag=wx.EXPAND,
+                       border=3)
+
+        #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)
+        panelsizer.AddGrowableCol(0)
+
         self.panel.SetAutoLayout(True)
-        self.panel.SetSizer(sizer)
-        sizer.Fit(self.panel)
+        self.panel.SetSizerAndFit(panelsizer)
+        self.SetSizer(mainsizer)
         self.Layout()
 
     def ListFiles(self):
@@ -101,7 +197,7 @@ class RLiSetupFrame(wx.Frame):
         for l in os.listdir(self.rlipath):
             if os.path.isfile(os.path.join(self.rlipath, l)):
                 listfiles.append(l)
-        return listfiles
+        return sorted(listfiles)
 
     def OnClose(self, event):
         """!Close window"""
@@ -109,14 +205,22 @@ class RLiSetupFrame(wx.Frame):
 
     def OnHelp(self, event):
         """!Launches help"""
-        gcmd.RunCommand('g.manual', parent = self, entry = 'wxGUI.rlisetup')
+        gcmd.RunCommand('g.manual', parent=self, entry='wxGUI.rlisetup')
 
     def OnRemove(self, event):
         """!Remove configuration file from path and update the list"""
         confile = self.listfiles[self.listfileBox.GetSelections()[0]]
-        self.listfileBox.Delete(self.listfileBox.GetSelections()[0])
-        grass.try_remove(os.path.join(self.rlipath, confile))
-        self.listfiles = self.ListFiles()
+        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])
+            grass.try_remove(os.path.join(self.rlipath, confile))
+            self.listfiles = self.ListFiles()
+        dlg.Destroy()
         return
 
     def OnNew(self, event):
@@ -145,3 +249,14 @@ class RLiSetupFrame(wx.Frame):
             self.listfiles = self.ListFiles()
             self.listfileBox.Clear()
             self.listfileBox.Set(self.listfiles)
+
+    def OnView(self, event):
+        """!Show and edit a configuration file"""
+        try:
+            confile = self.listfiles[self.listfileBox.GetSelections()[0]]
+        except:
+            gcmd.GMessage(parent=self,
+                          message=_("You have to select a configuration file"))
+            return
+        frame = ViewFrame(self, conf=confile)
+        frame.Show()

+ 71 - 1
gui/wxpython/rlisetup/functions.py

@@ -7,6 +7,37 @@ Created on Mon Nov 26 11:48:03 2012
 import wx
 import os
 import sys
+from grass.script import core as grass
+from core.gcmd import GError
+
+class SamplingType:
+    """"
+    KMWINC = samplingtype=moving, regionbox=keyboard, shape=circle
+    KMWINR = samplingtype moving, regionbox=keyboard, shape=rectangle
+    MMWINC = samplingtype=moving, regionbox=mouse, shape=circle
+    MMWINR = samplingtype moving, regionbox=mouse, shape=rectangle
+
+    KUNITSC = samplingtype=units, regionbox=keyboard, shape=cirlce
+    KUNITSR = samplingtype=units, regionbox=keyboard, shape=rectangle
+    MUNITSC = samplingtype=units, regionbox=mouse, shape=cirlce
+    MUNITSR = samplingtype=units, regionbox=mouse, shape=rectangle
+    """
+
+    WHOLE = 'whole'
+    REGIONS = 'regions'
+    UNITS = 'units'
+    VECT = 'vect'
+    MVWIN = 'moving'
+
+    KMVWINC = 'kmvwin_circle'
+    KMVWINR = 'kmvwin_rectangle'
+    MMVWINC = 'mmvwin_circle'
+    MMVWINR = 'mmvwin_rectangle'
+
+    KUNITSC = 'kunits_circle'
+    KUNITSR = 'kunits_rectangle'
+    MUNITSC = 'munits_circle'
+    MUNITSR = 'munits_rectangle'
 
 
 def checkValue(value):
@@ -17,7 +48,7 @@ def checkValue(value):
 
 
 def retRLiPath():
-    # configuration directory
+    """Return the directory of configuration files for r.li"""
     if sys.platform == 'win32':
         grass_config_dirname = "GRASS7"
         grass_config_dir = os.path.join(os.getenv('APPDATA'),
@@ -33,3 +64,42 @@ def retRLiPath():
     else:
         os.mkdir(rlipath)
         return rlipath
+
+
+def convertFeature(vect, outrast, cat, origrast):
+    """Convert a single feature to a raster"""
+    tmp_vect = "tmp_{rast}".format(rast=outrast)
+    grass.run_command('v.extract', input=vect, output=tmp_vect, cats=cat,
+                      overwrite=True, quiet=True)
+    grass.run_command('g.region', vect=tmp_vect, align=origrast)
+    grass.run_command('v.to.rast', input=vect, output=outrast, use='cat',
+                      cats=cat, overwrite=True, quiet=True)
+    grass.run_command('g.remove', vect=tmp_vect, quiet=True)
+
+
+def obtainAreaVector(outrast):
+    """Create the string for configuration file"""
+    reg = grass.region()
+    return "MASKEDOVERLAYAREA {name}|{n}|{s}|{e}|{w}\n".format(name=outrast,
+                                                             n=reg['n'],
+                                                             s=reg['s'],
+                                                             e=reg['e'],
+                                                             w=reg['w'])
+
+
+def sampleAreaVector(vect, rast, vect_cats, progDialog=None):
+    """Create the strings to add to the configuration file using vector"""
+    areanum = len(vect_cats)
+    output = []
+    #TODO if areanum == 0 exit from the program
+    if areanum == 0:
+        GError(message=_("The polygon seems to have 0 areas"))
+        return None
+    for n in range(areanum):
+        cat = vect_cats[n]
+        rast_name = "{name}_{cat}".format(name=vect.split('@')[0], cat=cat)
+        convertFeature(vect, rast_name, cat, rast)
+        output.append(obtainAreaVector(rast_name))
+        if progDialog:
+            progDialog.Update(n)
+    return output

+ 1 - 1
gui/wxpython/rlisetup/g.gui.rlisetup.py

@@ -46,7 +46,7 @@ def main():
     app = wx.PySimpleApp()
     if not CheckWxVersion([2, 9]):
         wx.InitAllImageHandlers()
-    frame = RLiSetupFrame(parent = None, giface = StandaloneGrassInterface())
+    frame = RLiSetupFrame(parent=None, giface=StandaloneGrassInterface())
     frame.Show()
 
     app.MainLoop()

+ 368 - 31
gui/wxpython/rlisetup/sampling_frame.py

@@ -22,6 +22,22 @@ import sys
 import wx
 import wx.aui
 
+
+#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.vector import *
+    from grass.lib.raster import *
+except ImportError:
+    pass
+
+#end new import
+
 # adding a path to wxGUI modules
 if __name__ == '__main__':
     WXGUIBASE = os.path.join(os.getenv('GISBASE'), 'etc', 'gui', 'wxpython')
@@ -39,17 +55,36 @@ from icons.icon import MetaIcon
 from grass.pydispatch.signal import Signal
 from grass.pydispatch.errors import DispatcherKeyError
 
+from functions import SamplingType
+
+
+class Circle:
+    def __init__(self, pt, r):
+        self.point = pt
+        self.radius = r
+
+
+class MaskedArea(object):
+    def __init__(self, region, raster):
+        self.region = region
+        self.raster = raster
+
 
 class RLiSetupMapPanel(wx.Panel):
     """!Panel with mapwindow used in r.li.setup"""
-    def __init__(self, parent, map_=None):
+    def __init__(self, parent, samplingType, graphicsType="rect", icon=None,
+                 map_=None):
         wx.Panel.__init__(self, parent=parent)
+
         self.mapWindowProperties = MapWindowProperties()
         self.mapWindowProperties.setValuesFromUserSettings()
         giface = StandaloneGrassInterface()
+        self.samplingtype = samplingType
+        self.gtype = graphicsType
+        self.parent = parent
 
-        self._region = {}
-        self.sampleFrameChanged = Signal('RLiSetupMapPanel.sampleFrameChanged')
+        ##print self.gtype
+        ##print samplingType
 
         if map_:
             self.map_ = map_
@@ -69,6 +104,10 @@ class RLiSetupMapPanel(wx.Panel):
         self._toolSwitcher.toggleToolChanged.connect(self._onToolChanged)
         self.toolbar = RLiSetupToolbar(self, self._toolSwitcher)
 
+        self.polycoords = []
+        self.coords = []
+        self.catId = 1
+
         self._mgr.AddPane(self.toolbar,
                           wx.aui.AuiPaneInfo().
                           Name("maptoolbar").Caption(_("Map Toolbar")).
@@ -77,19 +116,32 @@ class RLiSetupMapPanel(wx.Panel):
                           BestSize((self.toolbar.GetBestSize())))
         self._mgr.Update()
 
-        self.toolbar.SelectDefault()
+        if self.samplingtype != SamplingType.VECT:
+            self.toolbar.SelectDefault()
+        #print self.samplingtype
+        if self.samplingtype == SamplingType.REGIONS:
+            self.afterRegionDrawn = Signal('RLiSetupMapPanel.afterRegionDrawn')
+            self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(graphicsType='line')
+        elif self.samplingtype in [SamplingType.MUNITSR, SamplingType.KUNITSR,
+                                   SamplingType.KMVWINR, SamplingType.MMVWINR]:
+            self.sampleFrameChanged = Signal('RLiSetupMapPanel.sampleFrameChanged')
+            self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(graphicsType='box')
+        elif self.samplingtype in [SamplingType.MUNITSC, SamplingType.KUNITSC,
+                                   SamplingType.KMVWINC, SamplingType.MMVWINC]:
+            self.afterCircleDrawn = Signal('RLiSetupMapPanel.afterCircleDrawn')
+            self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(graphicsType='line')
+        else:
+            self.sampleFrameChanged = Signal('RLiSetupMapPanel.sampleFrameChanged')
+            self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(graphicsType='box')
 
-        self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(graphicsType='rectangle')
-        self._registeredGraphics.AddPen('rlisetup', wx.Pen(wx.GREEN, width=3, style=wx.SOLID))
-        self._registeredGraphics.AddItem(coords=[[0, 0], [0, 0]], penName='rlisetup', hide=True)
+        self._registeredGraphics.AddPen('rlisetup', wx.Pen(wx.GREEN, width=2,
+                                                           style=wx.SHORT_DASH))
+        self._registeredGraphics.AddItem(coords=[[0, 0], [0, 0]],
+                                         penName='rlisetup', hide=True)
 
     def GetMap(self):
         return self.map_
 
-    def GetRegion(self):
-        """!Returns currently drawn region in a dict"""
-        return self._region
-
     def OnPan(self, event):
         """!Panning, set mouse to drag."""
         self.mapWindow.SetModePan()
@@ -106,22 +158,225 @@ class RLiSetupMapPanel(wx.Panel):
         layers = self.map_.GetListOfLayers()
         self.mapWindow.ZoomToMap(layers=layers, ignoreNulls=False, render=True)
 
+    def OnDrawRadius(self, event):
+        """!Start draw mode"""
+        self.mapWindow.mouse['use'] = "None"
+        self.mapWindow.mouse['box'] = "line"
+        self.mapWindow.pen = wx.Pen(colour=wx.RED, width=1,
+                                    style=wx.SHORT_DASH)
+        self.mapWindow.SetNamedCursor('cross')
+        self.mapWindow.mouseLeftUp.connect(self._radiusDrawn)
+
+    def OnDigitizeRegion(self, event):
+        """!Start draw mode"""
+        self.mapWindow.mouse['use'] = "None"
+        self.mapWindow.mouse['box'] = "line"
+        self.mapWindow.pen = wx.Pen(colour=wx.RED, width=1,
+                                    style=wx.SHORT_DASH)
+        self.mapWindow.SetNamedCursor('cross')
+        self.mapWindow.mouseLeftDown.connect(self._mouseLeftDown)
+        self.mapWindow.mouseMoving.connect(self._mouseMoving)
+        self.mapWindow.mouseDClick.connect(self._mouseDbClick)
+
     def OnDraw(self, event):
         """!Start draw mode"""
-        self.mapWindow.mouse['use'] = None
+        self.mapWindow.mouse['use'] = "None"
         self.mapWindow.mouse['box'] = "box"
-        self.mapWindow.pen = wx.Pen(colour=wx.RED, width=2, style=wx.SHORT_DASH)
+        self.mapWindow.pen = wx.Pen(colour=wx.RED, width=2,
+                                    style=wx.SHORT_DASH)
         self.mapWindow.SetNamedCursor('cross')
-
         self.mapWindow.mouseLeftUp.connect(self._rectangleDrawn)
 
+    def _mouseLeftDown(self, x, y):
+        self.polycoords.append((x, y))
+        self.coords.append((x, y))
+        if len(self.polycoords) > 1:
+            item = self._registeredGraphics.GetItem(0)
+            item.SetCoords(self.polycoords)
+            self.coords = []
+            self.coords.append((x, y))
+            item.SetPropertyVal('hide', False)
+            self._registeredGraphics.Draw(self.mapWindow.pdc)
+
+    def _mouseMoving(self, x, y):
+        self.mapWindow.mouse['end'] = (x, y)
+        if len(self.coords) > 0:
+            mouse = self.mapWindow.mouse
+            item = self._registeredGraphics.GetItem(0)
+            item.SetCoords([self.coords[0], mouse['end']])
+            item.SetPropertyVal('hide', False)
+            self.mapWindow.ClearLines()
+            self._registeredGraphics.Draw(self.mapWindow.pdcTmp)
+
+    def _mouseDbClick(self, x, y):
+        if len(self.polycoords) > 1:
+            item = self._registeredGraphics.GetItem(0)
+            self.polycoords.append((x, y))
+            self.polycoords.append(self.polycoords[0])
+            item.SetCoords(self.polycoords)
+            item.SetPropertyVal('hide', False)
+            self.mapWindow.ClearLines()
+            self._registeredGraphics.Draw(self.mapWindow.pdc)
+            self.createRegion()
+
+    def createRegion(self):
+        dlg = wx.TextEntryDialog(None, 'Name of sample region',
+                                 'Create region', 'region' + str(self.catId))
+        ret = dlg.ShowModal()
+        if ret == wx.ID_OK:
+            raster = dlg.GetValue()
+            marea = self.writeArea(self.polycoords, raster)
+            self.nextRegion(next=True, area=marea)
+        else:
+            self.nextRegion(next=False)
+        dlg.Destroy()
+
+    def nextRegion(self, next=True, area=None):
+        self.coords = []
+        self.polycoords = []
+
+        self.mapWindow.ClearLines()
+        item = self._registeredGraphics.GetItem(0)
+        item.SetPropertyVal('hide', True)
+
+        layers = self.map_.GetListOfLayers()
+        self.mapWindow.ZoomToMap(layers=layers, ignoreNulls=False, render=True)
+        if next is True:
+            self.afterRegionDrawn.emit(marea=area)
+        else:
+            gcmd.GMessage(parent=self.parent,
+                          message=_("Raster map not created. redraw region again."))
+
+    def writeArea(self, coords, rasterName):
+        polyfile = tempfile.NamedTemporaryFile(delete=False)
+        polyfile.write("AREA\n")
+        for coor in coords:
+            east, north = coor
+            point = " %s %s\n" % (east, north)
+            polyfile.write(point)
+
+        catbuf = "=%d a\n" % self.catId
+        polyfile.write(catbuf)
+        self.catId = self.catId + 1
+
+        polyfile.close()
+        region_settings = grass.parse_command('g.region', flags='p',
+                                              delimiter=':')
+        pname = polyfile.name.split('/')[-1]
+        tmpraster = "rast_" + pname
+        tmpvector = "vect_" + pname
+        RunCommand('r.in.poly', input=polyfile.name, output=tmpraster,
+                   rows=region_settings['rows'], overwrite=True)
+
+        RunCommand('r.to.vect', input=tmpraster, output=tmpvector,
+                   type='area', overwrite=True)
+
+        RunCommand('v.to.rast', input=tmpvector, output=rasterName,
+                   value=1, use='val', overwrite=True)
+
+        grass.use_temp_region()
+        grass.run_command('g.region', vect=tmpvector)
+        region = grass.region()
+
+        marea = MaskedArea(region, rasterName)
+
+        RunCommand('g.remove', rast=tmpraster)
+        RunCommand('g.remove', vect=tmpvector)
+
+        os.unlink(polyfile.name)
+        return marea
+
     def _onToolChanged(self):
         """!Helper function to disconnect drawing"""
         try:
             self.mapWindow.mouseLeftUp.disconnect(self._rectangleDrawn)
+            self.mapWindow.mouseLeftUp.disconnect(self._radiusDrawn)
+            self.mapWindow.mouseMoving.disconnect(self._mouseMoving)
+            self.mapWindow.mouseLeftDown.disconnect(self._mouseLeftDown)
+            self.mapWindow.mouseDClick.disconnect(self._mouseDbClick)
         except DispatcherKeyError:
             pass
 
+    def _radiusDrawn(self, x, y):
+        """!When drawing finished, get region values"""
+        mouse = self.mapWindow.mouse
+        item = self._registeredGraphics.GetItem(0)
+        p1 = mouse['begin']
+        p2 = mouse['end']
+        dist, (north, east) = self.mapWindow.Distance(p1, p2, False)
+        circle = Circle(p1, dist)
+        self.mapWindow.ClearLines()
+        self.mapWindow.pdcTmp.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
+        pen = wx.Pen(colour=wx.RED, width=2)
+        self.mapWindow.pdcTmp.SetPen(pen)
+        self.mapWindow.pdcTmp.DrawCircle(circle.point[0], circle.point[1],
+                                         circle.radius)
+        self._registeredGraphics.Draw(self.mapWindow.pdcTmp)
+        self.createCricle(circle)
+
+    def createCricle(self, c):
+        dlg = wx.TextEntryDialog(None, 'Name of sample region',
+                                 'Create region', 'region' + str(self.catId))
+        ret = dlg.ShowModal()
+        if ret == wx.ID_OK:
+            raster = dlg.GetValue()
+            circle = self.writeCircle(c, raster)
+            self.nextCircle(next=True, circle=c)
+        else:
+            self.nextCircle(next=False)
+        dlg.Destroy()
+
+    def nextCircle(self, next=True, circle=None):
+        self.mapWindow.ClearLines()
+        item = self._registeredGraphics.GetItem(0)
+        item.SetPropertyVal('hide', True)
+        layers = self.map_.GetListOfLayers()
+        self.mapWindow.ZoomToMap(layers=layers, ignoreNulls=False, render=True)
+        if next is True:
+            self.afterCircleDrawn.emit(mcircle=circle)
+        else:
+            gcmd.GMessage(parent=self.parent,
+                          message=_("Raster map not created. redraw region again."))
+
+    def writeCircle(self, circle, rasterName):
+        polyfile = tempfile.NamedTemporaryFile(delete=False)
+        polyfile.write("AREA\n")
+        for coor in coords:
+            east, north = coor
+            point = " %s %s\n" % (east, north)
+            polyfile.write(point)
+
+        catbuf = "=%d a\n" % self.catId
+        polyfile.write(catbuf)
+        self.catId = self.catId + 1
+
+        polyfile.close()
+        region_settings = grass.parse_command('g.region', flags='p',
+                                              delimiter=':')
+        pname = polyfile.name.split('/')[-1]
+        tmpraster = "rast_" + pname
+        tmpvector = "vect_" + pname
+        RunCommand('r.in.poly', input=polyfile.name, output=tmpraster,
+                   rows=region_settings['rows'], overwrite=True)
+
+        RunCommand('r.to.vect', input=tmpraster, output=tmpvector,
+                   type='area', overwrite=True)
+
+        RunCommand('v.to.rast', input=tmpvector, output=rasterName,
+                   value=1, use='val', overwrite=True)
+
+        grass.use_temp_region()
+        grass.run_command('g.region', vect=tmpvector)
+        region = grass.region()
+
+        marea = MaskedArea(region, rasterName)
+
+        RunCommand('g.remove', rast=tmpraster)
+        RunCommand('g.remove', vect=tmpvector)
+
+        os.unlink(polyfile.name)
+        return marea
+
     def _rectangleDrawn(self):
         """!When drawing finished, get region values"""
         mouse = self.mapWindow.mouse
@@ -129,7 +384,7 @@ class RLiSetupMapPanel(wx.Panel):
         p1 = self.mapWindow.Pixel2Cell(mouse['begin'])
         p2 = self.mapWindow.Pixel2Cell(mouse['end'])
         item.SetCoords([p1, p2])
-        self._region = {'n': max(p1[1], p2[1]),
+        region = {'n': max(p1[1], p2[1]),
                         's': min(p1[1], p2[1]),
                         'w': min(p1[0], p2[0]),
                         'e': max(p1[0], p2[0])}
@@ -137,12 +392,43 @@ class RLiSetupMapPanel(wx.Panel):
         self.mapWindow.ClearLines()
         self._registeredGraphics.Draw(self.mapWindow.pdcTmp)
 
-        self.sampleFrameChanged.emit()
-
+        if self.samplingtype == SamplingType.MUNITSR:
+            dlg = wx.MessageDialog(self, "Is this area ok?",
+                                   "select sampling unit",
+                                   wx.YES_NO | wx.ICON_QUESTION)
+            ret = dlg.ShowModal()
+            if ret == wx.ID_YES:
+                grass.use_temp_region()
+                grass.run_command('g.region', n=region['n'], s=region['s'],
+                                  e=region['e'], w=region['w'])
+                tregion = grass.region()
+                self.sampleFrameChanged.emit(region=tregion)
+                self.mapWindow.ClearLines()
+                item = self._registeredGraphics.GetItem(0)
+                item.SetPropertyVal('hide', True)
+                layers = self.map_.GetListOfLayers()
+                self.mapWindow.ZoomToMap(layers=layers, ignoreNulls=False,
+                                         render=True)
+            else:
+                self.nextRegion(next=False)
+            dlg.Destroy()
+
+        elif self.samplingtype != SamplingType.WHOLE:
+            """!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'))}
+                          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):
@@ -151,32 +437,83 @@ class RLiSetupToolbar(BaseToolbar):
     def __init__(self, parent, toolSwitcher):
         """!RLiSetup toolbar constructor
         """
-        BaseToolbar.__init__(self, parent, toolSwitcher, style=wx.NO_BORDER | wx.TB_VERTICAL)
+
+        BaseToolbar.__init__(self, parent, toolSwitcher,
+                             style=wx.NO_BORDER | wx.TB_VERTICAL)
 
         self.InitToolbar(self._toolbarData())
-        self._default = self.draw
 
-        for tool in (self.draw, self.pan, self.zoomIn, self.zoomOut):
-            self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=tool)
+        """
+        if self.parent.samplingtype == SamplingType.REGIONS:
+            self._default = self.digitizeregion
+            self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=self.digitizeregion)
+        elif self.parent.samplingtype == SamplingType.MUNITSR:
+            self._default = self.digitizeunit
+            self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=self.digitizeunit)        
+        else:
+            self._default = self.draw
+            self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=self.draw)
+        """
+        if self.parent.samplingtype == SamplingType.REGIONS:
+            self._default = self.digitizeregion
+        elif self.parent.samplingtype == SamplingType.MUNITSR:
+            self._default = self.digitizeunit
+        elif self.parent.samplingtype == SamplingType.MUNITSC:
+            self._default = self.digitizeunitc
+        elif self.parent.samplingtype == SamplingType.VECT:
+            self._default = None
+        else:
+            self._default = self.draw
+
+        for tool in (self._default, self.pan, self.zoomIn, self.zoomOut):
+            if tool:
+                self.toolSwitcher.AddToolToGroup(group='mouseUse',
+                                                 toolbar=self, tool=tool)
 
         # realize the toolbar
         self.Realize()
 
     def _toolbarData(self):
         """!Toolbar data"""
-        return self._getToolbarData((('draw', icons['draw'],
+        if self.parent.samplingtype == SamplingType.REGIONS:
+            drawTool = ('digitizeregion', icons['digitizeregion'],
+                                     self.parent.OnDigitizeRegion,
+                                     wx.ITEM_CHECK)
+        elif self.parent.samplingtype == SamplingType.MUNITSR:
+            drawTool = ('digitizeunit', icons['digitizeunit'],
                                      self.parent.OnDraw,
-                                     wx.ITEM_CHECK),
-                                     (None, ),
-                                     ('pan', BaseIcons['pan'],
+                                     wx.ITEM_CHECK)
+        elif self.parent.samplingtype == SamplingType.MUNITSC:
+            drawTool = ('digitizeunitc', icons['digitizeunitc'],
+                                     self.parent.OnDrawRadius,
+                                     wx.ITEM_CHECK)
+        else:
+            drawTool = ('draw', icons['draw'],
+                         self.parent.OnDraw,
+                         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),))
+        else:
+            return self._getToolbarData((drawTool, (None, ),
+                       ('pan', BaseIcons['pan'],
                                       self.parent.OnPan,
                                       wx.ITEM_CHECK),
-                                     ('zoomIn', BaseIcons['zoomIn'],
+                       ('zoomIn', BaseIcons['zoomIn'],
                                       self.parent.OnZoomIn,
                                       wx.ITEM_CHECK),
-                                     ('zoomOut', BaseIcons['zoomOut'],
+                       ('zoomOut', BaseIcons['zoomOut'],
                                       self.parent.OnZoomOut,
                                       wx.ITEM_CHECK),
-                                     ('zoomExtent', BaseIcons['zoomExtent'],
-                                      self.parent.OnZoomToMap),
-                                     ))
+                       ('zoomExtent', BaseIcons['zoomExtent'],
+                                      self.parent.OnZoomToMap),))

File diff suppressed because it is too large
+ 656 - 122
gui/wxpython/rlisetup/wizard.py