QGIS API Documentation  3.16.0-Hannover (43b64b13f3)
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 "qgssettings.h"
21 #include "qgsexception.h"
22 #include "qgsprocessingcontext.h"
23 #include "qgsvectorlayerexporter.h"
24 #include "qgsvectorfilewriter.h"
25 #include "qgsmemoryproviderutils.h"
27 #include "qgsprocessingalgorithm.h"
30 #include "qgsfileutils.h"
31 #include "qgsvectorlayer.h"
32 #include "qgsproviderregistry.h"
33 #include "qgsmeshlayer.h"
34 #include "qgsreferencedgeometry.h"
35 #include "qgsrasterfilewriter.h"
36 #include "qgsvectortilelayer.h"
37 
38 QList<QgsRasterLayer *> QgsProcessingUtils::compatibleRasterLayers( QgsProject *project, bool sort )
39 {
40  if ( !project )
41  return QList<QgsRasterLayer *>();
42 
43  QList<QgsRasterLayer *> layers;
44 
45  const auto rasterLayers = project->layers<QgsRasterLayer *>();
46  for ( QgsRasterLayer *l : rasterLayers )
47  {
48  if ( canUseLayer( l ) )
49  layers << l;
50  }
51 
52  if ( sort )
53  {
54  std::sort( layers.begin(), layers.end(), []( const QgsRasterLayer * a, const QgsRasterLayer * b ) -> bool
55  {
56  return QString::localeAwareCompare( a->name(), b->name() ) < 0;
57  } );
58  }
59  return layers;
60 }
61 
62 QList<QgsVectorLayer *> QgsProcessingUtils::compatibleVectorLayers( QgsProject *project, const QList<int> &geometryTypes, bool sort )
63 {
64  if ( !project )
65  return QList<QgsVectorLayer *>();
66 
67  QList<QgsVectorLayer *> layers;
68  const auto vectorLayers = project->layers<QgsVectorLayer *>();
69  for ( QgsVectorLayer *l : vectorLayers )
70  {
71  if ( canUseLayer( l, geometryTypes ) )
72  layers << l;
73  }
74 
75  if ( sort )
76  {
77  std::sort( layers.begin(), layers.end(), []( const QgsVectorLayer * a, const QgsVectorLayer * b ) -> bool
78  {
79  return QString::localeAwareCompare( a->name(), b->name() ) < 0;
80  } );
81  }
82  return layers;
83 }
84 
85 QList<QgsMeshLayer *> QgsProcessingUtils::compatibleMeshLayers( QgsProject *project, bool sort )
86 {
87  if ( !project )
88  return QList<QgsMeshLayer *>();
89 
90  QList<QgsMeshLayer *> layers;
91  const auto meshLayers = project->layers<QgsMeshLayer *>();
92  for ( QgsMeshLayer *l : meshLayers )
93  {
94  if ( canUseLayer( l ) )
95  layers << l;
96  }
97 
98  if ( sort )
99  {
100  std::sort( layers.begin(), layers.end(), []( const QgsMeshLayer * a, const QgsMeshLayer * b ) -> bool
101  {
102  return QString::localeAwareCompare( a->name(), b->name() ) < 0;
103  } );
104  }
105  return layers;
106 }
107 
108 QList<QgsMapLayer *> QgsProcessingUtils::compatibleLayers( QgsProject *project, bool sort )
109 {
110  if ( !project )
111  return QList<QgsMapLayer *>();
112 
113  QList<QgsMapLayer *> layers;
114 
115  const auto rasterLayers = compatibleRasterLayers( project, false );
116  for ( QgsRasterLayer *rl : rasterLayers )
117  layers << rl;
118 
119  const auto vectorLayers = compatibleVectorLayers( project, QList< int >(), false );
120  for ( QgsVectorLayer *vl : vectorLayers )
121  layers << vl;
122 
123  const auto meshLayers = compatibleMeshLayers( project, false );
124  for ( QgsMeshLayer *vl : meshLayers )
125  layers << vl;
126 
127  if ( sort )
128  {
129  std::sort( layers.begin(), layers.end(), []( const QgsMapLayer * a, const QgsMapLayer * b ) -> bool
130  {
131  return QString::localeAwareCompare( a->name(), b->name() ) < 0;
132  } );
133  }
134  return layers;
135 }
136 
137 QString QgsProcessingUtils::encodeProviderKeyAndUri( const QString &providerKey, const QString &uri )
138 {
139  return QStringLiteral( "%1://%2" ).arg( providerKey, uri );
140 }
141 
142 bool QgsProcessingUtils::decodeProviderKeyAndUri( const QString &string, QString &providerKey, QString &uri )
143 {
144  QRegularExpression re( QStringLiteral( "^(\\w+?):\\/\\/(.+)$" ) );
145  const QRegularExpressionMatch match = re.match( string );
146  if ( !match.hasMatch() )
147  return false;
148 
149  providerKey = match.captured( 1 );
150  uri = match.captured( 2 );
151 
152  // double check that provider is valid
153  return QgsProviderRegistry::instance()->providerMetadata( providerKey );
154 }
155 
156 QgsMapLayer *QgsProcessingUtils::mapLayerFromStore( const QString &string, QgsMapLayerStore *store, QgsProcessingUtils::LayerHint typeHint )
157 {
158  if ( !store || string.isEmpty() )
159  return nullptr;
160 
161  QList< QgsMapLayer * > layers = store->mapLayers().values();
162 
163  layers.erase( std::remove_if( layers.begin(), layers.end(), []( QgsMapLayer * layer )
164  {
165  switch ( layer->type() )
166  {
167  case QgsMapLayerType::VectorLayer:
168  return !canUseLayer( qobject_cast< QgsVectorLayer * >( layer ) );
169  case QgsMapLayerType::RasterLayer:
170  return !canUseLayer( qobject_cast< QgsRasterLayer * >( layer ) );
171  case QgsMapLayerType::PluginLayer:
172  return true;
173  case QgsMapLayerType::MeshLayer:
174  return !canUseLayer( qobject_cast< QgsMeshLayer * >( layer ) );
175  case QgsMapLayerType::VectorTileLayer:
176  return !canUseLayer( qobject_cast< QgsVectorTileLayer * >( layer ) );
177  case QgsMapLayerType::AnnotationLayer:
178  return true;
179  }
180  return true;
181  } ), layers.end() );
182 
183  auto isCompatibleType = [typeHint]( QgsMapLayer * l ) -> bool
184  {
185  switch ( typeHint )
186  {
187  case LayerHint::UnknownType:
188  return true;
189 
190  case LayerHint::Vector:
191  return l->type() == QgsMapLayerType::VectorLayer;
192 
193  case LayerHint::Raster:
194  return l->type() == QgsMapLayerType::RasterLayer;
195 
196  case LayerHint::Mesh:
197  return l->type() == QgsMapLayerType::MeshLayer;
198  }
199  return true;
200  };
201 
202  for ( QgsMapLayer *l : qgis::as_const( layers ) )
203  {
204  if ( isCompatibleType( l ) && l->id() == string )
205  return l;
206  }
207  for ( QgsMapLayer *l : qgis::as_const( layers ) )
208  {
209  if ( isCompatibleType( l ) && l->name() == string )
210  return l;
211  }
212  for ( QgsMapLayer *l : qgis::as_const( layers ) )
213  {
214  if ( isCompatibleType( l ) && normalizeLayerSource( l->source() ) == normalizeLayerSource( string ) )
215  return l;
216  }
217  return nullptr;
218 }
219 
220 QgsMapLayer *QgsProcessingUtils::loadMapLayerFromString( const QString &string, const QgsCoordinateTransformContext &transformContext, LayerHint typeHint )
221 {
222  QString provider;
223  QString uri;
224  const bool useProvider = decodeProviderKeyAndUri( string, provider, uri );
225  if ( !useProvider )
226  uri = string;
227 
228  QString name;
229  // for disk based sources, we use the filename to determine a layer name
230  if ( !useProvider || ( provider == QLatin1String( "ogr" ) || provider == QLatin1String( "gdal" ) || provider == QLatin1String( "mdal" ) ) )
231  {
232  QStringList components = uri.split( '|' );
233  if ( components.isEmpty() )
234  return nullptr;
235 
236  QFileInfo fi;
237  if ( QFileInfo::exists( uri ) )
238  fi = QFileInfo( uri );
239  else if ( QFileInfo::exists( components.at( 0 ) ) )
240  fi = QFileInfo( components.at( 0 ) );
241  else
242  return nullptr;
243  name = fi.baseName();
244  }
245  else
246  {
247  name = QgsDataSourceUri( uri ).table();
248  }
249 
250  // brute force attempt to load a matching layer
251  if ( typeHint == LayerHint::UnknownType || typeHint == LayerHint::Vector )
252  {
253  QgsVectorLayer::LayerOptions options { transformContext };
254  options.loadDefaultStyle = false;
255  options.skipCrsValidation = true;
256 
257  std::unique_ptr< QgsVectorLayer > layer;
258  if ( useProvider )
259  {
260  layer = qgis::make_unique<QgsVectorLayer>( uri, name, provider, options );
261  }
262  else
263  {
264  // fallback to ogr
265  layer = qgis::make_unique<QgsVectorLayer>( uri, name, QStringLiteral( "ogr" ), options );
266  }
267  if ( layer->isValid() )
268  {
269  return layer.release();
270  }
271  }
272  if ( typeHint == LayerHint::UnknownType || typeHint == LayerHint::Raster )
273  {
274  QgsRasterLayer::LayerOptions rasterOptions;
275  rasterOptions.loadDefaultStyle = false;
276  rasterOptions.skipCrsValidation = true;
277 
278  std::unique_ptr< QgsRasterLayer > rasterLayer;
279  if ( useProvider )
280  {
281  rasterLayer = qgis::make_unique< QgsRasterLayer >( uri, name, provider, rasterOptions );
282  }
283  else
284  {
285  // fallback to gdal
286  rasterLayer = qgis::make_unique< QgsRasterLayer >( uri, name, QStringLiteral( "gdal" ), rasterOptions );
287  }
288 
289  if ( rasterLayer->isValid() )
290  {
291  return rasterLayer.release();
292  }
293  }
294  if ( typeHint == LayerHint::UnknownType || typeHint == LayerHint::Mesh )
295  {
296  QgsMeshLayer::LayerOptions meshOptions;
297  meshOptions.skipCrsValidation = true;
298 
299  std::unique_ptr< QgsMeshLayer > meshLayer;
300  if ( useProvider )
301  {
302  meshLayer = qgis::make_unique< QgsMeshLayer >( uri, name, provider, meshOptions );
303  }
304  else
305  {
306  meshLayer = qgis::make_unique< QgsMeshLayer >( uri, name, QStringLiteral( "mdal" ), meshOptions );
307  }
308  if ( meshLayer->isValid() )
309  {
310  return meshLayer.release();
311  }
312  }
313  return nullptr;
314 }
315 
316 QgsMapLayer *QgsProcessingUtils::mapLayerFromString( const QString &string, QgsProcessingContext &context, bool allowLoadingNewLayers, LayerHint typeHint )
317 {
318  if ( string.isEmpty() )
319  return nullptr;
320 
321  // prefer project layers
322  QgsMapLayer *layer = nullptr;
323  if ( auto *lProject = context.project() )
324  {
325  QgsMapLayer *layer = mapLayerFromStore( string, lProject->layerStore(), typeHint );
326  if ( layer )
327  return layer;
328  }
329 
330  layer = mapLayerFromStore( string, context.temporaryLayerStore(), typeHint );
331  if ( layer )
332  return layer;
333 
334  if ( !allowLoadingNewLayers )
335  return nullptr;
336 
337  layer = loadMapLayerFromString( string, context.transformContext(), typeHint );
338  if ( layer )
339  {
340  context.temporaryLayerStore()->addMapLayer( layer );
341  return layer;
342  }
343  else
344  {
345  return nullptr;
346  }
347 }
348 
349 QgsProcessingFeatureSource *QgsProcessingUtils::variantToSource( const QVariant &value, QgsProcessingContext &context, const QVariant &fallbackValue )
350 {
351  QVariant val = value;
352  bool selectedFeaturesOnly = false;
353  long long featureLimit = -1;
354  bool overrideGeometryCheck = false;
356  if ( val.canConvert<QgsProcessingFeatureSourceDefinition>() )
357  {
358  // input is a QgsProcessingFeatureSourceDefinition - get extra properties from it
359  QgsProcessingFeatureSourceDefinition fromVar = qvariant_cast<QgsProcessingFeatureSourceDefinition>( val );
360  selectedFeaturesOnly = fromVar.selectedFeaturesOnly;
361  featureLimit = fromVar.featureLimit;
362  val = fromVar.source;
363  overrideGeometryCheck = fromVar.flags & QgsProcessingFeatureSourceDefinition::Flag::FlagOverrideDefaultGeometryCheck;
364  geometryCheck = fromVar.geometryCheck;
365  }
366  else if ( val.canConvert<QgsProcessingOutputLayerDefinition>() )
367  {
368  // input is a QgsProcessingOutputLayerDefinition (e.g. an output from earlier in a model) - get extra properties from it
369  QgsProcessingOutputLayerDefinition fromVar = qvariant_cast<QgsProcessingOutputLayerDefinition>( val );
370  val = fromVar.sink;
371  }
372 
373  if ( QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( qvariant_cast<QObject *>( val ) ) )
374  {
375  std::unique_ptr< QgsProcessingFeatureSource> source = qgis::make_unique< QgsProcessingFeatureSource >( layer, context, false, featureLimit );
376  if ( overrideGeometryCheck )
377  source->setInvalidGeometryCheck( geometryCheck );
378  return source.release();
379  }
380 
381  QString layerRef;
382  if ( val.canConvert<QgsProperty>() )
383  {
384  layerRef = val.value< QgsProperty >().valueAsString( context.expressionContext(), fallbackValue.toString() );
385  }
386  else if ( !val.isValid() || val.toString().isEmpty() )
387  {
388  // fall back to default
389  if ( QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( qvariant_cast<QObject *>( fallbackValue ) ) )
390  {
391  std::unique_ptr< QgsProcessingFeatureSource> source = qgis::make_unique< QgsProcessingFeatureSource >( layer, context, false, featureLimit );
392  if ( overrideGeometryCheck )
393  source->setInvalidGeometryCheck( geometryCheck );
394  return source.release();
395  }
396 
397  layerRef = fallbackValue.toString();
398  }
399  else
400  {
401  layerRef = val.toString();
402  }
403 
404  if ( layerRef.isEmpty() )
405  return nullptr;
406 
407  QgsVectorLayer *vl = qobject_cast< QgsVectorLayer *>( QgsProcessingUtils::mapLayerFromString( layerRef, context, true, LayerHint::Vector ) );
408  if ( !vl )
409  return nullptr;
410 
411  std::unique_ptr< QgsProcessingFeatureSource> source;
412  if ( selectedFeaturesOnly )
413  {
414  source = qgis::make_unique< QgsProcessingFeatureSource>( new QgsVectorLayerSelectedFeatureSource( vl ), context, true, featureLimit );
415  }
416  else
417  {
418  source = qgis::make_unique< QgsProcessingFeatureSource >( vl, context, false, featureLimit );
419  }
420 
421  if ( overrideGeometryCheck )
422  source->setInvalidGeometryCheck( geometryCheck );
423  return source.release();
424 }
425 
426 QgsCoordinateReferenceSystem QgsProcessingUtils::variantToCrs( const QVariant &value, QgsProcessingContext &context, const QVariant &fallbackValue )
427 {
428  QVariant val = value;
429 
430  if ( val.canConvert<QgsCoordinateReferenceSystem>() )
431  {
432  // input is a QgsCoordinateReferenceSystem - done!
433  return val.value< QgsCoordinateReferenceSystem >();
434  }
435  else if ( val.canConvert<QgsProcessingFeatureSourceDefinition>() )
436  {
437  // input is a QgsProcessingFeatureSourceDefinition - get extra properties from it
438  QgsProcessingFeatureSourceDefinition fromVar = qvariant_cast<QgsProcessingFeatureSourceDefinition>( val );
439  val = fromVar.source;
440  }
441  else if ( val.canConvert<QgsProcessingOutputLayerDefinition>() )
442  {
443  // input is a QgsProcessingOutputLayerDefinition - get extra properties from it
444  QgsProcessingOutputLayerDefinition fromVar = qvariant_cast<QgsProcessingOutputLayerDefinition>( val );
445  val = fromVar.sink;
446  }
447 
448  if ( val.canConvert<QgsProperty>() && val.value< QgsProperty >().propertyType() == QgsProperty::StaticProperty )
449  {
450  val = val.value< QgsProperty >().staticValue();
451  }
452 
453  // maybe a map layer
454  if ( QgsMapLayer *layer = qobject_cast< QgsMapLayer * >( qvariant_cast<QObject *>( val ) ) )
455  return layer->crs();
456 
457  if ( val.canConvert<QgsProperty>() )
458  val = val.value< QgsProperty >().valueAsString( context.expressionContext(), fallbackValue.toString() );
459 
460  if ( !val.isValid() )
461  {
462  // fall back to default
463  val = fallbackValue;
464  }
465 
466  QString crsText = val.toString();
467  if ( crsText.isEmpty() )
468  crsText = fallbackValue.toString();
469 
470  if ( crsText.isEmpty() )
472 
473  // maybe special string
474  if ( context.project() && crsText.compare( QLatin1String( "ProjectCrs" ), Qt::CaseInsensitive ) == 0 )
475  return context.project()->crs();
476 
477  // maybe a map layer reference
478  if ( QgsMapLayer *layer = QgsProcessingUtils::mapLayerFromString( crsText, context ) )
479  return layer->crs();
480 
481  // else CRS from string
483  crs.createFromString( crsText );
484  return crs;
485 }
486 
487 bool QgsProcessingUtils::canUseLayer( const QgsMeshLayer *layer )
488 {
489  return layer && layer->dataProvider();
490 }
491 
492 bool QgsProcessingUtils::canUseLayer( const QgsVectorTileLayer *layer )
493 {
494  return layer && layer->isValid();
495 }
496 
497 bool QgsProcessingUtils::canUseLayer( const QgsRasterLayer *layer )
498 {
499  return layer && layer->isValid();
500 }
501 
502 bool QgsProcessingUtils::canUseLayer( const QgsVectorLayer *layer, const QList<int> &sourceTypes )
503 {
504  return layer && layer->isValid() &&
505  ( sourceTypes.isEmpty()
506  || ( sourceTypes.contains( QgsProcessing::TypeVectorPoint ) && layer->geometryType() == QgsWkbTypes::PointGeometry )
507  || ( sourceTypes.contains( QgsProcessing::TypeVectorLine ) && layer->geometryType() == QgsWkbTypes::LineGeometry )
508  || ( sourceTypes.contains( QgsProcessing::TypeVectorPolygon ) && layer->geometryType() == QgsWkbTypes::PolygonGeometry )
509  || ( sourceTypes.contains( QgsProcessing::TypeVectorAnyGeometry ) && layer->isSpatial() )
510  || sourceTypes.contains( QgsProcessing::TypeVector )
511  );
512 }
513 
514 QString QgsProcessingUtils::normalizeLayerSource( const QString &source )
515 {
516  QString normalized = source;
517  normalized.replace( '\\', '/' );
518  return normalized.trimmed();
519 }
520 
521 QString QgsProcessingUtils::variantToPythonLiteral( const QVariant &value )
522 {
523  if ( !value.isValid() )
524  return QStringLiteral( "None" );
525 
526  if ( value.canConvert<QgsProperty>() )
527  return QStringLiteral( "QgsProperty.fromExpression('%1')" ).arg( value.value< QgsProperty >().asExpression() );
528  else if ( value.canConvert<QgsCoordinateReferenceSystem>() )
529  {
530  if ( !value.value< QgsCoordinateReferenceSystem >().isValid() )
531  return QStringLiteral( "QgsCoordinateReferenceSystem()" );
532  else
533  return QStringLiteral( "QgsCoordinateReferenceSystem('%1')" ).arg( value.value< QgsCoordinateReferenceSystem >().authid() );
534  }
535  else if ( value.canConvert< QgsRectangle >() )
536  {
537  QgsRectangle r = value.value<QgsRectangle>();
538  return QStringLiteral( "'%1, %3, %2, %4'" ).arg( qgsDoubleToString( r.xMinimum() ),
541  qgsDoubleToString( r.yMaximum() ) );
542  }
543  else if ( value.canConvert< QgsReferencedRectangle >() )
544  {
546  return QStringLiteral( "'%1, %3, %2, %4 [%5]'" ).arg( qgsDoubleToString( r.xMinimum() ),
549  qgsDoubleToString( r.yMaximum() ), r.crs().authid() );
550  }
551  else if ( value.canConvert< QgsPointXY >() )
552  {
553  QgsPointXY r = value.value<QgsPointXY>();
554  return QStringLiteral( "'%1,%2'" ).arg( qgsDoubleToString( r.x() ),
555  qgsDoubleToString( r.y() ) );
556  }
557  else if ( value.canConvert< QgsReferencedPointXY >() )
558  {
559  QgsReferencedPointXY r = value.value<QgsReferencedPointXY>();
560  return QStringLiteral( "'%1,%2 [%3]'" ).arg( qgsDoubleToString( r.x() ),
561  qgsDoubleToString( r.y() ),
562  r.crs().authid() );
563  }
564 
565  switch ( value.type() )
566  {
567  case QVariant::Bool:
568  return value.toBool() ? QStringLiteral( "True" ) : QStringLiteral( "False" );
569 
570  case QVariant::Double:
571  return QString::number( value.toDouble() );
572 
573  case QVariant::Int:
574  case QVariant::UInt:
575  return QString::number( value.toInt() );
576 
577  case QVariant::LongLong:
578  case QVariant::ULongLong:
579  return QString::number( value.toLongLong() );
580 
581  case QVariant::List:
582  {
583  QStringList parts;
584  const QVariantList vl = value.toList();
585  for ( const QVariant &v : vl )
586  {
587  parts << variantToPythonLiteral( v );
588  }
589  return parts.join( ',' ).prepend( '[' ).append( ']' );
590  }
591 
592  case QVariant::Map:
593  {
594  const QVariantMap map = value.toMap();
595  QStringList parts;
596  parts.reserve( map.size() );
597  for ( auto it = map.constBegin(); it != map.constEnd(); ++it )
598  {
599  parts << QStringLiteral( "%1: %2" ).arg( stringToPythonLiteral( it.key() ), variantToPythonLiteral( it.value() ) );
600  }
601  return parts.join( ',' ).prepend( '{' ).append( '}' );
602  }
603 
604  default:
605  break;
606  }
607 
608  return QgsProcessingUtils::stringToPythonLiteral( value.toString() );
609 }
610 
611 QString QgsProcessingUtils::stringToPythonLiteral( const QString &string )
612 {
613  QString s = string;
614  s.replace( '\\', QLatin1String( "\\\\" ) );
615  s.replace( '\n', QLatin1String( "\\n" ) );
616  s.replace( '\r', QLatin1String( "\\r" ) );
617  s.replace( '\t', QLatin1String( "\\t" ) );
618  s.replace( '"', QLatin1String( "\\\"" ) );
619  s.replace( '\'', QLatin1String( "\\\'" ) );
620  s = s.prepend( '\'' ).append( '\'' );
621  return s;
622 }
623 
624 void QgsProcessingUtils::parseDestinationString( QString &destination, QString &providerKey, QString &uri, QString &layerName, QString &format, QMap<QString, QVariant> &options, bool &useWriter, QString &extension )
625 {
626  extension.clear();
627  bool matched = decodeProviderKeyAndUri( destination, providerKey, uri );
628 
629  if ( !matched )
630  {
631  QRegularExpression splitRx( QStringLiteral( "^(.{3,}?):(.*)$" ) );
632  QRegularExpressionMatch match = splitRx.match( destination );
633  if ( match.hasMatch() )
634  {
635  providerKey = match.captured( 1 );
636  uri = match.captured( 2 );
637  matched = true;
638  }
639  }
640 
641  if ( matched )
642  {
643  if ( providerKey == QLatin1String( "postgis" ) ) // older processing used "postgis" instead of "postgres"
644  {
645  providerKey = QStringLiteral( "postgres" );
646  }
647  if ( providerKey == QLatin1String( "ogr" ) )
648  {
649  QgsDataSourceUri dsUri( uri );
650  if ( !dsUri.database().isEmpty() )
651  {
652  if ( !dsUri.table().isEmpty() )
653  {
654  layerName = dsUri.table();
655  options.insert( QStringLiteral( "layerName" ), layerName );
656  }
657  uri = dsUri.database();
658  extension = QFileInfo( uri ).completeSuffix();
659  format = QgsVectorFileWriter::driverForExtension( extension );
660  options.insert( QStringLiteral( "driverName" ), format );
661  }
662  else
663  {
664  extension = QFileInfo( uri ).completeSuffix();
665  options.insert( QStringLiteral( "driverName" ), QgsVectorFileWriter::driverForExtension( extension ) );
666  }
667  options.insert( QStringLiteral( "update" ), true );
668  }
669  useWriter = false;
670  }
671  else
672  {
673  useWriter = true;
674  providerKey = QStringLiteral( "ogr" );
675 
676  QRegularExpression splitRx( QStringLiteral( "^(.*)\\.(.*?)$" ) );
677  QRegularExpressionMatch match = splitRx.match( destination );
678  if ( match.hasMatch() )
679  {
680  extension = match.captured( 2 );
681  format = QgsVectorFileWriter::driverForExtension( extension );
682  }
683 
684  if ( format.isEmpty() )
685  {
686  format = QStringLiteral( "GPKG" );
687  destination = destination + QStringLiteral( ".gpkg" );
688  }
689 
690  options.insert( QStringLiteral( "driverName" ), format );
691  uri = destination;
692  }
693 }
694 
695 QgsFeatureSink *QgsProcessingUtils::createFeatureSink( QString &destination, QgsProcessingContext &context, const QgsFields &fields, QgsWkbTypes::Type geometryType, const QgsCoordinateReferenceSystem &crs, const QVariantMap &createOptions, const QStringList &datasourceOptions, const QStringList &layerOptions, QgsFeatureSink::SinkFlags sinkFlags, QgsRemappingSinkDefinition *remappingDefinition )
696 {
697  QVariantMap options = createOptions;
698  if ( !options.contains( QStringLiteral( "fileEncoding" ) ) )
699  {
700  // no destination encoding specified, use default
701  options.insert( QStringLiteral( "fileEncoding" ), context.defaultEncoding().isEmpty() ? QStringLiteral( "system" ) : context.defaultEncoding() );
702  }
703 
704  if ( destination.isEmpty() || destination.startsWith( QLatin1String( "memory:" ) ) )
705  {
706  // strip "memory:" from start of destination
707  if ( destination.startsWith( QLatin1String( "memory:" ) ) )
708  destination = destination.mid( 7 );
709 
710  if ( destination.isEmpty() )
711  destination = QStringLiteral( "output" );
712 
713  // memory provider cannot be used with QgsVectorLayerImport - so create layer manually
714  std::unique_ptr< QgsVectorLayer > layer( QgsMemoryProviderUtils::createMemoryLayer( destination, fields, geometryType, crs ) );
715  if ( !layer || !layer->isValid() )
716  {
717  throw QgsProcessingException( QObject::tr( "Could not create memory layer" ) );
718  }
719 
720  layer->setCustomProperty( QStringLiteral( "OnConvertFormatRegeneratePrimaryKey" ), static_cast< bool >( sinkFlags & QgsFeatureSink::RegeneratePrimaryKey ) );
721 
722  // update destination to layer ID
723  destination = layer->id();
724 
725  // this is a factory, so we need to return a proxy
726  std::unique_ptr< QgsProcessingFeatureSink > sink( new QgsProcessingFeatureSink( layer->dataProvider(), destination, context ) );
727  context.temporaryLayerStore()->addMapLayer( layer.release() );
728 
729  return sink.release();
730  }
731  else
732  {
733  QString providerKey;
734  QString uri;
735  QString layerName;
736  QString format;
737  QString extension;
738  bool useWriter = false;
739  parseDestinationString( destination, providerKey, uri, layerName, format, options, useWriter, extension );
740 
741  QgsFields newFields = fields;
742  if ( useWriter && providerKey == QLatin1String( "ogr" ) )
743  {
744  // use QgsVectorFileWriter for OGR destinations instead of QgsVectorLayerImport, as that allows
745  // us to use any OGR format which supports feature addition
746  QString finalFileName;
747  QString finalLayerName;
749  saveOptions.fileEncoding = options.value( QStringLiteral( "fileEncoding" ) ).toString();
750  saveOptions.layerName = !layerName.isEmpty() ? layerName : options.value( QStringLiteral( "layerName" ) ).toString();
751  saveOptions.driverName = format;
752  saveOptions.datasourceOptions = !datasourceOptions.isEmpty() ? datasourceOptions : QgsVectorFileWriter::defaultDatasetOptions( format );
753  saveOptions.layerOptions = !layerOptions.isEmpty() ? layerOptions : QgsVectorFileWriter::defaultLayerOptions( format );
755  if ( remappingDefinition )
756  {
758  // sniff destination file to get correct wkb type and crs
759  std::unique_ptr< QgsVectorLayer > vl = qgis::make_unique< QgsVectorLayer >( destination );
760  if ( vl->isValid() )
761  {
762  remappingDefinition->setDestinationWkbType( vl->wkbType() );
763  remappingDefinition->setDestinationCrs( vl->crs() );
764  newFields = vl->fields();
765  remappingDefinition->setDestinationFields( newFields );
766  }
767  context.expressionContext().setFields( fields );
768  }
769  else
770  {
772  }
773  std::unique_ptr< QgsVectorFileWriter > writer( QgsVectorFileWriter::create( destination, newFields, geometryType, crs, context.transformContext(), saveOptions, sinkFlags, &finalFileName, &finalLayerName ) );
774  if ( writer->hasError() )
775  {
776  throw QgsProcessingException( QObject::tr( "Could not create layer %1: %2" ).arg( destination, writer->errorMessage() ) );
777  }
778  destination = finalFileName;
779  if ( !saveOptions.layerName.isEmpty() && !finalLayerName.isEmpty() )
780  destination += QStringLiteral( "|layername=%1" ).arg( finalLayerName );
781 
782  if ( remappingDefinition )
783  {
784  std::unique_ptr< QgsRemappingProxyFeatureSink > remapSink = qgis::make_unique< QgsRemappingProxyFeatureSink >( *remappingDefinition, writer.release(), true );
785  remapSink->setExpressionContext( context.expressionContext() );
786  remapSink->setTransformContext( context.transformContext() );
787  return new QgsProcessingFeatureSink( remapSink.release(), destination, context, true );
788  }
789  else
790  return new QgsProcessingFeatureSink( writer.release(), destination, context, true );
791  }
792  else
793  {
794  const QgsVectorLayer::LayerOptions layerOptions { context.transformContext() };
795  if ( remappingDefinition )
796  {
797  //write to existing layer
798 
799  // use destination string as layer name (eg "postgis:..." )
800  if ( !layerName.isEmpty() )
801  {
802  QVariantMap parts = QgsProviderRegistry::instance()->decodeUri( providerKey, uri );
803  parts.insert( QStringLiteral( "layerName" ), layerName );
804  uri = QgsProviderRegistry::instance()->encodeUri( providerKey, parts );
805  }
806 
807  std::unique_ptr< QgsVectorLayer > layer = qgis::make_unique<QgsVectorLayer>( uri, destination, providerKey, layerOptions );
808  // update destination to layer ID
809  destination = layer->id();
810  if ( layer->isValid() )
811  {
812  remappingDefinition->setDestinationWkbType( layer->wkbType() );
813  remappingDefinition->setDestinationCrs( layer->crs() );
814  remappingDefinition->setDestinationFields( layer->fields() );
815  }
816 
817  std::unique_ptr< QgsRemappingProxyFeatureSink > remapSink = qgis::make_unique< QgsRemappingProxyFeatureSink >( *remappingDefinition, layer->dataProvider(), false );
818  context.temporaryLayerStore()->addMapLayer( layer.release() );
819  remapSink->setExpressionContext( context.expressionContext() );
820  remapSink->setTransformContext( context.transformContext() );
821  context.expressionContext().setFields( fields );
822  return new QgsProcessingFeatureSink( remapSink.release(), destination, context, true );
823  }
824  else
825  {
826  //create empty layer
827  std::unique_ptr< QgsVectorLayerExporter > exporter = qgis::make_unique<QgsVectorLayerExporter>( uri, providerKey, newFields, geometryType, crs, true, options, sinkFlags );
828  if ( exporter->errorCode() )
829  {
830  throw QgsProcessingException( QObject::tr( "Could not create layer %1: %2" ).arg( destination, exporter->errorMessage() ) );
831  }
832 
833  // use destination string as layer name (eg "postgis:..." )
834  if ( !layerName.isEmpty() )
835  uri += QStringLiteral( "|layername=%1" ).arg( layerName );
836  // update destination to generated URI
837  destination = uri;
838 
839  return new QgsProcessingFeatureSink( exporter.release(), destination, context, true );
840  }
841  }
842  }
843 }
844 
845 void QgsProcessingUtils::createFeatureSinkPython( QgsFeatureSink **sink, QString &destination, QgsProcessingContext &context, const QgsFields &fields, QgsWkbTypes::Type geometryType, const QgsCoordinateReferenceSystem &crs, const QVariantMap &options )
846 {
847  *sink = createFeatureSink( destination, context, fields, geometryType, crs, options );
848 }
849 
850 
852 {
853  QgsRectangle extent;
854  for ( const QgsMapLayer *layer : layers )
855  {
856  if ( !layer )
857  continue;
858 
859  if ( crs.isValid() )
860  {
861  //transform layer extent to target CRS
862  QgsCoordinateTransform ct( layer->crs(), crs, context.transformContext() );
863  try
864  {
865  QgsRectangle reprojExtent = ct.transformBoundingBox( layer->extent() );
866  extent.combineExtentWith( reprojExtent );
867  }
868  catch ( QgsCsException & )
869  {
870  // can't reproject... what to do here? hmmm?
871  // let's ignore this layer for now, but maybe we should just use the original extent?
872  }
873  }
874  else
875  {
876  extent.combineExtentWith( layer->extent() );
877  }
878 
879  }
880  return extent;
881 }
882 
883 // Deprecated
885 {
886  QgsProcessingContext context;
887  return QgsProcessingUtils::combineLayerExtents( layers, crs, context );
888 }
889 
890 QVariant QgsProcessingUtils::generateIteratingDestination( const QVariant &input, const QVariant &id, QgsProcessingContext &context )
891 {
892  if ( !input.isValid() )
893  return QStringLiteral( "memory:%1" ).arg( id.toString() );
894 
895  if ( input.canConvert<QgsProcessingOutputLayerDefinition>() )
896  {
897  QgsProcessingOutputLayerDefinition fromVar = qvariant_cast<QgsProcessingOutputLayerDefinition>( input );
898  QVariant newSink = generateIteratingDestination( fromVar.sink, id, context );
899  fromVar.sink = QgsProperty::fromValue( newSink );
900  return fromVar;
901  }
902  else if ( input.canConvert<QgsProperty>() )
903  {
904  QString res = input.value< QgsProperty>().valueAsString( context.expressionContext() );
905  return generateIteratingDestination( res, id, context );
906  }
907  else
908  {
909  QString res = input.toString();
910  if ( res == QgsProcessing::TEMPORARY_OUTPUT )
911  {
912  // temporary outputs map to temporary outputs!
914  }
915  else if ( res.startsWith( QLatin1String( "memory:" ) ) )
916  {
917  return QString( res + '_' + id.toString() );
918  }
919  else
920  {
921  // assume a filename type output for now
922  // TODO - uris?
923  int lastIndex = res.lastIndexOf( '.' );
924  return QString( res.left( lastIndex ) + '_' + id.toString() + res.mid( lastIndex ) );
925  }
926  }
927 }
928 
930 {
931  // we maintain a list of temporary folders -- this allows us to append additional
932  // folders when a setting change causes the base temp folder to change, while deferring
933  // cleanup of ALL these temp folders until session end (we can't cleanup older folders immediately,
934  // because we don't know whether they have data in them which is still wanted)
935  static std::vector< std::unique_ptr< QTemporaryDir > > sTempFolders;
936  static QString sFolder;
937  static QMutex sMutex;
938  QMutexLocker locker( &sMutex );
939  const QString basePath = QgsSettings().value( QStringLiteral( "Processing/Configuration/TEMP_PATH2" ) ).toString();
940  if ( basePath.isEmpty() )
941  {
942  // default setting -- automatically create a temp folder
943  if ( sTempFolders.empty() )
944  {
945  const QString templatePath = QStringLiteral( "%1/processing_XXXXXX" ).arg( QDir::tempPath() );
946  std::unique_ptr< QTemporaryDir > tempFolder = qgis::make_unique< QTemporaryDir >( templatePath );
947  sFolder = tempFolder->path();
948  sTempFolders.emplace_back( std::move( tempFolder ) );
949  }
950  }
951  else if ( sFolder.isEmpty() || !sFolder.startsWith( basePath ) || sTempFolders.empty() )
952  {
953  if ( !QDir().exists( basePath ) )
954  QDir().mkpath( basePath );
955 
956  const QString templatePath = QStringLiteral( "%1/processing_XXXXXX" ).arg( basePath );
957  std::unique_ptr< QTemporaryDir > tempFolder = qgis::make_unique< QTemporaryDir >( templatePath );
958  sFolder = tempFolder->path();
959  sTempFolders.emplace_back( std::move( tempFolder ) );
960  }
961  return sFolder;
962 }
963 
964 QString QgsProcessingUtils::generateTempFilename( const QString &basename )
965 {
966  QString subPath = QUuid::createUuid().toString().remove( '-' ).remove( '{' ).remove( '}' );
967  QString path = tempFolder() + '/' + subPath;
968  if ( !QDir( path ).exists() ) //make sure the directory exists - it shouldn't, but lets be safe...
969  {
970  QDir tmpDir;
971  tmpDir.mkdir( path );
972  }
973  return path + '/' + QgsFileUtils::stringToSafeFilename( basename );
974 }
975 
977 {
978  auto getText = [map]( const QString & key )->QString
979  {
980  if ( map.contains( key ) )
981  return map.value( key ).toString();
982  return QString();
983  };
984 
985  QString s = QObject::tr( "<html><body><h2>Algorithm description</h2>\n" );
986  s += QStringLiteral( "<p>" ) + getText( QStringLiteral( "ALG_DESC" ) ) + QStringLiteral( "</p>\n" );
987 
988  QString inputs;
989 
990  const auto parameterDefinitions = algorithm->parameterDefinitions();
991  for ( const QgsProcessingParameterDefinition *def : parameterDefinitions )
992  {
993  inputs += QStringLiteral( "<h3>" ) + def->description() + QStringLiteral( "</h3>\n" );
994  inputs += QStringLiteral( "<p>" ) + getText( def->name() ) + QStringLiteral( "</p>\n" );
995  }
996  if ( !inputs.isEmpty() )
997  s += QObject::tr( "<h2>Input parameters</h2>\n" ) + inputs;
998 
999  QString outputs;
1000  const auto outputDefinitions = algorithm->outputDefinitions();
1001  for ( const QgsProcessingOutputDefinition *def : outputDefinitions )
1002  {
1003  outputs += QStringLiteral( "<h3>" ) + def->description() + QStringLiteral( "</h3>\n" );
1004  outputs += QStringLiteral( "<p>" ) + getText( def->name() ) + QStringLiteral( "</p>\n" );
1005  }
1006  if ( !outputs.isEmpty() )
1007  s += QObject::tr( "<h2>Outputs</h2>\n" ) + outputs;
1008 
1009  s += QLatin1String( "<br>" );
1010  if ( !map.value( QStringLiteral( "ALG_CREATOR" ) ).toString().isEmpty() )
1011  s += QObject::tr( "<p align=\"right\">Algorithm author: %1</p>" ).arg( getText( QStringLiteral( "ALG_CREATOR" ) ) );
1012  if ( !map.value( QStringLiteral( "ALG_HELP_CREATOR" ) ).toString().isEmpty() )
1013  s += QObject::tr( "<p align=\"right\">Help author: %1</p>" ).arg( getText( QStringLiteral( "ALG_HELP_CREATOR" ) ) );
1014  if ( !map.value( QStringLiteral( "ALG_VERSION" ) ).toString().isEmpty() )
1015  s += QObject::tr( "<p align=\"right\">Algorithm version: %1</p>" ).arg( getText( QStringLiteral( "ALG_VERSION" ) ) );
1016 
1017  s += QLatin1String( "</body></html>" );
1018  return s;
1019 }
1020 
1021 QString convertToCompatibleFormatInternal( const QgsVectorLayer *vl, bool selectedFeaturesOnly, const QString &baseName, const QStringList &compatibleFormats, const QString &preferredFormat, QgsProcessingContext &context, QgsProcessingFeedback *feedback, QString *layerName,
1022  long long featureLimit )
1023 {
1024  bool requiresTranslation = false;
1025 
1026  // if we are only looking for selected features then we have to export back to disk,
1027  // as we need to subset only selected features, a concept which doesn't exist outside QGIS!
1028  requiresTranslation = requiresTranslation || selectedFeaturesOnly;
1029 
1030  // if we are limiting the feature count, we better export
1031  requiresTranslation = requiresTranslation || featureLimit != -1;
1032 
1033  // if the data provider is NOT ogr, then we HAVE to convert. Otherwise we run into
1034  // issues with data providers like spatialite, delimited text where the format can be
1035  // opened outside of QGIS, but with potentially very different behavior!
1036  requiresTranslation = requiresTranslation || vl->providerType() != QLatin1String( "ogr" );
1037 
1038  // if the layer has a feature filter set, then we HAVE to convert. Feature filters are
1039  // a purely QGIS concept.
1040  requiresTranslation = requiresTranslation || !vl->subsetString().isEmpty();
1041 
1042  // if the layer opened using GDAL's virtual I/O mechanism (/vsizip/, etc.), then
1043  // we HAVE to convert as other tools may not work with it
1044  requiresTranslation = requiresTranslation || vl->source().startsWith( QLatin1String( "/vsi" ) );
1045 
1046  // Check if layer is a disk based format and if so if the layer's path has a compatible filename suffix
1047  QString diskPath;
1048  if ( !requiresTranslation )
1049  {
1050  const QVariantMap parts = QgsProviderRegistry::instance()->decodeUri( vl->providerType(), vl->source() );
1051  if ( parts.contains( QStringLiteral( "path" ) ) )
1052  {
1053  diskPath = parts.value( QStringLiteral( "path" ) ).toString();
1054  QFileInfo fi( diskPath );
1055  requiresTranslation = !compatibleFormats.contains( fi.suffix(), Qt::CaseInsensitive );
1056 
1057  // if the layer name doesn't match the filename, we need to convert the layer. This method can only return
1058  // a filename, and cannot handle layernames as well as file paths
1059  const QString srcLayerName = parts.value( QStringLiteral( "layerName" ) ).toString();
1060  if ( layerName )
1061  {
1062  // differing layer names are acceptable
1063  *layerName = srcLayerName;
1064  }
1065  else
1066  {
1067  // differing layer names are NOT acceptable
1068  requiresTranslation = requiresTranslation || ( !srcLayerName.isEmpty() && srcLayerName != fi.baseName() );
1069  }
1070  }
1071  else
1072  {
1073  requiresTranslation = true; // not a disk-based format
1074  }
1075  }
1076 
1077  if ( requiresTranslation )
1078  {
1079  QString temp = QgsProcessingUtils::generateTempFilename( baseName + '.' + preferredFormat );
1080 
1082  saveOptions.fileEncoding = context.defaultEncoding();
1083  saveOptions.driverName = QgsVectorFileWriter::driverForExtension( preferredFormat );
1084  std::unique_ptr< QgsVectorFileWriter > writer( QgsVectorFileWriter::create( temp, vl->fields(), vl->wkbType(), vl->crs(), context.transformContext(), saveOptions ) );
1085  QgsFeature f;
1086  QgsFeatureIterator it;
1087  if ( featureLimit != -1 )
1088  {
1089  if ( selectedFeaturesOnly )
1090  it = vl->getSelectedFeatures( QgsFeatureRequest().setLimit( featureLimit ) );
1091  else
1092  it = vl->getFeatures( QgsFeatureRequest().setLimit( featureLimit ) );
1093  }
1094  else
1095  {
1096  if ( selectedFeaturesOnly )
1097  it = vl->getSelectedFeatures( QgsFeatureRequest().setLimit( featureLimit ) );
1098  else
1099  it = vl->getFeatures();
1100  }
1101 
1102  while ( it.nextFeature( f ) )
1103  {
1104  if ( feedback->isCanceled() )
1105  return QString();
1106  writer->addFeature( f, QgsFeatureSink::FastInsert );
1107  }
1108  return temp;
1109  }
1110  else
1111  {
1112  return diskPath;
1113  }
1114 }
1115 
1116 QString QgsProcessingUtils::convertToCompatibleFormat( const QgsVectorLayer *vl, bool selectedFeaturesOnly, const QString &baseName, const QStringList &compatibleFormats, const QString &preferredFormat, QgsProcessingContext &context, QgsProcessingFeedback *feedback, long long featureLimit )
1117 {
1118  return convertToCompatibleFormatInternal( vl, selectedFeaturesOnly, baseName, compatibleFormats, preferredFormat, context, feedback, nullptr, featureLimit );
1119 }
1120 
1121 QString 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 )
1122 {
1123  layerName.clear();
1124  return convertToCompatibleFormatInternal( layer, selectedFeaturesOnly, baseName, compatibleFormats, preferredFormat, context, feedback, &layerName, featureLimit );
1125 }
1126 
1127 QgsFields QgsProcessingUtils::combineFields( const QgsFields &fieldsA, const QgsFields &fieldsB, const QString &fieldsBPrefix )
1128 {
1129  QgsFields outFields = fieldsA;
1130  QSet< QString > usedNames;
1131  for ( const QgsField &f : fieldsA )
1132  {
1133  usedNames.insert( f.name().toLower() );
1134  }
1135 
1136  for ( const QgsField &f : fieldsB )
1137  {
1138  QgsField newField = f;
1139  newField.setName( fieldsBPrefix + f.name() );
1140  if ( usedNames.contains( newField.name().toLower() ) )
1141  {
1142  int idx = 2;
1143  QString newName = newField.name() + '_' + QString::number( idx );
1144  while ( usedNames.contains( newName.toLower() ) )
1145  {
1146  idx++;
1147  newName = newField.name() + '_' + QString::number( idx );
1148  }
1149  newField.setName( newName );
1150  outFields.append( newField );
1151  }
1152  else
1153  {
1154  outFields.append( newField );
1155  }
1156  usedNames.insert( newField.name() );
1157  }
1158 
1159  return outFields;
1160 }
1161 
1162 
1163 QList<int> QgsProcessingUtils::fieldNamesToIndices( const QStringList &fieldNames, const QgsFields &fields )
1164 {
1165  QList<int> indices;
1166  if ( !fieldNames.isEmpty() )
1167  {
1168  indices.reserve( fieldNames.count() );
1169  for ( const QString &f : fieldNames )
1170  {
1171  int idx = fields.lookupField( f );
1172  if ( idx >= 0 )
1173  indices.append( idx );
1174  }
1175  }
1176  else
1177  {
1178  indices.reserve( fields.count() );
1179  for ( int i = 0; i < fields.count(); ++i )
1180  indices.append( i );
1181  }
1182  return indices;
1183 }
1184 
1185 
1186 QgsFields QgsProcessingUtils::indicesToFields( const QList<int> &indices, const QgsFields &fields )
1187 {
1188  QgsFields fieldsSubset;
1189  for ( int i : indices )
1190  fieldsSubset.append( fields.at( i ) );
1191  return fieldsSubset;
1192 }
1193 
1195 {
1196  QgsSettings settings;
1197  const int setting = settings.value( QStringLiteral( "Processing/Configuration/DefaultOutputVectorLayerExt" ), -1 ).toInt();
1198  if ( setting == -1 )
1199  return QStringLiteral( "gpkg" );
1200  return QgsVectorFileWriter::supportedFormatExtensions().value( setting, QStringLiteral( "gpkg" ) );
1201 }
1202 
1204 {
1205  QgsSettings settings;
1206  const int setting = settings.value( QStringLiteral( "Processing/Configuration/DefaultOutputRasterLayerExt" ), -1 ).toInt();
1207  if ( setting == -1 )
1208  return QStringLiteral( "tif" );
1209  return QgsRasterFileWriter::supportedFormatExtensions().value( setting, QStringLiteral( "tif" ) );
1210 }
1211 
1212 //
1213 // QgsProcessingFeatureSource
1214 //
1215 
1216 QgsProcessingFeatureSource::QgsProcessingFeatureSource( QgsFeatureSource *originalSource, const QgsProcessingContext &context, bool ownsOriginalSource, long long featureLimit )
1217  : mSource( originalSource )
1218  , mOwnsSource( ownsOriginalSource )
1219  , mInvalidGeometryCheck( QgsWkbTypes::geometryType( mSource->wkbType() ) == QgsWkbTypes::PointGeometry
1220  ? QgsFeatureRequest::GeometryNoCheck // never run geometry validity checks for point layers!
1221  : context.invalidGeometryCheck() )
1222  , mInvalidGeometryCallback( context.invalidGeometryCallback( originalSource ) )
1223  , mTransformErrorCallback( context.transformErrorCallback() )
1224  , mInvalidGeometryCallbackSkip( context.defaultInvalidGeometryCallbackForCheck( QgsFeatureRequest::GeometrySkipInvalid, originalSource ) )
1225  , mInvalidGeometryCallbackAbort( context.defaultInvalidGeometryCallbackForCheck( QgsFeatureRequest::GeometryAbortOnInvalid, originalSource ) )
1226  , mFeatureLimit( featureLimit )
1227 {}
1228 
1230 {
1231  if ( mOwnsSource )
1232  delete mSource;
1233 }
1234 
1236 {
1237  QgsFeatureRequest req( request );
1238  req.setTransformErrorCallback( mTransformErrorCallback );
1239 
1240  if ( flags & FlagSkipGeometryValidityChecks )
1242  else
1243  {
1244  req.setInvalidGeometryCheck( mInvalidGeometryCheck );
1245  req.setInvalidGeometryCallback( mInvalidGeometryCallback );
1246  }
1247 
1248  if ( mFeatureLimit != -1 && req.limit() != -1 )
1249  req.setLimit( std::min( static_cast< long long >( req.limit() ), mFeatureLimit ) );
1250  else if ( mFeatureLimit != -1 )
1251  req.setLimit( mFeatureLimit );
1252 
1253  return mSource->getFeatures( req );
1254 }
1255 
1257 {
1258  FeatureAvailability sourceAvailability = mSource->hasFeatures();
1259  if ( sourceAvailability == NoFeaturesAvailable )
1260  return NoFeaturesAvailable; // never going to be features if underlying source has no features
1261  else if ( mInvalidGeometryCheck == QgsFeatureRequest::GeometryNoCheck )
1262  return sourceAvailability;
1263  else
1264  // we don't know... source has features, but these may be filtered out by invalid geometry check
1265  return FeaturesMaybeAvailable;
1266 }
1267 
1269 {
1270  QgsFeatureRequest req( request );
1271  req.setInvalidGeometryCheck( mInvalidGeometryCheck );
1272  req.setInvalidGeometryCallback( mInvalidGeometryCallback );
1273  req.setTransformErrorCallback( mTransformErrorCallback );
1274 
1275  if ( mFeatureLimit != -1 && req.limit() != -1 )
1276  req.setLimit( std::min( static_cast< long long >( req.limit() ), mFeatureLimit ) );
1277  else if ( mFeatureLimit != -1 )
1278  req.setLimit( mFeatureLimit );
1279 
1280  return mSource->getFeatures( req );
1281 }
1282 
1284 {
1285  return mSource->sourceCrs();
1286 }
1287 
1289 {
1290  return mSource->fields();
1291 }
1292 
1294 {
1295  return mSource->wkbType();
1296 }
1297 
1299 {
1300  if ( mFeatureLimit == -1 )
1301  return mSource->featureCount();
1302  else
1303  return std::min( mFeatureLimit, static_cast< long long >( mSource->featureCount() ) );
1304 }
1305 
1307 {
1308  return mSource->sourceName();
1309 
1310 }
1311 
1312 QSet<QVariant> QgsProcessingFeatureSource::uniqueValues( int fieldIndex, int limit ) const
1313 {
1314  return mSource->uniqueValues( fieldIndex, limit );
1315 }
1316 
1317 QVariant QgsProcessingFeatureSource::minimumValue( int fieldIndex ) const
1318 {
1319  return mSource->minimumValue( fieldIndex );
1320 }
1321 
1322 QVariant QgsProcessingFeatureSource::maximumValue( int fieldIndex ) const
1323 {
1324  return mSource->maximumValue( fieldIndex );
1325 }
1326 
1328 {
1329  return mSource->sourceExtent();
1330 }
1331 
1333 {
1334  return mSource->allFeatureIds();
1335 }
1336 
1338 {
1339  return mSource->hasSpatialIndex();
1340 }
1341 
1343 {
1344  QgsExpressionContextScope *expressionContextScope = nullptr;
1345  QgsExpressionContextScopeGenerator *generator = dynamic_cast<QgsExpressionContextScopeGenerator *>( mSource );
1346  if ( generator )
1347  {
1348  expressionContextScope = generator->createExpressionContextScope();
1349  }
1350  return expressionContextScope;
1351 }
1352 
1354 {
1355  mInvalidGeometryCheck = method;
1356  switch ( mInvalidGeometryCheck )
1357  {
1359  mInvalidGeometryCallback = nullptr;
1360  break;
1361 
1363  mInvalidGeometryCallback = mInvalidGeometryCallbackSkip;
1364  break;
1365 
1367  mInvalidGeometryCallback = mInvalidGeometryCallbackAbort;
1368  break;
1369 
1370  }
1371 }
1372 
1373 
1374 //
1375 // QgsProcessingFeatureSink
1376 //
1377 QgsProcessingFeatureSink::QgsProcessingFeatureSink( QgsFeatureSink *originalSink, const QString &sinkName, QgsProcessingContext &context, bool ownsOriginalSink )
1378  : QgsProxyFeatureSink( originalSink )
1379  , mContext( context )
1380  , mSinkName( sinkName )
1381  , mOwnsSink( ownsOriginalSink )
1382 {}
1383 
1385 {
1386  if ( mOwnsSink )
1387  delete destinationSink();
1388 }
1389 
1390 bool QgsProcessingFeatureSink::addFeature( QgsFeature &feature, QgsFeatureSink::Flags flags )
1391 {
1392  bool result = QgsProxyFeatureSink::addFeature( feature, flags );
1393  if ( !result && mContext.feedback() )
1394  {
1395  const QString error = lastError();
1396  if ( !error.isEmpty() )
1397  mContext.feedback()->reportError( QObject::tr( "Feature could not be written to %1: %2" ).arg( mSinkName, error ) );
1398  else
1399  mContext.feedback()->reportError( QObject::tr( "Feature could not be written to %1" ).arg( mSinkName ) );
1400  }
1401  return result;
1402 }
1403 
1404 bool QgsProcessingFeatureSink::addFeatures( QgsFeatureList &features, QgsFeatureSink::Flags flags )
1405 {
1406  bool result = QgsProxyFeatureSink::addFeatures( features, flags );
1407  if ( !result && mContext.feedback() )
1408  {
1409  const QString error = lastError();
1410  if ( !error.isEmpty() )
1411  mContext.feedback()->reportError( QObject::tr( "%1 feature(s) could not be written to %2: %3" ).arg( features.count() ).arg( mSinkName, error ) );
1412  else
1413  mContext.feedback()->reportError( QObject::tr( "%1 feature(s) could not be written to %2" ).arg( features.count() ).arg( mSinkName ) );
1414  }
1415  return result;
1416 }
1417 
1418 bool QgsProcessingFeatureSink::addFeatures( QgsFeatureIterator &iterator, QgsFeatureSink::Flags flags )
1419 {
1420  bool result = QgsProxyFeatureSink::addFeatures( iterator, flags );
1421  if ( !result && mContext.feedback() )
1422  {
1423  const QString error = lastError();
1424  if ( !error.isEmpty() )
1425  mContext.feedback()->reportError( QObject::tr( "Features could not be written to %1: %2" ).arg( mSinkName, error ) );
1426  else
1427  mContext.feedback()->reportError( QObject::tr( "Features could not be written to %1" ).arg( mSinkName ) );
1428  }
1429  return result;
1430 }
QgsProcessingFeatureSourceDefinition::selectedFeaturesOnly
bool selectedFeaturesOnly
true if only selected features in the source should be used by algorithms.
Definition: qgsprocessingparameters.h:122
QgsVectorLayer::getFeatures
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
Definition: qgsvectorlayer.cpp:993
QgsProcessingFeatureSource::~QgsProcessingFeatureSource
~QgsProcessingFeatureSource() override
Definition: qgsprocessingutils.cpp:1229
QgsProcessingFeatureSource::uniqueValues
QSet< QVariant > uniqueValues(int fieldIndex, int limit=-1) const override
Returns the set of unique values contained within the specified fieldIndex from this source.
Definition: qgsprocessingutils.cpp:1312
QgsMapLayer::crs
QgsCoordinateReferenceSystem crs
Definition: qgsmaplayer.h:89
QgsVectorFileWriter::create
static QgsVectorFileWriter * create(const QString &fileName, const QgsFields &fields, QgsWkbTypes::Type 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.
Definition: qgsvectorfilewriter.cpp:150
QgsProcessingFeatureSource::minimumValue
QVariant minimumValue(int fieldIndex) const override
Returns the minimum value for an attribute column or an invalid variant in case of error.
Definition: qgsprocessingutils.cpp:1317
QgsFeatureSource::minimumValue
virtual QVariant minimumValue(int fieldIndex) const
Returns the minimum value for an attribute column or an invalid variant in case of error.
Definition: qgsfeaturesource.cpp:52
QgsProcessingUtils::compatibleMeshLayers
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.
Definition: qgsprocessingutils.cpp:85
QgsFeatureSource::hasSpatialIndex
virtual SpatialIndexPresence hasSpatialIndex() const
Returns an enum value representing the presence of a valid spatial index on the source,...
Definition: qgsfeaturesource.cpp:190
QgsProject::layers
QVector< T > layers() const
Returns a list of registered map layers with a specified layer type.
Definition: qgsproject.h:1070
QgsPointXY::y
double y
Definition: qgspointxy.h:48
QgsProcessingUtils::defaultVectorExtension
static QString defaultVectorExtension()
Returns the default vector extension to use, in the absence of all other constraints (e....
Definition: qgsprocessingutils.cpp:1194
QgsDataSourceUri
Class for storing the component parts of a RDBMS data source URI (e.g.
Definition: qgsdatasourceuri.h:36
QgsProcessingUtils::createFeatureSink
static QgsFeatureSink * createFeatureSink(QString &destination, QgsProcessingContext &context, const QgsFields &fields, QgsWkbTypes::Type 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.
Definition: qgsprocessingutils.cpp:695
QgsFeatureSource::sourceCrs
virtual QgsCoordinateReferenceSystem sourceCrs() const =0
Returns the coordinate reference system for features in the source.
QgsFeatureRequest::setInvalidGeometryCheck
QgsFeatureRequest & setInvalidGeometryCheck(InvalidGeometryCheck check)
Sets invalid geometry checking behavior.
Definition: qgsfeaturerequest.cpp:112
QgsVectorTileLayer
Implements a map layer that is dedicated to rendering of vector tiles.
Definition: qgsvectortilelayer.h:84
QgsCoordinateTransformContext
Contains information about the context in which a coordinate transform is executed.
Definition: qgscoordinatetransformcontext.h:58
QgsVectorLayer::wkbType
Q_INVOKABLE QgsWkbTypes::Type wkbType() const FINAL
Returns the WKBType or WKBUnknown in case of error.
Definition: qgsvectorlayer.cpp:664
QgsRemappingSinkDefinition::setDestinationWkbType
void setDestinationWkbType(QgsWkbTypes::Type type)
Sets the WKB geometry type for the destination.
Definition: qgsremappingproxyfeaturesink.h:116
QgsVectorFileWriter::SaveVectorOptions
Options to pass to writeAsVectorFormat()
Definition: qgsvectorfilewriter.h:446
QgsProperty
A store for object properties.
Definition: qgsproperty.h:232
QgsMapLayerStore::addMapLayer
QgsMapLayer * addMapLayer(QgsMapLayer *layer, bool takeOwnership=true)
Add a layer to the store.
Definition: qgsmaplayerstore.cpp:105
QgsFeatureRequest::GeometryAbortOnInvalid
@ GeometryAbortOnInvalid
Close iterator on encountering any features with invalid geometry. This requires a slow geometry vali...
Definition: qgsfeaturerequest.h:103
QgsProcessingUtils::variantToSource
static QgsProcessingFeatureSource * variantToSource(const QVariant &value, QgsProcessingContext &context, const QVariant &fallbackValue=QVariant())
Converts a variant value to a new feature source.
Definition: qgsprocessingutils.cpp:349
QgsRectangle::combineExtentWith
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle.
Definition: qgsrectangle.h:359
QgsVectorFileWriter::CreateOrOverwriteFile
@ CreateOrOverwriteFile
Create or overwrite file.
Definition: qgsvectorfilewriter.h:266
QgsProcessingUtils::compatibleRasterLayers
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.
Definition: qgsprocessingutils.cpp:38
QgsSettings::value
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
Definition: qgssettings.cpp:174
QgsMapLayerType::MeshLayer
@ MeshLayer
Added in 3.2.
QgsRemappingSinkDefinition::setDestinationCrs
void setDestinationCrs(const QgsCoordinateReferenceSystem &destination)
Sets the destination crs used for reprojecting incoming features to the sink's destination CRS.
Definition: qgsremappingproxyfeaturesink.h:102
QgsRemappingSinkDefinition
Defines the parameters used to remap features when creating a QgsRemappingProxyFeatureSink.
Definition: qgsremappingproxyfeaturesink.h:38
QgsProcessingContext::project
QgsProject * project() const
Returns the project in which the algorithm is being executed.
Definition: qgsprocessingcontext.h:105
QgsMapLayerType::VectorLayer
@ VectorLayer
QgsReferencedRectangle
A QgsRectangle with associated coordinate reference system.
Definition: qgsreferencedgeometry.h:74
QgsProcessingFeedback
Base class for providing feedback from a processing algorithm.
Definition: qgsprocessingfeedback.h:38
QgsProcessingFeatureSource::sourceExtent
QgsRectangle sourceExtent() const override
Returns the extent of all geometries from the source.
Definition: qgsprocessingutils.cpp:1327
algorithm
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
QgsProxyFeatureSink::destinationSink
QgsFeatureSink * destinationSink()
Returns the destination QgsFeatureSink which the proxy will forward features to.
Definition: qgsproxyfeaturesink.h:55
QgsPointXY::x
Q_GADGET double x
Definition: qgspointxy.h:47
crs
const QgsCoordinateReferenceSystem & crs
Definition: qgswfsgetfeature.cpp:51
QgsRasterLayer::LayerOptions::skipCrsValidation
bool skipCrsValidation
Controls whether the layer is allowed to have an invalid/unknown CRS.
Definition: qgsrasterlayer.h:137
QgsProcessingFeedback::reportError
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
Definition: qgsprocessingfeedback.cpp:39
QgsProxyFeatureSink
A simple feature sink which proxies feature addition on to another feature sink.
Definition: qgsproxyfeaturesink.h:40
QgsProcessingUtils::convertToCompatibleFormatAndLayerName
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)
Converts a source vector layer to a file path and layer name of a vector layer of compatible format.
Definition: qgsprocessingutils.cpp:1121
QgsProcessing::TypeVectorPolygon
@ TypeVectorPolygon
Vector polygon layers.
Definition: qgsprocessing.h:50
QgsProcessingFeatureSource::QgsProcessingFeatureSource
QgsProcessingFeatureSource(QgsFeatureSource *originalSource, const QgsProcessingContext &context, bool ownsOriginalSource=false, long long featureLimit=-1)
Constructor for QgsProcessingFeatureSource, accepting an original feature source originalSource and p...
Definition: qgsprocessingutils.cpp:1216
QgsProcessingUtils::normalizeLayerSource
static QString normalizeLayerSource(const QString &source)
Normalizes a layer source string for safe comparison across different operating system environments.
Definition: qgsprocessingutils.cpp:514
QgsProcessingFeatureSource::createExpressionContextScope
QgsExpressionContextScope * createExpressionContextScope() const
Returns an expression context scope suitable for this source.
Definition: qgsprocessingutils.cpp:1342
QgsProviderRegistry::encodeUri
QString encodeUri(const QString &providerKey, const QVariantMap &parts)
Reassembles a provider data source URI from its component paths (e.g.
Definition: qgsproviderregistry.cpp:442
QgsFields::count
int count() const
Returns number of items.
Definition: qgsfields.cpp:133
QgsFields
Container of fields for a vector layer.
Definition: qgsfields.h:45
QgsRectangle::yMinimum
double yMinimum() const SIP_HOLDGIL
Returns the y minimum value (bottom side of rectangle).
Definition: qgsrectangle.h:177
QgsProperty::asExpression
QString asExpression() const
Returns an expression string representing the state of the property, or an empty string if the proper...
Definition: qgsproperty.cpp:332
QgsProcessingUtils::indicesToFields
static QgsFields indicesToFields(const QList< int > &indices, const QgsFields &fields)
Returns a subset of fields based on the indices of desired fields.
Definition: qgsprocessingutils.cpp:1186
QgsFeatureSource
An interface for objects which provide features via a getFeatures method.
Definition: qgsfeaturesource.h:38
QgsVectorLayer::isSpatial
bool isSpatial() const FINAL
Returns true if this is a geometry layer and false in case of NoGeometry (table only) or UnknownGeome...
Definition: qgsvectorlayer.cpp:3599
QgsProcessingFeatureSourceDefinition::flags
Flags flags
Flags which dictate source behavior.
Definition: qgsprocessingparameters.h:137
QgsFeatureRequest::setInvalidGeometryCallback
QgsFeatureRequest & setInvalidGeometryCallback(const std::function< void(const QgsFeature &)> &callback)
Sets a callback function to use when encountering an invalid geometry and invalidGeometryCheck() is s...
Definition: qgsfeaturerequest.cpp:118
QgsVectorFileWriter::SaveVectorOptions::layerName
QString layerName
Layer name. If let empty, it will be derived from the filename.
Definition: qgsvectorfilewriter.h:457
QgsProcessingParameterDefinition
Base class for the definition of processing parameters.
Definition: qgsprocessingparameters.h:331
QgsProcessing::TypeVectorLine
@ TypeVectorLine
Vector line layers.
Definition: qgsprocessing.h:49
QgsProcessingFeatureSource::FlagSkipGeometryValidityChecks
@ FlagSkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
Definition: qgsprocessingutils.h:477
QgsSettings
This class is a composition of two QSettings instances:
Definition: qgssettings.h:62
QgsExpressionContext::setFields
void setFields(const QgsFields &fields)
Convenience function for setting a fields for the context.
Definition: qgsexpressioncontext.cpp:553
QgsProcessingOutputLayerDefinition
Encapsulates settings relating to a feature sink or output raster layer for a processing algorithm.
Definition: qgsprocessingparameters.h:200
QgsWkbTypes::Type
Type
The WKB type describes the number of dimensions a geometry has.
Definition: qgswkbtypes.h:70
QgsFeatureSource::uniqueValues
virtual QSet< QVariant > uniqueValues(int fieldIndex, int limit=-1) const
Returns the set of unique values contained within the specified fieldIndex from this source.
Definition: qgsfeaturesource.cpp:31
QgsProcessingFeatureSource::maximumValue
QVariant maximumValue(int fieldIndex) const override
Returns the maximum value for an attribute column or an invalid variant in case of error.
Definition: qgsprocessingutils.cpp:1322
QgsExpressionContextScopeGenerator
Abstract interface for generating an expression context scope.
Definition: qgsexpressioncontextscopegenerator.h:29
QgsProcessingFeatureSourceDefinition::geometryCheck
QgsFeatureRequest::InvalidGeometryCheck geometryCheck
Geometry check method to apply to this source.
Definition: qgsprocessingparameters.h:147
QgsMapLayer::isValid
bool isValid
Definition: qgsmaplayer.h:91
QgsProcessingUtils::LayerHint
LayerHint
Layer type hints.
Definition: qgsprocessingutils.h:137
QgsFeatureRequest::InvalidGeometryCheck
InvalidGeometryCheck
Handling of features with invalid geometries.
Definition: qgsfeaturerequest.h:100
QgsVectorFileWriter::NoSymbology
@ NoSymbology
Definition: qgsvectorfilewriter.h:183
QgsFeatureRequest::GeometrySkipInvalid
@ GeometrySkipInvalid
Skip any features with invalid geometry. This requires a slow geometry validity check for every featu...
Definition: qgsfeaturerequest.h:102
QgsProperty::propertyType
Type propertyType() const
Returns the property type.
Definition: qgsproperty.cpp:261
QgsProcessingUtils::encodeProviderKeyAndUri
static QString encodeProviderKeyAndUri(const QString &providerKey, const QString &uri)
Encodes a provider key and layer uri to a single string, for use with decodeProviderKeyAndUri()
Definition: qgsprocessingutils.cpp:137
QgsFields::append
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
QgsProcessingFeatureSink::~QgsProcessingFeatureSink
~QgsProcessingFeatureSink() override
Definition: qgsprocessingutils.cpp:1384
QgsProcessing::TypeVectorPoint
@ TypeVectorPoint
Vector point layers.
Definition: qgsprocessing.h:48
QgsProcessingUtils::stringToPythonLiteral
static QString stringToPythonLiteral(const QString &string)
Converts a string to a Python string literal.
Definition: qgsprocessingutils.cpp:611
QgsProcessingFeatureSourceDefinition::source
QgsProperty source
Source definition.
Definition: qgsprocessingparameters.h:117
QgsField::name
QString name
Definition: qgsfield.h:59
QgsRectangle
A rectangle specified with double values.
Definition: qgsrectangle.h:42
QgsWkbTypes::PolygonGeometry
@ PolygonGeometry
Definition: qgswkbtypes.h:144
QgsProperty::value
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...
Definition: qgsproperty.cpp:519
QgsProcessingUtils::combineFields
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).
Definition: qgsprocessingutils.cpp:1127
QgsCoordinateTransform::transformBoundingBox
QgsRectangle transformBoundingBox(const QgsRectangle &rectangle, TransformDirection direction=ForwardTransform, bool handle180Crossover=false) const SIP_THROW(QgsCsException)
Transforms a rectangle from the source CRS to the destination CRS.
Definition: qgscoordinatetransform.cpp:511
qgsDoubleToString
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
Definition: qgis.h:275
QgsProject
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
Definition: qgsproject.h:95
QgsProcessingUtils::LayerHint::Raster
@ Raster
Raster layer type.
QgsMeshLayer::LayerOptions
Setting options for loading mesh layers.
Definition: qgsmeshlayer.h:103
QgsProcessingUtils::generateIteratingDestination
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...
Definition: qgsprocessingutils.cpp:890
QgsProcessingUtils::LayerHint::Mesh
@ Mesh
Mesh layer type, since QGIS 3.6.
qgsrasterfilewriter.h
QgsMapLayer::providerType
QString providerType() const
Returns the provider type (provider key) for this layer.
Definition: qgsmaplayer.cpp:1617
QgsProcessingFeatureSource::getFeatures
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request, Flags flags) const
Returns an iterator for the features in the source, respecting the supplied feature flags.
Definition: qgsprocessingutils.cpp:1235
QgsMapLayerStore::mapLayers
QMap< QString, QgsMapLayer * > mapLayers() const
Returns a map of all layers by layer ID.
Definition: qgsmaplayerstore.cpp:235
QgsFeatureSource::allFeatureIds
virtual QgsFeatureIds allFeatureIds() const
Returns a list of all feature IDs for features present in the source.
Definition: qgsfeaturesource.cpp:115
QgsProperty::fromValue
static QgsProperty fromValue(const QVariant &value, bool isActive=true)
Returns a new StaticProperty created from the specified value.
Definition: qgsproperty.cpp:228
qgsvectortilelayer.h
QgsProxyFeatureSink::addFeature
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a single feature to the sink.
Definition: qgsproxyfeaturesink.h:47
QgsFeatureSource::hasFeatures
virtual FeatureAvailability hasFeatures() const
Determines if there are any features available in the source.
Definition: qgsfeaturesource.cpp:26
QgsProcessingAlgorithm::outputDefinitions
QgsProcessingOutputDefinitions outputDefinitions() const
Returns an ordered list of output definitions utilized by the algorithm.
Definition: qgsprocessingalgorithm.h:306
QgsProcessingOutputDefinition
Base class for the definition of processing outputs.
Definition: qgsprocessingoutputs.h:42
QgsVectorLayer::fields
QgsFields fields() const FINAL
Returns the list of fields of this layer.
Definition: qgsvectorlayer.cpp:3283
QgsProcessingFeatureSourceDefinition
Encapsulates settings relating to a feature source input to a processing algorithm.
Definition: qgsprocessingparameters.h:56
QgsRectangle::xMaximum
double xMaximum() const SIP_HOLDGIL
Returns the x maximum value (right side of rectangle).
Definition: qgsrectangle.h:162
QgsMapLayerStore
A storage object for map layers, in which the layers are owned by the store and have their lifetime b...
Definition: qgsmaplayerstore.h:36
QgsFeatureRequest
This class wraps a request for features to a vector layer (or directly its vector data provider).
Definition: qgsfeaturerequest.h:76
QgsMeshLayer::dataProvider
QgsMeshDataProvider * dataProvider() override
Returns the layer's data provider, it may be nullptr.
Definition: qgsmeshlayer.cpp:156
QgsCsException
Custom exception class for Coordinate Reference System related exceptions.
Definition: qgsexception.h:66
QgsMemoryProviderUtils::createMemoryLayer
static QgsVectorLayer * createMemoryLayer(const QString &name, const QgsFields &fields, QgsWkbTypes::Type geometryType=QgsWkbTypes::NoGeometry, const QgsCoordinateReferenceSystem &crs=QgsCoordinateReferenceSystem())
Creates a new memory layer using the specified parameters.
Definition: qgsmemoryproviderutils.cpp:59
QgsFeatureSource::maximumValue
virtual QVariant maximumValue(int fieldIndex) const
Returns the maximum value for an attribute column or an invalid variant in case of error.
Definition: qgsfeaturesource.cpp:75
QgsVectorLayerSelectedFeatureSource
QgsFeatureSource subclass for the selected features from a QgsVectorLayer.
Definition: qgsvectorlayerfeatureiterator.h:305
QgsProcessing::TypeVector
@ TypeVector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
Definition: qgsprocessing.h:53
QgsRasterFileWriter::supportedFormatExtensions
static QStringList supportedFormatExtensions(RasterFormatOptions options=SortRecommended)
Returns a list of file extensions for supported formats.
Definition: qgsrasterfilewriter.cpp:1203
QgsProcessingFeatureSink::addFeatures
bool addFeatures(QgsFeatureList &features, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a list of features to the sink.
Definition: qgsprocessingutils.cpp:1404
qgsproviderregistry.h
QgsProcessingFeatureSource::hasFeatures
QgsFeatureSource::FeatureAvailability hasFeatures() const override
Determines if there are any features available in the source.
Definition: qgsprocessingutils.cpp:1256
QgsProcessingUtils::convertToCompatibleFormat
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)
Converts a source vector layer to a file path of a vector layer of compatible format.
Definition: qgsprocessingutils.cpp:1116
QgsProxyFeatureSink::lastError
QString lastError() const override
Returns the most recent error encountered by the sink, e.g.
Definition: qgsproxyfeaturesink.h:50
QgsFeatureSource::sourceName
virtual QString sourceName() const =0
Returns a friendly display name for the source.
QgsProcessingFeatureSource::fields
QgsFields fields() const override
Returns the fields associated with features in the source.
Definition: qgsprocessingutils.cpp:1288
QgsProcessingContext
Contains information about the context in which a processing algorithm is executed.
Definition: qgsprocessingcontext.h:44
QgsProxyFeatureSink::addFeatures
bool addFeatures(QgsFeatureList &features, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a list of features to the sink.
Definition: qgsproxyfeaturesink.h:48
QgsFeatureRequest::setTransformErrorCallback
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...
Definition: qgsfeaturerequest.cpp:265
QgsProcessingUtils::fieldNamesToIndices
static QList< int > fieldNamesToIndices(const QStringList &fieldNames, const QgsFields &fields)
Returns a list of field indices parsed from the given list of field names.
Definition: qgsprocessingutils.cpp:1163
QgsVectorFileWriter::SaveVectorOptions::fileEncoding
QString fileEncoding
Encoding to use.
Definition: qgsvectorfilewriter.h:463
QgsRemappingSinkDefinition::setDestinationFields
void setDestinationFields(const QgsFields &fields)
Sets the fields for the destination sink.
Definition: qgsremappingproxyfeaturesink.h:130
QgsProcessingContext::defaultEncoding
QString defaultEncoding() const
Returns the default encoding to use for newly created files.
Definition: qgsprocessingcontext.h:464
qgsprocessingalgorithm.h
QgsMeshLayer
Represents a mesh layer supporting display of data on structured or unstructured meshes.
Definition: qgsmeshlayer.h:95
QgsMapLayerType::RasterLayer
@ RasterLayer
QgsFeatureSource::SpatialIndexPresence
SpatialIndexPresence
Enumeration of spatial index presence states.
Definition: qgsfeaturesource.h:188
QgsProcessing::TypeVectorAnyGeometry
@ TypeVectorAnyGeometry
Any vector layer with geometry.
Definition: qgsprocessing.h:47
QgsCoordinateReferenceSystem::authid
QString authid() const
Returns the authority identifier for the CRS.
Definition: qgscoordinatereferencesystem.cpp:1321
QgsMeshLayer::LayerOptions::skipCrsValidation
bool skipCrsValidation
Controls whether the layer is allowed to have an invalid/unknown CRS.
Definition: qgsmeshlayer.h:128
QgsFeatureSource::getFeatures
virtual QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const =0
Returns an iterator for the features in the source.
convertToCompatibleFormatInternal
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)
Definition: qgsprocessingutils.cpp:1021
QgsFeatureList
QList< QgsFeature > QgsFeatureList
Definition: qgsfeature.h:583
QgsProcessingFeatureSource::featureCount
long featureCount() const override
Returns the number of features contained in the source, or -1 if the feature count is unknown.
Definition: qgsprocessingutils.cpp:1298
QgsCoordinateReferenceSystem::isValid
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
Definition: qgscoordinatereferencesystem.cpp:924
QgsFeatureSource::NoFeaturesAvailable
@ NoFeaturesAvailable
There are certainly no features available in this source.
Definition: qgsfeaturesource.h:52
QgsProviderRegistry::decodeUri
QVariantMap decodeUri(const QString &providerKey, const QString &uri)
Breaks a provider data source URI into its component paths (e.g.
Definition: qgsproviderregistry.cpp:433
QgsVectorFileWriter::supportedFormatExtensions
static QStringList supportedFormatExtensions(VectorFormatOptions options=SortRecommended)
Returns a list of file extensions for supported formats, e.g "shp", "gpkg".
Definition: qgsvectorfilewriter.cpp:3326
QgsProcessing::TEMPORARY_OUTPUT
static const QString TEMPORARY_OUTPUT
Constant used to indicate that a Processing algorithm output should be a temporary layer/file.
Definition: qgsprocessing.h:99
qgsvectorlayerfeatureiterator.h
QgsProcessingUtils::decodeProviderKeyAndUri
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()
Definition: qgsprocessingutils.cpp:142
QgsProcessingUtils::createFeatureSinkPython
static void createFeatureSinkPython(QgsFeatureSink **sink, QString &destination, QgsProcessingContext &context, const QgsFields &fields, QgsWkbTypes::Type geometryType, const QgsCoordinateReferenceSystem &crs, const QVariantMap &createOptions=QVariantMap()) SIP_THROW(QgsProcessingException)
Creates a feature sink ready for adding features.
Definition: qgsprocessingutils.cpp:845
QgsVectorFileWriter::defaultLayerOptions
static QStringList defaultLayerOptions(const QString &driverName)
Returns a list of the default layer options for a specified driver.
Definition: qgsvectorfilewriter.cpp:2258
QgsProcessingContext::transformContext
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
Definition: qgsprocessingcontext.h:149
QgsProviderRegistry::providerMetadata
QgsProviderMetadata * providerMetadata(const QString &providerKey) const
Returns metadata of the provider or nullptr if not found.
Definition: qgsproviderregistry.cpp:724
QgsVectorFileWriter::driverForExtension
static QString driverForExtension(const QString &extension)
Returns the OGR driver name for a specified file extension.
Definition: qgsvectorfilewriter.cpp:3462
QgsRectangle::xMinimum
double xMinimum() const SIP_HOLDGIL
Returns the x minimum value (left side of rectangle).
Definition: qgsrectangle.h:167
QgsVectorFileWriter::SaveVectorOptions::actionOnExistingFile
QgsVectorFileWriter::ActionOnExistingFile actionOnExistingFile
Action on existing file.
Definition: qgsvectorfilewriter.h:460
QgsRasterLayer
Represents a raster layer.
Definition: qgsrasterlayer.h:71
QgsFeatureSource::sourceExtent
virtual QgsRectangle sourceExtent() const
Returns the extent of all geometries from the source.
Definition: qgsfeaturesource.cpp:98
QgsMapLayer::setTransformContext
virtual void setTransformContext(const QgsCoordinateTransformContext &transformContext)=0
Sets the coordinate transform context to transformContext.
QgsFeatureIds
QSet< QgsFeatureId > QgsFeatureIds
Definition: qgsfeatureid.h:37
QgsFeatureSink::RegeneratePrimaryKey
@ RegeneratePrimaryKey
This flag indicates, that a primary key field cannot be guaranteed to be unique and the sink should i...
Definition: qgsfeaturesink.h:55
qgsfileutils.h
QgsCoordinateReferenceSystem
This class represents a coordinate reference system (CRS).
Definition: qgscoordinatereferencesystem.h:206
QgsFeatureSource::fields
virtual QgsFields fields() const =0
Returns the fields associated with features in the source.
QgsProcessingContext::temporaryLayerStore
QgsMapLayerStore * temporaryLayerStore()
Returns a reference to the layer store used for storing temporary layers during algorithm execution.
Definition: qgsprocessingcontext.h:223
QgsReferencedPointXY
A QgsPointXY with associated coordinate reference system.
Definition: qgsreferencedgeometry.h:115
QgsExpressionContextScope
Single scope for storing variables and functions for use within a QgsExpressionContext.
Definition: qgsexpressioncontext.h:112
QgsVectorFileWriter::SaveVectorOptions::datasourceOptions
QStringList datasourceOptions
List of OGR data source creation options.
Definition: qgsvectorfilewriter.h:475
QgsVectorLayer::extent
QgsRectangle extent() const FINAL
Returns the extent of the layer.
Definition: qgsvectorlayer.cpp:833
QgsProcessingContext::feedback
QgsProcessingFeedback * feedback()
Returns the associated feedback object.
Definition: qgsprocessingcontext.h:476
QgsFeatureSource::featureCount
virtual long featureCount() const =0
Returns the number of features contained in the source, or -1 if the feature count is unknown.
QgsCoordinateReferenceSystem::createFromString
bool createFromString(const QString &definition)
Set up this CRS from a string definition.
Definition: qgscoordinatereferencesystem.cpp:272
qgsmeshlayer.h
qgsvectorlayer.h
QgsPointXY
A class to represent a 2D point.
Definition: qgspointxy.h:44
QgsProcessingFeatureSource::setInvalidGeometryCheck
void setInvalidGeometryCheck(QgsFeatureRequest::InvalidGeometryCheck method)
Overrides the default geometry check method for the source.
Definition: qgsprocessingutils.cpp:1353
QgsProcessingFeatureSink
QgsProxyFeatureSink subclass which reports feature addition errors to a QgsProcessingContext.
Definition: qgsprocessingutils.h:555
QgsVectorLayer::getSelectedFeatures
QgsFeatureIterator getSelectedFeatures(QgsFeatureRequest request=QgsFeatureRequest()) const
Returns an iterator of the selected features.
Definition: qgsvectorlayer.cpp:3476
QgsFeedback::isCanceled
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition: qgsfeedback.h:53
QgsVectorFileWriter::AppendToLayerNoNewFields
@ AppendToLayerNoNewFields
Append features to existing layer, but do not create new fields.
Definition: qgsvectorfilewriter.h:272
QgsVectorLayer::LayerOptions
Setting options for loading vector layers.
Definition: qgsvectorlayer.h:425
qgsprocessingutils.h
qgsprocessingparameters.h
QgsFeatureSource::FeatureAvailability
FeatureAvailability
Possible return value for hasFeatures() to determine if a source is empty.
Definition: qgsfeaturesource.h:51
QgsReferencedGeometryBase::crs
QgsCoordinateReferenceSystem crs() const
Returns the associated coordinate reference system, or an invalid CRS if no reference system is set.
Definition: qgsreferencedgeometry.h:53
QgsMapLayer::source
QString source() const
Returns the source for the layer.
Definition: qgsmaplayer.cpp:192
QgsProcessingUtils::LayerHint::Vector
@ Vector
Vector layer type.
qgsreferencedgeometry.h
QgsProcessingFeatureSourceDefinition::featureLimit
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...
Definition: qgsprocessingparameters.h:130
QgsRasterLayer::LayerOptions
Setting options for loading raster layers.
Definition: qgsrasterlayer.h:104
QgsWkbTypes::LineGeometry
@ LineGeometry
Definition: qgswkbtypes.h:143
QgsRasterLayer::LayerOptions::loadDefaultStyle
bool loadDefaultStyle
Sets to true if the default layer style should be loaded.
Definition: qgsrasterlayer.h:116
QgsWkbTypes::PointGeometry
@ PointGeometry
Definition: qgswkbtypes.h:142
QgsRectangle::yMaximum
double yMaximum() const SIP_HOLDGIL
Returns the y maximum value (top side of rectangle).
Definition: qgsrectangle.h:172
QgsProcessingUtils::generateTempFilename
static QString generateTempFilename(const QString &basename)
Returns a temporary filename for a given file, putting it into a temporary folder (creating that fold...
Definition: qgsprocessingutils.cpp:964
QgsProcessingAlgorithm
Abstract base class for processing algorithms.
Definition: qgsprocessingalgorithm.h:52
QgsFeatureIterator::nextFeature
bool nextFeature(QgsFeature &f)
Definition: qgsfeatureiterator.h:374
QgsProcessingUtils::tempFolder
static QString tempFolder()
Returns a session specific processing temporary folder for use in processing algorithms.
Definition: qgsprocessingutils.cpp:929
QgsFeatureSource::wkbType
virtual QgsWkbTypes::Type wkbType() const =0
Returns the geometry type for features returned by this source.
QgsVectorLayer
Represents a vector layer which manages a vector based data sets.
Definition: qgsvectorlayer.h:387
QgsProcessingUtils::variantToPythonLiteral
static QString variantToPythonLiteral(const QVariant &value)
Converts a variant to a Python literal.
Definition: qgsprocessingutils.cpp:521
QgsFeatureRequest::setLimit
QgsFeatureRequest & setLimit(long limit)
Set the maximum number of features to request.
Definition: qgsfeaturerequest.cpp:173
QgsProcessingUtils::compatibleVectorLayers
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.
Definition: qgsprocessingutils.cpp:62
qgsvectorlayerexporter.h
QgsMapLayer
Base class for all map layer types.
Definition: qgsmaplayer.h:83
QgsProcessingUtils::formatHelpMapAsHtml
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.
Definition: qgsprocessingutils.cpp:976
QgsProcessingContext::expressionContext
QgsExpressionContext & expressionContext()
Returns the expression context.
Definition: qgsprocessingcontext.h:133
QgsProcessingUtils::variantToCrs
static QgsCoordinateReferenceSystem variantToCrs(const QVariant &value, QgsProcessingContext &context, const QVariant &fallbackValue=QVariant())
Converts a variant value to a coordinate reference system.
Definition: qgsprocessingutils.cpp:426
QgsProcessingFeatureSource
QgsFeatureSource subclass which proxies methods to an underlying QgsFeatureSource,...
Definition: qgsprocessingutils.h:471
qgssettings.h
QgsProcessingFeatureSource::hasSpatialIndex
SpatialIndexPresence hasSpatialIndex() const override
Returns an enum value representing the presence of a valid spatial index on the source,...
Definition: qgsprocessingutils.cpp:1337
QgsFeatureSource::FeaturesMaybeAvailable
@ FeaturesMaybeAvailable
There may be features available in this source.
Definition: qgsfeaturesource.h:54
QgsFeatureRequest::GeometryNoCheck
@ GeometryNoCheck
No invalid geometry checking.
Definition: qgsfeaturerequest.h:101
qgsprocessingcontext.h
QgsProcessingUtils::combineLayerExtents
static QgsRectangle combineLayerExtents(const QList< QgsMapLayer * > &layers, const QgsCoordinateReferenceSystem &crs, QgsProcessingContext &context)
Combines the extent of several map layers.
Definition: qgsprocessingutils.cpp:851
QgsVectorLayer::subsetString
QString subsetString
Definition: qgsvectorlayer.h:390
QgsProcessingAlgorithm::parameterDefinitions
QgsProcessingParameterDefinitions parameterDefinitions() const
Returns an ordered list of parameter definitions utilized by the algorithm.
Definition: qgsprocessingalgorithm.h:279
qgsexception.h
QgsProcessingUtils::mapLayerFromString
static QgsMapLayer * mapLayerFromString(const QString &string, QgsProcessingContext &context, bool allowLoadingNewLayers=true, QgsProcessingUtils::LayerHint typeHint=QgsProcessingUtils::LayerHint::UnknownType)
Interprets a string as a map layer within the supplied context.
Definition: qgsprocessingutils.cpp:316
qgsexpressioncontextscopegenerator.h
QgsFeature
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:56
QgsProcessingFeatureSink::QgsProcessingFeatureSink
QgsProcessingFeatureSink(QgsFeatureSink *originalSink, const QString &sinkName, QgsProcessingContext &context, bool ownsOriginalSink=false)
Constructor for QgsProcessingFeatureSink, accepting an original feature sink originalSink and process...
Definition: qgsprocessingutils.cpp:1377
QgsWkbTypes
Handles storage of information regarding WKB types and their properties.
Definition: qgswkbtypes.h:42
qgsmemoryproviderutils.h
QgsProcessingFeatureSource::allFeatureIds
QgsFeatureIds allFeatureIds() const override
Returns a list of all feature IDs for features present in the source.
Definition: qgsprocessingutils.cpp:1332
QgsProcessingOutputLayerDefinition::sink
QgsProperty sink
Sink/layer definition.
Definition: qgsprocessingparameters.h:226
QgsVectorFileWriter::SaveVectorOptions::symbologyExport
QgsVectorFileWriter::SymbologyExport symbologyExport
Symbology to export.
Definition: qgsvectorfilewriter.h:487
qgsvectorfilewriter.h
QgsFields::lookupField
int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
Definition: qgsfields.cpp:344
QgsVectorFileWriter::SaveVectorOptions::layerOptions
QStringList layerOptions
List of OGR layer creation options.
Definition: qgsvectorfilewriter.h:478
QgsFields::at
QgsField at(int i) const
Gets field at particular index (must be in range 0..N-1)
Definition: qgsfields.cpp:163
QgsDataSourceUri::table
QString table() const
Returns the table name stored in the URI.
Definition: qgsdatasourceuri.cpp:314
QgsProperty::StaticProperty
@ StaticProperty
Static property (QgsStaticProperty)
Definition: qgsproperty.h:239
QgsCoordinateTransform
Class for doing transforms between two map coordinate systems.
Definition: qgscoordinatetransform.h:53
QgsVectorFileWriter::SaveVectorOptions::driverName
QString driverName
OGR driver to use.
Definition: qgsvectorfilewriter.h:454
QgsFeatureIterator
Wrapper for iterator of features from vector data provider or vector layer.
Definition: qgsfeatureiterator.h:265
QgsVectorLayer::geometryType
Q_INVOKABLE QgsWkbTypes::GeometryType geometryType() const
Returns point, line or polygon.
Definition: qgsvectorlayer.cpp:659
QgsProcessingFeatureSource::sourceCrs
QgsCoordinateReferenceSystem sourceCrs() const override
Returns the coordinate reference system for features in the source.
Definition: qgsprocessingutils.cpp:1283
QgsProcessingFeatureSink::addFeature
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a single feature to the sink.
Definition: qgsprocessingutils.cpp:1390
QgsProcessingFeatureSource::sourceName
QString sourceName() const override
Returns a friendly display name for the source.
Definition: qgsprocessingutils.cpp:1306
QgsProviderRegistry::instance
static QgsProviderRegistry * instance(const QString &pluginPath=QString())
Means of accessing canonical single instance.
Definition: qgsproviderregistry.cpp:48
QgsVectorFileWriter::defaultDatasetOptions
static QStringList defaultDatasetOptions(const QString &driverName)
Returns a list of the default dataset options for a specified driver.
Definition: qgsvectorfilewriter.cpp:2249
QgsProcessingUtils::defaultRasterExtension
static QString defaultRasterExtension()
Returns the default raster extension to use, in the absence of all other constraints (e....
Definition: qgsprocessingutils.cpp:1203
QgsProcessingFeatureSource::wkbType
QgsWkbTypes::Type wkbType() const override
Returns the geometry type for features returned by this source.
Definition: qgsprocessingutils.cpp:1293
QgsProject::crs
QgsCoordinateReferenceSystem crs
Definition: qgsproject.h:100
QgsProcessingException
Custom exception class for processing related exceptions.
Definition: qgsexception.h:83
qgsproject.h
QgsExpressionContextScopeGenerator::createExpressionContextScope
virtual QgsExpressionContextScope * createExpressionContextScope() const =0
This method needs to be reimplemented in all classes which implement this interface and return an exp...
QgsFeatureSink
An interface for objects which accept features via addFeature(s) methods.
Definition: qgsfeaturesink.h:34
QgsField::setName
void setName(const QString &name)
Set the field name.
Definition: qgsfield.cpp:174
QgsFileUtils::stringToSafeFilename
static QString stringToSafeFilename(const QString &string)
Converts a string to a safe filename, replacing characters which are not safe for filenames with an '...
Definition: qgsfileutils.cpp:92
QgsFeatureSink::FastInsert
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
Definition: qgsfeaturesink.h:70
QgsProcessingUtils::LayerHint::UnknownType
@ UnknownType
Unknown layer type.
QgsProcessingUtils::compatibleLayers
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.
Definition: qgsprocessingutils.cpp:108
QgsFeatureRequest::limit
long limit() const
Returns the maximum number of features to request, or -1 if no limit set.
Definition: qgsfeaturerequest.h:499
QgsField
Encapsulate a field in an attribute table or data source.
Definition: qgsfield.h:50