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

svn_grass at osgeo.org svn_grass at osgeo.org
Sun Feb 1 12:39:24 EST 2009


Author: martinl
Date: 2009-02-01 12:39:24 -0500 (Sun, 01 Feb 2009)
New Revision: 35711

Modified:
   grass/trunk/gui/wxpython/gui_modules/dbm.py
   grass/trunk/gui/wxpython/gui_modules/gcmd.py
   grass/trunk/gui/wxpython/gui_modules/georect.py
   grass/trunk/gui/wxpython/gui_modules/goutput.py
   grass/trunk/gui/wxpython/gui_modules/gselect.py
   grass/trunk/gui/wxpython/gui_modules/utils.py
Log:
wxGUI: fix vector georectifier and related issues
       (merge from relbr64, r35704)


Modified: grass/trunk/gui/wxpython/gui_modules/dbm.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/dbm.py	2009-02-01 17:37:54 UTC (rev 35710)
+++ grass/trunk/gui/wxpython/gui_modules/dbm.py	2009-02-01 17:39:24 UTC (rev 35711)
@@ -91,27 +91,30 @@
     Support virtual list class
     """
     def __init__(self, parent, log, mapDBInfo, layer):
-        wx.ListCtrl.__init__(self, parent=parent, id=wx.ID_ANY,
-                             style=wx.LC_REPORT | wx.LC_HRULES |
-                             wx.LC_VRULES | wx.LC_VIRTUAL | wx.LC_SORT_ASCENDING)
-
         #
         # initialize variables
         #
+        self.parent  = parent
         self.log     = log
         self.mapDBInfo = mapDBInfo
         self.layer   = layer
+        
+        self.columns = {} # <- LoadData()
 
-        self.columns = {} # <- LoadData()
+        wx.ListCtrl.__init__(self, parent=parent, id=wx.ID_ANY,
+                             style=wx.LC_REPORT | wx.LC_HRULES |
+                             wx.LC_VRULES | wx.LC_VIRTUAL | wx.LC_SORT_ASCENDING)
         
-        # self.selectedCats         = []
-        # self.lastTurnSelectedCats = [] # just temporary, for comparation
-
+        try:
+            keyColumn = self.LoadData(layer)
+        except gcmd.DBMError, e:
+            e.Show()
+            return
+        
         #
         # add some attributes (colourful background for each item rows)
         #
         self.attr1 = wx.ListItemAttr()
-        # self.attr1.SetBackgroundColour("light blue")
         self.attr1.SetBackgroundColour(wx.Colour(238,238,238))
         self.attr2 = wx.ListItemAttr()
         self.attr2.SetBackgroundColour("white")
@@ -121,9 +124,7 @@
         self.sm_dn = self.il.Add(wx.ArtProvider_GetBitmap(wx.ART_GO_DOWN, wx.ART_TOOLBAR,
                                                           (16,16)))
         self.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
-
-        keyColumn = self.LoadData(layer)
-
+        
         # setup mixins
         listmix.ListCtrlAutoWidthMixin.__init__(self)
         listmix.ColumnSorterMixin.__init__(self, len(self.columns))
@@ -133,20 +134,12 @@
             self.SortListItems(col=keyColumn, ascending=True) 
         else:
             self.SortListItems(col=0, ascending=True) 
-
+        
         # events
         self.Bind(wx.EVT_LIST_ITEM_SELECTED,   self.OnItemSelected)
         self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnItemDeselected)
         self.Bind(wx.EVT_LIST_COL_CLICK,       self.OnColumnClick)     # sorting
-        # self.Bind(wx.EVT_LIST_DELETE_ITEM, self.OnItemDelete, self.list)
-        # self.Bind(wx.EVT_LIST_COL_RIGHT_CLICK, self.OnColRightClick, self.list)
-        # self.Bind(wx.EVT_LIST_COL_BEGIN_DRAG, self.OnColBeginDrag, self.list)
-        # self.Bind(wx.EVT_LIST_COL_DRAGGING, self.OnColDragging, self.list)
-        # self.Bind(wx.EVT_LIST_COL_END_DRAG, self.OnColEndDrag, self.list)
-        # self.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT, self.OnBeginEdit, self.list)
-        # self.list.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)
-        # self.list.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown)
-
+        
     def Update(self, mapDBInfo):
         """Update list according new mapDBInfo description"""
         self.mapDBInfo = mapDBInfo
@@ -166,7 +159,13 @@
         
         tableName    = self.mapDBInfo.layers[layer]['table']
         keyColumn    = self.mapDBInfo.layers[layer]['key']
-        self.columns = self.mapDBInfo.tables[tableName]
+        try:
+            self.columns = self.mapDBInfo.tables[tableName]
+        except KeyError:
+            raise gcmd.DBMError(message=_("Attribute table <%s> not found. "
+                                          "For creating the table switch to "
+                                          "'Manage layers' tab.") % tableName,
+                                parent=self.parent)
         
         cmd = ["v.db.select",
                "-c", "--q",
@@ -415,6 +414,13 @@
         """Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py"""
         return (self.sm_dn, self.sm_up)
 
+    def IsEmpty(self):
+        """Check if list if empty"""
+        if self.columns:
+            return False
+        
+        return True
+    
 class AttributeManager(wx.Frame):
     """
     GRASS Attribute manager main window
@@ -549,6 +555,14 @@
                 continue
 
             panel = wx.Panel(parent=self.browsePage, id=wx.ID_ANY)
+            win = VirtualAttributeList(panel, self.log,
+                                       self.mapDBInfo, layer)
+            if win.IsEmpty():
+                del panel
+                continue
+            
+            win.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnDataItemActivated)
+
             self.layerPage[layer] = {'browsePage': panel.GetId()}
 
             self.browsePage.AddPage(page=panel, text=" %d / %s %s" % \
@@ -566,9 +580,6 @@
 
             sqlSizer = wx.StaticBoxSizer(sqlBox, wx.VERTICAL)
 
-            win = VirtualAttributeList(panel, self.log,
-                                       self.mapDBInfo, layer)
-            win.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnDataItemActivated)
             win.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnDataRightUp) #wxMSW
             win.Bind(wx.EVT_RIGHT_UP,            self.OnDataRightUp) #wxGTK
             if UserSettings.Get(group='atm', key='leftDbClick', subkey='selection') == 0:
@@ -671,7 +682,7 @@
             self.OnChangeSql(None)
             self.log.write(_("Number of loaded records: %d") % \
                            self.FindWindowById(self.layerPage[self.layer]['data']).GetItemCount())
-        except IndexError:
+        except (IndexError, KeyError):
             self.layer = None
         
     def __createManageTablePage(self, onlyLayer=-1):
@@ -680,9 +691,15 @@
             if onlyLayer > 0 and layer != onlyLayer:
                 continue
             
+            if not self.layerPage.has_key(layer):
+                continue
+            
             panel = wx.Panel(parent=self.manageTablePage, id=wx.ID_ANY)
             self.layerPage[layer]['tablePage'] = panel.GetId()
-            self.manageTablePage.AddPage(page=panel, text=" %d / %s %s" % (layer, _("Table"), self.mapDBInfo.layers[layer]['table']))
+            self.manageTablePage.AddPage(page=panel,
+                                         text=" %d / %s %s" % (layer,
+                                                               _("Table"),
+                                                               self.mapDBInfo.layers[layer]['table']))
             
             pageSizer = wx.BoxSizer(wx.VERTICAL)
             
@@ -2588,7 +2605,7 @@
         
         if ret == None:
             return columns
-
+        
         for column in ret.splitlines():
             columns.append(column)
         
@@ -3331,7 +3348,11 @@
         
     def GetColumns(self, table):
         """Return list of columns names (based on their index)"""
-        names = [''] * len(self.tables[table].keys())
+        try:
+            names = [''] * len(self.tables[table].keys())
+        except KeyError:
+            return []
+        
         for name, desc in self.tables[table].iteritems():
             names[desc['index']] = name
 

Modified: grass/trunk/gui/wxpython/gui_modules/gcmd.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/gcmd.py	2009-02-01 17:37:54 UTC (rev 35710)
+++ grass/trunk/gui/wxpython/gui_modules/gcmd.py	2009-02-01 17:39:24 UTC (rev 35711)
@@ -85,7 +85,7 @@
         self.Show()
         
         return ''
-
+    
 class GStdError(GException):
     """Generic exception"""
 

Modified: grass/trunk/gui/wxpython/gui_modules/georect.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/georect.py	2009-02-01 17:37:54 UTC (rev 35710)
+++ grass/trunk/gui/wxpython/gui_modules/georect.py	2009-02-01 17:39:24 UTC (rev 35711)
@@ -1,25 +1,29 @@
 """
 @package georect.py
 
-Georectification module for GRASS GIS. Includes ground control
+ at brief Georectification module for GRASS GIS. Includes ground control
 point management and interactive point and click GCP creation
 
 Classes:
- - Georectify
+ - GeorectWizard
+ - LocationPage
+ - GroupPage
+ - DispMapPage
  - GCP
- - GRMap
+ - GCPList
+ - VectGroup
+ - EditGCP
  - GrSettingsDialog
 
-COPYRIGHT: (C) 2006-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.
+(C) 2006-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.
+
 @author Michael Barton
-Updated by Martin Landa <landa.martin gmail.com>
+ at author Updated by Martin Landa <landa.martin gmail.com>
 """
 
-# recheck once completed to see how many of these are still needed
 import os
 import sys
 import tempfile
@@ -111,12 +115,14 @@
         self.grouppage = GroupPage(self.wizard, self)
         self.mappage = DispMapPage(self.wizard, self)
 
-        # Set the initial order of the pages
+        #
+        # set the initial order of the pages
+        #
         self.startpage.SetNext(self.grouppage)
         self.grouppage.SetPrev(self.startpage)
         self.grouppage.SetNext(self.mappage)
         self.mappage.SetPrev(self.grouppage)
-        
+
         #
         # do pages layout
         #
@@ -164,14 +170,14 @@
             if maptype == 'cell':
                 rendertype = 'raster'
                 cmdlist = ['d.rast', 'map=%s' % xy_map]
-            elif maptype == 'vector':
+            else: # -> vector layer
                 rendertype = 'vector'
                 cmdlist = ['d.vect', 'map=%s' % xy_map]
-
+            
             self.Map.AddLayer(type=rendertype, command=cmdlist, l_active=True,
                               name=utils.GetLayerNameFromCmd(cmdlist),
                               l_hidden=False, l_opacity=1.0, l_render=False)
-
+            
             #
             # start GCP form
             #
@@ -307,8 +313,10 @@
         #
         self.sizer.AddGrowableCol(2)
         # map type
-        self.rb_maptype = wx.RadioBox(parent=self, id=wx.ID_ANY, label=' %s ' % _("Map type to georectify"),
-                                      choices=[_('raster'), _('vector')], majorDimension=wx.RA_SPECIFY_COLS)
+        self.rb_maptype = wx.RadioBox(parent=self, id=wx.ID_ANY,
+                                      label=' %s ' % _("Map type to georectify"),
+                                      choices=[_('raster'), _('vector')],
+                                      majorDimension=wx.RA_SPECIFY_COLS)
         self.sizer.Add(item=self.rb_maptype,
                        flag=wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, border=5,
                        pos=(1, 1), span=(1, 2))
@@ -353,7 +361,7 @@
             maptype = 'cell'
         else:
             maptype = 'vector'
-
+        
     def OnLocation(self, event):
         """Sets source location for map(s) to georectify"""
         self.xylocation = event.GetString()
@@ -393,9 +401,9 @@
             wx.MessageBox(_('You must select a valid location and mapset in order to continue'))
             event.Veto()
             return
-        else:
-            self.parent.SetSrcEnv(self.xylocation, self.xymapset)
-
+        
+        self.parent.SetSrcEnv(self.xylocation, self.xymapset)
+        
     def OnEnterPage(self, event=None):
         if self.xylocation == '' or self.xymapset == '':
             wx.FindWindowById(wx.ID_FORWARD).Enable(False)
@@ -440,8 +448,17 @@
         self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Create group if none exists')),
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
                        pos=(2, 1))
+        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
         self.btn_mkgroup = wx.Button(parent=self, id=wx.ID_ANY, label=_("Create/edit group..."))
-        self.sizer.Add(item=self.btn_mkgroup,
+        self.btn_vgroup = wx.Button(parent=self, id=wx.ID_ANY, label=_("Add vector map to group..."))
+        self.btn_vgroup.Hide()
+        btnSizer.Add(item=self.btn_mkgroup,
+                     flag=wx.RIGHT, border=5)
+
+        btnSizer.Add(item=self.btn_vgroup,
+                     flag=wx.LEFT, border=5)
+        
+        self.sizer.Add(item=btnSizer,
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
                        pos=(2, 2))
         
@@ -459,7 +476,6 @@
         # bindings
         #
         self.Bind(wx.EVT_COMBOBOX, self.OnGroup, self.cb_group)
-        self.Bind(wx.EVT_BUTTON, self.OnMkGroup, self.btn_mkgroup)
         self.Bind(wx.EVT_TEXT, self.OnExtension, self.ext_txt)
         self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
         self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
@@ -470,19 +486,25 @@
         
     def OnMkGroup(self, event):
         """Create new group in source location/mapset"""
-        global maptype
+        menuform.GUI().ParseCommand(['i.group'],
+                                    completed=(self.GetOptData, None, ''),
+                                    parentframe=self.parent.parent, modal=True)
 
-        # open dialog
-        if maptype == 'cell':
-            menuform.GUI().ParseCommand(['i.group'],
-                                        completed=(self.GetOptData, None, ''),
-                                        parentframe=self.parent.parent, modal=True)
-        elif maptype == 'vector':
-            dlg = VectGroup(self, wx.ID_ANY, self.grassdatabase, self.xylocation, self.xymapset, self.xygroup)
-            if dlg.ShowModal() == wx.ID_OK:
-                dlg.MakeVGroup()
-                self.OnEnterPage()
+    def OnVGroup(self, event):
+        """Add vector maps to group"""
+        dlg = VectGroup(parent = self,
+                        id = wx.ID_ANY,
+                        grassdb = self.grassdatabase,
+                        location = self.xylocation,
+                        mapset = self.xymapset,
+                        group = self.xygroup)
 
+        if dlg.ShowModal() != wx.ID_OK:
+            return
+
+        dlg.MakeVGroup()
+        self.OnEnterPage()
+        
     def GetOptData(self, dcmd, layer, params, propwin):
         """Process i.group"""
         # update the page
@@ -507,47 +529,64 @@
             return
 
     def OnEnterPage(self, event=None):
+        global maptype
+        
         self.groupList = []
-        tmplist = []
 
         self.xylocation = self.parent.gisrc_dict['LOCATION_NAME']
         self.xymapset = self.parent.gisrc_dict['MAPSET']
 
         # create a list of groups in selected mapset
-        if os.path.isdir(os.path.join(self.grassdatabase,self.xylocation,self.xymapset,'group')):
-            tmplist = os.listdir(os.path.join(self.grassdatabase, self.xylocation, self.xymapset, 'group'))
-        else:
-            tmplist = []
-        # if (event and event.GetDirection()) and self.xygroup == '':
-        #             if tmplist == []:
-        #                 wx.MessageBox(_('No map/imagery groups exist to georectify. '
-        #                                 'You will need to create one.'))
-        #             else:
-        for item in tmplist:
-            if os.path.isdir(os.path.join(self.grassdatabase, self.xylocation, self.xymapset, 'group', item)):
-                self.groupList.append(item)
-                
+        if os.path.isdir(os.path.join(self.grassdatabase,
+                                      self.xylocation,
+                                      self.xymapset,
+                                      'group')):
+            tmplist = os.listdir(os.path.join(self.grassdatabase,
+                                              self.xylocation,
+                                              self.xymapset,
+                                              'group'))
+            for item in tmplist:
+                if os.path.isdir(os.path.join(self.grassdatabase,
+                                              self.xylocation,
+                                              self.xymapset,
+                                              'group',
+                                              item)):
+                    self.groupList.append(item)
+        
+        if maptype == 'cell':
+            self.btn_vgroup.Hide()
+            self.Bind(wx.EVT_BUTTON, self.OnMkGroup, self.btn_mkgroup)
+
+        elif maptype == 'vector':
+            self.btn_vgroup.Show()
+            self.Bind(wx.EVT_BUTTON, self.OnMkGroup, self.btn_mkgroup)
+            self.Bind(wx.EVT_BUTTON, self.OnVGroup, self.btn_vgroup)
+        
         utils.ListSortLower(self.groupList)
         self.cb_group.SetItems(self.groupList)
-        if len(self.groupList) > 0:
+        
+        if len(self.groupList) > 0 and \
+                self.xygroup == '':
             self.cb_group.SetSelection(0)
             self.xygroup = self.groupList[0]
-            
-        if self.xygroup == '' or self.extension == '':
+        
+        if self.xygroup == '' or \
+                self.extension == '':
             wx.FindWindowById(wx.ID_FORWARD).Enable(False)
         else:
             wx.FindWindowById(wx.ID_FORWARD).Enable(True)
-
+        
         # switch to source
         self.parent.SwitchEnv('new')
-
+    
 class DispMapPage(TitledPage):
     """
     Select ungeoreferenced map to display for interactively
     setting ground control points (GCPs).
     """
     def __init__(self, wizard, parent):
-        TitledPage.__init__(self, wizard, _("Select image/map to display for ground control point (GCP) creation"))
+        TitledPage.__init__(self, wizard,
+                            _("Select image/map to display for ground control point (GCP) creation"))
 
         self.parent = parent
         global maptype
@@ -558,8 +597,10 @@
         self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select display image/map:')),
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
                        pos=(1, 1))
-        self.selection = gselect.Select(self, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
-                                        type=maptype)
+        
+        self.selection = gselect.Select(self, id=wx.ID_ANY,
+                                        size=globalvar.DIALOG_GSELECT_SIZE)
+        
         self.sizer.Add(item=self.selection,
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
                        pos=(1, 2))
@@ -597,7 +638,8 @@
         global maptype
         global xy_map
         
-        self.selection.SetElementList(maptype)
+        self.selection.SetElementList(maptype,
+                                      mapsets = [self.parent.newmapset, ])
 
         if xy_map == '':
             wx.FindWindowById(wx.ID_FORWARD).Enable(False)
@@ -999,7 +1041,7 @@
         
         if self.CheckGCPcount(msg=True) == False:
             return
-                
+
         if maptype == 'cell':
             self.grwiz.SwitchEnv('new')
             cmdlist = ['i.rectify','-a','group=%s' % self.xygroup,
@@ -1009,45 +1051,99 @@
             
             self.parent.goutput.RunCmd(cmdlist, compReg=False,
                                        switchPage=True)
-
+            
             time.sleep(.1)
             self.grwiz.SwitchEnv('original')
 
         elif maptype == 'vector':
-            # loop through all vectors in VREF and move resulting vector to target location
-            f = open(self.vgrpfile)
+            # loop through all vectors in VREF
+            # and move resulting vector to target location
+            f = open(self.file['vgrp'])
             vectlist = []
             try:
-                for vect in f:
-                    vect = vect.strip(' \n')
+                for vect in f.readlines():
+                    vect = vect.strip('\n')
+                    if len(vect) < 1:
+                        continue
                     vectlist.append(vect)
             finally:
                 f.close()
             for vect in vectlist:
-                outname = vect+'_'+self.extension
-                p = gcmd.RunCommand('v.transform',
-                                    parent = self,
-                                    quiet = True,
-                                    input = vect,
-                                    output = outname, 
-                                    pointsfile = self.pointsfile)
+                self.grwiz.SwitchEnv('new')
+                self.outname = vect + '_' + self.extension
+                self.parent.goutput.WriteLog(text = _('Transforming <%s>...') % vect,
+                                             switchPage = True)
+                xyLayer = []
+                for layer in grass.vector_db(map = vect).itervalues():
+                    xyLayer.append((layer['driver'],
+                                    layer['database'],
+                                    layer['table']))
+                self.parent.goutput.RunCmd(['v.transform',
+                                            '--o',
+                                            'input=%s' % vect,
+                                            'output=%s' % self.outname,
+                                            'pointsfile=%s' % self.file['points']],
+                                           switchPage = True,
+                                           onDone = self.OnGeorectDone)
+
+                dbConnect = grass.db_connection()
+                for layer in xyLayer:                
+                    self.parent.goutput.RunCmd(['db.copy',
+                                                '--q',
+                                                '--o',
+                                                'from_driver=%s' % layer[0],
+                                                'from_database=%s' % layer[1],
+                                                'from_table=%s' % layer[2],
+                                                'to_driver=%s' % dbConnect['driver'],
+                                                'to_database=%s' % dbConnect['database'],
+                                                'to_table=%s' % layer[2] + '_' + self.extension])
+            
+    def OnGeorectDone(self, **kargs):
+        """Print final message"""
+        global maptype
+        if maptype == 'cell':
+            return
+        
+        returncode = kargs['returncode']
+        
+        xyvpath = os.path.join(self.grassdatabase,
+                               self.xylocation,
+                               self.xymapset,
+                               'vector',
+                               self.outname)
+        vpath = os.path.join(self.grassdatabase,
+                             self.currentlocation,
+                             self.currentmapset,
+                             'vector',
+                             self.outname)
+        
+        if os.path.isdir(vpath):
+            self.parent.goutput.WriteWarning(_('Vector map <%s> already exists. '
+                                               'Change extension name and '
+                                               'georectify again.') % self.outname)
+        else:
+            if returncode == 0:
+                if not os.path.isdir(os.path.join(self.grassdatabase,
+                                                  self.currentlocation,
+                                                  self.currentmapset,
+                                                  'vector')):
+                    os.mkdir(os.path.join(self.grassdatabase,
+                                          self.currentlocation,
+                                          self.currentmapset,
+                                          'vector'))
+                shutil.move(xyvpath, vpath)        
                 
-            if p == 0:
-                wx.MessageBox("All maps were georectified successfully")
-                for vect in vectlist:
-                    outname = vect+'_'+self.extension
-                    xyvpath = os.path.join(self.grassdatabase,self.xylocation,self.xymapset,'vector',outname)
-                    vpath = os.path.join(self.grassdatabase,self.currentlocation,self.currentmapset,'vector',outname)
-                    if os.path.isfile(vpath):
-                        wx.MessageBox("%s already exists. Change extension name and georectify again" % outname)
-                    else:
-                        shutil.move(xyvpath, vpath)                
-                                    
-                wx.MessageBox('For vector files with attribute tables, you will need to manually copy the tables to the new location')
+                self.parent.goutput.WriteCmdLog(_('Vector map <%s> georectified '
+                                                  'successfully') % self.outname)
+                # copy attributes
+                self.parent.goutput.WriteLog(_('Copying attributes...'))
+                
             else:
-                wx.MessageBox('Some maps were not georectified successfully')
-        else:
-            return
+                self.parent.goutput.WriteError(_('Georectification of vector map <%s> failed') %
+                                               self.outname)
+                
+        del self.outname
+        self.grwiz.SwitchEnv('original')
         
     def OnSettings(self, event):
         """Georectifier settings"""
@@ -1298,97 +1394,131 @@
 class VectGroup(wx.Dialog):
     """
     Dialog to create a vector group (VREF file) for georectifying
+
+    @todo Replace by g.group
     """
-
     def __init__(self, parent, id, grassdb, location, mapset, group,
-                style=wx.DEFAULT_DIALOG_STYLE):
-  
-        wx.Dialog.__init__(self, parent, id, style=style)
+                 style=wx.DEFAULT_DIALOG_STYLE):
         
+        wx.Dialog.__init__(self, parent, id, style=style,
+                           title = _("Create vector map group"))
+        
         self.grassdatabase = grassdb
         self.xylocation = location
         self.xymapset = mapset
         self.xygroup = group
         
+        #
         # get list of valid vector directories
-        vectlist = os.listdir(os.path.join(self.grassdatabase,self.xylocation,self.xymapset,'vector'))
+        #
+        vectlist = os.listdir(os.path.join(self.grassdatabase,
+                                           self.xylocation,
+                                           self.xymapset,
+                                           'vector'))
         for dir in vectlist:
-            if os.path.isfile(os.path.join(self.grassdatabase,self.xylocation,self.xymapset,'vector',dir,'coor')):
-                pass
-            else:
+            if not os.path.isfile(os.path.join(self.grassdatabase,
+                                           self.xylocation,
+                                           self.xymapset,
+                                           'vector',
+                                           dir,
+                                           'coor')):
                 vectlist.remove(dir)
         
-        self.vgrouplist = []
-        self.vgrpfile = os.path.join(self.grassdatabase,self.xylocation,self.xymapset,'group',self.xygroup,'VREF')
+        utils.ListSortLower(vectlist)
+        
+        # path to vref file
+        self.vgrpfile = os.path.join(self.grassdatabase,
+                                     self.xylocation,
+                                     self.xymapset,
+                                     'group',
+                                     self.xygroup,
+                                     'VREF')
+        
+        #
+        # buttons
+        #
+        self.btnCancel = wx.Button(parent = self,
+                                   id = wx.ID_CANCEL)
+        self.btnOK = wx.Button(parent = self,
+                                   id = wx.ID_OK)
+        self.btnOK.SetDefault()
+
+
+        #
+        # list of vector maps
+        #
+        self.listMap = wx.CheckListBox(parent = self, id = wx.ID_ANY,
+                                      choices = vectlist)
+        
         if os.path.isfile(self.vgrpfile):
             f = open(self.vgrpfile)
             try:
-                for line in f:
-                    if line != '':
-                        self.vgrouplist.append(line.strip(' \n'))
+                checked = []
+                for line in f.readlines():
+                    line = line.replace('\n', '')
+                    if len(line) < 1:
+                        continue
+                    checked.append(line)
+                self.listMap.SetCheckedStrings(checked)
             finally:
                 f.close()
-        
-        self.btnCancel = wx.Button(self, wx.ID_CANCEL)
-        self.btnSubmit = wx.Button(self, wx.ID_OK)
-        self.btnSubmit.SetDefault()
+                
+        line = wx.StaticLine(parent = self,
+                             id = wx.ID_ANY, size = (20, -1),
+                             style = wx.LI_HORIZONTAL)
 
+        #
+        # layout
+        #
         sizer = wx.BoxSizer(wx.VERTICAL)
         
         box = wx.BoxSizer(wx.HORIZONTAL)
-        label = wx.StaticText(parent=self, id=wx.ID_ANY,
-                              label='Select vector map(s) to add to group:')
-        box.Add(label, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, border=5)
-        self.addmap = wx.CheckListBox(self, -1, wx.DefaultPosition, wx.DefaultSize, vectlist)
-        box.Add(self.addmap, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT| wx.LEFT, border=5)
-        sizer.Add(box, flag=wx.ALIGN_RIGHT | wx.ALL, border=3)
+        box.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
+                                     label = _('Select vector map(s) to add to group:')),
+                flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
+                border = 5)
+
+        box.Add(item = self.listMap,
+                flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
+                border = 5)
+
         
-        box = wx.BoxSizer(wx.HORIZONTAL)
-        label = wx.StaticText(parent=self, id=wx.ID_ANY,
-                              label='Select vector map(s) to remove from group:')
-        box.Add(label, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, border=5)
-        self.remmap = wx.CheckListBox(self, -1, wx.DefaultPosition, wx.DefaultSize, self.vgrouplist)
-        box.Add(self.remmap, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT| wx.LEFT, border=5)
-        sizer.Add(box, flag=wx.ALIGN_RIGHT | wx.ALL, border=3)
-
+        sizer.Add(box, flag = wx.ALIGN_RIGHT | wx.ALL,
+                  border = 3)
+        
+        sizer.Add(item = line, proportion = 0,
+                  flag = wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+                  border = 5)
+        
         # buttons
         btnSizer = wx.StdDialogButtonSizer()
         btnSizer.AddButton(self.btnCancel)
-        btnSizer.AddButton(self.btnSubmit)
+        btnSizer.AddButton(self.btnOK)
         btnSizer.Realize()
 
-        sizer.Add(item=btnSizer, proportion=0,
-                  flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
-
+        sizer.Add(item = btnSizer, proportion = 0,
+                  flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER,
+                  border = 5)
+        
         self.SetSizer(sizer)
         sizer.Fit(self)
         self.Layout()
         
-        self.Bind(wx.EVT_CHECKLISTBOX, self.AddVect, self.addmap)
-        self.Bind(wx.EVT_CHECKLISTBOX, self.RemoveVect, self.remmap)
-
-    def AddVect(self, event):
-        index = event.GetSelection()
-        label = self.addmap.GetString(index)
-        if self.addmap.IsChecked(index):
-            self.vgrouplist.append(label)
-        self.addmap.SetSelection(index)    
-        event.Skip()
+    def MakeVGroup(self):
+        """Create VREF file"""
+        vgrouplist = []
+        for item in range(self.listMap.GetCount()):
+            if not self.listMap.IsChecked(item):
+                continue
+            vgrouplist.append(self.listMap.GetString(item))
         
-    def RemoveVect(self, event):
-        index = event.GetSelection()
-        label = self.remmap.GetString(index)
-        if self.remmap.IsChecked(index):
-            self.vgrouplist.remove(label)
-        self.remmap.SetSelection(index)    
-        event.Skip()
+        f = open(self.vgrpfile, mode='w')
+        try:
+            for vect in vgrouplist:
+                f.write(vect + '\n')
+        finally:
+            f.close()
         
-    def MakeVGroup(self):
-        f = open(self.vgrpfile, mode='w')
-        for vect in self.vgrouplist:
-            f.write(vect+'\n')
-         
-
 class EditGPC(wx.Dialog):
     def __init__(self, parent, data, id=wx.ID_ANY,
                  title=_("Edit GCP"),

Modified: grass/trunk/gui/wxpython/gui_modules/goutput.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/goutput.py	2009-02-01 17:37:54 UTC (rev 35710)
+++ grass/trunk/gui/wxpython/gui_modules/goutput.py	2009-02-01 17:39:24 UTC (rev 35711)
@@ -61,17 +61,17 @@
 
         self.start()
 
-    def RunCmd(self, callable, *args, **kwds):
+    def RunCmd(self, callable, onDone, *args, **kwds):
         CmdThread.requestId += 1
 
         self.requestCmd = None
-        self.requestQ.put((CmdThread.requestId, callable, args, kwds))
+        self.requestQ.put((CmdThread.requestId, callable, onDone, args, kwds))
         
         return CmdThread.requestId
 
     def run(self):
         while True:
-            requestId, callable, args, kwds = self.requestQ.get()
+            requestId, callable, onDone, args, kwds = self.requestQ.get()
             
             requestTime = time.time()
             event = wxCmdRun(cmd=args[0],
@@ -96,10 +96,11 @@
             
             time.sleep(.1)
             
-            event = wxCmdDone(aborted=aborted,
-                              returncode=returncode,
-                              time=requestTime,
-                              pid=requestId)
+            event = wxCmdDone(aborted = aborted,
+                              returncode = returncode,
+                              time = requestTime,
+                              pid = requestId,
+                              onDone = onDone)
             
             wx.PostEvent(self.parent, event)
 
@@ -213,7 +214,8 @@
 
         return False
 
-    def WriteLog(self, text, style=None, wrap=None):
+    def WriteLog(self, text, style = None, wrap = None,
+                 switchPage = False):
         """Generic method for writing log message in 
         given style
 
@@ -221,6 +223,10 @@
         @param style text style (see GMStc)
         @param stdout write to stdout or stderr
         """
+        if switchPage and \
+                self.parent.notebook.GetSelection() != self.parent.goutput.pageid:
+            self.parent.notebook.SetSelection(self.parent.goutput.pageid)
+        
         if not style:
             style = self.cmd_output.StyleDefault
         
@@ -244,16 +250,21 @@
         self.cmd_output.EnsureCaretVisible()
         
     def WriteCmdLog(self, line, pid=None):
-        """Write out line in selected style"""
+        """Write message in selected style"""
         if pid:
             line = '(' + str(pid) + ') ' + line
         self.WriteLog(line, style=self.cmd_output.StyleCommand)
 
     def WriteWarning(self, line):
-        """Write out line in warning style"""
+        """Write message in warning style"""
         self.WriteLog(line, style=self.cmd_output.StyleWarning)
 
-    def RunCmd(self, command, compReg=True, switchPage=False):
+    def WriteError(self, line):
+        """Write message in error style"""
+        self.WriteLog(line, style=self.cmd_output.StyleError)
+
+    def RunCmd(self, command, compReg=True, switchPage=False,
+               onDone = None):
         """
         Run in GUI GRASS (or other) commands typed into
         console command text widget, and send stdout output to output
@@ -269,6 +280,7 @@
         @param command command (list)
         @param compReg if true use computation region
         @param switchPage switch to output page
+        @param onDone function to be called when command is finished
         """
         
         # map display window available ?
@@ -320,10 +332,13 @@
                 #
                 
                 # switch to 'Command output'
-                if switchPage and \
-                        self.parent.notebook.GetSelection() != self.parent.goutput.pageid:
-                    self.parent.notebook.SetSelection(self.parent.goutput.pageid)
-
+                if switchPage:
+                    if self.parent.notebook.GetSelection() != self.parent.goutput.pageid:
+                        self.parent.notebook.SetSelection(self.parent.goutput.pageid)
+                    
+                    self.parent.SetFocus() # -> set focus
+                    self.parent.Raise()
+                
                 # activate computational region (set with g.region)
                 # for all non-display commands.
                 if compReg:
@@ -338,8 +353,9 @@
                 else:
                     # process GRASS command with argument
                     self.cmdThread.RunCmd(GrassCmd,
+                                          onDone,
                                           cmdlist,
-                                          self.cmd_stdout, self.cmd_stderr)
+                                          self.cmd_stdout, self.cmd_stderr)                                          
                     
                     self.cmd_output_timer.Start(50)
 
@@ -494,6 +510,9 @@
                 # stopped deamon
                 pass
         
+        if event.onDone:
+            event.onDone(returncode = event.returncode)
+        
         self.console_progressbar.SetValue(0) # reset progress bar on '0%'
 
         self.cmd_output_timer.Stop()

Modified: grass/trunk/gui/wxpython/gui_modules/gselect.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/gselect.py	2009-02-01 17:37:54 UTC (rev 35710)
+++ grass/trunk/gui/wxpython/gui_modules/gselect.py	2009-02-01 17:39:24 UTC (rev 35711)
@@ -35,7 +35,7 @@
 
 class Select(wx.combo.ComboCtrl):
     def __init__(self, parent, id, size,
-                 type, multiple=False, mapsets=None, exceptOf=[]):
+                 type=None, multiple=False, mapsets=None, exceptOf=[]):
         """
         Custom control to create a ComboBox with a tree control
         to display and select GIS elements within acessible mapsets.
@@ -51,13 +51,17 @@
 
         self.SetPopupControl(self.tcp)
         self.SetPopupExtents(0,100)
-        self.tcp.GetElementList(type, mapsets, exceptOf)
-        self.tcp.SetData(type, mapsets, exceptOf, multiple)
+        if type:
+            self.tcp.GetElementList(type, mapsets, exceptOf)
+            self.tcp.SetData(type = type, mapsets = mapsets,
+                             exceptOf = exceptOf, multiple = multiple)
 
-    def SetElementList(self, type):
+    def SetElementList(self, type, mapsets = None, exceptOf = []):
         self.tcp.seltree.DeleteAllItems()
         self.tcp.GetElementList(type)
-
+        self.tcp.SetData(type = type, mapsets = mapsets,
+                         exceptOf = exceptOf)
+        
 class TreeCtrlComboPopup(wx.combo.ComboPopup):
     """
     Create a tree ComboBox for selecting maps and other GIS elements
@@ -303,12 +307,16 @@
 
         evt.Skip()
 
-    def SetData(self, type, mapsets, exceptOf, multiple):
-        """Select multiple items?"""
-        self.type = type
-        self.mapsets = mapsets
-        self.exceptOf = exceptOf
-        self.multiple = multiple
+    def SetData(self, **kargs):
+        """Set object properties"""
+        if kargs.has_key('type'):
+            self.type = kargs['type']
+        if kargs.has_key('mapsets'):
+            self.mapsets = kargs['mapsets']
+        if kargs.has_key('exceptOf'):
+            self.exceptOf = kargs['exceptOf']
+        if kargs.has_key('multiple'):
+            self.multiple = kargs['multiple']
         
 class VectorDBInfo:
     """Class providing information about attribute tables

Modified: grass/trunk/gui/wxpython/gui_modules/utils.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/utils.py	2009-02-01 17:37:54 UTC (rev 35710)
+++ grass/trunk/gui/wxpython/gui_modules/utils.py	2009-02-01 17:39:24 UTC (rev 35711)
@@ -46,7 +46,7 @@
                           read = True,
                           pid = os.getpid())
 
-    tempfile = tempfileCmd.splitlines()[0].strip()
+    tempfile = ret.splitlines()[0].strip()
 
     # FIXME
     # ugly hack for MSYS (MS Windows)



More information about the grass-commit mailing list