49 changes: 23 additions & 26 deletions python/console/console_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,12 @@
Some portions of code were taken from https://code.google.com/p/pydee/
"""

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.Qsci import (QsciScintilla,
QsciScintillaBase,
QsciLexerPython)
from PyQt4.QtCore import Qt, QCoreApplication, QSettings, SIGNAL
from PyQt4.QtGui import QColor, QGridLayout, QSpacerItem, QSizePolicy, QFont, QShortcut, QKeySequence, QMenu, QApplication
from PyQt4.Qsci import QsciScintilla, QsciLexerPython
from qgis.core import QgsApplication
from qgis.gui import QgsMessageBar
import sys
import socket

class writeOut:
def __init__(self, shellOut, out=None, style=None):
Expand Down Expand Up @@ -147,9 +144,9 @@ def insertInitText(self):
## and the first command in console will be appended at the header text.
## The following code add a '\n' at the end of the string if not present.
if txtInit.endswith('\n'):
initText = self.setText(txtInit)
self.setText(txtInit)
else:
initText = self.setText(txtInit + '\n')
self.setText(txtInit + '\n')

def refreshSettingsOutput(self):
# Set Python lexer
Expand Down Expand Up @@ -207,33 +204,33 @@ def contextMenuEvent(self, e):
iconClear = QgsApplication.getThemeIcon("console/iconClearConsole.png")
iconHideTool = QgsApplication.getThemeIcon("console/iconHideToolConsole.png")
iconSettings = QgsApplication.getThemeIcon("console/iconSettingsConsole.png")
hideToolBar = menu.addAction(iconHideTool,
QCoreApplication.translate("PythonConsole", "Hide/Show Toolbar"),
self.hideToolBar)
menu.addAction(iconHideTool,
QCoreApplication.translate("PythonConsole", "Hide/Show Toolbar"),
self.hideToolBar)
menu.addSeparator()
showEditorAction = menu.addAction(
QCoreApplication.translate("PythonConsole", "Show Editor"),
self.showEditor)
QCoreApplication.translate("PythonConsole", "Show Editor"),
self.showEditor)
menu.addSeparator()
runAction = menu.addAction(iconRun,
QCoreApplication.translate("PythonConsole", "Enter Selected"),
self.enteredSelected,
QKeySequence(Qt.CTRL + Qt.Key_E))
QCoreApplication.translate("PythonConsole", "Enter Selected"),
self.enteredSelected,
QKeySequence(Qt.CTRL + Qt.Key_E))
clearAction = menu.addAction(iconClear,
QCoreApplication.translate("PythonConsole", "Clear console"),
self.clearConsole)
QCoreApplication.translate("PythonConsole", "Clear console"),
self.clearConsole)
menu.addSeparator()
copyAction = menu.addAction(
QCoreApplication.translate("PythonConsole", "Copy"),
self.copy, QKeySequence.Copy)
QCoreApplication.translate("PythonConsole", "Copy"),
self.copy, QKeySequence.Copy)
menu.addSeparator()
selectAllAction = menu.addAction(
QCoreApplication.translate("PythonConsole", "Select All"),
self.selectAll, QKeySequence.SelectAll)
QCoreApplication.translate("PythonConsole", "Select All"),
self.selectAll, QKeySequence.SelectAll)
menu.addSeparator()
settingsDialog = menu.addAction(iconSettings,
QCoreApplication.translate("PythonConsole", "Settings"),
self.parent.openSettings)
menu.addAction(iconSettings,
QCoreApplication.translate("PythonConsole", "Settings"),
self.parent.openSettings)
runAction.setEnabled(False)
clearAction.setEnabled(False)
copyAction.setEnabled(False)
Expand All @@ -247,7 +244,7 @@ def contextMenuEvent(self, e):
clearAction.setEnabled(True)
if self.parent.tabEditorWidget.isVisible():
showEditorAction.setEnabled(False)
action = menu.exec_(self.mapToGlobal(e.pos()))
menu.exec_(self.mapToGlobal(e.pos()))

def hideToolBar(self):
tB = self.parent.toolBar
Expand Down
55 changes: 25 additions & 30 deletions python/console/console_sci.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,9 @@
Some portions of code were taken from https://code.google.com/p/pydee/
"""

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.Qsci import (QsciScintilla,
QsciScintillaBase,
QsciLexerPython,
QsciAPIs)
from PyQt4.QtCore import Qt, QSettings, QByteArray, QCoreApplication, QFile, QSize
from PyQt4.QtGui import QDialog, QMenu, QColor, QShortcut, QKeySequence, QFont, QFontMetrics, QStandardItemModel, QStandardItem, QApplication, QClipboard
from PyQt4.Qsci import QsciScintilla, QsciLexerPython, QsciAPIs

import sys
import os
Expand Down Expand Up @@ -244,7 +241,7 @@ def getBytes(self):
the data is stored internally. """
len = self.SendScintilla(self.SCI_GETLENGTH)+1
bb = QByteArray(len,'0')
N = self.SendScintilla(self.SCI_GETTEXT, len, bb)
self.SendScintilla(self.SCI_GETTEXT, len, bb)
return bytes(bb)[:-1]

def getTextLength(self):
Expand Down Expand Up @@ -297,7 +294,7 @@ def updateHistory(self, command):
self.history.append(line)
elif not command == "":
if len(self.history) <= 0 or \
not command == self.history[-1]:
command != self.history[-1]:
self.history.append(command)
self.historyIndex = len(self.history)

Expand Down Expand Up @@ -424,9 +421,8 @@ def keyPressEvent(self, e):
self.setCursorPosition(line, 4)
self.recolor()

elif (e.modifiers() & (Qt.ControlModifier | Qt.MetaModifier) and \
e.key() == Qt.Key_V) or \
(e.modifiers() & Qt.ShiftModifier and e.key() == Qt.Key_Insert):
elif (e.modifiers() & (Qt.ControlModifier | Qt.MetaModifier) and e.key() == Qt.Key_V) or \
(e.modifiers() & Qt.ShiftModifier and e.key() == Qt.Key_Insert):
self.paste()
e.accept()

Expand All @@ -449,7 +445,7 @@ def keyPressEvent(self, e):
self.insert(self.opening[i] + selText + self.closing[i])
self.setCursorPosition(endLine, endPos+2)
return
elif t == '(' and (re.match(r'^[ \t]*def \w+$', txt) \
elif t == '(' and (re.match(r'^[ \t]*def \w+$', txt)
or re.match(r'^[ \t]*class \w+$', txt)):
self.insert('):')
else:
Expand All @@ -476,35 +472,35 @@ def contextMenuEvent(self, e):
subMenu = QMenu(menu)
titleHistoryMenu = QCoreApplication.translate("PythonConsole", "Command History")
subMenu.setTitle(titleHistoryMenu)
showHistoryAction = subMenu.addAction(
QCoreApplication.translate("PythonConsole", "Show"),
self.showHistory, 'Ctrl+Shift+SPACE')
subMenu.addAction(
QCoreApplication.translate("PythonConsole", "Show"),
self.showHistory, 'Ctrl+Shift+SPACE')
subMenu.addSeparator()
saveHistoryAction = subMenu.addAction(
QCoreApplication.translate("PythonConsole", "Save"),
self.writeHistoryFile)
subMenu.addAction(
QCoreApplication.translate("PythonConsole", "Save"),
self.writeHistoryFile)
subMenu.addSeparator()
clearHistoryAction = subMenu.addAction(
QCoreApplication.translate("PythonConsole", "Clear File"),
self.clearHistory)
clearSessHistoryAction = subMenu.addAction(
QCoreApplication.translate("PythonConsole", "Clear Session"),
self.clearHistorySession)
subMenu.addAction(
QCoreApplication.translate("PythonConsole", "Clear File"),
self.clearHistory)
subMenu.addAction(
QCoreApplication.translate("PythonConsole", "Clear Session"),
self.clearHistorySession)
menu.addMenu(subMenu)
menu.addSeparator()
copyAction = menu.addAction(
QCoreApplication.translate("PythonConsole", "Copy"),
self.copy, QKeySequence.Copy)
QCoreApplication.translate("PythonConsole", "Copy"),
self.copy, QKeySequence.Copy)
pasteAction = menu.addAction(
QCoreApplication.translate("PythonConsole", "Paste"),
self.paste, QKeySequence.Paste)
QCoreApplication.translate("PythonConsole", "Paste"),
self.paste, QKeySequence.Paste)
copyAction.setEnabled(False)
pasteAction.setEnabled(False)
if self.hasSelectedText():
copyAction.setEnabled(True)
if QApplication.clipboard().text():
pasteAction.setEnabled(True)
action = menu.exec_(self.mapToGlobal(e.pos()))
menu.exec_(self.mapToGlobal(e.pos()))

def mousePressEvent(self, e):
"""
Expand Down Expand Up @@ -579,7 +575,6 @@ def entered(self):

def currentCommand(self):
linenr, index = self.getCursorPosition()
txtLength = len(self.text(linenr))
string = self.text()
cmdLine = string[4:]
cmd = unicode(cmdLine)
Expand Down
10 changes: 5 additions & 5 deletions python/console/console_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
Some portions of code were taken from https://code.google.com/p/pydee/
"""

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtCore import QCoreApplication, SIGNAL, QSize, QSettings, QFileInfo, Qt
from PyQt4.QtGui import QDialog, QIcon, QFileDialog, QMessageBox, QTableWidgetItem, QFont, QColor
from console_compile_apis import PrepareAPIDialog

from ui_console_settings import Ui_SettingsDialogPythonConsole
Expand Down Expand Up @@ -74,7 +74,7 @@ def loadAPIFile(self):
settings = QSettings()
lastDirPath = settings.value("pythonConsole/lastDirAPIPath", "", type=str)
fileAPI = QFileDialog.getOpenFileName(
self, "Open API File", lastDirPath, "API file (*.api)")
self, "Open API File", lastDirPath, "API file (*.api)")
if fileAPI:
self.addAPI(fileAPI)

Expand Down Expand Up @@ -106,13 +106,13 @@ def _prepareAPI(self):

def accept(self):
if not self.preloadAPI.isChecked() and \
not self.groupBoxPreparedAPI.isChecked():
not self.groupBoxPreparedAPI.isChecked():
if self.tableWidget.rowCount() == 0:
QMessageBox.information(self, self.tr("Warning!"),
self.tr('Please specify API file or check "Use preloaded API files"'))
return
if self.groupBoxPreparedAPI.isChecked() and \
not self.lineEdit.text():
not self.lineEdit.text():
QMessageBox.information(self, self.tr("Warning!"),
self.tr('The APIs file was not compiled, click on "Compile APIs..."'))
return
Expand Down
1 change: 0 additions & 1 deletion python/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import string
from qgis._core import *


def register_function(function, arg_count, group, usesgeometry=False, **kwargs):
"""
Register a Python function to be used as a expression function.
Expand Down
5 changes: 2 additions & 3 deletions python/core/contextmanagers.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,8 @@ def qgisapp(args=None, guienabled=True, configpath=None, sysexit=True):
def main(app):
# Run your main code block
with qgisapp(sys.argv) as app:
main(app)
with qgisapp(sys.argv) as app:
main(app)
args - args passed to the underlying QApplication.
guienabled - True by default will create a QApplication with a GUI. Pass
Expand Down
33 changes: 16 additions & 17 deletions python/custom_widgets/qgis_customwidgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,27 +28,26 @@

# pluginType = CW_FILTER
# def getFilter():
# import qgis.gui
# import qgis.gui
#
# QGIS_widgets = {}
# for pyClass in dir(qgis.gui):
# QGIS_widgets[pyClass] = 'qgis.gui'
# QGIS_widgets = {}
# for pyClass in dir(qgis.gui):
# QGIS_widgets[pyClass] = 'qgis.gui'
#
# def _QGISfilter(widgetname, baseclassname, module):
# print widgetname, baseclassname, module
# if widgetname in QGIS_widgets:
# return (MATCH, (widgetname, baseclassname, QGIS_widgets[widgetname]))
# else:
# return (NO_MATCH, None)
# def _QGISfilter(widgetname, baseclassname, module):
# print widgetname, baseclassname, module
# if widgetname in QGIS_widgets:
# return (MATCH, (widgetname, baseclassname, QGIS_widgets[widgetname]))
# else:
# return (NO_MATCH, None)
#
# return _QGISfilter
# return _QGISfilter


pluginType = MODULE
def moduleInformation():
try:
import qgis.gui
return "qgis.gui", dir(qgis.gui)
except ImportError:
return "", []

try:
import qgis.gui
return "qgis.gui", dir(qgis.gui)
except ImportError:
return "", []
26 changes: 12 additions & 14 deletions python/plugins/GdalTools/GdalTools.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,12 @@
***************************************************************************/
"""
# Import the PyQt and QGIS libraries
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from PyQt4.QtCore import QObject, QCoreApplication, QSettings, QLocale, QFileInfo, QTranslator, SIGNAL
from PyQt4.QtGui import QMessageBox, QMenu, QIcon, QAction
from qgis.core import QGis
import qgis.utils

# Initialize Qt resources from file resources_rc.py
import resources_rc

# are all dependecies satisfied?
# are all dependencies satisfied?
valid = True

# Import required modules
Expand All @@ -50,7 +47,7 @@
# if a module is missing show a more friendly module's name
error_str = e.args[0]
error_mod = error_str.replace( "No module named ", "" )
if req_mods.has_key( error_mod ):
if error_mod in req_mods:
error_str = error_str.replace( error_mod, req_mods[error_mod] )
raise ImportError( error_str )

Expand Down Expand Up @@ -92,12 +89,13 @@ def __init__( self, iface ):
def initGui( self ):
if not valid: return
if int( self.QgisVersion ) < 1:
QMessageBox.warning( self.iface.getMainWindow(), "Gdal Tools",
QCoreApplication.translate( "GdalTools", "QGIS version detected: " ) +unicode( self.QgisVersion )+".xx\n"
+ QCoreApplication.translate( "GdalTools", "This version of Gdal Tools requires at least QGIS version 1.0.0\nPlugin will not be enabled." ) )
QMessageBox.warning(
self.iface.getMainWindow(), "Gdal Tools",
QCoreApplication.translate( "GdalTools", "QGIS version detected: " ) +unicode( self.QgisVersion )+".xx\n"
+ QCoreApplication.translate( "GdalTools", "This version of Gdal Tools requires at least QGIS version 1.0.0\nPlugin will not be enabled." ) )
return None

from tools.GdalTools_utils import Version, GdalConfig, LayerRegistry
from tools.GdalTools_utils import GdalConfig, LayerRegistry
self.GdalVersionNum = GdalConfig.versionNum()
LayerRegistry.setIface( self.iface )

Expand All @@ -109,11 +107,11 @@ def initGui( self ):
rasterText = QCoreApplication.translate( "QgisApp", "&Raster" )

for a in actions:
if a.menu() != None and a.menu().title() == rasterText:
if a.menu() is not None and a.menu().title() == rasterText:
rasterMenu = a.menu()
break

if rasterMenu == None:
if rasterMenu is None:
# no Raster menu, create and insert it before the Help menu
self.menu = QMenu( rasterText, self.iface.mainWindow() )
lastAction = actions[ len( actions ) - 1 ]
Expand Down
1 change: 0 additions & 1 deletion python/plugins/GdalTools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,3 @@ def classFactory(iface):
# load GdalTools class from file GdalTools
from GdalTools import GdalTools
return GdalTools(iface)

108 changes: 53 additions & 55 deletions python/plugins/GdalTools/tools/GdalTools_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,13 @@
# setLastUsedDir( QString *file_or_dir path )
# -------------------------------------------------

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtCore import QObject, QSettings, QFileInfo, SIGNAL, QDir, QCoreApplication
from PyQt4.QtGui import QFileDialog

from qgis.core import *
from qgis.gui import *
from qgis.core import QgsApplication, QgsMapLayerRegistry, QgsRectangle, QgsProviderRegistry, QgsLogger
from qgis.gui import QgsEncodingFileDialog

from osgeo import gdal, ogr, osr
from osgeo.gdalconst import *

import os
# to know the os
Expand Down Expand Up @@ -135,7 +134,7 @@ class LayerRegistry(QObject):

@staticmethod
def instance():
if LayerRegistry._instance == None:
if LayerRegistry._instance is None:
LayerRegistry._instance = LayerRegistry()
return LayerRegistry._instance

Expand All @@ -147,7 +146,7 @@ def setIface(iface):

def __init__(self):
QObject.__init__(self)
if LayerRegistry._instance != None:
if LayerRegistry._instance is not None:
return

LayerRegistry.layers = self.getAllLayers()
Expand Down Expand Up @@ -222,38 +221,38 @@ def getRasterFiles(path, recursive=False):

return rasters

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

if aFilter != None:
if aFilter is not None:
supportedRasters = GdalConfig.getSupportedRasters()
filterName = re.sub('^.*\] ', '', FileFilter.getFilterName( aFilter ))
if supportedRasters.has_key( filterName ):
if filterName is supportedRasters:
return supportedRasters[ filterName ][ "SHORTNAME" ]

shortName = GdalConfig.SupportedRasters.long2ShortName(filterName)

if shortName == '' and filename != None:
if shortName == '' and filename is not None:
shortName = GdalConfig.SupportedRasters.filename2ShortName(filename)

if shortName == '':
shortName = "GTiff"

return shortName

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

if aFilter != None:
if aFilter is not None:
supportedVectors = GdalConfig.getSupportedVectors()
filterName = re.sub('^.*\] ', '', FileFilter.getFilterName( aFilter ))
if supportedVectors.has_key( filterName ):
if filterName in supportedVectors:
return supportedVectors[ filterName ][ "SHORTNAME" ]

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

if shortName == '' and filename != None:
pass #shortName = GdalConfig.SupportedVectors.filename2ShortName(filename)
if shortName == '' and filename is not None:
pass # shortName = GdalConfig.SupportedVectors.filename2ShortName(filename)

if shortName == '':
shortName = "ESRI Shapefile"
Expand All @@ -267,7 +266,7 @@ def __init__(self):

def getVectorFields(vectorFile):
hds = ogr.Open( unicode(vectorFile).encode('utf8') )
if hds == None:
if hds is None:
raise UnsupportedOGRFormat()

fields = []
Expand Down Expand Up @@ -339,7 +338,7 @@ def getRasterExtent(parent, fileName):
# so sometimes the dialog excedes the screen width
class FileDialog:
@classmethod
def getDialog(self, parent = None, caption = '', acceptMode = QFileDialog.AcceptOpen, fileMode = QFileDialog.ExistingFile, filter = '', selectedFilter = None, useEncoding = False):
def getDialog(self, parent=None, caption='', acceptMode=QFileDialog.AcceptOpen, fileMode=QFileDialog.ExistingFile, filter='', selectedFilter=None, useEncoding=False):
if useEncoding:
dialog = QgsEncodingFileDialog(parent, caption, getLastUsedDir(), filter, getLastUsedEncoding())
else:
Expand Down Expand Up @@ -374,10 +373,10 @@ def getDialog(self, parent = None, caption = '', acceptMode = QFileDialog.Accept
firstExt = None
break

if firstExt == None:
if firstExt is None:
firstExt = ext

if firstExt != None:
if firstExt is not None:
if firstExt.startswith('*'):
files += firstExt[1:]

Expand All @@ -390,19 +389,19 @@ def getDialog(self, parent = None, caption = '', acceptMode = QFileDialog.Accept
return files

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

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

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

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

class FileFilter:
Expand Down Expand Up @@ -443,7 +442,7 @@ def saveRastersFilter(self):
for f in available:
if "*.tif" in f:
filters.append( f )
break
break

for f in available:
if "*.tif" in f or "*.zip" in f or "(*)" in f:
Expand Down Expand Up @@ -528,7 +527,7 @@ def versionNum(self):
# retrieve the supported rasters info
@classmethod
def getSupportedRasters(self):
if self.supportedRasters != None:
if self.supportedRasters is not None:
return self.supportedRasters

# first get the GDAL driver manager
Expand All @@ -542,7 +541,7 @@ def getSupportedRasters(self):
for i in range(gdal.GetDriverCount()):
driver = gdal.GetDriver(i)

if driver == None:
if driver is None:
QgsLogger.warning("unable to get driver " + str(i))
continue

Expand All @@ -557,7 +556,7 @@ def getSupportedRasters(self):
glob = []

metadata = driver.GetMetadata()
if metadata.has_key(gdal.DMD_EXTENSION):
if gdal.DMD_EXTENSION in metadata:
extensions = str(metadata[gdal.DMD_EXTENSION])

if longName != '':
Expand All @@ -569,8 +568,8 @@ def getSupportedRasters(self):
glob.append(string.split("*." + string.replace(extensions,"/", " *."), sep=(" ")))

# Add only the first JP2 driver found to the filter list (it's the one GDAL uses)
if description == "JPEG2000" or description.startswith("JP2"): # JP2ECW, JP2KAK, JP2MrSID
if jp2Driver != None:
if description == "JPEG2000" or description.startswith("JP2"): # JP2ECW, JP2KAK, JP2MrSID
if jp2Driver is not None:
continue # skip if already found a JP2 driver
jp2Driver = driver # first JP2 driver found
glob.append("*.j2k") # add alternate extension
Expand Down Expand Up @@ -601,7 +600,7 @@ def getSupportedRasters(self):
# retrieve the supported vectors info
@classmethod
def getSupportedVectors(self):
if self.supportedVectors != None:
if self.supportedVectors is not None:
return self.supportedVectors

# first get the OGR driver manager
Expand All @@ -613,7 +612,7 @@ def getSupportedVectors(self):
for i in range(ogr.GetDriverCount()):
driver = ogr.GetDriver(i)

if driver == None:
if driver is None:
QgsLogger.warning("unable to get driver " + str(i))
continue

Expand All @@ -622,7 +621,7 @@ def getSupportedVectors(self):
glob = []

if driverName.startswith( "AVCBin" ):
pass #myDirectoryDrivers += "Arc/Info Binary Coverage,AVCBin"
pass # myDirectoryDrivers += "Arc/Info Binary Coverage,AVCBin"
elif driverName.startswith( "AVCE00" ):
longName = "Arc/Info ASCII Coverage"
glob.append("*.e00")
Expand All @@ -633,24 +632,24 @@ def getSupportedVectors(self):
longName = "Comma Separated Value"
glob.append("*.csv")
elif driverName.startswith( "DODS" ):
pass #myProtocolDrivers += "DODS/OPeNDAP,DODS"
pass # myProtocolDrivers += "DODS/OPeNDAP,DODS"
elif driverName.startswith( "PGeo" ):
pass #myDatabaseDrivers += "ESRI Personal GeoDatabase,PGeo"
pass # myDatabaseDrivers += "ESRI Personal GeoDatabase,PGeo"

# on Windows add a pair to the dict for this driver
if platform.system() == "Windows":
longName = "ESRI Personal GeoDatabase"
glob.append("*.mdb")
elif driverName.startswith( "SDE" ):
pass #myDatabaseDrivers += "ESRI ArcSDE,SDE"
pass # myDatabaseDrivers += "ESRI ArcSDE,SDE"
elif driverName.startswith( "ESRI" ):
longName = "ESRI Shapefiles"
glob.append("*.shp")
elif driverName.startswith( "FMEObjects Gateway" ):
longName = "FMEObjects Gateway"
glob.append("*.fdd")
elif driverName.startswith( "GeoJSON" ):
pass #myProtocolDrivers += "GeoJSON,GeoJSON"
pass # myProtocolDrivers += "GeoJSON,GeoJSON"
longName = "GeoJSON"
glob.append("*.geojson")
elif driverName.startswith( "GeoRSS" ):
Expand All @@ -666,9 +665,9 @@ def getSupportedVectors(self):
longName = "GPX"
glob.append("*.gpx")
elif driverName.startswith( "GRASS" ):
pass #myDirectoryDrivers += "Grass Vector,GRASS"
pass # myDirectoryDrivers += "Grass Vector,GRASS"
elif driverName.startswith( "IDB" ):
pass #myDatabaseDrivers += "Informix DataBlade,IDB"
pass # myDatabaseDrivers += "Informix DataBlade,IDB"
elif driverName.startswith( "Interlis 1" ):
longName = "INTERLIS 1"
glob.append("*.itf")
Expand All @@ -680,7 +679,7 @@ def getSupportedVectors(self):
glob.append("*.xml")
glob.append("*.ili")
elif driverName.startswith( "INGRES" ):
pass #myDatabaseDrivers += "INGRES,INGRES"
pass # myDatabaseDrivers += "INGRES,INGRES"
elif driverName.startswith( "KML" ):
longName = "KML"
glob.append("*.kml")
Expand All @@ -692,15 +691,15 @@ def getSupportedVectors(self):
longName = "Microstation DGN"
glob.append("*.dgn")
elif driverName.startswith( "MySQL" ):
pass #myDatabaseDrivers += "MySQL,MySQL"
pass # myDatabaseDrivers += "MySQL,MySQL"
elif driverName.startswith( "OCI" ):
pass #myDatabaseDrivers += "Oracle Spatial,OCI"
pass # myDatabaseDrivers += "Oracle Spatial,OCI"
elif driverName.startswith( "ODBC" ):
pass #myDatabaseDrivers += "ODBC,ODBC"
pass # myDatabaseDrivers += "ODBC,ODBC"
elif driverName.startswith( "OGDI" ):
pass #myDatabaseDrivers += "OGDI Vectors,OGDI"
pass # myDatabaseDrivers += "OGDI Vectors,OGDI"
elif driverName.startswith( "PostgreSQL" ):
pass #myDatabaseDrivers += "PostgreSQL,PostgreSQL"
pass # myDatabaseDrivers += "PostgreSQL,PostgreSQL"
elif driverName.startswith( "S57" ):
longName = "S-57 Base file"
glob.append("*.000")
Expand All @@ -711,9 +710,9 @@ def getSupportedVectors(self):
longName = "SQLite"
glob.append("*.sqlite")
elif driverName.startswith( "UK .NTF" ):
pass #myDirectoryDrivers += "UK. NTF,UK. NTF"
pass # myDirectoryDrivers += "UK. NTF,UK. NTF"
elif driverName.startswith( "TIGER" ):
pass #myDirectoryDrivers += "U.S. Census TIGER/Line,TIGER"
pass # myDirectoryDrivers += "U.S. Census TIGER/Line,TIGER"
elif driverName.startswith( "VRT" ):
longName = "VRT - Virtual Datasource "
glob.append("*.vrt")
Expand Down Expand Up @@ -742,7 +741,7 @@ def long2ShortName(self, longName):
if longName == '':
return ''

if self.dict_long2shortName.has_key(longName):
if longName in self.dict_long2shortName:
return self.dict_long2shortName[longName]

# first get the GDAL driver manager
Expand All @@ -754,7 +753,7 @@ def long2ShortName(self, longName):
# for each loaded GDAL driver
for i in range(gdal.GetDriverCount()):
driver = gdal.GetDriver(i)
if driver == None:
if driver is None:
continue

# if this is the driver we searched for then return its short name
Expand Down Expand Up @@ -838,19 +837,19 @@ def setProcessEnvironment(process):
sep = os.pathsep

for name, val in envvar_list.iteritems():
if val == None or val == "":
if val is None or val == "":
continue

envval = os.getenv(name)
if envval == None or envval == "":
if envval is None or envval == "":
envval = str(val)
elif (platform.system() == "Windows" and val.lower() not in envval.lower().split( sep )) or \
(platform.system() != "Windows" and val not in envval.split( sep )):
(platform.system() != "Windows" and val not in envval.split( sep )):
envval += "%s%s" % (sep, str(val))
else:
envval = None

if envval != None:
if envval is not None:
os.putenv( name, envval )

def setMacOSXDefaultEnvironment():
Expand Down Expand Up @@ -898,4 +897,3 @@ def setMacOSXDefaultEnvironment():
# setup the MacOSX path to both GDAL executables and python modules
if platform.system() == "Darwin":
setMacOSXDefaultEnvironment()

13 changes: 5 additions & 8 deletions python/plugins/GdalTools/tools/dialogBase.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,17 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import Qt, SIGNAL, QProcess, QUrl, QIODevice, QCoreApplication
from PyQt4.QtGui import QDialog, QIcon, QDialogButtonBox, QMessageBox, QDesktopServices, QErrorMessage, QApplication

# to know the os
import platform
import os

from ui_dialogBase import Ui_GdalToolsDialog as Ui_Dialog
import GdalTools_utils as Utils
from .. import resources_rc
#from .. import resources_rc

import os, platform, string
import string

class GdalToolsBaseDialog(QDialog, Ui_Dialog):

Expand Down Expand Up @@ -154,7 +151,7 @@ def refreshArgs(self, args):
self.textEditCommand.setPlainText(self.command + " " + Utils.escapeAndJoin(self.arguments))

# enables the OK button
def enableRun(self, enable = True):
def enableRun(self, enable=True):
self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(enable)

# start the command execution
Expand Down
7 changes: 3 additions & 4 deletions python/plugins/GdalTools/tools/dialogSRS.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,9 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QDialog, QVBoxLayout, QDialogButtonBox
from qgis.gui import QgsProjectionSelector

class GdalToolsSRSDialog(QDialog):
def __init__(self, title, parent=None):
Expand Down
13 changes: 4 additions & 9 deletions python/plugins/GdalTools/tools/doBuildVRT.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,8 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import SIGNAL, QCoreApplication, QObject
from PyQt4.QtGui import QWidget

from ui_widgetBuildVRT import Ui_GdalToolsWidget as Ui_Widget
from widgetPluginBase import GdalToolsBasePluginWidget as BasePluginWidget
Expand All @@ -47,8 +45,7 @@ def __init__(self, iface):
self.recurseCheck.hide()
self.visibleRasterLayers = []

self.setParamsStatus(
[
self.setParamsStatus([
(self.inSelector, SIGNAL("filenameChanged()")),
(self.outSelector, SIGNAL("filenameChanged()")),
(self.resolutionComboBox, SIGNAL("currentIndexChanged(int)"), self.resolutionCheck),
Expand All @@ -58,8 +55,7 @@ def __init__(self, iface):
(self.allowProjDiffCheck, SIGNAL("stateChanged(int)"), None, 1700),
(self.recurseCheck, SIGNAL("stateChanged(int)"), self.inputDirCheck),
(self.inputSelLayersCheck, SIGNAL("stateChanged(int)"))
]
)
])

self.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFilesEdit)
self.connect(self.outSelector, SIGNAL("selectClicked()"), self.fillOutputFileEdit)
Expand Down Expand Up @@ -163,4 +159,3 @@ def getInputFileName(self):

def addLayerIntoCanvas(self, fileInfo):
self.iface.addRasterLayer(fileInfo.filePath())

16 changes: 6 additions & 10 deletions python/plugins/GdalTools/tools/doClipper.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,9 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QWidget
from qgis.core import QGis

from ui_widgetClipper import Ui_GdalToolsWidget as Ui_Widget
from widgetPluginBase import GdalToolsBasePluginWidget as BasePluginWidget
Expand All @@ -46,17 +45,15 @@ def __init__(self, iface):
self.extentSelector.setCanvas(self.canvas)
self.outputFormat = Utils.fillRasterOutputFormat()

self.setParamsStatus(
[
self.setParamsStatus([
(self.inSelector, SIGNAL("filenameChanged()") ),
(self.outSelector, SIGNAL("filenameChanged()") ),
(self.noDataSpin, SIGNAL("valueChanged(int)"), self.noDataCheck, 1700),
(self.maskSelector, SIGNAL("filenameChanged()"), self.maskModeRadio, 1600),
(self.alphaBandCheck, SIGNAL( "stateChanged( int )") ),
(self.extentSelector, [SIGNAL("selectionStarted()"), SIGNAL("newExtentDefined()")], self.extentModeRadio),
(self.modeStackedWidget, SIGNAL("currentIndexChanged(int)"))
]
)
])

self.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFileEdit)
self.connect(self.outSelector, SIGNAL("selectClicked()"), self.fillOutputFileEdit)
Expand Down Expand Up @@ -143,7 +140,7 @@ def getArgsModeExtent(self):
arguments.append( str(self.noDataSpin.value()))
if self.extentModeRadio.isChecked() and self.extentSelector.isCoordsValid():
rect = self.extentSelector.getExtent()
if rect != None:
if rect is not None:
arguments.append("-projwin")
arguments.append(str(rect.xMinimum()))
arguments.append(str(rect.yMaximum()))
Expand Down Expand Up @@ -189,4 +186,3 @@ def getInputFileName(self):

def addLayerIntoCanvas(self, fileInfo):
self.iface.addRasterLayer(fileInfo.filePath())

16 changes: 6 additions & 10 deletions python/plugins/GdalTools/tools/doContour.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,8 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import SIGNAL, QDir
from PyQt4.QtGui import QWidget, QApplication

from ui_widgetContour import Ui_GdalToolsWidget as Ui_Widget
from widgetPluginBase import GdalToolsBasePluginWidget as BasePluginWidget
Expand All @@ -44,21 +42,19 @@ def __init__(self, iface):
gdalVersion = Utils.GdalConfig.versionNum()
self.useDirAsOutput = gdalVersion < 1700
if self.useDirAsOutput:
self.label_2.setText( QApplication.translate("GdalToolsWidget", "&Output directory for contour lines (shapefile)") )
self.label_2.setText( QApplication.translate("GdalToolsWidget", "&Output directory for contour lines (shapefile)") )

self.outSelector.setType( self.outSelector.FILE )

# set the default QSpinBoxes value
self.intervalDSpinBox.setValue(10.0)

self.setParamsStatus(
[
self.setParamsStatus([
(self.inSelector, SIGNAL("filenameChanged()") ),
(self.outSelector, SIGNAL("filenameChanged()")),
(self.intervalDSpinBox, SIGNAL("valueChanged(double)")),
(self.attributeEdit, SIGNAL("textChanged(const QString &)"), self.attributeCheck)
]
)
])

self.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFileEdit)
self.connect(self.outSelector, SIGNAL("selectClicked()"), self.fillOutputFileEdit)
Expand Down Expand Up @@ -114,6 +110,6 @@ def getOutputFileName(self):

def addLayerIntoCanvas(self, fileInfo):
vl = self.iface.addVectorLayer(fileInfo.filePath(), fileInfo.baseName(), "ogr")
if vl != None and vl.isValid():
if vl is not None and vl.isValid():
if hasattr(self, 'lastEncoding'):
vl.setProviderEncoding(self.lastEncoding)
13 changes: 4 additions & 9 deletions python/plugins/GdalTools/tools/doDEM.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,8 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QWidget

from ui_widgetDEM import Ui_GdalToolsWidget as Ui_Widget
from widgetPluginBase import GdalToolsBasePluginWidget as BasePluginWidget
Expand Down Expand Up @@ -62,8 +60,7 @@ def __init__(self, iface):
self.outputFormat = Utils.fillRasterOutputFormat()
self.creationOptionsWidget.setFormat(self.outputFormat)

self.setParamsStatus(
[
self.setParamsStatus([
(self.inSelector, SIGNAL("filenameChanged()")),
(self.outSelector, SIGNAL("filenameChanged()")),
(self.computeEdgesCheck, SIGNAL("stateChanged(int)"), None, 1800),
Expand All @@ -79,8 +76,7 @@ def __init__(self, iface):
(self.configSelector, SIGNAL("filenameChanged()")),
([self.colorExactRadio, self.colorNearestRadio], SIGNAL("toggled(bool)"), self.colorMatchGroupBox),
(self.colorAlphaCheck, SIGNAL("stateChanged(int)"))
]
)
])

self.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFileEdit)
self.connect(self.outSelector, SIGNAL("selectClicked()"), self.fillOutputFileEdit)
Expand Down Expand Up @@ -181,4 +177,3 @@ def getOutputFileName(self):

def addLayerIntoCanvas(self, fileInfo):
self.iface.addRasterLayer(fileInfo.filePath())

11 changes: 5 additions & 6 deletions python/plugins/GdalTools/tools/doExtractProj.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,23 +23,22 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import Qt, SIGNAL, QCoreApplication, QObject, QThread, QMutex
from PyQt4.QtGui import QDialog, QDialogButtonBox, QApplication, QCursor, QMessageBox

from ui_dialogExtractProjection import Ui_GdalToolsDialog as Ui_Dialog
import GdalTools_utils as Utils

import os.path

req_mods = { "osgeo": "osgeo [python-gdal]" }
try:
from osgeo import gdal
from osgeo import osr
except ImportError, e:
error_str = e.args[ 0 ]
error_mod = error_str.replace( "No module named ", "" )
if req_mods.has_key( error_mod ):
if error_mod in req_mods:
error_str = error_str.replace( error_mod, req_mods[error_mod] )
raise ImportError( error_str )

Expand Down Expand Up @@ -126,7 +125,7 @@ def processingInterrupted( self ):
self.restoreGui()

def stopProcessing( self ):
if self.extractor != None:
if self.extractor is not None:
self.extractor.stop()
self.extractor = None

Expand Down
15 changes: 5 additions & 10 deletions python/plugins/GdalTools/tools/doFillNodata.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,13 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import Qt, QObject, SIGNAL, QCoreApplication, QDir
from PyQt4.QtGui import QWidget

from ui_widgetFillNodata import Ui_GdalToolsWidget as Ui_Widget
from widgetBatchBase import GdalToolsBaseBatchWidget as BaseBatchWidget
import GdalTools_utils as Utils

import os.path
import re

class GdalToolsDialog( QWidget, Ui_Widget, BaseBatchWidget ):
Expand All @@ -54,17 +51,15 @@ def __init__( self, iface ):

self.outputFormat = Utils.fillRasterOutputFormat()

self.setParamsStatus(
[
self.setParamsStatus([
( self.inSelector, SIGNAL( "filenameChanged()" ) ),
( self.outSelector, SIGNAL( "filenameChanged()" ) ),
( self.maskSelector, SIGNAL( "filenameChanged()" ), self.maskCheck ),
( self.distanceSpin, SIGNAL( "valueChanged( int )" ), self.distanceCheck ),
( self.smoothSpin, SIGNAL( "valueChanged( int )" ), self.smoothCheck ),
( self.bandSpin, SIGNAL( "valueChanged( int )" ), self.bandCheck ),
( self.nomaskCheck, SIGNAL( "stateChanged( int )" ) )
]
)
])

self.connect( self.inSelector, SIGNAL( "selectClicked()" ), self.fillInputFile )
self.connect( self.outSelector, SIGNAL( "selectClicked()" ), self.fillOutputFile)
Expand Down Expand Up @@ -228,7 +223,7 @@ def batchRun(self):

for f in files:
self.inFiles.append( inDir + "/" + f )
if outDir != None:
if outDir is not None:
outFile = re.sub( "\.[a-zA-Z0-9]{2,4}", outExt, f )
self.outFiles.append( outDir + "/" + outFile )

Expand Down
19 changes: 7 additions & 12 deletions python/plugins/GdalTools/tools/doGrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,8 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import SIGNAL, QFileInfo, QTextCodec
from PyQt4.QtGui import QWidget, QErrorMessage

from ui_widgetGrid import Ui_GdalToolsWidget as Ui_Widget
from widgetPluginBase import GdalToolsBasePluginWidget as BasePluginWidget
Expand Down Expand Up @@ -56,8 +54,7 @@ def __init__(self, iface):
self.outputFormat = Utils.fillRasterOutputFormat()
self.lastEncoding = Utils.getLastUsedEncoding()

self.setParamsStatus(
[
self.setParamsStatus([
(self.inSelector, SIGNAL("filenameChanged()")),
(self.outSelector, SIGNAL("filenameChanged()")),
(self.zfieldCombo, SIGNAL("currentIndexChanged(int)"), self.zfieldCheck),
Expand All @@ -73,8 +70,7 @@ def __init__(self, iface):
(self.datametricsMinPointsSpin, SIGNAL("valueChanged(int)")),
(self.extentSelector, [SIGNAL("selectionStarted()"), SIGNAL("newExtentDefined()")], self.extentGroup),
( [self.widthSpin, self.heightSpin], SIGNAL( "valueChanged(int)" ), self.resizeGroupBox )
]
)
])

self.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFileEdit)
self.connect(self.outSelector, SIGNAL("selectClicked()"), self.fillOutputFileEdit)
Expand All @@ -93,7 +89,7 @@ def onLayersChanged(self):
self.inSelector.setLayers( Utils.LayerRegistry.instance().getVectorLayers() )

def fillFieldsCombo(self):
if self.inSelector.layer() == None:
if self.inSelector.layer() is None:
return

self.lastEncoding = self.inSelector.layer().dataProvider().encoding()
Expand Down Expand Up @@ -132,7 +128,7 @@ def getArguments(self):
arguments.append( QFileInfo( inputFn ).baseName())
if self.extentGroup.isChecked():
rect = self.extentSelector.getExtent()
if rect != None:
if rect is not None:
arguments.append( "-txe")
arguments.append( str(rect.xMinimum()))
arguments.append( str(rect.xMaximum()))
Expand Down Expand Up @@ -198,7 +194,7 @@ def algorithmArguments(self, index):
arguments.append("nodata=" + str(self.datametricsNoDataSpin.value()))
return ':'.join(arguments)

def loadFields(self, vectorFile = ''):
def loadFields(self, vectorFile=''):
self.zfieldCombo.clear()

if not vectorFile:
Expand All @@ -214,4 +210,3 @@ def loadFields(self, vectorFile = ''):
ncodec = QTextCodec.codecForName(self.lastEncoding)
for name in names:
self.zfieldCombo.addItem( ncodec.toUnicode(name) )

14 changes: 4 additions & 10 deletions python/plugins/GdalTools/tools/doInfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,14 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import Qt, QObject, SIGNAL
from PyQt4.QtGui import QWidget, QAction, QApplication, QMenu

from ui_widgetInfo import Ui_GdalToolsWidget as Ui_Widget
from widgetPluginBase import GdalToolsBasePluginWidget as BasePluginWidget
import GdalTools_utils as Utils

import platform
import string

class GdalToolsDialog( QWidget, Ui_Widget, BasePluginWidget ):

Expand All @@ -49,13 +46,11 @@ def __init__( self, iface ):
# make window large
self.base.resize( 400, 360 )

self.setParamsStatus(
[
self.setParamsStatus([
(self.inSelector, SIGNAL("filenameChanged()") ),
( self.suppressGCPCheck, SIGNAL( "stateChanged( int )" ) ),
( self.suppressMDCheck, SIGNAL( "stateChanged( int )" ) )
]
)
])

self.connect( self.inSelector, SIGNAL( "selectClicked()" ), self.fillInputFileEdit )

Expand Down Expand Up @@ -138,4 +133,3 @@ def contextMenuEvent( self, event ):
menu.addAction( self.copyLine )
menu.addAction( self.copyAll )
menu.exec_( event.globalPos() )

27 changes: 11 additions & 16 deletions python/plugins/GdalTools/tools/doMerge.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,8 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import SIGNAL, QObject, QCoreApplication
from PyQt4.QtGui import QWidget, QMessageBox

from ui_widgetMerge import Ui_GdalToolsWidget as Ui_Widget
from widgetPluginBase import GdalToolsBasePluginWidget as BasePluginWidget
Expand All @@ -50,20 +48,18 @@ def __init__(self, iface):
self.outputFormat = Utils.fillRasterOutputFormat()
self.extent = None

self.setParamsStatus(
[
self.setParamsStatus([
(self.inSelector, SIGNAL("filenameChanged()")),
(self.outSelector, SIGNAL("filenameChanged()")),
(self.noDataSpin, SIGNAL("valueChanged(int)"), self.noDataCheck),
(self.inputDirCheck, SIGNAL("stateChanged(int)")),
(self.recurseCheck, SIGNAL("stateChanged(int)"), self.inputDirCheck),
( self.separateCheck, SIGNAL( "stateChanged( int )" ) ),
( self.pctCheck, SIGNAL( "stateChanged( int )" ) ),
( self.intersectCheck, SIGNAL( "stateChanged( int )" ) ),
(self.separateCheck, SIGNAL( "stateChanged( int )" ) ),
(self.pctCheck, SIGNAL( "stateChanged( int )" ) ),
(self.intersectCheck, SIGNAL( "stateChanged( int )" ) ),
(self.creationOptionsWidget, SIGNAL("optionsChanged()")),
(self.creationOptionsGroupBox, SIGNAL("toggled(bool)"))
]
)
])

self.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFilesEdit)
self.connect(self.outSelector, SIGNAL("selectClicked()"), self.fillOutputFileEdit)
Expand Down Expand Up @@ -109,7 +105,7 @@ def refreshExtent(self):

self.extent = self.getIntersectedExtent( files )

if self.extent == None:
if self.extent is None:
QMessageBox.warning( self, self.tr( "Error retrieving the extent" ), self.tr( 'GDAL was unable to retrieve the extent from any file. \nThe "Use intersected extent" option will be unchecked.' ) )
self.intersectCheck.setChecked( False )
return
Expand Down Expand Up @@ -138,7 +134,7 @@ def fillInputDir( self ):
def getArguments(self):
arguments = []
if self.intersectCheck.isChecked():
if self.extent != None:
if self.extent is not None:
arguments.append("-ul_lr")
arguments.append(str( self.extent.xMinimum() ))
arguments.append(str( self.extent.yMaximum() ))
Expand Down Expand Up @@ -186,17 +182,16 @@ def addLayerIntoCanvas(self, fileInfo):
def getIntersectedExtent(self, files):
res = None
for fileName in files:
if res == None:
if res is None:
res = Utils.getRasterExtent( self, fileName )
continue

rect2 = Utils.getRasterExtent( self, fileName )
if rect2 == None:
if rect2 is None:
continue

res = res.intersect( rect2 )
if res.isEmpty():
break

return res

14 changes: 4 additions & 10 deletions python/plugins/GdalTools/tools/doNearBlack.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,8 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from osgeo import ogr
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QWidget

from ui_widgetNearBlack import Ui_GdalToolsWidget as Ui_Widget
from widgetPluginBase import GdalToolsBasePluginWidget as BasePluginWidget
Expand All @@ -47,14 +44,12 @@ def __init__(self, iface):
# set the default QSpinBoxes value
self.nearSpin.setValue(15)

self.setParamsStatus(
[
self.setParamsStatus([
(self.inSelector, SIGNAL("filenameChanged()")),
(self.outSelector, SIGNAL("filenameChanged()")),
(self.nearSpin, SIGNAL("valueChanged(int)"), self.nearCheck),
(self.whiteCheckBox, SIGNAL("stateChanged(int)"))
]
)
])

self.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFileEdit)
self.connect(self.outSelector, SIGNAL("selectClicked()"), self.fillOutputFileEdit)
Expand Down Expand Up @@ -100,4 +95,3 @@ def getInputFileName(self):

def addLayerIntoCanvas(self, fileInfo):
self.iface.addRasterLayer(fileInfo.filePath())

19 changes: 6 additions & 13 deletions python/plugins/GdalTools/tools/doOverview.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,13 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import QObject, SIGNAL, QCoreApplication, QgsRaster
from PyQt4.QtGui import QWidget

from ui_widgetOverview import Ui_GdalToolsWidget as Ui_Widget
from widgetBatchBase import GdalToolsBaseBatchWidget as BaseBatchWidget
import GdalTools_utils as Utils

import platform

class GdalToolsDialog( QWidget, Ui_Widget, BaseBatchWidget ):

def __init__( self, iface ):
Expand All @@ -51,19 +47,17 @@ def __init__( self, iface ):
# we don't need load to canvas functionality
self.base.loadCheckBox.hide()

self.setParamsStatus(
[
self.setParamsStatus([
( self.inSelector, SIGNAL("filenameChanged()")),
( self.cleanCheck, SIGNAL( "stateChanged(int)" ), None, 1700 ),
( self.mPyramidOptionsWidget, SIGNAL( "overviewListChanged()" )),
( self.mPyramidOptionsWidget, SIGNAL( "someValueChanged()" ))
]
)
])

self.connect( self.inSelector, SIGNAL( "selectClicked()" ), self.fillInputFile )
self.connect( self.batchCheck, SIGNAL( "stateChanged( int )" ), self.switchToolMode )

self.init = False #workaround bug that pyramid options widgets are not initialized at first
self.init = False # workaround bug that pyramid options widgets are not initialized at first

# make sure we get a command line when dialog appears
def show_(self):
Expand Down Expand Up @@ -165,7 +159,7 @@ def getOutputFileName( self ):
def addLayerIntoCanvas(self, fileInfo):
self.iface.addRasterLayer(fileInfo.filePath())

def getBatchArguments(self, inFile, outFile = None):
def getBatchArguments(self, inFile, outFile=None):
arguments = self.getArguments()
arguments.append(inFile)
if len(self.mPyramidOptionsWidget.overviewList()) == 0:
Expand Down Expand Up @@ -200,4 +194,3 @@ def updateProgress(self, index, total):
self.progressBar.setValue( index + 1 )
else:
self.progressBar.setValue( 0 )

13 changes: 4 additions & 9 deletions python/plugins/GdalTools/tools/doPctRgb.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,8 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import QObject, SIGNAL, QCoreApplication
from PyQt4.QtGui import QWidget

from ui_widgetConvert import Ui_GdalToolsWidget as Ui_Widget
from widgetBatchBase import GdalToolsBaseBatchWidget as BaseBatchWidget
Expand All @@ -53,14 +51,12 @@ def __init__(self, iface):
self.progressBar.hide()
self.outputFormat = Utils.fillRasterOutputFormat()

self.setParamsStatus(
[
self.setParamsStatus([
(self.inSelector, SIGNAL("filenameChanged()")),
(self.outSelector, SIGNAL("filenameChanged()")),
(self.colorsSpin, SIGNAL("valueChanged(int)"), self.colorsCheck, "-1"), # hide this option
(self.bandSpin, SIGNAL("valueChanged(int)"), self.bandCheck)
]
)
])

self.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFile)
self.connect(self.outSelector, SIGNAL("selectClicked()"), self.fillOutputFileEdit)
Expand Down Expand Up @@ -165,4 +161,3 @@ def updateProgress(self, index, total):
self.progressBar.setValue( index + 1 )
else:
self.progressBar.setValue( 0 )

15 changes: 5 additions & 10 deletions python/plugins/GdalTools/tools/doPolygonize.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,8 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import SIGNAL, QFileInfo
from PyQt4.QtGui import QWidget

from ui_widgetPolygonize import Ui_GdalToolsWidget as Ui_Widget
from widgetPluginBase import GdalToolsBasePluginWidget as BasePluginWidget
Expand All @@ -45,14 +43,12 @@ def __init__(self, iface):
self.outSelector.setType( self.outSelector.FILE )
self.outputFormat = Utils.fillVectorOutputFormat()

self.setParamsStatus(
[
self.setParamsStatus([
(self.inSelector, SIGNAL("filenameChanged()")),
(self.outSelector, SIGNAL("filenameChanged()")),
(self.maskSelector, SIGNAL("filenameChanged()"), self.maskCheck),
(self.fieldEdit, SIGNAL("textChanged(const QString &)"), self.fieldCheck)
]
)
])

self.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFileEdit)
self.connect(self.outSelector, SIGNAL("selectClicked()"), self.fillOutputFileEdit)
Expand Down Expand Up @@ -120,7 +116,6 @@ def getMaskFileName(self):

def addLayerIntoCanvas(self, fileInfo):
vl = self.iface.addVectorLayer(fileInfo.filePath(), fileInfo.baseName(), "ogr")
if vl != None and vl.isValid():
if vl is not None and vl.isValid():
if hasattr(self, 'lastEncoding'):
vl.setProviderEncoding(self.lastEncoding)

14 changes: 5 additions & 9 deletions python/plugins/GdalTools/tools/doProjection.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,15 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import Qt, QObject, SIGNAL, QCoreApplication, QFile, QFileInfo
from PyQt4.QtGui import QWidget, QMessageBox
from qgis.core import QgsMapLayerRegistry, QgsMapLayer

from ui_widgetProjection import Ui_GdalToolsWidget as Ui_Widget
from widgetBatchBase import GdalToolsBaseBatchWidget as BaseBatchWidget
from dialogSRS import GdalToolsSRSDialog as SRSDialog
import GdalTools_utils as Utils

import os.path
import re


Expand All @@ -54,12 +52,10 @@ def __init__( self, iface ):
self.progressBar.hide()
self.recurseCheck.hide()

self.setParamsStatus(
[
self.setParamsStatus([
( self.inSelector, SIGNAL( "filenameChanged()" ) ),
( self.desiredSRSEdit, SIGNAL( "textChanged( const QString & )" ) )
]
)
])

self.connect( self.inSelector, SIGNAL( "selectClicked()" ), self.fillInputFileEdit )
self.connect( self.selectDesiredSRSButton, SIGNAL( "clicked()" ), self.fillDesiredSRSEdit )
Expand Down
16 changes: 4 additions & 12 deletions python/plugins/GdalTools/tools/doProximity.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,8 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from qgis.core import *
from qgis.gui import *

from osgeo import ogr
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QWidget

from ui_widgetProximity import Ui_GdalToolsWidget as Ui_Widget
from widgetPluginBase import GdalToolsBasePluginWidget as BasePluginWidget
Expand All @@ -47,17 +42,15 @@ def __init__(self, iface):
self.outSelector.setType( self.outSelector.FILE )
self.outputFormat = Utils.fillRasterOutputFormat()

self.setParamsStatus(
[
self.setParamsStatus([
(self.inSelector, SIGNAL("filenameChanged()")),
(self.outSelector, SIGNAL("filenameChanged()")),
(self.valuesEdit, SIGNAL("textChanged(const QString &)"), self.valuesCheck),
(self.distUnitsCombo, SIGNAL("currentIndexChanged(int)"), self.distUnitsCheck),
(self.maxDistSpin, SIGNAL("valueChanged(int)"), self.maxDistCheck),
(self.noDataSpin, SIGNAL("valueChanged(int)"), self.noDataCheck),
(self.fixedBufValSpin, SIGNAL("valueChanged(int)"), self.fixedBufValCheck)
]
)
])

self.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFileEdit)
self.connect(self.outSelector, SIGNAL("selectClicked()"), self.fillOutputFileEdit)
Expand Down Expand Up @@ -119,4 +112,3 @@ def getInputFileName(self):

def addLayerIntoCanvas(self, fileInfo):
self.iface.addRasterLayer(fileInfo.filePath())

15 changes: 5 additions & 10 deletions python/plugins/GdalTools/tools/doRasterize.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,8 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from osgeo import ogr
from PyQt4.QtCore import SIGNAL, QFileInfo, QTextCodec
from PyQt4.QtGui import QWidget, QMessageBox, QErrorMessage

from ui_widgetRasterize import Ui_GdalToolsWidget as Ui_Widget
from widgetPluginBase import GdalToolsBasePluginWidget as BasePluginWidget
Expand All @@ -52,15 +49,13 @@ def __init__(self, iface):

self.lastEncoding = Utils.getLastUsedEncoding()

self.setParamsStatus(
[
self.setParamsStatus([
(self.inSelector, SIGNAL("filenameChanged()")),
(self.outSelector, SIGNAL("filenameChanged()")),
(self.attributeComboBox, SIGNAL("currentIndexChanged(int)")),
( [self.widthSpin, self.heightSpin], SIGNAL( "valueChanged(int)" )),
( [self.horizresSpin, self.vertresSpin], SIGNAL( "valueChanged(double)" ))
]
)
])

self.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFileEdit)
self.connect(self.outSelector, SIGNAL("selectClicked()"), self.fillOutputFileEdit)
Expand All @@ -72,7 +67,7 @@ def onLayersChanged(self):
self.inSelector.setLayers( Utils.LayerRegistry.instance().getVectorLayers() )

def fillFieldsCombo(self):
if self.inSelector.layer() == None:
if self.inSelector.layer() is None:
return
self.lastEncoding = self.inSelector.layer().dataProvider().encoding()
self.loadFields( self.getInputFileName() )
Expand Down
13 changes: 4 additions & 9 deletions python/plugins/GdalTools/tools/doRgbPct.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,8 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import SIGNAL, QObject, QCoreApplication
from PyQt4.QtGui import QWidget

from ui_widgetConvert import Ui_GdalToolsWidget as Ui_Widget
from widgetBatchBase import GdalToolsBaseBatchWidget as BaseBatchWidget
Expand All @@ -50,14 +48,12 @@ def __init__(self, iface):
self.progressBar.hide()
self.outputFormat = Utils.fillRasterOutputFormat()

self.setParamsStatus(
[
self.setParamsStatus([
(self.inSelector, SIGNAL("filenameChanged()")),
(self.outSelector, SIGNAL("filenameChanged()")),
(self.colorsSpin, SIGNAL("valueChanged(int)"), self.colorsCheck),
(self.bandSpin, SIGNAL("valueChanged(int)"), self.bandCheck, "-1") # hide this option
]
)
])

self.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFile)
self.connect(self.outSelector, SIGNAL("selectClicked()"), self.fillOutputFileEdit)
Expand Down Expand Up @@ -162,4 +158,3 @@ def updateProgress(self, index, total):
self.progressBar.setValue( index + 1 )
else:
self.progressBar.setValue( 0 )

21 changes: 8 additions & 13 deletions python/plugins/GdalTools/tools/doSettings.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,12 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import Qt, SIGNAL, QObject
from PyQt4.QtGui import QDialog, QPixmap

from ui_dialogSettings import Ui_GdalToolsSettingsDialog as Ui_Dialog
import GdalTools_utils as Utils

from .. import resources_rc

class GdalToolsSettingsDialog( QDialog, Ui_Dialog ):
def __init__( self, iface ):
QDialog.__init__( self, iface.mainWindow() )
Expand All @@ -44,8 +40,8 @@ def __init__( self, iface ):
self.leGdalBinPath.setText( Utils.getGdalBinPath() )
QObject.connect( self.btnSetBinPath, SIGNAL( "clicked()" ), self.setBinPath )
self.bin_tooltip_label.setPixmap( QPixmap(':/icons/tooltip.png') )
self.bin_tooltip_label.setToolTip( self.tr( \
u"""A list of colon-separated (Linux and MacOS) or
self.bin_tooltip_label.setToolTip( self.tr( u"""\
A list of colon-separated (Linux and MacOS) or
semicolon-separated (Windows) paths to both binaries
and python executables.
Expand All @@ -56,16 +52,16 @@ def __init__( self, iface ):
self.leGdalPymodPath.setText( Utils.getGdalPymodPath() )
QObject.connect( self.btnSetPymodPath, SIGNAL( "clicked()" ), self.setPymodPath )
self.pymod_tooltip_label.setPixmap( QPixmap(':/icons/tooltip.png') )
self.pymod_tooltip_label.setToolTip( self.tr( \
u"""A list of colon-separated (Linux and MacOS) or
self.pymod_tooltip_label.setToolTip( self.tr( u"""\
A list of colon-separated (Linux and MacOS) or
semicolon-separated (Windows) paths to python modules.""") )

# help
self.leGdalHelpPath.setText( Utils.getHelpPath() )
QObject.connect( self.btnSetHelpPath, SIGNAL( "clicked()" ), self.setHelpPath )
self.help_tooltip_label.setPixmap( QPixmap(':/icons/tooltip.png') )
self.help_tooltip_label.setToolTip( self.tr( \
u"""Useful to open local GDAL documentation instead of online help
self.help_tooltip_label.setToolTip( self.tr( u"""\
Useful to open local GDAL documentation instead of online help
when pressing on the tool dialog's Help button.""") )


Expand Down Expand Up @@ -96,4 +92,3 @@ def accept( self ):
Utils.setGdalPymodPath( self.leGdalPymodPath.text() )
Utils.setHelpPath( self.leGdalHelpPath.text() )
QDialog.accept( self )

13 changes: 4 additions & 9 deletions python/plugins/GdalTools/tools/doSieve.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,8 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from osgeo import ogr
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QWidget

from ui_widgetSieve import Ui_GdalToolsWidget as Ui_Widget
from widgetPluginBase import GdalToolsBasePluginWidget as BasePluginWidget
Expand All @@ -45,14 +42,12 @@ def __init__(self, iface):
self.outSelector.setType( self.outSelector.FILE )
self.outputFormat = Utils.fillRasterOutputFormat()

self.setParamsStatus(
[
self.setParamsStatus([
(self.inSelector, SIGNAL("filenameChanged()")),
(self.outSelector, SIGNAL("filenameChanged()")),
(self.thresholdSpin, SIGNAL("valueChanged(int)"), self.thresholdCheck),
(self.connectionsCombo, SIGNAL("currentIndexChanged(int)"), self.connectionsCheck)
]
)
])

self.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFileEdit)
self.connect(self.outSelector, SIGNAL("selectClicked()"), self.fillOutputFileEdit)
Expand Down
17 changes: 5 additions & 12 deletions python/plugins/GdalTools/tools/doTileIndex.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,13 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QWidget

from ui_widgetTileIndex import Ui_GdalToolsWidget as Ui_Widget
from widgetPluginBase import GdalToolsBasePluginWidget as BasePluginWidget
import GdalTools_utils as Utils

import os.path

class GdalToolsDialog( QWidget, Ui_Widget, BasePluginWidget ):

def __init__( self, iface ):
Expand All @@ -46,16 +42,14 @@ def __init__( self, iface ):
self.inSelector.setType( self.inSelector.FILE )
self.outSelector.setType( self.outSelector.FILE )

self.setParamsStatus(
[
self.setParamsStatus([
( self.inSelector, SIGNAL( "filenameChanged()" ) ),
#( self.recurseCheck, SIGNAL( "stateChanged( int )" ),
( self.outSelector, SIGNAL( "filenameChanged()" ) ),
( self.indexFieldEdit, SIGNAL( "textChanged( const QString & )" ), self.indexFieldCheck),
( self.absolutePathCheck, SIGNAL( "stateChanged( int )" ), None, 1500 ),
( self.skipDifferentProjCheck, SIGNAL( "stateChanged( int )" ), None, 1500 )
]
)
])

self.connect( self.inSelector, SIGNAL( "selectClicked()" ), self.fillInputDirEdit )
self.connect( self.outSelector, SIGNAL( "selectClicked()" ), self.fillOutputFileEdit )
Expand Down Expand Up @@ -98,7 +92,6 @@ def getInputFileName( self ):

def addLayerIntoCanvas( self, fileInfo ):
vl = self.iface.addVectorLayer( fileInfo.filePath(), fileInfo.baseName(), "ogr" )
if vl != None and vl.isValid():
if vl is not None and vl.isValid():
if hasattr( self, 'lastEncoding' ):
vl.setProviderEncoding( self.lastEncoding )

20 changes: 8 additions & 12 deletions python/plugins/GdalTools/tools/doTranslate.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,8 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import QObject, Qt, SIGNAL, QCoreApplication, QDir
from PyQt4.QtGui import QWidget, QMessageBox

from ui_widgetTranslate import Ui_GdalToolsWidget as Ui_Widget
from widgetBatchBase import GdalToolsBaseBatchWidget as BaseBatchWidget
Expand Down Expand Up @@ -63,8 +61,7 @@ def __init__(self, iface):

self.outputFormat = Utils.fillRasterOutputFormat()

self.setParamsStatus(
[
self.setParamsStatus([
(self.inSelector, SIGNAL("filenameChanged()")),
(self.outSelector, SIGNAL("filenameChanged()")),
(self.targetSRSEdit, SIGNAL("textChanged(const QString &)"), self.targetSRSCheck),
Expand All @@ -76,8 +73,7 @@ def __init__(self, iface):
(self.sdsCheck, SIGNAL("stateChanged(int)")),
(self.srcwinEdit, SIGNAL("textChanged(const QString &)"), self.srcwinCheck),
(self.prjwinEdit, SIGNAL("textChanged(const QString &)"), self.prjwinCheck)
]
)
])

#self.connect(self.canvas, SIGNAL("layersChanged()"), self.fillInputLayerCombo)
self.connect(self.inSelector, SIGNAL("layerChanged()"), self.fillTargetSRSEditDefault)
Expand Down Expand Up @@ -173,7 +169,7 @@ def fillOutputDir( self ):
self.outSelector.setFilename( outputDir )

def fillTargetSRSEditDefault(self):
if self.inSelector.layer() == None:
if self.inSelector.layer() is None:
return
self.refreshTargetSRS()

Expand Down Expand Up @@ -210,7 +206,7 @@ def getArguments(self):
if len(coordList) == 4 and coordList[3]:
try:
for x in coordList:
test = int(x)
int(x)
except ValueError:
#print "Coordinates must be integer numbers."
QMessageBox.critical(self, self.tr("Translate - srcwin"), self.tr("Image coordinates (pixels) must be integer numbers."))
Expand All @@ -223,7 +219,7 @@ def getArguments(self):
if len(coordList) == 4 and coordList[3]:
try:
for x in coordList:
test = float(x)
float(x)
except ValueError:
#print "Coordinates must be integer numbers."
QMessageBox.critical(self, self.tr("Translate - prjwin"), self.tr("Image coordinates (geographic) must be numbers."))
Expand Down Expand Up @@ -299,7 +295,7 @@ def batchRun(self):

for f in files:
self.inFiles.append( inDir + "/" + f )
if outDir != None:
if outDir is not None:
outFile = re.sub( "\.[a-zA-Z0-9]{2,4}", outExt, f )
self.outFiles.append( outDir + "/" + outFile )

Expand Down
16 changes: 6 additions & 10 deletions python/plugins/GdalTools/tools/doWarp.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,9 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import QObject, QCoreApplication, SIGNAL, QDir
from PyQt4.QtGui import QWidget
from qgis.core import QGis

from ui_widgetWarp import Ui_GdalToolsWidget as Ui_Widget
from widgetBatchBase import GdalToolsBaseBatchWidget as BaseBatchWidget
Expand Down Expand Up @@ -54,8 +53,7 @@ def __init__(self, iface):

self.outputFormat = Utils.fillRasterOutputFormat()

self.setParamsStatus(
[
self.setParamsStatus([
(self.inSelector, SIGNAL("filenameChanged()")),
(self.outSelector, SIGNAL("filenameChanged()")),
(self.sourceSRSEdit, SIGNAL("textChanged(const QString &)"), self.sourceSRSCheck),
Expand All @@ -68,8 +66,7 @@ def __init__(self, iface):
(self.multithreadCheck, SIGNAL("stateChanged(int)")),
(self.noDataEdit, SIGNAL( "textChanged( const QString & )" ), self.noDataCheck),
(self.maskSelector, SIGNAL("filenameChanged()"), self.maskCheck, 1600),
]
)
])

self.connect(self.inSelector, SIGNAL("layerChanged()"), self.fillSourceSRSEditDefault)
self.connect(self.inSelector, SIGNAL("selectClicked()"), self.fillInputFile)
Expand Down Expand Up @@ -170,7 +167,7 @@ def fillSourceSRSEdit(self):
self.sourceSRSEdit.setText(dialog.getProjection())

def fillSourceSRSEditDefault(self):
if self.inSelector.layer() == None:
if self.inSelector.layer() is None:
return
self.refreshSourceSRS()

Expand Down Expand Up @@ -252,4 +249,3 @@ def updateProgress(self, index, total):
self.progressBar.setValue( index + 1 )
else:
self.progressBar.setValue( 0 )

21 changes: 10 additions & 11 deletions python/plugins/GdalTools/tools/extentSelector.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,12 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QWidget, QColor
from qgis.core import QgsPoint, QgsRectangle, QGis
from qgis.gui import QgsMapTool, QgsMapToolEmitPoint, QgsRubberBand

from ui_extentSelector import Ui_GdalToolsExtentSelector as Ui_ExtentSelector
import GdalTools_utils as Utils

class GdalToolsExtentSelector(QWidget, Ui_ExtentSelector):

Expand Down Expand Up @@ -70,7 +69,7 @@ def stop(self):
def start(self):
prevMapTool = self.canvas.mapTool()
if prevMapTool != self.tool:
self.previousMapTool = prevMapTool
self.previousMapTool = prevMapTool
self.canvas.setMapTool(self.tool)
self.isStarted = True
self.btnEnable.setVisible(False)
Expand All @@ -93,8 +92,8 @@ def getExtent(self):

def isCoordsValid(self):
try:
point1 = QgsPoint( float(self.x1CoordEdit.text()), float(self.y1CoordEdit.text()) )
point2 = QgsPoint( float(self.x2CoordEdit.text()), float(self.y2CoordEdit.text()) )
QgsPoint( float(self.x1CoordEdit.text()), float(self.y1CoordEdit.text()) )
QgsPoint( float(self.x2CoordEdit.text()), float(self.y2CoordEdit.text()) )
except ValueError:
return False

Expand All @@ -112,7 +111,7 @@ def coordsChanged(self):
def fillCoords(self):
rect = self.getExtent()
self.blockSignals(True)
if rect != None:
if rect is not None:
self.x1CoordEdit.setText( str(rect.xMinimum()) )
self.x2CoordEdit.setText( str(rect.xMaximum()) )
self.y1CoordEdit.setText( str(rect.yMaximum()) )
Expand Down Expand Up @@ -178,7 +177,7 @@ def showRect(self, startPoint, endPoint):
self.rubberBand.show()

def rectangle(self):
if self.startPoint == None or self.endPoint == None:
if self.startPoint is None or self.endPoint is None:
return None
elif self.startPoint.x() == self.endPoint.x() or self.startPoint.y() == self.endPoint.y():
return None
Expand All @@ -189,7 +188,7 @@ def setRectangle(self, rect):
if rect == self.rectangle():
return False

if rect == None:
if rect is None:
self.reset()
else:
self.startPoint = QgsPoint(rect.xMaximum(), rect.yMaximum())
Expand Down
18 changes: 8 additions & 10 deletions python/plugins/GdalTools/tools/inOutSelector.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,12 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtCore import SIGNAL, Qt, pyqtProperty
from PyQt4.QtGui import QWidget, QComboBox

from qgis.core import QgsMapLayerRegistry, QgsMapLayer

from ui_inOutSelector import Ui_GdalToolsInOutSelector
import GdalTools_utils as Utils

class GdalToolsInOutSelector(QWidget, Ui_GdalToolsInOutSelector):
FILE = 0x1
Expand All @@ -43,7 +42,7 @@ class GdalToolsInOutSelector(QWidget, Ui_GdalToolsInOutSelector):
__pyqtSignals__ = ("selectClicked()", "filenameChanged(), layerChanged()")


def __init__(self, parent = None, type=None):
def __init__(self, parent=None, type=None):
QWidget.__init__(self, parent)

self.setupUi(self)
Expand All @@ -53,7 +52,7 @@ def __init__(self, parent = None, type=None):
self.clear()

self.typ = None
if type == None:
if type is None:
self.resetType()
else:
self.setType(type)
Expand Down Expand Up @@ -135,7 +134,7 @@ def setFilename(self, fn=None):
elif isinstance(fn, str) or isinstance(fn, unicode):
fn = unicode( fn )

#TODO test
# TODO test
elif isinstance(fn, list):
if len( fn ) > 0:
if self.getType() & self.MULTIFILE:
Expand Down Expand Up @@ -190,7 +189,7 @@ def setLayer(self, layer=None):


def setLayers(self, layers=None):
if layers == None or not hasattr(layers, '__iter__') or len(layers) <= 0:
if layers is None or not hasattr(layers, '__iter__') or len(layers) <= 0:
self.combo.clear()
return

Expand Down Expand Up @@ -220,7 +219,7 @@ def saveComboState(self):
self.prevState = ( index, text, layerID )

def restoreComboState(self):
if self.prevState == None:
if self.prevState is None:
return
index, text, layerID = self.prevState

Expand Down Expand Up @@ -257,8 +256,7 @@ def filename(self):
return self.filenames
return self.combo.currentText()
layer = self.layer()
if layer != None:
if layer is not None:
return layer.source()

return ''

9 changes: 4 additions & 5 deletions python/plugins/GdalTools/tools/optionsTable.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,14 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QWidget, QTableWidgetItem

from ui_optionsTable import Ui_GdalToolsOptionsTable as Ui_OptionsTable

class GdalToolsOptionsTable(QWidget, Ui_OptionsTable):

def __init__(self, parent = None):
def __init__(self, parent=None):
QWidget.__init__(self, parent)

self.setupUi(self)
Expand All @@ -49,7 +49,7 @@ def enableDeleteButton(self):
def addNewRow(self):
self.table.insertRow(self.table.rowCount())
# select the added row
newRow = self.table.rowCount()-1;
newRow = self.table.rowCount()-1
item = QTableWidgetItem()
self.table.setItem(newRow, 0, item)
self.table.setCurrentItem(item)
Expand All @@ -76,4 +76,3 @@ def options(self):

options.append( name.text() + "=" + value.text())
return options

17 changes: 7 additions & 10 deletions python/plugins/GdalTools/tools/widgetBatchBase.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,8 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import Qt, QFile, QFileInfo
from PyQt4.QtGui import QMessageBox, QErrorMessage

from widgetPluginBase import GdalToolsBasePluginWidget as BasePluginWidget
import GdalTools_utils as Utils
Expand All @@ -36,11 +34,11 @@ class GdalToolsBaseBatchWidget(BasePluginWidget):
def __init__(self, iface, commandName):
BasePluginWidget.__init__(self, iface, commandName)

def getBatchArguments(self, inFile, outFile = None):
def getBatchArguments(self, inFile, outFile=None):
arguments = []
arguments.extend( self.getArguments() )
arguments.append( inFile )
if outFile != None:
if outFile is not None:
arguments.append(outFile)
return arguments

Expand All @@ -61,7 +59,7 @@ def getBatchOutputFileName(self, fn):
outDir = self.getOutputFileName()

# if overwrites existent files
if outDir == None or outDir == inDir:
if outDir is None or outDir == inDir:
return fn + ".tmp"

return outDir + fn[len(inDir):]
Expand Down Expand Up @@ -122,7 +120,7 @@ def onFinished(self, exitCode, status):
# overwrite existent files
inDir = self.getInputFileName()
outDir = self.getOutputFileName()
if outDir == None or inDir == outDir:
if outDir is None or inDir == outDir:
oldFile = QFile( self.inFiles[self.batchIndex] )
newFile = QFile( self.outFiles[self.batchIndex] )
if oldFile.remove():
Expand All @@ -140,7 +138,7 @@ def batchFinished( self ):

inDir = self.getInputFileName()
outDir = self.getOutputFileName()
if outDir == None or inDir == outDir:
if outDir is None or inDir == outDir:
self.outFiles = self.inFiles

# load layers managing the render flag to avoid waste of time
Expand All @@ -161,4 +159,3 @@ def batchFinished( self ):
QMessageBox.information( self, self.tr( "Finished" ), self.tr( "Operation completed." ) )
else:
QMessageBox.warning( self, self.tr( "Warning" ), self.tr( "The following files were not created: \n{0}" ).format( ', '.join( notCreatedList ) ) )

18 changes: 8 additions & 10 deletions python/plugins/GdalTools/tools/widgetPluginBase.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,8 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import SIGNAL, QFileInfo
from PyQt4.QtGui import QWidget, QMessageBox, QAbstractButton, QGroupBox

from dialogBase import GdalToolsBaseDialog as BaseDialog
import GdalTools_utils as Utils
Expand Down Expand Up @@ -105,7 +103,7 @@ def addLayerIntoCanvas(self, fileInfo):

def finished(self, load):
outFn = self.getOutputFileName()
if outFn == None:
if outFn is None:
return

if outFn == '':
Expand Down Expand Up @@ -169,7 +167,7 @@ def setParamsStatus(self, wdgts_sgnls_chk_ver_list):

# if check version fails, disable the widget then hide both it and its enabler checkbox
# new check for gdal 1.10, must update all widgets for this and then remove previous check
if ver != None and isinstance(ver, int):
if ver is not None and isinstance(ver, int):
gdalVerNum = Utils.GdalConfig.versionNum()
if ver > gdalVerNum:
wdgt.setVisible(False)
Expand All @@ -179,11 +177,11 @@ def setParamsStatus(self, wdgts_sgnls_chk_ver_list):
sgnls = None
chk = False

elif ver != None:
elif ver is not None:
if not isinstance(ver, Utils.Version):
ver = Utils.Version(ver)
gdalVer = Utils.GdalConfig.version()
if ver < "0" or ( gdalVer != None and ver > gdalVer ):
if ver < "0" or ( gdalVer is not None and ver > gdalVer ):
wdgt.setVisible(False)
if isinstance(chk, QWidget):
chk.setVisible(False)
Expand All @@ -198,14 +196,14 @@ def setParamsStatus(self, wdgts_sgnls_chk_ver_list):
return

sgnl = sgnls
if sgnl != None:
if sgnl is not None:
self.connect(wdgt, sgnl, self.someValueChanged)

# set the passed checkbox as widget enabler
if isinstance(chk, bool):
wdgt.setEnabled(chk)
if ( isinstance(chk, QAbstractButton) or isinstance(chk, QGroupBox) ) and \
chk.isCheckable():
chk.isCheckable():
wdgt.setEnabled(chk.isChecked())
self.connect(chk, SIGNAL("toggled(bool)"), wdgt.setEnabled)
self.connect(chk, SIGNAL("toggled(bool)"), self.someValueChanged)
3 changes: 0 additions & 3 deletions python/plugins/MetaSearch/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,6 @@
#
###############################################################################

import os
import site

def classFactory(iface):
"""invoke plugin"""
from MetaSearch.plugin import MetaSearchPlugin
Expand Down
4 changes: 0 additions & 4 deletions python/plugins/MetaSearch/dialogs/maindialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,6 @@
from owslib.csw import CatalogueServiceWeb
from owslib.fes import BBox, PropertyIsLike
from owslib.ows import ExceptionReport
from owslib.wcs import WebCoverageService
from owslib.wfs import WebFeatureService
from owslib.wms import WebMapService
from owslib.wmts import WebMapTileService

from MetaSearch import link_types
from MetaSearch.dialogs.manageconnectionsdialog import ManageConnectionsDialog
Expand Down
2 changes: 1 addition & 1 deletion python/plugins/MetaSearch/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

import logging

from PyQt4.QtCore import QCoreApplication, QLocale, QSettings, QTranslator
from PyQt4.QtCore import QCoreApplication
from PyQt4.QtGui import QAction, QIcon

from MetaSearch.dialogs.maindialog import MetaSearchDialog
Expand Down
4 changes: 2 additions & 2 deletions python/plugins/db_manager/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,5 @@
"""

def classFactory(iface):
from .db_manager_plugin import DBManagerPlugin
return DBManagerPlugin(iface)
from .db_manager_plugin import DBManagerPlugin
return DBManagerPlugin(iface)
771 changes: 390 additions & 381 deletions python/plugins/db_manager/db_manager.py

Large diffs are not rendered by default.

88 changes: 44 additions & 44 deletions python/plugins/db_manager/db_manager_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,57 +20,57 @@
***************************************************************************/
"""

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtCore import Qt, QObject, SIGNAL
from PyQt4.QtGui import QAction, QIcon, QApplication

try:
from . import resources_rc
from . import resources_rc
except ImportError:
pass
pass

class DBManagerPlugin:
def __init__(self, iface):
self.iface = iface
self.dlg = None
def __init__(self, iface):
self.iface = iface
self.dlg = None

def initGui(self):
self.action = QAction( QIcon(":/db_manager/icon"), QApplication.translate("DBManagerPlugin","DB Manager"), self.iface.mainWindow() )
self.action.setObjectName("dbManager")
QObject.connect( self.action, SIGNAL( "triggered()" ), self.run )
# Add toolbar button and menu item
if hasattr( self.iface, 'addDatabaseToolBarIcon' ):
self.iface.addDatabaseToolBarIcon(self.action)
else:
self.iface.addToolBarIcon(self.action)
if hasattr( self.iface, 'addPluginToDatabaseMenu' ):
self.iface.addPluginToDatabaseMenu( QApplication.translate("DBManagerPlugin","DB Manager"), self.action )
else:
self.iface.addPluginToMenu( QApplication.translate("DBManagerPlugin","DB Manager"), self.action )
def initGui(self):
self.action = QAction( QIcon(":/db_manager/icon"), QApplication.translate("DBManagerPlugin","DB Manager"), self.iface.mainWindow() )
self.action.setObjectName("dbManager")
QObject.connect( self.action, SIGNAL( "triggered()" ), self.run )
# Add toolbar button and menu item
if hasattr( self.iface, 'addDatabaseToolBarIcon' ):
self.iface.addDatabaseToolBarIcon(self.action)
else:
self.iface.addToolBarIcon(self.action)
if hasattr( self.iface, 'addPluginToDatabaseMenu' ):
self.iface.addPluginToDatabaseMenu( QApplication.translate("DBManagerPlugin","DB Manager"), self.action )
else:
self.iface.addPluginToMenu( QApplication.translate("DBManagerPlugin","DB Manager"), self.action )

def unload(self):
# Remove the plugin menu item and icon
if hasattr( self.iface, 'removePluginDatabaseMenu' ):
self.iface.removePluginDatabaseMenu( QApplication.translate("DBManagerPlugin","DB Manager"), self.action )
else:
self.iface.removePluginMenu( QApplication.translate("DBManagerPlugin","DB Manager"), self.action )
if hasattr( self.iface, 'removeDatabaseToolBarIcon' ):
self.iface.removeDatabaseToolBarIcon(self.action)
else:
self.iface.removeToolBarIcon(self.action)
def unload(self):
# Remove the plugin menu item and icon
if hasattr( self.iface, 'removePluginDatabaseMenu' ):
self.iface.removePluginDatabaseMenu( QApplication.translate("DBManagerPlugin","DB Manager"), self.action )
else:
self.iface.removePluginMenu( QApplication.translate("DBManagerPlugin","DB Manager"), self.action )
if hasattr( self.iface, 'removeDatabaseToolBarIcon' ):
self.iface.removeDatabaseToolBarIcon(self.action)
else:
self.iface.removeToolBarIcon(self.action)

if self.dlg != None:
self.dlg.close()
if self.dlg is not None:
self.dlg.close()

def run(self):
# keep opened only one instance
if self.dlg == None:
from db_manager import DBManager
self.dlg = DBManager(self.iface)
QObject.connect(self.dlg, SIGNAL("destroyed(QObject *)"), self.onDestroyed)
self.dlg.show()
self.dlg.raise_()
self.dlg.setWindowState( self.dlg.windowState() & ~Qt.WindowMinimized )
self.dlg.activateWindow()
def run(self):
# keep opened only one instance
if self.dlg is None:
from db_manager import DBManager
self.dlg = DBManager(self.iface)
QObject.connect(self.dlg, SIGNAL("destroyed(QObject *)"), self.onDestroyed)
self.dlg.show()
self.dlg.raise_()
self.dlg.setWindowState( self.dlg.windowState() & ~Qt.WindowMinimized )
self.dlg.activateWindow()

def onDestroyed(self, obj):
self.dlg = None
def onDestroyed(self, obj):
self.dlg = None
968 changes: 484 additions & 484 deletions python/plugins/db_manager/db_model.py

Large diffs are not rendered by default.

52 changes: 24 additions & 28 deletions python/plugins/db_manager/db_plugins/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,51 +20,47 @@
***************************************************************************/
"""

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class NotSupportedDbType(Exception):
def __init__(self, dbtype):
self.msg = self.tr("%s is not supported yet") % dbtype
Exception(self, self.msg)
def __init__(self, dbtype):
self.msg = self.tr("%s is not supported yet") % dbtype
Exception(self, self.msg)

def __str__(self):
return self.msg.encode('utf-8')
def __str__(self):
return self.msg.encode('utf-8')


def initDbPluginList():
import os
current_dir = os.path.dirname(__file__)
for name in os.listdir(current_dir):
if not os.path.isdir( os.path.join( current_dir, name ) ):
continue
import os
current_dir = os.path.dirname(__file__)
for name in os.listdir(current_dir):
if not os.path.isdir( os.path.join( current_dir, name ) ):
continue

try:
exec( u"from .%s import plugin as mod" % name )
except ImportError, e:
DBPLUGIN_ERRORS.append( u"%s: %s" % (name, e.message) )
continue
try:
exec( u"from .%s import plugin as mod" % name )
except ImportError, e:
DBPLUGIN_ERRORS.append( u"%s: %s" % (name, e.message) )
continue

pluginclass = mod.classFactory()
SUPPORTED_DBTYPES[ pluginclass.typeName() ] = pluginclass
pluginclass = mod.classFactory()
SUPPORTED_DBTYPES[ pluginclass.typeName() ] = pluginclass

return len(SUPPORTED_DBTYPES) > 0
return len(SUPPORTED_DBTYPES) > 0

def supportedDbTypes():
return sorted(SUPPORTED_DBTYPES.keys())
return sorted(SUPPORTED_DBTYPES.keys())

def getDbPluginErrors():
return DBPLUGIN_ERRORS
return DBPLUGIN_ERRORS

def createDbPlugin(dbtype, conn_name=None):
if not SUPPORTED_DBTYPES.has_key( dbtype ):
raise NotSupportedDbType( dbtype )
dbplugin = SUPPORTED_DBTYPES[ dbtype ]
return dbplugin if conn_name is None else dbplugin(conn_name)
if dbtype not in SUPPORTED_DBTYPES:
raise NotSupportedDbType( dbtype )
dbplugin = SUPPORTED_DBTYPES[ dbtype ]
return dbplugin if conn_name is None else dbplugin(conn_name)


# initialize the plugin list
SUPPORTED_DBTYPES = {}
DBPLUGIN_ERRORS = []
initDbPluginList()

316 changes: 156 additions & 160 deletions python/plugins/db_manager/db_plugins/connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,206 +20,202 @@
***************************************************************************/
"""

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from qgis.core import QgsDataSourceURI

from .plugin import BaseError, DbError, ConnectionError
from .plugin import DbError, ConnectionError

class DBConnector:
def __init__(self, uri):
self.connection = None
self._uri = uri

def __del__(self):
pass #print "DBConnector.__del__", self._uri.connectionInfo()
if self.connection != None:
self.connection.close()
self.connection = None


def uri(self):
return QgsDataSourceURI( self._uri.uri() )

def publicUri(self):
publicUri = QgsDataSourceURI.removePassword( self._uri.uri() )
return QgsDataSourceURI( publicUri )


def hasSpatialSupport(self):
return False

def hasRasterSupport(self):
return False

def hasCustomQuerySupport(self):
return False

def hasTableColumnEditingSupport(self):
return False
def __init__(self, uri):
self.connection = None
self._uri = uri

def __del__(self):
pass # print "DBConnector.__del__", self._uri.connectionInfo()
if self.connection is not None:
self.connection.close()
self.connection = None

def execution_error_types(self):
raise Exception("DBConnector.execution_error_types() is an abstract method")

def connection_error_types(self):
raise Exception("DBConnector.connection_error_types() is an abstract method")
def uri(self):
return QgsDataSourceURI( self._uri.uri() )

def error_types(self):
return self.connection_error_types() + self.execution_error_types()
def publicUri(self):
publicUri = QgsDataSourceURI.removePassword( self._uri.uri() )
return QgsDataSourceURI( publicUri )

def _execute(self, cursor, sql):
if cursor == None:
cursor = self._get_cursor()
try:
cursor.execute(unicode(sql))

except self.connection_error_types() as e:
raise ConnectionError(e)
def hasSpatialSupport(self):
return False

except self.execution_error_types() as e:
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
self._rollback()
raise DbError(e, sql)
def hasRasterSupport(self):
return False

return cursor
def hasCustomQuerySupport(self):
return False

def _execute_and_commit(self, sql):
""" tries to execute and commit some action, on error it rolls back the change """
self._execute(None, sql)
self._commit()
def hasTableColumnEditingSupport(self):
return False

def _get_cursor(self, name=None):
try:
if name != None:
name = unicode(name).encode('ascii', 'replace').replace( '?', "_" )
self._last_cursor_named_id = 0 if not hasattr(self, '_last_cursor_named_id') else self._last_cursor_named_id + 1
return self.connection.cursor( "%s_%d" % (name, self._last_cursor_named_id) )

return self.connection.cursor()
def execution_error_types(self):
raise Exception("DBConnector.execution_error_types() is an abstract method")

except self.connection_error_types(), e:
raise ConnectionError(e)
def connection_error_types(self):
raise Exception("DBConnector.connection_error_types() is an abstract method")

except self.execution_error_types(), e:
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
self._rollback()
raise DbError(e)
def error_types(self):
return self.connection_error_types() + self.execution_error_types()

def _close_cursor(self, c):
try:
if c and not c.closed:
c.close()
def _execute(self, cursor, sql):
if cursor is None:
cursor = self._get_cursor()
try:
cursor.execute(unicode(sql))

except self.error_types(), e:
pass
except self.connection_error_types() as e:
raise ConnectionError(e)

return
except self.execution_error_types() as e:
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
self._rollback()
raise DbError(e, sql)

return cursor

def _fetchall(self, c):
try:
return c.fetchall()
def _execute_and_commit(self, sql):
""" tries to execute and commit some action, on error it rolls back the change """
self._execute(None, sql)
self._commit()

except self.connection_error_types(), e:
raise ConnectionError(e)
def _get_cursor(self, name=None):
try:
if name is not None:
name = unicode(name).encode('ascii', 'replace').replace( '?', "_" )
self._last_cursor_named_id = 0 if not hasattr(self, '_last_cursor_named_id') else self._last_cursor_named_id + 1
return self.connection.cursor( "%s_%d" % (name, self._last_cursor_named_id) )

except self.execution_error_types(), e:
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
self._rollback()
raise DbError(e)
return self.connection.cursor()

def _fetchone(self, c):
try:
return c.fetchone()
except self.connection_error_types(), e:
raise ConnectionError(e)

except self.connection_error_types(), e:
raise ConnectionError(e)
except self.execution_error_types(), e:
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
self._rollback()
raise DbError(e)

except self.execution_error_types(), e:
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
self._rollback()
raise DbError(e)
def _close_cursor(self, c):
try:
if c and not c.closed:
c.close()

except self.error_types(), e:
pass

def _commit(self):
try:
self.connection.commit()
return

except self.connection_error_types(), e:
raise ConnectionError(e)

except self.execution_error_types(), e:
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
self._rollback()
raise DbError(e)
def _fetchall(self, c):
try:
return c.fetchall()

except self.connection_error_types(), e:
raise ConnectionError(e)

def _rollback(self):
try:
self.connection.rollback()
except self.execution_error_types(), e:
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
self._rollback()
raise DbError(e)

except self.connection_error_types(), e:
raise ConnectionError(e)

except self.execution_error_types(), e:
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
self._rollback()
raise DbError(e)
def _fetchone(self, c):
try:
return c.fetchone()

except self.connection_error_types(), e:
raise ConnectionError(e)

def _get_cursor_columns(self, c):
try:
if c.description:
return map(lambda x: x[0], c.description)
except self.execution_error_types(), e:
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
self._rollback()
raise DbError(e)

except self.connection_error_types() + self.execution_error_types(), e:
return []

def _commit(self):
try:
self.connection.commit()

@classmethod
def quoteId(self, identifier):
if hasattr(identifier, '__iter__'):
ids = list()
for i in identifier:
if i == None or i == "":
continue
ids.append( self.quoteId(i) )
return u'.'.join( ids )

identifier = unicode(identifier) if identifier != None else unicode() # make sure it's python unicode string
return u'"%s"' % identifier.replace('"', '""')

@classmethod
def quoteString(self, txt):
""" make the string safe - replace ' with '' """
if hasattr(txt, '__iter__'):
txts = list()
for i in txt:
if i == None:
continue
txts.append( self.quoteString(i) )
return u'.'.join( txts )
except self.connection_error_types(), e:
raise ConnectionError(e)

txt = unicode(txt) if txt != None else unicode() # make sure it's python unicode string
return u"'%s'" % txt.replace("'", "''")
except self.execution_error_types(), e:
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
self._rollback()
raise DbError(e)

@classmethod
def getSchemaTableName(self, table):
if not hasattr(table, '__iter__'):
return (None, table)
elif len(table) < 2:
return (None, table[0])
else:
return (table[0], table[1])

@classmethod
def getSqlDictionary(self):
""" return a generic SQL dictionary """
try:
from ..sql_dictionary import getSqlDictionary
return getSqlDictionary()
except ImportError:
return []
def _rollback(self):
try:
self.connection.rollback()

except self.connection_error_types(), e:
raise ConnectionError(e)

except self.execution_error_types(), e:
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
self._rollback()
raise DbError(e)


def _get_cursor_columns(self, c):
try:
if c.description:
return map(lambda x: x[0], c.description)

except self.connection_error_types() + self.execution_error_types(), e:
return []


@classmethod
def quoteId(self, identifier):
if hasattr(identifier, '__iter__'):
ids = list()
for i in identifier:
if i is None or i == "":
continue
ids.append( self.quoteId(i) )
return u'.'.join( ids )

identifier = unicode(identifier) if identifier is not None else unicode() # make sure it's python unicode string
return u'"%s"' % identifier.replace('"', '""')

@classmethod
def quoteString(self, txt):
""" make the string safe - replace ' with '' """
if hasattr(txt, '__iter__'):
txts = list()
for i in txt:
if i is None:
continue
txts.append( self.quoteString(i) )
return u'.'.join( txts )

txt = unicode(txt) if txt is not None else unicode() # make sure it's python unicode string
return u"'%s'" % txt.replace("'", "''")

@classmethod
def getSchemaTableName(self, table):
if not hasattr(table, '__iter__'):
return (None, table)
elif len(table) < 2:
return (None, table[0])
else:
return (table[0], table[1])

@classmethod
def getSqlDictionary(self):
""" return a generic SQL dictionary """
try:
from ..sql_dictionary import getSqlDictionary
return getSqlDictionary()
except ImportError:
return []
Loading