File: ProcessingConfig.py

package info (click to toggle)
qgis 3.40.10%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,183,672 kB
  • sloc: cpp: 1,595,771; python: 372,544; xml: 23,474; sh: 3,761; perl: 3,664; ansic: 2,257; sql: 2,137; yacc: 1,068; lex: 577; javascript: 540; lisp: 411; makefile: 161
file content (489 lines) | stat: -rw-r--r-- 16,721 bytes parent folder | download | duplicates (6)
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
"""
***************************************************************************
    ProcessingConfig.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"

import os
import tempfile

from qgis.PyQt.QtCore import QCoreApplication, QObject, pyqtSignal
from qgis.core import (
    NULL,
    QgsApplication,
    QgsSettings,
    QgsVectorFileWriter,
    QgsRasterFileWriter,
    QgsProcessingUtils,
)
from processing.tools.system import defaultOutputFolder
import processing.tools.dataobjects
from multiprocessing import cpu_count


class SettingsWatcher(QObject):
    settingsChanged = pyqtSignal()


settingsWatcher = SettingsWatcher()


class ProcessingConfig:
    OUTPUT_FOLDER = "OUTPUTS_FOLDER"
    RASTER_STYLE = "RASTER_STYLE"
    VECTOR_POINT_STYLE = "VECTOR_POINT_STYLE"
    VECTOR_LINE_STYLE = "VECTOR_LINE_STYLE"
    VECTOR_POLYGON_STYLE = "VECTOR_POLYGON_STYLE"
    FILTER_INVALID_GEOMETRIES = "FILTER_INVALID_GEOMETRIES"
    PREFER_FILENAME_AS_LAYER_NAME = "prefer-filename-as-layer-name"
    KEEP_DIALOG_OPEN = "KEEP_DIALOG_OPEN"
    PRE_EXECUTION_SCRIPT = "PRE_EXECUTION_SCRIPT"
    POST_EXECUTION_SCRIPT = "POST_EXECUTION_SCRIPT"
    SHOW_CRS_DEF = "SHOW_CRS_DEF"
    WARN_UNMATCHING_CRS = "WARN_UNMATCHING_CRS"
    SHOW_PROVIDERS_TOOLTIP = "SHOW_PROVIDERS_TOOLTIP"
    SHOW_ALGORITHMS_KNOWN_ISSUES = "SHOW_ALGORITHMS_KNOWN_ISSUES"
    MAX_THREADS = "MAX_THREADS"
    DEFAULT_OUTPUT_RASTER_LAYER_EXT = "default-output-raster-ext"
    DEFAULT_OUTPUT_VECTOR_LAYER_EXT = "default-output-vector-ext"
    TEMP_PATH = "temp-path"
    RESULTS_GROUP_NAME = "RESULTS_GROUP_NAME"
    VECTOR_FEATURE_COUNT = "VECTOR_FEATURE_COUNT"

    settings = {}
    settingIcons = {}

    @staticmethod
    def initialize():
        icon = QgsApplication.getThemeIcon("/processingAlgorithm.svg")
        ProcessingConfig.settingIcons["General"] = icon
        ProcessingConfig.addSetting(
            Setting(
                ProcessingConfig.tr("General"),
                ProcessingConfig.KEEP_DIALOG_OPEN,
                ProcessingConfig.tr("Keep dialog open after running an algorithm"),
                True,
            )
        )
        ProcessingConfig.addSetting(
            Setting(
                ProcessingConfig.tr("General"),
                ProcessingConfig.PREFER_FILENAME_AS_LAYER_NAME,
                ProcessingConfig.tr("Prefer output filename for layer names"),
                True,
                hasSettingEntry=True,
            )
        )
        ProcessingConfig.addSetting(
            Setting(
                ProcessingConfig.tr("General"),
                ProcessingConfig.SHOW_PROVIDERS_TOOLTIP,
                ProcessingConfig.tr("Show tooltip when there are disabled providers"),
                True,
            )
        )
        ProcessingConfig.addSetting(
            Setting(
                ProcessingConfig.tr("General"),
                ProcessingConfig.OUTPUT_FOLDER,
                ProcessingConfig.tr("Output folder"),
                defaultOutputFolder(),
                valuetype=Setting.FOLDER,
            )
        )
        ProcessingConfig.addSetting(
            Setting(
                ProcessingConfig.tr("General"),
                ProcessingConfig.SHOW_CRS_DEF,
                ProcessingConfig.tr("Show layer CRS definition in selection boxes"),
                True,
            )
        )
        ProcessingConfig.addSetting(
            Setting(
                ProcessingConfig.tr("General"),
                ProcessingConfig.WARN_UNMATCHING_CRS,
                ProcessingConfig.tr(
                    "Warn before executing if parameter CRS's do not match"
                ),
                True,
            )
        )
        ProcessingConfig.addSetting(
            Setting(
                ProcessingConfig.tr("General"),
                ProcessingConfig.SHOW_ALGORITHMS_KNOWN_ISSUES,
                ProcessingConfig.tr("Show algorithms with known issues"),
                False,
            )
        )
        ProcessingConfig.addSetting(
            Setting(
                ProcessingConfig.tr("General"),
                ProcessingConfig.RASTER_STYLE,
                ProcessingConfig.tr("Style for raster layers"),
                "",
                valuetype=Setting.FILE,
            )
        )
        ProcessingConfig.addSetting(
            Setting(
                ProcessingConfig.tr("General"),
                ProcessingConfig.VECTOR_POINT_STYLE,
                ProcessingConfig.tr("Style for point layers"),
                "",
                valuetype=Setting.FILE,
            )
        )
        ProcessingConfig.addSetting(
            Setting(
                ProcessingConfig.tr("General"),
                ProcessingConfig.VECTOR_LINE_STYLE,
                ProcessingConfig.tr("Style for line layers"),
                "",
                valuetype=Setting.FILE,
            )
        )
        ProcessingConfig.addSetting(
            Setting(
                ProcessingConfig.tr("General"),
                ProcessingConfig.VECTOR_POLYGON_STYLE,
                ProcessingConfig.tr("Style for polygon layers"),
                "",
                valuetype=Setting.FILE,
            )
        )
        ProcessingConfig.addSetting(
            Setting(
                ProcessingConfig.tr("General"),
                ProcessingConfig.PRE_EXECUTION_SCRIPT,
                ProcessingConfig.tr("Pre-execution script"),
                "",
                valuetype=Setting.FILE,
            )
        )
        ProcessingConfig.addSetting(
            Setting(
                ProcessingConfig.tr("General"),
                ProcessingConfig.POST_EXECUTION_SCRIPT,
                ProcessingConfig.tr("Post-execution script"),
                "",
                valuetype=Setting.FILE,
            )
        )

        invalidFeaturesOptions = [
            ProcessingConfig.tr("Do not filter (better performance)"),
            ProcessingConfig.tr("Skip (ignore) features with invalid geometries"),
            ProcessingConfig.tr("Stop algorithm execution when a geometry is invalid"),
        ]
        ProcessingConfig.addSetting(
            Setting(
                ProcessingConfig.tr("General"),
                ProcessingConfig.FILTER_INVALID_GEOMETRIES,
                ProcessingConfig.tr("Invalid features filtering"),
                invalidFeaturesOptions[2],
                valuetype=Setting.SELECTION,
                options=invalidFeaturesOptions,
            )
        )

        threads = (
            QgsApplication.maxThreads()
        )  # if user specified limit for rendering, lets keep that as default here, otherwise max
        threads = (
            cpu_count() if threads == -1 else threads
        )  # if unset, maxThreads() returns -1
        ProcessingConfig.addSetting(
            Setting(
                ProcessingConfig.tr("General"),
                ProcessingConfig.MAX_THREADS,
                ProcessingConfig.tr("Max Threads"),
                threads,
                valuetype=Setting.INT,
            )
        )

        extensions = QgsVectorFileWriter.supportedFormatExtensions()
        ProcessingConfig.addSetting(
            Setting(
                ProcessingConfig.tr("General"),
                ProcessingConfig.DEFAULT_OUTPUT_VECTOR_LAYER_EXT,
                ProcessingConfig.tr("Default output vector layer extension"),
                QgsVectorFileWriter.supportedFormatExtensions()[0],
                valuetype=Setting.SELECTION_STORE_STRING,
                options=extensions,
                hasSettingEntry=True,
            )
        )

        extensions = QgsRasterFileWriter.supportedFormatExtensions()
        ProcessingConfig.addSetting(
            Setting(
                ProcessingConfig.tr("General"),
                ProcessingConfig.DEFAULT_OUTPUT_RASTER_LAYER_EXT,
                ProcessingConfig.tr("Default output raster layer extension"),
                "tif",
                valuetype=Setting.SELECTION_STORE_STRING,
                options=extensions,
                hasSettingEntry=True,
            )
        )

        ProcessingConfig.addSetting(
            Setting(
                ProcessingConfig.tr("General"),
                ProcessingConfig.TEMP_PATH,
                ProcessingConfig.tr("Override temporary output folder path"),
                None,
                valuetype=Setting.FOLDER,
                placeholder=ProcessingConfig.tr("Leave blank for default"),
                hasSettingEntry=True,
            )
        )

        ProcessingConfig.addSetting(
            Setting(
                ProcessingConfig.tr("General"),
                ProcessingConfig.RESULTS_GROUP_NAME,
                ProcessingConfig.tr("Results group name"),
                "",
                valuetype=Setting.STRING,
                placeholder=ProcessingConfig.tr(
                    "Leave blank to avoid loading results in a predetermined group"
                ),
            )
        )

        ProcessingConfig.addSetting(
            Setting(
                ProcessingConfig.tr("General"),
                ProcessingConfig.VECTOR_FEATURE_COUNT,
                ProcessingConfig.tr("Show feature count for output vector layers"),
                False,
            )
        )

    @staticmethod
    def setGroupIcon(group, icon):
        ProcessingConfig.settingIcons[group] = icon

    @staticmethod
    def getGroupIcon(group):
        if group == ProcessingConfig.tr("General"):
            return QgsApplication.getThemeIcon("/processingAlgorithm.svg")
        if group in ProcessingConfig.settingIcons:
            return ProcessingConfig.settingIcons[group]
        else:
            return QgsApplication.getThemeIcon("/processingAlgorithm.svg")

    @staticmethod
    def addSetting(setting):
        ProcessingConfig.settings[setting.name] = setting

    @staticmethod
    def removeSetting(name):
        del ProcessingConfig.settings[name]

    @staticmethod
    def getSettings():
        """Return settings as a dict with group names as keys and lists of settings as values"""
        settings = {}
        for setting in list(ProcessingConfig.settings.values()):
            if setting.group not in settings:
                group = []
                settings[setting.group] = group
            else:
                group = settings[setting.group]
            group.append(setting)
        return settings

    @staticmethod
    def readSettings():
        for setting in list(ProcessingConfig.settings.values()):
            setting.read()

    @staticmethod
    def getSetting(name, readable=False):
        if name not in list(ProcessingConfig.settings.keys()):
            return None
        v = ProcessingConfig.settings[name].value
        try:
            if v == NULL:
                v = None
        except:
            pass
        if ProcessingConfig.settings[name].valuetype != Setting.SELECTION:
            return v
        if readable:
            return v
        return ProcessingConfig.settings[name].options.index(v)

    @staticmethod
    def setSettingValue(name, value):
        if name in list(ProcessingConfig.settings.keys()):
            if ProcessingConfig.settings[name].valuetype == Setting.SELECTION:
                ProcessingConfig.settings[name].setValue(
                    ProcessingConfig.settings[name].options[value]
                )
            else:
                ProcessingConfig.settings[name].setValue(value)
            ProcessingConfig.settings[name].save()

    @staticmethod
    def tr(string, context=""):
        if context == "":
            context = "ProcessingConfig"
        return QCoreApplication.translate(context, string)


class Setting:
    """A simple config parameter that will appear on the config dialog."""

    STRING = 0
    FILE = 1
    FOLDER = 2
    SELECTION = 3
    FLOAT = 4
    INT = 5
    MULTIPLE_FOLDERS = 6
    SELECTION_STORE_STRING = 7

    def __init__(
        self,
        group,
        name,
        description,
        default,
        hidden=False,
        valuetype=None,
        validator=None,
        options=None,
        placeholder="",
        hasSettingEntry=False,
    ):
        """
        hasSettingEntry is true if the given setting is part of QgsSettingsRegistry entries
        """
        self.group = group
        self.name = name
        self.qname = (
            "qgis/configuration/" if hasSettingEntry else "Processing/Configuration/"
        ) + self.name
        self.description = description
        self.default = default
        self.hidden = hidden
        self.valuetype = valuetype
        self.options = options
        self.placeholder = placeholder

        if self.valuetype is None:
            if isinstance(default, int):
                self.valuetype = self.INT
            elif isinstance(default, float):
                self.valuetype = self.FLOAT

        if validator is None:
            if self.valuetype == self.FLOAT:

                def checkFloat(v):
                    try:
                        float(v)
                    except ValueError:
                        raise ValueError(
                            self.tr("Wrong parameter value:\n{0}").format(v)
                        )

                validator = checkFloat
            elif self.valuetype == self.INT:

                def checkInt(v):
                    try:
                        int(v)
                    except ValueError:
                        raise ValueError(
                            self.tr("Wrong parameter value:\n{0}").format(v)
                        )

                validator = checkInt
            elif self.valuetype in [self.FILE, self.FOLDER]:

                def checkFileOrFolder(v):
                    if v and not os.path.exists(v):
                        raise ValueError(
                            self.tr("Specified path does not exist:\n{0}").format(v)
                        )

                validator = checkFileOrFolder
            elif self.valuetype == self.MULTIPLE_FOLDERS:

                def checkMultipleFolders(v):
                    folders = v.split(";")
                    for f in folders:
                        if f and not os.path.exists(f):
                            raise ValueError(
                                self.tr("Specified path does not exist:\n{0}").format(f)
                            )

                validator = checkMultipleFolders
            else:

                def validator(x):
                    return True

        self.validator = validator
        self.value = default

    def setValue(self, value):
        self.validator(value)
        self.value = value

    def read(self, qsettings=None):
        if not qsettings:
            qsettings = QgsSettings()
        value = qsettings.value(self.qname, None)
        if value is not None:
            if isinstance(self.value, bool):
                value = str(value).lower() == str(True).lower()

            if self.valuetype == self.SELECTION:
                try:
                    self.value = self.options[int(value)]
                except:
                    self.value = self.options[0]
            else:
                self.value = value

    def save(self, qsettings=None):
        if not qsettings:
            qsettings = QgsSettings()
        if self.value == self.default:
            qsettings.remove(self.qname)
            return
        if self.valuetype == self.SELECTION:
            qsettings.setValue(self.qname, self.options.index(self.value))
        else:
            qsettings.setValue(self.qname, self.value)

    def __str__(self):
        return self.name + "=" + str(self.value)

    def tr(self, string, context=""):
        if context == "":
            context = "ProcessingConfig"
        return QCoreApplication.translate(context, string)