Skip to content

Commit

Permalink
- [API] introduce QgsMessageLog::MessageLevel and change logMessage()…
Browse files Browse the repository at this point in the history
… level

  parameter to that type
- change default level to WARNING
- change startup messages to INFO
- don't unhide the warning button for INFO messages
- fix warnings produced by python code
  • Loading branch information
jef-n committed Jan 26, 2013
1 parent 5ed164a commit 994dc1c
Show file tree
Hide file tree
Showing 22 changed files with 135 additions and 77 deletions.
11 changes: 9 additions & 2 deletions python/core/qgsmessagelog.sip
Expand Up @@ -7,8 +7,15 @@ class QgsMessageLog
public:
static QgsMessageLog *instance();

enum MessageLevel
{
INFO = 0,
WARNING = 1,
CRITICAL = 2
};

//! add a message to the instance (and create it if necessary)
static void logMessage( QString message, QString tag = QString::null, int level = 0 );
static void logMessage( QString message, QString tag = QString::null, MessageLevel level = WARNING);

signals:
void messageReceived( QString message, QString tag, int level );
Expand All @@ -34,5 +41,5 @@ class QgsMessageLogConsole : QObject
QgsMessageLogConsole();

public slots:
void logMessage( QString message, QString tag, int level );
void logMessage( QString message, QString tag, QgsMessageLog::MessageLevel level );
};
3 changes: 1 addition & 2 deletions python/plugins/GdalTools/tools/GdalTools_utils.py
Expand Up @@ -35,9 +35,8 @@
from qgis.core import *
from qgis.gui import *

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

import os
# to know the os
Expand Down
39 changes: 19 additions & 20 deletions python/plugins/sextante/core/GeoAlgorithm.py
Expand Up @@ -41,7 +41,6 @@ def __init__(self):

self.defineCharacteristics()


def getCopy(self):
newone = copy.copy(self)
newone.parameters = copy.deepcopy(self.parameters)
Expand Down Expand Up @@ -106,8 +105,8 @@ def checkParameterValuesBeforeExecuting(self):
This check is called from the parameters dialog, and also when calling from the console'''
return None
#=========================================================


def execute(self, progress):
'''The method to use to call a SEXTANTE algorithm.
Although the body of the algorithm is in processAlgorithm(),
Expand All @@ -120,9 +119,9 @@ def execute(self, progress):
self.resolveTemporaryOutputs()
self.checkOutputFileExtensions()
self.runPreExecutionScript(progress)
self.processAlgorithm(progress)
self.processAlgorithm(progress)
self.convertUnsupportedFormats(progress)
self.runPostExecutionScript(progress)
self.runPostExecutionScript(progress)
except GeoAlgorithmExecutionException, gaee:
SextanteLog.addToLog(SextanteLog.LOG_ERROR, gaee.msg)
raise gaee
Expand All @@ -144,49 +143,49 @@ def execute(self, progress):
def runPostExecutionScript(self, progress):
scriptFile = SextanteConfig.getSetting(SextanteConfig.POST_EXECUTION_SCRIPT)
self.runHookScript(scriptFile, progress);

def runPreExecutionScript(self, progress):
scriptFile = SextanteConfig.getSetting(SextanteConfig.PRE_EXECUTION_SCRIPT)
self.runHookScript(scriptFile, progress);
def runHookScript(self, filename, progress):

def runHookScript(self, filename, progress):
if not os.path.exists(filename):
return
try:
try:
script = "import sextante\n"
ns = {}
ns['progress'] = progress
ns['alg'] = self
ns['alg'] = self
f = open(filename)
lines = f.readlines()
for line in lines:
script+=line
exec(script) in ns
exec(script) in ns
except: # a wrong script should not cause problems, so we swallow all exceptions
pass

def convertUnsupportedFormats(self, progress):
i = 0
progress.setText("Converting outputs")
for out in self.outputs:
if isinstance(out, OutputVector):
for out in self.outputs:
if isinstance(out, OutputVector):
if out.compatible is not None:
layer = QGisLayers.getObjectFromUri(out.compatible)
provider = layer.dataProvider()
writer = out.getVectorWriter( provider.fields(), provider.geometryType(), provider.crs())
features = QGisLayers.features(layer)
for feature in features:
writer.addFeature(feature)
elif isinstance(out, OutputRaster):
elif isinstance(out, OutputRaster):
if out.compatible is not None:
layer = QGisLayers.getObjectFromUri(out.compatible)
provider = layer.dataProvider()
writer = QgsRasterFileWriter(out.value)
format = self.getFormatShortNameFromFilename(out.value)
writer.setOutputFormat(format);
writer.writeRaster(layer.pipe(), layer.width(), layer.height(), layer.extent(), layer.crs())
progress.setPercentage(100 * i / float(len(self.outputs)))
writer.setOutputFormat(format);
writer.writeRaster(layer.pipe(), layer.width(), layer.height(), layer.extent(), layer.crs())
progress.setPercentage(100 * i / float(len(self.outputs)))

def getFormatShortNameFromFilename(self, filename):
ext = filename[filename.rfind(".")+1:]
supported = GdalUtils.getSupportedRasters()
Expand All @@ -195,7 +194,7 @@ def getFormatShortNameFromFilename(self, filename):
if ext in exts:
return name
return "GTiff"

def checkOutputFileExtensions(self):
'''Checks if the values of outputs are correct and have one of the supported output extensions.
If not, it adds the first one of the supported extensions, which is assumed to be the default one'''
Expand Down
4 changes: 3 additions & 1 deletion python/plugins/sextante/gdal/GdalOgrAlgorithmProvider.py
Expand Up @@ -81,11 +81,13 @@ def _loadAlgorithms(self):
self.algs = self.preloadedAlgs

def createAlgsList(self):
#First we populate the list of algorihtms with those created extending
#First we populate the list of algorithms with those created extending
#GeoAlgorithm directly (those that execute GDAL using the console)

self.preloadedAlgs = [nearblack(), information(), warp(), translate(),
rgb2pct(), pct2rgb(), merge(), polygonize(), gdaladdo(),
OgrInfo(), Ogr2Ogr(), OgrSql()]

#And then we add those that are created as python scripts
folder = self.scriptsFolder()
for descriptionFile in os.listdir(folder):
Expand Down
12 changes: 10 additions & 2 deletions python/plugins/sextante/gdal/GdalUtils.py
Expand Up @@ -28,7 +28,12 @@
import subprocess
from sextante.core.SextanteLog import SextanteLog
import os
import gdal

try:
from osgeo import gdal
gdalAvailable = True
except:
gdalAvailable = False

class GdalUtils():

Expand Down Expand Up @@ -57,6 +62,9 @@ def getConsoleOutput():

@staticmethod
def getSupportedRasters():
if not gdalAvailable:
return {}

'''this has been adapted from GdalTools plugin'''
if GdalUtils.supportedRasters != None:
return GdalUtils.supportedRasters
Expand All @@ -76,7 +84,7 @@ def getSupportedRasters():
if not metadata.has_key(gdal.DCAP_CREATE) or metadata[gdal.DCAP_CREATE] != 'YES':
continue
if metadata.has_key(gdal.DMD_EXTENSION):
extensions = metadata[gdal.DMD_EXTENSION].split("/")
extensions = metadata[gdal.DMD_EXTENSION].split("/")
if extensions:
GdalUtils.supportedRasters[shortName] = extensions

Expand Down
12 changes: 9 additions & 3 deletions python/plugins/sextante/gdal/OgrAlgorithm.py
Expand Up @@ -30,7 +30,12 @@
from PyQt4.QtGui import *
import string
import re
import ogr

try:
from osgeo import ogr
ogrAvailable = True
except:
ogrAvailable = False

class OgrAlgorithm(GeoAlgorithm):

Expand Down Expand Up @@ -61,8 +66,9 @@ def ogrConnectionString(self, uri):

def drivers(self):
list = []
for iDriver in range(ogr.GetDriverCount()):
list.append("%s" % ogr.GetDriver(iDriver).GetName())
if ogrAvailable:
for iDriver in range(ogr.GetDriverCount()):
list.append("%s" % ogr.GetDriver(iDriver).GetName())
return list

def failure(self, pszDataSource):
Expand Down
12 changes: 9 additions & 3 deletions python/plugins/sextante/gdal/ogr2ogr.py
Expand Up @@ -39,10 +39,12 @@
import re
import os
import tempfile
import ogr
import gdal
import osr

try:
from osgeo import gdal, ogr, osr
gdalAvailable = True
except:
gdalAvailable = False

GeomOperation = Enum(["NONE", "SEGMENTIZE", "SIMPLIFY_PRESERVE_TOPOLOGY"])

Expand Down Expand Up @@ -71,6 +73,10 @@ def defineCharacteristics(self):
def processAlgorithm(self, progress):
'''Here is where the processing itself takes place'''

if not gdalAvailable:
SextanteLog.addToLog(SextanteLog.LOG_ERROR, "GDAL bindings not installed." )
return

input = self.getParameterValue(self.INPUT_LAYER)
ogrLayer = self.ogrConnectionString(input)
output = self.getOutputValue(self.OUTPUT_LAYER)
Expand Down
12 changes: 11 additions & 1 deletion python/plugins/sextante/gdal/ogrinfo.py
Expand Up @@ -30,7 +30,13 @@
from PyQt4.QtGui import *
import string
import re
import ogr

try:
from osgeo import ogr
ogrAvailable = True
except:
ogrAvailable = False

from sextante.gdal.OgrAlgorithm import OgrAlgorithm

class OgrInfo(OgrAlgorithm):
Expand Down Expand Up @@ -71,6 +77,10 @@ def ogrinfo(self, pszDataSource):
bSummaryOnly = True
self.info = ''

if not ogrAvailable:
self.info = "OGR bindings not installed"
return

qDebug("Opening data source '%s'" % pszDataSource)
poDS = ogr.Open( pszDataSource, False )

Expand Down
12 changes: 11 additions & 1 deletion python/plugins/sextante/gdal/ogrsql.py
Expand Up @@ -33,7 +33,13 @@
from PyQt4.QtGui import *
import string
import re
import ogr

try:
from osgeo import ogr
ogrAvailable = True
except:
ogrAvailable = False

from sextante.gdal.OgrAlgorithm import OgrAlgorithm

class OgrSql(OgrAlgorithm):
Expand All @@ -58,6 +64,10 @@ def defineCharacteristics(self):


def processAlgorithm(self, progress):
if not ogrAvailable:
SextanteLog.addToLog(SextanteLog.LOG_ERROR, "OGR bindings not installed" )
return

input = self.getParameterValue(self.INPUT_LAYER)
sql = self.getParameterValue(self.SQL)
ogrLayer = self.ogrConnectionString(input)
Expand Down
14 changes: 10 additions & 4 deletions python/plugins/sextante/gdal/pyogr/ogr2ogr.py
Expand Up @@ -29,9 +29,12 @@
import sys
import os
import stat
import ogr
import gdal
import osr

try:
from osgeo import gdal, ogr, osr
gdalAvailable = True
except:
gdalAvailable = False

###############################################################################

Expand Down Expand Up @@ -127,7 +130,7 @@ def flush(self):
bSkipFailures = False
nGroupTransactions = 200
bPreserveFID = False
nFIDToFetch = ogr.NullFID
nFIDToFetch = ogr.NullFID if gdalAvailable else None

class Enum(set):
def __getattr__(self, name):
Expand Down Expand Up @@ -1593,6 +1596,9 @@ def TranslateLayer(poSrcDS, poSrcLayer, poDstDS, papszLCO, pszNewLayerName, \
return True

if __name__ == '__main__':
if not gdalAvailable:
print('ERROR: Python bindings of GDAL 1.8.0 or later required')

version_num = int(gdal.VersionInfo('VERSION_NUM'))
if version_num < 1800: # because of ogr.GetFieldTypeName
print('ERROR: Python bindings of GDAL 1.8.0 or later required')
Expand Down
2 changes: 1 addition & 1 deletion python/plugins/sextante/gdal/pyogr/ogrds.py
Expand Up @@ -23,7 +23,7 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

import ogr
from osgeo import ogr

class OgrDs:

Expand Down
5 changes: 3 additions & 2 deletions python/plugins/sextante/gdal/pyogr/ogrvrt.py
Expand Up @@ -28,8 +28,9 @@
import re
import cgi
import sys
import ogr
import gdal

from osgeo import gdal, ogr

from string import Template
import os
import tempfile
Expand Down
9 changes: 2 additions & 7 deletions python/plugins/sextante/gdal/scripts/fillnodata.py
Expand Up @@ -31,12 +31,7 @@
##[GDAL] Analysis=group
from sextante.gdal.GdalUtils import GdalUtils

try:
from osgeo import gdal, ogr
except ImportError:
import gdal
import ogr

from osgeo import gdal, ogr

def CopyBand( srcband, dstband ):
for line in range(srcband.YSize):
Expand Down Expand Up @@ -73,4 +68,4 @@ def CopyBand( srcband, dstband ):

src_ds = None
dst_ds = None
mask_ds = None
mask_ds = None
6 changes: 1 addition & 5 deletions python/plugins/sextante/gdal/scripts/sieve.py
Expand Up @@ -32,11 +32,7 @@
##connectedness=selection 4;8
from sextante.gdal.GdalUtils import GdalUtils

try:
from osgeo import gdal, ogr
except ImportError:
import gdal
import ogr
from osgeo import gdal, ogr

threshold = 2
connectedness=int(connectedness)
Expand Down
1 change: 1 addition & 0 deletions python/utils.py
Expand Up @@ -43,6 +43,7 @@
# ERROR HANDLING

warnings.simplefilter('default')
warnings.filterwarnings("ignore", "the sets module is deprecated")

def showWarning(message, category, filename, lineno, file=None, line=None):
QgsMessageLog.logMessage(
Expand Down

0 comments on commit 994dc1c

Please sign in to comment.