[GRASS-SVN] r65624 - grass/trunk/gui/wxpython/gui_core

svn_grass at osgeo.org svn_grass at osgeo.org
Sun Jul 19 07:43:47 PDT 2015


Author: martinl
Date: 2015-07-19 07:43:47 -0700 (Sun, 19 Jul 2015)
New Revision: 65624

Modified:
   grass/trunk/gui/wxpython/gui_core/dialogs.py
   grass/trunk/gui/wxpython/gui_core/forms.py
   grass/trunk/gui/wxpython/gui_core/gselect.py
   grass/trunk/gui/wxpython/gui_core/widgets.py
Log:
wxGUI: implement possibility to use GdalSelect and LayersList in forms.py
       LayerList moved to widgets


Modified: grass/trunk/gui/wxpython/gui_core/dialogs.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/dialogs.py	2015-07-19 14:37:16 UTC (rev 65623)
+++ grass/trunk/gui/wxpython/gui_core/dialogs.py	2015-07-19 14:43:47 UTC (rev 65624)
@@ -16,7 +16,6 @@
  - :class:`GdalImportDialog`
  - :class:`GdalOutputDialog`
  - :class:`DxfImportDialog`
- - :class:`LayersList` (used by MultiImport)
  - :class:`SetOpacityDialog`
  - :class:`ImageSizeDialog`
  - :class:`SqlQueryFrame`
@@ -34,7 +33,6 @@
 import os
 import sys
 import re
-from bisect import bisect
 
 import wx
 import wx.lib.filebrowsebutton as filebrowse
@@ -50,7 +48,8 @@
 from gui_core.gselect import LocationSelect, MapsetSelect, Select, \
                              OgrTypeSelect, GdalSelect, MapsetSelect, \
                              SubGroupSelect
-from gui_core.widgets import SingleSymbolPanel, GListCtrl, SimpleValidator, MapValidator
+from gui_core.widgets import SingleSymbolPanel, GListCtrl, SimpleValidator, \
+    MapValidator, LayersList
 from core.utils import GetValidLayerName, _
 from core.settings import UserSettings, GetDisplayVectSettings
 from core.debug import Debug
@@ -1885,6 +1884,7 @@
         
         self.dsnInput = GdalSelect(parent = self, panel = self.panel,
                                    ogr = ogr, link = link)
+        self.dsnInput.AttachSettings()
         self.dsnInput.reloadDataRequired.connect(lambda data: self.list.LoadData(data))
 
         if link:
@@ -2058,6 +2058,7 @@
         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)
@@ -2201,83 +2202,6 @@
         
         self.list.LoadData(data)
 
-
-class LayersList(GListCtrl, listmix.TextEditMixin):
-    """List of layers to be imported (dxf, shp...)"""
-    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) == 3:
-            width = (65, 200)
-        else:
-            width = (65, 180, 90, 70)
-        
-        for i in range(len(width)):
-            self.SetColumnWidth(col = i, width = width[i])
-        
-    def LoadData(self, data = None):
-        """Load data into list"""
-        self.DeleteAllItems()
-        if data is None:
-            return
-        
-        for item in data:
-            index = self.InsertStringItem(sys.maxint, str(item[0]))
-            for i in range(1, len(item)):
-                self.SetStringItem(index, i, item[i])
-        
-        # check by default only on one item
-        if len(data) == 1:
-            self.CheckItem(index, True)
-        
-    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)"""
-        data = []
-        item = -1
-        while True:
-            item = self.GetNextItem(item)
-            if item == -1:
-                break
-            if not self.IsChecked(item):
-                continue
-            # layer / output name
-            layer = self.GetItem(item, 1).GetText()
-            ftype = self.GetItem(item, 2).GetText()
-            if '/' in ftype:
-                layer += '|%s' % ftype.split('/', 1)[0]
-            output = self.GetItem(item, self.GetColumnCount() - 1).GetText()
-            data.append((layer, output))
-        
-        return data
-
 class SetOpacityDialog(wx.Dialog):
     """Set opacity of map layers.
     Dialog expects opacity between 0 and 1 and returns this range, too.    

Modified: grass/trunk/gui/wxpython/gui_core/forms.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/forms.py	2015-07-19 14:37:16 UTC (rev 65623)
+++ grass/trunk/gui/wxpython/gui_core/forms.py	2015-07-19 14:43:47 UTC (rev 65624)
@@ -93,6 +93,7 @@
 from core.settings    import UserSettings
 from gui_core.widgets import FloatValidator, GNotebook, FormNotebook, FormListbook
 from core.giface import Notification
+from gui_core.dialogs import LayersList
 
 wxUpdateDialog, EVT_DIALOG_UPDATE = NewEvent()
 
@@ -1104,46 +1105,47 @@
                 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:
-                    txt3 = 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
-                        txt3.SetValue(str(value))
-                    
-                    txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
+                        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)
                     
-                    txt3 = wx.SpinCtrl(parent = which_panel, value = p.get('default', ''),
+                    win = wx.SpinCtrl(parent = which_panel, value = p.get('default', ''),
                                        size = globalvar.DIALOG_SPIN_SIZE,
                                        min = minValue, max = maxValue)
                     if value:
-                        txt3.SetValue(int(value)) # parameter previously set
-                        txt3.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
+                        win.SetValue(int(value)) # parameter previously set
+                        win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
 
                     style = wx.BOTTOM | wx.LEFT | wx.RIGHT
                 else: # float
-                    txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
+                    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:
-                        txt3.SetValue(str(value)) # parameter previously set
+                        win.SetValue(str(value)) # parameter previously set
                 
-                txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
+                win.Bind(wx.EVT_TEXT, self.OnSetValue)
                 
-                which_sizer.Add(item = txt3, proportion = 0,
+                which_sizer.Add(item = win, proportion = 0,
                                 flag = style, border = 5)
-                p['wxId'] = [ txt3.GetId(), ]
-
+                p['wxId'] = [win.GetId()]
+            
             #
             # element selection tree combobox (maps, icons, regions, etc.)
             #
@@ -1169,7 +1171,9 @@
                                               'dir',
                                               'colortable',
                                               'barscale',
-                                              'northarrow'):
+                                              'northarrow',
+                                              'datasource',
+                                              'datasource_layer'):
                     multiple = p.get('multiple', False)
                     if p.get('age', '') == 'new':
                         mapsets = [grass.gisenv()['MAPSET'],]
@@ -1677,7 +1681,39 @@
                     if p.get('guidependency', ''):
                         cb.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
 
+                elif prompt == 'datasource':
+                    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()]
+                    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)
+                    winDataSource = self.FindWindowById(porf['wxId'][0])
+                    winDataSource.reloadDataRequired.connect(lambda data: self.win1.LoadData(data))
+                    p['wxId'] = [self.win1.GetId()]
+                    def OnCheckItem(index, flag):
+                        layers = list()
+                        for layer, match in self.win1.GetLayers():
+                            layers.append(layer)
+                        porf = self.task.get_param('layer', element = 'name', raiseError = False)
+                        porf['value'] = ','.join(layers)
+                        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"))
@@ -2198,6 +2234,7 @@
         for porf in self.task.params + self.task.flags:
             if 'wxId' not in porf:
                 continue
+            
             if myId in porf['wxId']:
                 found = True
                 break
@@ -2209,9 +2246,16 @@
             porf['value'] = event.dsn
         elif name == 'ModelParam':
             porf['parameterized'] = me.IsChecked()
+        elif name == 'GdalSelectDataSource':
+            win = self.FindWindowById(porf['wxId'][0])
+            porf['value'] = win.GetDsn()
+            pLayer = self.task.get_param('layer', element = 'name', raiseError = False)
+            pLayer['value'] = ''
         else:
             if isinstance(me, wx.SpinCtrl):
                 porf['value'] = str(me.GetValue())
+            elif isinstance(me, wx.Choice):
+                porf['value'] = me.GetStringSelection()                    
             else:
                 porf['value'] = me.GetValue()
         

Modified: grass/trunk/gui/wxpython/gui_core/gselect.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/gselect.py	2015-07-19 14:37:16 UTC (rev 65623)
+++ grass/trunk/gui/wxpython/gui_core/gselect.py	2015-07-19 14:43:47 UTC (rev 65624)
@@ -1257,12 +1257,9 @@
 
         return formatToExt.get(name, '')
 
-# unused code since r47938
-# wxGdalSelect, EVT_GDALSELECT = NewEvent()
-
 class GdalSelect(wx.Panel):
     def __init__(self, parent, panel, ogr=False, link=False, dest=False,
-                 exclude=None):
+                 exclude=None, settings=True):
         """Widget for selecting GDAL/OGR datasource, format
 
         .. todo::
@@ -1281,20 +1278,11 @@
         self.dest = dest
         self._sourceType = None
 
-        wx.Panel.__init__(self, parent=panel)
+        wx.Panel.__init__(self, parent=panel, name='GdalSelect')
 
         self.reloadDataRequired = Signal('GdalSelect.reloadDataRequired')
 
-        if self.ogr:
-            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)
-        self.settsManager.settingsSaving.connect(self.OnSettingsSaving)
-
         self.inputBox = wx.StaticBox(parent=self)
         if dest:
             self.inputBox.SetLabel(" %s " % _("Output settings"))
@@ -1393,6 +1381,7 @@
                                              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)
 
@@ -1405,6 +1394,7 @@
                                             buttonText=_('Browse'),
                                             startDirectory=os.getcwd(),
                                             changeCallback=self.OnUpdate)
+        browse.GetChildren()[1].SetName('GdalSelectDataSource')
 
         self.dirWidgets['browse'] = browse
         formatSelect = wx.Choice(parent=self.dirPanel, size=(300, -1))
@@ -1444,10 +1434,12 @@
                                              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)
+        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)
+        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:"))
@@ -1545,7 +1537,7 @@
 
     def _layout(self):
         """Layout"""
-        mainSizer = wx.BoxSizer(wx.VERTICAL)
+        self.mainSizer = wx.BoxSizer(wx.VERTICAL)
 
         self.changingSizer = wx.StaticBoxSizer(self.inputBox, wx.VERTICAL)
 
@@ -1705,15 +1697,12 @@
             self.changingSizer.Add(item=panel, proportion=1,
                                    flag=wx.EXPAND)
 
-        mainSizer.Add(item=self.settsManager, proportion=0,
-                      flag=wx.ALL | wx.EXPAND, border=5)
-        mainSizer.Add(item=self.source, proportion=0,
+        self.mainSizer.Add(item=self.source, proportion=0,
                       flag=wx.LEFT | wx.RIGHT | wx.EXPAND, border=5)
-        mainSizer.Add(item=self.changingSizer, proportion=1,
+        self.mainSizer.Add(item=self.changingSizer, proportion=1,
                       flag=wx.ALL | wx.EXPAND, border=5)
-        self.mainSizer = mainSizer
-        self.SetSizer(mainSizer)
-        mainSizer.Fit(self)
+        self.SetSizer(self.mainSizer)
+        self.mainSizer.Fit(self)
 
     def _getExtension(self, name):
         """Get file extension by format name"""
@@ -1792,6 +1781,21 @@
             self.reloadDataRequired.emit(data=None)
             self._reloadLayers()
 
+    def AttachSettings(self):
+        if self.ogr:
+            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)
+        self.settsManager.settingsSaving.connect(self.OnSettingsSaving)
+
+        # do layout
+        self.mainSizer.Insert(0, item=self.settsManager,
+                              flag=wx.ALL | wx.EXPAND, border=5)
+
     def OnSettingsSaving(self, name):
         """Saving data"""
         if not self.GetDsn():
@@ -1947,20 +1951,14 @@
                 ext = self.dirWidgets['extension'].GetValue()
                 for filename in glob.glob(os.path.join(dsn, "%s") % self._getExtPatternGlob(ext)):
                     baseName = os.path.basename(filename)
+
                     grassName = GetValidLayerName(baseName.split('.', -1)[0])
                     data.append((layerId, baseName, grassName))
                     layerId += 1
-# unused code since r47938
-#        if self.ogr:
-#            dsn += '@OGR'
-#
-#        evt = wxGdalSelect(dsn = dsn)
-#        evt.SetId(self.input[self.dsnType][1].GetId())
-#        wx.PostEvent(self.parent, evt)
+        
+        # emit signal
+        self.reloadDataRequired.emit(data=data)
 
-        if self.parent.GetName() == 'MultiImportDialog':
-            self.reloadDataRequired.emit(data=data)
-
     def ExtensionChanged(self, event):
         if not self.dest:
             # reload layers

Modified: grass/trunk/gui/wxpython/gui_core/widgets.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/widgets.py	2015-07-19 14:37:16 UTC (rev 65623)
+++ grass/trunk/gui/wxpython/gui_core/widgets.py	2015-07-19 14:43:47 UTC (rev 65624)
@@ -27,6 +27,7 @@
  - widgets::ColorTablesComboBox
  - widgets::BarscalesComboBox
  - widgets::NArrowsComboBox
+ - widgets::LayersList
 
 @todo:
  - move validators to a separate file gui_core/validators.py
@@ -47,7 +48,7 @@
 import sys
 import string
 import re
-
+from bisect import bisect
 from datetime import datetime
 
 import wx
@@ -1450,3 +1451,79 @@
 
     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):
+        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) == 3:
+            width = (65, 200)
+        else:
+            width = (65, 180, 90, 70)
+        
+        for i in range(len(width)):
+            self.SetColumnWidth(col = i, width = width[i])
+        
+    def LoadData(self, data = None):
+        """Load data into list"""
+        self.DeleteAllItems()
+        if data is None:
+            return
+        
+        for item in data:
+            index = self.InsertStringItem(sys.maxint, 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:
+            self.CheckItem(index, True)
+        
+    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)"""
+        data = []
+        item = -1
+        while True:
+            item = self.GetNextItem(item)
+            if item == -1:
+                break
+            if not self.IsChecked(item):
+                continue
+            # layer / output name
+            layer = self.GetItem(item, 1).GetText()
+            ftype = self.GetItem(item, 2).GetText()
+            if '/' in ftype:
+                layer += '|%s' % ftype.split('/', 1)[0]
+            output = self.GetItem(item, self.GetColumnCount() - 1).GetText()
+            data.append((layer, output))
+        
+        return data



More information about the grass-commit mailing list