QGIS API Documentation  3.6.0-Noosa (5873452)
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 
36 QList<QgsRasterLayer *> QgsProcessingUtils::compatibleRasterLayers( QgsProject *project, bool sort )
37 {
38  if ( !project )
39  return QList<QgsRasterLayer *>();
40 
41  QList<QgsRasterLayer *> layers;
42 
43  const auto rasterLayers = project->layers<QgsRasterLayer *>();
44  for ( QgsRasterLayer *l : rasterLayers )
45  {
46  if ( canUseLayer( l ) )
47  layers << l;
48  }
49 
50  if ( sort )
51  {
52  std::sort( layers.begin(), layers.end(), []( const QgsRasterLayer * a, const QgsRasterLayer * b ) -> bool
53  {
54  return QString::localeAwareCompare( a->name(), b->name() ) < 0;
55  } );
56  }
57  return layers;
58 }
59 
60 QList<QgsVectorLayer *> QgsProcessingUtils::compatibleVectorLayers( QgsProject *project, const QList<int> &geometryTypes, bool sort )
61 {
62  if ( !project )
63  return QList<QgsVectorLayer *>();
64 
65  QList<QgsVectorLayer *> layers;
66  const auto vectorLayers = project->layers<QgsVectorLayer *>();
67  for ( QgsVectorLayer *l : vectorLayers )
68  {
69  if ( canUseLayer( l, geometryTypes ) )
70  layers << l;
71  }
72 
73  if ( sort )
74  {
75  std::sort( layers.begin(), layers.end(), []( const QgsVectorLayer * a, const QgsVectorLayer * b ) -> bool
76  {
77  return QString::localeAwareCompare( a->name(), b->name() ) < 0;
78  } );
79  }
80  return layers;
81 }
82 
83 QList<QgsMeshLayer *> QgsProcessingUtils::compatibleMeshLayers( QgsProject *project, bool sort )
84 {
85  if ( !project )
86  return QList<QgsMeshLayer *>();
87 
88  QList<QgsMeshLayer *> layers;
89  const auto meshLayers = project->layers<QgsMeshLayer *>();
90  for ( QgsMeshLayer *l : meshLayers )
91  {
92  if ( canUseLayer( l ) )
93  layers << l;
94  }
95 
96  if ( sort )
97  {
98  std::sort( layers.begin(), layers.end(), []( const QgsMeshLayer * a, const QgsMeshLayer * b ) -> bool
99  {
100  return QString::localeAwareCompare( a->name(), b->name() ) < 0;
101  } );
102  }
103  return layers;
104 }
105 
106 QList<QgsMapLayer *> QgsProcessingUtils::compatibleLayers( QgsProject *project, bool sort )
107 {
108  if ( !project )
109  return QList<QgsMapLayer *>();
110 
111  QList<QgsMapLayer *> layers;
112 
113  const auto rasterLayers = compatibleRasterLayers( project, false );
114  for ( QgsRasterLayer *rl : rasterLayers )
115  layers << rl;
116 
117  const auto vectorLayers = compatibleVectorLayers( project, QList< int >(), false );
118  for ( QgsVectorLayer *vl : vectorLayers )
119  layers << vl;
120 
121  const auto meshLayers = compatibleMeshLayers( project, false );
122  for ( QgsMeshLayer *vl : meshLayers )
123  layers << vl;
124 
125  if ( sort )
126  {
127  std::sort( layers.begin(), layers.end(), []( const QgsMapLayer * a, const QgsMapLayer * b ) -> bool
128  {
129  return QString::localeAwareCompare( a->name(), b->name() ) < 0;
130  } );
131  }
132  return layers;
133 }
134 
135 QgsMapLayer *QgsProcessingUtils::mapLayerFromStore( const QString &string, QgsMapLayerStore *store, QgsProcessingUtils::LayerHint typeHint )
136 {
137  if ( !store || string.isEmpty() )
138  return nullptr;
139 
140  QList< QgsMapLayer * > layers = store->mapLayers().values();
141 
142  layers.erase( std::remove_if( layers.begin(), layers.end(), []( QgsMapLayer * layer )
143  {
144  switch ( layer->type() )
145  {
147  return !canUseLayer( qobject_cast< QgsVectorLayer * >( layer ) );
149  return !canUseLayer( qobject_cast< QgsRasterLayer * >( layer ) );
151  return true;
153  return !canUseLayer( qobject_cast< QgsMeshLayer * >( layer ) );
154  }
155  return true;
156  } ), layers.end() );
157 
158  auto isCompatibleType = [typeHint]( QgsMapLayer * l ) -> bool
159  {
160  switch ( typeHint )
161  {
162  case UnknownType:
163  return true;
164 
165  case Vector:
166  return l->type() == QgsMapLayer::VectorLayer;
167 
168  case Raster:
169  return l->type() == QgsMapLayer::RasterLayer;
170 
171  case Mesh:
172  return l->type() == QgsMapLayer::MeshLayer;
173  }
174  return true;
175  };
176 
177  for ( QgsMapLayer *l : qgis::as_const( layers ) )
178  {
179  if ( isCompatibleType( l ) && l->id() == string )
180  return l;
181  }
182  for ( QgsMapLayer *l : qgis::as_const( layers ) )
183  {
184  if ( isCompatibleType( l ) && l->name() == string )
185  return l;
186  }
187  for ( QgsMapLayer *l : qgis::as_const( layers ) )
188  {
189  if ( isCompatibleType( l ) && normalizeLayerSource( l->source() ) == normalizeLayerSource( string ) )
190  return l;
191  }
192  return nullptr;
193 }
194 
196 class ProjectionSettingRestorer
197 {
198  public:
199 
200  ProjectionSettingRestorer()
201  {
202  QgsSettings settings;
203  previousSetting = settings.value( QStringLiteral( "/Projections/defaultBehavior" ) ).toString();
204  settings.setValue( QStringLiteral( "/Projections/defaultBehavior" ), QStringLiteral( "useProject" ) );
205  }
206 
207  ~ProjectionSettingRestorer()
208  {
209  QgsSettings settings;
210  settings.setValue( QStringLiteral( "/Projections/defaultBehavior" ), previousSetting );
211  }
212 
213  QString previousSetting;
214 };
216 
217 QgsMapLayer *QgsProcessingUtils::loadMapLayerFromString( const QString &string, LayerHint typeHint )
218 {
219  QStringList components = string.split( '|' );
220  if ( components.isEmpty() )
221  return nullptr;
222 
223  QFileInfo fi;
224  if ( QFileInfo::exists( string ) )
225  fi = QFileInfo( string );
226  else if ( QFileInfo::exists( components.at( 0 ) ) )
227  fi = QFileInfo( components.at( 0 ) );
228  else
229  return nullptr;
230 
231  // TODO - remove when there is a cleaner way to block the unknown projection dialog!
232  ProjectionSettingRestorer restorer;
233  ( void )restorer; // no warnings
234 
235  QString name = fi.baseName();
236 
237  // brute force attempt to load a matching layer
238  if ( typeHint == UnknownType || typeHint == Vector )
239  {
241  options.loadDefaultStyle = false;
242  std::unique_ptr< QgsVectorLayer > layer( new QgsVectorLayer( string, name, QStringLiteral( "ogr" ), options ) );
243  if ( layer->isValid() )
244  {
245  return layer.release();
246  }
247  }
248  if ( typeHint == UnknownType || typeHint == Raster )
249  {
250  QgsRasterLayer::LayerOptions rasterOptions;
251  rasterOptions.loadDefaultStyle = false;
252  std::unique_ptr< QgsRasterLayer > rasterLayer( new QgsRasterLayer( string, name, QStringLiteral( "gdal" ), rasterOptions ) );
253  if ( rasterLayer->isValid() )
254  {
255  return rasterLayer.release();
256  }
257  }
258  if ( typeHint == UnknownType || typeHint == Mesh )
259  {
260  QgsMeshLayer::LayerOptions meshOptions;
261  std::unique_ptr< QgsMeshLayer > meshLayer( new QgsMeshLayer( string, name, QStringLiteral( "mdal" ), meshOptions ) );
262  if ( meshLayer->isValid() )
263  {
264  return meshLayer.release();
265  }
266  }
267  return nullptr;
268 }
269 
270 QgsMapLayer *QgsProcessingUtils::mapLayerFromString( const QString &string, QgsProcessingContext &context, bool allowLoadingNewLayers, LayerHint typeHint )
271 {
272  if ( string.isEmpty() )
273  return nullptr;
274 
275  // prefer project layers
276  QgsMapLayer *layer = nullptr;
277  if ( context.project() )
278  {
279  QgsMapLayer *layer = mapLayerFromStore( string, context.project()->layerStore(), typeHint );
280  if ( layer )
281  return layer;
282  }
283 
284  layer = mapLayerFromStore( string, context.temporaryLayerStore(), typeHint );
285  if ( layer )
286  return layer;
287 
288  if ( !allowLoadingNewLayers )
289  return nullptr;
290 
291  layer = loadMapLayerFromString( string, typeHint );
292  if ( layer )
293  {
294  context.temporaryLayerStore()->addMapLayer( layer );
295  return layer;
296  }
297  else
298  {
299  return nullptr;
300  }
301 }
302 
303 QgsProcessingFeatureSource *QgsProcessingUtils::variantToSource( const QVariant &value, QgsProcessingContext &context, const QVariant &fallbackValue )
304 {
305  QVariant val = value;
306  bool selectedFeaturesOnly = false;
307  if ( val.canConvert<QgsProcessingFeatureSourceDefinition>() )
308  {
309  // input is a QgsProcessingFeatureSourceDefinition - get extra properties from it
311  selectedFeaturesOnly = fromVar.selectedFeaturesOnly;
312  val = fromVar.source;
313  }
314  else if ( val.canConvert<QgsProcessingOutputLayerDefinition>() )
315  {
316  // input is a QgsProcessingOutputLayerDefinition (e.g. an output from earlier in a model) - get extra properties from it
318  val = fromVar.sink;
319  }
320 
321  if ( QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( qvariant_cast<QObject *>( val ) ) )
322  {
323  return new QgsProcessingFeatureSource( layer, context );
324  }
325 
326  QString layerRef;
327  if ( val.canConvert<QgsProperty>() )
328  {
329  layerRef = val.value< QgsProperty >().valueAsString( context.expressionContext(), fallbackValue.toString() );
330  }
331  else if ( !val.isValid() || val.toString().isEmpty() )
332  {
333  // fall back to default
334  if ( QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( qvariant_cast<QObject *>( fallbackValue ) ) )
335  {
336  return new QgsProcessingFeatureSource( layer, context );
337  }
338 
339  layerRef = fallbackValue.toString();
340  }
341  else
342  {
343  layerRef = val.toString();
344  }
345 
346  if ( layerRef.isEmpty() )
347  return nullptr;
348 
349  QgsVectorLayer *vl = qobject_cast< QgsVectorLayer *>( QgsProcessingUtils::mapLayerFromString( layerRef, context, true, Vector ) );
350  if ( !vl )
351  return nullptr;
352 
353  if ( selectedFeaturesOnly )
354  {
355  return new QgsProcessingFeatureSource( new QgsVectorLayerSelectedFeatureSource( vl ), context, true );
356  }
357  else
358  {
359  return new QgsProcessingFeatureSource( vl, context );
360  }
361 }
362 
363 bool QgsProcessingUtils::canUseLayer( const QgsMeshLayer *layer )
364 {
365  return layer && layer->dataProvider();
366 }
367 
368 bool QgsProcessingUtils::canUseLayer( const QgsRasterLayer *layer )
369 {
370  // only gdal file-based layers
371  return layer && layer->providerType() == QStringLiteral( "gdal" );
372 }
373 
374 bool QgsProcessingUtils::canUseLayer( const QgsVectorLayer *layer, const QList<int> &sourceTypes )
375 {
376  return layer &&
377  ( sourceTypes.isEmpty()
378  || ( sourceTypes.contains( QgsProcessing::TypeVectorPoint ) && layer->geometryType() == QgsWkbTypes::PointGeometry )
379  || ( sourceTypes.contains( QgsProcessing::TypeVectorLine ) && layer->geometryType() == QgsWkbTypes::LineGeometry )
380  || ( sourceTypes.contains( QgsProcessing::TypeVectorPolygon ) && layer->geometryType() == QgsWkbTypes::PolygonGeometry )
381  || ( sourceTypes.contains( QgsProcessing::TypeVectorAnyGeometry ) && layer->isSpatial() )
382  || sourceTypes.contains( QgsProcessing::TypeVector )
383  );
384 }
385 
386 QString QgsProcessingUtils::normalizeLayerSource( const QString &source )
387 {
388  QString normalized = source;
389  normalized.replace( '\\', '/' );
390  return normalized.trimmed();
391 }
392 
393 QString QgsProcessingUtils::variantToPythonLiteral( const QVariant &value )
394 {
395  if ( !value.isValid() )
396  return QStringLiteral( "None" );
397 
398  if ( value.canConvert<QgsProperty>() )
399  return QStringLiteral( "QgsProperty.fromExpression('%1')" ).arg( value.value< QgsProperty >().asExpression() );
400  else if ( value.canConvert<QgsCoordinateReferenceSystem>() )
401  {
402  if ( !value.value< QgsCoordinateReferenceSystem >().isValid() )
403  return QStringLiteral( "QgsCoordinateReferenceSystem()" );
404  else
405  return QStringLiteral( "QgsCoordinateReferenceSystem('%1')" ).arg( value.value< QgsCoordinateReferenceSystem >().authid() );
406  }
407  else if ( value.canConvert< QgsRectangle >() )
408  {
409  QgsRectangle r = value.value<QgsRectangle>();
410  return QStringLiteral( "'%1, %3, %2, %4'" ).arg( qgsDoubleToString( r.xMinimum() ),
413  qgsDoubleToString( r.yMaximum() ) );
414  }
415  else if ( value.canConvert< QgsReferencedRectangle >() )
416  {
418  return QStringLiteral( "'%1, %3, %2, %4 [%5]'" ).arg( qgsDoubleToString( r.xMinimum() ),
421  qgsDoubleToString( r.yMaximum() ), r.crs().authid() );
422  }
423  else if ( value.canConvert< QgsPointXY >() )
424  {
425  QgsPointXY r = value.value<QgsPointXY>();
426  return QStringLiteral( "'%1,%2'" ).arg( qgsDoubleToString( r.x() ),
427  qgsDoubleToString( r.y() ) );
428  }
429  else if ( value.canConvert< QgsReferencedPointXY >() )
430  {
431  QgsReferencedPointXY r = value.value<QgsReferencedPointXY>();
432  return QStringLiteral( "'%1,%2 [%3]'" ).arg( qgsDoubleToString( r.x() ),
433  qgsDoubleToString( r.y() ),
434  r.crs().authid() );
435  }
436 
437  switch ( value.type() )
438  {
439  case QVariant::Bool:
440  return value.toBool() ? QStringLiteral( "True" ) : QStringLiteral( "False" );
441 
442  case QVariant::Double:
443  return QString::number( value.toDouble() );
444 
445  case QVariant::Int:
446  case QVariant::UInt:
447  return QString::number( value.toInt() );
448 
449  case QVariant::LongLong:
450  case QVariant::ULongLong:
451  return QString::number( value.toLongLong() );
452 
453  case QVariant::List:
454  {
455  QStringList parts;
456  const QVariantList vl = value.toList();
457  for ( const QVariant &v : vl )
458  {
459  parts << variantToPythonLiteral( v );
460  }
461  return parts.join( ',' ).prepend( '[' ).append( ']' );
462  }
463 
464  default:
465  break;
466  }
467 
468  return QgsProcessingUtils::stringToPythonLiteral( value.toString() );
469 }
470 
471 QString QgsProcessingUtils::stringToPythonLiteral( const QString &string )
472 {
473  QString s = string;
474  s.replace( '\\', QStringLiteral( "\\\\" ) );
475  s.replace( '\n', QStringLiteral( "\\n" ) );
476  s.replace( '\r', QStringLiteral( "\\r" ) );
477  s.replace( '\t', QStringLiteral( "\\t" ) );
478  s.replace( '"', QStringLiteral( "\\\"" ) );
479  s.replace( '\'', QStringLiteral( "\\\'" ) );
480  s = s.prepend( '\'' ).append( '\'' );
481  return s;
482 }
483 
484 void QgsProcessingUtils::parseDestinationString( QString &destination, QString &providerKey, QString &uri, QString &layerName, QString &format, QMap<QString, QVariant> &options, bool &useWriter )
485 {
486  QRegularExpression splitRx( QStringLiteral( "^(.{3,}?):(.*)$" ) );
487  QRegularExpressionMatch match = splitRx.match( destination );
488  if ( match.hasMatch() )
489  {
490  providerKey = match.captured( 1 );
491  if ( providerKey == QStringLiteral( "postgis" ) ) // older processing used "postgis" instead of "postgres"
492  {
493  providerKey = QStringLiteral( "postgres" );
494  }
495  uri = match.captured( 2 );
496  if ( providerKey == QLatin1String( "ogr" ) )
497  {
498  QgsDataSourceUri dsUri( uri );
499  if ( !dsUri.database().isEmpty() )
500  {
501  if ( !dsUri.table().isEmpty() )
502  {
503  layerName = dsUri.table();
504  options.insert( QStringLiteral( "layerName" ), layerName );
505  }
506  uri = dsUri.database();
507  format = QgsVectorFileWriter::driverForExtension( QFileInfo( uri ).completeSuffix() );
508  }
509  options.insert( QStringLiteral( "update" ), true );
510  }
511  useWriter = false;
512  }
513  else
514  {
515  useWriter = true;
516  providerKey = QStringLiteral( "ogr" );
517  QRegularExpression splitRx( QStringLiteral( "^(.*)\\.(.*?)$" ) );
518  QRegularExpressionMatch match = splitRx.match( destination );
519  QString extension;
520  if ( match.hasMatch() )
521  {
522  extension = match.captured( 2 );
523  format = QgsVectorFileWriter::driverForExtension( extension );
524  }
525 
526  if ( format.isEmpty() )
527  {
528  format = QStringLiteral( "GPKG" );
529  destination = destination + QStringLiteral( ".gpkg" );
530  }
531 
532  options.insert( QStringLiteral( "driverName" ), format );
533  uri = destination;
534  }
535 }
536 
537 QgsFeatureSink *QgsProcessingUtils::createFeatureSink( QString &destination, QgsProcessingContext &context, const QgsFields &fields, QgsWkbTypes::Type geometryType, const QgsCoordinateReferenceSystem &crs, const QVariantMap &createOptions, QgsFeatureSink::SinkFlags sinkFlags )
538 {
539  QVariantMap options = createOptions;
540  if ( !options.contains( QStringLiteral( "fileEncoding" ) ) )
541  {
542  // no destination encoding specified, use default
543  options.insert( QStringLiteral( "fileEncoding" ), context.defaultEncoding().isEmpty() ? QStringLiteral( "system" ) : context.defaultEncoding() );
544  }
545 
546  if ( destination.isEmpty() || destination.startsWith( QLatin1String( "memory:" ) ) )
547  {
548  // strip "memory:" from start of destination
549  if ( destination.startsWith( QLatin1String( "memory:" ) ) )
550  destination = destination.mid( 7 );
551 
552  if ( destination.isEmpty() )
553  destination = QStringLiteral( "output" );
554 
555  // memory provider cannot be used with QgsVectorLayerImport - so create layer manually
556  std::unique_ptr< QgsVectorLayer > layer( QgsMemoryProviderUtils::createMemoryLayer( destination, fields, geometryType, crs ) );
557  if ( !layer || !layer->isValid() )
558  {
559  throw QgsProcessingException( QObject::tr( "Could not create memory layer" ) );
560  }
561 
562  // update destination to layer ID
563  destination = layer->id();
564 
565  // this is a factory, so we need to return a proxy
566  std::unique_ptr< QgsProcessingFeatureSink > sink( new QgsProcessingFeatureSink( layer->dataProvider(), destination, context ) );
567  context.temporaryLayerStore()->addMapLayer( layer.release() );
568 
569  return sink.release();
570  }
571  else
572  {
573  QString providerKey;
574  QString uri;
575  QString layerName;
576  QString format;
577  bool useWriter = false;
578  parseDestinationString( destination, providerKey, uri, layerName, format, options, useWriter );
579 
580  QgsFields newFields = fields;
581  if ( useWriter && providerKey == QLatin1String( "ogr" ) )
582  {
583  // use QgsVectorFileWriter for OGR destinations instead of QgsVectorLayerImport, as that allows
584  // us to use any OGR format which supports feature addition
585  QString finalFileName;
586  std::unique_ptr< QgsVectorFileWriter > writer = qgis::make_unique< QgsVectorFileWriter >( destination, options.value( QStringLiteral( "fileEncoding" ) ).toString(), newFields, geometryType, crs, format, QgsVectorFileWriter::defaultDatasetOptions( format ),
587  QgsVectorFileWriter::defaultLayerOptions( format ), &finalFileName, QgsVectorFileWriter::NoSymbology, sinkFlags );
588 
589  if ( writer->hasError() )
590  {
591  throw QgsProcessingException( QObject::tr( "Could not create layer %1: %2" ).arg( destination, writer->errorMessage() ) );
592  }
593  destination = finalFileName;
594  return new QgsProcessingFeatureSink( writer.release(), destination, context, true );
595  }
596  else
597  {
598  //create empty layer
599  std::unique_ptr< QgsVectorLayerExporter > exporter( new QgsVectorLayerExporter( uri, providerKey, newFields, geometryType, crs, true, options, sinkFlags ) );
600  if ( exporter->errorCode() )
601  {
602  throw QgsProcessingException( QObject::tr( "Could not create layer %1: %2" ).arg( destination, exporter->errorMessage() ) );
603  }
604 
605  // use destination string as layer name (eg "postgis:..." )
606  if ( !layerName.isEmpty() )
607  uri += QStringLiteral( "|layername=%1" ).arg( layerName );
608  std::unique_ptr< QgsVectorLayer > layer( new QgsVectorLayer( uri, destination, providerKey ) );
609  // update destination to layer ID
610  destination = layer->id();
611 
612  context.temporaryLayerStore()->addMapLayer( layer.release() );
613  return new QgsProcessingFeatureSink( exporter.release(), destination, context, true );
614  }
615  }
616  return nullptr;
617 }
618 
619 void QgsProcessingUtils::createFeatureSinkPython( QgsFeatureSink **sink, QString &destination, QgsProcessingContext &context, const QgsFields &fields, QgsWkbTypes::Type geometryType, const QgsCoordinateReferenceSystem &crs, const QVariantMap &options )
620 {
621  *sink = createFeatureSink( destination, context, fields, geometryType, crs, options );
622 }
623 
624 
626 {
627  QgsRectangle extent;
628  for ( const QgsMapLayer *layer : layers )
629  {
630  if ( !layer )
631  continue;
632 
633  if ( crs.isValid() )
634  {
635  //transform layer extent to target CRS
637  QgsCoordinateTransform ct( layer->crs(), crs );
639  try
640  {
641  QgsRectangle reprojExtent = ct.transformBoundingBox( layer->extent() );
642  extent.combineExtentWith( reprojExtent );
643  }
644  catch ( QgsCsException & )
645  {
646  // can't reproject... what to do here? hmmm?
647  // let's ignore this layer for now, but maybe we should just use the original extent?
648  }
649  }
650  else
651  {
652  extent.combineExtentWith( layer->extent() );
653  }
654 
655  }
656  return extent;
657 }
658 
659 QVariant QgsProcessingUtils::generateIteratingDestination( const QVariant &input, const QVariant &id, QgsProcessingContext &context )
660 {
661  if ( !input.isValid() )
662  return QStringLiteral( "memory:%1" ).arg( id.toString() );
663 
664  if ( input.canConvert<QgsProcessingOutputLayerDefinition>() )
665  {
667  QVariant newSink = generateIteratingDestination( fromVar.sink, id, context );
668  fromVar.sink = QgsProperty::fromValue( newSink );
669  return fromVar;
670  }
671  else if ( input.canConvert<QgsProperty>() )
672  {
673  QString res = input.value< QgsProperty>().valueAsString( context.expressionContext() );
674  return generateIteratingDestination( res, id, context );
675  }
676  else
677  {
678  QString res = input.toString();
679  if ( res.startsWith( QLatin1String( "memory:" ) ) )
680  {
681  return res + '_' + id.toString();
682  }
683  else
684  {
685  // assume a filename type output for now
686  // TODO - uris?
687  int lastIndex = res.lastIndexOf( '.' );
688  return res.left( lastIndex ) + '_' + id.toString() + res.mid( lastIndex );
689  }
690  }
691 }
692 
694 {
695  static QString sFolder;
696  static QMutex sMutex;
697  sMutex.lock();
698  if ( sFolder.isEmpty() )
699  {
700  QString subPath = QUuid::createUuid().toString().remove( '-' ).remove( '{' ).remove( '}' );
701  sFolder = QDir::tempPath() + QStringLiteral( "/processing_" ) + subPath;
702  if ( !QDir( sFolder ).exists() )
703  QDir().mkpath( sFolder );
704  }
705  sMutex.unlock();
706  return sFolder;
707 }
708 
709 QString QgsProcessingUtils::generateTempFilename( const QString &basename )
710 {
711  QString subPath = QUuid::createUuid().toString().remove( '-' ).remove( '{' ).remove( '}' );
712  QString path = tempFolder() + '/' + subPath;
713  if ( !QDir( path ).exists() ) //make sure the directory exists - it shouldn't, but lets be safe...
714  {
715  QDir tmpDir;
716  tmpDir.mkdir( path );
717  }
718  return path + '/' + QgsFileUtils::stringToSafeFilename( basename );
719 }
720 
722 {
723  auto getText = [map]( const QString & key )->QString
724  {
725  if ( map.contains( key ) )
726  return map.value( key ).toString();
727  return QString();
728  };
729 
730  QString s = QObject::tr( "<html><body><h2>Algorithm description</h2>\n" );
731  s += QStringLiteral( "<p>" ) + getText( QStringLiteral( "ALG_DESC" ) ) + QStringLiteral( "</p>\n" );
732 
733  QString inputs;
734 
735  const auto parameterDefinitions = algorithm->parameterDefinitions();
736  for ( const QgsProcessingParameterDefinition *def : parameterDefinitions )
737  {
738  inputs += QStringLiteral( "<h3>" ) + def->description() + QStringLiteral( "</h3>\n" );
739  inputs += QStringLiteral( "<p>" ) + getText( def->name() ) + QStringLiteral( "</p>\n" );
740  }
741  if ( !inputs.isEmpty() )
742  s += QObject::tr( "<h2>Input parameters</h2>\n" ) + inputs;
743 
744  QString outputs;
745  const auto outputDefinitions = algorithm->outputDefinitions();
746  for ( const QgsProcessingOutputDefinition *def : outputDefinitions )
747  {
748  outputs += QStringLiteral( "<h3>" ) + def->description() + QStringLiteral( "</h3>\n" );
749  outputs += QStringLiteral( "<p>" ) + getText( def->name() ) + QStringLiteral( "</p>\n" );
750  }
751  if ( !outputs.isEmpty() )
752  s += QObject::tr( "<h2>Outputs</h2>\n" ) + outputs;
753 
754  s += QLatin1String( "<br>" );
755  if ( !map.value( QStringLiteral( "ALG_CREATOR" ) ).toString().isEmpty() )
756  s += QObject::tr( "<p align=\"right\">Algorithm author: %1</p>" ).arg( getText( QStringLiteral( "ALG_CREATOR" ) ) );
757  if ( !map.value( QStringLiteral( "ALG_HELP_CREATOR" ) ).toString().isEmpty() )
758  s += QObject::tr( "<p align=\"right\">Help author: %1</p>" ).arg( getText( QStringLiteral( "ALG_HELP_CREATOR" ) ) );
759  if ( !map.value( QStringLiteral( "ALG_VERSION" ) ).toString().isEmpty() )
760  s += QObject::tr( "<p align=\"right\">Algorithm version: %1</p>" ).arg( getText( QStringLiteral( "ALG_VERSION" ) ) );
761 
762  s += QStringLiteral( "</body></html>" );
763  return s;
764 }
765 
766 QString QgsProcessingUtils::convertToCompatibleFormat( const QgsVectorLayer *vl, bool selectedFeaturesOnly, const QString &baseName, const QStringList &compatibleFormats, const QString &preferredFormat, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
767 {
768  bool requiresTranslation = false;
769 
770  // if we are only looking for selected features then we have to export back to disk,
771  // as we need to subset only selected features, a concept which doesn't exist outside QGIS!
772  requiresTranslation = requiresTranslation || selectedFeaturesOnly;
773 
774  // if the data provider is NOT ogr, then we HAVE to convert. Otherwise we run into
775  // issues with data providers like spatialite, delimited text where the format can be
776  // opened outside of QGIS, but with potentially very different behavior!
777  requiresTranslation = requiresTranslation || vl->dataProvider()->name() != QLatin1String( "ogr" );
778 
779  // if the layer has a feature filter set, then we HAVE to convert. Feature filters are
780  // a purely QGIS concept.
781  requiresTranslation = requiresTranslation || !vl->subsetString().isEmpty();
782 
783  // Check if layer is a disk based format and if so if the layer's path has a compatible filename suffix
784  if ( !requiresTranslation )
785  {
786  const QVariantMap parts = QgsProviderRegistry::instance()->decodeUri( vl->dataProvider()->name(), vl->source() );
787  if ( parts.contains( QLatin1String( "path" ) ) )
788  {
789  QFileInfo fi( parts.value( QLatin1String( "path" ) ).toString() );
790  requiresTranslation = !compatibleFormats.contains( fi.suffix(), Qt::CaseInsensitive );
791  }
792  else
793  {
794  requiresTranslation = true; // not a disk-based format
795  }
796  }
797 
798  if ( requiresTranslation )
799  {
800  QString temp = QgsProcessingUtils::generateTempFilename( baseName + '.' + preferredFormat );
801 
802  QgsVectorFileWriter writer( temp, context.defaultEncoding(),
803  vl->fields(), vl->wkbType(), vl->crs(), QgsVectorFileWriter::driverForExtension( preferredFormat ) );
804  QgsFeature f;
806  if ( selectedFeaturesOnly )
807  it = vl->getSelectedFeatures();
808  else
809  it = vl->getFeatures();
810 
811  while ( it.nextFeature( f ) )
812  {
813  if ( feedback->isCanceled() )
814  return QString();
815  writer.addFeature( f, QgsFeatureSink::FastInsert );
816  }
817  return temp;
818  }
819  else
820  {
821  return vl->source();
822  }
823 }
824 
826 {
827  QgsFields outFields = fieldsA;
828  QSet< QString > usedNames;
829  for ( const QgsField &f : fieldsA )
830  {
831  usedNames.insert( f.name().toLower() );
832  }
833 
834  for ( const QgsField &f : fieldsB )
835  {
836  if ( usedNames.contains( f.name().toLower() ) )
837  {
838  int idx = 2;
839  QString newName = f.name() + '_' + QString::number( idx );
840  while ( usedNames.contains( newName.toLower() ) )
841  {
842  idx++;
843  newName = f.name() + '_' + QString::number( idx );
844  }
845  QgsField newField = f;
846  newField.setName( newName );
847  outFields.append( newField );
848  usedNames.insert( newName.toLower() );
849  }
850  else
851  {
852  usedNames.insert( f.name().toLower() );
853  outFields.append( f );
854  }
855  }
856 
857  return outFields;
858 }
859 
860 
861 QList<int> QgsProcessingUtils::fieldNamesToIndices( const QStringList &fieldNames, const QgsFields &fields )
862 {
863  QList<int> indices;
864  if ( !fieldNames.isEmpty() )
865  {
866  indices.reserve( fieldNames.count() );
867  for ( const QString &f : fieldNames )
868  {
869  int idx = fields.lookupField( f );
870  if ( idx >= 0 )
871  indices.append( idx );
872  }
873  }
874  else
875  {
876  indices.reserve( fields.count() );
877  for ( int i = 0; i < fields.count(); ++i )
878  indices.append( i );
879  }
880  return indices;
881 }
882 
883 
884 QgsFields QgsProcessingUtils::indicesToFields( const QList<int> &indices, const QgsFields &fields )
885 {
886  QgsFields fieldsSubset;
887  for ( int i : indices )
888  fieldsSubset.append( fields.at( i ) );
889  return fieldsSubset;
890 }
891 
892 //
893 // QgsProcessingFeatureSource
894 //
895 
896 QgsProcessingFeatureSource::QgsProcessingFeatureSource( QgsFeatureSource *originalSource, const QgsProcessingContext &context, bool ownsOriginalSource )
897  : mSource( originalSource )
898  , mOwnsSource( ownsOriginalSource )
899  , mInvalidGeometryCheck( QgsWkbTypes::geometryType( mSource->wkbType() ) == QgsWkbTypes::PointGeometry
900  ? QgsFeatureRequest::GeometryNoCheck // never run geometry validity checks for point layers!
901  : context.invalidGeometryCheck() )
902  , mInvalidGeometryCallback( context.invalidGeometryCallback() )
903  , mTransformErrorCallback( context.transformErrorCallback() )
904 {}
905 
907 {
908  if ( mOwnsSource )
909  delete mSource;
910 }
911 
913 {
914  QgsFeatureRequest req( request );
915  req.setTransformErrorCallback( mTransformErrorCallback );
916 
917  if ( flags & FlagSkipGeometryValidityChecks )
919  else
920  {
921  req.setInvalidGeometryCheck( mInvalidGeometryCheck );
922  req.setInvalidGeometryCallback( mInvalidGeometryCallback );
923  }
924 
925  return mSource->getFeatures( req );
926 }
927 
929 {
930  FeatureAvailability sourceAvailability = mSource->hasFeatures();
931  if ( sourceAvailability == NoFeaturesAvailable )
932  return NoFeaturesAvailable; // never going to be features if underlying source has no features
933  else if ( mInvalidGeometryCheck == QgsFeatureRequest::GeometryNoCheck )
934  return sourceAvailability;
935  else
936  // we don't know... source has features, but these may be filtered out by invalid geometry check
937  return FeaturesMaybeAvailable;
938 }
939 
941 {
942  QgsFeatureRequest req( request );
943  req.setInvalidGeometryCheck( mInvalidGeometryCheck );
944  req.setInvalidGeometryCallback( mInvalidGeometryCallback );
945  req.setTransformErrorCallback( mTransformErrorCallback );
946  return mSource->getFeatures( req );
947 }
948 
950 {
951  return mSource->sourceCrs();
952 }
953 
955 {
956  return mSource->fields();
957 }
958 
960 {
961  return mSource->wkbType();
962 }
963 
965 {
966  return mSource->featureCount();
967 }
968 
970 {
971  return mSource->sourceName();
972 
973 }
974 
975 QSet<QVariant> QgsProcessingFeatureSource::uniqueValues( int fieldIndex, int limit ) const
976 {
977  return mSource->uniqueValues( fieldIndex, limit );
978 }
979 
980 QVariant QgsProcessingFeatureSource::minimumValue( int fieldIndex ) const
981 {
982  return mSource->minimumValue( fieldIndex );
983 }
984 
985 QVariant QgsProcessingFeatureSource::maximumValue( int fieldIndex ) const
986 {
987  return mSource->maximumValue( fieldIndex );
988 }
989 
991 {
992  return mSource->sourceExtent();
993 }
994 
996 {
997  return mSource->allFeatureIds();
998 }
999 
1001 {
1002  QgsExpressionContextScope *expressionContextScope = nullptr;
1003  QgsExpressionContextScopeGenerator *generator = dynamic_cast<QgsExpressionContextScopeGenerator *>( mSource );
1004  if ( generator )
1005  {
1006  expressionContextScope = generator->createExpressionContextScope();
1007  }
1008  return expressionContextScope;
1009 }
1010 
1011 
1012 //
1013 // QgsProcessingFeatureSink
1014 //
1015 QgsProcessingFeatureSink::QgsProcessingFeatureSink( QgsFeatureSink *originalSink, const QString &sinkName, QgsProcessingContext &context, bool ownsOriginalSink )
1016  : QgsProxyFeatureSink( originalSink )
1017  , mContext( context )
1018  , mSinkName( sinkName )
1019  , mOwnsSink( ownsOriginalSink )
1020 {}
1021 
1023 {
1024  if ( mOwnsSink )
1025  delete destinationSink();
1026 }
1027 
1028 bool QgsProcessingFeatureSink::addFeature( QgsFeature &feature, QgsFeatureSink::Flags flags )
1029 {
1030  bool result = QgsProxyFeatureSink::addFeature( feature, flags );
1031  if ( !result )
1032  mContext.feedback()->reportError( QObject::tr( "Feature could not be written to %1" ).arg( mSinkName ) );
1033  return result;
1034 }
1035 
1036 bool QgsProcessingFeatureSink::addFeatures( QgsFeatureList &features, QgsFeatureSink::Flags flags )
1037 {
1038  bool result = QgsProxyFeatureSink::addFeatures( features, flags );
1039  if ( !result )
1040  mContext.feedback()->reportError( QObject::tr( "%1 feature(s) could not be written to %2" ).arg( features.count() ).arg( mSinkName ) );
1041  return result;
1042 }
1043 
1044 bool QgsProcessingFeatureSink::addFeatures( QgsFeatureIterator &iterator, QgsFeatureSink::Flags flags )
1045 {
1046  bool result = !QgsProxyFeatureSink::addFeatures( iterator, flags );
1047  if ( !result )
1048  mContext.feedback()->reportError( QObject::tr( "Features could not be written to %1" ).arg( mSinkName ) );
1049  return result;
1050 }
int lookupField(const QString &fieldName) const
Looks up field&#39;s index from the field name.
Definition: qgsfields.cpp:324
QgsProperty sink
Sink/layer definition.
Wrapper for iterator of features from vector data provider or vector layer.
virtual QgsRectangle sourceExtent() const
Returns the extent of all geometries from the source.
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
A rectangle specified with double values.
Definition: qgsrectangle.h:41
QgsWkbTypes::Type wkbType() const override
Returns the geometry type for features returned by this source.
QString asExpression() const
Returns an expression string representing the state of the property, or an empty string if the proper...
Base class for all map layer types.
Definition: qgsmaplayer.h:64
bool loadDefaultStyle
Sets to true if the default layer style should be loaded.
QString table() const
Returns the table.
QSet< QgsFeatureId > QgsFeatureIds
Definition: qgsfeatureid.h:34
QgsFeatureRequest & setInvalidGeometryCallback(const std::function< void(const QgsFeature &)> &callback)
Sets a callback function to use when encountering an invalid geometry and invalidGeometryCheck() is s...
Base class for providing feedback from a processing algorithm.
QgsProcessingParameterDefinitions parameterDefinitions() const
Returns an ordered list of parameter definitions utilized by the algorithm.
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
virtual QgsFields fields() const =0
Returns the fields associated with features in the source.
Encapsulates settings relating to a feature sink or output raster layer for a processing algorithm...
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.
A simple feature sink which proxies feature addition on to another feature sink.
static QgsRectangle combineLayerExtents(const QList< QgsMapLayer *> &layers, const QgsCoordinateReferenceSystem &crs=QgsCoordinateReferenceSystem())
Combines the extent of several map layers.
QgsFeatureRequest & setInvalidGeometryCheck(InvalidGeometryCheck check)
Sets invalid geometry checking behavior.
QgsProcessingFeatureSource(QgsFeatureSource *originalSource, const QgsProcessingContext &context, bool ownsOriginalSource=false)
Constructor for QgsProcessingFeatureSource, accepting an original feature source originalSource and p...
This class is a composition of two QSettings instances:
Definition: qgssettings.h:58
FeatureAvailability
Possible return value for hasFeatures() to determine if a source is empty.
QgsWkbTypes::Type wkbType() const FINAL
Returns the WKBType or WKBUnknown in case of error.
Setting options for loading vector layers.
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
LayerHint
Layer type hints.
This class provides qgis with the ability to render raster datasets onto the mapcanvas.
QList< QgsFeature > QgsFeatureList
Definition: qgsfeature.h:571
Handles storage of information regarding WKB types and their properties.
Definition: qgswkbtypes.h:40
double y
Definition: qgspointxy.h:48
A class to represent a 2D point.
Definition: qgspointxy.h:43
A QgsPointXY with associated coordinate reference system.
QgsFeatureIds allFeatureIds() const override
Returns a list of all feature IDs for features present in the source.
virtual QgsWkbTypes::Type wkbType() const =0
Returns the geometry type for features returned by this source.
An interface for objects which accept features via addFeature(s) methods.
#define Q_NOWARN_DEPRECATED_PUSH
Definition: qgis.h:624
static QList< QgsRasterLayer *> compatibleRasterLayers(QgsProject *project, bool sort=true)
Returns a list of raster layers from a project which are compatible with the processing framework...
static QString stringToPythonLiteral(const QString &string)
Converts a string to a Python string literal.
QgsWkbTypes::GeometryType geometryType() const
Returns point, line or polygon.
QgsFeatureSource subclass which proxies methods to an underlying QgsFeatureSource, modifying results according to the settings in a QgsProcessingContext.
Container of fields for a vector layer.
Definition: qgsfields.h:42
void setName(const QString &name)
Set the field name.
Definition: qgsfield.cpp:141
bool addFeatures(QgsFeatureList &features, QgsFeatureSink::Flags flags=nullptr) override
Adds a list of features to the sink.
QVariantMap decodeUri(const QString &providerKey, const QString &uri)
Breaks a provider data source URI into its component paths (e.g.
static QString driverForExtension(const QString &extension)
Returns the OGR driver name for a specified file extension.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request, Flags flags) const
Returns an iterator for the features in the source, respecting the supplied feature flags...
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...
Setting options for loading mesh layers.
Definition: qgsmeshlayer.h:97
A convenience class for writing vector files to disk.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:55
const QgsCoordinateReferenceSystem & crs
QVariant maximumValue(int fieldIndex) const override
Returns the maximum value for an attribute column or an invalid variant in case of error...
static QString convertToCompatibleFormat(const QgsVectorLayer *layer, bool selectedFeaturesOnly, const QString &baseName, const QStringList &compatibleFormats, const QString &preferredFormat, QgsProcessingContext &context, QgsProcessingFeedback *feedback)
Converts a source vector layer to a file path to a vector layer of compatible format.
QgsRectangle sourceExtent() const override
Returns the extent of all geometries from the source.
static QString normalizeLayerSource(const QString &source)
Normalizes a layer source string for safe comparison across different operating system environments...
Abstract base class for processing algorithms.
int count() const
Returns number of items.
Definition: qgsfields.cpp:133
bool isSpatial() const FINAL
Returns true if this is a geometry layer and false in case of NoGeometry (table only) or UnknownGeome...
QgsMapLayerStore * layerStore()
Returns a pointer to the project&#39;s internal layer store.
virtual QString name() const =0
Returns a provider name.
QgsProject * project() const
Returns the project in which the algorithm is being executed.
bool selectedFeaturesOnly
True if only selected features in the source should be used by algorithms.
QgsField at(int i) const
Gets field at particular index (must be in range 0..N-1)
Definition: qgsfields.cpp:163
Added in 3.2.
Definition: qgsmaplayer.h:111
bool addFeatures(QgsFeatureList &features, QgsFeatureSink::Flags flags=nullptr) override
Adds a list of features to the sink.
QgsCoordinateReferenceSystem crs() const
Returns the associated coordinate reference system, or an invalid CRS if no reference system is set...
QSet< QVariant > uniqueValues(int fieldIndex, int limit=-1) const override
Returns the set of unique values contained within the specified fieldIndex from this source...
static QgsFeatureSink * createFeatureSink(QString &destination, QgsProcessingContext &context, const QgsFields &fields, QgsWkbTypes::Type geometryType, const QgsCoordinateReferenceSystem &crs, const QVariantMap &createOptions=QVariantMap(), QgsFeatureSink::SinkFlags sinkFlags=nullptr)
Creates a feature sink ready for adding features.
QgsProcessingFeedback * feedback()
Returns the associated feedback object.
static QList< int > fieldNamesToIndices(const QStringList &fieldNames, const QgsFields &fields)
Returns a list of field indices parsed from the given list of field names.
Type
The WKB type describes the number of dimensions a geometry has.
Definition: qgswkbtypes.h:68
static QgsProviderRegistry * instance(const QString &pluginPath=QString())
Means of accessing canonical single instance.
virtual QVariant minimumValue(int fieldIndex) const
Returns the minimum value for an attribute column or an invalid variant in case of error...
QgsFields fields() const override
Returns the fields associated with features in the source.
static QgsProperty fromValue(const QVariant &value, bool isActive=true)
Returns a new StaticProperty created from the specified value.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
QgsMapLayerStore * temporaryLayerStore()
Returns a reference to the layer store used for storing temporary layers during algorithm execution...
QgsProperty source
Source definition.
static QStringList defaultLayerOptions(const QString &driverName)
Returns a list of the default layer options for a specified driver.
QVariant minimumValue(int fieldIndex) const override
Returns the minimum value for an attribute column or an invalid variant in case of error...
QgsFeatureIterator getSelectedFeatures(QgsFeatureRequest request=QgsFeatureRequest()) const
Returns an iterator of the selected features.
static QgsFields combineFields(const QgsFields &fieldsA, const QgsFields &fieldsB)
Combines two field lists, avoiding duplicate field names (in a case-insensitive manner).
static QString stringToSafeFilename(const QString &string)
Converts a string to a safe filename, replacing characters which are not safe for filenames with an &#39;...
bool loadDefaultStyle
Sets to true if the default layer style should be loaded.
QgsCoordinateReferenceSystem sourceCrs() const override
Returns the coordinate reference system for features in the source.
QString providerType() const
[ data provider interface ] Which provider is being used for this Raster Layer?
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
Definition: qgis.h:225
There are certainly no features available in this source.
This class wraps a request for features to a vector layer (or directly its vector data provider)...
Custom exception class for processing related exceptions.
Definition: qgsexception.h:82
QString subsetString
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...
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
Reads and writes project states.
Definition: qgsproject.h:89
Vector polygon layers.
Definition: qgsprocessing.h:50
No invalid geometry checking.
A QgsRectangle with associated coordinate reference system.
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=nullptr) override
Adds a single feature to the sink.
Encapsulate a field in an attribute table or data source.
Definition: qgsfield.h:48
QgsMeshDataProvider * dataProvider() override
Returns the layer&#39;s data provider, it may be null.
Single scope for storing variables and functions for use within a QgsExpressionContext.
static QgsProcessingFeatureSource * variantToSource(const QVariant &value, QgsProcessingContext &context, const QVariant &fallbackValue=QVariant())
Converts a variant value to a new feature source.
A store for object properties.
Definition: qgsproperty.h:229
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
virtual QSet< QVariant > uniqueValues(int fieldIndex, int limit=-1) const
Returns the set of unique values contained within the specified fieldIndex from this source...
QgsExpressionContext & expressionContext()
Returns the expression context.
QgsRectangle extent() const FINAL
Returns the extent of the layer.
double x
Definition: qgspointxy.h:47
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...
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...
A convenience class for exporting vector layers to a destination data provider.
static QString tempFolder()
Returns a session specific processing temporary folder for use in processing algorithms.
virtual QgsCoordinateReferenceSystem sourceCrs() const =0
Returns the coordinate reference system for features in the source.
QgsExpressionContextScope * createExpressionContextScope() const
Returns an expression context scope suitable for this source.
Encapsulates settings relating to a feature source input to a processing algorithm.
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
Definition: qgsrectangle.h:177
QgsProcessingOutputDefinitions outputDefinitions() const
Returns an ordered list of output definitions utilized by the algorithm.
static QString generateTempFilename(const QString &basename)
Returns a temporary filename for a given file, putting it into a temporary folder (creating that fold...
double xMaximum() const
Returns the x maximum value (right side of rectangle).
Definition: qgsrectangle.h:162
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle...
Definition: qgsrectangle.h:359
Base class for the definition of processing outputs.
#define Q_NOWARN_DEPRECATED_POP
Definition: qgis.h:625
static QString variantToPythonLiteral(const QVariant &value)
Converts a variant to a Python literal.
QgsProxyFeatureSink subclass which reports feature addition errors to a QgsProcessingContext.
static QString formatHelpMapAsHtml(const QVariantMap &map, const QgsProcessingAlgorithm *algorithm)
Returns a HTML formatted version of the help text encoded in a variant map for a specified algorithm...
static QgsFields indicesToFields(const QList< int > &indices, const QgsFields &fields)
Returns a subset of fields based on the indices of desired fields.
QVector< T > layers() const
Returns a list of registered map layers with a specified layer type.
Definition: qgsproject.h:767
virtual QgsExpressionContextScope * createExpressionContextScope() const =0
This method needs to be reimplemented in all classes which implement this interface and return an exp...
QMap< QString, QgsMapLayer * > mapLayers() const
Returns a map of all layers by layer ID.
QgsFeatureSource subclass for the selected features from a QgsVectorLayer.
QgsMapLayer * addMapLayer(QgsMapLayer *layer, bool takeOwnership=true)
Add a layer to the store.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition: qgsfeedback.h:54
Vector point layers.
Definition: qgsprocessing.h:48
Abstract interface for generating an expression context scope.
QString defaultEncoding() const
Returns the default encoding to use for newly created files.
An interface for objects which provide features via a getFeatures method.
QString source() const
Returns the source for the layer.
void setValue(const QString &key, const QVariant &value, QgsSettings::Section section=QgsSettings::NoSection)
Sets the value of setting key to value.
QgsFeatureSource::FeatureAvailability hasFeatures() const override
Determines if there are any features available in the source.
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...
QString sourceName() const override
Returns a friendly display name for the source.
static QStringList defaultDatasetOptions(const QString &driverName)
Returns a list of the default dataset options for a specified driver.
This class represents a coordinate reference system (CRS).
Base class for the definition of processing parameters.
Vector line layers.
Definition: qgsprocessing.h:49
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
Definition: qgsprocessing.h:53
Class for doing transforms between two map coordinate systems.
double xMinimum() const
Returns the x minimum value (left side of rectangle).
Definition: qgsrectangle.h:167
double yMaximum() const
Returns the y maximum value (top side of rectangle).
Definition: qgsrectangle.h:172
Represents a mesh layer supporting display of data on structured or unstructured meshes.
Definition: qgsmeshlayer.h:89
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Query the layer for features specified in request.
QString name
Definition: qgsmaplayer.h:68
A storage object for map layers, in which the layers are owned by the store and have their lifetime b...
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=nullptr) override
Adds a single feature to the sink.
Custom exception class for Coordinate Reference System related exceptions.
Definition: qgsexception.h:65
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.
virtual QVariant maximumValue(int fieldIndex) const
Returns the maximum value for an attribute column or an invalid variant in case of error...
There may be features available in this source.
QgsVectorDataProvider * dataProvider() FINAL
Returns the layer&#39;s data provider, it may be null.
bool nextFeature(QgsFeature &f)
QgsFeatureSink * destinationSink()
Returns the destination QgsFeatureSink which the proxy will forward features to.
static QgsMapLayer * mapLayerFromString(const QString &string, QgsProcessingContext &context, bool allowLoadingNewLayers=true, LayerHint typeHint=UnknownType)
Interprets a string as a map layer within the supplied context.
virtual QString sourceName() const =0
Returns a friendly display name for the source.
long featureCount() const override
Returns the number of features contained in the source, or -1 if the feature count is unknown...
Class for storing the component parts of a PostgreSQL/RDBMS datasource URI.
Represents a vector layer which manages a vector based data sets.
virtual QgsFeatureIds allFeatureIds() const
Returns a list of all feature IDs for features present in the source.
Contains information about the context in which a processing algorithm is executed.
virtual FeatureAvailability hasFeatures() const
Determines if there are any features available in the source.
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
QString database() const
Returns the database.
Any vector layer with geometry.
Definition: qgsprocessing.h:47
QString authid() const
Returns the authority identifier for the CRS.
Setting options for loading raster layers.
QgsCoordinateReferenceSystem crs
Definition: qgsmaplayer.h:71
virtual QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const =0
Returns an iterator for the features in the source.
virtual long featureCount() const =0
Returns the number of features contained in the source, or -1 if the feature count is unknown...
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
QgsProcessingFeatureSink(QgsFeatureSink *originalSink, const QString &sinkName, QgsProcessingContext &context, bool ownsOriginalSink=false)
Constructor for QgsProcessingFeatureSink, accepting an original feature sink originalSink and process...