QGIS API Documentation 3.99.0-Master (8e76e220402)
Loading...
Searching...
No Matches
qgsprocessingcontext.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsprocessingcontext.cpp
3 ----------------------
4 begin : April 2017
5 copyright : (C) 2017 by Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
19
20#include "qgsprocessing.h"
21#include "qgsprocessingutils.h"
22#include "qgsproviderregistry.h"
23#include "qgsunittypes.h"
24
25#include <QString>
26
27using namespace Qt::StringLiterals;
28
29//
30// QgsProcessingContext
31//
32
34 : mPreferredVectorFormat( QgsProcessingUtils::defaultVectorExtension() )
35 , mPreferredRasterFormat( QgsProcessingUtils::defaultRasterFormat() )
36{
37 auto callback = [this]( const QgsFeature & feature )
38 {
39 if ( mFeedback )
40 mFeedback->reportError( QObject::tr( "Encountered a transform error when reprojecting feature with id %1." ).arg( feature.id() ) );
41 };
42 mTransformErrorCallback = callback;
43 mExpressionContext.setLoadedLayerStore( &tempLayerStore );
44}
45
47{
48 for ( auto it = mLayersToLoadOnCompletion.constBegin(); it != mLayersToLoadOnCompletion.constEnd(); ++it )
49 {
50 delete it.value().postProcessor();
51 }
52}
53
55{
56 mExpressionContext = context;
57 // any layers temporarily loaded by expressions should use the same temporary layer store as this context
58 mExpressionContext.setLoadedLayerStore( &tempLayerStore );
59}
60
61void QgsProcessingContext::setLayersToLoadOnCompletion( const QMap<QString, QgsProcessingContext::LayerDetails> &layers )
62{
63 for ( auto it = mLayersToLoadOnCompletion.constBegin(); it != mLayersToLoadOnCompletion.constEnd(); ++it )
64 {
65 if ( !layers.contains( it.key() ) || layers.value( it.key() ).postProcessor() != it.value().postProcessor() )
66 delete it.value().postProcessor();
67 }
68 mLayersToLoadOnCompletion = layers;
69}
70
72{
73 if ( mLayersToLoadOnCompletion.contains( layer ) && mLayersToLoadOnCompletion.value( layer ).postProcessor() != details.postProcessor() )
74 delete mLayersToLoadOnCompletion.value( layer ).postProcessor();
75
76 mLayersToLoadOnCompletion.insert( layer, details );
77}
78
80{
81 mInvalidGeometryCheck = check;
82 mUseDefaultInvalidGeometryCallback = true;
83 mInvalidGeometryCallback = defaultInvalidGeometryCallbackForCheck( check );
84}
85
86std::function<void ( const QgsFeature & )> QgsProcessingContext::invalidGeometryCallback( QgsFeatureSource *source ) const
87{
88 if ( mUseDefaultInvalidGeometryCallback )
89 return defaultInvalidGeometryCallbackForCheck( mInvalidGeometryCheck, source );
90 else
91 return mInvalidGeometryCallback;
92}
93
95{
96 const QString sourceName = source ? source->sourceName() : QString();
97 switch ( check )
98 {
100 {
101 auto callback = [sourceName]( const QgsFeature & feature )
102 {
103 if ( !sourceName.isEmpty() )
104 throw QgsProcessingException( QObject::tr( "Feature (%1) from “%2” has invalid geometry. Please fix the geometry or change the “Invalid features filtering” option for this input or globally in Processing settings." ).arg( feature.id() ).arg( sourceName ) );
105 else
106 throw QgsProcessingException( QObject::tr( "Feature (%1) has invalid geometry. Please fix the geometry or change the “Invalid features filtering” option for input layers or globally in Processing settings." ).arg( feature.id() ) );
107 };
108 return callback;
109 }
110
112 {
113 auto callback = [this, sourceName]( const QgsFeature & feature )
114 {
115 if ( mFeedback )
116 {
117 if ( !sourceName.isEmpty() )
118 mFeedback->reportError( QObject::tr( "Feature (%1) from “%2” has invalid geometry and has been skipped. Please fix the geometry or change the “Invalid features filtering” option for this input or globally in Processing settings." ).arg( feature.id() ).arg( sourceName ) );
119 else
120 mFeedback->reportError( QObject::tr( "Feature (%1) has invalid geometry and has been skipped. Please fix the geometry or change the “Invalid features filtering” option for input layers or globally in Processing settings." ).arg( feature.id() ) );
121 }
122 };
123 return callback;
124 }
125
127 return nullptr;
128 }
129 return nullptr;
130}
131
133{
134 setLayersToLoadOnCompletion( context.mLayersToLoadOnCompletion );
135 mModelResult = context.mModelResult;
136 context.mLayersToLoadOnCompletion.clear();
137 tempLayerStore.transferLayersFromStore( context.temporaryLayerStore() );
138}
139
141{
142 return QgsProcessingUtils::mapLayerFromString( identifier, *this, false );
143}
144
146{
147 return tempLayerStore.takeMapLayer( tempLayerStore.mapLayer( id ) );
148}
149
151{
152 return mLogLevel;
153}
154
156{
157 mLogLevel = level;
158}
159
161{
162 return mTemporaryFolderOverride;
163}
164
165void QgsProcessingContext::setTemporaryFolder( const QString &folder )
166{
167 mTemporaryFolderOverride = folder;
168}
169
171{
172 return mMaximumThreads;
173}
174
176{
177 mMaximumThreads = threads;
178}
179
181{
182 QVariantMap res;
183 if ( mDistanceUnit != Qgis::DistanceUnit::Unknown )
184 res.insert( u"distance_units"_s, QgsUnitTypes::encodeUnit( mDistanceUnit ) );
185 if ( mAreaUnit != Qgis::AreaUnit::Unknown )
186 res.insert( u"area_units"_s, QgsUnitTypes::encodeUnit( mAreaUnit ) );
187 if ( !mEllipsoid.isEmpty() )
188 res.insert( u"ellipsoid"_s, mEllipsoid );
189 if ( mProject )
190 res.insert( u"project_path"_s, mProject->fileName() );
191
192 return res;
193}
194
196{
197 auto escapeIfNeeded = []( const QString & input ) -> QString
198 {
199 // play it safe and escape everything UNLESS it's purely alphanumeric characters (and a very select scattering of other common characters!)
200 const thread_local QRegularExpression nonAlphaNumericRx( u"[^a-zA-Z0-9.\\-/_]"_s );
201 if ( nonAlphaNumericRx.match( input ).hasMatch() )
202 {
203 QString escaped = input;
204 escaped.replace( '\'', "'\\''"_L1 );
205 return u"'%1'"_s.arg( escaped );
206 }
207 else
208 {
209 return input;
210 }
211 };
212
213 QStringList res;
214 if ( mDistanceUnit != Qgis::DistanceUnit::Unknown )
215 res << u"--distance_units=%1"_s.arg( QgsUnitTypes::encodeUnit( mDistanceUnit ) );
216 if ( mAreaUnit != Qgis::AreaUnit::Unknown )
217 res << u"--area_units=%1"_s.arg( QgsUnitTypes::encodeUnit( mAreaUnit ) );
218 if ( !mEllipsoid.isEmpty() )
219 res << u"--ellipsoid=%1"_s.arg( mEllipsoid );
220
222 {
223 res << u"--project_path=%1"_s.arg( escapeIfNeeded( mProject->fileName() ) );
224 }
225
226 return res;
227}
228
230{
231 return mCurrentTimeRange;
232}
233
238
240{
241 return mEllipsoid;
242}
243
245{
246 mEllipsoid = ellipsoid;
247}
248
250{
251 return mDistanceUnit;
252}
253
255{
256 mDistanceUnit = unit;
257}
258
260{
261 return mAreaUnit;
262}
263
268
273
275{
276 if ( mPostProcessor && mPostProcessor != processor )
277 delete mPostProcessor;
278
279 mPostProcessor = processor;
280}
281
283{
284 if ( !layer )
285 return;
286
287 const bool preferFilenameAsLayerName = QgsProcessing::settingsPreferFilenameAsLayerName->value();
288
289 // note - for temporary layers, we don't use the filename, regardless of user setting (it will be meaningless!)
290 if ( ( !forceName && preferFilenameAsLayerName && !layer->isTemporary() ) || name.isEmpty() )
291 {
292 const QVariantMap sourceParts = QgsProviderRegistry::instance()->decodeUri( layer->providerType(), layer->source() );
293 const QString layerName = sourceParts.value( u"layerName"_s ).toString();
294 // if output layer name exists, use that!
295 if ( !layerName.isEmpty() )
296 layer->setName( layerName );
297 else
298 {
299 const QString path = sourceParts.value( u"path"_s ).toString();
300 if ( !path.isEmpty() )
301 {
302 const QFileInfo fi( path );
303 layer->setName( fi.baseName() );
304 }
305 else if ( !name.isEmpty() )
306 {
307 // fallback to parameter's name -- shouldn't happen!
308 layer->setName( name );
309 }
310 }
311 }
312 else
313 {
314 layer->setName( name );
315 }
316}
317
318
323
324void QgsProcessingContext::setModelInitialRunConfig( std::unique_ptr< QgsProcessingModelInitialRunConfig > config )
325{
326 mModelConfig = std::move( config );
327}
328
329std::unique_ptr< QgsProcessingModelInitialRunConfig > QgsProcessingContext::takeModelInitialRunConfig()
330{
331 return std::move( mModelConfig );
332}
333
335{
336 mModelResult.clear();
337}
DistanceUnit
Units of distance.
Definition qgis.h:5120
@ Unknown
Unknown distance unit.
Definition qgis.h:5170
AreaUnit
Units of area.
Definition qgis.h:5197
@ Unknown
Unknown areal unit.
Definition qgis.h:5210
InvalidGeometryCheck
Methods for handling of features with invalid geometries.
Definition qgis.h:2296
@ NoCheck
No invalid geometry checking.
Definition qgis.h:2297
@ AbortOnInvalid
Close iterator on encountering any features with invalid geometry. This requires a slow geometry vali...
Definition qgis.h:2299
@ SkipInvalid
Skip any features with invalid geometry. This requires a slow geometry validity check for every featu...
Definition qgis.h:2298
ProcessingLogLevel
Logging level for algorithms to use when pushing feedback messages.
Definition qgis.h:3727
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void setLoadedLayerStore(QgsMapLayerStore *store)
Sets the destination layer store for any layers loaded during expression evaluation.
An interface for objects which provide features via a getFeatures method.
virtual QString sourceName() const =0
Returns a friendly display name for the source.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
Base class for all map layer types.
Definition qgsmaplayer.h:83
virtual bool isTemporary() const
Returns true if the layer is considered a temporary layer.
QString source() const
Returns the source for the layer.
QString providerType() const
Returns the provider type (provider key) for this layer.
void setName(const QString &name)
Set the display name of the layer.
Details for layers to load into projects.
bool forceName
Set to true if LayerDetails::name should always be used as the loaded layer name, regardless of the u...
QgsProcessingLayerPostProcessorInterface * postProcessor() const
Layer post-processor.
QString name
Friendly name for layer, possibly for use when loading layer into project.
void setPostProcessor(QgsProcessingLayerPostProcessorInterface *processor)
Sets the layer post-processor.
void setOutputLayerName(QgsMapLayer *layer) const
Sets a layer name to match this output, respecting any local user settings which affect this name.
QgsProcessingContext::Flags flags() const
Returns any flags set in the context.
@ IncludeProjectPath
Include the associated project path argument.
QFlags< ProcessArgumentFlag > ProcessArgumentFlags
std::unique_ptr< QgsProcessingModelInitialRunConfig > takeModelInitialRunConfig()
Takes the model initial run configuration from the context.
QgsDateTimeRange currentTimeRange() const
Returns the current time range to use for temporal operations.
void takeResultsFrom(QgsProcessingContext &context)
Takes the results from another context and merges them with the results currently stored in this cont...
QVariantMap exportToMap() const
Exports the context's settings to a variant map.
Qgis::AreaUnit areaUnit() const
Returns the area unit to use for area calculations.
QStringList asQgisProcessArguments(QgsProcessingContext::ProcessArgumentFlags flags=QgsProcessingContext::ProcessArgumentFlags()) const
Returns list of the equivalent qgis_process arguments representing the settings from the context.
void setLogLevel(Qgis::ProcessingLogLevel level)
Sets the logging level for algorithms to use when pushing feedback messages to users.
void clearModelResult()
Clears model results previously populated when the context was used to run a model algorithm.
QgsMapLayer * getMapLayer(const QString &identifier)
Returns a map layer from the context with a matching identifier.
std::function< void(const QgsFeature &) > invalidGeometryCallback(QgsFeatureSource *source=nullptr) const
Returns the callback function to use when encountering an invalid geometry and invalidGeometryCheck()...
void setMaximumThreads(int threads)
Sets the (optional) number of threads to use when running algorithms.
void setExpressionContext(const QgsExpressionContext &context)
Sets the expression context.
std::function< void(const QgsFeature &) > defaultInvalidGeometryCallbackForCheck(Qgis::InvalidGeometryCheck check, QgsFeatureSource *source=nullptr) const
Returns the default callback function to use for a particular invalid geometry check.
void setLayersToLoadOnCompletion(const QMap< QString, QgsProcessingContext::LayerDetails > &layers)
Sets the map of layers (by ID or datasource) to LayerDetails, to load into the canvas upon completion...
QgsMapLayer * takeResultLayer(const QString &id)
Takes the result map layer with matching id from the context and transfers ownership of it back to th...
void setDistanceUnit(Qgis::DistanceUnit unit)
Sets the unit to use for distance calculations.
void setInvalidGeometryCheck(Qgis::InvalidGeometryCheck check)
Sets the behavior used for checking invalid geometries in input layers.
void addLayerToLoadOnCompletion(const QString &layer, const QgsProcessingContext::LayerDetails &details)
Adds a layer to load (by ID or datasource) into the canvas upon completion of the algorithm or model.
void setAreaUnit(Qgis::AreaUnit areaUnit)
Sets the unit to use for area calculations.
void setEllipsoid(const QString &ellipsoid)
Sets a specified ellipsoid to use for distance and area calculations.
QgsProcessingModelInitialRunConfig * modelInitialRunConfig()
Returns a reference to the model initial run configuration, used to run a model algorithm.
Qgis::DistanceUnit distanceUnit() const
Returns the distance unit to use for distance calculations.
Qgis::ProcessingLogLevel logLevel() const
Returns the logging level for algorithms to use when pushing feedback messages to users.
QString ellipsoid() const
Returns the ellipsoid to use for distance and area calculations.
void setModelInitialRunConfig(std::unique_ptr< QgsProcessingModelInitialRunConfig > config)
Sets the model initial run configuration, used to run a model algorithm.
QgsMapLayerStore * temporaryLayerStore()
Returns a reference to the layer store used for storing temporary layers during algorithm execution.
void setTemporaryFolder(const QString &folder)
Sets the (optional) temporary folder to use when running algorithms.
QString temporaryFolder() const
Returns the (optional) temporary folder to use when running algorithms.
void setCurrentTimeRange(const QgsDateTimeRange &currentTimeRange)
Sets the current time range to use for temporal operations.
int maximumThreads() const
Returns the (optional) number of threads to use when running algorithms.
Custom exception class for processing related exceptions.
An interface for layer post-processing handlers for execution following a processing algorithm operat...
Configuration settings which control how a Processing model is executed.
Utility functions for use with processing classes.
static QgsMapLayer * mapLayerFromString(const QString &string, QgsProcessingContext &context, bool allowLoadingNewLayers=true, QgsProcessingUtils::LayerHint typeHint=QgsProcessingUtils::LayerHint::UnknownType, QgsProcessing::LayerOptionsFlags flags=QgsProcessing::LayerOptionsFlags())
Interprets a string as a map layer within the supplied context.
static const QgsSettingsEntryBool * settingsPreferFilenameAsLayerName
Settings entry prefer filename as layer name.
QVariantMap decodeUri(const QString &providerKey, const QString &uri)
Breaks a provider data source URI into its component paths (e.g.
static QgsProviderRegistry * instance(const QString &pluginPath=QString())
Means of accessing canonical single instance.
static Q_INVOKABLE QString encodeUnit(Qgis::DistanceUnit unit)
Encodes a distance unit to a string.
QgsTemporalRange< QDateTime > QgsDateTimeRange
QgsRange which stores a range of date times.
Definition qgsrange.h:764