File: dataobjects.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 (365 lines) | stat: -rw-r--r-- 12,871 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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# -*- coding: utf-8 -*-

"""
***************************************************************************
    dataobject.py
    ---------------------
    Date                 : August 2012
    Copyright            : (C) 2012 by Victor Olaya
    Email                : volayaf at gmail dot com
***************************************************************************
*                                                                         *
*   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.                                   *
*                                                                         *
***************************************************************************
"""

__author__ = 'Victor Olaya'
__date__ = 'August 2012'
__copyright__ = '(C) 2012, Victor Olaya'

# This will get replaced with a git SHA1 when you do a git archive

__revision__ = '$Format:%H$'

from os import path
from qgis.core import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.utils import iface
from processing.core.ProcessingConfig import ProcessingConfig
from processing.algs.gdal.GdalUtils import GdalUtils
from processing.tools.system import *

ALL_TYPES = [-1]

_loadedLayers = {}

def resetLoadedLayers():
    global _loadedLayers
    _loadedLayers = {}

def getSupportedOutputVectorLayerExtensions():
    formats = QgsVectorFileWriter.supportedFiltersAndFormats()
    exts = ['shp']  # shp is the default, should be the first
    for extension in formats.keys():
        extension = unicode(extension)
        extension = extension[extension.find('*.') + 2:]
        extension = extension[:extension.find(' ')]
        if extension.lower() != 'shp':
            exts.append(extension)
    return exts


def getSupportedOutputRasterLayerExtensions():
    allexts = ['tif']
    for exts in GdalUtils.getSupportedRasters().values():
        for ext in exts:
            if ext not in allexts:
                allexts.append(ext)
    return allexts


def getSupportedOutputTableExtensions():
    exts = ['csv']
    return exts


def getRasterLayers():
    layers = QgsMapLayerRegistry.instance().mapLayers().values()
    raster = []

    for layer in layers:
        if layer.type() == layer.RasterLayer:
            if layer.providerType() == 'gdal':  # only gdal file-based layers
                raster.append(layer)
    return sorted(raster,  key=lambda layer: layer.name().lower())


def getVectorLayers(shapetype=[-1]):
    layers = QgsMapLayerRegistry.instance().mapLayers().values()
    vector = []
    for layer in layers:
        if layer.type() == layer.VectorLayer:
            if shapetype == ALL_TYPES or layer.geometryType() in shapetype:
                uri = unicode(layer.source())
                if not uri.lower().endswith('csv') and not uri.lower().endswith('dbf'):
                    vector.append(layer)
    return sorted(vector,  key=lambda layer: layer.name().lower())


def getAllLayers():
    layers = []
    layers += getRasterLayers()
    layers += getVectorLayers()
    return sorted(layers,  key=lambda layer: layer.name().lower())


def getTables():
    layers = QgsMapLayerRegistry.instance().mapLayers().values()
    tables = list()
    for layer in layers:
        if layer.type() == layer.VectorLayer:
            tables.append(layer)
    return sorted(tables,  key=lambda table: table.name().lower())


def extent(layers):
    first = True
    for layer in layers:
        if not isinstance(layer, (QgsRasterLayer, QgsVectorLayer)):
            layer = getObjectFromUri(layer)
            if layer is None:
                continue
        if first:
            xmin = layer.extent().xMinimum()
            xmax = layer.extent().xMaximum()
            ymin = layer.extent().yMinimum()
            ymax = layer.extent().yMaximum()
        else:
            xmin = min(xmin, layer.extent().xMinimum())
            xmax = max(xmax, layer.extent().xMaximum())
            ymin = min(ymin, layer.extent().yMinimum())
            ymax = max(ymax, layer.extent().yMaximum())
        first = False
    if first:
        return '0,0,0,0'
    else:
        return str(xmin) + ',' + str(xmax) + ',' + str(ymin) + ',' + str(ymax)


def loadList(layers):
    for layer in layers:
        load(layer)


def load(fileName, name=None, crs=None, style=None):
    """Loads a layer/table into the current project, given its file.
    """

    if fileName is None:
        return
    prjSetting = None
    settings = QSettings()
    if crs is not None:
        prjSetting = settings.value('/Projections/defaultBehaviour')
        settings.setValue('/Projections/defaultBehaviour', '')
    if name is None:
        name = path.split(fileName)[1]
    qgslayer = QgsVectorLayer(fileName, name, 'ogr')
    if qgslayer.isValid():
        if crs is not None and qgslayer.crs() is None:
            qgslayer.setCrs(crs, False)
        if style is None:
            if qgslayer.geometryType == 0:
                style = ProcessingConfig.getSetting(
                        ProcessingConfig.VECTOR_POINT_STYLE)
            elif qgslayer.geometryType == 1:
                style = ProcessingConfig.getSetting(
                        ProcessingConfig.VECTOR_LINE_STYLE)
            else:
                style = ProcessingConfig.getSetting(
                        ProcessingConfig.VECTOR_POLYGON_STYLE)
        qgslayer.loadNamedStyle(style)
        QgsMapLayerRegistry.instance().addMapLayers([qgslayer])
    else:
        qgslayer = QgsRasterLayer(fileName, name)
        if qgslayer.isValid():
            if crs is not None:
                qgslayer.setCrs(crs, False)
            if style is None:
                style = ProcessingConfig.getSetting(
                        ProcessingConfig.RASTER_STYLE)
            qgslayer.loadNamedStyle(style)
            QgsMapLayerRegistry.instance().addMapLayers([qgslayer])
            iface.legendInterface().refreshLayerSymbology(qgslayer)
        else:
            if prjSetting:
                settings.setValue('/Projections/defaultBehaviour', prjSetting)
            raise RuntimeError(
                    'Could not load layer: ' + unicode(fileName)
                    + '\nCheck the procesing framework log to look for errors')
    if prjSetting:
        settings.setValue('/Projections/defaultBehaviour', prjSetting)

    return qgslayer


def getObjectFromName(name):
    layers = getAllLayers()
    for layer in layers:
        if layer.name() == name:
            return layer


def getObject(uriorname):
    ret = getObjectFromName(uriorname)
    if ret is None:
        ret = getObjectFromUri(uriorname)
    return ret


def getObjectFromUri(uri, forceLoad=True):
    """Returns an object (layer/table) given a file location.

    if forceLoad is true, it tries to load it if it is not currently open
    Otherwise, it will return the object only if it is loaded in QGIS.
    """

    if uri is None:
        return None
    print _loadedLayers
    if uri in _loadedLayers:
        return _loadedLayers[uri]
    layers = getRasterLayers()
    for layer in layers:
        if layer.source() == uri:
            return layer
    layers = getVectorLayers()
    for layer in layers:
        if layer.source() == uri:
            return layer
    tables = getTables()
    for table in tables:
        if table.source() == uri:
            return table
    if forceLoad:
        settings = QSettings()
        prjSetting = settings.value('/Projections/defaultBehaviour')
        settings.setValue('/Projections/defaultBehaviour', '')

        # If is not opened, we open it
        layer = QgsVectorLayer(uri, uri, 'ogr')
        if layer.isValid():
            if prjSetting:
                settings.setValue('/Projections/defaultBehaviour', prjSetting)
            _loadedLayers[layer.source()] = layer
            return layer
        layer = QgsRasterLayer(uri, uri)
        if layer.isValid():
            if prjSetting:
                settings.setValue('/Projections/defaultBehaviour', prjSetting)
            _loadedLayers[layer.source()] = layer
            return layer
        if prjSetting:
            settings.setValue('/Projections/defaultBehaviour', prjSetting)
    else:
        return None


def exportVectorLayer(layer):
    """Takes a QgsVectorLayer and returns the filename to refer to it,
    which allows external apps which support only file-based layers to
    use it. It performs the necessary export in case the input layer
    is not in a standard format suitable for most applications, it is
    a remote one or db-based (non-file based) one, or if there is a
    selection and it should be used, exporting just the selected
    features.

    Currently, the output is restricted to shapefiles, so anything
    that is not in a shapefile will get exported. It also export to
    a new file if the original one contains non-ascii characters.
    """

    settings = QSettings()
    systemEncoding = settings.value('/UI/encoding', 'System')

    filename = os.path.basename(unicode(layer.source()))
    idx = filename.rfind('.')
    if idx != -1:
        filename = filename[:idx]

    filename = unicode(layer.name())
    validChars = \
        'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:'
    filename = ''.join(c for c in filename if c in validChars)
    if len(filename) == 0:
        filename = 'layer'
    output = getTempFilenameInTempFolder(filename + '.shp')
    provider = layer.dataProvider()
    useSelection = ProcessingConfig.getSetting(ProcessingConfig.USE_SELECTED)
    if useSelection and layer.selectedFeatureCount() != 0:
        writer = QgsVectorFileWriter(output, systemEncoding,
                                     layer.pendingFields(),
                                     provider.geometryType(), layer.crs())
        selection = layer.selectedFeatures()
        for feat in selection:
            writer.addFeature(feat)
        del writer
        return output
    else:
        isASCII = True
        try:
            unicode(layer.source()).decode('ascii')
        except UnicodeEncodeError:
            isASCII = False
        if not unicode(layer.source()).endswith('shp') or not isASCII:
            writer = QgsVectorFileWriter(output, systemEncoding,
                    layer.pendingFields(), provider.geometryType(),
                    layer.crs())
            for feat in layer.getFeatures():
                writer.addFeature(feat)
            del writer
            return output
        else:
            return unicode(layer.source())


def exportRasterLayer(layer):
    """Takes a QgsRasterLayer and returns the filename to refer to it,
    which allows external apps which support only file-based layers to
    use it. It performs the necessary export in case the input layer
    is not in a standard format suitable for most applications, it is
    a remote one or db-based (non-file based) one.

    Currently, the output is restricted to geotiff, but not all other
    formats are exported. Only those formats not supported by GDAL are
    exported, so it is assumed that the external app uses GDAL to read
    the layer.
    """

    # TODO: Do the conversion here
    return unicode(layer.source())


def exportTable(table):
    """Takes a QgsVectorLayer and returns the filename to refer to its
    attributes table, which allows external apps which support only
    file-based layers to use it.

    It performs the necessary export in case the input layer is not in
    a standard format suitable for most applications, it isa remote
    one or db-based (non-file based) one.

    Currently, the output is restricted to DBF. It also export to a new
    file if the original one contains non-ascii characters.
    """

    settings = QSettings()
    systemEncoding = settings.value('/UI/encoding', 'System')
    output = getTempFilename('dbf')
    provider = table.dataProvider()
    isASCII = True
    try:
        unicode(table.source()).decode('ascii')
    except UnicodeEncodeError:
        isASCII = False
    isDbf = unicode(table.source()).endswith('dbf') \
        or unicode(table.source()).endswith('shp')
    if not isDbf or not isASCII:
        writer = QgsVectorFileWriter(output, systemEncoding,
                                     provider.fields(), QGis.WKBNoGeometry,
                                     QgsCoordinateReferenceSystem('4326'))
        for feat in table.getFeatures():
            writer.addFeature(feat)
        del writer
        return output
    else:
        filename = unicode(table.source())
        if unicode(table.source()).endswith('shp'):
            return filename[:-3] + 'dbf'
        else:
            return filename