[GRASS-SVN] r42033 - in grass/branches/develbranch_6/gui/wxpython: . gui_modules

svn_grass at osgeo.org svn_grass at osgeo.org
Mon Apr 26 13:07:11 EDT 2010


Author: martinl
Date: 2010-04-26 13:07:10 -0400 (Mon, 26 Apr 2010)
New Revision: 42033

Modified:
   grass/branches/develbranch_6/gui/wxpython/gui_modules/gdialogs.py
   grass/branches/develbranch_6/gui/wxpython/gui_modules/gselect.py
   grass/branches/develbranch_6/gui/wxpython/wxgui.py
Log:
wxGUI: GdalSelect class implemented
(merge r42032 from trunk)


Modified: grass/branches/develbranch_6/gui/wxpython/gui_modules/gdialogs.py
===================================================================
--- grass/branches/develbranch_6/gui/wxpython/gui_modules/gdialogs.py	2010-04-26 16:41:52 UTC (rev 42032)
+++ grass/branches/develbranch_6/gui/wxpython/gui_modules/gdialogs.py	2010-04-26 17:07:10 UTC (rev 42033)
@@ -12,7 +12,9 @@
  - DecorationDialog
  - TextLayerDialog 
  - LoadMapLayersDialog
- - MultiImportDialog
+ - ImportDialog
+ - GdalImportDialog
+ - DxfImportDialog
  - LayersList (used by MultiImport) 
  - SetOpacityDialog
 
@@ -28,7 +30,6 @@
 import os
 import sys
 import re
-import glob
 
 import wx
 import wx.lib.filebrowsebutton as filebrowse
@@ -925,155 +926,36 @@
         """!Get selected layer type"""
         return self.layerType.GetStringSelection()
     
-class MultiImportDialog(wx.Dialog):
-    """!Import dxf layers"""
+class ImportDialog(wx.Dialog):
+    """!Dialog for bulk import of various data (base class)"""
     def __init__(self, parent, type,
-                 id=wx.ID_ANY, title=_("Multiple import"),
-                 link = False,
-                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
-
+                 id = wx.ID_ANY, title = _("Multiple import"),
+                 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
         self.parent = parent # GMFrame 
         self.importType = type
-        self.link = link     # Link or import data (only for GDAL/OGR) 
         
         self.commandId = -1  # id of running command
-       
-        wx.Dialog.__init__(self, parent, id, title, style=style)
-
-        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
         
-        self.inputTitle = _("Source name")
+        wx.Dialog.__init__(self, parent, id, title, style=style,
+                           name = "MultiImportDialog")
         
-        self.inputBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
-                                     label=" %s " % self.inputTitle)
+        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+        
         self.layerBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
                                      label=_(" List of %s layers ") % self.importType.upper())
-
-        #
-        # input
-        #
-        if self.importType == 'dxf':
-            inputFile = filebrowse.FileBrowseButton(parent=self.panel, id=wx.ID_ANY, 
-                                                     size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
-                                                     dialogTitle=_('Choose DXF file to import'),
-                                                     buttonText=_('Browse'),
-                                                     startDirectory=os.getcwd(), fileMode=0,
-                                                     changeCallback=self.OnSetInput,
-                                                     fileMask="DXF File (*.dxf)|*.dxf")
-            self.input = { 'file' : [_("DXF file:"),
-                                     inputFile,
-                                     list()] }
-            self.inputType = 'file'
-        else:
-            self.typeRadio = wx.RadioBox(parent = self.panel, id = wx.ID_ANY,
-                                         label = _('Source type'),
-                                         style = wx.RA_SPECIFY_COLS,
-                                         choices = [_("File"),
-                                                    _("Directory"),
-                                                    _("Database"),
-                                                    _("Protocol")])
-            self.typeRadio.SetSelection(0)
-            self.Bind(wx.EVT_RADIOBOX, self.OnChangeType)
-            
-            # input widgets
-            if self.importType == 'gdal':
-                filemask = 'GeoTIFF (*.tif)|*.tif'
-            else:
-                filemask = 'ESRI Shapefile (*.shp)|*.shp'
-            inputFile = filebrowse.FileBrowseButton(parent=self.panel, id=wx.ID_ANY, 
-                                                    size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
-                                                    dialogTitle=_('Choose input file'),
-                                                    buttonText=_('Browse'),
-                                                    startDirectory=os.getcwd(),
-                                                    changeCallback=self.OnSetInput,
-                                                    fileMask=filemask)
-            
-            inputDir = filebrowse.DirBrowseButton(parent=self.panel, id=wx.ID_ANY, 
-                                                  size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
-                                                  dialogTitle=_('Choose input directory'),
-                                                  buttonText=_('Browse'),
-                                                  startDirectory=os.getcwd(),
-                                                  changeCallback=self.OnSetInput)
-            inputDir.Hide()
-
-            inputDbFile = filebrowse.FileBrowseButton(parent=self.panel, id=wx.ID_ANY, 
-                                                      size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
-                                                      dialogTitle=_('Choose file'),
-                                                      buttonText=_('Browse'),
-                                                      startDirectory=os.getcwd(),
-                                                      changeCallback=self.OnSetInput)
-            inputDbFile.Hide()
-            
-            inputDbText = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY)
-            inputDbText.Hide()
-            inputDbText.Bind(wx.EVT_TEXT, self.OnSetInput)
-
-            inputDbChoice = wx.Choice(parent = self.panel, id = wx.ID_ANY)
-            inputDbChoice.Hide()
-            inputDbChoice.Bind(wx.EVT_CHOICE, self.OnSetInput)
-            
-            inputPro = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY)
-            inputPro.Hide()
-            inputPro.Bind(wx.EVT_TEXT, self.OnSetInput)
-
-            # format widget
-            self.formatText = wx.StaticText(self.panel, id=wx.ID_ANY, label=_("Format:"))
-            self.format = gselect.FormatSelect(parent = self.panel,
-                                               ftype = self.importType)
-            self.format.Bind(wx.EVT_CHOICE, self.OnSetFormat)
-            
-            self.input = { 'file' : [_("File:"),
-                                     inputFile,
-                                     globalvar.formats[self.importType]['file']],
-                           'dir'  : [_("Directory:"),
-                                     inputDir,
-                                     globalvar.formats[self.importType]['file']],
-                           'db'   : [_("Database:"),
-                                     inputDbFile,
-                                     globalvar.formats[self.importType]['database']],
-                           'pro'  : [_("Protocol:"),
-                                     inputPro,
-                                     globalvar.formats[self.importType]['protocol']],
-                           'db-win' : { 'file'   : inputDbFile,
-                                        'text'   : inputDbText,
-                                        'choice' : inputDbChoice },
-                           }
-            
-            self.inputType = 'file'
-            self.format.SetItems(self.input[self.inputType][2])
-            
-            if self.importType == 'gdal':
-                self.format.SetStringSelection('GeoTIFF')
-            elif self.importType == 'ogr':
-                self.format.SetStringSelection('ESRI Shapefile')
         
-        self.inputText = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
-                                       label = self.input[self.inputType][0],
-                                       size = (75, -1))
-        
         #
         # list of layers
         #
         self.list = LayersList(self.panel)
         self.list.LoadData()
-
-        self.add = wx.CheckBox(parent=self.panel, id=wx.ID_ANY)
-        if link:
-            self.add.SetLabel(_("Add linked layers into layer tree"))
-        else:
-            self.add.SetLabel(_("Add imported layers into layer tree"))
-
-        if not link and self.importType in ('gdal', 'ogr'):
-            self.overrideCheck = wx.CheckBox(parent=self.panel, id=wx.ID_ANY,
-                                             label=_("Override projection (use location's projection)"))
-            self.overrideCheck.SetValue(True)
-                                             
-        self.add.SetValue(UserSettings.Get(group='cmd', key='addNewLayer', subkey='enabled'))
-
+        
         self.overwrite = wx.CheckBox(parent=self.panel, id=wx.ID_ANY,
                                      label=_("Allow output files to overwrite existing files"))
         self.overwrite.SetValue(UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))
         
+        self.add = wx.CheckBox(parent=self.panel, id=wx.ID_ANY)
+        
         #
         # buttons
         #
@@ -1082,52 +964,19 @@
         self.btn_cancel.SetToolTipString(_("Close dialog"))
         self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
         # run
-        if link:
-            self.btn_run = wx.Button(parent=self.panel, id=wx.ID_OK, label= _("&Link"))
-            self.btn_run.SetToolTipString(_("Link selected layers"))
-        else:
-            self.btn_run = wx.Button(parent=self.panel, id=wx.ID_OK, label= _("&Import"))
-            self.btn_run.SetToolTipString(_("Import selected layers"))
+        self.btn_run = wx.Button(parent=self.panel, id=wx.ID_OK)
         self.btn_run.SetDefault()
         self.btn_run.Enable(False)
         self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
-        
-        self.__doLayout()
-        self.Layout()
 
-    def __doLayout(self):
+    def doLayout(self):
+        """!Do layout"""
         dialogSizer = wx.BoxSizer(wx.VERTICAL)
-        #
-        # input
-        #
-        inputSizer = wx.StaticBoxSizer(self.inputBox, wx.HORIZONTAL)
         
-        gridSizer = wx.FlexGridSizer(cols=2, vgap=5, hgap=5)
-       
-        gridSizer.Add(item=self.inputText,
-                      flag=wx.ALIGN_CENTER_VERTICAL)
-        gridSizer.AddGrowableCol(1)
-        self.inputTypeSizer = wx.BoxSizer(wx.HORIZONTAL)
-        self.inputTypeSizer.Add(item=self.input[self.inputType][1], proportion = 1,
-                                flag = wx.ALIGN_CENTER_VERTICAL)
+        # dsn input
+        dialogSizer.Add(item = self.dsnInput, proportion = 0,
+                        flag = wx.EXPAND)
         
-        gridSizer.Add(item=self.inputTypeSizer,
-                      flag=wx.EXPAND | wx.ALL)
-        
-        if self.importType != 'dxf':
-            gridSizer.Add(item=self.formatText,
-                          flag=wx.ALIGN_CENTER_VERTICAL)
-            gridSizer.Add(item=self.format)
-        
-        inputSizer.Add(item=gridSizer, proportion=1,
-                       flag=wx.EXPAND | wx.ALL)
-
-        if self.importType != 'dxf':
-            dialogSizer.Add(item=self.typeRadio, proportion=0,
-                            flag=wx.ALL | wx.EXPAND, border=5)
-        dialogSizer.Add(item=inputSizer, proportion=0,
-                        flag=wx.ALL | wx.EXPAND, border=5)
-
         #
         # list of DXF layers
         #
@@ -1138,17 +987,17 @@
         
         dialogSizer.Add(item=layerSizer, proportion=1,
                         flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=5)
-
+        
         if hasattr(self, "overrideCheck"):
             dialogSizer.Add(item=self.overrideCheck, proportion=0,
                             flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=5)
-
+        
         dialogSizer.Add(item=self.overwrite, proportion=0,
                         flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=5)
         
         dialogSizer.Add(item=self.add, proportion=0,
                         flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=5)
-
+        
         #
         # buttons
         #
@@ -1170,64 +1019,101 @@
         self.panel.SetSizer(dialogSizer)
         dialogSizer.Fit(self.panel)
         
-        self.Layout()
         # auto-layout seems not work here - FIXME
         size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 175, 400)
         self.SetMinSize(size)
         self.SetSize((size.width, size.height + 100))
         width = self.GetSize()[0]
         self.list.SetColumnWidth(col=1, width=width/2 - 50)
+        self.Layout()
         
-    def OnChangeType(self, event):
-        """!Datasource type changed"""
-        sel = event.GetSelection()
-        win = self.input[self.inputType][1]
-        self.inputTypeSizer.Remove(win)
-        win.Hide()
+    def OnCancel(self, event=None):
+        """!Close dialog"""
+        self.Close()
+
+    def OnRun(self, event):
+        """!Import/Link data (each layes as separate vector map)"""
+        pass
+    
+    def AddLayers(self, returncode):
+        """!Add imported/linked layers into layer tree"""
+        self.commandId += 1
         
-        if sel == 0:   # file
-            self.inputType = 'file'
-            format = self.input[self.inputType][2][0]
-            try:
-                ext = self.format.GetExtension(format)
-                if not ext:
-                    raise KeyError
-                format += ' (*.%s)|*.%s' % (ext, ext)
-            except KeyError:
-                format += ' (*.*)|*.*'
-            
-            win = filebrowse.FileBrowseButton(parent=self.panel, id=wx.ID_ANY, 
-                                              size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
-                                              dialogTitle=_('Choose input file'),
-                                              buttonText=_('Browse'),
-                                              startDirectory=os.getcwd(),
-                                              changeCallback=self.OnSetInput,
-                                              fileMask = format)
-            self.input[self.inputType][1] = win
-        elif sel == 1: # directory
-            self.inputType = 'dir'
-        elif sel == 2: # database
-            self.inputType = 'db'
-        elif sel == 3: # protocol
-            self.inputType = 'pro'
+        if not self.add.IsChecked():
+            return
         
-        win = self.input[self.inputType][1]
-        self.inputTypeSizer.Add(item = win, proportion = 1,
-                                flag = wx.ALIGN_CENTER_VERTICAL)
-        win.SetValue('')
-        self.list.DeleteAllItems()
-        win.Show()
+        maptree = self.parent.curr_page.maptree
         
-        self.inputText.SetLabel(self.input[self.inputType][0])
-        self.format.SetItems(self.input[self.inputType][2])
-        self.format.SetSelection(0)
+        layer, output = self.list.GetLayers()[self.commandId]
         
-        self.inputTypeSizer.Layout()
+        if '@' not in output:
+            name = output + '@' + grass.gisenv()['MAPSET']
+        else:
+            name = output
+        # add imported layers into layer tree
+        if self.importType == 'gdal':
+            cmd = ['d.rast',
+                   'map=%s' % name]
+            if UserSettings.Get(group='cmd', key='rasterOpaque', subkey='enabled'):
+                cmd.append('-n')
+                
+            item = maptree.AddLayer(ltype='raster',
+                                    lname=name,
+                                    lcmd=cmd)
+        else:
+            item = maptree.AddLayer(ltype='vector',
+                                    lname=name,
+                                    lcmd=['d.vect',
+                                          'map=%s' % name])
+        maptree.mapdisplay.MapWindow.ZoomToMap()
         
-    def OnCancel(self, event=None):
-        """!Close dialog"""
-        self.Close()
+    def OnAbort(self, event):
+        """!Abort running import
 
+        @todo not yet implemented
+        """
+        pass
+
+class GdalImportDialog(ImportDialog):
+    """!Dialog for bulk import of various raster/vector data"""
+    def __init__(self, parent, ogr = False, link = False):
+        self.link = link
+        if ogr:
+            ImportDialog.__init__(self, parent, type = 'ogr')
+            if link:
+                self.SetTitle(_("Link vector data"))
+            else:
+                self.SetTitle(_("Import vector data"))
+        else:
+            ImportDialog.__init__(self, parent, type = 'gdal') 
+            if link:
+                self.SetTitle(_("Link raster data"))
+            else:
+                self.SetTitle(_("Import raster data"))
+       
+        self.dsnInput = gselect.GdalSelect(parent = self, panel = self.panel, ogr = ogr)
+
+        if not link:
+            self.overrideCheck = wx.CheckBox(parent=self.panel, id=wx.ID_ANY,
+                                             label=_("Override projection (use location's projection)"))
+            self.overrideCheck.SetValue(True)
+        
+        if link:
+            self.add.SetLabel(_("Add linked layers into layer tree"))
+        else:
+            self.add.SetLabel(_("Add imported layers into layer tree"))
+        
+        self.add.SetValue(UserSettings.Get(group='cmd', key='addNewLayer', subkey='enabled'))
+
+        if link:
+            self.btn_run.SetLabel(_("&Link"))
+            self.btn_run.SetToolTipString(_("Link selected layers"))
+        else:
+            self.btn_run.SetLabel(_("&Import"))
+            self.btn_run.SetToolTipString(_("Import selected layers"))
+        
+        self.doLayout()
+
     def OnRun(self, event):
         """!Import/Link data (each layes as separate vector map)"""
         data = self.list.GetLayers()
@@ -1235,30 +1121,13 @@
         # hide dialog
         self.Hide()
         
-        if self.importType == 'dxf':
-            inputDxf = self.input[self.inputType][1].GetValue()
-        else:
-            if self.inputType == 'file':
-                dsn = os.path.dirname(self.input[self.inputType][1].GetValue())
-            else:
-                if self.format.GetStringSelection() == 'PostgreSQL':
-                    dsn = 'PG:dbname=%s' % self.input[self.inputType][1].GetStringSelection()
-                else:
-                    dsn = self.input[self.inputType][1].GetValue()
-            try:
-                ext = '.' + self.format.GetExtension(self.format.GetStringSelection())
-            except KeyError:
-                ext = ''
-        
+        dsn = self.dsnInput.GetDsn()
+        ext = self.dsnInput.GetFormatExt()
+            
         for layer, output in data:
-            if self.importType == 'dxf':
-                cmd = ['v.in.dxf',
-                       'input=%s' % inputDxf,
-                       'layers=%s' % layer,
-                       'output=%s' % output]
-            elif self.importType == 'ogr':
-                if layer.rfind(ext) > -1:
-                    layer = layer.replace(ext, '')
+            if self.importType == 'ogr':
+                if ext and layer.rfind(ext) > -1:
+                    layer = layer.replace('.' + ext, '')
                 if self.link:
                     cmd = ['v.external',
                            'dsn=%s' % dsn,
@@ -1270,19 +1139,22 @@
                            'layer=%s' % layer,
                            'output=%s' % output]
             else: # gdal
+                if self.dsnInput.GetType() == 'dir':
+                    dsn = os.path.join(dsn, layer)
+                
                 if self.link:
                     cmd = ['r.external',
-                           'input=%s' % (os.path.join(dsn, layer)),
+                           'input=%s' % dsn,
                            'output=%s' % output]
                 else:
                     cmd = ['r.in.gdal',
-                           'input=%s' % (os.path.join(dsn, layer)),
+                           'input=%s' % dsn,
                            'output=%s' % output]
             
             if self.overwrite.IsChecked():
                 cmd.append('--overwrite')
             
-            if hasattr(self, "overrideCheck") and self.overrideCheck.IsChecked():
+            if not self.link and self.overrideCheck.IsChecked():
                 cmd.append('-o')
             
             if UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'):
@@ -1290,174 +1162,79 @@
             
             # run in Layer Manager
             self.parent.goutput.RunCmd(cmd, switchPage=True,
-                                       onDone = self._addLayers)
+                                       onDone = self.AddLayers)
         
         self.OnCancel()
         
-    def _addLayers(self, returncode):
-        """!Add imported/linked layers into layer tree"""
-        self.commandId += 1
+class DxfImportDialog(ImportDialog):
+    """!Dialog for bulk import of DXF layers""" 
+    def __init__(self, parent):
+        ImportDialog.__init__(self, parent, type = 'dxf',
+                              title = _("Import DXF layers"))
         
-        if not self.add.IsChecked():
-            return
+        self.dsnInput = filebrowse.FileBrowseButton(parent=self.panel, id=wx.ID_ANY, 
+                                                    size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
+                                                    dialogTitle=_('Choose DXF file to import'),
+                                                    buttonText=_('Browse'),
+                                                    startDirectory=os.getcwd(), fileMode=0,
+                                                    changeCallback=self.OnSetDsn,
+                                                    fileMask="DXF File (*.dxf)|*.dxf")
         
-        maptree = self.parent.curr_page.maptree
+        self.add.SetLabel(_("Add imported layers into layer tree"))
         
-        layer, output = self.list.GetLayers()[self.commandId]
+        self.add.SetValue(UserSettings.Get(group='cmd', key='addNewLayer', subkey='enabled'))
         
-        if '@' not in output:
-            name = output + '@' + grass.gisenv()['MAPSET']
-        else:
-            name = output
-        # add imported layers into layer tree
-        if self.importType == 'gdal':
-            cmd = ['d.rast',
-                   'map=%s' % name]
-            if UserSettings.Get(group='cmd', key='rasterOverlay', subkey='enabled'):
-                cmd.append('-o')
-                
-            item = maptree.AddLayer(ltype='raster',
-                                    lname=name,
-                                    lcmd=cmd)
-        else:
-            item = maptree.AddLayer(ltype='vector',
-                                    lname=name,
-                                    lcmd=['d.vect',
-                                          'map=%s' % name])
-        maptree.mapdisplay.MapWindow.ZoomToMap()
+        self.doLayout()
         
-    def OnAbort(self, event):
-        """!Abort running import
-
-        @todo not yet implemented
-        """
-        pass
+    def OnRun(self, event):
+        """!Import/Link data (each layes as separate vector map)"""
+        data = self.list.GetLayers()
         
-    def OnSetFormat(self, event):
-        """!Format changed"""
-        if self.inputType not in ['file', 'db']:
-            return
+        # hide dialog
+        self.Hide()
         
-        win = self.input[self.inputType][1]
-        self.inputTypeSizer.Remove(win)
+        inputDxf = self.dsnInput.GetValue()
         
-        if self.inputType == 'file':
-            win.Destroy()
-        else: # database
-            win.Hide()
-        
-        format = event.GetString()
-        
-        if self.inputType == 'file':
-            try:
-                ext = self.format.GetExtension(format)
-                if not ext:
-                    raise KeyError
-                format += ' (*.%s)|*.%s' % (ext, ext)
-            except KeyError:
-                format += ' (*.*)|*.*'
+        for layer, output in data:
+            cmd = ['v.in.dxf',
+                   'input=%s' % inputDxf,
+                   'layers=%s' % layer,
+                   'output=%s' % output]
             
-            win = filebrowse.FileBrowseButton(parent=self.panel, id=wx.ID_ANY, 
-                                              size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
-                                              dialogTitle=_('Choose file'),
-                                              buttonText=_('Browse'),
-                                              startDirectory=os.getcwd(),
-                                              changeCallback=self.OnSetInput,
-                                              fileMask = format)
-        else: # database
-            if format == 'SQLite':
-                win = self.input['db-win']['file']
-            elif format == 'PostgreSQL':
-                if grass.find_program('psql'):
-                    win = self.input['db-win']['choice']
-                    if not win.GetItems():
-                        p = grass.Popen(['psql', '-ltA'], stdout = grass.PIPE)
-                        ret = p.communicate()[0]
-                        if ret:
-                            db = list()
-                            for line in ret.splitlines():
-                                sline = line.split('|')
-                                if len(sline) < 2:
-                                    continue
-                                dbname = sline[0]
-                                if dbname:
-                                    db.append(dbname)
-                            win.SetItems(db)
-                else:
-                    win = self.input['db-win']['text']
-            else:
-                win = self.input['db-win']['text']
+            if self.overwrite.IsChecked() or \
+                    UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'):
+                cmd.append('--overwrite')
+            
+            # run in Layer Manager
+            self.parent.goutput.RunCmd(cmd, switchPage=True,
+                                       onDone = self.AddLayers)
         
-        self.input[self.inputType][1] = win
-        if not win.IsShown():
-            win.Show()
-        self.inputTypeSizer.Add(item = win, proportion = 1,
-                                flag = wx.ALIGN_CENTER_VERTICAL)
-        self.inputTypeSizer.Layout()
-        
-    def OnSetInput(self, event):
-        """!Input DXF file/OGR dsn defined, update list of layer widget"""
+        self.OnCancel()
+
+    def OnSetDsn(self, event):
+        """!Input DXF file defined, update list of layer widget"""
         path = event.GetString()
         if not path:
             return 
-
+        
         data = list()        
-        if self.importType == 'dxf':
-            ret = gcmd.RunCommand('v.in.dxf',
-                                  quiet = True,
-                                  parent = self,
-                                  read = True,
-                                  flags = 'l',
-                                  input = path)
-            if not ret:
-                self.list.LoadData()
-                self.btn_run.Enable(False)
-                return
+        ret = gcmd.RunCommand('v.in.dxf',
+                              quiet = True,
+                              parent = self,
+                              read = True,
+                              flags = 'l',
+                              input = path)
+        if not ret:
+            self.list.LoadData()
+            self.btn_run.Enable(False)
+            return
             
-            for line in ret.splitlines():
-                layerId = line.split(':')[0].split(' ')[1]
-                layerName = line.split(':')[1].strip()
-                grassName = utils.GetValidLayerName(layerName)
-                data.append((layerId, layerName.strip(), grassName.strip()))
+        for line in ret.splitlines():
+            layerId = line.split(':')[0].split(' ')[1]
+            layerName = line.split(':')[1].strip()
+            grassName = utils.GetValidLayerName(layerName)
+            data.append((layerId, layerName.strip(), grassName.strip()))
         
-        else: # gdal/ogr (for ogr maybe to use v.in.ogr -l)
-            layerId = 1
-            if self.format.GetStringSelection() == 'PostgreSQL':
-                dsn = 'PG:dbname=%s' % self.input[self.inputType][1].GetStringSelection()
-            else:
-                dsn = self.input[self.inputType][1].GetValue()
-            if self.inputType == 'file':
-                baseName = os.path.basename(dsn)
-                grassName = utils.GetValidLayerName(baseName.split('.', -1)[0])
-                data.append((layerId, baseName, grassName))
-            elif self.inputType == 'dir':
-                try:
-                    ext = self.format.GetExtension(self.format.GetStringSelection())
-                except KeyError:
-                    ext = ''
-                for file in glob.glob(os.path.join(dsn, "*.%s") % ext):
-                    baseName = os.path.basename(file)
-                    grassName = utils.GetValidLayerName(baseName.split('.', -1)[0])
-                    data.append((layerId, baseName, grassName))
-                    layerId += 1
-            elif self.inputType == 'db':
-                ret = gcmd.RunCommand('v.in.ogr',
-                                      quiet = True,
-                                      parent = self,
-                                      read = True,
-                                      flags = 'l',
-                                      dsn = dsn)
-                if not ret:
-                    self.list.LoadData()
-                    self.btn_run.Enable(False)
-                    return
-                layerId = 1
-                for line in ret.split(','):
-                    layerName = line.strip()
-                    grassName = utils.GetValidLayerName(layerName)
-                    data.append((layerId, layerName.strip(), grassName.strip()))
-                    layerId += 1
-        
         self.list.LoadData(data)
         if len(data) > 0:
             self.btn_run.Enable(True)

Modified: grass/branches/develbranch_6/gui/wxpython/gui_modules/gselect.py
===================================================================
--- grass/branches/develbranch_6/gui/wxpython/gui_modules/gselect.py	2010-04-26 16:41:52 UTC (rev 42032)
+++ grass/branches/develbranch_6/gui/wxpython/gui_modules/gselect.py	2010-04-26 17:07:10 UTC (rev 42033)
@@ -16,7 +16,8 @@
  - MapsetSelect
  - SubGroupSelect
  - FormatSelect
-
+ - GdalSelect
+ 
 (C) 2007-2010 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.
@@ -27,9 +28,11 @@
 
 import os
 import sys
+import glob
 
 import wx
 import wx.combo
+import wx.lib.filebrowsebutton as filebrowse
 
 import globalvar
 
@@ -765,18 +768,24 @@
         self.SetValue('')
 
 class FormatSelect(wx.Choice):
-    def __init__(self, parent, ftype, sourceType = None, id = wx.ID_ANY, size = globalvar.DIALOG_COMBOBOX_SIZE, 
+    def __init__(self, parent, ogr = False,
+                 sourceType = None, id = wx.ID_ANY, size = globalvar.DIALOG_COMBOBOX_SIZE, 
                  **kwargs):
         """!Widget for selecting external (GDAL/OGR) format
 
         @param parent parent window
         @param sourceType source type ('file', 'directory', 'database', 'protocol') or None
-        @param dataType data type ('gdal' or 'ogr')
+        @param ogr True for OGR otherwise GDAL
         """
         super(FormatSelect, self).__init__(parent, id, size = size, 
                                            style = wx.CB_READONLY, **kwargs)
         self.SetName("FormatSelect")
-
+        
+        if ogr:
+            ftype = 'ogr'
+        else:
+            ftype = 'gdal'
+        
         formats = list()
         for f in globalvar.formats[ftype].values():
             formats += f
@@ -853,3 +862,347 @@
         except KeyError:
             return ''
         
+class GdalSelect(wx.Panel):
+    def __init__(self, parent, panel, ogr = False,
+                 defSource = 'file',
+                 sources = [_("File"), _("Directory"),
+                            _("Database"), _("Protocol")],
+                 envHandler = None):
+        """!Widget for selecting GDAL/OGR datasource, format
+        
+        @param parent parent window
+        @param ogr    use OGR selector instead of GDAL
+        """
+        self.parent = parent
+        wx.Panel.__init__(self, parent = panel, id = wx.ID_ANY)
+        
+        self.inputBox = wx.StaticBox(parent = self, id=wx.ID_ANY,
+                                     label=" %s " % _("Source name"))
+        
+        # source type
+        self.source = wx.RadioBox(parent = self, id = wx.ID_ANY,
+                                  label = _('Source type'),
+                                  style = wx.RA_SPECIFY_COLS,
+                                  choices = sources)
+        self.source.SetSelection(0)
+        self.source.Bind(wx.EVT_RADIOBOX, self.OnSetType)
+        
+        # dsn widgets
+        if not ogr:
+            filemask = 'GeoTIFF (*.tif)|*.tif'
+        else:
+            filemask = 'ESRI Shapefile (*.shp)|*.shp'
+        
+        dsnFile = filebrowse.FileBrowseButton(parent=self, id=wx.ID_ANY, 
+                                              size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
+                                              dialogTitle=_('Choose input file'),
+                                              buttonText=_('Browse'),
+                                              startDirectory=os.getcwd(),
+                                              changeCallback=self.OnSetDsn,
+                                              fileMask=filemask)
+        dsnFile.Hide()
+        
+        dsnDir = filebrowse.DirBrowseButton(parent=self, id=wx.ID_ANY, 
+                                            size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
+                                            dialogTitle=_('Choose input directory'),
+                                            buttonText=_('Browse'),
+                                            startDirectory=os.getcwd(),
+                                            changeCallback=self.OnSetDsn)
+        dsnDir.Hide()
+        
+        dsnDbFile = filebrowse.FileBrowseButton(parent=self, id=wx.ID_ANY, 
+                                                size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
+                                                  dialogTitle=_('Choose file'),
+                                                buttonText=_('Browse'),
+                                                startDirectory=os.getcwd(),
+                                                changeCallback=self.OnSetDsn)
+        dsnDbFile.Hide()
+        
+        dsnDbText = wx.TextCtrl(parent = self, id = wx.ID_ANY)
+        dsnDbText.Hide()
+        dsnDbText.Bind(wx.EVT_TEXT, self.OnSetDsn)
+        
+        dsnDbChoice = wx.Choice(parent = self, id = wx.ID_ANY)
+        dsnDbChoice.Hide()
+        dsnDbChoice.Bind(wx.EVT_CHOICE, self.OnSetDsn)
+        
+        dsnPro = wx.TextCtrl(parent = self, id = wx.ID_ANY)
+        dsnPro.Hide()
+        dsnPro.Bind(wx.EVT_TEXT, self.OnSetDsn)
+
+        # format
+        self.format = FormatSelect(parent = self,
+                                   ogr = ogr)
+        self.format.Bind(wx.EVT_CHOICE, self.OnSetFormat)
+        
+        if ogr:
+            fType = 'ogr'
+        else:
+            fType = 'gdal'
+        self.input = { 'file' : [_("File:"),
+                                 dsnFile,
+                                 globalvar.formats[fType]['file']],
+                       'dir'  : [_("Directory:"),
+                                 dsnDir,
+                                 globalvar.formats[fType]['file']],
+                       'db'   : [_("Database:"),
+                                 dsnDbFile,
+                                 globalvar.formats[fType]['database']],
+                       'pro'  : [_("Protocol:"),
+                                 dsnPro,
+                                 globalvar.formats[fType]['protocol']],
+                       'db-win' : { 'file'   : dsnDbFile,
+                                    'text'   : dsnDbText,
+                                    'choice' : dsnDbChoice },
+                       }
+        
+        self.dsnType = defSource
+        self.input[self.dsnType][1].Show()
+        self.format.SetItems(self.input[self.dsnType][2])
+        
+        if not ogr:
+            self.format.SetStringSelection('GeoTIFF')
+        else:
+            self.format.SetStringSelection('ESRI Shapefile')
+        
+        self.dsnText = wx.StaticText(parent = self, id = wx.ID_ANY,
+                                     label = self.input[self.dsnType][0],
+                                     size = (75, -1))
+        self.formatText = wx.StaticText(parent = self, id = wx.ID_ANY,
+                                        label = _("Format:"))
+        self._layout()
+        
+    def _layout(self):
+        """!Layout"""
+        mainSizer = wx.BoxSizer(wx.VERTICAL)
+        inputSizer = wx.StaticBoxSizer(self.inputBox, wx.HORIZONTAL)
+        
+        self.dsnSizer = wx.GridBagSizer(vgap=3, hgap=3)
+        self.dsnSizer.AddGrowableCol(1)
+        
+        self.dsnSizer.Add(item=self.dsnText,
+                          flag=wx.ALIGN_CENTER_VERTICAL,
+                          pos = (0, 0))
+        self.dsnSizer.Add(item=self.input[self.dsnType][1],
+                          flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+                          pos = (0, 1))
+        
+        self.dsnSizer.Add(item=self.formatText,
+                          flag=wx.ALIGN_CENTER_VERTICAL,
+                          pos = (1, 0))
+        self.dsnSizer.Add(item=self.format,
+                          pos = (1, 1))
+        
+        inputSizer.Add(item=self.dsnSizer, proportion=1,
+                       flag=wx.EXPAND | wx.ALL)
+        
+        mainSizer.Add(item=self.source, proportion=0,
+                      flag=wx.ALL | wx.EXPAND, border=5)
+        mainSizer.Add(item=inputSizer, proportion=0,
+                      flag=wx.ALL | wx.EXPAND, border=5)
+        
+        self.SetSizer(mainSizer)
+        mainSizer.Fit(self)
+        
+    def OnSetType(self, event):
+        """!Datasource type changed"""
+        sel = event.GetSelection()
+        win = self.input[self.dsnType][1]
+        self.dsnSizer.Remove(win)
+        win.Hide()
+        
+        if sel == 0:   # file
+            self.dsnType = 'file'
+            format = self.input[self.dsnType][2][0]
+            try:
+                ext = self.format.GetExtension(format)
+                if not ext:
+                    raise KeyError
+                format += ' (*.%s)|*.%s' % (ext, ext)
+            except KeyError:
+                format += ' (*.*)|*.*'
+            
+            win = filebrowse.FileBrowseButton(parent=self, id=wx.ID_ANY, 
+                                              size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
+                                              dialogTitle=_('Choose input file'),
+                                              buttonText=_('Browse'),
+                                              startDirectory=os.getcwd(),
+                                              changeCallback=self.OnSetDsn,
+                                              fileMask = format)
+            self.input[self.dsnType][1] = win
+        elif sel == 1: # directory
+            self.dsnType = 'dir'
+        elif sel == 2: # database
+            self.dsnType = 'db'
+        elif sel == 3: # protocol
+            self.dsnType = 'pro'
+            
+        # if self.importType != 'dxf':
+        #     self.dsnSizer.Add(item=self.formatText,
+        #                   flag=wx.ALIGN_CENTER_VERTICAL)
+
+        win = self.input[self.dsnType][1]
+        self.dsnSizer.Add(item=self.input[self.dsnType][1],
+                          flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+                          pos = (0, 1))
+        win.SetValue('')
+        if self.parent.GetName() == 'MultiImportDialog':
+            self.parent.list.DeleteAllItems()
+        win.Show()
+        
+        self.dsnText.SetLabel(self.input[self.dsnType][0])
+        self.format.SetItems(self.input[self.dsnType][2])
+        self.format.SetSelection(0)
+        
+        self.dsnSizer.Layout()
+        
+    def OnSetDsn(self, event):
+        """!Input DXF file/OGR dsn defined, update list of layer widget"""
+        path = event.GetString()
+        if not path:
+            return 
+
+        data = list()        
+        # if self.importType == 'dxf':
+        #     ret = gcmd.RunCommand('v.in.dxf',
+        #                           quiet = True,
+        #                           parent = self,
+        #                           read = True,
+        #                           flags = 'l',
+        #                           input = path)
+        #     if not ret:
+        #         self.list.LoadData()
+        #         self.btn_run.Enable(False)
+        #         return
+            
+        #     for line in ret.splitlines():
+        #         layerId = line.split(':')[0].split(' ')[1]
+        #         layerName = line.split(':')[1].strip()
+        #         grassName = utils.GetValidLayerName(layerName)
+        #         data.append((layerId, layerName.strip(), grassName.strip()))
+        
+        layerId = 1
+        if self.format.GetStringSelection() == 'PostgreSQL':
+            dsn = 'PG:dbname=%s' % self.input[self.dsnType][1].GetStringSelection()
+        else:
+            dsn = self.input[self.dsnType][1].GetValue()
+        if self.dsnType == 'file':
+            baseName = os.path.basename(dsn)
+            grassName = utils.GetValidLayerName(baseName.split('.', -1)[0])
+            data.append((layerId, baseName, grassName))
+        elif self.dsnType == 'dir':
+            try:
+                ext = self.format.GetExtension(self.format.GetStringSelection())
+            except KeyError:
+                ext = ''
+            for file in glob.glob(os.path.join(dsn, "*.%s") % ext):
+                baseName = os.path.basename(file)
+                grassName = utils.GetValidLayerName(baseName.split('.', -1)[0])
+                data.append((layerId, baseName, grassName))
+                layerId += 1
+        elif self.dsnType == 'db':
+            ret = gcmd.RunCommand('v.in.ogr',
+                                  quiet = True,
+                                  parent = self,
+                                  read = True,
+                                  flags = 'l',
+                                  dsn = dsn)
+            if not ret:
+                self.list.LoadData()
+                self.btn_run.Enable(False)
+                return
+            layerId = 1
+            for line in ret.splitlines():
+                layerName = line.strip()
+                grassName = utils.GetValidLayerName(layerName)
+                data.append((layerId, layerName.strip(), grassName.strip()))
+                layerId += 1
+        
+        if self.parent.GetName() == 'MultiImportDialog':
+            self.parent.list.LoadData(data)
+            if len(data) > 0:
+                self.parent.btn_run.Enable(True)
+            else:
+                self.parent.btn_run.Enable(False)
+        
+    def OnSetFormat(self, event):
+        """!Format changed"""
+        if self.dsnType not in ['file', 'db']:
+            return
+        
+        win = self.input[self.dsnType][1]
+        self.dsnSizer.Remove(win)
+        
+        if self.dsnType == 'file':
+            win.Destroy()
+        else: # database
+            win.Hide()
+        
+        format = event.GetString()
+        
+        if self.dsnType == 'file':
+            try:
+                ext = self.format.GetExtension(format)
+                if not ext:
+                    raise KeyError
+                format += ' (*.%s)|*.%s' % (ext, ext)
+            except KeyError:
+                format += ' (*.*)|*.*'
+            
+            win = filebrowse.FileBrowseButton(parent=self, id=wx.ID_ANY, 
+                                              size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
+                                              dialogTitle=_('Choose file'),
+                                              buttonText=_('Browse'),
+                                              startDirectory=os.getcwd(),
+                                              changeCallback=self.OnSetDsn,
+                                              fileMask = format)
+        else: # database
+            if format == 'SQLite':
+                win = self.input['db-win']['file']
+            elif format == 'PostgreSQL':
+                if grass.find_program('psql'):
+                    win = self.input['db-win']['choice']
+                    if not win.GetItems():
+                        p = grass.Popen(['psql', '-ltA'], stdout = grass.PIPE)
+                        ret = p.communicate()[0]
+                        if ret:
+                            db = list()
+                            for line in ret.splitlines():
+                                sline = line.split('|')
+                                if len(sline) < 2:
+                                    continue
+                                dbname = sline[0]
+                                if dbname:
+                                    db.append(dbname)
+                            win.SetItems(db)
+                else:
+                    win = self.input['db-win']['text']
+            else:
+                win = self.input['db-win']['text']
+        
+        self.input[self.dsnType][1] = win
+        if not win.IsShown():
+            win.Show()
+        self.dsnSizer.Add(item=self.input[self.dsnType][1],
+                          flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+                          pos = (0, 1))
+        self.dsnSizer.Layout()
+
+    def GetType(self):
+        """!Get source type"""
+        return self.dsnType
+
+    def GetDsn(self):
+        """!Get DSN"""
+        if self.format.GetStringSelection() == 'PostgreSQL':
+            return 'PG:dbname=%s' % self.input[self.dsnType][1].GetStringSelection()
+        
+        return self.input[self.dsnType][1].GetValue()
+
+    def SetDsnHandler(self):
+        """!Get DSN"""
+        
+    def GetFormatExt(self):
+        """!Get format extension"""
+        return self.format.GetExtension(self.format.GetStringSelection())
+    

Modified: grass/branches/develbranch_6/gui/wxpython/wxgui.py
===================================================================
--- grass/branches/develbranch_6/gui/wxpython/wxgui.py	2010-04-26 16:41:52 UTC (rev 42032)
+++ grass/branches/develbranch_6/gui/wxpython/wxgui.py	2010-04-26 17:07:10 UTC (rev 42033)
@@ -1083,34 +1083,27 @@
 
     def OnImportDxfFile(self, event):
         """!Convert multiple DXF layers to GRASS vector map layers"""
-        dlg = gdialogs.MultiImportDialog(parent=self, type='dxf',
-                                         title=_("Import DXF layers"))
+        dlg = gdialogs.DxfImportDialog(parent=self)
         dlg.ShowModal()
 
     def OnImportGdalLayers(self, event):
         """!Convert multiple GDAL layers to GRASS raster map layers"""
-        dlg = gdialogs.MultiImportDialog(parent=self, type='gdal',
-                                         title=_("Import raster data"))
+        dlg = gdialogs.GdalImportDialog(parent=self)
         dlg.ShowModal()
 
     def OnLinkGdalLayers(self, event):
         """!Link multiple GDAL layers to GRASS raster map layers"""
-        dlg = gdialogs.MultiImportDialog(parent=self, type='gdal',
-                                         title=_("Link raster data"),
-                                         link = True)
+        dlg = gdialogs.GdalImportDialog(parent=self, link = True)
         dlg.ShowModal()
         
     def OnImportOgrLayers(self, event):
         """!Convert multiple OGR layers to GRASS vector map layers"""
-        dlg = gdialogs.MultiImportDialog(parent=self, type='ogr',
-                                         title=_("Import vector data"))
+        dlg = gdialogs.GdalImportDialog(parent=self, ogr = True)
         dlg.ShowModal()
-    
+        
     def OnLinkOgrLayers(self, event):
         """!Links multiple OGR layers to GRASS vector map layers"""
-        dlg = gdialogs.MultiImportDialog(parent=self, type='ogr',
-                                         title=_("Link vector data"),
-                                         link = True)
+        dlg = gdialogs.GdalImportDialog(parent=self, ogr = True, link = True)
         dlg.ShowModal()
         
     def OnImportWMS(self, event):



More information about the grass-commit mailing list