[GRASS-SVN] r33346 - grass/trunk/gui/wxpython/gui_modules

svn_grass at osgeo.org svn_grass at osgeo.org
Tue Sep 9 03:57:21 EDT 2008


Author: martinl
Date: 2008-09-09 03:57:21 -0400 (Tue, 09 Sep 2008)
New Revision: 33346

Modified:
   grass/trunk/gui/wxpython/gui_modules/gselect.py
Log:
cmbarton: New classes create comboboxes for selecting vector layers, vector attribute columns, and generic data table columns.
(merge ftom trunk r33342)


Modified: grass/trunk/gui/wxpython/gui_modules/gselect.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/gselect.py	2008-09-09 07:54:43 UTC (rev 33345)
+++ grass/trunk/gui/wxpython/gui_modules/gselect.py	2008-09-09 07:57:21 UTC (rev 33346)
@@ -1,21 +1,18 @@
 """
- at package gselect
+MODULE: gselect
 
- at brief Custom control that selects GRASS GIS elements
-
 CLASSES:
- - Select
- - TreeCrtlComboPopup
- - VectorDBInfo
- - LayerSelect
- - ColumnSelect
+ * Select
+ * TreeCrtlComboPopup
 
-(C) 2007-2008 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.
+PURPOSE: Custon control that selects GRASS GIS elements
 
- at author Michael Barton, Martin Landa
+AUTHORS: The GRASS Development Team. Michael Barton & Martin Landa
+
+COPYRIGHT: (C) 2007 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.
 """
 
 import os
@@ -301,18 +298,20 @@
     linked to a vector map"""
     def __init__(self, map):
         self.map = map
-        # {layer number : {table, database, driver})
-        self.layers = {}
-        # {table : {column name : type, length, values, ids}}
-        self.tables = {}
 
-        if not self.__CheckDBConnection(): # -> self.layers
+        self.layers = {} # dictionary of layer number and associated table
+        self.tables = {} # dictionary of table and associated columns
+        
+        ## {table : {column name : type, length, values, ids}}
+        #self.tables = {}
+
+        if not self.__GetLayers():  # -> self.layers
             return
+        self.__GetColumns() # -> self.tables
 
-        self.__DescribeTables() # -> self.tables
-
-    def __CheckDBConnection(self):
-        """Check DB connection"""
+    def __GetLayers(self):
+        """Create layers dictionary"""
+        
         layerCommand = gcmd.Command(cmd=["v.db.connect",
                                          "-g", "--q",
                                          "map=%s" % self.map],
@@ -320,91 +319,39 @@
         if layerCommand.returncode != 0:
             return False
 
-        # list of available layers & (table, database, driver)
+        # create dictionary of layers (as strings) and associated table names for vector
         for line in layerCommand.ReadStdOutput():
             lineList = line.split(' ')
             layer = lineList[0]
             if '/' in layer:
-                layer, layer_name = lineList[0].split('/')
-            else:
-                layer_name = None
-            # database can contain ' ' in it's path
-            if len(lineList) > 5:
-                database = ''.join(lineList[3:-1])
-            else:
-                database = lineList[3]
-            self.layers[int(layer)] = {
-                "name"     : layer_name,
-                "table"    : lineList[1],
-                "key"      : lineList[2],
-                "database" : database,
-                "driver"   : lineList[-1]
-                }
-            
+                layer = layer.split('/')[0]
+            table = lineList[1]
+            self.layers[layer] = table
+                        
         if (len(self.layers.keys()) == 0):
             return False
 
         return True
 
-    def __DescribeTables(self):
-        """Describe linked tables"""
+    def __GetColumns(self):
+        """Create dictionary of tables and associated columns"""
         for layer in self.layers.keys():
+            columns = []
             # determine column names and types
-            table = self.layers[layer]["table"]
-            columnsCommand = gcmd.Command (cmd=["db.describe",
-                                                "-c", "--q",
-                                                "table=%s" % self.layers[layer]["table"],
-                                                "driver=%s" % self.layers[layer]["driver"],
-                                                "database=%s" % self.layers[layer]["database"]])
-
-
-            columns = {} # {name: {type, length, [values], [ids]}}
-
-            if columnsCommand.returncode == 0:
-                # skip nrows and ncols
-                i = 0
-                for line in columnsCommand.ReadStdOutput()[2:]:
-                    num, name, type, length = line.strip().split(':')
-                    # FIXME: support more datatypes
-                    if type.lower() == "integer":
-                        ctype = int
-                    elif type.lower() == "double precision":
-                        ctype = float
-                    else:
-                        ctype = str
-
-                    columns[name.strip()] = { 'index'  : i,
-                                              'type'   : type.lower(),
-                                              'ctype'  : ctype,
-                                              'length' : int(length),
-                                              'values' : [],
-                                              'ids'    : []}
-                    i += 1
-            else:
-                return False
-
-            # check for key column
-            # v.db.connect -g/p returns always key column name lowercase
-            if self.layers[layer]["key"] not in columns.keys():
-                for col in columns.keys():
-                    if col.lower() == self.layers[layer]["key"]:
-                        self.layers[layer]["key"] = col.upper()
-                        break
+            table = self.layers[layer]
+            cmd = ['v.info', '-c', 'map=%s' % table, 'layer=%s' % layer]
+            try:
+                info = gcmd.Command(cmd).ReadStdOutput()
+                for line in info:
+                    col = line.split('|')[1]
+                    columns.append(col)
+            except gcmd.CmdError:
+                columns = []
             
             self.tables[table] = columns
-            #print 'self tables =', self.tables[table]
-
+        
         return True
     
-    def Reset(self):
-        """Reset"""
-        for layer in self.layers:
-            table = self.layers[layer]["table"] # get table desc
-            columns = self.tables[table]
-            for name in self.tables[table].keys():
-                self.tables[table][name]['values'] = []
-                self.tables[table][name]['ids']    = []
-
 class LayerSelect(wx.ComboBox):
     """
     Creates combo box for selecting data layers defined for vector.
@@ -416,20 +363,17 @@
 
         super(LayerSelect, self).__init__(parent, id, value, pos, size, choices)
 
-        self.vector = kargs['vector'] # vector map to check for attribute tables
+        lsvector = kargs['vector'] # vector map to check for attribute tables
 
-        if self.vector == '':
+        if lsvector == '':
             return
         else:
-            self.InsertLayers(self.vector)
+            self.InsertLayers(lsvector)
         
     def InsertLayers(self, vector):
         """insert layers for a vector into the layer combobox"""
         layerchoices = VectorDBInfo(vector).layers.keys()
-        self.Clear()
-        for n in range(len(layerchoices)):
-            self.Insert(str(layerchoices[n]), n)
-
+        self.SetItems(layerchoices)
         self.SetSelection(0)
         self.SetValue('1') # all vectors have a layer 1 by default
 
@@ -444,24 +388,53 @@
 
         super(ColumnSelect, self).__init__(parent, id, value, pos, size, choices)
 
-        self.vector = kargs['vector'] # vector map to check for attribute tables
-        self.layer = kargs['layer'] # data layer connected to attribute table
+        csvector = kargs['vector'] # vector map to check for attribute tables
+        cslayer = kargs['layer'] # data layer connected to attribute table
 
-        if self.vector == '' or self.layer == '':
+        if csvector == '' or cslayer == '':
             return
         else:
-            self.InsertColumns(self.vector, self.layer)
+            self.InsertColumns(csvector, cslayer)
                 
     def InsertColumns(self, vector, layer):
-        """Return list of columns names for a vector layer"""
+        """insert columns for a vector attribute table into the columns combobox"""
         if vector == '' or layer == '': return
+        table = VectorDBInfo(vector).layers[str(layer)]
+        columnchoices = VectorDBInfo(vector).tables[table]
+        #columnchoices.sort()
+        self.SetItems(columnchoices)
+
+class DbColumnSelect(wx.ComboBox):
+    """
+    Creates combo box for selecting columns from any table.
+    """
+    def __init__(self, parent,
+                 id=wx.ID_ANY, value='', pos=wx.DefaultPosition,
+                 size=wx.DefaultSize, choices=[''], **kargs):
+
+        super(ColumnSelect, self).__init__(parent, id, value, pos, size, choices)
+
+        dbtable = kargs['table'] # table to check for columns
+        dbdriver = kargs['driver'] # driver for table
+        dbdatabase = kargs['database'] # database for table
+
+        if dbtable == '':
+            return
+        else:
+            self.InsertColumns(dbtable)
+                
+    def InsertColumns(self, table):
+        """insert columns for a table into the columns combobox"""
+        if table == '' : return
         
-        table = VectorDBInfo(vector).layers[layer]["table"]
-        columnchoices = VectorDBInfo(vector).tables[table].keys()
-        columnchoices.sort()
-        self.Clear()
-        for n in range(len(columnchoices)):
-            self.Insert(columnchoices[n], n)
-            
-        self.SetSelection(0)
-        self.SetValue(columnchoices[0]) #set the combobox to the first column 
+        cmd = ['db.columns','table=%s' % table]
+        if dbdriver != '': cmd.append('driver=%s' % dbdriver)
+        if dbdatabase != '': cmd.append('database=%s' % dbdatabase)
+        
+        try:
+            columnchoices = gcmd.Command(cmd).ReadStdOutput()
+        except gcmd.CmdError:
+            columnchoices = []
+
+        #columnchoices.sort()
+        self.SetItems(columnchoices)



More information about the grass-commit mailing list