Exemple #1
0
 def accept(self):
     self.buttonOk.setEnabled( False )
     if self.xMin.text() == "" or self.xMax.text() == "" or self.yMin.text() == "" or self.yMax.text() == "":
         QMessageBox.information(self, self.tr("Vector grid"), self.tr("Please specify valid extent coordinates"))
     elif self.outShape.text() == "":
         QMessageBox.information(self, self.tr("Vector grid"), self.tr("Please specify output shapefile"))
     else:
         try:
             boundBox = QgsRectangle(
             float( self.xMin.text() ),
             float( self.yMin.text() ),
             float( self.xMax.text() ),
             float( self.yMax.text() ) )
         except:
             QMessageBox.information(self, self.tr("Vector grid"), self.tr("Invalid extent coordinates entered"))
         xSpace = self.spnX.value()
         ySpace = self.spnY.value()
         if self.rdoPolygons.isChecked():
           polygon = True
         else:
           polygon = False
         self.outShape.clear()
         QApplication.setOverrideCursor(Qt.WaitCursor)
         self.compute( boundBox, xSpace, ySpace, polygon )
         QApplication.restoreOverrideCursor()
         addToTOC = QMessageBox.question(self, self.tr("Generate Vector Grid"), self.tr("Created output shapefile:\n%1\n\nWould you like to add the new layer to the TOC?").arg(unicode(self.shapefileName)), QMessageBox.Yes, QMessageBox.No, QMessageBox.NoButton)
         if addToTOC == QMessageBox.Yes:
             ftools_utils.addShapeToCanvas( self.shapefileName )
             self.populateLayers()
     self.progressBar.setValue( 0 )
     self.buttonOk.setEnabled( True )
 def accept(self):
     self.buttonOk.setEnabled( False )
     if self.xMin.text() == "" or self.xMax.text() == "" or self.yMin.text() == "" or self.yMax.text() == "":
         QMessageBox.information(self, self.tr("Vector grid"), self.tr("Please specify valid extent coordinates"))
     elif self.outShape.text() == "":
         QMessageBox.information(self, self.tr("Vector grid"), self.tr("Please specify output shapefile"))
     else:
         try:
             boundBox = QgsRectangle(
             float( self.xMin.text() ),
             float( self.yMin.text() ),
             float( self.xMax.text() ),
             float( self.yMax.text() ) )
         except:
             QMessageBox.information(self, self.tr("Vector grid"), self.tr("Invalid extent coordinates entered"))
         xSpace = self.spnX.value()
         ySpace = self.spnY.value()
         if self.rdoPolygons.isChecked(): polygon = True
         else: polygon = False
         self.outShape.clear()
         self.compute( boundBox, xSpace, ySpace, polygon )
         addToTOC = QMessageBox.question(self, self.tr("Generate Vector Grid"), self.tr("Created output shapefile:\n%1\n\nWould you like to add the new layer to the TOC?").arg(unicode(self.shapefileName)), QMessageBox.Yes, QMessageBox.No, QMessageBox.NoButton)
         if addToTOC == QMessageBox.Yes:
             ftools_utils.addShapeToCanvas( self.shapefileName )
             self.populateLayers()
     self.progressBar.setValue( 0 )
     self.buttonOk.setEnabled( True )
 def accept(self):
     if self.inShape.currentText() == "":
         QMessageBox.information(self, "Voronoi/Thiessen tesselation", "Please specify input point layer")
     elif self.outShape.text() == "":
         QMessageBox.information(self, "Voronoi/Thiessen tesselations", "Please specify output polygon shapefile")
     else:
         self.outShape.clear()
         self.vlayer = ftools_utils.getVectorLayerByName(self.inShape.currentText())
         self.voronoi_polygons()
         ftools_utils.addShapeToCanvas(self.shapefileName)
Exemple #4
0
 def accept(self):
     self.buttonOk.setEnabled(False)
     if self.inLine1.currentText() == "":
         QMessageBox.information(self, self.tr("Locate Line Intersections"), self.tr("Please specify input line layer"))
     elif self.outShape.text() == "":
         QMessageBox.information(self, self.tr("Locate Line Intersections"), self.tr("Please specify output shapefile"))
     elif self.inLine2.currentText() == "":
         QMessageBox.information(self, self.tr("Locate Line Intersections"), self.tr("Please specify line intersect layer"))
     elif self.inField1.currentText() == "":
         QMessageBox.information(self, self.tr("Locate Line Intersections"), self.tr("Please specify input unique ID field"))
     elif self.inField2.currentText() == "":
         QMessageBox.information(self, self.tr("Locate Line Intersections"), self.tr("Please specify intersect unique ID field"))
     else:
         line1 = self.inLine1.currentText()
         line2 = self.inLine2.currentText()
         field1 = self.inField1.currentText()
         field2 = self.inField2.currentText()
         outPath = self.outShape.text()
         self.outShape.clear()
         self.compute(line1, line2, field1, field2, outPath, self.progressBar)
         self.progressBar.setValue(100)
         if self.addToCanvasCheck.isChecked():
             addCanvasCheck = ftools_utils.addShapeToCanvas(unicode(outPath))
             if not addCanvasCheck:
                 QMessageBox.warning(self, self.tr("Geoprocessing"), self.tr("Error loading output shapefile:\n%s") % (unicode(outPath)))
             self.populateLayers()
         else:
             QMessageBox.information(self, self.tr("Generate Centroids"), self.tr("Created output shapefile:\n%s") % (unicode(outPath)))
     self.progressBar.setValue(0)
     self.buttonOk.setEnabled(True)
Exemple #5
0
 def accept(self):
     self.buttonOk.setEnabled(False)
     if not self.rdoCoordinates.isChecked() and self.inShape.currentText(
     ) == "":
         QMessageBox.information(self, self.tr("Generate Regular Points"),
                                 self.tr("Please specify input layer"))
     elif self.rdoCoordinates.isChecked() and (self.xMin.text() == ""
                                               or self.xMax.text() == ""
                                               or self.yMin.text() == ""
                                               or self.yMax.text() == ""):
         QMessageBox.information(
             self, self.tr("Generate Regular Points"),
             self.tr("Please properly specify extent coordinates"))
     elif self.outShape.text() == "":
         QMessageBox.information(self, self.tr("Generate Regular Points"),
                                 self.tr("Please specify output shapefile"))
     else:
         inName = self.inShape.currentText()
         outPath = self.outShape.text()
         self.outShape.clear()
         if self.rdoSpacing.isChecked():
             value = self.spnSpacing.value()
         else:
             value = self.spnNumber.value()
         if self.chkRandom.isChecked():
             offset = True
         else:
             offset = False
         if self.rdoBoundary.isChecked():
             mLayer = ftools_utils.getMapLayerByName(unicode(inName))
             boundBox = mLayer.extent()
             crs = mLayer.crs()
         else:
             boundBox = QgsRectangle(float(self.xMin.text()),
                                     float(self.yMin.text()),
                                     float(self.xMax.text()),
                                     float(self.yMax.text()))
             crs = self.mapCanvas.mapRenderer().destinationCrs()
             print crs.isValid()
             if not crs.isValid():
                 crs = None
         self.regularize(boundBox, outPath, offset, value,
                         self.rdoSpacing.isChecked(), self.spnInset.value(),
                         crs)
         if self.addToCanvasCheck.isChecked():
             addCanvasCheck = ftools_utils.addShapeToCanvas(
                 unicode(outPath))
             if not addCanvasCheck:
                 QMessageBox.warning(
                     self, self.tr("Generate Regular Points"),
                     self.tr("Error loading output shapefile:\n%s") %
                     (unicode(outPath)))
             self.populateLayers()
         else:
             QMessageBox.information(
                 self, self.tr("Generate Regular Points"),
                 self.tr("Created output shapefile:\n%s") %
                 (unicode(outPath)))
     self.progressBar.setValue(0)
     self.buttonOk.setEnabled(True)
Exemple #6
0
 def accept(self):
     self.buttonOk.setEnabled( False )
     if self.inPolygon.currentText() == "":
         QMessageBox.information(self, self.tr("Sum Line Lengths In Polyons"), self.tr("Please specify input polygon vector layer"))
     elif self.outShape.text() == "":
         QMessageBox.information(self, self.tr("Sum Line Lengths In Polyons"), self.tr("Please specify output shapefile"))
     elif self.inPoint.currentText() == "":
         QMessageBox.information(self, self.tr("Sum Line Lengths In Polyons"), self.tr("Please specify input line vector layer"))
     elif self.lnField.text() == "":
         QMessageBox.information(self, self.tr("Sum Line Lengths In Polyons"), self.tr("Please specify output length field"))
     else:
         inPoly = self.inPolygon.currentText()
         inLns = self.inPoint.currentText()
         inField = self.lnField.text()
         outPath = self.outShape.text()
         self.compute(inPoly, inLns, inField, outPath, self.progressBar)
         self.outShape.clear()
         if self.addToCanvasCheck.isChecked():
             addCanvasCheck = ftools_utils.addShapeToCanvas(unicode(outPath))
             if not addCanvasCheck:
                 QMessageBox.warning( self, self.tr("Sum line lengths"), self.tr( "Error loading output shapefile:\n%s" ) % ( unicode( outPath ) ))
             self.populateLayers()
         else:
             QMessageBox.information(self, self.tr("Sum line lengths"),self.tr("Created output shapefile:\n%s" ) % ( unicode( outPath )))
     self.progressBar.setValue(0)
     self.buttonOk.setEnabled( True )
    def accept(self):
        self.buttonOk.setEnabled(False)
        if self.inShape.currentText() == "":
            QMessageBox.information(self, self.tr("Coordinate statistics"),
                                    self.tr("No input vector layer specified"))
        elif self.outShape.text() == "":
            QMessageBox.information(self, self.tr("Coordinate statistics"),
                                    self.tr("Please specify output shapefile"))
        else:
            inName = self.inShape.currentText()
            outPath = self.outShape.text()

            self.compute(inName, self.weightField.currentText(),
                         self.sizeValue.value(),
                         self.uniqueField.currentText())
            self.progressBar.setValue(100)
            self.outShape.clear()
            if self.addToCanvasCheck.isChecked():
                addCanvasCheck = ftools_utils.addShapeToCanvas(
                    unicode(outPath))
                if not addCanvasCheck:
                    QMessageBox.warning(
                        self, self.tr("Coordinate statistics"),
                        self.tr("Error loading output shapefile:\n%s") %
                        (unicode(outPath)))
                self.populateLayers()
            else:
                QMessageBox.information(
                    self, self.tr("Coordinate statistics"),
                    self.tr("Created output shapefile:\n%s") %
                    (unicode(outPath)))
        self.progressBar.setValue(0)
        self.buttonOk.setEnabled(True)
Exemple #8
0
 def accept(self):
     self.buttonOk.setEnabled(False)
     if self.inPolygon.currentText() == "":
         QMessageBox.information(self, self.tr("Sum Line Lengths In Polyons"), self.tr("Please specify input polygon vector layer"))
     elif self.outShape.text() == "":
         QMessageBox.information(self, self.tr("Sum Line Lengths In Polyons"), self.tr("Please specify output shapefile"))
     elif self.inPoint.currentText() == "":
         QMessageBox.information(self, self.tr("Sum Line Lengths In Polyons"), self.tr("Please specify input line vector layer"))
     elif self.lnField.text() == "":
         QMessageBox.information(self, self.tr("Sum Line Lengths In Polyons"), self.tr("Please specify output length field"))
     else:
         inPoly = self.inPolygon.currentText()
         inLns = self.inPoint.currentText()
         inField = self.lnField.text()
         outPath = self.outShape.text()
         self.compute(inPoly, inLns, inField, outPath, self.progressBar)
         self.outShape.clear()
         if self.addToCanvasCheck.isChecked():
             addCanvasCheck = ftools_utils.addShapeToCanvas(unicode(outPath))
             if not addCanvasCheck:
                 QMessageBox.warning(self, self.tr("Sum line lengths"), self.tr("Error loading output shapefile:\n%s") % (unicode(outPath)))
             self.populateLayers()
         else:
             QMessageBox.information(self, self.tr("Sum line lengths"), self.tr("Created output shapefile:\n%s") % (unicode(outPath)))
     self.progressBar.setValue(0)
     self.buttonOk.setEnabled(True)
Exemple #9
0
 def accept(self):
     self.buttonOk.setEnabled( False )
     if not self.rdoCoordinates.isChecked() and self.inShape.currentText() == "":
         QMessageBox.information(self, self.tr("Generate Regular Points"), self.tr("Please specify input layer"))
     elif self.rdoCoordinates.isChecked() and (self.xMin.text() == "" or self.xMax.text() == "" or self.yMin.text() == "" or self.yMax.text() == ""):
         QMessageBox.information(self, self.tr("Generate Regular Points"), self.tr("Please properly specify extent coordinates"))
     elif self.outShape.text() == "":
         QMessageBox.information(self, self.tr("Generate Regular Points"), self.tr("Please specify output shapefile"))
     else:
         inName = self.inShape.currentText()
         outPath = self.outShape.text()
         self.outShape.clear()
         if self.rdoSpacing.isChecked(): value = self.spnSpacing.value()
         else: value = self.spnNumber.value()
         if self.chkRandom.isChecked(): offset = True
         else: offset = False
         if self.rdoBoundary.isChecked():
             mLayer = ftools_utils.getMapLayerByName(unicode(inName))
             boundBox = mLayer.extent()
             crs = mLayer.crs()
         else:
             boundBox = QgsRectangle(float(self.xMin.text()), float(self.yMin.text()), float(self.xMax.text()), float(self.yMax.text()))
             crs = self.mapCanvas.mapRenderer().destinationCrs()
             print crs.isValid()
             if not crs.isValid(): crs = None
         self.regularize(boundBox, outPath, offset, value, self.rdoSpacing.isChecked(), self.spnInset.value(), crs)
         if self.addToCanvasCheck.isChecked():
             addCanvasCheck = ftools_utils.addShapeToCanvas(unicode(outPath))
             if not addCanvasCheck:
                 QMessageBox.warning( self, self.tr("Generate Regular Points"), self.tr( "Error loading output shapefile:\n%s" ) % ( unicode( outPath ) ))
             self.populateLayers()
         else:
             QMessageBox.information(self, self.tr("Generate Regular Points"),self.tr("Created output shapefile:\n%s" ) % ( unicode( outPath )))
     self.progressBar.setValue(0)
     self.buttonOk.setEnabled( True )
Exemple #10
0
 def accept(self):
     self.buttonOk.setEnabled(False)
     if self.xMin.text() == "" or self.xMax.text() == "" or self.yMin.text() == "" or self.yMax.text() == "":
         QMessageBox.information(self, self.tr("Vector grid"), self.tr("Please specify valid extent coordinates"))
     elif self.outShape.text() == "":
         QMessageBox.information(self, self.tr("Vector grid"), self.tr("Please specify output shapefile"))
     else:
         try:
             boundBox = QgsRectangle(
                 float(self.xMin.text()),
                 float(self.yMin.text()),
                 float(self.xMax.text()),
                 float(self.yMax.text()))
         except:
             QMessageBox.information(self, self.tr("Vector grid"), self.tr("Invalid extent coordinates entered"))
         xSpace = self.spnX.value()
         ySpace = self.spnY.value()
         if self.rdoPolygons.isChecked():
             polygon = True
         else:
             polygon = False
         self.outShape.clear()
         QApplication.setOverrideCursor(Qt.WaitCursor)
         self.compute(boundBox, xSpace, ySpace, polygon)
         QApplication.restoreOverrideCursor()
         if self.addToCanvasCheck.isChecked():
             addCanvasCheck = ftools_utils.addShapeToCanvas(unicode(self.shapefileName))
             if not addCanvasCheck:
                 QMessageBox.warning(self, self.tr("Generate Vector Grid"), self.tr("Error loading output shapefile:\n%s") % (unicode(self.shapefileName)))
             self.populateLayers()
         else:
             QMessageBox.information(self, self.tr("Generate Vector Grid"), self.tr("Created output shapefile:\n%s") % (unicode(self.shapefileName)))
     self.progressBar.setValue(0)
     self.buttonOk.setEnabled(True)
Exemple #11
0
 def accept(self):
     self.buttonOk.setEnabled( False )
     if self.xMin.text() == "" or self.xMax.text() == "" or self.yMin.text() == "" or self.yMax.text() == "":
         QMessageBox.information(self, self.tr("Vector grid"), self.tr("Please specify valid extent coordinates"))
     elif self.outShape.text() == "":
         QMessageBox.information(self, self.tr("Vector grid"), self.tr("Please specify output shapefile"))
     else:
         try:
             boundBox = QgsRectangle(
             float( self.xMin.text() ),
             float( self.yMin.text() ),
             float( self.xMax.text() ),
             float( self.yMax.text() ) )
         except:
             QMessageBox.information(self, self.tr("Vector grid"), self.tr("Invalid extent coordinates entered"))
         xSpace = self.spnX.value()
         ySpace = self.spnY.value()
         if self.rdoPolygons.isChecked():
           polygon = True
         else:
           polygon = False
         self.outShape.clear()
         QApplication.setOverrideCursor(Qt.WaitCursor)
         self.compute( boundBox, xSpace, ySpace, polygon )
         QApplication.restoreOverrideCursor()
         if self.addToCanvasCheck.isChecked():
             addCanvasCheck = ftools_utils.addShapeToCanvas(unicode(self.shapefileName))
             if not addCanvasCheck:
                 QMessageBox.warning( self, self.tr("Generate Vector Grid"), self.tr( "Error loading output shapefile:\n%s" ) % ( unicode( self.shapefileName ) ))
             self.populateLayers()
         else:
             QMessageBox.information(self, self.tr("Generate Vector Grid"),self.tr("Created output shapefile:\n%s" ) % ( unicode( self.shapefileName )))
     self.progressBar.setValue( 0 )
     self.buttonOk.setEnabled( True )
Exemple #12
0
 def runFinishedFromThread( self, success ):
   self.testThread.stop()
   self.buttonOk.setEnabled( True )
   extra = ""
   if success == "math_error":
     QMessageBox.warning( self, self.tr("Geometry"), self.tr("Error processing specified tolerance!\nPlease choose larger tolerance...") )
     if not QgsVectorFileWriter.deleteShapeFile( self.shapefileName ):
       QMessageBox.warning( self, self.tr("Geometry"), self.tr( "Unable to delete incomplete shapefile." ) )
   elif success == "attr_error":
     QMessageBox.warning( self, self.tr("Geometry"), self.tr("At least two features must have same attribute value!\nPlease choose another field...") )
     if not QgsVectorFileWriter.deleteShapeFile( self.shapefileName ):
       QMessageBox.warning( self, self.tr("Geometry"), self.tr( "Unable to delete incomplete shapefile." ) )
   else:
     if success == "valid_error":
       extra = self.tr("One or more features in the output layer may have invalid "
                     + "geometry, please check using the check validity tool\n")
       success = True
     self.cancel_close.setText( "Close" )
     QObject.disconnect( self.cancel_close, SIGNAL( "clicked()" ), self.cancelThread )
     if success:
       addToTOC = QMessageBox.question( self, self.tr("Geometry"),
         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 ),
         QMessageBox.Yes, QMessageBox.No, QMessageBox.NoButton )
       if addToTOC == QMessageBox.Yes:
         if not ftools_utils.addShapeToCanvas( unicode( self.shapefileName ) ):
           QMessageBox.warning( self, self.tr("Geoprocessing"), self.tr( "Error loading output shapefile:\n%1" ).arg( unicode( self.shapefileName ) ))
     else:
       QMessageBox.warning( self, self.tr("Geometry"), self.tr( "Error writing output shapefile." ) )
Exemple #13
0
 def accept(self):
     self.buttonOk.setEnabled( False )
     if self.inLine1.currentText() == "":
         QMessageBox.information(self, self.tr("Locate Line Intersections"), self.tr("Please specify input line layer") )
     elif self.outShape.text() == "":
         QMessageBox.information(self, self.tr("Locate Line Intersections"), self.tr("Please specify output shapefile") )
     elif self.inLine2.currentText() == "":
         QMessageBox.information(self, self.tr("Locate Line Intersections"), self.tr("Please specify line intersect layer") )
     elif self.inField1.currentText() == "":
         QMessageBox.information(self, self.tr("Locate Line Intersections"), self.tr("Please specify input unique ID field") )
     elif self.inField2.currentText() == "":
         QMessageBox.information(self, self.tr("Locate Line Intersections"), self.tr("Please specify intersect unique ID field") )
     else:
         line1 = self.inLine1.currentText()
         line2 = self.inLine2.currentText()
         field1 = self.inField1.currentText()
         field2 = self.inField2.currentText()
         outPath = self.outShape.text()
         self.outShape.clear()
         self.compute(line1, line2, field1, field2, outPath, self.progressBar)
         self.progressBar.setValue(100)
         addToTOC = QMessageBox.question(self, self.tr("Generate Centroids"), self.tr("Created output point shapefile:\n%s\n\nWould you like to add the new layer to the TOC?") % ( outPath ), QMessageBox.Yes, QMessageBox.No, QMessageBox.NoButton)
         if addToTOC == QMessageBox.Yes:
             if not ftools_utils.addShapeToCanvas( unicode( outPath ) ):
                 QMessageBox.warning( self, self.tr("Geoprocessing"), self.tr( "Error loading output shapefile:\n%s" ) % ( unicode( outPath ) ))
             self.populateLayers()
     self.progressBar.setValue(0)
     self.buttonOk.setEnabled( True )
Exemple #14
0
 def accept(self):
     self.buttonOk.setEnabled( False )
     if self.inLine1.currentText() == "":
         QMessageBox.information(self, self.tr("Locate Line Intersections"), self.tr("Please specify input line layer") )
     elif self.outShape.text() == "":
         QMessageBox.information(self, self.tr("Locate Line Intersections"), self.tr("Please specify output shapefile") )
     elif self.inLine2.currentText() == "":
         QMessageBox.information(self, self.tr("Locate Line Intersections"), self.tr("Please specify line intersect layer") )
     elif self.inField1.currentText() == "":
         QMessageBox.information(self, self.tr("Locate Line Intersections"), self.tr("Please specify input unique ID field") )
     elif self.inField2.currentText() == "":
         QMessageBox.information(self, self.tr("Locate Line Intersections"), self.tr("Please specify intersect unique ID field") )
     else:
         line1 = self.inLine1.currentText()
         line2 = self.inLine2.currentText()
         field1 = self.inField1.currentText()
         field2 = self.inField2.currentText()
         outPath = self.outShape.text()
         self.outShape.clear()
         self.compute(line1, line2, field1, field2, outPath, self.progressBar)
         self.progressBar.setValue(100)
         addToTOC = QMessageBox.question(self, self.tr("Generate Centroids"), self.tr("Created output point shapefile:\n%1\n\nWould you like to add the new layer to the TOC?").arg( outPath ), QMessageBox.Yes, QMessageBox.No, QMessageBox.NoButton)
         if addToTOC == QMessageBox.Yes:
             if not ftools_utils.addShapeToCanvas( unicode( outPath ) ):
                 QMessageBox.warning( self, self.tr("Geoprocessing"), self.tr( "Error loading output shapefile:\n%1" ).arg( unicode( outPath ) ))
     self.progressBar.setValue(0)
     self.buttonOk.setEnabled( True )
 def runFinishedFromThread(self, success):
     self.testThread.stop()
     self.buttonOk.setEnabled(True)
     extra = ""
     if success == "math_error":
         QMessageBox.warning(
             self, self.tr("Geometry"),
             self.
             tr("Error processing specified tolerance!\nPlease choose larger tolerance..."
                ))
         if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
             QMessageBox.warning(
                 self, self.tr("Geometry"),
                 self.tr("Unable to delete incomplete shapefile."))
     elif success == "attr_error":
         QMessageBox.warning(
             self, self.tr("Geometry"),
             self.
             tr("At least two features must have same attribute value!\nPlease choose another field..."
                ))
         if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
             QMessageBox.warning(
                 self, self.tr("Geometry"),
                 self.tr("Unable to delete incomplete shapefile."))
     else:
         if success == "valid_error":
             extra = self.tr(
                 "One or more features in the output layer may have invalid "
                 + "geometry, please check using the check validity tool\n")
             success = True
         self.cancel_close.setText("Close")
         QObject.disconnect(self.cancel_close, SIGNAL("clicked()"),
                            self.cancelThread)
         if success:
             if (self.myFunction == 5
                     and self.chkWriteShapefile.isChecked()
                 ) or self.myFunction != 5:
                 addToTOC = QMessageBox.question(
                     self, self.tr("Geometry"),
                     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),
                     QMessageBox.Yes, QMessageBox.No, QMessageBox.NoButton)
                 if addToTOC == QMessageBox.Yes:
                     if not ftools_utils.addShapeToCanvas(
                             unicode(self.shapefileName)):
                         QMessageBox.warning(
                             self, self.tr("Geometry"),
                             self.tr(
                                 "Error loading output shapefile:\n%1").arg(
                                     unicode(self.shapefileName)))
                     self.populateLayers()
             else:
                 QMessageBox.information(
                     self, self.tr("Geometry"),
                     self.tr("Layer '%1' updated").arg(
                         self.inShape.currentText()))
         else:
             QMessageBox.warning(self, self.tr("Geometry"),
                                 self.tr("Error writing output shapefile."))
Exemple #16
0
  def processingFinished( self ):
    self.stopProcessing()

    if self.chkAddToCanvas.isChecked():
      if not ftools_utils.addShapeToCanvas( unicode( self.outFileName ) ):
        QMessageBox.warning( self, self.tr( "Merging" ), self.tr( "Error loading output shapefile:\n%1" ).arg( unicode( self.outFileName ) ) )

    self.restoreGui()
Exemple #17
0
  def processingFinished( self ):
    self.stopProcessing()

    if self.chkAddToCanvas.isChecked():
      if not ftools_utils.addShapeToCanvas( unicode( self.outFileName ) ):
        QMessageBox.warning( self, self.tr( "Merging" ), self.tr( "Error loading output shapefile:\n%1" ).arg( unicode( self.outFileName ) ) )

    self.restoreGui()
Exemple #18
0
 def accept(self):
     self.buttonOk.setEnabled(False)
     if self.inShape.currentText() == "":
         QMessageBox.information(self, self.tr("Random Points"),
                                 self.tr("No input layer specified"))
     elif self.outShape.text() == "":
         QMessageBox.information(self, self.tr("Random Points"),
                                 self.tr("Please specify output shapefile"))
     else:
         inName = self.inShape.currentText()
         self.progressBar.setValue(1)
         outPath = self.outShape.text()
         self.progressBar.setValue(2.5)
         outName = ftools_utils.getShapefileName(outPath)
         self.progressBar.setValue(5)
         mLayer = ftools_utils.getMapLayerByName(unicode(inName))
         if mLayer.type() == mLayer.VectorLayer:
             inLayer = ftools_utils.getVectorLayerByName(unicode(inName))
             if self.rdoUnstratified.isChecked():
                 design = self.tr("unstratified")
                 value = self.spnUnstratified.value()
             elif self.rdoStratified.isChecked():
                 design = self.tr("stratified")
                 value = self.spnStratified.value()
             elif self.rdoDensity.isChecked():
                 design = self.tr("density")
                 value = self.spnDensity.value()
             else:
                 design = self.tr("field")
                 value = unicode(self.cmbField.currentText())
         elif mLayer.type() == mLayer.RasterLayer:
             inLayer = ftools_utils.getRasterLayerByName(unicode(inName))
             design = self.tr("unstratified")
             value = self.spnUnstratified.value()
         else:
             QMessageBox.information(self, self.tr("Random Points"),
                                     self.tr("Unknown layer type..."))
         minimum = 0.00
         self.progressBar.setValue(10)
         if self.randomize(inLayer, outPath, minimum, design, value):
             self.progressBar.setValue(100)
             self.outShape.clear()
             if self.addToCanvasCheck.isChecked():
                 addCanvasCheck = ftools_utils.addShapeToCanvas(
                     unicode(outPath))
                 if not addCanvasCheck:
                     QMessageBox.warning(
                         self, self.tr("Random Points"),
                         self.tr("Error loading output shapefile:\n%s") %
                         (unicode(outPath)))
                 self.populateLayers()
             else:
                 QMessageBox.information(
                     self, self.tr("Random Points"),
                     self.tr("Created output shapefile:\n%s") %
                     (unicode(outPath)))
     self.progressBar.setValue(0)
     self.buttonOk.setEnabled(True)
    def processFinished(self):
        self.stopProcessing()
        if self.addToCanvasCheck.isChecked():
            addCanvasCheck = ftools_utils.addShapeToCanvas(unicode(self.outShape.text()))
            if not addCanvasCheck:
                QMessageBox.warning( self, self.tr("Count Points in Polygon"), self.tr( "Error loading output shapefile:\n%s" ) % ( unicode( self.outShape.text() ) ))
            self.populateLayers()
        else:
            QMessageBox.information(self, self.tr("Count Points in Polygon"),self.tr("Created output shapefile:\n%s" ) % ( unicode( self.outShape.text() )))

        self.restoreGui()
    def processFinished(self):
        self.stopProcessing()
        if self.addToCanvasCheck.isChecked():
            addCanvasCheck = ftools_utils.addShapeToCanvas(unicode(self.outShape.text()))
            if not addCanvasCheck:
                QMessageBox.warning(self, self.tr("Count Points in Polygon"), self.tr("Error loading output shapefile:\n%s") % (unicode(self.outShape.text())))
            self.populateLayers()
        else:
            QMessageBox.information(self, self.tr("Count Points in Polygon"), self.tr("Created output shapefile:\n%s") % (unicode(self.outShape.text())))

        self.restoreGui()
Exemple #21
0
 def runFinishedFromThread(self, success):
     self.testThread.stop()
     self.buttonOk.setEnabled(True)
     extra = ""
     if success == "math_error":
         QMessageBox.warning(
             self,
             self.tr("Geometry"),
             self.tr("Error processing specified tolerance!\nPlease choose larger tolerance..."),
         )
         if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
             QMessageBox.warning(self, self.tr("Geometry"), self.tr("Unable to delete incomplete shapefile."))
     elif success == "attr_error":
         QMessageBox.warning(
             self,
             self.tr("Geometry"),
             self.tr("At least two features must have same attribute value!\nPlease choose another field..."),
         )
         if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
             QMessageBox.warning(self, self.tr("Geometry"), self.tr("Unable to delete incomplete shapefile."))
     else:
         if success == "valid_error":
             extra = self.tr(
                 "One or more features in the output layer may have invalid "
                 + "geometry, please check using the check validity tool\n"
             )
             success = True
         self.cancel_close.setText("Close")
         QObject.disconnect(self.cancel_close, SIGNAL("clicked()"), self.cancelThread)
         if success:
             if (self.myFunction == 5 and self.chkWriteShapefile.isChecked()) or self.myFunction != 5:
                 if self.addToCanvasCheck.isChecked():
                     addCanvasCheck = ftools_utils.addShapeToCanvas(unicode(self.shapefileName))
                     if not addCanvasCheck:
                         QMessageBox.warning(
                             self,
                             self.tr("Geometry"),
                             self.tr("Error loading output shapefile:\n%s") % (unicode(self.shapefileName)),
                         )
                     self.populateLayers()
                 else:
                     QMessageBox.information(
                         self,
                         self.tr("Geometry"),
                         self.tr("Created output shapefile:\n%s\n%s") % (unicode(self.shapefileName), extra),
                     )
             else:
                 QMessageBox.information(
                     self, self.tr("Geometry"), self.tr("Layer '{0}' updated").format(self.inShape.currentText())
                 )
         else:
             QMessageBox.warning(self, self.tr("Geometry"), self.tr("Error writing output shapefile."))
    def add_new_layer3D(self):
        # fetch reference grid from listReferenceGrid
        ReferenceGridLayerName = self.listReferenceGrid.currentText()
        if not ReferenceGridLayerName == "":
            ReferenceGridLayer = ftools_utils.getMapLayerByName(
                unicode(ReferenceGridLayerName))

        # Copy reference grid to shapefile to user defined location
        OutFileName, Encoding = ftools_utils.saveDialog(self)
        if (OutFileName, OutFileName) == (None, None):
            return ()

        # write new layer to shapefile
        ftools_utils.writeVectorLayerToShape(ReferenceGridLayer, OutFileName,
                                             self.encoding)

        # get new layer name
        file_info = QFileInfo(OutFileName)
        if file_info.exists():
            newLayerName = file_info.completeBaseName()

        # check whether this layer name is already in the 3D list
        if len(self.listLayers3D.findItems(newLayerName,
                                           Qt.MatchFixedString)) != 0:
            QMessageBox.information(
                self, self.tr("Gridder"),
                self.tr("This layer is already in the list."))
            return ()

        # Load new layer into map canvas ...
        for (name,
             layer) in QgsMapLayerRegistry.instance().mapLayers().iteritems():
            # Note : reload() doesn't work.
            if layer.source() == self.OutFileName:
                QgsMapLayerRegistry.instance().removeMapLayers(layer.id())
        ftools_utils.addShapeToCanvas(OutFileName)

        # add new layer to listLayers3D
        self.listLayers3D.addItem(newLayerName)
Exemple #23
0
 def runFinishedFromThread(self, success):
     self.testThread.stop()
     QApplication.restoreOverrideCursor()
     self.buttonOk.setEnabled(True)
     if success == "writeShape":
         extra = ""
         if self.addToCanvasCheck.isChecked():
             addCanvasCheck = ftools_utils.addShapeToCanvas(
                 unicode(self.shapefileName))
             if not addCanvasCheck:
                 QMessageBox.warning(
                     self, self.tr("Geometry"),
                     self.tr("Error loading output shapefile:\n%s") %
                     (unicode(self.shapefileName)))
         else:
             QMessageBox.information(
                 self, self.tr("Geometry"),
                 self.tr("Created output shapefile:\n%s\n%s") %
                 (unicode(self.shapefileName), extra))
     else:
         self.tblUnique.setColumnCount(2)
         count = 0
         for rec in success:
             if len(rec[1]) < 1:
                 continue
             where = None
             for err in rec[1]:  # for each error we find
                 self.tblUnique.insertRow(count)
                 fidItem = QTableWidgetItem(str(rec[0]))
                 self.tblUnique.setItem(count, 0, fidItem)
                 message = err.what()
                 errItem = QTableWidgetItem(message)
                 if err.hasWhere(
                 ):  # if there is a location associated with the error
                     errItem.setData(Qt.UserRole, 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")
     QObject.disconnect(self.cancel_close, SIGNAL("clicked()"),
                        self.cancelThread)
     return True
Exemple #24
0
    def add_new_layer3D(self):
	# fetch reference grid from listReferenceGrid
	ReferenceGridLayerName = self.listReferenceGrid.currentText()
        if not ReferenceGridLayerName == "":
            ReferenceGridLayer = ftools_utils.getMapLayerByName( unicode( ReferenceGridLayerName ) )

	# Copy reference grid to shapefile to user defined location
	OutFileName, Encoding = ftools_utils.saveDialog( self )
	if (OutFileName, OutFileName) == (None, None) :
	    return()

	# write new layer to shapefile
	ftools_utils.writeVectorLayerToShape( ReferenceGridLayer, OutFileName, self.encoding )


	# get new layer name
	file_info = QFileInfo( OutFileName )
	if file_info.exists():
	    newLayerName = file_info.completeBaseName()

	# check whether this layer name is already in the 3D list
	if len(self.listLayers3D.findItems(newLayerName,Qt.MatchFixedString)) != 0 : 
	    QMessageBox.information(self, self.tr("Gridder"), 
		    self.tr("This layer is already in the list."))
	    return()


	# Load new layer into map canvas ...
	for (name,layer) in	QgsMapLayerRegistry.instance().mapLayers().iteritems():
	    # Note : reload() doesn't work.
	    if layer.source()==self.OutFileName:
		QgsMapLayerRegistry.instance().removeMapLayers( layer.id() )
	ftools_utils.addShapeToCanvas( OutFileName )
        
	# add new layer to listLayers3D
	self.listLayers3D.addItem(newLayerName)
Exemple #25
0
 def accept(self):
     self.buttonOk.setEnabled( False )
     if self.inShape.currentText() == "":
         QMessageBox.information(self, self.tr("Random Points"), self.tr("No input layer specified"))
     elif self.outShape.text() == "":
         QMessageBox.information(self, self.tr("Random Points"), self.tr("Please specify output shapefile"))
     else:
         inName = self.inShape.currentText()
         self.progressBar.setValue(1)
         outPath = self.outShape.text()
         self.progressBar.setValue(2.5)
         outName = ftools_utils.getShapefileName( outPath )
         self.progressBar.setValue(5)
         mLayer = ftools_utils.getMapLayerByName(unicode(inName))
         if mLayer.type() == mLayer.VectorLayer:
             inLayer = ftools_utils.getVectorLayerByName(unicode(inName))
             if self.rdoUnstratified.isChecked():
                 design = self.tr("unstratified")
                 value = self.spnUnstratified.value()
             elif self.rdoStratified.isChecked():
                 design = self.tr("stratified")
                 value = self.spnStratified.value()
             elif self.rdoDensity.isChecked():
                 design = self.tr("density")
                 value = self.spnDensity.value()
             else:
                 design = self.tr("field")
                 value = unicode(self.cmbField.currentText())
         elif mLayer.type() == mLayer.RasterLayer:
             inLayer = ftools_utils.getRasterLayerByName(unicode(inName))
             design = self.tr("unstratified")
             value = self.spnUnstratified.value()
         else:
             QMessageBox.information(self, self.tr("Random Points"), self.tr("Unknown layer type..."))
         minimum = 0.00
         self.progressBar.setValue(10)
         if self.randomize(inLayer, outPath, minimum, design, value):
           self.progressBar.setValue(100)
           self.outShape.clear()
           if self.addToCanvasCheck.isChecked():
             addCanvasCheck = ftools_utils.addShapeToCanvas(unicode(outPath))
             if not addCanvasCheck:
                 QMessageBox.warning( self, self.tr("Random Points"), self.tr( "Error loading output shapefile:\n%s" ) % ( unicode( outPath ) ))
             self.populateLayers()
           else:
             QMessageBox.information(self, self.tr("Random Points"),self.tr("Created output shapefile:\n%s" ) % ( unicode( outPath )))
     self.progressBar.setValue(0)
     self.buttonOk.setEnabled( True )
Exemple #26
0
 def accept(self):
     self.buttonOk.setEnabled(False)
     if self.inLine1.currentText() == "":
         QMessageBox.information(self, self.tr("Locate Line Intersections"),
                                 self.tr("Please specify input line layer"))
     elif self.outShape.text() == "":
         QMessageBox.information(self, self.tr("Locate Line Intersections"),
                                 self.tr("Please specify output shapefile"))
     elif self.inLine2.currentText() == "":
         QMessageBox.information(
             self, self.tr("Locate Line Intersections"),
             self.tr("Please specify line intersect layer"))
     elif self.inField1.currentText() == "":
         QMessageBox.information(
             self, self.tr("Locate Line Intersections"),
             self.tr("Please specify input unique ID field"))
     elif self.inField2.currentText() == "":
         QMessageBox.information(
             self, self.tr("Locate Line Intersections"),
             self.tr("Please specify intersect unique ID field"))
     else:
         line1 = self.inLine1.currentText()
         line2 = self.inLine2.currentText()
         field1 = self.inField1.currentText()
         field2 = self.inField2.currentText()
         outPath = self.outShape.text()
         self.outShape.clear()
         self.compute(line1, line2, field1, field2, outPath,
                      self.progressBar)
         self.progressBar.setValue(100)
         if self.addToCanvasCheck.isChecked():
             addCanvasCheck = ftools_utils.addShapeToCanvas(
                 unicode(outPath))
             if not addCanvasCheck:
                 QMessageBox.warning(
                     self, self.tr("Geoprocessing"),
                     self.tr("Error loading output shapefile:\n%s") %
                     (unicode(outPath)))
             self.populateLayers()
         else:
             QMessageBox.information(
                 self, self.tr("Generate Centroids"),
                 self.tr("Created output shapefile:\n%s") %
                 (unicode(outPath)))
     self.progressBar.setValue(0)
     self.buttonOk.setEnabled(True)
Exemple #27
0
  def processFinished( self, pointsCount ):
    self.stopProcessing()

    if self.myFunction == 1:
      QMessageBox.information( self, self.tr( "Simplify results" ),
                               self.tr( "There were %d vertices in original dataset which\nwere reduced to %d vertices after simplification" ) % ( pointsCount[ 0 ], pointsCount[ 1 ] ) )

    self.restoreGui()

    if self.chkAddToCanvas.isEnabled() and self.chkAddToCanvas.isChecked():
      if not ftools_utils.addShapeToCanvas( unicode( self.shapeFileName ) ):
        QMessageBox.warning( self, self.tr( "Error" ),
                             self.tr( "Error loading output shapefile:\n%s" ) % ( unicode( self.shapeFileName ) ) )
      self.populateLayers()

    QMessageBox.information( self, self.tr( "Finished" ), self.tr( "Processing completed." ) )
    self.iface.mapCanvas().refresh()
Exemple #28
0
    def processFinished(self, pointsCount):
        self.stopProcessing()

        if self.myFunction == 1:
            QMessageBox.information(self, self.tr("Simplify results"),
                                    self.tr("There were %d vertices in original dataset which\nwere reduced to %d vertices after simplification") % (pointsCount[0], pointsCount[1]))

        self.restoreGui()

        if self.chkAddToCanvas.isEnabled() and self.chkAddToCanvas.isChecked():
            if not ftools_utils.addShapeToCanvas(unicode(self.shapeFileName)):
                QMessageBox.warning(self, self.tr("Error"),
                                    self.tr("Error loading output shapefile:\n%s") % (unicode(self.shapeFileName)))
            self.populateLayers()

        QMessageBox.information(self, self.tr("Finished"), self.tr("Processing completed."))
        self.iface.mapCanvas().refresh()
Exemple #29
0
  def generalizationFinished( self, pointsCount ):
    self.stopProcessing()

    QMessageBox.information( self,
                             self.tr( "Simplify results" ),
                             self.tr( "There were %1 vertices in original dataset which\nwere reduced to %2 vertices after simplification" )
                             .arg( pointsCount[ 0 ] )
                             .arg( pointsCount[ 1 ] ) )

    self.restoreGui()
    if self.addToCanvasCheck.isEnabled() and self.addToCanvasCheck.isChecked():
      if not ftools_utils.addShapeToCanvas( unicode( self.shapefileName ) ):
        QMessageBox.warning( self, self.tr( "Merging" ),
                             self.tr( "Error loading output shapefile:\n%1" )
                             .arg( unicode( self.shapefileName ) ) )

    self.iface.mapCanvas().refresh()
Exemple #30
0
    def generalizationFinished(self, pointsCount):
        self.stopProcessing()

        QMessageBox.information(
            self, self.tr("Simplify results"),
            self.
            tr("There were %1 vertices in original dataset which\nwere reduced to %2 vertices after simplification"
               ).arg(pointsCount[0]).arg(pointsCount[1]))

        self.restoreGui()
        if self.addToCanvasCheck.isEnabled(
        ) and self.addToCanvasCheck.isChecked():
            if not ftools_utils.addShapeToCanvas(unicode(self.shapefileName)):
                QMessageBox.warning(
                    self, self.tr("Merging"),
                    self.tr("Error loading output shapefile:\n%1").arg(
                        unicode(self.shapefileName)))

        self.iface.mapCanvas().refresh()
Exemple #31
0
 def accept(self):
   self.buttonOk.setEnabled( False )
   if self.inShape.currentText() == "":
     QMessageBox.information(self, self.tr("Join Attributes"), self.tr("Please specify target vector layer"))
   elif self.outShape.text() == "":
     QMessageBox.information(self, self.tr("Join Attributes"), self.tr("Please specify output shapefile"))
   elif self.joinShape.currentText() == "" and self.rdoVector.isChecked():
     QMessageBox.information(self, self.tr("Join Attributes"), self.tr("Please specify join vector layer"))
   elif self.inField.currentText() == "":
     QMessageBox.information(self, self.tr("Join Attributes"), self.tr("Please specify target join field"))
   elif self.joinField.currentText() == "":
     QMessageBox.information(self, self.tr("Join Attributes"), self.tr("Please specify join field"))
   elif self.inTable.text() == "" and self.rdoTable.isChecked():
     QMessageBox.information(self, self.tr("Join Attributes"), self.tr("Please specify input table"))
   else:
     keep = self.rdoKeep.isChecked()
     inName = self.inShape.currentText()
     inField = self.inField.currentText()
     if self.rdoVector.isChecked():
       joinName = self.joinShape.currentText()
       useTable = False
     else:
       joinName = self.inTable.text()
       useTable = True
     joinField = self.joinField.currentText()
     outPath = self.outShape.text()
     encoding = self.cmbEncoding.currentText()
     QSettings().setValue( "/UI/encoding", encoding)
     res = self.compute(inName, inField, joinName, joinField, 
     outPath, keep, useTable, encoding, self.progressBar)
     self.outShape.clear()
     if res:
       addToTOC = QMessageBox.question(self, self.tr("Join Attributes"),
           self.tr("Created output shapefile:\n%1\n\nWould you like to add the new layer to the TOC?")
           .arg( unicode(self.shapefileName) ), QMessageBox.Yes, QMessageBox.No, QMessageBox.NoButton)
       if addToTOC == QMessageBox.Yes:
         if not ftools_utils.addShapeToCanvas( unicode( outPath ) ):
           QMessageBox.warning( self, self.tr("Geoprocessing"), self.tr( "Error loading output shapefile:\n%1" )
           .arg( unicode( outPath ) ))
   self.progressBar.setValue(0)
   self.buttonOk.setEnabled( True )
Exemple #32
0
 def runFinishedFromThread( self, success ):
   self.testThread.stop()
   QApplication.restoreOverrideCursor()
   self.buttonOk.setEnabled( True )
   if success == "writeShape":
     extra = ""
     addToTOC = QMessageBox.question( self, self.tr("Geometry"),
                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 ),
                QMessageBox.Yes, QMessageBox.No, QMessageBox.NoButton )
     if addToTOC == QMessageBox.Yes:
       if not ftools_utils.addShapeToCanvas( unicode( self.shapefileName ) ):
         QMessageBox.warning( self, self.tr( "Geometry"),
                              self.tr( "Error loading output shapefile:\n%1" ).arg( unicode( self.shapefileName ) ) )
   else:
     self.tblUnique.setColumnCount( 2 )
     count = 0
     for rec in success:
       if len(rec[1]) < 1:
         continue
       where = None
       for err in rec[1]: # for each error we find
         self.tblUnique.insertRow(count)
         fidItem = QTableWidgetItem( str(rec[0]) )
         self.tblUnique.setItem( count, 0, fidItem )
         message = err.what()
         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" )
   QObject.disconnect( self.cancel_close, SIGNAL( "clicked()" ), self.cancelThread )
   return True
Exemple #33
0
    def accept(self):
        self.buttonOk.setEnabled(False)
        if self.inShape.currentText() == "":
            QMessageBox.information(self, self.tr("Coordinate statistics"), self.tr("No input vector layer specified"))
        elif self.outShape.text() == "":
            QMessageBox.information(self, self.tr("Coordinate statistics"), self.tr("Please specify output shapefile"))
        else:
            inName = self.inShape.currentText()
            outPath = self.outShape.text()

            self.compute(inName, self.weightField.currentText(), self.sizeValue.value(), self.uniqueField.currentText())
            self.progressBar.setValue(100)
            self.outShape.clear()
            if self.addToCanvasCheck.isChecked():
                addCanvasCheck = ftools_utils.addShapeToCanvas(unicode(outPath))
                if not addCanvasCheck:
                    QMessageBox.warning(self, self.tr("Coordinate statistics"), self.tr("Error loading output shapefile:\n%s") % (unicode(outPath)))
                self.populateLayers()
            else:
                QMessageBox.information(self, self.tr("Coordinate statistics"), self.tr("Created output shapefile:\n%s") % (unicode(outPath)))
        self.progressBar.setValue(0)
        self.buttonOk.setEnabled(True)
Exemple #34
0
    def eliminate(self, inLayer, boundary, progressBar, outFileName=None):
        # keep references to the features to eliminate
        fidsToEliminate = inLayer.selectedFeaturesIds()
        fidsToProcess = inLayer.selectedFeaturesIds()

        if outFileName:  # user wants a new shape file to be created as result
            provider = inLayer.dataProvider()
            error = QgsVectorFileWriter.writeAsVectorFormat(
                inLayer, outFileName, provider.encoding(), inLayer.crs(),
                "ESRI Shapefile")

            if error != QgsVectorFileWriter.NoError:
                QtGui.QMessageBox.warning(
                    self, self.tr("Eliminate"),
                    self.tr("Error creating output file"))
                return None

            outLayer = QgsVectorLayer(
                outFileName,
                QtCore.QFileInfo(outFileName).completeBaseName(), "ogr")

        else:
            outLayer = inLayer
            outLayer.removeSelection(False)

        outLayer.startEditing()
        doCommit = True

        # ANALYZE
        start = 20.00
        progressBar.setValue(start)
        add = 80.00 / len(fidsToEliminate)

        lastLen = 0
        geomsToMerge = dict()

        # we go through the list and see if we find any polygons we can merge the selected with
        # if we have no success with some we merge and then restart the whole story
        while (lastLen != len(fidsToProcess)):  #check if we made any progress
            lastLen = len(fidsToProcess)
            fidsNotEliminated = []
            fidsToDelete = []

            #iterate over the polygons to eliminate
            for fid in fidsToProcess:
                feat = QgsFeature()

                if outLayer.featureAtId(fid, feat, True, False):
                    geom = feat.geometry()
                    bbox = geom.boundingBox()
                    outLayer.select(bbox, False)  # make a new selection
                    mergeWithFid = None
                    mergeWithGeom = None
                    max = 0

                    for selFid in outLayer.selectedFeaturesIds():
                        if fid != selFid:
                            #check if this feature is to be eliminated, too
                            try:
                                found = fidsToEliminate.index(selFid)
                            except ValueError:  #selFid is not in fidsToEliminate
                                # check wether the geometry to eliminate and the other geometry intersect
                                selFeat = QgsFeature()

                                if outLayer.featureAtId(
                                        selFid, selFeat, True, False):
                                    selGeom = selFeat.geometry()

                                    if geom.intersects(
                                            selGeom):  # we have a candidate
                                        iGeom = geom.intersection(selGeom)

                                        if boundary:
                                            selValue = iGeom.length()
                                        else:
                                            # we need a common boundary
                                            if 0 < iGeom.length():
                                                selValue = selGeom.area()
                                            else:
                                                selValue = 0

                                        if selValue > max:
                                            max = selValue
                                            mergeWithFid = selFid
                                            mergeWithGeom = QgsGeometry(
                                                selGeom
                                            )  # deep copy of the geometry

                    if mergeWithFid:  # a successful candidate
                        try:
                            geomList = geomsToMerge[mergeWithFid]
                        except KeyError:
                            geomList = [mergeWithGeom]

                        geomList.append(
                            QgsGeometry(geom))  # deep copy of the geom
                        geomsToMerge[mergeWithFid] = geomList
                        fidsToDelete.append(fid)

                        start = start + add
                        progressBar.setValue(start)
                    else:
                        fidsNotEliminated.append(fid)

            # PROCESS
            for aFid in geomsToMerge.iterkeys():
                geomList = geomsToMerge[aFid]

                if len(geomList) > 1:
                    for i in range(len(geomList)):
                        aGeom = geomList[i]

                        if i == 0:
                            newGeom = aGeom
                        else:
                            newGeom = newGeom.combine(aGeom)

                    # replace geometry in outLayer
                    if not outLayer.changeGeometry(aFid, newGeom):
                        QtGui.QMessageBox.warning(
                            self, self.tr("Eliminate"),
                            self.
                            tr("Could not replace geometry of feature with id "
                               ) + str(aFid))
                        doCommit = False
                        break

            # delete eliminated features
            for aFid in fidsToDelete:
                if not outLayer.deleteFeature(aFid):
                    QtGui.QMessageBox.warning(
                        self, self.tr("Eliminate"),
                        self.tr("Could not delete feature with id ") +
                        str(aFid))
                    doCommit = False
                    break
            # prepare array for the next loop
            fidsToProcess = fidsNotEliminated

        # SAVE CHANGES
        if doCommit:
            if not outLayer.commitChanges():
                QtGui.QMessageBox.warning(self, self.tr("Commit error"),
                                          self.tr("Commit Error"))
        else:
            outLayer.rollBack()

        if outFileName:
            if self.addToCanvasCheck.isChecked():
                ftools_utils.addShapeToCanvas(outFileName)
            else:
                QtGui.QMessageBox.information(
                    self, self.tr("Eliminate"),
                    self.tr("Created output shapefile:\n%1").arg(outFileName))

        # inform user
        if len(fidsNotEliminated) > 0:
            fidList = QtCore.QString()

            for fid in fidsNotEliminated:
                if not fidList.isEmpty():
                    fidList.append(", ")

                fidList.append(str(fid))

            QtGui.QMessageBox.information(
                self, self.tr("Eliminate"),
                self.tr("Could not eliminate features with these ids:\n%1").
                arg(fidList))

        self.iface.mapCanvas().refresh()
Exemple #35
0
    def eliminate(self, inLayer, boundary, progressBar, outFileName):
        # keep references to the features to eliminate
        fidsToEliminate = inLayer.selectedFeaturesIds()

        if outFileName:  # user wants a new shape file to be created as result
            provider = inLayer.dataProvider()
            error = QgsVectorFileWriter.writeAsVectorFormat(
                inLayer, outFileName, provider.encoding(), inLayer.crs(), "ESRI Shapefile"
            )

            if error != QgsVectorFileWriter.NoError:
                QtGui.QMessageBox.warning(self, self.tr("Eliminate"), self.tr("Error creating output file"))
                return None

            outLayer = QgsVectorLayer(outFileName, QtCore.QFileInfo(outFileName).completeBaseName(), "ogr")

        else:
            QtGui.QMessageBox.information(self, self.tr("Eliminate"), self.tr("Please specify output shapefile"))
            return None

        # delete features to be eliminated in outLayer
        outLayer.setSelectedFeatures(fidsToEliminate)
        outLayer.startEditing()

        if outLayer.deleteSelectedFeatures():
            if self.saveChanges(outLayer):
                outLayer.startEditing()
        else:
            QtGui.QMessageBox.warning(self, self.tr("Eliminate"), self.tr("Could not delete features"))
            return None

        # ANALYZE
        start = 20.00
        progressBar.setValue(start)
        add = 80.00 / len(fidsToEliminate)

        lastLen = 0
        geomsToMerge = dict()

        # we go through the list and see if we find any polygons we can merge the selected with
        # if we have no success with some we merge and then restart the whole story
        while lastLen != inLayer.selectedFeatureCount():  # check if we made any progress
            lastLen = inLayer.selectedFeatureCount()
            fidsToDeselect = []

            # iterate over the polygons to eliminate
            for fid2Eliminate in inLayer.selectedFeaturesIds():
                feat = QgsFeature()

                if inLayer.getFeatures(
                    QgsFeatureRequest().setFilterFid(fid2Eliminate).setSubsetOfAttributes([])
                ).nextFeature(feat):
                    geom2Eliminate = feat.geometry()
                    bbox = geom2Eliminate.boundingBox()
                    outLayer.select(bbox, False)  # make a new selection
                    mergeWithFid = None
                    mergeWithGeom = None
                    max = 0

                    for selFid in outLayer.selectedFeaturesIds():
                        selFeat = QgsFeature()

                        if outLayer.getFeatures(
                            QgsFeatureRequest().setFilterFid(selFid).setSubsetOfAttributes([])
                        ).nextFeature(selFeat):
                            selGeom = selFeat.geometry()

                            if geom2Eliminate.intersects(selGeom):  # we have a candidate
                                iGeom = geom2Eliminate.intersection(selGeom)

                                if boundary:
                                    selValue = iGeom.length()
                                else:
                                    # we need a common boundary
                                    if 0 < iGeom.length():
                                        selValue = selGeom.area()
                                    else:
                                        selValue = 0

                                if selValue > max:
                                    max = selValue
                                    mergeWithFid = selFid
                                    mergeWithGeom = QgsGeometry(selGeom)  # deep copy of the geometry

                    if mergeWithFid != None:  # a successful candidate
                        newGeom = mergeWithGeom.combine(geom2Eliminate)

                        if outLayer.changeGeometry(mergeWithFid, newGeom):
                            # write change back to disc
                            if self.saveChanges(outLayer):
                                outLayer.startEditing()
                            else:
                                return None

                            # mark feature as eliminated in inLayer
                            fidsToDeselect.append(fid2Eliminate)
                        else:
                            QtGui.QMessageBox.warning(
                                self,
                                self.tr("Eliminate"),
                                self.tr("Could not replace geometry of feature with id %1").arg(mergeWithFid),
                            )
                            return None

                        start = start + add
                        progressBar.setValue(start)
            # end for fid2Eliminate

            # deselect features that are already eliminated in inLayer
            for aFid in fidsToDeselect:
                inLayer.deselect(aFid, False)

        # end while

        if inLayer.selectedFeatureCount() > 0:
            # copy all features that could not be eliminated to outLayer
            if outLayer.addFeatures(inLayer.selectedFeatures()):
                # inform user
                fidList = QtCore.QString()

                for fid in inLayer.selectedFeaturesIds():
                    if not fidList.isEmpty():
                        fidList.append(", ")

                    fidList.append(str(fid))

                QtGui.QMessageBox.information(
                    self, self.tr("Eliminate"), self.tr("Could not eliminate features with these ids:\n%1").arg(fidList)
                )
            else:
                QtGui.QMessageBox.warning(self, self.tr("Eliminate"), self.tr("Could not add features"))

        # stop editing outLayer and commit any pending changes
        if not self.saveChanges(outLayer):
            return None

        if outFileName:
            if self.addToCanvasCheck.isChecked():
                ftools_utils.addShapeToCanvas(outFileName)
            else:
                QtGui.QMessageBox.information(
                    self, self.tr("Eliminate"), self.tr("Created output shapefile:\n%1").arg(outFileName)
                )

        self.iface.mapCanvas().refresh()
Exemple #36
0
    def eliminate(self, inLayer, boundary, progressBar, outFileName = None):
        # keep references to the features to eliminate
        fidsToEliminate = inLayer.selectedFeaturesIds()
        fidsToProcess = inLayer.selectedFeaturesIds()

        if outFileName: # user wants a new shape file to be created as result
            provider = inLayer.dataProvider()
            error = QgsVectorFileWriter.writeAsVectorFormat(inLayer, outFileName, provider.encoding(), inLayer.crs(), "ESRI Shapefile")

            if error != QgsVectorFileWriter.NoError:
                QtGui.QMessageBox.warning(self, self.tr("Eliminate"), self.tr("Error creating output file"))
                return None

            outLayer = QgsVectorLayer(outFileName, QtCore.QFileInfo(outFileName).completeBaseName(), "ogr")

        else:
            outLayer = inLayer
            outLayer.removeSelection(False)

        outLayer.startEditing()
        doCommit = True

        # ANALYZE
        start = 20.00
        progressBar.setValue(start)
        add = 80.00 / len(fidsToEliminate)

        lastLen = 0
        geomsToMerge = dict()

        # we go through the list and see if we find any polygons we can merge the selected with
        # if we have no success with some we merge and then restart the whole story
        while (lastLen != len(fidsToProcess)): #check if we made any progress
            lastLen = len(fidsToProcess)
            fidsNotEliminated = []
            fidsToDelete = []

            #iterate over the polygons to eliminate
            for fid in fidsToProcess:
                feat = QgsFeature()

                if outLayer.featureAtId(fid, feat, True, False):
                    geom = feat.geometry()
                    bbox = geom.boundingBox()
                    outLayer.select(bbox, False) # make a new selection
                    mergeWithFid = None
                    mergeWithGeom = None
                    max = 0

                    for selFid in outLayer.selectedFeaturesIds():
                        if fid != selFid:
                            #check if this feature is to be eliminated, too
                            try:
                                found = fidsToEliminate.index(selFid)
                            except ValueError: #selFid is not in fidsToEliminate
                                # check wether the geometry to eliminate and the other geometry intersect
                                selFeat = QgsFeature()

                                if outLayer.featureAtId(selFid, selFeat, True, False):
                                    selGeom = selFeat.geometry()

                                    if geom.intersects(selGeom): # we have a candidate
                                        iGeom = geom.intersection(selGeom)

                                        if boundary:
                                            selValue = iGeom.length()
                                        else:
                                            # we need a common boundary
                                            if 0 < iGeom.length():
                                                selValue = selGeom.area()
                                            else:
                                                selValue = 0

                                        if selValue > max:
                                            max = selValue
                                            mergeWithFid = selFid
                                            mergeWithGeom = QgsGeometry(selGeom) # deep copy of the geometry

                    if mergeWithFid: # a successful candidate
                        try:
                            geomList = geomsToMerge[mergeWithFid]
                        except KeyError:
                            geomList = [mergeWithGeom]

                        geomList.append(QgsGeometry(geom)) # deep copy of the geom
                        geomsToMerge[mergeWithFid] = geomList
                        fidsToDelete.append(fid)

                        start = start + add
                        progressBar.setValue(start)
                    else:
                        fidsNotEliminated.append(fid)

            # PROCESS
            for aFid in geomsToMerge.iterkeys():
                geomList = geomsToMerge[aFid]

                if len(geomList) > 1:
                    for i in range(len(geomList)):
                        aGeom = geomList[i]

                        if i == 0:
                            newGeom = aGeom
                        else:
                            newGeom = newGeom.combine(aGeom)

                    # replace geometry in outLayer
                    if not outLayer.changeGeometry(aFid, newGeom):
                        QtGui.QMessageBox.warning(self, self.tr("Eliminate"),
                            self.tr("Could not replace geometry of feature with id %1").arg( aFid ))
                        doCommit = False
                        break

            # delete eliminated features
            for aFid in fidsToDelete:
                if not outLayer.deleteFeature(aFid):
                    QtGui.QMessageBox.warning(self, self.tr("Eliminate"),
                        self.tr("Could not delete feature with id %1").arg( aFid ))
                    doCommit = False
                    break
            # prepare array for the next loop
            fidsToProcess = fidsNotEliminated

        # SAVE CHANGES
        if doCommit:
            if not outLayer.commitChanges():
                QtGui.QMessageBox.warning(self, self.tr("Commit error"), self.tr("Commit error"))
        else:
            outLayer.rollBack()

        if outFileName:
            if self.addToCanvasCheck.isChecked():
                ftools_utils.addShapeToCanvas(outFileName)
            else:
                QtGui.QMessageBox.information(self, self.tr("Eliminate"),
                    self.tr("Created output shapefile:\n%1").arg(outFileName))

        # inform user
        if len(fidsNotEliminated) > 0:
            fidList = QtCore.QString()

            for fid in fidsNotEliminated:
                if not fidList.isEmpty():
                    fidList.append(", ")

                fidList.append(str(fid))

            QtGui.QMessageBox.information(self, self.tr("Eliminate"),
                    self.tr("Could not eliminate features with these ids:\n%1").arg(fidList))

        self.iface.mapCanvas().refresh()
Exemple #37
0
 def accept(self):
     import ftools_utils
     self.ui.buttonOk.setEnabled(False)
     if self.ui.spnXmin.text() == "" or self.ui.spnXmax.text() == "" or self.ui.spnYmin.text() == "" or \
     self.ui.spnYmax.text() == "":
         QtGui.QMessageBox.information(self, self.tr("Planning Grid"), \
         self.tr("Please specify valid extent coordinates"))
     elif self.ui.outShape.text() == "":
         QtGui.QMessageBox.information(self, self.tr("Planning Grid"), \
         self.tr("Please specify output shapefile"))
     else:
         try:
             boundBox = QgsRectangle(float(self.ui.spnXmin.value()),
                                     float(self.ui.spnYmin.value()),
                                     float(self.ui.spnXmax.value()),
                                     float(self.ui.spnYmax.value()))
         except:
             QtGui.QMessageBox.information(
                 self, self.tr("Planning Grid"),
                 self.tr("Invalid extent coordinates entered"))
         sideLen = self.ui.spnSideLength.value()
         unitArea = self.ui.spnUnitArea.value()
         if self.ui.rdoHexagon.isChecked():
             hexagon = True
         else:
             hexagon = False
         if self.ui.rdoArea.isChecked() == True:
             if hexagon == True:
                 sideLen = self.CalculateHexagonSideLength(unitArea)
             else:
                 sideLen = self.CalculateSquareSideLength(unitArea)
             makegrid = QtGui.QMessageBox.question(self, self.tr("Side Length Check"), \
                 self.tr("Planning grid side length will %d map units. Proceed?" % sideLen), \
                 QtGui.QMessageBox.Yes, QtGui.QMessageBox.No, QtGui.QMessageBox.NoButton)
             if makegrid != QtGui.QMessageBox.Yes:
                 self.ui.progressBar.setValue(0)
                 self.ui.buttonOk.setEnabled(True)
                 return ()
         self.ui.outShape.clear()
         if self.ui.cbLimit.isChecked():
             # create temp 4 x 4 grid
             tfn = 'tempgrid' + str(os.getpid()) + '.shp'
             tin = 'tempint' + str(os.getpid()) + '.shp'
             tfp = os.path.dirname(str(self.mLayer.source()))
             tfpn = os.path.join(tfp, tfn)
             tipn = os.path.join(tfp, tin)
             tempLen = min((boundBox.yMaximum() - boundBox.yMinimum()),
                           (boundBox.xMaximum() - boundBox.xMinimum()))
             self.writeTempFile(boundBox, tempLen / 3.8, tfpn,
                                self.encoding)
             # intersect temp 4 x 4 grid with source layer
             d = qmCalculateThread(tfpn, 'temp_id',
                                   str(self.mLayer.source()), '', '', '',
                                   '', '')
             mLayerName = str(self.mLayer.source())
             QtCore.QObject.connect(
                 d, QtCore.SIGNAL("runSubProgress(PyQt_PyObject)"),
                 self.setThreadProgress)
             QtCore.QObject.connect(
                 d, QtCore.SIGNAL("runSubRange(PyQt_PyObject)"),
                 self.setThreadRange)
             ok, message, intLyr, valField = d.intersectLayers(
                 mLayerName, tfpn, tipn, [], ['temp_id'])
             intLyr = None
             os.remove(tfpn)
             os.remove(tfpn[:-4] + '.dbf')
             os.remove(tfpn[:-4] + '.shx')
             os.remove(tfpn[:-4] + '.prj')
             os.remove(tfpn[:-4] + '.qpj')
             # write output with continual intersection checks
             self.tLayer = QgsVectorLayer(tipn, 'int', 'ogr')
             self.writeFile(boundBox, sideLen, hexagon, self.shapefileName,
                            self.encoding)
             self.tLayer = None
             os.remove(tipn)
             os.remove(tipn[:-4] + '.dbf')
             os.remove(tipn[:-4] + '.shx')
             os.remove(tipn[:-4] + '.prj')
             os.remove(tipn[:-4] + '.qpj')
         else:
             self.writeFile(boundBox, sideLen, hexagon, self.shapefileName,
                            self.encoding)
         self.ui.progressBar.setValue(100)
         self.ui.progressBar.repaint()
         addToTOC = QtGui.QMessageBox.question(self, self.tr("Generate Vector Grid"), \
             self.tr("Created output shapefile:" + \
             "\n%1\n\nWould you like to add the new layer to the TOC?").arg(unicode(self.shapefileName)), \
             QtGui.QMessageBox.Yes, QtGui.QMessageBox.No, QtGui.QMessageBox.NoButton)
         if addToTOC == QtGui.QMessageBox.Yes:
             ftools_utils.addShapeToCanvas(self.shapefileName)
     self.ui.progressBar.setValue(0)
     self.ui.buttonOk.setEnabled(True)
Exemple #38
0
    def eliminate(self, inLayer, boundary, progressBar, outFileName):
        # keep references to the features to eliminate
        fidsToEliminate = inLayer.selectedFeaturesIds()

        if outFileName: # user wants a new shape file to be created as result
            provider = inLayer.dataProvider()
            error = QgsVectorFileWriter.writeAsVectorFormat(inLayer, outFileName, provider.encoding(), inLayer.crs(), "ESRI Shapefile")

            if error != QgsVectorFileWriter.NoError:
                QtGui.QMessageBox.warning(self, self.tr("Eliminate"), self.tr("Error creating output file"))
                return None

            outLayer = QgsVectorLayer(outFileName, QtCore.QFileInfo(outFileName).completeBaseName(), "ogr")

        else:
            QtGui.QMessageBox.information(self, self.tr("Eliminate"), self.tr("Please specify output shapefile"))
            return None

        # delete features to be eliminated in outLayer
        outLayer.setSelectedFeatures(fidsToEliminate)
        outLayer.startEditing()

        if outLayer.deleteSelectedFeatures():
            if self.saveChanges(outLayer):
                outLayer.startEditing()
        else:
            QtGui.QMessageBox.warning(self, self.tr("Eliminate"), self.tr("Could not delete features"))
            return None

        # ANALYZE
        start = 20.00
        progressBar.setValue(start)
        add = 80.00 / len(fidsToEliminate)

        lastLen = 0
        geomsToMerge = dict()

        # we go through the list and see if we find any polygons we can merge the selected with
        # if we have no success with some we merge and then restart the whole story
        while (lastLen != inLayer.selectedFeatureCount()): #check if we made any progress
            lastLen = inLayer.selectedFeatureCount()
            fidsToDeselect = []

            #iterate over the polygons to eliminate
            for fid2Eliminate in inLayer.selectedFeaturesIds():
                feat = QgsFeature()

                if inLayer.getFeatures( QgsFeatureRequest().setFilterFid( fid2Eliminate ).setSubsetOfAttributes([]) ).nextFeature( feat ):
                    geom2Eliminate = feat.geometry()
                    bbox = geom2Eliminate.boundingBox()
                    outLayer.select(bbox, False) # make a new selection
                    mergeWithFid = None
                    mergeWithGeom = None
                    max = 0

                    for selFid in outLayer.selectedFeaturesIds():
                        selFeat = QgsFeature()

                        if outLayer.getFeatures( QgsFeatureRequest().setFilterFid( selFid ).setSubsetOfAttributes([]) ).nextFeature( selFeat ):
                            selGeom = selFeat.geometry()

                            if geom2Eliminate.intersects(selGeom): # we have a candidate
                                iGeom = geom2Eliminate.intersection(selGeom)

                                if boundary:
                                    selValue = iGeom.length()
                                else:
                                    # we need a common boundary
                                    if 0 < iGeom.length():
                                        selValue = selGeom.area()
                                    else:
                                        selValue = 0

                                if selValue > max:
                                    max = selValue
                                    mergeWithFid = selFid
                                    mergeWithGeom = QgsGeometry(selGeom) # deep copy of the geometry

                    if mergeWithFid != None: # a successful candidate
                        newGeom = mergeWithGeom.combine(geom2Eliminate)

                        if outLayer.changeGeometry(mergeWithFid, newGeom):
                            # write change back to disc
                            if self.saveChanges(outLayer):
                                outLayer.startEditing()
                            else:
                                return None

                            # mark feature as eliminated in inLayer
                            fidsToDeselect.append(fid2Eliminate)
                        else:
                            QtGui.QMessageBox.warning(self, self.tr("Eliminate"),
                                self.tr("Could not replace geometry of feature with id %1").arg( mergeWithFid ))
                            return None

                        start = start + add
                        progressBar.setValue(start)
            # end for fid2Eliminate

            # deselect features that are already eliminated in inLayer
            for aFid in fidsToDeselect:
                inLayer.deselect(aFid, False)

        #end while

        if inLayer.selectedFeatureCount() > 0:
            # copy all features that could not be eliminated to outLayer
            if outLayer.addFeatures(inLayer.selectedFeatures()):
                # inform user
                fidList = QtCore.QString()

                for fid in inLayer.selectedFeaturesIds():
                    if not fidList.isEmpty():
                        fidList.append(", ")

                    fidList.append(str(fid))

                QtGui.QMessageBox.information(self, self.tr("Eliminate"),
                        self.tr("Could not eliminate features with these ids:\n%1").arg(fidList))
            else:
                QtGui.QMessageBox.warning(self, self.tr("Eliminate"), self.tr("Could not add features"))

        # stop editing outLayer and commit any pending changes
        if not self.saveChanges(outLayer):
            return None

        if outFileName:
            if self.addToCanvasCheck.isChecked():
                ftools_utils.addShapeToCanvas(outFileName)
            else:
                QtGui.QMessageBox.information(self, self.tr("Eliminate"),
                    self.tr("Created output shapefile:\n%1").arg(outFileName))

        self.iface.mapCanvas().refresh()
    def run_write_grid(self):
        self.buttonWriteGrid.setEnabled(False)

        # Check input data
        if (self.textXmin.text() == "" or self.textXmax.text() == ""
                or self.textYmin.text() == "" or self.textYmax.text() == ""):
            QMessageBox.information(
                self, self.tr("Gridder"),
                self.tr("Please specify valid extent coordinates"))
        elif self.textOutFilename.text() == "":
            QMessageBox.information(
                self, self.tr("Gridder"),
                self.tr("Please specify valid output shapefile"))
        elif self.sboxXres.value() == 0:
            QMessageBox.information(self, self.tr("Gridder"),
                                    self.tr("Please specify valid resolution"))
        elif float( self.textXmin.text() ) >= float( self.textXmax.text() ) or \
         float( self.textYmin.text() ) >= float( self.textYmax.text() ):
            QMessageBox.information(self, self.tr("Gridder"),
                                    self.tr("Check extent coordinates"))
        else:
            try:
                boundBox = QgsRectangle(float(self.textXmin.text()),
                                        float(self.textYmin.text()),
                                        float(self.textXmax.text()),
                                        float(self.textYmax.text()))
            except:
                QMessageBox.information(
                    self, self.tr("Vector grid"),
                    self.tr("Invalid extent coordinates entered"))
            Xres = self.sboxXres.value()
            Yres = self.sboxYres.value()

            # Compute number of elements

            n = int(round((boundBox.yMaximum() - boundBox.yMinimum()) / Yres))
            m = int(round((boundBox.xMaximum() - boundBox.xMinimum()) / Xres))

            # Adjust bounding box to respect Yres and Xres with linspace
            boundBox.setXMaximum(boundBox.xMinimum() + m * Xres)
            boundBox.setYMaximum(boundBox.yMinimum() + n * Yres)

            if n * m <= 0:
                QMessageBox.information(
                    self, self.tr("Gridder"),
                    self.tr("Invalid extent or resolution entered"))
                return
        # TO DO : Here, you should check whether elements  is correct...
        # Or add it directly as information in the grid resolution frame
            QApplication.setOverrideCursor(Qt.WaitCursor)

            # ------------ Input data validated, build Grid

            # If a source layer is defined, retrieve CRS
            if ftools_utils.getMapLayerByName(
                    unicode(self.listSourceLayer.currentText())) != None:
                crs = ftools_utils.getMapLayerByName(
                    unicode(self.listSourceLayer.currentText())).crs()
                if not crs.isValid():
                    crs = None
            else:
                crs = None

        # Initialize field for base feature
        # TO DO : add useful attributes
        #fields = {0:QgsField("ID", QVariant.Int)}
            fields = QgsFields()
            fields.append(QgsField("ID", QVariant.Int))
            # Initialize base rectangle feature
            rectFeat = QgsFeature()
            rectGeom = QgsGeometry()
            rectFeat.setGeometry(rectGeom.fromRect(boundBox))
            #rectFeat.setAttributeMap(fields)
            rectFeat.initAttributes(1)
            idVar = 0
            #rectFeat.addAttribute(0, QVariant(idVar))
            rectFeat.setAttribute(0, idVar)

            # if the file exits, remove it
            check = QFile(self.OutFileName)
            if QFile(self.OutFileName).exists():
                if not QgsVectorFileWriter.deleteShapeFile(self.OutFileName):
                    return

        # Load shape file writer
            writer = QgsVectorFileWriter(unicode(self.textOutFilename.text()),
                                         self.encoding, fields,
                                         QGis.WKBPolygon, crs)

            # Call function to make grid
            qgridder_utils.make_rgrid(rectFeat, n, m, writer,
                                      self.progressBarBuildGrid)

            # Delete writer
            del writer

            # Post-operation information
            QApplication.restoreOverrideCursor()
            QMessageBox.information(
                self, self.tr("Generate Vector Grid"),
                "Created output shapefile:\n" + unicode(self.OutFileName) +
                "\n")

            # Load output layer if it is not already loaded
            if self.checkLoadLayer.isChecked():
                # list currently loaded layer. If the layer is loaded, unload it.
                for (name, layer) in QgsMapLayerRegistry.instance().mapLayers(
                ).iteritems():
                    # Note : reload() doesn't work.
                    if layer.source() == self.OutFileName:
                        QgsMapLayerRegistry.instance().removeMapLayers(
                            layer.id())

                # load layer
                ftools_utils.addShapeToCanvas(self.OutFileName)
                # update layer list in plugin
                self.populate_layer_list(self.listSourceLayer)
        # Enable Write Grid button
        self.buttonWriteGrid.setEnabled(True)
    def run_write_grid(self):
	self.buttonWriteGrid.setEnabled( False )

	# Check input data 
        if (self.textXmin.text() == "" or self.textXmax.text() == "" or
		self.textYmin.text() == "" or self.textYmax.text() == ""):
            QMessageBox.information(self, self.tr("Gridder"), 
		    self.tr("Please specify valid extent coordinates")
		    )
        elif self.textOutFilename.text() == "":
            QMessageBox.information(self, self.tr("Gridder"),
		    self.tr("Please specify valid output shapefile")
		    )
	elif self.sboxXres.value() == 0:
            QMessageBox.information(self, self.tr("Gridder"),
		    self.tr("Please specify valid resolution")
		    )
	elif float( self.textXmin.text() ) >= float( self.textXmax.text() ) or \
		float( self.textYmin.text() ) >= float( self.textYmax.text() ):
		    QMessageBox.information(self, self.tr("Gridder"), 
		    self.tr("Check extent coordinates")
		    )
	else:
            try:
                boundBox = QgsRectangle(
                float( self.textXmin.text() ),
                float( self.textYmin.text() ),
                float( self.textXmax.text() ),
                float( self.textYmax.text() ) )
	    except:
                QMessageBox.information(self, self.tr("Vector grid"),
			self.tr("Invalid extent coordinates entered")
			)
            Xres = self.sboxXres.value()
            Yres = self.sboxYres.value()

	    # Compute number of elements


	    n = int( round( (boundBox.yMaximum() - boundBox.yMinimum()) / Yres ) )
	    m = int( round( (boundBox.xMaximum() - boundBox.xMinimum()) / Xres ) )

	    # Adjust bounding box to respect Yres and Xres with linspace
	    boundBox.setXMaximum( boundBox.xMinimum() + m*Xres )
	    boundBox.setYMaximum( boundBox.yMinimum() + n*Yres )

	    if n*m <= 0 :
		QMessageBox.information(self, self.tr("Gridder"),
			self.tr("Invalid extent or resolution entered")
			)
		return
	    # TO DO : Here, you should check whether elements  is correct...
	    # Or add it directly as information in the grid resolution frame
            QApplication.setOverrideCursor(Qt.WaitCursor)

	    # ------------ Input data validated, build Grid


	    # If a source layer is defined, retrieve CRS
	    if ftools_utils.getMapLayerByName(unicode(self.listSourceLayer.currentText())) != None :
		crs = ftools_utils.getMapLayerByName(unicode(self.listSourceLayer.currentText())).crs()
		if not crs.isValid(): 
		    crs = None
	    else :
		crs = None

	    # Initialize field for base feature
	    # TO DO : add useful attributes
	    #fields = {0:QgsField("ID", QVariant.Int)}
	    fields = QgsFields()
	    fields.append(QgsField("ID", QVariant.Int))
	    # Initialize base rectangle feature
	    rectFeat = QgsFeature()
	    rectGeom = QgsGeometry()
	    rectFeat.setGeometry(rectGeom.fromRect(boundBox))
	    #rectFeat.setAttributeMap(fields)
	    rectFeat.initAttributes(1)
	    idVar = 0
	    #rectFeat.addAttribute(0, QVariant(idVar))
	    rectFeat.setAttribute(0, idVar)

	    # if the file exits, remove it
	    check = QFile(self.OutFileName)
	    if QFile(self.OutFileName).exists():
		if not QgsVectorFileWriter.deleteShapeFile(self.OutFileName):
		    return

	    # Load shape file writer
	    writer = QgsVectorFileWriter(unicode(self.textOutFilename.text()), self.encoding, fields, QGis.WKBPolygon, crs)
	    
	    # Call function to make grid
	    qgridder_utils.make_rgrid(rectFeat, n, m, writer, self.progressBarBuildGrid)

	    # Delete writer
	    del writer

	    # Post-operation information
	    QApplication.restoreOverrideCursor()
	    QMessageBox.information(self, self.tr("Generate Vector Grid"), 
		    "Created output shapefile:\n" + unicode(self.OutFileName) + "\n"
		    )

	    # Load output layer if it is not already loaded
	    if self.checkLoadLayer.isChecked():
		# list currently loaded layer. If the layer is loaded, unload it.	
		for (name,layer) in	QgsMapLayerRegistry.instance().mapLayers().iteritems():
		    # Note : reload() doesn't work.
		    if layer.source()==self.OutFileName:
			QgsMapLayerRegistry.instance().removeMapLayers( layer.id() )
			
		# load layer
		ftools_utils.addShapeToCanvas( self.OutFileName )
		# update layer list in plugin
		self.populate_layer_list(self.listSourceLayer)
	# Enable Write Grid button
	self.buttonWriteGrid.setEnabled( True )