QGIS API Documentation 3.37.0-Master (fdefdf9c27f)
qgsprocessingutils.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsprocessingutils.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
18#include "qgsprocessingutils.h"
19#include "qgsproject.h"
20#include "qgsexception.h"
23#include "qgsvectorfilewriter.h"
29#include "qgsfileutils.h"
30#include "qgsvectorlayer.h"
31#include "qgsproviderregistry.h"
32#include "qgsmeshlayer.h"
33#include "qgspluginlayer.h"
35#include "qgsrasterfilewriter.h"
36#include "qgsvectortilelayer.h"
37#include "qgspointcloudlayer.h"
38#include "qgsannotationlayer.h"
39#include "qgstiledscenelayer.h"
40#include <QRegularExpression>
41#include <QTextCodec>
42#include <QUuid>
43
44QList<QgsRasterLayer *> QgsProcessingUtils::compatibleRasterLayers( QgsProject *project, bool sort )
45{
46 return compatibleMapLayers< QgsRasterLayer >( project, sort );
47}
48
49QList<QgsVectorLayer *> QgsProcessingUtils::compatibleVectorLayers( QgsProject *project, const QList<int> &geometryTypes, bool sort )
50{
51 if ( !project )
52 return QList<QgsVectorLayer *>();
53
54 QList<QgsVectorLayer *> layers;
55 const auto vectorLayers = project->layers<QgsVectorLayer *>();
56 for ( QgsVectorLayer *l : vectorLayers )
57 {
58 if ( canUseLayer( l, geometryTypes ) )
59 layers << l;
60 }
61
62 if ( sort )
63 {
64 std::sort( layers.begin(), layers.end(), []( const QgsVectorLayer * a, const QgsVectorLayer * b ) -> bool
65 {
66 return QString::localeAwareCompare( a->name(), b->name() ) < 0;
67 } );
68 }
69 return layers;
70}
71
72QList<QgsMeshLayer *> QgsProcessingUtils::compatibleMeshLayers( QgsProject *project, bool sort )
73{
74 return compatibleMapLayers< QgsMeshLayer >( project, sort );
75}
76
77QList<QgsPluginLayer *> QgsProcessingUtils::compatiblePluginLayers( QgsProject *project, bool sort )
78{
79 return compatibleMapLayers< QgsPluginLayer >( project, sort );
80}
81
82QList<QgsPointCloudLayer *> QgsProcessingUtils::compatiblePointCloudLayers( QgsProject *project, bool sort )
83{
84 return compatibleMapLayers< QgsPointCloudLayer >( project, sort );
85}
86
87QList<QgsAnnotationLayer *> QgsProcessingUtils::compatibleAnnotationLayers( QgsProject *project, bool sort )
88{
89 // we have to defer sorting until we've added the main annotation layer too
90 QList<QgsAnnotationLayer *> res = compatibleMapLayers< QgsAnnotationLayer >( project, false );
91 if ( project )
92 res.append( project->mainAnnotationLayer() );
93
94 if ( sort )
95 {
96 std::sort( res.begin(), res.end(), []( const QgsAnnotationLayer * a, const QgsAnnotationLayer * b ) -> bool
97 {
98 return QString::localeAwareCompare( a->name(), b->name() ) < 0;
99 } );
100 }
101
102 return res;
103}
104
105QList<QgsVectorTileLayer *> QgsProcessingUtils::compatibleVectorTileLayers( QgsProject *project, bool sort )
106{
107 return compatibleMapLayers< QgsVectorTileLayer >( project, sort );
108}
109
110QList<QgsTiledSceneLayer *> QgsProcessingUtils::compatibleTiledSceneLayers( QgsProject *project, bool sort )
111{
112 return compatibleMapLayers< QgsTiledSceneLayer >( project, sort );
113}
114
115template<typename T> QList<T *> QgsProcessingUtils::compatibleMapLayers( QgsProject *project, bool sort )
116{
117 if ( !project )
118 return QList<T *>();
119
120 QList<T *> layers;
121 const auto projectLayers = project->layers<T *>();
122 for ( T *l : projectLayers )
123 {
124 if ( canUseLayer( l ) )
125 layers << l;
126 }
127
128 if ( sort )
129 {
130 std::sort( layers.begin(), layers.end(), []( const T * a, const T * b ) -> bool
131 {
132 return QString::localeAwareCompare( a->name(), b->name() ) < 0;
133 } );
134 }
135 return layers;
136}
137
138QList<QgsMapLayer *> QgsProcessingUtils::compatibleLayers( QgsProject *project, bool sort )
139{
140 if ( !project )
141 return QList<QgsMapLayer *>();
142
143 QList<QgsMapLayer *> layers;
144
145 const auto rasterLayers = compatibleMapLayers< QgsRasterLayer >( project, false );
146 for ( QgsRasterLayer *rl : rasterLayers )
147 layers << rl;
148
149 const auto vectorLayers = compatibleVectorLayers( project, QList< int >(), false );
150 for ( QgsVectorLayer *vl : vectorLayers )
151 layers << vl;
152
153 const auto meshLayers = compatibleMapLayers< QgsMeshLayer >( project, false );
154 for ( QgsMeshLayer *ml : meshLayers )
155 layers << ml;
156
157 const auto pointCloudLayers = compatibleMapLayers< QgsPointCloudLayer >( project, false );
158 for ( QgsPointCloudLayer *pcl : pointCloudLayers )
159 layers << pcl;
160
161 const auto annotationLayers = compatibleMapLayers< QgsAnnotationLayer >( project, false );
162 for ( QgsAnnotationLayer *al : annotationLayers )
163 layers << al;
164 layers << project->mainAnnotationLayer();
165
166 const auto vectorTileLayers = compatibleMapLayers< QgsVectorTileLayer >( project, false );
167 for ( QgsVectorTileLayer *vtl : vectorTileLayers )
168 layers << vtl;
169
170 const auto tiledSceneLayers = compatibleMapLayers< QgsTiledSceneLayer >( project, false );
171 for ( QgsTiledSceneLayer *tml : tiledSceneLayers )
172 layers << tml;
173
174 const auto pluginLayers = compatibleMapLayers< QgsPluginLayer >( project, false );
175 for ( QgsPluginLayer *pl : pluginLayers )
176 layers << pl;
177
178 if ( sort )
179 {
180 std::sort( layers.begin(), layers.end(), []( const QgsMapLayer * a, const QgsMapLayer * b ) -> bool
181 {
182 return QString::localeAwareCompare( a->name(), b->name() ) < 0;
183 } );
184 }
185 return layers;
186}
187
188QString QgsProcessingUtils::encodeProviderKeyAndUri( const QString &providerKey, const QString &uri )
189{
190 return QStringLiteral( "%1://%2" ).arg( providerKey, uri );
191}
192
193bool QgsProcessingUtils::decodeProviderKeyAndUri( const QString &string, QString &providerKey, QString &uri )
194{
195 const thread_local QRegularExpression re( QStringLiteral( "^(\\w+?):\\/\\/(.+)$" ) );
196 const QRegularExpressionMatch match = re.match( string );
197 if ( !match.hasMatch() )
198 return false;
199
200 providerKey = match.captured( 1 );
201 uri = match.captured( 2 );
202
203 // double check that provider is valid
204 return QgsProviderRegistry::instance()->providerMetadata( providerKey );
205}
206
207QgsMapLayer *QgsProcessingUtils::mapLayerFromStore( const QString &string, QgsMapLayerStore *store, QgsProcessingUtils::LayerHint typeHint )
208{
209 if ( !store || string.isEmpty() )
210 return nullptr;
211
212 QList< QgsMapLayer * > layers = store->mapLayers().values();
213
214 layers.erase( std::remove_if( layers.begin(), layers.end(), []( QgsMapLayer * layer )
215 {
216 switch ( layer->type() )
217 {
218 case Qgis::LayerType::Vector:
219 return !canUseLayer( qobject_cast< QgsVectorLayer * >( layer ) );
220 case Qgis::LayerType::Raster:
221 return !canUseLayer( qobject_cast< QgsRasterLayer * >( layer ) );
222 case Qgis::LayerType::Plugin:
223 case Qgis::LayerType::Group:
224 return true;
225 case Qgis::LayerType::Mesh:
226 return !canUseLayer( qobject_cast< QgsMeshLayer * >( layer ) );
227 case Qgis::LayerType::VectorTile:
228 return !canUseLayer( qobject_cast< QgsVectorTileLayer * >( layer ) );
229 case Qgis::LayerType::TiledScene:
230 return !canUseLayer( qobject_cast< QgsTiledSceneLayer * >( layer ) );
231 case Qgis::LayerType::PointCloud:
232 return !canUseLayer( qobject_cast< QgsPointCloudLayer * >( layer ) );
233 case Qgis::LayerType::Annotation:
234 return !canUseLayer( qobject_cast< QgsAnnotationLayer * >( layer ) );
235 }
236 return true;
237 } ), layers.end() );
238
239 auto isCompatibleType = [typeHint]( QgsMapLayer * l ) -> bool
240 {
241 switch ( typeHint )
242 {
243 case LayerHint::UnknownType:
244 return true;
245
246 case LayerHint::Vector:
247 return l->type() == Qgis::LayerType::Vector;
248
249 case LayerHint::Raster:
250 return l->type() == Qgis::LayerType::Raster;
251
252 case LayerHint::Mesh:
253 return l->type() == Qgis::LayerType::Mesh;
254
255 case LayerHint::PointCloud:
256 return l->type() == Qgis::LayerType::PointCloud;
257
258 case LayerHint::Annotation:
259 return l->type() == Qgis::LayerType::Annotation;
260
261 case LayerHint::VectorTile:
262 return l->type() == Qgis::LayerType::VectorTile;
263
264 case LayerHint::TiledScene:
265 return l->type() == Qgis::LayerType::TiledScene;
266 }
267 return true;
268 };
269
270 for ( QgsMapLayer *l : std::as_const( layers ) )
271 {
272 if ( isCompatibleType( l ) && l->id() == string )
273 return l;
274 }
275 for ( QgsMapLayer *l : std::as_const( layers ) )
276 {
277 if ( isCompatibleType( l ) && l->name() == string )
278 return l;
279 }
280 for ( QgsMapLayer *l : std::as_const( layers ) )
281 {
282 if ( isCompatibleType( l ) && normalizeLayerSource( l->source() ) == normalizeLayerSource( string ) )
283 return l;
284 }
285 return nullptr;
286}
287
288QgsMapLayer *QgsProcessingUtils::loadMapLayerFromString( const QString &string, const QgsCoordinateTransformContext &transformContext, LayerHint typeHint, QgsProcessing::LayerOptionsFlags flags )
289{
290 QString provider;
291 QString uri;
292 const bool useProvider = decodeProviderKeyAndUri( string, provider, uri );
293 if ( !useProvider )
294 uri = string;
295
296 QString name;
297
298 const QgsProviderMetadata *providerMetadata = useProvider ? QgsProviderRegistry::instance()->providerMetadata( provider ) : nullptr;
299 if ( providerMetadata )
300 {
301 // use the uri parts to determine a suitable layer name
302 const QVariantMap parts = providerMetadata->decodeUri( uri );
303 const QString layerName = parts.value( QStringLiteral( "layerName" ) ).toString();
304
305 if ( !layerName.isEmpty() )
306 {
307 name = layerName;
308 }
309 else if ( const QString path = parts.value( QStringLiteral( "path" ) ).toString(); !path.isEmpty() )
310 {
311 name = QFileInfo( path ).baseName();
312 }
313 }
314 else
315 {
316 const QStringList components = uri.split( '|' );
317 if ( components.isEmpty() )
318 return nullptr;
319
320 if ( QFileInfo fi( components.at( 0 ) ); fi.isFile() )
321 name = fi.baseName();
322 else
323 name = QFileInfo( uri ).baseName();
324 }
325
326 if ( name.isEmpty() )
327 {
328 name = QgsDataSourceUri( uri ).table();
329 }
330 if ( name.isEmpty() )
331 {
332 name = uri;
333 }
334
335 QList< Qgis::LayerType > candidateTypes;
336 switch ( typeHint )
337 {
339 {
340 if ( providerMetadata )
341 {
342 // refine the type hint based on what the provider supports
343 candidateTypes = providerMetadata->supportedLayerTypes();
344 }
345 break;
346 }
348 candidateTypes.append( Qgis::LayerType::Vector );
349 break;
351 candidateTypes.append( Qgis::LayerType::Raster );
352 break;
353 case LayerHint::Mesh:
354 candidateTypes.append( Qgis::LayerType::Mesh );
355 break;
357 candidateTypes.append( Qgis::LayerType::PointCloud );
358 break;
360 candidateTypes.append( Qgis::LayerType::Annotation );
361 break;
363 candidateTypes.append( Qgis::LayerType::VectorTile );
364 break;
366 candidateTypes.append( Qgis::LayerType::TiledScene );
367 break;
368 }
369
370 // brute force attempt to load a matching layer
371 if ( candidateTypes.empty() || candidateTypes.contains( Qgis::LayerType::Vector ) )
372 {
373 QgsVectorLayer::LayerOptions options { transformContext };
374 options.loadDefaultStyle = false;
375 options.skipCrsValidation = true;
376
377 std::unique_ptr< QgsVectorLayer > layer;
378 if ( providerMetadata )
379 {
380 layer = std::make_unique<QgsVectorLayer>( uri, name, providerMetadata->key(), options );
381 }
382 else
383 {
384 // fallback to ogr
385 layer = std::make_unique<QgsVectorLayer>( uri, name, QStringLiteral( "ogr" ), options );
386 }
387 if ( layer->isValid() )
388 {
389 return layer.release();
390 }
391 }
392 if ( candidateTypes.empty() || candidateTypes.contains( Qgis::LayerType::Raster ) )
393 {
394 QgsRasterLayer::LayerOptions rasterOptions;
395 rasterOptions.loadDefaultStyle = false;
396 rasterOptions.skipCrsValidation = true;
397
398 std::unique_ptr< QgsRasterLayer > rasterLayer;
399 if ( providerMetadata )
400 {
401 rasterLayer = std::make_unique< QgsRasterLayer >( uri, name, providerMetadata->key(), rasterOptions );
402 }
403 else
404 {
405 // fallback to gdal
406 rasterLayer = std::make_unique< QgsRasterLayer >( uri, name, QStringLiteral( "gdal" ), rasterOptions );
407 }
408
409 if ( rasterLayer->isValid() )
410 {
411 return rasterLayer.release();
412 }
413 }
414 if ( candidateTypes.empty() || candidateTypes.contains( Qgis::LayerType::Mesh ) )
415 {
416 QgsMeshLayer::LayerOptions meshOptions;
417 meshOptions.skipCrsValidation = true;
418
419 std::unique_ptr< QgsMeshLayer > meshLayer;
420 if ( providerMetadata )
421 {
422 meshLayer = std::make_unique< QgsMeshLayer >( uri, name, providerMetadata->key(), meshOptions );
423 }
424 else
425 {
426 meshLayer = std::make_unique< QgsMeshLayer >( uri, name, QStringLiteral( "mdal" ), meshOptions );
427 }
428 if ( meshLayer->isValid() )
429 {
430 return meshLayer.release();
431 }
432 }
433 if ( candidateTypes.empty() || candidateTypes.contains( Qgis::LayerType::PointCloud ) )
434 {
435 QgsPointCloudLayer::LayerOptions pointCloudOptions;
436 pointCloudOptions.skipCrsValidation = true;
437
439 {
440 pointCloudOptions.skipIndexGeneration = true;
441 }
442
443 std::unique_ptr< QgsPointCloudLayer > pointCloudLayer;
444 if ( providerMetadata )
445 {
446 pointCloudLayer = std::make_unique< QgsPointCloudLayer >( uri, name, providerMetadata->key(), pointCloudOptions );
447 }
448 else
449 {
450 const QList< QgsProviderRegistry::ProviderCandidateDetails > preferredProviders = QgsProviderRegistry::instance()->preferredProvidersForUri( uri );
451 if ( !preferredProviders.empty() )
452 {
453 pointCloudLayer = std::make_unique< QgsPointCloudLayer >( uri, name, preferredProviders.at( 0 ).metadata()->key(), pointCloudOptions );
454 }
455 else
456 {
457 // pdal provider can read ascii files but it is not exposed by the provider to
458 // prevent automatic loading of tabular ascii files.
459 // Try to open the file with pdal provider.
460 QgsProviderMetadata *pdalProvider = QgsProviderRegistry::instance()->providerMetadata( QStringLiteral( "pdal" ) );
461 if ( pdalProvider )
462 {
463 pointCloudLayer = std::make_unique< QgsPointCloudLayer >( uri, name, QStringLiteral( "pdal" ), pointCloudOptions );
464 }
465 }
466 }
467 if ( pointCloudLayer && pointCloudLayer->isValid() )
468 {
469 return pointCloudLayer.release();
470 }
471 }
472 if ( candidateTypes.empty() || candidateTypes.contains( Qgis::LayerType::VectorTile ) )
473 {
474 QgsDataSourceUri dsUri;
475 dsUri.setParam( "type", "mbtiles" );
476 dsUri.setParam( "url", uri );
477
478 std::unique_ptr< QgsVectorTileLayer > tileLayer;
479 tileLayer = std::make_unique< QgsVectorTileLayer >( dsUri.encodedUri(), name );
480
481 if ( tileLayer->isValid() )
482 {
483 return tileLayer.release();
484 }
485 }
486 if ( candidateTypes.empty() || candidateTypes.contains( Qgis::LayerType::TiledScene ) )
487 {
488 QgsTiledSceneLayer::LayerOptions tiledSceneOptions;
489 tiledSceneOptions.skipCrsValidation = true;
490
491 std::unique_ptr< QgsTiledSceneLayer > tiledSceneLayer;
492 if ( providerMetadata )
493 {
494 tiledSceneLayer = std::make_unique< QgsTiledSceneLayer >( uri, name, providerMetadata->key(), tiledSceneOptions );
495 }
496 else
497 {
498 const QList< QgsProviderRegistry::ProviderCandidateDetails > preferredProviders = QgsProviderRegistry::instance()->preferredProvidersForUri( uri );
499 if ( !preferredProviders.empty() )
500 {
501 tiledSceneLayer = std::make_unique< QgsTiledSceneLayer >( uri, name, preferredProviders.at( 0 ).metadata()->key(), tiledSceneOptions );
502 }
503 }
504 if ( tiledSceneLayer && tiledSceneLayer->isValid() )
505 {
506 return tiledSceneLayer.release();
507 }
508 }
509 return nullptr;
510}
511
512QgsMapLayer *QgsProcessingUtils::mapLayerFromString( const QString &string, QgsProcessingContext &context, bool allowLoadingNewLayers, LayerHint typeHint, QgsProcessing::LayerOptionsFlags flags )
513{
514 if ( string.isEmpty() )
515 return nullptr;
516
517 // prefer project layers
518 if ( context.project() && typeHint == LayerHint::Annotation && string.compare( QLatin1String( "main" ), Qt::CaseInsensitive ) == 0 )
519 return context.project()->mainAnnotationLayer();
520
521 QgsMapLayer *layer = nullptr;
522 if ( auto *lProject = context.project() )
523 {
524 QgsMapLayer *layer = mapLayerFromStore( string, lProject->layerStore(), typeHint );
525 if ( layer )
526 return layer;
527 }
528
529 layer = mapLayerFromStore( string, context.temporaryLayerStore(), typeHint );
530 if ( layer )
531 return layer;
532
533 if ( !allowLoadingNewLayers )
534 return nullptr;
535
536 layer = loadMapLayerFromString( string, context.transformContext(), typeHint, flags );
537 if ( layer )
538 {
539 context.temporaryLayerStore()->addMapLayer( layer );
540 return layer;
541 }
542 else
543 {
544 return nullptr;
545 }
546}
547
548QgsProcessingFeatureSource *QgsProcessingUtils::variantToSource( const QVariant &value, QgsProcessingContext &context, const QVariant &fallbackValue )
549{
550 QVariant val = value;
551 bool selectedFeaturesOnly = false;
552 long long featureLimit = -1;
553 QString filterExpression;
554 bool overrideGeometryCheck = false;
556 if ( val.userType() == QMetaType::type( "QgsProcessingFeatureSourceDefinition" ) )
557 {
558 // input is a QgsProcessingFeatureSourceDefinition - get extra properties from it
559 QgsProcessingFeatureSourceDefinition fromVar = qvariant_cast<QgsProcessingFeatureSourceDefinition>( val );
560 selectedFeaturesOnly = fromVar.selectedFeaturesOnly;
561 featureLimit = fromVar.featureLimit;
562 filterExpression = fromVar.filterExpression;
563 val = fromVar.source;
565 geometryCheck = fromVar.geometryCheck;
566 }
567 else if ( val.userType() == QMetaType::type( "QgsProcessingOutputLayerDefinition" ) )
568 {
569 // input is a QgsProcessingOutputLayerDefinition (e.g. an output from earlier in a model) - get extra properties from it
570 QgsProcessingOutputLayerDefinition fromVar = qvariant_cast<QgsProcessingOutputLayerDefinition>( val );
571 val = fromVar.sink;
572 }
573
574 if ( QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( qvariant_cast<QObject *>( val ) ) )
575 {
576 std::unique_ptr< QgsProcessingFeatureSource> source = std::make_unique< QgsProcessingFeatureSource >( layer, context, false, featureLimit, filterExpression );
577 if ( overrideGeometryCheck )
578 source->setInvalidGeometryCheck( geometryCheck );
579 return source.release();
580 }
581
582 QString layerRef;
583 if ( val.userType() == QMetaType::type( "QgsProperty" ) )
584 {
585 layerRef = val.value< QgsProperty >().valueAsString( context.expressionContext(), fallbackValue.toString() );
586 }
587 else if ( !val.isValid() || val.toString().isEmpty() )
588 {
589 // fall back to default
590 if ( QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( qvariant_cast<QObject *>( fallbackValue ) ) )
591 {
592 std::unique_ptr< QgsProcessingFeatureSource> source = std::make_unique< QgsProcessingFeatureSource >( layer, context, false, featureLimit, filterExpression );
593 if ( overrideGeometryCheck )
594 source->setInvalidGeometryCheck( geometryCheck );
595 return source.release();
596 }
597
598 layerRef = fallbackValue.toString();
599 }
600 else
601 {
602 layerRef = val.toString();
603 }
604
605 if ( layerRef.isEmpty() )
606 return nullptr;
607
608 QgsVectorLayer *vl = qobject_cast< QgsVectorLayer *>( QgsProcessingUtils::mapLayerFromString( layerRef, context, true, LayerHint::Vector ) );
609 if ( !vl )
610 return nullptr;
611
612 std::unique_ptr< QgsProcessingFeatureSource> source;
613 if ( selectedFeaturesOnly )
614 {
615 source = std::make_unique< QgsProcessingFeatureSource>( new QgsVectorLayerSelectedFeatureSource( vl ), context, true, featureLimit, filterExpression );
616 }
617 else
618 {
619 source = std::make_unique< QgsProcessingFeatureSource >( vl, context, false, featureLimit, filterExpression );
620 }
621
622 if ( overrideGeometryCheck )
623 source->setInvalidGeometryCheck( geometryCheck );
624 return source.release();
625}
626
627QgsCoordinateReferenceSystem QgsProcessingUtils::variantToCrs( const QVariant &value, QgsProcessingContext &context, const QVariant &fallbackValue )
628{
629 QVariant val = value;
630
631 if ( val.userType() == QMetaType::type( "QgsCoordinateReferenceSystem" ) )
632 {
633 // input is a QgsCoordinateReferenceSystem - done!
634 return val.value< QgsCoordinateReferenceSystem >();
635 }
636 else if ( val.userType() == QMetaType::type( "QgsProcessingFeatureSourceDefinition" ) )
637 {
638 // input is a QgsProcessingFeatureSourceDefinition - get extra properties from it
639 QgsProcessingFeatureSourceDefinition fromVar = qvariant_cast<QgsProcessingFeatureSourceDefinition>( val );
640 val = fromVar.source;
641 }
642 else if ( val.userType() == QMetaType::type( "QgsProcessingOutputLayerDefinition" ) )
643 {
644 // input is a QgsProcessingOutputLayerDefinition - get extra properties from it
645 QgsProcessingOutputLayerDefinition fromVar = qvariant_cast<QgsProcessingOutputLayerDefinition>( val );
646 val = fromVar.sink;
647 }
648
649 if ( val.userType() == QMetaType::type( "QgsProperty" ) && val.value< QgsProperty >().propertyType() == Qgis::PropertyType::Static )
650 {
651 val = val.value< QgsProperty >().staticValue();
652 }
653
654 // maybe a map layer
655 if ( QgsMapLayer *layer = qobject_cast< QgsMapLayer * >( qvariant_cast<QObject *>( val ) ) )
656 return layer->crs();
657
658 if ( val.userType() == QMetaType::type( "QgsProperty" ) )
659 val = val.value< QgsProperty >().valueAsString( context.expressionContext(), fallbackValue.toString() );
660
661 if ( !val.isValid() )
662 {
663 // fall back to default
664 val = fallbackValue;
665 }
666
667 QString crsText = val.toString();
668 if ( crsText.isEmpty() )
669 crsText = fallbackValue.toString();
670
671 if ( crsText.isEmpty() )
673
674 // maybe special string
675 if ( context.project() && crsText.compare( QLatin1String( "ProjectCrs" ), Qt::CaseInsensitive ) == 0 )
676 return context.project()->crs();
677
678 // maybe a map layer reference
679 if ( QgsMapLayer *layer = QgsProcessingUtils::mapLayerFromString( crsText, context ) )
680 return layer->crs();
681
682 // else CRS from string
684 crs.createFromString( crsText );
685 return crs;
686}
687
688bool QgsProcessingUtils::canUseLayer( const QgsMeshLayer *layer )
689{
690 return layer && layer->dataProvider();
691}
692
693bool QgsProcessingUtils::canUseLayer( const QgsPluginLayer *layer )
694{
695 return layer && layer->isValid();
696}
697
698bool QgsProcessingUtils::canUseLayer( const QgsVectorTileLayer *layer )
699{
700 return layer && layer->isValid();
701}
702
703bool QgsProcessingUtils::canUseLayer( const QgsRasterLayer *layer )
704{
705 return layer && layer->isValid();
706}
707
708bool QgsProcessingUtils::canUseLayer( const QgsPointCloudLayer *layer )
709{
710 return layer && layer->isValid();
711}
712
713bool QgsProcessingUtils::canUseLayer( const QgsAnnotationLayer *layer )
714{
715 return layer && layer->isValid();
716}
717
718bool QgsProcessingUtils::canUseLayer( const QgsTiledSceneLayer *layer )
719{
720 return layer && layer->isValid();
721}
722
723bool QgsProcessingUtils::canUseLayer( const QgsVectorLayer *layer, const QList<int> &sourceTypes )
724{
725 return layer && layer->isValid() &&
726 ( sourceTypes.isEmpty()
727 || ( sourceTypes.contains( static_cast< int >( Qgis::ProcessingSourceType::VectorPoint ) ) && layer->geometryType() == Qgis::GeometryType::Point )
728 || ( sourceTypes.contains( static_cast< int >( Qgis::ProcessingSourceType::VectorLine ) ) && layer->geometryType() == Qgis::GeometryType::Line )
729 || ( sourceTypes.contains( static_cast< int >( Qgis::ProcessingSourceType::VectorPolygon ) ) && layer->geometryType() == Qgis::GeometryType::Polygon )
730 || ( sourceTypes.contains( static_cast< int >( Qgis::ProcessingSourceType::VectorAnyGeometry ) ) && layer->isSpatial() )
731 || sourceTypes.contains( static_cast< int >( Qgis::ProcessingSourceType::Vector ) )
732 );
733}
734
735QString QgsProcessingUtils::normalizeLayerSource( const QString &source )
736{
737 QString normalized = source;
738 normalized.replace( '\\', '/' );
739 return normalized.trimmed();
740}
741
743{
744 if ( !layer )
745 return QString();
746
747 const QString source = QgsProcessingUtils::normalizeLayerSource( layer->source() );
748 if ( !source.isEmpty() )
749 {
750 const QString provider = layer->providerType();
751 // don't prepend provider type for these exceptional providers -- we assume them
752 // by default if the provider type is excluded. See logic in QgsProcessingUtils::loadMapLayerFromString
753 if ( provider.compare( QLatin1String( "gdal" ), Qt::CaseInsensitive ) == 0
754 || provider.compare( QLatin1String( "ogr" ), Qt::CaseInsensitive ) == 0
755 || provider.compare( QLatin1String( "mdal" ), Qt::CaseInsensitive ) == 0 )
756 return source;
757
758 return QStringLiteral( "%1://%2" ).arg( provider, source );
759 }
760 return layer->id();
761}
762
763QString QgsProcessingUtils::variantToPythonLiteral( const QVariant &value )
764{
765 if ( !value.isValid() )
766 return QStringLiteral( "None" );
767
768 if ( value.userType() == QMetaType::type( "QgsProperty" ) )
769 return QStringLiteral( "QgsProperty.fromExpression('%1')" ).arg( value.value< QgsProperty >().asExpression() );
770 else if ( value.userType() == QMetaType::type( "QgsCoordinateReferenceSystem" ) )
771 {
772 if ( !value.value< QgsCoordinateReferenceSystem >().isValid() )
773 return QStringLiteral( "QgsCoordinateReferenceSystem()" );
774 else
775 return QStringLiteral( "QgsCoordinateReferenceSystem('%1')" ).arg( value.value< QgsCoordinateReferenceSystem >().authid() );
776 }
777 else if ( value.userType() == QMetaType::type( "QgsRectangle" ) )
778 {
779 QgsRectangle r = value.value<QgsRectangle>();
780 return QStringLiteral( "'%1, %3, %2, %4'" ).arg( qgsDoubleToString( r.xMinimum() ),
784 }
785 else if ( value.userType() == QMetaType::type( "QgsReferencedRectangle" ) )
786 {
788 return QStringLiteral( "'%1, %3, %2, %4 [%5]'" ).arg( qgsDoubleToString( r.xMinimum() ),
791 qgsDoubleToString( r.yMaximum() ), r.crs().authid() );
792 }
793 else if ( value.userType() == QMetaType::type( "QgsPointXY" ) )
794 {
795 QgsPointXY r = value.value<QgsPointXY>();
796 return QStringLiteral( "'%1,%2'" ).arg( qgsDoubleToString( r.x() ),
797 qgsDoubleToString( r.y() ) );
798 }
799 else if ( value.userType() == QMetaType::type( "QgsReferencedPointXY" ) )
800 {
802 return QStringLiteral( "'%1,%2 [%3]'" ).arg( qgsDoubleToString( r.x() ),
803 qgsDoubleToString( r.y() ),
804 r.crs().authid() );
805 }
806
807 switch ( value.type() )
808 {
809 case QVariant::Bool:
810 return value.toBool() ? QStringLiteral( "True" ) : QStringLiteral( "False" );
811
812 case QVariant::Double:
813 return QString::number( value.toDouble() );
814
815 case QVariant::Int:
816 case QVariant::UInt:
817 return QString::number( value.toInt() );
818
819 case QVariant::LongLong:
820 case QVariant::ULongLong:
821 return QString::number( value.toLongLong() );
822
823 case QVariant::List:
824 {
825 QStringList parts;
826 const QVariantList vl = value.toList();
827 for ( const QVariant &v : vl )
828 {
829 parts << variantToPythonLiteral( v );
830 }
831 return parts.join( ',' ).prepend( '[' ).append( ']' );
832 }
833
834 case QVariant::Map:
835 {
836 const QVariantMap map = value.toMap();
837 QStringList parts;
838 parts.reserve( map.size() );
839 for ( auto it = map.constBegin(); it != map.constEnd(); ++it )
840 {
841 parts << QStringLiteral( "%1: %2" ).arg( stringToPythonLiteral( it.key() ), variantToPythonLiteral( it.value() ) );
842 }
843 return parts.join( ',' ).prepend( '{' ).append( '}' );
844 }
845
846 case QVariant::DateTime:
847 {
848 const QDateTime dateTime = value.toDateTime();
849 return QStringLiteral( "QDateTime(QDate(%1, %2, %3), QTime(%4, %5, %6))" )
850 .arg( dateTime.date().year() )
851 .arg( dateTime.date().month() )
852 .arg( dateTime.date().day() )
853 .arg( dateTime.time().hour() )
854 .arg( dateTime.time().minute() )
855 .arg( dateTime.time().second() );
856 }
857
858 default:
859 break;
860 }
861
862 return QgsProcessingUtils::stringToPythonLiteral( value.toString() );
863}
864
865QString QgsProcessingUtils::stringToPythonLiteral( const QString &string )
866{
867 QString s = string;
868 s.replace( '\\', QLatin1String( "\\\\" ) );
869 s.replace( '\n', QLatin1String( "\\n" ) );
870 s.replace( '\r', QLatin1String( "\\r" ) );
871 s.replace( '\t', QLatin1String( "\\t" ) );
872
873 if ( s.contains( '\'' ) && !s.contains( '\"' ) )
874 {
875 s = s.prepend( '"' ).append( '"' );
876 }
877 else
878 {
879 s.replace( '\'', QLatin1String( "\\\'" ) );
880 s = s.prepend( '\'' ).append( '\'' );
881 }
882 return s;
883}
884
885void QgsProcessingUtils::parseDestinationString( QString &destination, QString &providerKey, QString &uri, QString &layerName, QString &format, QMap<QString, QVariant> &options, bool &useWriter, QString &extension )
886{
887 extension.clear();
888 bool matched = decodeProviderKeyAndUri( destination, providerKey, uri );
889
890 if ( !matched )
891 {
892 const thread_local QRegularExpression splitRx( QStringLiteral( "^(.{3,}?):(.*)$" ) );
893 QRegularExpressionMatch match = splitRx.match( destination );
894 if ( match.hasMatch() )
895 {
896 providerKey = match.captured( 1 );
897 uri = match.captured( 2 );
898 matched = true;
899 }
900 }
901
902 if ( matched )
903 {
904 if ( providerKey == QLatin1String( "postgis" ) ) // older processing used "postgis" instead of "postgres"
905 {
906 providerKey = QStringLiteral( "postgres" );
907 }
908 if ( providerKey == QLatin1String( "ogr" ) )
909 {
910 QgsDataSourceUri dsUri( uri );
911 if ( !dsUri.database().isEmpty() )
912 {
913 if ( !dsUri.table().isEmpty() )
914 {
915 layerName = dsUri.table();
916 options.insert( QStringLiteral( "layerName" ), layerName );
917 }
918 uri = dsUri.database();
919 extension = QFileInfo( uri ).completeSuffix();
920 format = QgsVectorFileWriter::driverForExtension( extension );
921 options.insert( QStringLiteral( "driverName" ), format );
922 }
923 else
924 {
925 extension = QFileInfo( uri ).completeSuffix();
926 options.insert( QStringLiteral( "driverName" ), QgsVectorFileWriter::driverForExtension( extension ) );
927 }
928 options.insert( QStringLiteral( "update" ), true );
929 }
930 useWriter = false;
931 }
932 else
933 {
934 useWriter = true;
935 providerKey = QStringLiteral( "ogr" );
936
937 const thread_local QRegularExpression splitRx( QStringLiteral( "^(.*)\\.(.*?)$" ) );
938 QRegularExpressionMatch match = splitRx.match( destination );
939 if ( match.hasMatch() )
940 {
941 extension = match.captured( 2 );
942 format = QgsVectorFileWriter::driverForExtension( extension );
943 }
944
945 if ( format.isEmpty() )
946 {
947 format = QStringLiteral( "GPKG" );
948 destination = destination + QStringLiteral( ".gpkg" );
949 }
950
951 options.insert( QStringLiteral( "driverName" ), format );
952 uri = destination;
953 }
954}
955
956QgsFeatureSink *QgsProcessingUtils::createFeatureSink( QString &destination, QgsProcessingContext &context, const QgsFields &fields, Qgis::WkbType geometryType, const QgsCoordinateReferenceSystem &crs, const QVariantMap &createOptions, const QStringList &datasourceOptions, const QStringList &layerOptions, QgsFeatureSink::SinkFlags sinkFlags, QgsRemappingSinkDefinition *remappingDefinition )
957{
958 QVariantMap options = createOptions;
959 if ( !options.contains( QStringLiteral( "fileEncoding" ) ) )
960 {
961 // no destination encoding specified, use default
962 options.insert( QStringLiteral( "fileEncoding" ), context.defaultEncoding().isEmpty() ? QStringLiteral( "system" ) : context.defaultEncoding() );
963 }
964
965 if ( destination.isEmpty() || destination.startsWith( QLatin1String( "memory:" ) ) )
966 {
967 // strip "memory:" from start of destination
968 if ( destination.startsWith( QLatin1String( "memory:" ) ) )
969 destination = destination.mid( 7 );
970
971 if ( destination.isEmpty() )
972 destination = QStringLiteral( "output" );
973
974 // memory provider cannot be used with QgsVectorLayerImport - so create layer manually
975 std::unique_ptr< QgsVectorLayer > layer( QgsMemoryProviderUtils::createMemoryLayer( destination, fields, geometryType, crs, false ) );
976 if ( !layer || !layer->isValid() )
977 {
978 throw QgsProcessingException( QObject::tr( "Could not create memory layer" ) );
979 }
980
981 if ( QgsProcessingFeedback *feedback = context.feedback() )
982 {
983 for ( const QgsField &field : fields )
984 {
985 // TODO -- support these!
986 if ( !field.alias().isEmpty() )
987 feedback->pushWarning( QObject::tr( "%1: Aliases are not compatible with scratch layers" ).arg( field.name() ) );
988 if ( !field.alias().isEmpty() )
989 feedback->pushWarning( QObject::tr( "%1: Comments are not compatible with scratch layers" ).arg( field.name() ) );
990 }
991 }
992
993 layer->setCustomProperty( QStringLiteral( "OnConvertFormatRegeneratePrimaryKey" ), static_cast< bool >( sinkFlags & QgsFeatureSink::RegeneratePrimaryKey ) );
994
995 // update destination to layer ID
996 destination = layer->id();
997
998 // this is a factory, so we need to return a proxy
999 std::unique_ptr< QgsProcessingFeatureSink > sink( new QgsProcessingFeatureSink( layer->dataProvider(), destination, context ) );
1000 context.temporaryLayerStore()->addMapLayer( layer.release() );
1001
1002 return sink.release();
1003 }
1004 else
1005 {
1006 QString providerKey;
1007 QString uri;
1008 QString layerName;
1009 QString format;
1010 QString extension;
1011 bool useWriter = false;
1012 parseDestinationString( destination, providerKey, uri, layerName, format, options, useWriter, extension );
1013
1014 QgsFields newFields = fields;
1015 if ( useWriter && providerKey == QLatin1String( "ogr" ) )
1016 {
1017 // use QgsVectorFileWriter for OGR destinations instead of QgsVectorLayerImport, as that allows
1018 // us to use any OGR format which supports feature addition
1019 QString finalFileName;
1020 QString finalLayerName;
1022 saveOptions.fileEncoding = options.value( QStringLiteral( "fileEncoding" ) ).toString();
1023 saveOptions.layerName = !layerName.isEmpty() ? layerName : options.value( QStringLiteral( "layerName" ) ).toString();
1024 saveOptions.driverName = format;
1025 saveOptions.datasourceOptions = !datasourceOptions.isEmpty() ? datasourceOptions : QgsVectorFileWriter::defaultDatasetOptions( format );
1026 saveOptions.layerOptions = !layerOptions.isEmpty() ? layerOptions : QgsVectorFileWriter::defaultLayerOptions( format );
1028 if ( remappingDefinition )
1029 {
1031 // sniff destination file to get correct wkb type and crs
1032 std::unique_ptr< QgsVectorLayer > vl = std::make_unique< QgsVectorLayer >( destination );
1033 if ( vl->isValid() )
1034 {
1035 remappingDefinition->setDestinationWkbType( vl->wkbType() );
1036 remappingDefinition->setDestinationCrs( vl->crs() );
1037 newFields = vl->fields();
1038 remappingDefinition->setDestinationFields( newFields );
1039 }
1040 context.expressionContext().setFields( fields );
1041 }
1042 else
1043 {
1045 }
1046 std::unique_ptr< QgsVectorFileWriter > writer( QgsVectorFileWriter::create( destination, newFields, geometryType, crs, context.transformContext(), saveOptions, sinkFlags, &finalFileName, &finalLayerName ) );
1047 if ( writer->hasError() )
1048 {
1049 throw QgsProcessingException( QObject::tr( "Could not create layer %1: %2" ).arg( destination, writer->errorMessage() ) );
1050 }
1051
1052 if ( QgsProcessingFeedback *feedback = context.feedback() )
1053 {
1054 for ( const QgsField &field : fields )
1055 {
1056 if ( !field.alias().isEmpty() && !( writer->capabilities() & Qgis::VectorFileWriterCapability::FieldAliases ) )
1057 feedback->pushWarning( QObject::tr( "%1: Aliases are not supported by %2" ).arg( field.name(), writer->driverLongName() ) );
1058 if ( !field.alias().isEmpty() && !( writer->capabilities() & Qgis::VectorFileWriterCapability::FieldComments ) )
1059 feedback->pushWarning( QObject::tr( "%1: Comments are not supported by %2" ).arg( field.name(), writer->driverLongName() ) );
1060 }
1061 }
1062
1063 destination = finalFileName;
1064 if ( !saveOptions.layerName.isEmpty() && !finalLayerName.isEmpty() )
1065 destination += QStringLiteral( "|layername=%1" ).arg( finalLayerName );
1066
1067 if ( remappingDefinition )
1068 {
1069 std::unique_ptr< QgsRemappingProxyFeatureSink > remapSink = std::make_unique< QgsRemappingProxyFeatureSink >( *remappingDefinition, writer.release(), true );
1070 remapSink->setExpressionContext( context.expressionContext() );
1071 remapSink->setTransformContext( context.transformContext() );
1072 return new QgsProcessingFeatureSink( remapSink.release(), destination, context, true );
1073 }
1074 else
1075 return new QgsProcessingFeatureSink( writer.release(), destination, context, true );
1076 }
1077 else
1078 {
1079 const QgsVectorLayer::LayerOptions layerOptions { context.transformContext() };
1080 if ( remappingDefinition )
1081 {
1082 //write to existing layer
1083
1084 // use destination string as layer name (eg "postgis:..." )
1085 if ( !layerName.isEmpty() )
1086 {
1087 QVariantMap parts = QgsProviderRegistry::instance()->decodeUri( providerKey, uri );
1088 parts.insert( QStringLiteral( "layerName" ), layerName );
1089 uri = QgsProviderRegistry::instance()->encodeUri( providerKey, parts );
1090 }
1091
1092 std::unique_ptr< QgsVectorLayer > layer = std::make_unique<QgsVectorLayer>( uri, destination, providerKey, layerOptions );
1093 // update destination to layer ID
1094 destination = layer->id();
1095 if ( layer->isValid() )
1096 {
1097 remappingDefinition->setDestinationWkbType( layer->wkbType() );
1098 remappingDefinition->setDestinationCrs( layer->crs() );
1099 remappingDefinition->setDestinationFields( layer->fields() );
1100 }
1101
1102 if ( QgsProcessingFeedback *feedback = context.feedback() )
1103 {
1104 const Qgis::VectorDataProviderAttributeEditCapabilities capabilities = layer->dataProvider() ? layer->dataProvider()->attributeEditCapabilities() : Qgis::VectorDataProviderAttributeEditCapabilities();
1105 for ( const QgsField &field : fields )
1106 {
1107 if ( !field.alias().isEmpty() && !( capabilities & Qgis::VectorDataProviderAttributeEditCapability::EditAlias ) )
1108 feedback->pushWarning( QObject::tr( "%1: Aliases are not supported by the %2 provider" ).arg( field.name(), providerKey ) );
1109 if ( !field.alias().isEmpty() && !( capabilities & Qgis::VectorDataProviderAttributeEditCapability::EditComment ) )
1110 feedback->pushWarning( QObject::tr( "%1: Comments are not supported by the %2 provider" ).arg( field.name(), providerKey ) );
1111 }
1112 }
1113
1114 std::unique_ptr< QgsRemappingProxyFeatureSink > remapSink = std::make_unique< QgsRemappingProxyFeatureSink >( *remappingDefinition, layer->dataProvider(), false );
1115 context.temporaryLayerStore()->addMapLayer( layer.release() );
1116 remapSink->setExpressionContext( context.expressionContext() );
1117 remapSink->setTransformContext( context.transformContext() );
1118 context.expressionContext().setFields( fields );
1119 return new QgsProcessingFeatureSink( remapSink.release(), destination, context, true );
1120 }
1121 else
1122 {
1123 //create empty layer
1124 std::unique_ptr< QgsVectorLayerExporter > exporter = std::make_unique<QgsVectorLayerExporter>( uri, providerKey, newFields, geometryType, crs, true, options, sinkFlags );
1125 if ( exporter->errorCode() != Qgis::VectorExportResult::Success )
1126 {
1127 throw QgsProcessingException( QObject::tr( "Could not create layer %1: %2" ).arg( destination, exporter->errorMessage() ) );
1128 }
1129
1130 // use destination string as layer name (eg "postgis:..." )
1131 if ( !layerName.isEmpty() )
1132 {
1133 uri += QStringLiteral( "|layername=%1" ).arg( layerName );
1134 // update destination to generated URI
1135 destination = uri;
1136 }
1137
1138 if ( QgsProcessingFeedback *feedback = context.feedback() )
1139 {
1140 for ( const QgsField &field : fields )
1141 {
1142 if ( !field.alias().isEmpty() && !( exporter->attributeEditCapabilities() & Qgis::VectorDataProviderAttributeEditCapability::EditAlias ) )
1143 feedback->pushWarning( QObject::tr( "%1: Aliases are not supported by the %2 provider" ).arg( field.name(), providerKey ) );
1144 if ( !field.alias().isEmpty() && !( exporter->attributeEditCapabilities() & Qgis::VectorDataProviderAttributeEditCapability::EditComment ) )
1145 feedback->pushWarning( QObject::tr( "%1: Comments are not supported by the %2 provider" ).arg( field.name(), providerKey ) );
1146 }
1147 }
1148
1149 return new QgsProcessingFeatureSink( exporter.release(), destination, context, true );
1150 }
1151 }
1152 }
1153}
1154
1155void QgsProcessingUtils::createFeatureSinkPython( QgsFeatureSink **sink, QString &destination, QgsProcessingContext &context, const QgsFields &fields, Qgis::WkbType geometryType, const QgsCoordinateReferenceSystem &crs, const QVariantMap &options )
1156{
1157 *sink = createFeatureSink( destination, context, fields, geometryType, crs, options );
1158}
1159
1160
1162{
1163 QgsRectangle extent;
1164 for ( const QgsMapLayer *layer : layers )
1165 {
1166 if ( !layer )
1167 continue;
1168
1169 if ( crs.isValid() )
1170 {
1171 //transform layer extent to target CRS
1172 QgsCoordinateTransform ct( layer->crs(), crs, context.transformContext() );
1174 try
1175 {
1176 QgsRectangle reprojExtent = ct.transformBoundingBox( layer->extent() );
1177 extent.combineExtentWith( reprojExtent );
1178 }
1179 catch ( QgsCsException & )
1180 {
1181 // can't reproject... what to do here? hmmm?
1182 // let's ignore this layer for now, but maybe we should just use the original extent?
1183 }
1184 }
1185 else
1186 {
1187 extent.combineExtentWith( layer->extent() );
1188 }
1189
1190 }
1191 return extent;
1192}
1193
1194// Deprecated
1196{
1197 QgsProcessingContext context;
1198 return QgsProcessingUtils::combineLayerExtents( layers, crs, context );
1199}
1200
1201QVariant QgsProcessingUtils::generateIteratingDestination( const QVariant &input, const QVariant &id, QgsProcessingContext &context )
1202{
1203 if ( !input.isValid() )
1204 return QStringLiteral( "memory:%1" ).arg( id.toString() );
1205
1206 if ( input.userType() == QMetaType::type( "QgsProcessingOutputLayerDefinition" ) )
1207 {
1208 QgsProcessingOutputLayerDefinition fromVar = qvariant_cast<QgsProcessingOutputLayerDefinition>( input );
1209 QVariant newSink = generateIteratingDestination( fromVar.sink, id, context );
1210 fromVar.sink = QgsProperty::fromValue( newSink );
1211 return fromVar;
1212 }
1213 else if ( input.userType() == QMetaType::type( "QgsProperty" ) )
1214 {
1215 QString res = input.value< QgsProperty>().valueAsString( context.expressionContext() );
1216 return generateIteratingDestination( res, id, context );
1217 }
1218 else
1219 {
1220 QString res = input.toString();
1222 {
1223 // temporary outputs map to temporary outputs!
1225 }
1226 else if ( res.startsWith( QLatin1String( "memory:" ) ) )
1227 {
1228 return QString( res + '_' + id.toString() );
1229 }
1230 else
1231 {
1232 // assume a filename type output for now
1233 // TODO - uris?
1234 int lastIndex = res.lastIndexOf( '.' );
1235 return lastIndex >= 0 ? QString( res.left( lastIndex ) + '_' + id.toString() + res.mid( lastIndex ) ) : QString( res + '_' + id.toString() );
1236 }
1237 }
1238}
1239
1241{
1242 // we maintain a list of temporary folders -- this allows us to append additional
1243 // folders when a setting change causes the base temp folder to change, while deferring
1244 // cleanup of ALL these temp folders until session end (we can't cleanup older folders immediately,
1245 // because we don't know whether they have data in them which is still wanted)
1246 static std::vector< std::unique_ptr< QTemporaryDir > > sTempFolders;
1247 static QString sFolder;
1248 static QMutex sMutex;
1249 QMutexLocker locker( &sMutex );
1250 QString basePath;
1251
1252 if ( context )
1253 basePath = context->temporaryFolder();
1254 if ( basePath.isEmpty() )
1256
1257 if ( basePath.isEmpty() )
1258 {
1259 // default setting -- automatically create a temp folder
1260 if ( sTempFolders.empty() )
1261 {
1262 const QString templatePath = QStringLiteral( "%1/processing_XXXXXX" ).arg( QDir::tempPath() );
1263 std::unique_ptr< QTemporaryDir > tempFolder = std::make_unique< QTemporaryDir >( templatePath );
1264 sFolder = tempFolder->path();
1265 sTempFolders.emplace_back( std::move( tempFolder ) );
1266 }
1267 }
1268 else if ( sFolder.isEmpty() || !sFolder.startsWith( basePath ) || sTempFolders.empty() )
1269 {
1270 if ( !QDir().exists( basePath ) )
1271 QDir().mkpath( basePath );
1272
1273 const QString templatePath = QStringLiteral( "%1/processing_XXXXXX" ).arg( basePath );
1274 std::unique_ptr< QTemporaryDir > tempFolder = std::make_unique< QTemporaryDir >( templatePath );
1275 sFolder = tempFolder->path();
1276 sTempFolders.emplace_back( std::move( tempFolder ) );
1277 }
1278 return sFolder;
1279}
1280
1281QString QgsProcessingUtils::generateTempFilename( const QString &basename, const QgsProcessingContext *context )
1282{
1283 QString subPath = QUuid::createUuid().toString().remove( '-' ).remove( '{' ).remove( '}' );
1284 QString path = tempFolder( context ) + '/' + subPath;
1285 if ( !QDir( path ).exists() ) //make sure the directory exists - it shouldn't, but lets be safe...
1286 {
1287 QDir tmpDir;
1288 tmpDir.mkdir( path );
1289 }
1290 return path + '/' + QgsFileUtils::stringToSafeFilename( basename );
1291}
1292
1294{
1295 auto getText = [map]( const QString & key )->QString
1296 {
1297 if ( map.contains( key ) )
1298 return map.value( key ).toString();
1299 return QString();
1300 };
1301
1302 QString s;
1303 s += QStringLiteral( "<html><body><p>" ) + getText( QStringLiteral( "ALG_DESC" ) ) + QStringLiteral( "</p>\n" );
1304
1305 QString inputs;
1306 const auto parameterDefinitions = algorithm->parameterDefinitions();
1307 for ( const QgsProcessingParameterDefinition *def : parameterDefinitions )
1308 {
1309 if ( def->flags() & Qgis::ProcessingParameterFlag::Hidden || def->isDestination() )
1310 continue;
1311
1312 if ( !getText( def->name() ).isEmpty() )
1313 {
1314 inputs += QStringLiteral( "<h3>" ) + def->description() + QStringLiteral( "</h3>\n" );
1315 inputs += QStringLiteral( "<p>" ) + getText( def->name() ) + QStringLiteral( "</p>\n" );
1316 }
1317 }
1318 if ( !inputs.isEmpty() )
1319 s += QStringLiteral( "<h2>" ) + QObject::tr( "Input parameters" ) + QStringLiteral( "</h2>\n" ) + inputs;
1320
1321 QString outputs;
1322 const auto outputDefinitions = algorithm->outputDefinitions();
1323 for ( const QgsProcessingOutputDefinition *def : outputDefinitions )
1324 {
1325 if ( !getText( def->name() ).isEmpty() )
1326 {
1327 outputs += QStringLiteral( "<h3>" ) + def->description() + QStringLiteral( "</h3>\n" );
1328 outputs += QStringLiteral( "<p>" ) + getText( def->name() ) + QStringLiteral( "</p>\n" );
1329 }
1330 }
1331 if ( !outputs.isEmpty() )
1332 s += QStringLiteral( "<h2>" ) + QObject::tr( "Outputs" ) + QStringLiteral( "</h2>\n" ) + outputs;
1333
1334 if ( !map.value( QStringLiteral( "EXAMPLES" ) ).toString().isEmpty() )
1335 s += QStringLiteral( "<h2>%1</h2>\n<p>%2</p>" ).arg( QObject::tr( "Examples" ), getText( QStringLiteral( "EXAMPLES" ) ) );
1336
1337 s += QLatin1String( "<br>" );
1338 if ( !map.value( QStringLiteral( "ALG_CREATOR" ) ).toString().isEmpty() )
1339 s += QStringLiteral( "<p align=\"right\">" ) + QObject::tr( "Algorithm author:" ) + QStringLiteral( " " ) + getText( QStringLiteral( "ALG_CREATOR" ) ) + QStringLiteral( "</p>" );
1340 if ( !map.value( QStringLiteral( "ALG_HELP_CREATOR" ) ).toString().isEmpty() )
1341 s += QStringLiteral( "<p align=\"right\">" ) + QObject::tr( "Help author:" ) + QStringLiteral( " " ) + getText( QStringLiteral( "ALG_HELP_CREATOR" ) ) + QStringLiteral( "</p>" );
1342 if ( !map.value( QStringLiteral( "ALG_VERSION" ) ).toString().isEmpty() )
1343 s += QStringLiteral( "<p align=\"right\">" ) + QObject::tr( "Algorithm version:" ) + QStringLiteral( " " ) + getText( QStringLiteral( "ALG_VERSION" ) ) + QStringLiteral( "</p>" );
1344
1345 s += QLatin1String( "</body></html>" );
1346 return s;
1347}
1348
1349QString convertToCompatibleFormatInternal( const QgsVectorLayer *vl, bool selectedFeaturesOnly, const QString &baseName, const QStringList &compatibleFormats, const QString &preferredFormat, QgsProcessingContext &context, QgsProcessingFeedback *feedback, QString *layerName,
1350 long long featureLimit, const QString &filterExpression )
1351{
1352 bool requiresTranslation = false;
1353
1354 // if we are only looking for selected features then we have to export back to disk,
1355 // as we need to subset only selected features, a concept which doesn't exist outside QGIS!
1356 requiresTranslation = requiresTranslation || selectedFeaturesOnly;
1357
1358 // if we are limiting the feature count, we better export
1359 requiresTranslation = requiresTranslation || featureLimit != -1 || !filterExpression.isEmpty();
1360
1361 // if the data provider is NOT ogr, then we HAVE to convert. Otherwise we run into
1362 // issues with data providers like spatialite, delimited text where the format can be
1363 // opened outside of QGIS, but with potentially very different behavior!
1364 requiresTranslation = requiresTranslation || vl->providerType() != QLatin1String( "ogr" );
1365
1366 // if the layer has a feature filter set, then we HAVE to convert. Feature filters are
1367 // a purely QGIS concept.
1368 requiresTranslation = requiresTranslation || !vl->subsetString().isEmpty();
1369
1370 // if the layer opened using GDAL's virtual I/O mechanism (/vsizip/, etc.), then
1371 // we HAVE to convert as other tools may not work with it
1372 requiresTranslation = requiresTranslation || vl->source().startsWith( QLatin1String( "/vsi" ) );
1373
1374 // Check if layer is a disk based format and if so if the layer's path has a compatible filename suffix
1375 QString diskPath;
1376 if ( !requiresTranslation )
1377 {
1378 const QVariantMap parts = QgsProviderRegistry::instance()->decodeUri( vl->providerType(), vl->source() );
1379 if ( parts.contains( QStringLiteral( "path" ) ) )
1380 {
1381 diskPath = parts.value( QStringLiteral( "path" ) ).toString();
1382 QFileInfo fi( diskPath );
1383 requiresTranslation = !compatibleFormats.contains( fi.suffix(), Qt::CaseInsensitive );
1384
1385 // if the layer name doesn't match the filename, we need to convert the layer. This method can only return
1386 // a filename, and cannot handle layernames as well as file paths
1387 const QString srcLayerName = parts.value( QStringLiteral( "layerName" ) ).toString();
1388 if ( layerName )
1389 {
1390 // differing layer names are acceptable
1391 *layerName = srcLayerName;
1392 }
1393 else
1394 {
1395 // differing layer names are NOT acceptable
1396 requiresTranslation = requiresTranslation || ( !srcLayerName.isEmpty() && srcLayerName != fi.baseName() );
1397 }
1398 }
1399 else
1400 {
1401 requiresTranslation = true; // not a disk-based format
1402 }
1403 }
1404
1405 if ( requiresTranslation )
1406 {
1407 QString temp = QgsProcessingUtils::generateTempFilename( baseName + '.' + preferredFormat, &context );
1408
1410 saveOptions.fileEncoding = context.defaultEncoding();
1411 saveOptions.driverName = QgsVectorFileWriter::driverForExtension( preferredFormat );
1412 std::unique_ptr< QgsVectorFileWriter > writer( QgsVectorFileWriter::create( temp, vl->fields(), vl->wkbType(), vl->crs(), context.transformContext(), saveOptions ) );
1413 QgsFeature f;
1415 QgsFeatureRequest request;
1416 if ( featureLimit != -1 )
1417 {
1418 request.setLimit( featureLimit );
1419 }
1420 if ( !filterExpression.isEmpty() )
1421 {
1422 request.setFilterExpression( filterExpression );
1423 }
1424
1425 if ( selectedFeaturesOnly )
1426 it = vl->getSelectedFeatures( request );
1427 else
1428 it = vl->getFeatures( request );
1429
1430 while ( it.nextFeature( f ) )
1431 {
1432 if ( feedback && feedback->isCanceled() )
1433 return QString();
1434 writer->addFeature( f, QgsFeatureSink::FastInsert );
1435 }
1436 return temp;
1437 }
1438 else
1439 {
1440 return diskPath;
1441 }
1442}
1443
1444QString QgsProcessingUtils::convertToCompatibleFormat( const QgsVectorLayer *vl, bool selectedFeaturesOnly, const QString &baseName, const QStringList &compatibleFormats, const QString &preferredFormat, QgsProcessingContext &context, QgsProcessingFeedback *feedback, long long featureLimit, const QString &filterExpression )
1445{
1446 return convertToCompatibleFormatInternal( vl, selectedFeaturesOnly, baseName, compatibleFormats, preferredFormat, context, feedback, nullptr, featureLimit, filterExpression );
1447}
1448
1449QString QgsProcessingUtils::convertToCompatibleFormatAndLayerName( const QgsVectorLayer *layer, bool selectedFeaturesOnly, const QString &baseName, const QStringList &compatibleFormats, const QString &preferredFormat, QgsProcessingContext &context, QgsProcessingFeedback *feedback, QString &layerName, long long featureLimit, const QString &filterExpression )
1450{
1451 layerName.clear();
1452 return convertToCompatibleFormatInternal( layer, selectedFeaturesOnly, baseName, compatibleFormats, preferredFormat, context, feedback, &layerName, featureLimit, filterExpression );
1453}
1454
1455QgsFields QgsProcessingUtils::combineFields( const QgsFields &fieldsA, const QgsFields &fieldsB, const QString &fieldsBPrefix )
1456{
1457 QgsFields outFields = fieldsA;
1458 QSet< QString > usedNames;
1459 for ( const QgsField &f : fieldsA )
1460 {
1461 usedNames.insert( f.name().toLower() );
1462 }
1463
1464 for ( const QgsField &f : fieldsB )
1465 {
1466 QgsField newField = f;
1467 newField.setName( fieldsBPrefix + f.name() );
1468 if ( usedNames.contains( newField.name().toLower() ) )
1469 {
1470 int idx = 2;
1471 QString newName = newField.name() + '_' + QString::number( idx );
1472 while ( usedNames.contains( newName.toLower() ) || fieldsB.indexOf( newName ) != -1 )
1473 {
1474 idx++;
1475 newName = newField.name() + '_' + QString::number( idx );
1476 }
1477 newField.setName( newName );
1478 outFields.append( newField );
1479 }
1480 else
1481 {
1482 outFields.append( newField );
1483 }
1484 usedNames.insert( newField.name() );
1485 }
1486
1487 return outFields;
1488}
1489
1490
1491QList<int> QgsProcessingUtils::fieldNamesToIndices( const QStringList &fieldNames, const QgsFields &fields )
1492{
1493 QList<int> indices;
1494 if ( !fieldNames.isEmpty() )
1495 {
1496 indices.reserve( fieldNames.count() );
1497 for ( const QString &f : fieldNames )
1498 {
1499 int idx = fields.lookupField( f );
1500 if ( idx >= 0 )
1501 indices.append( idx );
1502 }
1503 }
1504 else
1505 {
1506 indices.reserve( fields.count() );
1507 for ( int i = 0; i < fields.count(); ++i )
1508 indices.append( i );
1509 }
1510 return indices;
1511}
1512
1513
1514QgsFields QgsProcessingUtils::indicesToFields( const QList<int> &indices, const QgsFields &fields )
1515{
1516 QgsFields fieldsSubset;
1517 for ( int i : indices )
1518 fieldsSubset.append( fields.at( i ) );
1519 return fieldsSubset;
1520}
1521
1523{
1525 if ( setting == -1 )
1526 return QStringLiteral( "gpkg" );
1527 return QgsVectorFileWriter::supportedFormatExtensions().value( setting, QStringLiteral( "gpkg" ) );
1528}
1529
1531{
1533 if ( setting == -1 )
1534 return QStringLiteral( "tif" );
1535 return QgsRasterFileWriter::supportedFormatExtensions().value( setting, QStringLiteral( "tif" ) );
1536}
1537
1539{
1540 return QStringLiteral( "las" );
1541}
1542
1544{
1545 return QStringLiteral( "mbtiles" );
1546}
1547
1548QVariantMap QgsProcessingUtils::removePointerValuesFromMap( const QVariantMap &map )
1549{
1550 auto layerPointerToString = []( QgsMapLayer * layer ) -> QString
1551 {
1552 if ( layer && layer->providerType() == QLatin1String( "memory" ) )
1553 return layer->id();
1554 else if ( layer )
1555 return layer->source();
1556 else
1557 return QString();
1558 };
1559
1560 auto cleanPointerValues = [&layerPointerToString]( const QVariant & value ) -> QVariant
1561 {
1562 if ( QgsMapLayer *layer = qobject_cast< QgsMapLayer * >( value.value< QObject * >() ) )
1563 {
1564 // don't store pointers in maps for long-term storage
1565 return layerPointerToString( layer );
1566 }
1567 else if ( value.userType() == QMetaType::type( "QPointer< QgsMapLayer >" ) )
1568 {
1569 // don't store pointers in maps for long-term storage
1570 return layerPointerToString( value.value< QPointer< QgsMapLayer > >().data() );
1571 }
1572 else
1573 {
1574 return value;
1575 }
1576 };
1577
1578 QVariantMap res;
1579 for ( auto it = map.constBegin(); it != map.constEnd(); ++it )
1580 {
1581 if ( it->type() == QVariant::Map )
1582 {
1583 res.insert( it.key(), removePointerValuesFromMap( it.value().toMap() ) );
1584 }
1585 else if ( it->type() == QVariant::List )
1586 {
1587 QVariantList dest;
1588 const QVariantList source = it.value().toList();
1589 dest.reserve( source.size() );
1590 for ( const QVariant &v : source )
1591 {
1592 dest.append( cleanPointerValues( v ) );
1593 }
1594 res.insert( it.key(), dest );
1595 }
1596 else
1597 {
1598 res.insert( it.key(), cleanPointerValues( it.value() ) );
1599 }
1600 }
1601 return res;
1602}
1603
1604QVariantMap QgsProcessingUtils::preprocessQgisProcessParameters( const QVariantMap &parameters, bool &ok, QString &error )
1605{
1606 QVariantMap output;
1607 ok = true;
1608 for ( auto it = parameters.constBegin(); it != parameters.constEnd(); ++it )
1609 {
1610 if ( it.value().type() == QVariant::Map )
1611 {
1612 const QVariantMap value = it.value().toMap();
1613 if ( value.value( QStringLiteral( "type" ) ).toString() == QLatin1String( "data_defined" ) )
1614 {
1615 const QString expression = value.value( QStringLiteral( "expression" ) ).toString();
1616 const QString field = value.value( QStringLiteral( "field" ) ).toString();
1617 if ( !expression.isEmpty() )
1618 {
1619 output.insert( it.key(), QgsProperty::fromExpression( expression ) );
1620 }
1621 else if ( !field.isEmpty() )
1622 {
1623 output.insert( it.key(), QgsProperty::fromField( field ) );
1624 }
1625 else
1626 {
1627 ok = false;
1628 error = QObject::tr( "Invalid data defined parameter for %1, requires 'expression' or 'field' values." ).arg( it.key() );
1629 }
1630 }
1631 else
1632 {
1633 output.insert( it.key(), it.value() );
1634 }
1635 }
1636 else if ( it.value().type() == QVariant::String )
1637 {
1638 const QString stringValue = it.value().toString();
1639
1640 if ( stringValue.startsWith( QLatin1String( "field:" ) ) )
1641 {
1642 output.insert( it.key(), QgsProperty::fromField( stringValue.mid( 6 ) ) );
1643 }
1644 else if ( stringValue.startsWith( QLatin1String( "expression:" ) ) )
1645 {
1646 output.insert( it.key(), QgsProperty::fromExpression( stringValue.mid( 11 ) ) );
1647 }
1648 else
1649 {
1650 output.insert( it.key(), it.value() );
1651 }
1652 }
1653 else
1654 {
1655 output.insert( it.key(), it.value() );
1656 }
1657 }
1658 return output;
1659}
1660
1661QString QgsProcessingUtils::resolveDefaultEncoding( const QString &defaultEncoding )
1662{
1663 if ( ! QTextCodec::availableCodecs().contains( defaultEncoding.toLatin1() ) )
1664 {
1665 const QString systemCodec = QTextCodec::codecForLocale()->name();
1666 if ( ! systemCodec.isEmpty() )
1667 {
1668 return systemCodec;
1669 }
1670 return QString( "UTF-8" );
1671 }
1672
1673 return defaultEncoding;
1674}
1675
1676//
1677// QgsProcessingFeatureSource
1678//
1679
1680QgsProcessingFeatureSource::QgsProcessingFeatureSource( QgsFeatureSource *originalSource, const QgsProcessingContext &context, bool ownsOriginalSource, long long featureLimit, const QString &filterExpression )
1681 : mSource( originalSource )
1682 , mOwnsSource( ownsOriginalSource )
1683 , mSourceCrs( mSource->sourceCrs() )
1684 , mSourceFields( mSource->fields() )
1685 , mSourceWkbType( mSource->wkbType() )
1686 , mSourceName( mSource->sourceName() )
1687 , mSourceExtent( mSource->sourceExtent() )
1688 , mSourceSpatialIndexPresence( mSource->hasSpatialIndex() )
1689 , mInvalidGeometryCheck( QgsWkbTypes::geometryType( mSource->wkbType() ) == Qgis::GeometryType::Point
1690 ? Qgis::InvalidGeometryCheck::NoCheck // never run geometry validity checks for point layers!
1691 : context.invalidGeometryCheck() )
1692 , mInvalidGeometryCallback( context.invalidGeometryCallback( originalSource ) )
1693 , mTransformErrorCallback( context.transformErrorCallback() )
1694 , mInvalidGeometryCallbackSkip( context.defaultInvalidGeometryCallbackForCheck( Qgis::InvalidGeometryCheck::SkipInvalid, originalSource ) )
1695 , mInvalidGeometryCallbackAbort( context.defaultInvalidGeometryCallbackForCheck( Qgis::InvalidGeometryCheck::AbortOnInvalid, originalSource ) )
1696 , mFeatureLimit( featureLimit )
1697 , mFilterExpression( filterExpression )
1698{}
1699
1701{
1702 if ( mOwnsSource )
1703 delete mSource;
1704}
1705
1707{
1708 QgsFeatureRequest req( request );
1709 req.setTransformErrorCallback( mTransformErrorCallback );
1710
1713 else
1714 {
1715 req.setInvalidGeometryCheck( mInvalidGeometryCheck );
1716 req.setInvalidGeometryCallback( mInvalidGeometryCallback );
1717 }
1718
1719 if ( mFeatureLimit != -1 && req.limit() != -1 )
1720 req.setLimit( std::min( static_cast< long long >( req.limit() ), mFeatureLimit ) );
1721 else if ( mFeatureLimit != -1 )
1722 req.setLimit( mFeatureLimit );
1723
1724 if ( !mFilterExpression.isEmpty() )
1725 req.combineFilterExpression( mFilterExpression );
1726
1727 return mSource->getFeatures( req );
1728}
1729
1731{
1732 Qgis::FeatureAvailability sourceAvailability = mSource->hasFeatures();
1733 if ( sourceAvailability == Qgis::FeatureAvailability::NoFeaturesAvailable )
1734 return Qgis::FeatureAvailability::NoFeaturesAvailable; // never going to be features if underlying source has no features
1735 else if ( mInvalidGeometryCheck == Qgis::InvalidGeometryCheck::NoCheck && mFilterExpression.isEmpty() )
1736 return sourceAvailability;
1737 else
1738 // we don't know... source has features, but these may be filtered out by invalid geometry check or filter expression
1740}
1741
1743{
1744 QgsFeatureRequest req( request );
1745 req.setInvalidGeometryCheck( mInvalidGeometryCheck );
1746 req.setInvalidGeometryCallback( mInvalidGeometryCallback );
1747 req.setTransformErrorCallback( mTransformErrorCallback );
1748
1749 if ( mFeatureLimit != -1 && req.limit() != -1 )
1750 req.setLimit( std::min( static_cast< long long >( req.limit() ), mFeatureLimit ) );
1751 else if ( mFeatureLimit != -1 )
1752 req.setLimit( mFeatureLimit );
1753
1754 if ( !mFilterExpression.isEmpty() )
1755 req.combineFilterExpression( mFilterExpression );
1756
1757 return mSource->getFeatures( req );
1758}
1759
1761{
1762 return mSourceCrs;
1763}
1764
1766{
1767 return mSourceFields;
1768}
1769
1771{
1772 return mSourceWkbType;
1773}
1774
1776{
1777 if ( !mFilterExpression.isEmpty() )
1778 return static_cast< int >( Qgis::FeatureCountState::UnknownCount );
1779
1780 if ( mFeatureLimit == -1 )
1781 return mSource->featureCount();
1782 else
1783 return std::min( mFeatureLimit, mSource->featureCount() );
1784}
1785
1787{
1788 return mSourceName;
1789}
1790
1791QSet<QVariant> QgsProcessingFeatureSource::uniqueValues( int fieldIndex, int limit ) const
1792{
1793 if ( mFilterExpression.isEmpty() )
1794 return mSource->uniqueValues( fieldIndex, limit );
1795
1796 // inefficient method when filter expression in use
1797 // TODO QGIS 4.0 -- add filter expression to virtual ::uniqueValues function
1798 if ( fieldIndex < 0 || fieldIndex >= fields().count() )
1799 return QSet<QVariant>();
1800
1803 req.setSubsetOfAttributes( QgsAttributeList() << fieldIndex );
1804 req.setFilterExpression( mFilterExpression );
1805
1806 QSet<QVariant> values;
1807 QgsFeatureIterator it = getFeatures( req );
1808 QgsFeature f;
1809 while ( it.nextFeature( f ) )
1810 {
1811 values.insert( f.attribute( fieldIndex ) );
1812 if ( limit > 0 && values.size() >= limit )
1813 return values;
1814 }
1815 return values;
1816}
1817
1818QVariant QgsProcessingFeatureSource::minimumValue( int fieldIndex ) const
1819{
1820 if ( mFilterExpression.isEmpty() )
1821 return mSource->minimumValue( fieldIndex );
1822
1823 // inefficient method when filter expression in use
1824 // TODO QGIS 4.0 -- add filter expression to virtual ::minimumValue function
1825 if ( fieldIndex < 0 || fieldIndex >= fields().count() )
1826 return QVariant();
1827
1830 req.setSubsetOfAttributes( QgsAttributeList() << fieldIndex );
1831
1832 QVariant min;
1833 QgsFeatureIterator it = getFeatures( req );
1834 QgsFeature f;
1835 while ( it.nextFeature( f ) )
1836 {
1837 const QVariant v = f.attribute( fieldIndex );
1838 if ( !QgsVariantUtils::isNull( v ) && ( qgsVariantLessThan( v, min ) || QgsVariantUtils::isNull( min ) ) )
1839 {
1840 min = v;
1841 }
1842 }
1843 return min;
1844}
1845
1846QVariant QgsProcessingFeatureSource::maximumValue( int fieldIndex ) const
1847{
1848 if ( mFilterExpression.isEmpty() )
1849 return mSource->maximumValue( fieldIndex );
1850
1851 // inefficient method when filter expression in use
1852 // TODO QGIS 4.0 -- add filter expression to virtual ::maximumValue function
1853 if ( fieldIndex < 0 || fieldIndex >= fields().count() )
1854 return QVariant();
1855
1858 req.setSubsetOfAttributes( QgsAttributeList() << fieldIndex );
1859
1860 QVariant max;
1861 QgsFeatureIterator it = getFeatures( req );
1862 QgsFeature f;
1863 while ( it.nextFeature( f ) )
1864 {
1865 const QVariant v = f.attribute( fieldIndex );
1866 if ( !QgsVariantUtils::isNull( v ) && ( qgsVariantGreaterThan( v, max ) || QgsVariantUtils::isNull( max ) ) )
1867 {
1868 max = v;
1869 }
1870 }
1871 return max;
1872}
1873
1875{
1876 return mSourceExtent;
1877}
1878
1880{
1881 if ( mFilterExpression.isEmpty() )
1882 return mSource->allFeatureIds();
1883
1886 .setNoAttributes()
1887 .setFilterExpression( mFilterExpression ) );
1888
1889 QgsFeatureIds ids;
1890
1891 QgsFeature fet;
1892 while ( fit.nextFeature( fet ) )
1893 {
1894 ids << fet.id();
1895 }
1896
1897 return ids;
1898}
1899
1901{
1902 return mSourceSpatialIndexPresence;
1903}
1904
1906{
1907 QgsExpressionContextScope *expressionContextScope = nullptr;
1908 QgsExpressionContextScopeGenerator *generator = dynamic_cast<QgsExpressionContextScopeGenerator *>( mSource );
1909 if ( generator )
1910 {
1911 expressionContextScope = generator->createExpressionContextScope();
1912 }
1913 return expressionContextScope;
1914}
1915
1917{
1918 mInvalidGeometryCheck = method;
1919 switch ( mInvalidGeometryCheck )
1920 {
1922 mInvalidGeometryCallback = nullptr;
1923 break;
1924
1926 mInvalidGeometryCallback = mInvalidGeometryCallbackSkip;
1927 break;
1928
1930 mInvalidGeometryCallback = mInvalidGeometryCallbackAbort;
1931 break;
1932
1933 }
1934}
1935
1937{
1938 return mInvalidGeometryCheck;
1939}
1940
1941
1942//
1943// QgsProcessingFeatureSink
1944//
1945QgsProcessingFeatureSink::QgsProcessingFeatureSink( QgsFeatureSink *originalSink, const QString &sinkName, QgsProcessingContext &context, bool ownsOriginalSink )
1946 : QgsProxyFeatureSink( originalSink )
1947 , mContext( context )
1948 , mSinkName( sinkName )
1949 , mOwnsSink( ownsOriginalSink )
1950{}
1951
1953{
1954 if ( mOwnsSink )
1955 delete destinationSink();
1956}
1957
1959{
1960 bool result = QgsProxyFeatureSink::addFeature( feature, flags );
1961 if ( !result && mContext.feedback() )
1962 {
1963 const QString error = lastError();
1964 if ( !error.isEmpty() )
1965 mContext.feedback()->reportError( QObject::tr( "Feature could not be written to %1: %2" ).arg( mSinkName, error ) );
1966 else
1967 mContext.feedback()->reportError( QObject::tr( "Feature could not be written to %1" ).arg( mSinkName ) );
1968 }
1969 return result;
1970}
1971
1973{
1974 bool result = QgsProxyFeatureSink::addFeatures( features, flags );
1975 if ( !result && mContext.feedback() )
1976 {
1977 const QString error = lastError();
1978 if ( !error.isEmpty() )
1979 mContext.feedback()->reportError( QObject::tr( "%n feature(s) could not be written to %1: %2", nullptr, features.count() ).arg( mSinkName, error ) );
1980 else
1981 mContext.feedback()->reportError( QObject::tr( "%n feature(s) could not be written to %1", nullptr, features.count() ).arg( mSinkName ) );
1982 }
1983 return result;
1984}
1985
1987{
1988 bool result = QgsProxyFeatureSink::addFeatures( iterator, flags );
1989 if ( !result && mContext.feedback() )
1990 {
1991 const QString error = lastError();
1992 if ( !error.isEmpty() )
1993 mContext.feedback()->reportError( QObject::tr( "Features could not be written to %1: %2" ).arg( mSinkName, error ) );
1994 else
1995 mContext.feedback()->reportError( QObject::tr( "Features could not be written to %1" ).arg( mSinkName ) );
1996 }
1997 return result;
1998}
The Qgis class provides global constants for use throughout the application.
Definition: qgis.h:54
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
@ VectorAnyGeometry
Any vector layer with geometry.
@ VectorPoint
Vector point layers.
@ VectorPolygon
Vector polygon layers.
@ VectorLine
Vector line layers.
@ FieldComments
Writer can support field comments.
@ FieldAliases
Writer can support field aliases.
SpatialIndexPresence
Enumeration of spatial index presence states.
Definition: qgis.h:349
@ Success
No errors were encountered.
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
@ Static
Static property.
@ Polygon
Polygons.
FeatureAvailability
Possible return value for QgsFeatureSource::hasFeatures() to determine if a source is empty.
Definition: qgis.h:368
@ FeaturesMaybeAvailable
There may be features available in this source.
@ NoFeaturesAvailable
There are certainly no features available in this source.
@ TiledScene
Tiled scene layer. Added in QGIS 3.34.
@ Annotation
Contains freeform, georeferenced annotations. Added in QGIS 3.16.
@ Vector
Vector layer.
@ VectorTile
Vector tile layer. Added in QGIS 3.14.
@ Mesh
Mesh layer. Added in QGIS 3.2.
@ Raster
Raster layer.
@ PointCloud
Point cloud layer. Added in QGIS 3.18.
QFlags< VectorDataProviderAttributeEditCapability > VectorDataProviderAttributeEditCapabilities
Attribute editing capabilities which may be supported by vector data providers.
Definition: qgis.h:393
InvalidGeometryCheck
Methods for handling of features with invalid geometries.
Definition: qgis.h:1778
@ NoCheck
No invalid geometry checking.
@ AbortOnInvalid
Close iterator on encountering any features with invalid geometry. This requires a slow geometry vali...
@ SkipInvalid
Skip any features with invalid geometry. This requires a slow geometry validity check for every featu...
@ OverrideDefaultGeometryCheck
If set, the default geometry check method (as dictated by QgsProcessingContext) will be overridden fo...
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition: qgis.h:182
@ Hidden
Parameter is hidden and should not be shown to users.
@ NoSymbology
Export only data.
QFlags< ProcessingFeatureSourceFlag > ProcessingFeatureSourceFlags
Flags which control how QgsProcessingFeatureSource fetches features.
Definition: qgis.h:3011
Represents a map layer containing a set of georeferenced annotations, e.g.
This class represents a coordinate reference system (CRS).
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
bool createFromString(const QString &definition)
Set up this CRS from a string definition.
Contains information about the context in which a coordinate transform is executed.
Class for doing transforms between two map coordinate systems.
void setBallparkTransformsAreAppropriate(bool appropriate)
Sets whether approximate "ballpark" results are appropriate for this coordinate transform.
QgsRectangle transformBoundingBox(const QgsRectangle &rectangle, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool handle180Crossover=false) const
Transforms a rectangle from the source CRS to the destination CRS.
Custom exception class for Coordinate Reference System related exceptions.
Definition: qgsexception.h:67
Class for storing the component parts of a RDBMS data source URI (e.g.
QByteArray encodedUri() const
Returns the complete encoded URI as a byte array.
QString table() const
Returns the table name stored in the URI.
void setParam(const QString &key, const QString &value)
Sets a generic parameter value on the URI.
QString database() const
Returns the database name stored in the URI.
Abstract interface for generating an expression context scope.
virtual QgsExpressionContextScope * createExpressionContextScope() const =0
This method needs to be reimplemented in all classes which implement this interface and return an exp...
Single scope for storing variables and functions for use within a QgsExpressionContext.
void setFields(const QgsFields &fields)
Convenience function for setting a fields for the context.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFlags(Qgis::FeatureRequestFlags flags)
Sets flags that affect how features will be fetched.
QgsFeatureRequest & setLimit(long long limit)
Set the maximum number of features to request.
long long limit() const
Returns the maximum number of features to request, or -1 if no limit set.
QgsFeatureRequest & combineFilterExpression(const QString &expression)
Modifies the existing filter expression to add an additional expression filter.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QgsFeatureRequest & setInvalidGeometryCheck(Qgis::InvalidGeometryCheck check)
Sets invalid geometry checking behavior.
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
QgsFeatureRequest & setInvalidGeometryCallback(const std::function< void(const QgsFeature &)> &callback)
Sets a callback function to use when encountering an invalid geometry and invalidGeometryCheck() is s...
QgsFeatureRequest & setTransformErrorCallback(const std::function< void(const QgsFeature &)> &callback)
Sets a callback function to use when encountering a transform error when iterating features and a des...
An interface for objects which accept features via addFeature(s) methods.
QFlags< SinkFlag > SinkFlags
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
@ RegeneratePrimaryKey
This flag indicates, that a primary key field cannot be guaranteed to be unique and the sink should i...
QFlags< Flag > Flags
An interface for objects which provide features via a getFeatures method.
virtual QSet< QVariant > uniqueValues(int fieldIndex, int limit=-1) const
Returns the set of unique values contained within the specified fieldIndex from this source.
virtual Qgis::FeatureAvailability hasFeatures() const
Determines if there are any features available in the source.
virtual QVariant minimumValue(int fieldIndex) const
Returns the minimum value for an attribute column or an invalid variant in case of error.
virtual QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const =0
Returns an iterator for the features in the source.
virtual QVariant maximumValue(int fieldIndex) const
Returns the maximum value for an attribute column or an invalid variant in case of error.
virtual long long featureCount() const =0
Returns the number of features contained in the source, or -1 if the feature count is unknown.
virtual QgsFeatureIds allFeatureIds() const
Returns a list of all feature IDs for features present in the source.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition: qgsfeature.h:56
QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
Definition: qgsfeature.cpp:335
Q_GADGET QgsFeatureId id
Definition: qgsfeature.h:64
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition: qgsfeedback.h:53
Encapsulate a field in an attribute table or data source.
Definition: qgsfield.h:53
QString name
Definition: qgsfield.h:62
void setName(const QString &name)
Set the field name.
Definition: qgsfield.cpp:216
Container of fields for a vector layer.
Definition: qgsfields.h:45
bool append(const QgsField &field, FieldOrigin origin=OriginProvider, int originIndex=-1)
Appends a field. The field must have unique name, otherwise it is rejected (returns false)
Definition: qgsfields.cpp:59
int indexOf(const QString &fieldName) const
Gets the field index from the field name.
Definition: qgsfields.cpp:207
int count() const
Returns number of items.
Definition: qgsfields.cpp:133
QgsField at(int i) const
Returns the field at particular index (must be in range 0..N-1).
Definition: qgsfields.cpp:163
int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
Definition: qgsfields.cpp:359
static QString stringToSafeFilename(const QString &string)
Converts a string to a safe filename, replacing characters which are not safe for filenames with an '...
A storage object for map layers, in which the layers are owned by the store and have their lifetime b...
QMap< QString, QgsMapLayer * > mapLayers() const
Returns a map of all layers by layer ID.
QgsMapLayer * addMapLayer(QgsMapLayer *layer, bool takeOwnership=true)
Add a layer to the store.
Base class for all map layer types.
Definition: qgsmaplayer.h:75
QString source() const
Returns the source for the layer.
QString providerType() const
Returns the provider type (provider key) for this layer.
QgsCoordinateReferenceSystem crs
Definition: qgsmaplayer.h:81
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
bool isValid
Definition: qgsmaplayer.h:83
virtual void setTransformContext(const QgsCoordinateTransformContext &transformContext)=0
Sets the coordinate transform context to transformContext.
static QgsVectorLayer * createMemoryLayer(const QString &name, const QgsFields &fields, Qgis::WkbType geometryType=Qgis::WkbType::NoGeometry, const QgsCoordinateReferenceSystem &crs=QgsCoordinateReferenceSystem(), bool loadDefaultStyle=true) SIP_FACTORY
Creates a new memory layer using the specified parameters.
Represents a mesh layer supporting display of data on structured or unstructured meshes.
Definition: qgsmeshlayer.h:101
QgsMeshDataProvider * dataProvider() override
Returns the layer's data provider, it may be nullptr.
Base class for plugin layers.
Represents a map layer supporting display of point clouds.
A class to represent a 2D point.
Definition: qgspointxy.h:60
double y
Definition: qgspointxy.h:64
Q_GADGET double x
Definition: qgspointxy.h:63
Abstract base class for processing algorithms.
QgsProcessingOutputDefinitions outputDefinitions() const
Returns an ordered list of output definitions utilized by the algorithm.
QgsProcessingParameterDefinitions parameterDefinitions() const
Returns an ordered list of parameter definitions utilized by the algorithm.
Contains information about the context in which a processing algorithm is executed.
QString defaultEncoding() const
Returns the default encoding to use for newly created files.
QgsProcessingFeedback * feedback()
Returns the associated feedback object.
QgsExpressionContext & expressionContext()
Returns the expression context.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
QgsProject * project() const
Returns the project in which the algorithm is being executed.
QgsMapLayerStore * temporaryLayerStore()
Returns a reference to the layer store used for storing temporary layers during algorithm execution.
QString temporaryFolder() const
Returns the (optional) temporary folder to use when running algorithms.
Custom exception class for processing related exceptions.
Definition: qgsexception.h:83
QgsProxyFeatureSink subclass which reports feature addition errors to a QgsProcessingContext.
QgsProcessingFeatureSink(QgsFeatureSink *originalSink, const QString &sinkName, QgsProcessingContext &context, bool ownsOriginalSink=false)
Constructor for QgsProcessingFeatureSink, accepting an original feature sink originalSink and process...
bool addFeatures(QgsFeatureList &features, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a list of features to the sink.
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a single feature to the sink.
Encapsulates settings relating to a feature source input to a processing algorithm.
bool selectedFeaturesOnly
true if only selected features in the source should be used by algorithms.
Qgis::InvalidGeometryCheck geometryCheck
Geometry check method to apply to this source.
Qgis::ProcessingFeatureSourceDefinitionFlags flags
Flags which dictate source behavior.
long long featureLimit
If set to a value > 0, places a limit on the maximum number of features which will be read from the s...
QString filterExpression
Optional expression filter to use for filtering features which will be read from the source.
QgsFeatureSource subclass which proxies methods to an underlying QgsFeatureSource,...
QgsRectangle sourceExtent() const override
Returns the extent of all geometries from the source.
QSet< QVariant > uniqueValues(int fieldIndex, int limit=-1) const override
Returns the set of unique values contained within the specified fieldIndex from this source.
QgsExpressionContextScope * createExpressionContextScope() const
Returns an expression context scope suitable for this source.
QgsProcessingFeatureSource(QgsFeatureSource *originalSource, const QgsProcessingContext &context, bool ownsOriginalSource=false, long long featureLimit=-1, const QString &filterExpression=QString())
Constructor for QgsProcessingFeatureSource, accepting an original feature source originalSource and p...
void setInvalidGeometryCheck(Qgis::InvalidGeometryCheck method)
Overrides the default geometry check method for the source.
Qgis::InvalidGeometryCheck invalidGeometryCheck() const
Returns the geometry check method for the source.
QVariant maximumValue(int fieldIndex) const override
Returns the maximum value for an attribute column or an invalid variant in case of error.
QgsCoordinateReferenceSystem sourceCrs() const override
Returns the coordinate reference system for features in the source.
Qgis::WkbType wkbType() const override
Returns the geometry type for features returned by this source.
QVariant minimumValue(int fieldIndex) const override
Returns the minimum value for an attribute column or an invalid variant in case of error.
long long featureCount() const override
Returns the number of features contained in the source, or -1 if the feature count is unknown.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request, Qgis::ProcessingFeatureSourceFlags flags) const
Returns an iterator for the features in the source, respecting the supplied feature flags.
Qgis::FeatureAvailability hasFeatures() const override
Determines if there are any features available in the source.
QString sourceName() const override
Returns a friendly display name for the source.
QgsFeatureIds allFeatureIds() const override
Returns a list of all feature IDs for features present in the source.
Qgis::SpatialIndexPresence hasSpatialIndex() const override
Returns an enum value representing the presence of a valid spatial index on the source,...
QgsFields fields() const override
Returns the fields associated with features in the source.
Base class for providing feedback from a processing algorithm.
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
Base class for the definition of processing outputs.
Encapsulates settings relating to a feature sink or output raster layer for a processing algorithm.
QgsProperty sink
Sink/layer definition.
Base class for the definition of processing parameters.
static QList< QgsTiledSceneLayer * > compatibleTiledSceneLayers(QgsProject *project, bool sort=true)
Returns a list of tiled scene layers from a project which are compatible with the processing framewor...
static QString stringToPythonLiteral(const QString &string)
Converts a string to a Python string literal.
static QString defaultVectorExtension()
Returns the default vector extension to use, in the absence of all other constraints (e....
static QVariant generateIteratingDestination(const QVariant &input, const QVariant &id, QgsProcessingContext &context)
Converts an input parameter value for use in source iterating mode, where one individual sink is crea...
static QgsFields indicesToFields(const QList< int > &indices, const QgsFields &fields)
Returns a subset of fields based on the indices of desired fields.
static QList< int > fieldNamesToIndices(const QStringList &fieldNames, const QgsFields &fields)
Returns a list of field indices parsed from the given list of field names.
static QVariantMap preprocessQgisProcessParameters(const QVariantMap &parameters, bool &ok, QString &error)
Pre-processes a set of parameter values for the qgis_process command.
static QList< QgsAnnotationLayer * > compatibleAnnotationLayers(QgsProject *project, bool sort=true)
Returns a list of annotation layers from a project which are compatible with the processing framework...
static QString generateTempFilename(const QString &basename, const QgsProcessingContext *context=nullptr)
Returns a temporary filename for a given file, putting it into a temporary folder (creating that fold...
static QString normalizeLayerSource(const QString &source)
Normalizes a layer source string for safe comparison across different operating system environments.
static QString formatHelpMapAsHtml(const QVariantMap &map, const QgsProcessingAlgorithm *algorithm)
Returns a HTML formatted version of the help text encoded in a variant map for a specified algorithm.
static QgsFields combineFields(const QgsFields &fieldsA, const QgsFields &fieldsB, const QString &fieldsBPrefix=QString())
Combines two field lists, avoiding duplicate field names (in a case-insensitive manner).
static QString encodeProviderKeyAndUri(const QString &providerKey, const QString &uri)
Encodes a provider key and layer uri to a single string, for use with decodeProviderKeyAndUri()
LayerHint
Layer type hints.
@ TiledScene
Tiled scene layer type, since QGIS 3.34.
@ Annotation
Annotation layer type, since QGIS 3.22.
@ Vector
Vector layer type.
@ VectorTile
Vector tile layer type, since QGIS 3.32.
@ Mesh
Mesh layer type, since QGIS 3.6.
@ Raster
Raster layer type.
@ UnknownType
Unknown layer type.
@ PointCloud
Point cloud layer type, since QGIS 3.22.
static QString layerToStringIdentifier(const QgsMapLayer *layer)
Returns a string representation of the source for a layer.
static QgsProcessingFeatureSource * variantToSource(const QVariant &value, QgsProcessingContext &context, const QVariant &fallbackValue=QVariant())
Converts a variant value to a new feature source.
static QList< QgsRasterLayer * > compatibleRasterLayers(QgsProject *project, bool sort=true)
Returns a list of raster layers from a project which are compatible with the processing framework.
static QgsRectangle combineLayerExtents(const QList< QgsMapLayer * > &layers, const QgsCoordinateReferenceSystem &crs, QgsProcessingContext &context)
Combines the extent of several map layers.
static QString resolveDefaultEncoding(const QString &defaultEncoding="System")
Returns the default encoding.
static QList< QgsPluginLayer * > compatiblePluginLayers(QgsProject *project, bool sort=true)
Returns a list of plugin layers from a project which are compatible with the processing framework.
static QString variantToPythonLiteral(const QVariant &value)
Converts a variant to a Python literal.
static QgsCoordinateReferenceSystem variantToCrs(const QVariant &value, QgsProcessingContext &context, const QVariant &fallbackValue=QVariant())
Converts a variant value to a coordinate reference system.
static QList< QgsVectorLayer * > compatibleVectorLayers(QgsProject *project, const QList< int > &sourceTypes=QList< int >(), bool sort=true)
Returns a list of vector layers from a project which are compatible with the processing framework.
static QVariantMap removePointerValuesFromMap(const QVariantMap &map)
Removes any raw pointer values from an input map, replacing them with appropriate string values where...
static bool decodeProviderKeyAndUri(const QString &string, QString &providerKey, QString &uri)
Decodes a provider key and layer uri from an encoded string, for use with encodeProviderKeyAndUri()
static void createFeatureSinkPython(QgsFeatureSink **sink, QString &destination, QgsProcessingContext &context, const QgsFields &fields, Qgis::WkbType geometryType, const QgsCoordinateReferenceSystem &crs, const QVariantMap &createOptions=QVariantMap())
Creates a feature sink ready for adding features.
static QList< QgsVectorTileLayer * > compatibleVectorTileLayers(QgsProject *project, bool sort=true)
Returns a list of vector tile layers from a project which are compatible with the processing framewor...
static QString convertToCompatibleFormatAndLayerName(const QgsVectorLayer *layer, bool selectedFeaturesOnly, const QString &baseName, const QStringList &compatibleFormats, const QString &preferredFormat, QgsProcessingContext &context, QgsProcessingFeedback *feedback, QString &layerName, long long featureLimit=-1, const QString &filterExpression=QString())
Converts a source vector layer to a file path and layer name of a vector layer of compatible format.
static QList< QgsMapLayer * > compatibleLayers(QgsProject *project, bool sort=true)
Returns a list of map layers from a project which are compatible with the processing framework.
static QString convertToCompatibleFormat(const QgsVectorLayer *layer, bool selectedFeaturesOnly, const QString &baseName, const QStringList &compatibleFormats, const QString &preferredFormat, QgsProcessingContext &context, QgsProcessingFeedback *feedback, long long featureLimit=-1, const QString &filterExpression=QString())
Converts a source vector layer to a file path of a vector layer of compatible format.
static QgsFeatureSink * createFeatureSink(QString &destination, QgsProcessingContext &context, const QgsFields &fields, Qgis::WkbType geometryType, const QgsCoordinateReferenceSystem &crs, const QVariantMap &createOptions=QVariantMap(), const QStringList &datasourceOptions=QStringList(), const QStringList &layerOptions=QStringList(), QgsFeatureSink::SinkFlags sinkFlags=QgsFeatureSink::SinkFlags(), QgsRemappingSinkDefinition *remappingDefinition=nullptr)
Creates a feature sink ready for adding features.
static QString defaultRasterExtension()
Returns the default raster extension to use, in the absence of all other constraints (e....
static QString defaultVectorTileExtension()
Returns the default vector tile extension to use, in the absence of all other constraints (e....
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 QString defaultPointCloudExtension()
Returns the default point cloud extension to use, in the absence of all other constraints (e....
static QList< QgsPointCloudLayer * > compatiblePointCloudLayers(QgsProject *project, bool sort=true)
Returns a list of point cloud layers from a project which are compatible with the processing framewor...
static QList< QgsMeshLayer * > compatibleMeshLayers(QgsProject *project, bool sort=true)
Returns a list of mesh layers from a project which are compatible with the processing framework.
static QString tempFolder(const QgsProcessingContext *context=nullptr)
Returns a session specific processing temporary folder for use in processing algorithms.
static const QgsSettingsEntryInteger * settingsDefaultOutputRasterLayerExt
Settings entry default output raster layer ext.
QFlags< LayerOptionsFlag > LayerOptionsFlags
Definition: qgsprocessing.h:63
static const QgsSettingsEntryInteger * settingsDefaultOutputVectorLayerExt
Settings entry default output vector layer ext.
static const QgsSettingsEntryString * settingsTempPath
Settings entry temp path.
static const QString TEMPORARY_OUTPUT
Constant used to indicate that a Processing algorithm output should be a temporary layer/file.
@ SkipIndexGeneration
Do not generate index when creating a layer. Makes sense only for point cloud layers.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
Definition: qgsproject.h:107
QgsAnnotationLayer * mainAnnotationLayer()
Returns the main annotation layer associated with the project.
QVector< T > layers() const
Returns a list of registered map layers with a specified layer type.
Definition: qgsproject.h:1181
QgsCoordinateReferenceSystem crs
Definition: qgsproject.h:112
A store for object properties.
Definition: qgsproperty.h:228
QString asExpression() const
Returns an expression string representing the state of the property, or an empty string if the proper...
Qgis::PropertyType propertyType() const
Returns the property type.
QVariant value(const QgsExpressionContext &context, const QVariant &defaultValue=QVariant(), bool *ok=nullptr) const
Calculates the current value of the property, including any transforms which are set for the property...
static QgsProperty fromExpression(const QString &expression, bool isActive=true)
Returns a new ExpressionBasedProperty created from the specified expression.
static QgsProperty fromField(const QString &fieldName, bool isActive=true)
Returns a new FieldBasedProperty created from the specified field name.
static QgsProperty fromValue(const QVariant &value, bool isActive=true)
Returns a new StaticProperty created from the specified value.
Holds data provider key, description, and associated shared library file or function pointer informat...
QString key() const
This returns the unique key associated with the provider.
virtual QList< Qgis::LayerType > supportedLayerTypes() const
Returns a list of the map layer types supported by the provider.
virtual QVariantMap decodeUri(const QString &uri) const
Breaks a provider data source URI into its component paths (e.g.
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.
QList< QgsProviderRegistry::ProviderCandidateDetails > preferredProvidersForUri(const QString &uri) const
Returns the details for the preferred provider(s) for opening the specified uri.
QString encodeUri(const QString &providerKey, const QVariantMap &parts)
Reassembles a provider data source URI from its component paths (e.g.
QgsProviderMetadata * providerMetadata(const QString &providerKey) const
Returns metadata of the provider or nullptr if not found.
A simple feature sink which proxies feature addition on to another feature sink.
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a single feature to the sink.
QString lastError() const override
Returns the most recent error encountered by the sink, e.g.
QgsFeatureSink * destinationSink()
Returns the destination QgsFeatureSink which the proxy will forward features to.
bool addFeatures(QgsFeatureList &features, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a list of features to the sink.
static QStringList supportedFormatExtensions(RasterFormatOptions options=SortRecommended)
Returns a list of file extensions for supported formats.
Represents a raster layer.
A rectangle specified with double values.
Definition: qgsrectangle.h:42
double xMinimum() const
Returns the x minimum value (left side of rectangle).
Definition: qgsrectangle.h:201
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
Definition: qgsrectangle.h:211
double xMaximum() const
Returns the x maximum value (right side of rectangle).
Definition: qgsrectangle.h:196
double yMaximum() const
Returns the y maximum value (top side of rectangle).
Definition: qgsrectangle.h:206
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle.
Definition: qgsrectangle.h:413
QgsCoordinateReferenceSystem crs() const
Returns the associated coordinate reference system, or an invalid CRS if no reference system is set.
A QgsPointXY with associated coordinate reference system.
A QgsRectangle with associated coordinate reference system.
Defines the parameters used to remap features when creating a QgsRemappingProxyFeatureSink.
void setDestinationCrs(const QgsCoordinateReferenceSystem &destination)
Sets the destination crs used for reprojecting incoming features to the sink's destination CRS.
void setDestinationWkbType(Qgis::WkbType type)
Sets the WKB geometry type for the destination.
void setDestinationFields(const QgsFields &fields)
Sets the fields for the destination sink.
T value(const QString &dynamicKeyPart=QString()) const
Returns settings value.
Represents a map layer supporting display of tiled scene objects.
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
Options to pass to writeAsVectorFormat()
QString layerName
Layer name. If let empty, it will be derived from the filename.
QStringList layerOptions
List of OGR layer creation options.
Qgis::FeatureSymbologyExport symbologyExport
Symbology to export.
QgsVectorFileWriter::ActionOnExistingFile actionOnExistingFile
Action on existing file.
QStringList datasourceOptions
List of OGR data source creation options.
static QStringList defaultLayerOptions(const QString &driverName)
Returns a list of the default layer options for a specified driver.
static QString driverForExtension(const QString &extension)
Returns the OGR driver name for a specified file extension.
static QgsVectorFileWriter * create(const QString &fileName, const QgsFields &fields, Qgis::WkbType geometryType, const QgsCoordinateReferenceSystem &srs, const QgsCoordinateTransformContext &transformContext, const QgsVectorFileWriter::SaveVectorOptions &options, QgsFeatureSink::SinkFlags sinkFlags=QgsFeatureSink::SinkFlags(), QString *newFilename=nullptr, QString *newLayer=nullptr)
Create a new vector file writer.
static QStringList defaultDatasetOptions(const QString &driverName)
Returns a list of the default dataset options for a specified driver.
static QStringList supportedFormatExtensions(VectorFormatOptions options=SortRecommended)
Returns a list of file extensions for supported formats, e.g "shp", "gpkg".
@ CreateOrOverwriteFile
Create or overwrite file.
@ AppendToLayerNoNewFields
Append features to existing layer, but do not create new fields.
QgsFeatureSource subclass for the selected features from a QgsVectorLayer.
Represents a vector layer which manages a vector based data sets.
bool isSpatial() const FINAL
Returns true if this is a geometry layer and false in case of NoGeometry (table only) or UnknownGeome...
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
Q_INVOKABLE Qgis::WkbType wkbType() const FINAL
Returns the WKBType or WKBUnknown in case of error.
QString subsetString
QgsFeatureIterator getSelectedFeatures(QgsFeatureRequest request=QgsFeatureRequest()) const
Returns an iterator of the selected features.
Q_INVOKABLE Qgis::GeometryType geometryType() const
Returns point, line or polygon.
QgsRectangle extent() const FINAL
Returns the extent of the layer.
Implements a map layer that is dedicated to rendering of vector tiles.
Handles storage of information regarding WKB types and their properties.
Definition: qgswkbtypes.h:42
@ UnknownCount
Provider returned an unknown feature count.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into allowing algorithms to be written in pure substantial changes are required in order to port existing x Processing algorithms for QGIS x The most significant changes are outlined not GeoAlgorithm For algorithms which operate on features one by consider subclassing the QgsProcessingFeatureBasedAlgorithm class This class allows much of the boilerplate code for looping over features from a vector layer to be bypassed and instead requires implementation of a processFeature method Ensure that your algorithm(or algorithm 's parent class) implements the new pure virtual createInstance(self) call
bool qgsVariantLessThan(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether the first is less than the second.
Definition: qgis.cpp:120
bool qgsVariantGreaterThan(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether the first is greater than the second.
Definition: qgis.cpp:188
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
Definition: qgis.h:5124
QList< QgsFeature > QgsFeatureList
Definition: qgsfeature.h:917
QSet< QgsFeatureId > QgsFeatureIds
Definition: qgsfeatureid.h:37
QList< int > QgsAttributeList
Definition: qgsfield.h:27
QString convertToCompatibleFormatInternal(const QgsVectorLayer *vl, bool selectedFeaturesOnly, const QString &baseName, const QStringList &compatibleFormats, const QString &preferredFormat, QgsProcessingContext &context, QgsProcessingFeedback *feedback, QString *layerName, long long featureLimit, const QString &filterExpression)
const QgsCoordinateReferenceSystem & crs
Setting options for loading mesh layers.
Definition: qgsmeshlayer.h:109
bool skipCrsValidation
Controls whether the layer is allowed to have an invalid/unknown CRS.
Definition: qgsmeshlayer.h:143
Setting options for loading point cloud layers.
bool skipCrsValidation
Controls whether the layer is allowed to have an invalid/unknown CRS.
bool skipIndexGeneration
Set to true if point cloud index generation should be skipped.
Setting options for loading raster layers.
bool skipCrsValidation
Controls whether the layer is allowed to have an invalid/unknown CRS.
bool loadDefaultStyle
Sets to true if the default layer style should be loaded.
Setting options for loading tiled scene layers.
bool skipCrsValidation
Controls whether the layer is allowed to have an invalid/unknown CRS.
Setting options for loading vector layers.