File: doVectorSplit.py

package info (click to toggle)
qgis 2.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 374,696 kB
  • ctags: 66,263
  • sloc: cpp: 396,139; ansic: 241,070; python: 130,609; xml: 14,884; perl: 1,290; sh: 1,287; sql: 500; yacc: 268; lex: 242; makefile: 168
file content (210 lines) | stat: -rw-r--r-- 7,392 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# -*- coding: utf-8 -*-
#-----------------------------------------------------------
#
# fTools
# Copyright (C) 2008-2011  Carson Farmer
# EMAIL: carson.farmer (at) gmail.com
# WEB  : http://www.ftools.ca/fTools.html
#
# A collection of data management and analysis tools for vector data
#
#-----------------------------------------------------------
#
# licensed under the terms of GNU GPL 2
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#---------------------------------------------------------------------

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
import ftools_utils
from ui_frmVectorSplit import Ui_Dialog

class Dialog(QDialog, Ui_Dialog):
    def __init__(self, iface):
        QDialog.__init__(self, iface.mainWindow())
        self.iface = iface

        self.setupUi(self)
        self.setWindowTitle(self.tr("Split vector layer"))

        QObject.connect(self.toolOut, SIGNAL("clicked()"), self.outFile)
        QObject.connect(self.inShape, SIGNAL("currentIndexChanged(QString)"), self.update)

        self.workThread = None

        self.btnOk = self.buttonBox_2.button( QDialogButtonBox.Ok )
        self.btnClose = self.buttonBox_2.button( QDialogButtonBox.Close )

        # populate layer list
        mapCanvas = self.iface.mapCanvas()
        layers = ftools_utils.getLayerNames([QGis.Point, QGis.Line, QGis.Polygon])
        self.inShape.addItems(layers)

    def update(self, inputLayer):
        self.inField.clear()
        changedLayer = ftools_utils.getVectorLayerByName(inputLayer)
        changedField = ftools_utils.getFieldList(changedLayer)
        for f in changedField:
            self.inField.addItem(unicode(f.name()))

    def outFile(self):
        self.outShape.clear()
        ( self.folderName, self.encoding ) = ftools_utils.dirDialog( self )
        if self.folderName is None or self.encoding is None:
            return
        self.outShape.setText( self.folderName )

    def accept(self):
        inShape = self.inShape.currentText()
        outDir = self.outShape.text()
        if inShape == "":
            QMessageBox.information(self, self.tr("Vector Split"),
                                    self.tr("No input shapefile specified"))
            return
        elif outDir == "":
            QMessageBox.information(self, self.tr("Vector Split"),
                                    self.tr("Please specify output shapefile"))
            return

        self.btnOk.setEnabled( False )

        vLayer = ftools_utils.getVectorLayerByName(unicode(self.inShape.currentText()))
        self.workThread = SplitThread(vLayer, self.inField.currentText(), self.encoding, outDir)

        QObject.connect(self.workThread, SIGNAL("rangeCalculated(PyQt_PyObject)"), self.setProgressRange)
        QObject.connect(self.workThread, SIGNAL("valueProcessed()"), self.valueProcessed)
        QObject.connect(self.workThread, SIGNAL("processFinished(PyQt_PyObject)"), self.processFinished)
        QObject.connect(self.workThread, SIGNAL("processInterrupted()"), self.processInterrupted)

        self.btnClose.setText(self.tr("Cancel"))
        QObject.disconnect(self.buttonBox_2, SIGNAL("rejected()"), self.reject)
        QObject.connect(self.btnClose, SIGNAL("clicked()"), self.stopProcessing)

        self.workThread.start()

    def setProgressRange(self, maximum):
        self.progressBar.setRange(0, maximum)

    def valueProcessed(self):
        self.progressBar.setValue(self.progressBar.value() + 1)

    def restoreGui(self):
        self.progressBar.setValue(0)
        self.outShape.clear()
        QObject.connect(self.buttonBox_2, SIGNAL("rejected()"), self.reject)
        self.btnClose.setText(self.tr("Close"))
        self.btnOk.setEnabled(True)

    def stopProcessing(self):
        if self.workThread != None:
            self.workThread.stop()
            self.workThread = None

    def processInterrupted( self ):
        self.restoreGui()

    def processFinished(self, errors):
        self.stopProcessing()
        outPath = self.outShape.text()
        self.restoreGui()

        if errors:
            msg = self.tr( "Processing of the following layers/files ended with error:<br><br>" ) + "<br>".join(errors)
            QErrorMessage( self ).showMessage( msg )

        QMessageBox.information(self, self.tr("Vector Split"),
                                self.tr("Created output shapefiles in folder:\n%s") % (outPath))

class SplitThread(QThread):
    def __init__(self, layer, splitField, encoding, outDir):
        QThread.__init__(self, QThread.currentThread())
        self.layer = layer
        self.field = splitField
        self.encoding = encoding
        self.outDir = outDir

        self.mutex = QMutex()
        self.stopMe = 0

        self.errors = []

    def run(self):
        self.mutex.lock()
        self.stopMe = 0
        self.mutex.unlock()

        interrupted = False

        outPath = self.outDir

        if outPath.find("\\") != -1:
            outPath.replace("\\", "/")

        if not outPath.endswith("/"):
            outPath = outPath + "/"

        provider = self.layer.dataProvider()
        index = provider.fieldNameIndex(self.field)
        unique = ftools_utils.getUniqueValues(provider, int(index))
        baseName = unicode( outPath + self.layer.name() + "_" + self.field + "_" )

        fieldList = ftools_utils.getFieldList(self.layer)
        sRs = provider.crs()
        geom = self.layer.wkbType()
        inFeat = QgsFeature()

        self.emit(SIGNAL("rangeCalculated(PyQt_PyObject)"), len(unique))


        for i in unique:
            check = QFile(baseName + "_" + unicode(i).strip() + ".shp")
            fName = check.fileName()
            if check.exists():
                if not QgsVectorFileWriter.deleteShapeFile(fName):
                    self.errors.append( fName )
                    continue

            writer = QgsVectorFileWriter(fName, self.encoding, fieldList, geom, sRs)

            fit = provider.getFeatures()
            while fit.nextFeature(inFeat):
                atMap = inFeat.attributes()
                if atMap[index] == i:
                    writer.addFeature(inFeat)
            del writer

            self.emit(SIGNAL("valueProcessed()"))

            self.mutex.lock()
            s = self.stopMe
            self.mutex.unlock()
            if s == 1:
                interrupted = True
                break

        if not interrupted:
            self.emit(SIGNAL("processFinished( PyQt_PyObject )"), self.errors)
        else:
            self.emit(SIGNAL("processInterrupted()"))

    def stop(self):
        self.mutex.lock()
        self.stopMe = 1
        self.mutex.unlock()

        QThread.wait(self)