def __init__(self, iface):
        QDialog.__init__(self)
        # Set up the user interface from Designer.
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.iface = iface

        QObject.connect(self.ui.btnBrowse, SIGNAL("clicked()"), self.outFile)
        QObject.connect(self.ui.btnCancel, SIGNAL("clicked()"), self.closeForm)
        QObject.connect(self.ui.btnOK, SIGNAL("clicked()"), self.Polygonize)
        QObject.connect(self.ui.bAbout, SIGNAL("clicked()"), self.ShowAbout)

        layerList = getLayersNames()
        self.ui.cmbLayer.addItems(layerList)
コード例 #2
0
  def __init__(self, iface):
    QDialog.__init__(self)
    # Set up the user interface from Designer.
    self.ui = Ui_Form()
    self.ui.setupUi(self)
    self.iface = iface

    QObject.connect( self.ui.btnBrowse, SIGNAL( "clicked()" ), self.outFile )
    QObject.connect( self.ui.btnCancel, SIGNAL( "clicked()" ), self.closeForm )
    QObject.connect( self.ui.btnOK, SIGNAL( "clicked()" ), self.Polygonize )
コード例 #3
0
    def __init__(self, iface):
        QDialog.__init__(self)
        # Set up the user interface from Designer.
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.iface = iface

        QObject.connect(self.ui.btnBrowse, SIGNAL("clicked()"), self.outFile)
        QObject.connect(self.ui.btnCancel, SIGNAL("clicked()"), self.closeForm)
        QObject.connect(self.ui.btnOK, SIGNAL("clicked()"), self.Polygonize)
        QObject.connect(self.ui.bAbout, SIGNAL("clicked()"), self.ShowAbout)

        layerList = getLayersNames()
        self.ui.cmbLayer.addItems(layerList)
コード例 #4
0
class PolygonizerDialog(QDialog):
    def __init__(self, iface):
        QDialog.__init__(self)
        # Set up the user interface from Designer.
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.iface = iface

        QObject.connect(self.ui.btnBrowse, SIGNAL("clicked()"), self.outFile)
        QObject.connect(self.ui.btnCancel, SIGNAL("clicked()"), self.closeForm)
        QObject.connect(self.ui.btnOK, SIGNAL("clicked()"), self.Polygonize)
        QObject.connect(self.ui.bAbout, SIGNAL("clicked()"), self.ShowAbout)

        layerList = getLayersNames()
        self.ui.cmbLayer.addItems(layerList)
        # QInputDialog.getText( self.iface.mainWindow(), "m", "e",   QLineEdit.Normal, str( layerList ) )

    def ShowAbout(self):
        # QMessageBox.question(self, 'Polygonizer', self.version , QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        dlg = PolygonizerAboutDialog(self.iface)
        # show the dialog
        dlg.setModal(True)
        dlg.show()
        result = dlg.exec_()

    def outFile(self):
        """Open a file save dialog and set the output file path."""
        outFilePath = saveDialog(self)
        if not outFilePath:
            return
        self.setOutFilePath(QString(outFilePath))

    def setOutFilePath(self, outFilePath):
        """Set the output file path."""
        self.ui.eOutput.setText(outFilePath)

    def closeForm(self):
        self.close()

    def Polygonize(self):
        if self.ui.cmbLayer.currentText() == "":
            QMessageBox.critical(self, "Polygonizer", "Select line layer first!")
        elif getMapLayerByName(self.ui.cmbLayer.currentText()).dataProvider().featureCount() == 0:
            QMessageBox.critical(self, "Polygonizer", "Selected layer has no lines!")
        elif self.ui.eOutput.text() == "":
            QMessageBox.critical(self, "Polygonizer", "Choose output file!")
        else:
            sys.setcheckinterval(10000)
            setValue = self.ui.pbProgress.setValue
            SetWidgetsEnabled(self.ui, False)

            setValue(0)

            self.t1 = time()

            if self.ui.rbNew.isChecked():
                inFeat = QgsFeature()
                outFeat = QgsFeature()
                layer = QgsVectorLayer()

                layer = getMapLayerByName(self.ui.cmbLayer.currentText())

                progress = 0.0

                provider = layer.dataProvider()
                allAttrs = provider.attributeIndexes()
                provider.select(allAttrs)
                fields = provider.fields()

                provider.select()

                step = 30.0 / layer.featureCount()
                allLinesList = []
                allLinesListExtend = allLinesList.extend
                allLinesListAppend = allLinesList.append

                while provider.nextFeature(inFeat):
                    geom = inFeat.geometry()

                    if geom.isMultipart():
                        allLinesListExtend(geom.asMultiPolyline())
                    else:
                        allLinesListAppend(geom.asPolyline())

                    progress += step
                    setValue(progress)

                allLines = MultiLineString(allLinesList)
                allLines = allLines.union(Point(0, 0))

                polygons = list(polygonize([allLines]))

                self.polyCount = len(polygons)
                if self.polyCount == 0:
                    QMessageBox.critical(self, "Polygonizer", "Sorry, I don't see any polygon!")
                    SetWidgetsEnabled(self.ui, True)
                    setValue(0)
                    return
                else:
                    step = 65.0 / self.polyCount

                    # addFeature = writer.addFeature
                    setGeometry = outFeat.setGeometry  # ok
                    setAttributeMap = outFeat.setAttributeMap  # ok

                    if self.ui.cbGeometry.isChecked():
                        fields[len(fields)] = QgsField("area", QVariant.Double, "double", 16, 2)
                        fields[len(fields)] = QgsField("perimeter", QVariant.Double, "double", 16, 2)
                        nrArea = len(fields) - 2
                        nrPerimeter = len(fields) - 1

                        writer = QgsVectorFileWriter(
                            self.ui.eOutput.text(), provider.encoding(), fields, QGis.WKBPolygon, layer.srs()
                        )

                        for polygon in polygons:
                            # QInputDialog.getText( self, "m", "e",   QLineEdit.Normal,  str(fields) )
                            setGeometry(QgsGeometry.fromWkt(polygon.wkt))
                            setAttributeMap({nrArea: polygon.area, nrPerimeter: polygon.length})
                            writer.addFeature(outFeat)

                            progress += step
                            setValue(progress)

                        setValue(100)
                        del writer

                    else:
                        writer = QgsVectorFileWriter(
                            self.ui.eOutput.text(), provider.encoding(), fields, QGis.WKBPolygon, layer.srs()
                        )
                        for polygon in polygons:
                            setGeometry(QgsGeometry.fromWkt(polygon.wkt))
                            writer.addFeature(outFeat)

                            progress += step
                            setValue(progress)

                        setValue(100)
                        del writer

            else:
                inFeat = QgsFeature()
                inFeatB = QgsFeature()
                outFeat = QgsFeature()
                layer = QgsVectorLayer()
                layer = self.getMapLayerByName(self.ui.cmbLayer.currentText())
                progress = 0.0

                provider = layer.dataProvider()

                allAttrs = provider.attributeIndexes()
                provider.select(allAttrs)
                fields = provider.fields()

                new_path = self.ui.eOutput.text()
                if new_path.contains("\\"):
                    out_name = new_path.right((new_path.length() - new_path.lastIndexOf("\\")) - 1)
                else:
                    out_name = new_path.right((new_path.length() - new_path.lastIndexOf("/")) - 1)
                if out_name.endsWith(".shp"):
                    out_name = out_name.left(out_name.length() - 4)

                step = 20.0 / float(provider.featureCount())

                # to single lines and without duplicate lines
                provider.select()
                lines = []
                while provider.nextFeature(inFeat):

                    inGeom = inFeat.geometry()
                    if inFeat.geometry().isMultipart():
                        for line in inFeat.geometry().asMultiPolyline():
                            self.splitline(line, lines)
                    else:
                        self.splitline(inFeat.geometry().asPolyline(), lines)
                    progress += step
                    setValue(progress)

                # QMessageBox.critical(self.iface.mainWindow(), "d", str(len(lines)))

                single_lines = QgsVectorLayer("LineString", "single", "memory")
                single_provider = single_lines.dataProvider()

                step = 20.0 / float(len(lines))
                for line in lines:
                    outFeat.setGeometry(QgsGeometry.fromPolyline(line))
                    single_provider.addFeatures([outFeat])
                    single_lines.updateExtents()
                    progress += step
                    setValue(progress)

                # intersections
                index = createIndex(single_provider)
                lines = []
                single_provider.select()
                step = 50.0 / float(single_provider.featureCount())
                while single_provider.nextFeature(inFeat):
                    pointList = []
                    inGeom = inFeat.geometry()
                    lineList = index.intersects(inGeom.boundingBox())
                    if len(lineList) > 0:
                        for i in lineList:
                            single_provider.featureAtId(int(i), inFeatB, True, allAttrs)
                            tmpGeom = QgsGeometry(inFeatB.geometry())
                            if inGeom.intersects(tmpGeom):
                                pointGeom = inGeom.intersection(tmpGeom)
                                if pointGeom.type() == QGis.Point:
                                    if pointGeom.asPoint() not in pointList:
                                        pointList.append(pointGeom.asPoint())
                        linePoints = []
                        linePoints = inGeom.asPolyline()
                        s = [i for i in pointList + linePoints if i not in linePoints]
                        if len(s) > 1:
                            l = sortPoints(linePoints[0], s)
                        else:
                            l = s

                        tempLine = []
                        tempLine.append(linePoints[0])
                        tempLine.extend(l)
                        tempLine.append(linePoints[1])

                        countSubLines = len(tempLine) - 1
                        for p in range(countSubLines):
                            lines.append([tempLine[p], tempLine[p + 1]])
                    progress += step
                    setValue(progress)

                del single_lines
                del single_provider

                # create polygons

                polygons = list(polygonize(lines))

                self.polyCount = 0
                self.polyCount = len(polygons)
                # QMessageBox.critical(self.iface.mainWindow(), "d", str(fields))

                setValue(95)

                setGeometry = outFeat.setGeometry  # ok
                setAttributeMap = outFeat.setAttributeMap  # ok

                if self.ui.cbGeometry.isChecked():
                    fields[len(fields)] = QgsField("area", QVariant.Double, "double", 16, 2)
                    fields[len(fields)] = QgsField("perimeter", QVariant.Double, "double", 16, 2)
                    nrArea = len(fields) - 2
                    nrPerimeter = len(fields) - 1

                    writer = QgsVectorFileWriter(new_path, provider.encoding(), fields, QGis.WKBPolygon, layer.srs())

                    for polygon in polygons:
                        # QInputDialog.getText( self.parent, "m", "e",   QLineEdit.Normal,  str(polygon))
                        setGeometry(QgsGeometry.fromWkt(polygon.wkt))
                        setAttributeMap({nrArea: polygon.area, nrPerimeter: polygon.length})
                        writer.addFeature(outFeat)

                        progress += step
                        setValue(progress)

                    del writer
                    setValue(100)
                else:
                    writer = QgsVectorFileWriter(new_path, provider.encoding(), fields, QGis.WKBPolygon, layer.srs())

                    for polygon in polygons:
                        # QInputDialog.getText( self.parent, "m", "e",   QLineEdit.Normal,  str(polygon))
                        setGeometry(QgsGeometry.fromWkt(polygon.wkt))
                        writer.addFeature(outFeat)

                        progress += step
                        setValue(progress)

                    del writer
                    setValue(100)

            # koniec
            self.t2 = time()

            # self.ui.pbProgress.setValue(0)
            SetWidgetsEnabled(self.ui, True)

            msg = QMessageBox.question(
                self,
                "Polygonizer",
                "Polygonization finished in %03.2f seconds. \n %d polygons were crested. \n Load created layer?"
                % ((self.t2 - self.t1), self.polyCount),
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.Yes,
            )
            if msg == QMessageBox.Yes:
                new_path = self.ui.eOutput.text()
                if new_path.contains("\\"):
                    out_name = new_path.right((new_path.length() - new_path.lastIndexOf("\\")) - 1)
                else:
                    out_name = new_path.right((new_path.length() - new_path.lastIndexOf("/")) - 1)
                if out_name.endsWith(".shp"):
                    out_name = out_name.left(out_name.length() - 4)

                self.iface.addVectorLayer(self.ui.eOutput.text(), out_name, "ogr")

            self.close()

    def getMapLayerByName(self, myName):
        layermap = QgsMapLayerRegistry.instance().mapLayers()
        for name, layer in layermap.iteritems():
            if layer.name() == myName:
                if layer.isValid():
                    return layer
                else:
                    return None

    def splitline(self, line, lines):
        for i in range(1, len(line)):
            temp = line[i - 1 : i + 1]
            revTemp = [temp[-1], temp[0]]
            if temp not in lines and revTemp not in lines:
                lines.append(temp)
class PolygonizerDialog(QDialog):
    def __init__(self, iface):
        QDialog.__init__(self)
        # Set up the user interface from Designer.
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.iface = iface

        QObject.connect(self.ui.btnBrowse, SIGNAL("clicked()"), self.outFile)
        QObject.connect(self.ui.btnCancel, SIGNAL("clicked()"), self.closeForm)
        QObject.connect(self.ui.btnOK, SIGNAL("clicked()"), self.Polygonize)
        QObject.connect(self.ui.bAbout, SIGNAL("clicked()"), self.ShowAbout)

        layerList = getLayersNames()
        self.ui.cmbLayer.addItems(layerList)
        #QInputDialog.getText( self.iface.mainWindow(), "m", "e",   QLineEdit.Normal, str( layerList ) )

    def ShowAbout(self):
        #QMessageBox.question(self, 'Polygonizer', self.version , QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        dlg = PolygonizerAboutDialog(self.iface)
        # show the dialog
        dlg.setModal(True)
        dlg.show()
        result = dlg.exec_()

    def outFile(self):
        """Open a file save dialog and set the output file path."""
        outFilePath = saveDialog(self)
        if not outFilePath:
            return
        self.setOutFilePath(QString(outFilePath))

    def setOutFilePath(self, outFilePath):
        """Set the output file path."""
        self.ui.eOutput.setText(outFilePath)

    def closeForm(self):
        self.close()

    def Polygonize(self):
        if self.ui.cmbLayer.currentText() == "":
            QMessageBox.critical(self, "Polygonizer",
                                 "Select line layer first!")
        elif getMapLayerByName(self.ui.cmbLayer.currentText()).dataProvider(
        ).featureCount() == 0:
            QMessageBox.critical(self, "Polygonizer",
                                 "Selected layer has no lines!")
        elif self.ui.eOutput.text() == "":
            QMessageBox.critical(self, "Polygonizer", "Choose output file!")
        else:
            sys.setcheckinterval(10000)
            setValue = self.ui.pbProgress.setValue
            SetWidgetsEnabled(self.ui, False)

            setValue(0)

            self.t1 = time()

            if self.ui.rbNew.isChecked():
                inFeat = QgsFeature()
                outFeat = QgsFeature()
                layer = QgsVectorLayer()

                layer = getMapLayerByName(self.ui.cmbLayer.currentText())

                progress = 0.

                provider = layer.dataProvider()
                allAttrs = provider.attributeIndexes()
                provider.select(allAttrs)
                fields = provider.fields()

                provider.select()

                step = 30. / layer.featureCount()
                allLinesList = []
                allLinesListExtend = allLinesList.extend
                allLinesListAppend = allLinesList.append

                while provider.nextFeature(inFeat):
                    geom = inFeat.geometry()

                    if geom.isMultipart():
                        allLinesListExtend(geom.asMultiPolyline())
                    else:
                        allLinesListAppend(geom.asPolyline())

                    progress += step
                    setValue(progress)

                allLines = MultiLineString(allLinesList)
                allLines = allLines.union(Point(0, 0))

                polygons = list(polygonize([allLines]))

                self.polyCount = len(polygons)
                if self.polyCount == 0:
                    QMessageBox.critical(self, "Polygonizer",
                                         "Sorry, I don't see any polygon!")
                    SetWidgetsEnabled(self.ui, True)
                    setValue(0)
                    return
                else:
                    step = 65. / self.polyCount

                    #addFeature = writer.addFeature
                    setGeometry = outFeat.setGeometry  #ok
                    setAttributeMap = outFeat.setAttributeMap  #ok

                    if self.ui.cbGeometry.isChecked():
                        fields[len(fields)] = QgsField("area", QVariant.Double,
                                                       "double", 16, 2)
                        fields[len(fields)] = QgsField("perimeter",
                                                       QVariant.Double,
                                                       "double", 16, 2)
                        nrArea = len(fields) - 2
                        nrPerimeter = len(fields) - 1

                        writer = QgsVectorFileWriter(self.ui.eOutput.text(),
                                                     provider.encoding(),
                                                     fields, QGis.WKBPolygon,
                                                     layer.srs())

                        for polygon in polygons:
                            #QInputDialog.getText( self, "m", "e",   QLineEdit.Normal,  str(fields) )
                            setGeometry(QgsGeometry.fromWkt(polygon.wkt))
                            setAttributeMap({
                                nrArea: polygon.area,
                                nrPerimeter: polygon.length
                            })
                            writer.addFeature(outFeat)

                            progress += step
                            setValue(progress)

                        setValue(100)
                        del writer

                    else:
                        writer = QgsVectorFileWriter(self.ui.eOutput.text(),
                                                     provider.encoding(),
                                                     fields, QGis.WKBPolygon,
                                                     layer.srs())
                        for polygon in polygons:
                            setGeometry(QgsGeometry.fromWkt(polygon.wkt))
                            writer.addFeature(outFeat)

                            progress += step
                            setValue(progress)

                        setValue(100)
                        del writer

            else:
                inFeat = QgsFeature()
                inFeatB = QgsFeature()
                outFeat = QgsFeature()
                layer = QgsVectorLayer()
                layer = self.getMapLayerByName(self.ui.cmbLayer.currentText())
                progress = 0.

                provider = layer.dataProvider()

                allAttrs = provider.attributeIndexes()
                provider.select(allAttrs)
                fields = provider.fields()

                new_path = self.ui.eOutput.text()
                if new_path.contains("\\"):
                    out_name = new_path.right((new_path.length() -
                                               new_path.lastIndexOf("\\")) - 1)
                else:
                    out_name = new_path.right((new_path.length() -
                                               new_path.lastIndexOf("/")) - 1)
                if out_name.endsWith(".shp"):
                    out_name = out_name.left(out_name.length() - 4)

                step = 20. / float(provider.featureCount())

                #to single lines and without duplicate lines
                provider.select()
                lines = []
                while provider.nextFeature(inFeat):

                    inGeom = inFeat.geometry()
                    if inFeat.geometry().isMultipart():
                        for line in inFeat.geometry().asMultiPolyline():
                            self.splitline(line, lines)
                    else:
                        self.splitline(inFeat.geometry().asPolyline(), lines)
                    progress += step
                    setValue(progress)

                #QMessageBox.critical(self.iface.mainWindow(), "d", str(len(lines)))

                single_lines = QgsVectorLayer("LineString", "single", "memory")
                single_provider = single_lines.dataProvider()

                step = 20. / float(len(lines))
                for line in lines:
                    outFeat.setGeometry(QgsGeometry.fromPolyline(line))
                    single_provider.addFeatures([outFeat])
                    single_lines.updateExtents()
                    progress += step
                    setValue(progress)

                #intersections
                index = createIndex(single_provider)
                lines = []
                single_provider.select()
                step = 50. / float(single_provider.featureCount())
                while single_provider.nextFeature(inFeat):
                    pointList = []
                    inGeom = inFeat.geometry()
                    lineList = index.intersects(inGeom.boundingBox())
                    if len(lineList) > 0:
                        for i in lineList:
                            single_provider.featureAtId(
                                int(i), inFeatB, True, allAttrs)
                            tmpGeom = QgsGeometry(inFeatB.geometry())
                            if inGeom.intersects(tmpGeom):
                                pointGeom = inGeom.intersection(tmpGeom)
                                if pointGeom.type() == QGis.Point:
                                    if pointGeom.asPoint() not in pointList:
                                        pointList.append(pointGeom.asPoint())
                        linePoints = []
                        linePoints = inGeom.asPolyline()
                        s = [
                            i for i in pointList + linePoints
                            if i not in linePoints
                        ]
                        if len(s) > 1:
                            l = sortPoints(linePoints[0], s)
                        else:
                            l = s

                        tempLine = []
                        tempLine.append(linePoints[0])
                        tempLine.extend(l)
                        tempLine.append(linePoints[1])

                        countSubLines = len(tempLine) - 1
                        for p in range(countSubLines):
                            lines.append([tempLine[p], tempLine[p + 1]])
                    progress += step
                    setValue(progress)

                del single_lines
                del single_provider

                #create polygons

                polygons = list(polygonize(lines))

                self.polyCount = 0
                self.polyCount = len(polygons)
                #QMessageBox.critical(self.iface.mainWindow(), "d", str(fields))

                setValue(95)

                setGeometry = outFeat.setGeometry  #ok
                setAttributeMap = outFeat.setAttributeMap  #ok

                if self.ui.cbGeometry.isChecked():
                    fields[len(fields)] = QgsField("area", QVariant.Double,
                                                   "double", 16, 2)
                    fields[len(fields)] = QgsField("perimeter",
                                                   QVariant.Double, "double",
                                                   16, 2)
                    nrArea = len(fields) - 2
                    nrPerimeter = len(fields) - 1

                    writer = QgsVectorFileWriter(new_path, provider.encoding(),
                                                 fields, QGis.WKBPolygon,
                                                 layer.srs())

                    for polygon in polygons:
                        #QInputDialog.getText( self.parent, "m", "e",   QLineEdit.Normal,  str(polygon))
                        setGeometry(QgsGeometry.fromWkt(polygon.wkt))
                        setAttributeMap({
                            nrArea: polygon.area,
                            nrPerimeter: polygon.length
                        })
                        writer.addFeature(outFeat)

                        progress += step
                        setValue(progress)

                    del writer
                    setValue(100)
                else:
                    writer = QgsVectorFileWriter(new_path, provider.encoding(),
                                                 fields, QGis.WKBPolygon,
                                                 layer.srs())

                    for polygon in polygons:
                        #QInputDialog.getText( self.parent, "m", "e",   QLineEdit.Normal,  str(polygon))
                        setGeometry(QgsGeometry.fromWkt(polygon.wkt))
                        writer.addFeature(outFeat)

                        progress += step
                        setValue(progress)

                    del writer
                    setValue(100)

            # koniec
            self.t2 = time()

            #self.ui.pbProgress.setValue(0)
            SetWidgetsEnabled(self.ui, True)

            msg = QMessageBox.question(
                self, 'Polygonizer',
                'Polygonization finished in %03.2f seconds. \n %d polygons were crested. \n Load created layer?'
                % ((self.t2 - self.t1), self.polyCount),
                QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
            if msg == QMessageBox.Yes:
                new_path = self.ui.eOutput.text()
                if new_path.contains("\\"):
                    out_name = new_path.right((new_path.length() -
                                               new_path.lastIndexOf("\\")) - 1)
                else:
                    out_name = new_path.right((new_path.length() -
                                               new_path.lastIndexOf("/")) - 1)
                if out_name.endsWith(".shp"):
                    out_name = out_name.left(out_name.length() - 4)

                self.iface.addVectorLayer(self.ui.eOutput.text(), out_name,
                                          "ogr")

            self.close()

    def getMapLayerByName(self, myName):
        layermap = QgsMapLayerRegistry.instance().mapLayers()
        for name, layer in layermap.iteritems():
            if layer.name() == myName:
                if layer.isValid():
                    return layer
                else:
                    return None

    def splitline(self, line, lines):
        for i in range(1, len(line)):
            temp = line[i - 1:i + 1]
            revTemp = [temp[-1], temp[0]]
            if temp not in lines and revTemp not in lines: lines.append(temp)
コード例 #6
0
class PolygonizerDialog(QDialog):
  def __init__(self, iface):
    QDialog.__init__(self)
    # Set up the user interface from Designer.
    self.ui = Ui_Form()
    self.ui.setupUi(self)
    self.iface = iface

    QObject.connect( self.ui.btnBrowse, SIGNAL( "clicked()" ), self.outFile )
    QObject.connect( self.ui.btnCancel, SIGNAL( "clicked()" ), self.closeForm )
    QObject.connect( self.ui.btnOK, SIGNAL( "clicked()" ), self.Polygonize )

  def outFile(self):
    """Open a file save dialog and set the output file path."""
    outFilePath = saveDialog(self)
    if not outFilePath:
      return
    self.ui.eOutput.setText((QString(outFilePath)))

  def closeForm(self):
    ''' Stop polygonization process or close window '''
    if self.ui.btnCancel.text() == 'Cancel':
      msg = QMessageBox.question(self, 'Polygonizer', 'Stop process?', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
      if msg == QMessageBox.No:
        return

      QObject.disconnect(self.polygonizeThread,SIGNAL("finished()"), self.threadFinished)
      QObject.disconnect(self.layer,SIGNAL("editingStarted()"), self.startEditing)

      self.polygonizeThread.terminate()
      self.SetWidgetsEnabled(True)
      self.ui.pbProgress.setValue(0)
    else:
      self.close()

  def SetWidgetsEnabled(self, value):
    '''
    Sets wigdets disabled while calculating  
    value: True (enable) or False (disable)
    '''
    self.ui.btnOK.setEnabled(value)
    self.ui.cmbLayer.setEnabled(value)
    self.ui.cbGeometry.setEnabled(value)
    self.ui.cbTable.setEnabled(value)
    self.ui.rbNew.setEnabled(value)
    self.ui.rbOld.setEnabled(value)
    self.ui.cbOutput.setEnabled(value)
    self.ui.eOutput.setEnabled(self.ui.cbOutput.isChecked() and value )
    self.ui.btnBrowse.setEnabled(self.ui.cbOutput.isChecked() and value)

    if not value:
      self.ui.btnCancel.setText('Cancel')
    else:
      self.ui.btnCancel.setText('Close')


  def threadFinished(self):
    '''
    run when calculation ends
    ask to load created shapefile
    '''
    self.t2 = time()

    if self.ui.cbOutput.isChecked():
      msg = QMessageBox.question(self, 'Polygonizer', 'Polygonization finished in %03.2f seconds. \n %d polygons were crested. \n Load created layer?' % ((self.t2 - self.t1), polyCount), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
      if msg == QMessageBox.Yes:
        new_path = self.ui.eOutput.text()
        if new_path.contains("\\"):
          out_name = new_path.right((new_path.length() - new_path.lastIndexOf("\\")) - 1)
        else:
          out_name = new_path.right((new_path.length() - new_path.lastIndexOf("/")) - 1)
        if out_name.endsWith(".shp"):
          out_name = out_name.left(out_name.length() - 4)

        self.iface.addVectorLayer(self.ui.eOutput.text(), out_name, "ogr")
    else:
      QgsMapLayerRegistry().instance().addMapLayer(self.mLayer)
      QMessageBox.information(self, 'Polygonizer', 'Polygonization finished in %03.2f seconds. \n %d polygons were crested.' % ((self.t2 - self.t1), polyCount))

    QObject.disconnect(self.layer,SIGNAL("editingStarted()"), self.startEditing)
    QObject.disconnect(self.polygonizeThread, SIGNAL("progress"), self.setProgress)
    self.close()


  def startEditing(self):
    '''Disable editing line layer while calculating'''
    QMessageBox.critical(self, "Polygonizer", "You can't edit layer while polygonizing!" )
    self.layer.rollBack()


  def noPolygons(self):
    '''reset GUI when no polygons where created by polygonize process'''
    QMessageBox.critical(self, "Polygonizer", "No polygons were created!" )
    self.SetWidgetsEnabled(True)
    self.ui.pbProgress.setValue(0)


  def Polygonize(self):
    '''start calculation'''
    if self.ui.cmbLayer.currentText() == "":
      QMessageBox.critical(self, "Polygonizer", "Select line layer first!" )
      return
    elif getMapLayerByName(self.ui.cmbLayer.currentText()).dataProvider().featureCount() == 0:
      QMessageBox.critical(self, "Polygonizer", "Selected layer has no lines!" )
      return

    self.SetWidgetsEnabled(False)
    self.t1 = time()

    self.polygonizeThread = polygonizeThread(self, self.ui.rbNew.isChecked() )

    #thread finished
    QObject.connect(self.polygonizeThread,SIGNAL("finished()"), self.threadFinished)
    #set progress bar value
    QObject.connect(self.polygonizeThread, SIGNAL("progress"), self.setProgress)
    #show info and reset GUI when no polygons where created by polygonize process
    QObject.connect(self.polygonizeThread, SIGNAL("noPolygons"), self.noPolygons)

    self.polygonizeThread.start()


  def setProgress(self, value):
    '''
    set progress bar value
    value: value to set
    '''
    self.ui.pbProgress.setValue(value)