GdalTools_utils.py

Rhenriques Henriques, 2014-03-06 03:04 PM

Download (27.9 KB)

 
1
# -*- coding: utf-8 -*-
2

    
3
"""
4
***************************************************************************
5
    GdalTools_utils.py
6
    ---------------------
7
    Date                 : June 2010
8
    Copyright            : (C) 2010 by Giuseppe Sucameli
9
    Email                : brush dot tyler at gmail dot com
10
***************************************************************************
11
*                                                                         *
12
*   This program is free software; you can redistribute it and/or modify  *
13
*   it under the terms of the GNU General Public License as published by  *
14
*   the Free Software Foundation; either version 2 of the License, or     *
15
*   (at your option) any later version.                                   *
16
*                                                                         *
17
***************************************************************************
18
"""
19

    
20
__author__ = 'Giuseppe Sucameli'
21
__date__ = 'June 2010'
22
__copyright__ = '(C) 2010, Giuseppe Sucameli'
23
# This will get replaced with a git SHA1 when you do a git archive
24
__revision__ = '$Format:%H$'
25

    
26
# Utility functions
27
# -------------------------------------------------
28
# getLastUsedDir()
29
# setLastUsedDir( QString *file_or_dir path )
30
# -------------------------------------------------
31

    
32
from PyQt4.QtCore import *
33
from PyQt4.QtGui import *
34

    
35
from qgis.core import *
36
from qgis.gui import *
37

    
38
from osgeo import gdal, ogr, osr
39
from osgeo.gdalconst import *
40

    
41
import os
42
# to know the os
43
import platform
44
import sys
45
import string
46
import re
47

    
48
# Escapes arguments and return them joined in a string
49
def escapeAndJoin(strList):
50
    joined = ''
51
    for s in strList:
52
      if s.find(" ") is not -1:
53
        escaped = '"' + s.replace('\\', '\\\\').replace('"', '\\"') + '"'
54
      else:
55
        escaped = s
56
      joined += escaped + " "
57
    return joined.strip()
58

    
59
# Retrieves last used dir from persistent settings
60
def getLastUsedDir():
61
    settings = QSettings()
62
    lastProjectDir = settings.value( "/UI/lastProjectDir", ".", type=str )
63
    return settings.value( "/GdalTools/lastUsedDir", lastProjectDir, type=str )
64

    
65
# Stores last used dir in persistent settings
66
def setLastUsedDir(filePath):
67
    settings = QSettings()
68
    fileInfo = QFileInfo(filePath)
69
    if fileInfo.isDir():
70
      dirPath = fileInfo.filePath()
71
    else:
72
      dirPath = fileInfo.path()
73
    settings.setValue( "/GdalTools/lastUsedDir", dirPath )
74

    
75
# Retrieves GDAL binaries location
76
def getGdalBinPath():
77
  settings = QSettings()
78
  return settings.value( "/GdalTools/gdalPath", u"" )
79

    
80
# Stores GDAL binaries location
81
def setGdalBinPath( path ):
82
  settings = QSettings()
83
  settings.setValue( "/GdalTools/gdalPath", path )
84

    
85
# Retrieves GDAL python modules location
86
def getGdalPymodPath():
87
  settings = QSettings()
88
  return settings.value( "/GdalTools/gdalPymodPath", u"" )
89

    
90
# Stores GDAL python modules location
91
def setGdalPymodPath( path ):
92
  settings = QSettings()
93
  settings.setValue( "/GdalTools/gdalPymodPath", path )
94

    
95
# Retrieves GDAL help files location
96
def getHelpPath():
97
  settings = QSettings()
98
  return settings.value( "/GdalTools/helpPath", u"" )
99

    
100
# Stores GDAL help files location
101
def setHelpPath( path ):
102
  settings = QSettings()
103
  settings.setValue( "/GdalTools/helpPath", path )
104

    
105
# Retrieves last used encoding from persistent settings
106
def getLastUsedEncoding():
107
    settings = QSettings()
108
    return settings.value( "/UI/encoding", u"System" )
109

    
110
# Stores last used encoding in persistent settings
111
def setLastUsedEncoding(encoding):
112
    settings = QSettings()
113
    settings.setValue( "/UI/encoding", encoding)
114

    
115
def getRasterExtensions():
116
  formats = FileFilter.allRastersFilter().split( ";;" )
117
  extensions = []
118
  for f in formats:
119
    if string.find(f, "*.bt" ) is not -1 or string.find(f, "*.mpr" ) is not -1:   # Binary Terrain or ILWIS
120
      continue
121
    extensions.extend( FileFilter.getFilterExtensions( f ) )
122
  return extensions
123

    
124
def getVectorExtensions():
125
  formats = FileFilter.allVectorsFilter().split( ";;" )
126
  extensions = []
127
  for f in formats:
128
    extensions.extend( FileFilter.getFilterExtensions( f ) )
129
  return extensions
130

    
131
class LayerRegistry(QObject):
132

    
133
    _instance = None
134
    _iface = None
135

    
136
    @staticmethod
137
    def instance():
138
      if LayerRegistry._instance == None:
139
        LayerRegistry._instance = LayerRegistry()
140
      return LayerRegistry._instance
141

    
142
    @staticmethod
143
    def setIface(iface):
144
      LayerRegistry._iface = iface
145

    
146
    layers = []
147

    
148
    def __init__(self):
149
      QObject.__init__(self)
150
      if LayerRegistry._instance != None:
151
        return
152

    
153
      LayerRegistry.layers = self.getAllLayers()
154
      LayerRegistry._instance = self
155
      self.connect(QgsMapLayerRegistry.instance(), SIGNAL("removeAll()"), self.removeAllLayers)
156
      self.connect(QgsMapLayerRegistry.instance(), SIGNAL("layerWasAdded(QgsMapLayer *)"), self.layerAdded)
157
      self.connect(QgsMapLayerRegistry.instance(), SIGNAL("layerWillBeRemoved(QString)"), self.removeLayer)
158

    
159
    def getAllLayers(self):
160
       if LayerRegistry._iface and hasattr(LayerRegistry._iface, 'legendInterface'):
161
         return LayerRegistry._iface.legendInterface().layers()
162
       return QgsMapLayerRegistry.instance().mapLayers().values()
163

    
164
    def layerAdded(self, layer):
165
       LayerRegistry.layers.append( layer )
166
       self.emit( SIGNAL( "layersChanged" ) )
167

    
168
    def removeLayer(self, layerId):
169
       LayerRegistry.layers = filter( lambda x: x.id() != layerId, LayerRegistry.layers)
170
       self.emit( SIGNAL( "layersChanged" ) )
171

    
172
    def removeAllLayers(self):
173
       LayerRegistry.layers = []
174
       self.emit( SIGNAL( "layersChanged" ) )
175

    
176
    @classmethod
177
    def isRaster(self, layer):
178
      # only gdal raster layers
179
      if layer.type() != layer.RasterLayer:
180
        return False
181
      if layer.providerType() != 'gdal':
182
        return False
183
      return True
184

    
185
    def getRasterLayers(self):
186
      return filter( self.isRaster, LayerRegistry.layers )
187

    
188
    @classmethod
189
    def isVector(self, layer):
190
      if layer.type() != layer.VectorLayer:
191
        return False
192
      if layer.providerType() != 'ogr':
193
        return False
194
      return True
195

    
196
    def getVectorLayers(self):
197
      return filter( self.isVector, LayerRegistry.layers )
198

    
199
def getRasterFiles(path, recursive=False):
200
  rasters = []
201
  if not QFileInfo(path).exists():
202
    return rasters
203

    
204
  # TODO remove *.aux.xml
205
  _filter = getRasterExtensions()
206
  workDir = QDir( path )
207
  workDir.setFilter( QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot )
208
  workDir.setNameFilters( _filter )
209
  files = workDir.entryList()
210
  for f in files:
211
    rasters.append( path + "/" + f )
212

    
213
  if recursive:
214
    for myRoot, myDirs, myFiles in os.walk( unicode(path) ):
215
      for dir in myDirs:
216
        workDir = QDir( myRoot + "/" + dir )
217
        workDir.setFilter( QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot )
218
        workDir.setNameFilters( _filter )
219
        workFiles = workDir.entryList()
220
        for f in workFiles:
221
          rasters.append( myRoot + "/" + dir + "/" + f )
222

    
223
  return rasters
224

    
225
def fillRasterOutputFormat(aFilter = None, filename = None):
226
  shortName = ''
227

    
228
  if aFilter != None:
229
    supportedRasters = GdalConfig.getSupportedRasters()
230
    filterName = re.sub('^.*\] ', '', FileFilter.getFilterName( aFilter[0] ))
231
    if supportedRasters.has_key( filterName ):
232
      return supportedRasters[ filterName ][ "SHORTNAME" ]
233

    
234
    shortName = GdalConfig.SupportedRasters.long2ShortName(filterName)
235

    
236
  if shortName == '' and filename != None:
237
    shortName = GdalConfig.SupportedRasters.filename2ShortName(filename)
238

    
239
  if shortName == '':
240
    shortName = "GTiff"
241

    
242
  return shortName
243

    
244
def fillVectorOutputFormat(aFilter = None, filename = None):
245
  shortName = ''
246

    
247
  if aFilter != None:
248
    supportedVectors = GdalConfig.getSupportedVectors()
249
    filterName = re.sub('^.*\] ', '', FileFilter.getFilterName( aFilter[0] ))
250
    if supportedVectors.has_key( filterName ):
251
      return supportedVectors[ filterName ][ "SHORTNAME" ]
252

    
253
    pass #shortName = GdalConfig.SupportedVectors.long2ShortName(filterName)
254

    
255
  if shortName == '' and filename != None:
256
    pass #shortName = GdalConfig.SupportedVectors.filename2ShortName(filename)
257

    
258
  if shortName == '':
259
    shortName = "ESRI Shapefile"
260

    
261
  return shortName
262

    
263
class UnsupportedOGRFormat(Exception):
264
    def __init__(self):
265
      msg = QCoreApplication.translate( "GdalTools", "The selected file is not a supported OGR format" )
266
      Exception.__init__(self, msg)
267

    
268
def getVectorFields(vectorFile):
269
    hds = ogr.Open( unicode(vectorFile).encode('utf8') )
270
    if hds == None:
271
      raise UnsupportedOGRFormat()
272

    
273
    fields = []
274
    names = []
275

    
276
    layer = hds.GetLayer(0)
277
    defn = layer.GetLayerDefn()
278

    
279
    for i in range(defn.GetFieldCount()):
280
      fieldDefn = defn.GetFieldDefn(i)
281
      fieldType = fieldDefn.GetType()
282
      if fieldType == 0 or fieldType == 2:
283
        fields.append(fieldDefn)
284
        names.append(fieldDefn.GetName())
285

    
286
    return (fields, names)
287

    
288
# get raster SRS if possible
289
def getRasterSRS( parent, fileName ):
290
    ds = gdal.Open(fileName)
291
    if ds is None:
292
        return ''
293

    
294
    proj = ds.GetProjectionRef()
295
    if proj is None:
296
      return ''
297

    
298
    sr = osr.SpatialReference()
299
    if sr.ImportFromWkt(proj) != gdal.CE_None:
300
        return ''
301

    
302
    name = sr.GetAuthorityName(None)
303
    code = sr.GetAuthorityCode(None)
304
    if name is not None and code is not None:
305
        return '%s:%s' % (name,code)
306

    
307
    return ''
308

    
309
# get raster extent using python API - replaces old method which parsed gdalinfo output
310
def getRasterExtent(parent, fileName):
311
    ds = gdal.Open(fileName)
312
    if ds is None:
313
        return
314

    
315
    x = ds.RasterXSize
316
    y = ds.RasterYSize
317

    
318
    gt = ds.GetGeoTransform()
319
    if gt is None:
320
        xUL = 0
321
        yUL = 0
322
        xLR = x
323
        yLR = y
324
    else:
325
        xUL = gt[0]
326
        yUL = gt[3]
327
        xLR = gt[0] + gt[1]*x + gt[2]*y
328
        yLR = gt[3] + gt[4]*x + gt[5]*y
329

    
330
    return QgsRectangle( xUL, yLR, xLR, yUL )
331

    
332

    
333
# This class is used to replace the QFileDialog class.
334
# Its static methods are used in place of the respective QFileDialog ones to:
335
# 1. set the last used directory
336
# 2. append the selected extension to the file name
337
# 3. bypass the following bug:
338
# when you use the 'filter' argument, the dialog is enlarged up to the longest filter length,
339
# so sometimes the dialog excedes the screen width
340
class FileDialog:
341
  @classmethod
342
  def getDialog(self, parent = None, caption = '', acceptMode = QFileDialog.AcceptOpen, fileMode = QFileDialog.ExistingFile, filter = '', selectedFilter = None, useEncoding = False):
343
    if useEncoding:
344
      dialog = QgsEncodingFileDialog(parent, caption, getLastUsedDir(), filter, getLastUsedEncoding())
345
    else:
346
      dialog = QFileDialog(parent, caption, getLastUsedDir(), filter)
347
    dialog.setFileMode(fileMode)
348
    dialog.setAcceptMode(acceptMode)
349

    
350
    if selectedFilter is not None:
351
      dialog.selectNameFilter(selectedFilter[0])
352

    
353
    if not dialog.exec_():
354
      if useEncoding:
355
        return ('', None)
356
      return ''
357

    
358
    # change the selected filter value
359
    if selectedFilter is not None:
360
      selectedFilter[0] = dialog.selectedNameFilter()
361

    
362
    # save the last used dir and return the selected files
363
    files = dialog.selectedFiles()
364
    if files != '':
365
      setLastUsedDir(files[0])
366

    
367
      if fileMode != QFileDialog.ExistingFiles:
368
        files = files[0]
369
        # append the extension if not already present
370
        if fileMode == QFileDialog.AnyFile:
371
          firstExt = None
372
          for ext in FileFilter.getFilterExtensions(dialog.selectedNameFilter()):
373
            if FileFilter.filenameMatchesFilterExt(files, ext):
374
              firstExt = None
375
              break
376

    
377
            if firstExt == None:
378
              firstExt = ext
379

    
380
          if firstExt != None:
381
            if firstExt.startswith('*'):
382
              files += firstExt[1:]
383

    
384
    if useEncoding:
385
      encoding = dialog.encoding()
386
      # encoding setted yet by QgsEncodingFileDialog
387
      #setLastUsedEncoding(encoding)
388
      return (files, encoding)
389

    
390
    return files
391

    
392
  @classmethod
393
  def getOpenFileNames(self, parent = None, caption = '', filter = '', selectedFilter = None, useEncoding = False):
394
    return self.getDialog(parent, caption, QFileDialog.AcceptOpen, QFileDialog.ExistingFiles, filter, selectedFilter, useEncoding)
395

    
396
  @classmethod
397
  def getOpenFileName(self, parent = None, caption = '', filter = '', selectedFilter = None, useEncoding = False):
398
    return self.getDialog(parent, caption, QFileDialog.AcceptOpen, QFileDialog.ExistingFile, filter, selectedFilter, useEncoding)
399

    
400
  @classmethod
401
  def getSaveFileName(self, parent = None, caption = '', filter = '', selectedFilter = None, useEncoding = False):
402
    return self.getDialog(parent, caption, QFileDialog.AcceptSave, QFileDialog.AnyFile, filter, selectedFilter, useEncoding)
403

    
404
  @classmethod
405
  def getExistingDirectory(self, parent = None, caption = '', useEncoding = False):
406
    return self.getDialog(parent, caption, QFileDialog.AcceptOpen, QFileDialog.DirectoryOnly, '', None, useEncoding)
407

    
408
class FileFilter:
409
  @classmethod
410
  def getFilter(self, typeName):
411
      settings = QSettings()
412
      return settings.value( "/GdalTools/" + typeName + "FileFilter", u"", type=str )  # add ', type=str'
413

    
414
  @classmethod
415
  def setFilter(self, typeName, aFilter):
416
      settings = QSettings()
417
      settings.setValue( "/GdalTools/" + typeName + "FileFilter", aFilter )
418

    
419
  # stores the supported raster file filter
420
  rastersFilter = ''
421

    
422
  # Retrieves the filter for supported raster files
423
  @classmethod
424
  def allRastersFilter(self):
425
    if self.rastersFilter == '':
426
      self.rastersFilter = QgsProviderRegistry.instance().fileRasterFilters()
427

    
428
      # workaround for QGis < 1.5 (see #2376)
429
      # removed as this is a core plugin QGis >= 1.9
430

    
431
    return self.rastersFilter
432

    
433
  # Retrieves the last used filter for raster files
434
  # Note: filter string is in a list
435
  @classmethod
436
  def lastUsedRasterFilter(self):
437
     return [self.getFilter("lastRaster")]
438

    
439
  @classmethod
440
  def setLastUsedRasterFilter(self, aFilter):
441
     self.setFilter("lastRaster", aFilter[0])
442

    
443
  # stores the supported vectors file filter
444
  vectorsFilter = ''
445

    
446
  # Retrieves the filter for supported vector files
447
  @classmethod
448
  def allVectorsFilter(self):
449
    if self.vectorsFilter == '':
450
      self.vectorsFilter = QgsProviderRegistry.instance().fileVectorFilters()
451
    return self.vectorsFilter
452

    
453
  # Retrieves the last used filter for vector files
454
  # Note: filter string is in a list
455
  @classmethod
456
  def lastUsedVectorFilter(self):
457
     return [self.getFilter("lastVector")]
458

    
459
  @classmethod
460
  def setLastUsedVectorFilter(self, aFilter):
461
     self.setFilter("lastVector", aFilter[0])
462

    
463
  # Retrieves the extensions list from a filter string
464
  @classmethod
465
  def getFilterExtensions(self, aFilter):
466
    extList = []
467
    # foreach format in filter string
468
    for f in aFilter.split( ";;" ):
469
      # gets the list of extensions from the filter
470
      exts = re.sub('\).*$', '', re.sub('^.*\(', '', f))
471
      # if there is no extensions or the filter matches all, then return an empty list
472
      # otherwise return the list of estensions
473
      if exts != '' and exts != "*" and exts != "*.*":
474
        extList.extend(exts.split(" "))
475
    return extList
476

    
477
  @classmethod
478
  def getFilterName(self, aFilter):
479
    return string.strip(re.sub('\ \(.*$', '', aFilter))
480

    
481
  @classmethod
482
  def filenameMatchesFilterExt(self, fileName, ext):
483
    return re.match( '.'+str(ext), fileName ) is not None
484

    
485
# Retrieves gdal information
486
class GdalConfig:
487
  # retrieves and return the installed gdal version
488
  @classmethod
489
  def version(self):
490
      return Version(gdal.VersionInfo("RELEASE_NAME"))
491

    
492
  @classmethod
493
  def versionNum(self):
494
      return int(gdal.VersionInfo("VERSION_NUM"))
495

    
496
  # store the supported rasters info
497
  supportedRasters = None
498

    
499
  # retrieve the supported rasters info
500
  @classmethod
501
  def getSupportedRasters(self):
502
    if self.supportedRasters != None:
503
      return self.supportedRasters
504

    
505
    # first get the GDAL driver manager
506
    if gdal.GetDriverCount() == 0:
507
      gdal.AllRegister()
508

    
509
    self.supportedRasters = dict()
510
    jp2Driver = None
511

    
512
    # for each loaded GDAL driver
513
    for i in range(gdal.GetDriverCount()):
514
      driver = gdal.GetDriver(i)
515

    
516
      if driver == None:
517
        QgsLogger.warning("unable to get driver " + str(i))
518
        continue
519

    
520
      # now we need to see if the driver is for something currently
521
      # supported; if not, we give it a miss for the next driver
522

    
523
      longName = string.strip(re.sub('\(.*$', '', driver.LongName))
524
      shortName = string.strip(re.sub('\(.*$', '', driver.ShortName))
525
      extensions = ''
526

    
527
      description = driver.GetDescription()
528
      glob = []
529

    
530
      metadata = driver.GetMetadata()
531
      if metadata.has_key(gdal.DMD_EXTENSION):
532
        extensions = str(metadata[gdal.DMD_EXTENSION])
533

    
534
      if longName != '':
535
        if extensions != '':
536
          # XXX add check for SDTS; in that case we want (*CATD.DDF)
537

    
538
          #TODO fix and test
539
          #glob.append( QString("*." + extensions.replace("/", " *.")).split(" "))
540
          glob.append(string.split("*." + string.replace(extensions,"/", " *."), sep=(" ")))
541

    
542
          # Add only the first JP2 driver found to the filter list (it's the one GDAL uses)
543
          if description == "JPEG2000" or description.startswith("JP2"): # JP2ECW, JP2KAK, JP2MrSID
544
            if jp2Driver != None:
545
              continue               # skip if already found a JP2 driver
546
            jp2Driver = driver   # first JP2 driver found
547
            glob.append("*.j2k")           # add alternate extension
548
          elif description == "GTiff":
549
            glob.append("*.tiff")
550
          elif description == "JPEG":
551
            glob.append("*.jpeg")
552
        else:
553
          # USGS DEMs use "*.dem"
554
          if description.startswith( "USGSDEM" ):
555
            glob.append("*.dem")
556
          elif description.startswith( "DTED" ):
557
            # DTED use "*.dt0"
558
            glob.append("*.dt0")
559
          elif description.startswith( "MrSID" ):
560
            # MrSID use "*.sid"
561
            glob.append("*.sid")
562
          else:
563
            continue
564

    
565
        self.supportedRasters[longName] = {'EXTENSIONS': glob, 'LONGNAME': longName, 'SHORTNAME': shortName, 'DESCRIPTION': description}
566

    
567
    return self.supportedRasters
568

    
569
  # store the supported vectors info
570
  supportedVectors = None
571

    
572
  # retrieve the supported vectors info
573
  @classmethod
574
  def getSupportedVectors(self):
575
    if self.supportedVectors != None:
576
      return self.supportedVectors
577

    
578
    # first get the OGR driver manager
579
    QgsApplication.registerOgrDrivers()
580

    
581
    self.supportedVectors = dict()
582

    
583
    # for each loaded OGR driver
584
    for i in range(ogr.GetDriverCount()):
585
      driver = ogr.GetDriver(i)
586

    
587
      if driver == None:
588
        QgsLogger.warning("unable to get driver " + str(i))
589
        continue
590

    
591
      driverName = driver.GetName()
592
      longName = ''
593
      glob = []
594

    
595
      if driverName.startswith( "AVCBin" ):
596
        pass #myDirectoryDrivers += "Arc/Info Binary Coverage,AVCBin"
597
      elif driverName.startswith( "AVCE00" ):
598
        longName = "Arc/Info ASCII Coverage"
599
        glob.append("*.e00")
600
      elif driverName.startswith( "BNA" ):
601
        longName = "Atlas BNA"
602
        glob.append("*.bna")
603
      elif driverName.startswith( "CSV" ):
604
        longName = "Comma Separated Value"
605
        glob.append("*.csv")
606
      elif driverName.startswith( "DODS" ):
607
        pass #myProtocolDrivers += "DODS/OPeNDAP,DODS"
608
      elif driverName.startswith( "PGeo" ):
609
        pass #myDatabaseDrivers += "ESRI Personal GeoDatabase,PGeo"
610

    
611
        # on Windows add a pair to the dict for this driver
612
        if platform.system() == "Windows":
613
          longName = "ESRI Personal GeoDatabase"
614
          glob.append("*.mdb")
615
      elif driverName.startswith( "SDE" ):
616
        pass #myDatabaseDrivers += "ESRI ArcSDE,SDE"
617
      elif driverName.startswith( "ESRI" ):
618
        longName = "ESRI Shapefiles"
619
        glob.append("*.shp")
620
      elif driverName.startswith( "FMEObjects Gateway" ):
621
        longName = "FMEObjects Gateway"
622
        glob.append("*.fdd")
623
      elif driverName.startswith( "GeoJSON" ):
624
        pass #myProtocolDrivers += "GeoJSON,GeoJSON"
625
        longName = "GeoJSON"
626
        glob.append("*.geojson")
627
      elif driverName.startswith( "GeoRSS" ):
628
        longName = "GeoRSS"
629
        glob.append("*.xml")
630
      elif driverName.startswith( "GML" ):
631
        longName = "Geography Markup Language"
632
        glob.append("*.gml")
633
      elif driverName.startswith( "GMT" ):
634
        longName = "GMT"
635
        glob.append("*.gmt")
636
      elif driverName.startswith( "GPX" ):
637
        longName = "GPX"
638
        glob.append("*.gpx")
639
      elif driverName.startswith( "GRASS" ):
640
        pass #myDirectoryDrivers += "Grass Vector,GRASS"
641
      elif driverName.startswith( "IDB" ):
642
        pass #myDatabaseDrivers += "Informix DataBlade,IDB"
643
      elif driverName.startswith( "Interlis 1" ):
644
        longName = "INTERLIS 1"
645
        glob.append("*.itf")
646
        glob.append("*.xml")
647
        glob.append("*.ili")
648
      elif driverName.startswith( "Interlis 2" ):
649
        longName = "INTERLIS 2"
650
        glob.append("*.itf")
651
        glob.append("*.xml")
652
        glob.append("*.ili")
653
      elif driverName.startswith( "INGRES" ):
654
        pass #myDatabaseDrivers += "INGRES,INGRES"
655
      elif driverName.startswith( "KML" ):
656
        longName = "KML"
657
        glob.append("*.kml")
658
      elif driverName.startswith( "MapInfo File" ):
659
        longName = "Mapinfo File"
660
        glob.append("*.mif")
661
        glob.append("*.tab")
662
      elif driverName.startswith( "DGN" ):
663
        longName = "Microstation DGN"
664
        glob.append("*.dgn")
665
      elif driverName.startswith( "MySQL" ):
666
        pass #myDatabaseDrivers += "MySQL,MySQL"
667
      elif driverName.startswith( "OCI" ):
668
        pass #myDatabaseDrivers += "Oracle Spatial,OCI"
669
      elif driverName.startswith( "ODBC" ):
670
        pass #myDatabaseDrivers += "ODBC,ODBC"
671
      elif driverName.startswith( "OGDI" ):
672
        pass #myDatabaseDrivers += "OGDI Vectors,OGDI"
673
      elif driverName.startswith( "PostgreSQL" ):
674
        pass #myDatabaseDrivers += "PostgreSQL,PostgreSQL"
675
      elif driverName.startswith( "S57" ):
676
        longName = "S-57 Base file"
677
        glob.append("*.000")
678
      elif driverName.startswith( "SDTS" ):
679
        longName = "Spatial Data Transfer Standard"
680
        glob.append("*catd.ddf")
681
      elif driverName.startswith( "SQLite" ):
682
        longName = "SQLite"
683
        glob.append("*.sqlite")
684
      elif driverName.startswith( "UK .NTF" ):
685
        pass #myDirectoryDrivers += "UK. NTF,UK. NTF"
686
      elif driverName.startswith( "TIGER" ):
687
        pass #myDirectoryDrivers += "U.S. Census TIGER/Line,TIGER"
688
      elif driverName.startswith( "VRT" ):
689
        longName = "VRT - Virtual Datasource "
690
        glob.append("*.vrt")
691
      elif driverName.startswith( "XPlane" ):
692
        longName = "X-Plane/Flighgear"
693
        glob.append("apt.dat")
694
        glob.append("nav.dat")
695
        glob.append("fix.dat")
696
        glob.append("awy.dat")
697

    
698
      longName = string.strip(longName)
699

    
700
      if longName =='':
701
        continue
702

    
703
      self.supportedVectors[longName] = {'EXTENSIONS': glob, 'LONGNAME': longName, 'SHORTNAME': driverName}
704

    
705
    return self.supportedVectors
706

    
707
  class SupportedRasters:
708
    dict_long2shortName = dict()
709

    
710
    # retrieve the raster format short name by long format name
711
    @classmethod
712
    def long2ShortName(self, longName):
713
      if longName == '':
714
        return ''
715

    
716
      if self.dict_long2shortName.has_key(longName):
717
        return self.dict_long2shortName[longName]
718

    
719
      # first get the GDAL driver manager
720
      if gdal.GetDriverCount() == 0:
721
        gdal.AllRegister()
722

    
723
      shortName = ''
724

    
725
      # for each loaded GDAL driver
726
      for i in range(gdal.GetDriverCount()):
727
        driver = gdal.GetDriver(i)
728
        if driver == None:
729
          continue
730

    
731
        # if this is the driver we searched for then return its short name
732
        if FileFilter.getFilterName(driver.LongName) == longName:
733
          shortName = FileFilter.getFilterName(driver.ShortName)
734
          self.dict_long2shortName[longName] = shortName
735
          break
736

    
737
      return shortName
738

    
739
    # retrieve the raster format short name by using the file name extension
740
    @classmethod
741
    def filename2ShortName(self, fileName):
742
      if fileName == '':
743
        return ''
744

    
745
      shortName = ''
746

    
747
      # for each raster format search for the file extension
748
      formats = FileFilter.allRastersFilter().split( ";;" )
749
      for f in formats:
750
        for ext in FileFilter.getFilterExtensions(f):
751
          if FileFilter.filenameMatchesFilterExt(fileName, ext):
752
            longName = FileFilter.getFilterName(f)
753
            shortName = self.long2ShortName(longName)
754
            break
755

    
756
        if not shortName == '':
757
          break
758

    
759
      return shortName
760

    
761
# class which allows to create version objects and compare them
762
class Version:
763
  def __init__(self, ver):
764
      self.vers = ('0', '0', '0')
765

    
766
      if isinstance(ver, Version):
767
        self.vers = ver.vers
768
      elif isinstance(ver, tuple) or isinstance(ver, list):
769
        self.vers = map(str, ver)
770
      elif isinstance(ver, str):
771
        self.vers = self.string2vers(ver)
772

    
773
  @staticmethod
774
  def string2vers(string):
775
      vers = ['0', '0', '0']
776

    
777
      nums = str(string).split(".")
778

    
779
      if len(nums) > 0:
780
        vers[0] = nums[0]
781
      if len(nums) > 1:
782
        vers[1] = nums[1]
783
      if len(nums) > 2:
784
        vers[2] = nums[2]
785

    
786
      return (vers[0], vers[1], vers[2])
787

    
788
  def __cmp__(self, other):
789
      if not isinstance(other, Version):
790
        other = Version(other)
791

    
792
      if self.vers > other.vers:
793
        return 1
794
      if self.vers < other.vers:
795
        return -1
796
      return 0
797

    
798
  def __str__(self):
799
    return ".".join(self.vers)
800

    
801

    
802
def setProcessEnvironment(process):
803
    envvar_list = {
804
        "PATH" : getGdalBinPath(),
805
        "PYTHONPATH" : getGdalPymodPath(),
806
        "GDAL_FILENAME_IS_UTF8" : "NO"
807
    }
808

    
809
    sep = os.pathsep
810

    
811
    for name, val in envvar_list.iteritems():
812
      if val == None or val == "":
813
        continue
814

    
815
      envval = os.getenv(name)
816
      if envval == None or envval == "":
817
        envval = str(val)
818
      elif (platform.system() == "Windows" and val.lower() not in envval.lower().split( sep )) or \
819
          (platform.system() != "Windows" and val not in envval.split( sep )):
820
        envval += "%s%s" % (sep, str(val))
821
      else:
822
        envval = None
823

    
824
      if envval != None:
825
        os.putenv( name, envval )
826

    
827
def setMacOSXDefaultEnvironment():
828
  # fix bug #3170: many GDAL Tools don't work in OS X standalone
829

    
830
  if platform.system() != "Darwin":
831
    return
832

    
833
  # QgsApplication.prefixPath() contains the path to qgis executable (i.e. .../Qgis.app/MacOS)
834
  # get the path to Qgis application folder
835
  qgis_app = u"%s/.." % QgsApplication.prefixPath()
836
  qgis_app = QDir( qgis_app ).absolutePath()
837

    
838
  qgis_bin = u"%s/bin" % QgsApplication.prefixPath()   # path to QGis bin folder
839
  qgis_python = u"%s/Resources/python" % qgis_app    # path to QGis python folder
840

    
841
  # path to the GDAL framework within the Qgis application folder (QGis standalone only)
842
  qgis_standalone_gdal_path = u"%s/Frameworks/GDAL.framework" % qgis_app
843

    
844
  # path to the GDAL framework when installed as external framework
845
  gdal_versionsplit = str(GdalConfig.version()).split('.')
846
  gdal_base_path = u"/Library/Frameworks/GDAL.framework/Versions/%s.%s" % (gdal_versionsplit[0], gdal_versionsplit[1])
847

    
848
  if os.path.exists( qgis_standalone_gdal_path ):  # qgis standalone
849
    # GDAL executables are in the QGis bin folder
850
    if getGdalBinPath() == '':
851
      setGdalBinPath( qgis_bin )
852
    # GDAL pymods are in the QGis python folder
853
    if getGdalPymodPath() == '':
854
      setGdalPymodPath( qgis_python )
855
    # GDAL help is in the framework folder
856
    if getHelpPath() == '':
857
      setHelpPath( u"%s/Resources/doc" % qgis_standalone_gdal_path )
858

    
859
  elif os.path.exists( gdal_base_path ):
860
    # all GDAL parts are in the GDAL framework folder
861
    if getGdalBinPath() == '':
862
      setGdalBinPath( u"%s/Programs" % gdal_base_path )
863
    if getGdalPymodPath() == '':
864
      setGdalPymodPath( u"%s/Python/%s.%s/site-packages" % (gdal_base_path, sys.version_info[0], sys.version_info[1]) )
865
    if getHelpPath() == '':
866
      setHelpPath( u"%s/Resources/doc" % gdal_base_path )
867

    
868

    
869
# setup the MacOSX path to both GDAL executables and python modules
870
if platform.system() == "Darwin":
871
  setMacOSXDefaultEnvironment()
872