Skip to content

Commit

Permalink
[FEATURE] Possibility to save error messages as shapefile from check
Browse files Browse the repository at this point in the history
geometry validity tool. Contributed by Salvatore Larosa
  • Loading branch information
alexbruy committed Nov 26, 2012
1 parent 677c9ca commit 24e259b
Show file tree
Hide file tree
Showing 4 changed files with 216 additions and 79 deletions.
5 changes: 5 additions & 0 deletions i18n/qgis_it.ts
Expand Up @@ -830,6 +830,11 @@ sono stati ridotti a %2 dopo la semplificazione</translation>
<source>Press Ctrl+C to copy results to the clipboard</source> <source>Press Ctrl+C to copy results to the clipboard</source>
<translation>Premi Ctrl+C per copiare i risultati negli appunti</translation> <translation>Premi Ctrl+C per copiare i risultati negli appunti</translation>
</message> </message>
<message>
<location filename="../python/plugins/fTools/tools/frmVisual.ui" line="120"/>
<source>Save errors location</source>
<translation>Salva posizione errori</translation>
</message>
<message> <message>
<source>Sum line lengths</source> <source>Sum line lengths</source>
<translation>Somma lunghezza linee</translation> <translation>Somma lunghezza linee</translation>
Expand Down
154 changes: 115 additions & 39 deletions python/plugins/fTools/tools/doValidate.py
Expand Up @@ -60,7 +60,7 @@ def setGeom(self, p):


def reset(self): def reset(self):
if not self.__marker is None: if not self.__marker is None:
self.__canvas.scene().removeItem(self.__marker) self.__canvas.scene().removeItem(self.__marker)
del self.__marker del self.__marker
self.__marker = None self.__marker = None


Expand All @@ -83,9 +83,10 @@ def __init__(self, iface):
self.tblUnique.setSelectionBehavior(QAbstractItemView.SelectRows) self.tblUnique.setSelectionBehavior(QAbstractItemView.SelectRows)
# populate list of available layers # populate list of available layers
myList = ftools_utils.getLayerNames( [ QGis.Point, QGis.Line, QGis.Polygon ] ) myList = ftools_utils.getLayerNames( [ QGis.Point, QGis.Line, QGis.Polygon ] )
self.connect(self.tblUnique, SIGNAL("currentItemChanged(QTableWidgetItem*, QTableWidgetItem*)" ), self.connect(self.tblUnique, SIGNAL("currentItemChanged(QTableWidgetItem*, QTableWidgetItem*)" ),
self.zoomToError) self.zoomToError)
self.inShape.addItems( myList ) self.inShape.addItems( myList )
self.buttonBox_2.setOrientation(Qt.Horizontal)
self.cancel_close = self.buttonBox_2.button(QDialogButtonBox.Close) self.cancel_close = self.buttonBox_2.button(QDialogButtonBox.Close)
self.buttonOk = self.buttonBox_2.button(QDialogButtonBox.Ok) self.buttonOk = self.buttonBox_2.button(QDialogButtonBox.Ok)
self.progressBar.setValue(0) self.progressBar.setValue(0)
Expand All @@ -96,12 +97,16 @@ def __init__(self, iface):
settings = QSettings() settings = QSettings()
self.restoreGeometry( settings.value("/fTools/ValidateDialog/geometry").toByteArray() ) self.restoreGeometry( settings.value("/fTools/ValidateDialog/geometry").toByteArray() )


QObject.connect( self.browseShpError, SIGNAL( "clicked()" ), self.outFile )
QObject.connect( self.ckBoxShpError, SIGNAL( "stateChanged( int )" ), self.updateGui )
self.updateGui()

def closeEvent(self, e): def closeEvent(self, e):
settings = QSettings() settings = QSettings()
settings.setValue( "/fTools/ValidateDialog/geometry", QVariant(self.saveGeometry()) ) settings.setValue( "/fTools/ValidateDialog/geometry", QVariant(self.saveGeometry()) )
QDialog.closeEvent(self, e) QDialog.closeEvent(self, e)
del self.marker del self.marker

def keyPressEvent( self, e ): def keyPressEvent( self, e ):
if ( e.modifiers() == Qt.ControlModifier or \ if ( e.modifiers() == Qt.ControlModifier or \
e.modifiers() == Qt.MetaModifier ) and \ e.modifiers() == Qt.MetaModifier ) and \
Expand All @@ -122,10 +127,37 @@ def accept( self ):
QMessageBox.information( self, self.tr("Error!"), self.tr( "Please specify input vector layer" ) ) QMessageBox.information( self, self.tr("Error!"), self.tr( "Please specify input vector layer" ) )
elif self.cmbField.isVisible() and self.cmbField.currentText() == "": elif self.cmbField.isVisible() and self.cmbField.currentText() == "":
QMessageBox.information( self, self.tr("Error!"), self.tr( "Please specify input field" ) ) QMessageBox.information( self, self.tr("Error!"), self.tr( "Please specify input field" ) )
elif self.ckBoxShpError.isChecked() and self.lineEditShpError.text() == "":
QMessageBox.information( self, self.tr( "Error!" ), self.tr( "Please specify output shapefile" ) )
else: else:
self.vlayer = ftools_utils.getVectorLayerByName( self.inShape.currentText() ) self.vlayer = ftools_utils.getVectorLayerByName( self.inShape.currentText() )
self.validate( self.useSelected.checkState() ) self.validate( self.useSelected.checkState() )


def updateGui( self ):
if self.ckBoxShpError.isChecked():
self.lineEditShpError.setEnabled( True )
self.browseShpError.setEnabled( True )
self.tblUnique.setEnabled( False )
self.lstCount.setEnabled( False )
self.label_2.setEnabled( False )
self.label_4.setEnabled( False )
self.label_5.setEnabled( False )
else:
self.lineEditShpError.setEnabled( False )
self.browseShpError.setEnabled( False )
self.tblUnique.setEnabled( True )
self.lstCount.setEnabled( True )
self.label_2.setEnabled( True )
self.label_4.setEnabled( True )
self.label_5.setEnabled( True )

def outFile( self ):
self.lineEditShpError.clear()
(self.shapefileName, self.encoding) = ftools_utils.saveDialog( self )
if self.shapefileName is None or self.encoding is None:
return
self.lineEditShpError.setText( QString( self.shapefileName ) )

def zoomToError(self, curr, prev): def zoomToError(self, curr, prev):
if curr is None: if curr is None:
return return
Expand Down Expand Up @@ -162,11 +194,16 @@ def zoomToError(self, curr, prev):
mc.refresh() mc.refresh()


def validate( self, mySelection ): def validate( self, mySelection ):
self.tblUnique.clearContents() if not self.ckBoxShpError.isChecked():
self.tblUnique.setRowCount( 0 ) self.tblUnique.clearContents()
self.lstCount.clear() self.tblUnique.setRowCount( 0 )
self.lstCount.clear()
self.shapefileName = None
self.encoding = None

self.buttonOk.setEnabled( False ) self.buttonOk.setEnabled( False )
self.testThread = validateThread( self.iface.mainWindow(), self, self.vlayer, mySelection )
self.testThread = validateThread( self.iface.mainWindow(), self, self.vlayer, mySelection, self.shapefileName, self.encoding, self.ckBoxShpError.isChecked() )
QObject.connect( self.testThread, SIGNAL( "runFinished(PyQt_PyObject)" ), self.runFinishedFromThread ) QObject.connect( self.testThread, SIGNAL( "runFinished(PyQt_PyObject)" ), self.runFinishedFromThread )
QObject.connect( self.testThread, SIGNAL( "runStatus(PyQt_PyObject)" ), self.runStatusFromThread ) QObject.connect( self.testThread, SIGNAL( "runStatus(PyQt_PyObject)" ), self.runStatusFromThread )
QObject.connect( self.testThread, SIGNAL( "runRange(PyQt_PyObject)" ), self.runRangeFromThread ) QObject.connect( self.testThread, SIGNAL( "runRange(PyQt_PyObject)" ), self.runRangeFromThread )
Expand All @@ -180,60 +217,73 @@ def reject(self):
# Remove Marker # Remove Marker
self.marker.reset() self.marker.reset()
QDialog.reject(self) QDialog.reject(self)

def cancelThread( self ): def cancelThread( self ):
self.testThread.stop() self.testThread.stop()
QApplication.restoreOverrideCursor() QApplication.restoreOverrideCursor()
self.buttonOk.setEnabled( True ) self.buttonOk.setEnabled( True )

def runFinishedFromThread( self, output ): def runFinishedFromThread( self, success ):
self.testThread.stop() self.testThread.stop()
QApplication.restoreOverrideCursor() QApplication.restoreOverrideCursor()
self.buttonOk.setEnabled( True ) self.buttonOk.setEnabled( True )
self.tblUnique.setColumnCount( 2 ) if success == "writeShape":
count = 0 extra = ""
for rec in output: addToTOC = QMessageBox.question( self, self.tr("Geometry"),
if len(rec[1]) < 1: self.tr( "Created output shapefile:\n%1\n%2\n\nWould you like to add the new layer to the TOC?" ).arg( unicode( self.shapefileName ) ).arg( extra ),
continue QMessageBox.Yes, QMessageBox.No, QMessageBox.NoButton )
where = None if addToTOC == QMessageBox.Yes:
for err in rec[1]: # for each error we find if not ftools_utils.addShapeToCanvas( unicode( self.shapefileName ) ):
self.tblUnique.insertRow(count) QMessageBox.warning( self, self.tr( "Geometry"),
fidItem = QTableWidgetItem( str(rec[0]) ) self.tr( "Error loading output shapefile:\n%1" ).arg( unicode( self.shapefileName ) ) )
self.tblUnique.setItem( count, 0, fidItem ) else:
message = err.what() self.tblUnique.setColumnCount( 2 )
errItem = QTableWidgetItem( message ) count = 0
if err.hasWhere(): # if there is a location associated with the error for rec in success:
errItem.setData(Qt.UserRole, QVariant(err.where())) if len(rec[1]) < 1:
self.tblUnique.setItem( count, 1, errItem ) continue
count += 1 where = None
self.tblUnique.setHorizontalHeaderLabels( [ self.tr("Feature"), self.tr("Error(s)") ] ) for err in rec[1]: # for each error we find
self.tblUnique.horizontalHeader().setResizeMode( 0, QHeaderView.ResizeToContents ) self.tblUnique.insertRow(count)
self.tblUnique.horizontalHeader().show() fidItem = QTableWidgetItem( str(rec[0]) )
self.tblUnique.horizontalHeader().setResizeMode( 1, QHeaderView.Stretch ) self.tblUnique.setItem( count, 0, fidItem )
self.tblUnique.resizeRowsToContents() message = err.what()
self.lstCount.insert(str(count)) errItem = QTableWidgetItem( message )
if err.hasWhere(): # if there is a location associated with the error
errItem.setData(Qt.UserRole, QVariant(err.where()))
self.tblUnique.setItem( count, 1, errItem )
count += 1
self.tblUnique.setHorizontalHeaderLabels( [ self.tr("Feature"), self.tr("Error(s)") ] )
self.tblUnique.horizontalHeader().setResizeMode( 0, QHeaderView.ResizeToContents )
self.tblUnique.horizontalHeader().show()
self.tblUnique.horizontalHeader().setResizeMode( 1, QHeaderView.Stretch )
self.tblUnique.resizeRowsToContents()
self.lstCount.insert(str(count))
self.cancel_close.setText( "Close" ) self.cancel_close.setText( "Close" )
QObject.disconnect( self.cancel_close, SIGNAL( "clicked()" ), self.cancelThread ) QObject.disconnect( self.cancel_close, SIGNAL( "clicked()" ), self.cancelThread )
return True return True

def runStatusFromThread( self, status ): def runStatusFromThread( self, status ):
self.progressBar.setValue( status ) self.progressBar.setValue( status )

def runRangeFromThread( self, range_vals ): def runRangeFromThread( self, range_vals ):
self.progressBar.setRange( range_vals[ 0 ], range_vals[ 1 ] ) self.progressBar.setRange( range_vals[ 0 ], range_vals[ 1 ] )


class validateThread( QThread ): class validateThread( QThread ):
def __init__( self, parentThread, parentObject, vlayer, mySelection ): def __init__( self, parentThread, parentObject, vlayer, mySelection, myName, myEncoding, myNewShape ):
QThread.__init__( self, parentThread ) QThread.__init__( self, parentThread )
self.parent = parentObject self.parent = parentObject
self.running = False self.running = False
self.vlayer = vlayer self.vlayer = vlayer
self.mySelection = mySelection self.mySelection = mySelection
self.myName = myName
self.myEncoding = myEncoding
self.writeShape = myNewShape


def run( self ): def run( self ):
self.running = True self.running = True
output = self.check_geometry( self.vlayer ) success = self.check_geometry( self.vlayer )
self.emit( SIGNAL( "runFinished(PyQt_PyObject)" ), output ) self.emit( SIGNAL( "runFinished(PyQt_PyObject)" ), success )


def stop(self): def stop(self):
self.running = False self.running = False
Expand Down Expand Up @@ -265,4 +315,30 @@ def check_geometry( self, vlayer ):
if not geom.isGeosEmpty(): if not geom.isGeosEmpty():
lstErrors.append((feat.id(), list(geom.validateGeometry()))) lstErrors.append((feat.id(), list(geom.validateGeometry())))
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nFeat ) self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nFeat )
return lstErrors
if self.writeShape:
fields = { 0 : QgsField( "FEAT_ID", QVariant.Int ),
1 : QgsField( "ERROR", QVariant.String ) }
writer = QgsVectorFileWriter( self.myName, self.myEncoding, fields,
QGis.WKBPoint, vlayer.crs() )
for rec in lstErrors:
if len(rec[1]) < 1:
continue
for err in rec[1]:
fidItem = str(rec[0])
message = err.what()
if err.hasWhere():
locErr = err.where()
xP = locErr.x()
yP = locErr.y()
myPoint = QgsPoint( xP, yP )
geometry = QgsGeometry().fromPoint( myPoint )
ft = QgsFeature()
ft.setGeometry( geometry )
ft.setAttributeMap( { 0 : QVariant( fidItem ),
1 : QVariant( message ) } )
writer.addFeature( ft )
del writer
return "writeShape"
else:
return lstErrors
13 changes: 11 additions & 2 deletions python/plugins/fTools/tools/doVisual.py
Expand Up @@ -41,6 +41,15 @@ def __init__( self, iface, function ):
self.iface = iface self.iface = iface
self.setupUi( self ) self.setupUi( self )
self.myFunction = function self.myFunction = function

## Set object visibility to False if tool is not Check geometry
self.ckBoxShpError.hide()
self.browseShpError.hide()
self.lineEditShpError.hide()
self.label_6.hide()
self.line.hide()
self.buttonBox_2.setOrientation(Qt.Horizontal)

if self.myFunction == 2 or self.myFunction == 3: if self.myFunction == 2 or self.myFunction == 3:
QObject.connect( self.inShape, SIGNAL( "currentIndexChanged(QString)" ), self.update ) QObject.connect( self.inShape, SIGNAL( "currentIndexChanged(QString)" ), self.update )
self.manageGui() self.manageGui()
Expand Down Expand Up @@ -289,7 +298,7 @@ def basic_statistics( self, vlayer, myField ):
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nElement ) self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nElement )
else: # there is no selection, process the whole layer else: # there is no selection, process the whole layer
nFeat = vprovider.featureCount() nFeat = vprovider.featureCount()
if nFeat > 0: if nFeat > 0:
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), 0 ) self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), 0 )
self.emit( SIGNAL( "runRange(PyQt_PyObject)" ), ( 0, nFeat ) ) self.emit( SIGNAL( "runRange(PyQt_PyObject)" ), ( 0, nFeat ) )
vprovider.select( allAttrs ) vprovider.select( allAttrs )
Expand Down Expand Up @@ -355,7 +364,7 @@ def basic_statistics( self, vlayer, myField ):
else: # there is no selection, process the whole layer else: # there is no selection, process the whole layer
nFeat = vprovider.featureCount() nFeat = vprovider.featureCount()
uniqueVal = ftools_utils.getUniqueValuesCount( vlayer, index, False ) uniqueVal = ftools_utils.getUniqueValuesCount( vlayer, index, False )
if nFeat > 0: if nFeat > 0:
self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), 0 ) self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), 0 )
self.emit( SIGNAL( "runRange(PyQt_PyObject)" ), ( 0, nFeat ) ) self.emit( SIGNAL( "runRange(PyQt_PyObject)" ), ( 0, nFeat ) )
vprovider.select( allAttrs ) vprovider.select( allAttrs )
Expand Down

0 comments on commit 24e259b

Please sign in to comment.