Skip to content

Commit 28f7a8b

Browse files
committed
Move expression context generation out of parameters
1 parent 416770b commit 28f7a8b

File tree

5 files changed

+33
-72
lines changed

5 files changed

+33
-72
lines changed

python/plugins/processing/core/GeoAlgorithm.py

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,6 @@ def execute(self, parameters, context=None, feedback=None, model=None):
120120
try:
121121
self.setOutputCRS()
122122
self.resolveOutputs()
123-
self.evaluateParameterValues()
124123
self.runPreExecutionScript(feedback)
125124
self.processAlgorithm(parameters, context, feedback)
126125
feedback.setProgress(100)
@@ -229,14 +228,6 @@ def getFormatShortNameFromFilename(self, filename):
229228
return name
230229
return 'GTiff'
231230

232-
def evaluateParameterValues(self):
233-
for param in self.parameters:
234-
try:
235-
param.evaluate(self)
236-
except ValueError as e:
237-
traceback.print_exc()
238-
raise GeoAlgorithmExecutionException(str(e))
239-
240231
def resolveOutputs(self):
241232
"""Sets temporary outputs (output.value = None) with a
242233
temporary file instead. Resolves expressions as well.

python/plugins/processing/core/parameters.py

Lines changed: 3 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,10 @@
3737
import numbers
3838

3939
from qgis.core import QgsProcessingUtils
40-
from qgis.utils import iface
40+
4141
from qgis.PyQt.QtCore import QCoreApplication
4242
from qgis.core import (QgsRasterLayer, QgsVectorLayer, QgsMapLayer, QgsCoordinateReferenceSystem,
43-
QgsExpressionContext, QgsExpressionContextUtils, QgsExpression, QgsExpressionContextScope,
43+
QgsExpression,
4444
QgsProject,
4545
QgsRectangle,
4646
QgsVectorFileWriter,
@@ -72,25 +72,6 @@ def _createDescriptiveName(s):
7272
return s.replace('_', ' ')
7373

7474

75-
def _expressionContext():
76-
context = QgsExpressionContext()
77-
context.appendScope(QgsExpressionContextUtils.globalScope())
78-
context.appendScope(QgsExpressionContextUtils.projectScope(QgsProject.instance()))
79-
80-
if iface.mapCanvas():
81-
context.appendScope(QgsExpressionContextUtils.mapSettingsScope(iface.mapCanvas().mapSettings()))
82-
83-
processingScope = QgsExpressionContextScope()
84-
85-
extent = iface.mapCanvas().fullExtent()
86-
processingScope.setVariable('fullextent_minx', extent.xMinimum())
87-
processingScope.setVariable('fullextent_miny', extent.yMinimum())
88-
processingScope.setVariable('fullextent_maxx', extent.xMaximum())
89-
processingScope.setVariable('fullextent_maxy', extent.yMaximum())
90-
context.appendScope(processingScope)
91-
return context
92-
93-
9475
class Parameter(object):
9576

9677
"""
@@ -139,9 +120,6 @@ def tr(self, string, context=''):
139120
context = 'Parameter'
140121
return QCoreApplication.translate(context, string)
141122

142-
def evaluate(self, alg):
143-
pass
144-
145123

146124
class ParameterBoolean(Parameter):
147125

@@ -726,8 +704,7 @@ def setValue(self, n):
726704

727705
if isinstance(n, str):
728706
try:
729-
v = self._evaluate(n)
730-
self.value = float(v)
707+
self.value = float(n)
731708
if self.isInteger:
732709
self.value = int(math.floor(self.value))
733710
return True
@@ -772,22 +749,6 @@ def fromScriptCode(self, line):
772749
default = None
773750
return ParameterNumber(name, descName, default=default, optional=isOptional)
774751

775-
def _evaluate(self, value):
776-
exp = QgsExpression(value)
777-
if exp.hasParserError():
778-
raise ValueError(self.tr("Error in parameter expression: ") + exp.parserErrorString())
779-
result = exp.evaluate(_expressionContext())
780-
if exp.hasEvalError():
781-
raise ValueError("Error evaluating parameter expression: " + exp.evalErrorString())
782-
if self.isInteger:
783-
return math.floor(result)
784-
else:
785-
return result
786-
787-
def evaluate(self, alg):
788-
if isinstance(self.value, str) and bool(self.value):
789-
self.value = self._evaluate(self.value)
790-
791752
def _layerVariables(self, element, alg=None):
792753
variables = {}
793754
context = dataobjects.createContext()
@@ -827,9 +788,6 @@ def evaluateForModeler(self, value, model):
827788

828789
return value
829790

830-
def expressionContext(self):
831-
return _expressionContext()
832-
833791
def getValueAsCommandLineParameter(self):
834792
if self.value is None:
835793
return str(None)
@@ -1070,7 +1028,6 @@ def __init__(self, name='', description='', default=None, multiline=False,
10701028
optional=False, evaluateExpressions=False, metadata={}):
10711029
Parameter.__init__(self, name, description, default, optional, metadata)
10721030
self.multiline = parseBool(multiline)
1073-
self.evaluateExpressions = parseBool(evaluateExpressions)
10741031

10751032
def setValue(self, obj):
10761033
if not bool(obj):
@@ -1118,19 +1075,6 @@ def fromScriptCode(self, line):
11181075
else:
11191076
return ParameterString(name, descName, multiline=True, optional=isOptional)
11201077

1121-
def evaluate(self, alg):
1122-
if isinstance(self.value, str) and bool(self.value) and self.evaluateExpressions:
1123-
exp = QgsExpression(self.value)
1124-
if exp.hasParserError():
1125-
raise ValueError(self.tr("Error in parameter expression: ") + exp.parserErrorString())
1126-
result = exp.evaluate(_expressionContext())
1127-
if exp.hasEvalError():
1128-
raise ValueError("Error evaluating parameter expression: " + exp.evalErrorString())
1129-
self.value = result
1130-
1131-
def expressionContext(self):
1132-
return _expressionContext()
1133-
11341078

11351079
class ParameterExpression(Parameter):
11361080

python/plugins/processing/gui/NumberInputPanel.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
from processing.core.parameters import ParameterNumber, ParameterVector, ParameterRaster
4040
from processing.core.outputs import OutputNumber, OutputVector, OutputRaster
4141
from processing.modeler.ModelerAlgorithm import ValueFromInput, ValueFromOutput, CompoundValue
42+
from processing.tools.dataobjects import createExpressionContext
4243

4344
pluginPath = os.path.split(os.path.dirname(__file__))[0]
4445
NUMBER_WIDGET, NUMBER_BASE = uic.loadUiType(
@@ -48,6 +49,7 @@
4849

4950

5051
class ModellerNumberInputPanel(BASE, WIDGET):
52+
5153
"""
5254
Number input panel for use inside the modeller - this input panel
5355
is based off the base input panel and includes a text based line input
@@ -70,7 +72,7 @@ def __init__(self, param, modelParametersDialog):
7072
self.leText.textChanged.connect(lambda: self.hasChanged.emit())
7173

7274
def showExpressionsBuilder(self):
73-
context = self.param.expressionContext()
75+
context = createExpressionContext()
7476
dlg = QgsExpressionBuilderDialog(None, str(self.leText.text()), self, 'generic', context)
7577

7678
context.popScope()
@@ -138,6 +140,7 @@ def setValue(self, value):
138140

139141

140142
class NumberInputPanel(NUMBER_BASE, NUMBER_WIDGET):
143+
141144
"""
142145
Number input panel for use outside the modeller - this input panel
143146
contains a user friendly spin box for entering values. It also
@@ -195,7 +198,7 @@ def __init__(self, param):
195198
self.spnValue.valueChanged.connect(lambda: self.hasChanged.emit())
196199

197200
def showExpressionsBuilder(self):
198-
context = self.param.expressionContext()
201+
context = createExpressionContext()
199202
dlg = QgsExpressionBuilderDialog(None, str(self.spnValue.value()), self, 'generic', context)
200203

201204
dlg.setWindowTitle(self.tr('Expression based input'))

python/plugins/processing/gui/wrappers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,7 @@ def wrapWithExpressionButton(self, basewidget):
230230
return widget
231231

232232
def showExpressionsBuilder(self):
233-
context = self.param.expressionContext()
233+
context = dataobjects.createExpressionContext()
234234
value = self.value()
235235
if not isinstance(value, str):
236236
value = ''

python/plugins/processing/tools/dataobjects.py

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,13 @@
4040
QgsSettings,
4141
QgsProcessingUtils,
4242
QgsProcessingContext,
43-
QgsFeatureRequest)
43+
QgsFeatureRequest,
44+
QgsExpressionContext,
45+
QgsExpressionContextUtils,
46+
QgsExpressionContextScope)
4447
from qgis.gui import QgsSublayersDialog
4548
from qgis.PyQt.QtCore import QCoreApplication
49+
from qgis.utils import iface
4650

4751
from processing.core.ProcessingConfig import ProcessingConfig
4852
from processing.algs.gdal.GdalUtils import GdalUtils
@@ -91,6 +95,25 @@ def raise_error(f):
9195
return context
9296

9397

98+
def createExpressionContext():
99+
context = QgsExpressionContext()
100+
context.appendScope(QgsExpressionContextUtils.globalScope())
101+
context.appendScope(QgsExpressionContextUtils.projectScope(QgsProject.instance()))
102+
103+
if iface.mapCanvas():
104+
context.appendScope(QgsExpressionContextUtils.mapSettingsScope(iface.mapCanvas().mapSettings()))
105+
106+
processingScope = QgsExpressionContextScope()
107+
108+
extent = iface.mapCanvas().fullExtent()
109+
processingScope.setVariable('fullextent_minx', extent.xMinimum())
110+
processingScope.setVariable('fullextent_miny', extent.yMinimum())
111+
processingScope.setVariable('fullextent_maxx', extent.xMaximum())
112+
processingScope.setVariable('fullextent_maxy', extent.yMaximum())
113+
context.appendScope(processingScope)
114+
return context
115+
116+
94117
def getSupportedOutputRasterLayerExtensions():
95118
allexts = []
96119
for exts in list(GdalUtils.getSupportedRasters().values()):

0 commit comments

Comments
 (0)