/
Processing.py
executable file
·255 lines (226 loc) · 11.1 KB
/
Processing.py
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
# -*- coding: utf-8 -*-
"""
***************************************************************************
Processing.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. *
* *
***************************************************************************
"""
from __future__ import print_function
from builtins import str
from builtins import object
__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$'
import os
import traceback
from qgis.PyQt.QtCore import Qt, QCoreApplication
from qgis.PyQt.QtWidgets import QApplication
from qgis.PyQt.QtGui import QCursor
from qgis.utils import iface
from qgis.core import (QgsMessageLog,
QgsApplication,
QgsProcessingProvider,
QgsProcessingUtils,
QgsProcessingParameterDefinition)
import processing
from processing.script.ScriptUtils import ScriptUtils
from processing.core.ProcessingConfig import ProcessingConfig
from processing.core.GeoAlgorithm import GeoAlgorithm
from processing.gui.MessageBarProgress import MessageBarProgress
from processing.gui.RenderingStyles import RenderingStyles
from processing.gui.Postprocessing import handleAlgorithmResults
from processing.gui.AlgorithmExecutor import execute
from processing.tools import dataobjects
from processing.algs.qgis.QGISAlgorithmProvider import QGISAlgorithmProvider # NOQA
#from processing.algs.grass7.Grass7AlgorithmProvider import Grass7AlgorithmProvider # NOQA
#from processing.algs.gdal.GdalAlgorithmProvider import GdalAlgorithmProvider # NOQA
#from processing.algs.saga.SagaAlgorithmProvider import SagaAlgorithmProvider # NOQA
#from processing.script.ScriptAlgorithmProvider import ScriptAlgorithmProvider # NOQA
#from processing.preconfigured.PreconfiguredAlgorithmProvider import PreconfiguredAlgorithmProvider # NOQA
# should be loaded last - ensures that all dependent algorithms are available when loading models
from processing.modeler.ModelerAlgorithmProvider import ModelerAlgorithmProvider # NOQA
class Processing(object):
BASIC_PROVIDERS = []
@staticmethod
def activateProvider(providerOrName, activate=True):
provider_id = providerOrName.id() if isinstance(providerOrName, QgsProcessingProvider) else providerOrName
provider = QgsApplication.processingRegistry().providerById(provider_id)
try:
provider.setActive(True)
provider.refreshAlgorithms()
except:
# provider could not be activated
QgsMessageLog.logMessage(Processing.tr('Error: Provider {0} could not be activated\n').format(provider_id),
Processing.tr("Processing"))
@staticmethod
def initialize():
if "model" in [p.id() for p in QgsApplication.processingRegistry().providers()]:
return
# Add the basic providers
for c in QgsProcessingProvider.__subclasses__():
p = c()
Processing.BASIC_PROVIDERS.append(p)
QgsApplication.processingRegistry().addProvider(p)
# And initialize
ProcessingConfig.initialize()
ProcessingConfig.readSettings()
RenderingStyles.loadStyles()
@staticmethod
def deinitialize():
for p in Processing.BASIC_PROVIDERS:
QgsApplication.processingRegistry().removeProvider(p)
Processing.BASIC_PROVIDERS = []
@staticmethod
def addScripts(folder):
Processing.initialize()
provider = QgsApplication.processingRegistry().providerById("qgis")
scripts = ScriptUtils.loadFromFolder(folder)
# fix_print_with_import
print(scripts)
for script in scripts:
script.allowEdit = False
script._icon = provider._icon
provider.externalAlgs.extend(scripts)
provider.refreshAlgorithms()
@staticmethod
def removeScripts(folder):
provider = QgsApplication.processingRegistry().providerById("qgis")
for alg in provider.externalAlgs[::-1]:
path = os.path.dirname(alg.descriptionFile)
if path == folder:
provider.externalAlgs.remove(alg)
provider.refreshAlgorithms()
@staticmethod
def runAlgorithm(algOrName, onFinish, *args, **kwargs):
if isinstance(algOrName, GeoAlgorithm):
alg = algOrName
else:
alg = QgsApplication.processingRegistry().algorithmById(algOrName)
if alg is None:
# fix_print_with_import
print('Error: Algorithm not found\n')
QgsMessageLog.logMessage(Processing.tr('Error: Algorithm {0} not found\n').format(algOrName),
Processing.tr("Processing"))
return
parameters = {}
if len(args) == 1 and isinstance(args[0], dict):
# Set params by name and try to run the alg even if not all parameter values are provided,
# by using the default values instead.
for (name, value) in list(args[0].items()):
param = alg.parameterDefinition(name)
if param:
parameters[param.name()] = value
continue
# fix_print_with_import
print('Error: Wrong parameter value %s for parameter %s.' % (value, name))
QgsMessageLog.logMessage(
Processing.tr('Error: Wrong parameter value {0} for parameter {1}.').format(value, name),
Processing.tr("Processing"))
QgsMessageLog.logMessage(Processing.tr('Error in {0}. Wrong parameter value {1} for parameter {2}.').format(
alg.name(), value, name
), Processing.tr("Processing"),
QgsMessageLog.CRITICAL
)
return
# check for any manadatory parameters which were not specified
for param in alg.parameterDefinitions():
if param.name() not in parameters:
if not param.flags() & QgsProcessingParameterDefinition.FlagOptional:
# fix_print_with_import
print('Error: Missing parameter value for parameter %s.' % param.name())
QgsMessageLog.logMessage(
Processing.tr('Error: Missing parameter value for parameter {0}.').format(param.name()),
Processing.tr("Processing"))
return
else:
if len(args) != alg.countVisibleParameters():
# fix_print_with_import
print('Error: Wrong number of parameters')
QgsMessageLog.logMessage(Processing.tr('Error: Wrong number of parameters'),
Processing.tr("Processing"))
processing.algorithmHelp(algOrName)
return
i = 0
for param in alg.parameterDefinitions():
if not param.flags() & QgsProcessingParameterDefinition.FlagHidden:
if not True: # TODO param.setValue(args[i]):
# fix_print_with_import
print('Error: Wrong parameter value: ' + str(args[i]))
QgsMessageLog.logMessage(Processing.tr('Error: Wrong parameter value: ') + str(args[i]),
Processing.tr("Processing"))
return
else:
parameters[param.name()] = args[i]
i = i + 1
for output in alg.outputs:
if not output.flags() & QgsProcessingParameterDefinition.FlagHidden:
if not output.setValue(args[i]):
# fix_print_with_import
print('Error: Wrong output value: ' + str(args[i]))
QgsMessageLog.logMessage(Processing.tr('Error: Wrong output value: ') + str(args[i]),
Processing.tr("Processing"))
return
i = i + 1
feedback = None
if kwargs is not None and "feedback" in list(kwargs.keys()):
feedback = kwargs["feedback"]
elif iface is not None:
feedback = MessageBarProgress(alg.displayName())
context = None
if kwargs is not None and 'context' in list(kwargs.keys()):
context = kwargs["context"]
else:
context = dataobjects.createContext(feedback)
ok, msg = alg.checkParameterValues(parameters, context)
if not ok:
# fix_print_with_import
print('Unable to execute algorithm\n' + str(msg))
QgsMessageLog.logMessage(Processing.tr('Unable to execute algorithm\n{0}').format(msg),
Processing.tr("Processing"))
return
if not alg.validateInputCrs(parameters, context):
print('Warning: Not all input layers use the same CRS.\n' +
'This can cause unexpected results.')
QgsMessageLog.logMessage(
Processing.tr('Warning: Not all input layers use the same CRS.\nThis can cause unexpected results.'),
Processing.tr("Processing"))
# Don't set the wait cursor twice, because then when you
# restore it, it will still be a wait cursor.
overrideCursor = False
if iface is not None:
cursor = QApplication.overrideCursor()
if cursor is None or cursor == 0:
QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
overrideCursor = True
elif cursor.shape() != Qt.WaitCursor:
QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
overrideCursor = True
ret, results = execute(alg, parameters, context, feedback)
if ret:
if onFinish is not None:
onFinish(alg, context, feedback)
else:
QgsMessageLog.logMessage(Processing.tr("There were errors executing the algorithm."),
Processing.tr("Processing"))
if overrideCursor:
QApplication.restoreOverrideCursor()
if isinstance(feedback, MessageBarProgress):
feedback.close()
return results
@staticmethod
def tr(string, context=''):
if context == '':
context = 'Processing'
return QCoreApplication.translate(context, string)