QGIS API Documentation
3.16.0-Hannover (43b64b13f3)
|
Go to the documentation of this file.
41 return QList<QgsRasterLayer *>();
43 QList<QgsRasterLayer *> layers;
48 if ( canUseLayer( l ) )
56 return QString::localeAwareCompare( a->name(), b->name() ) < 0;
65 return QList<QgsVectorLayer *>();
67 QList<QgsVectorLayer *> layers;
71 if ( canUseLayer( l, geometryTypes ) )
79 return QString::localeAwareCompare( a->name(), b->name() ) < 0;
88 return QList<QgsMeshLayer *>();
90 QList<QgsMeshLayer *> layers;
94 if ( canUseLayer( l ) )
102 return QString::localeAwareCompare( a->name(), b->name() ) < 0;
111 return QList<QgsMapLayer *>();
113 QList<QgsMapLayer *> layers;
131 return QString::localeAwareCompare( a->name(), b->name() ) < 0;
139 return QStringLiteral(
"%1://%2" ).arg( providerKey, uri );
144 QRegularExpression re( QStringLiteral(
"^(\\w+?):\\/\\/(.+)$" ) );
145 const QRegularExpressionMatch match = re.match(
string );
146 if ( !match.hasMatch() )
149 providerKey = match.captured( 1 );
150 uri = match.captured( 2 );
158 if ( !store ||
string.isEmpty() )
161 QList< QgsMapLayer * > layers = store->
mapLayers().values();
163 layers.erase( std::remove_if( layers.begin(), layers.end(), [](
QgsMapLayer * layer )
165 switch ( layer->type() )
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:
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:
183 auto isCompatibleType = [typeHint](
QgsMapLayer * l ) ->
bool
187 case LayerHint::UnknownType:
190 case LayerHint::Vector:
193 case LayerHint::Raster:
196 case LayerHint::Mesh:
204 if ( isCompatibleType( l ) && l->id() == string )
209 if ( isCompatibleType( l ) && l->name() == string )
214 if ( isCompatibleType( l ) && normalizeLayerSource( l->source() ) == normalizeLayerSource(
string ) )
230 if ( !useProvider || ( provider == QLatin1String(
"ogr" ) || provider == QLatin1String(
"gdal" ) || provider == QLatin1String(
"mdal" ) ) )
232 QStringList components = uri.split(
'|' );
233 if ( components.isEmpty() )
237 if ( QFileInfo::exists( uri ) )
238 fi = QFileInfo( uri );
239 else if ( QFileInfo::exists( components.at( 0 ) ) )
240 fi = QFileInfo( components.at( 0 ) );
243 name = fi.baseName();
254 options.loadDefaultStyle =
false;
255 options.skipCrsValidation =
true;
257 std::unique_ptr< QgsVectorLayer > layer;
260 layer = qgis::make_unique<QgsVectorLayer>( uri, name, provider, options );
265 layer = qgis::make_unique<QgsVectorLayer>( uri, name, QStringLiteral(
"ogr" ), options );
267 if ( layer->isValid() )
269 return layer.release();
278 std::unique_ptr< QgsRasterLayer > rasterLayer;
281 rasterLayer = qgis::make_unique< QgsRasterLayer >( uri, name, provider, rasterOptions );
286 rasterLayer = qgis::make_unique< QgsRasterLayer >( uri, name, QStringLiteral(
"gdal" ), rasterOptions );
289 if ( rasterLayer->isValid() )
291 return rasterLayer.release();
299 std::unique_ptr< QgsMeshLayer > meshLayer;
302 meshLayer = qgis::make_unique< QgsMeshLayer >( uri, name, provider, meshOptions );
306 meshLayer = qgis::make_unique< QgsMeshLayer >( uri, name, QStringLiteral(
"mdal" ), meshOptions );
308 if ( meshLayer->isValid() )
310 return meshLayer.release();
318 if (
string.isEmpty() )
323 if (
auto *lProject = context.
project() )
325 QgsMapLayer *layer = mapLayerFromStore(
string, lProject->layerStore(), typeHint );
334 if ( !allowLoadingNewLayers )
337 layer = loadMapLayerFromString(
string, context.
transformContext(), typeHint );
351 QVariant val = value;
352 bool selectedFeaturesOnly =
false;
353 long long featureLimit = -1;
354 bool overrideGeometryCheck =
false;
363 overrideGeometryCheck = fromVar.
flags & QgsProcessingFeatureSourceDefinition::Flag::FlagOverrideDefaultGeometryCheck;
373 if (
QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( qvariant_cast<QObject *>( val ) ) )
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();
386 else if ( !val.isValid() || val.toString().isEmpty() )
389 if (
QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( qvariant_cast<QObject *>( fallbackValue ) ) )
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();
397 layerRef = fallbackValue.toString();
401 layerRef = val.toString();
404 if ( layerRef.isEmpty() )
411 std::unique_ptr< QgsProcessingFeatureSource> source;
412 if ( selectedFeaturesOnly )
418 source = qgis::make_unique< QgsProcessingFeatureSource >( vl, context,
false, featureLimit );
421 if ( overrideGeometryCheck )
422 source->setInvalidGeometryCheck( geometryCheck );
423 return source.release();
428 QVariant val = value;
454 if (
QgsMapLayer *layer = qobject_cast< QgsMapLayer * >( qvariant_cast<QObject *>( val ) ) )
460 if ( !val.isValid() )
466 QString crsText = val.toString();
467 if ( crsText.isEmpty() )
468 crsText = fallbackValue.toString();
470 if ( crsText.isEmpty() )
474 if ( context.
project() && crsText.compare( QLatin1String(
"ProjectCrs" ), Qt::CaseInsensitive ) == 0 )
487 bool QgsProcessingUtils::canUseLayer(
const QgsMeshLayer *layer )
494 return layer && layer->
isValid();
497 bool QgsProcessingUtils::canUseLayer(
const QgsRasterLayer *layer )
499 return layer && layer->
isValid();
502 bool QgsProcessingUtils::canUseLayer(
const QgsVectorLayer *layer,
const QList<int> &sourceTypes )
504 return layer && layer->
isValid() &&
505 ( sourceTypes.isEmpty()
516 QString normalized = source;
517 normalized.replace(
'\\',
'/' );
518 return normalized.trimmed();
523 if ( !value.isValid() )
524 return QStringLiteral(
"None" );
527 return QStringLiteral(
"QgsProperty.fromExpression('%1')" ).arg( value.value<
QgsProperty >().
asExpression() );
531 return QStringLiteral(
"QgsCoordinateReferenceSystem()" );
565 switch ( value.type() )
568 return value.toBool() ? QStringLiteral(
"True" ) : QStringLiteral(
"False" );
570 case QVariant::Double:
571 return QString::number( value.toDouble() );
575 return QString::number( value.toInt() );
577 case QVariant::LongLong:
578 case QVariant::ULongLong:
579 return QString::number( value.toLongLong() );
584 const QVariantList vl = value.toList();
585 for (
const QVariant &v : vl )
589 return parts.join(
',' ).prepend(
'[' ).append(
']' );
594 const QVariantMap map = value.toMap();
596 parts.reserve( map.size() );
597 for (
auto it = map.constBegin(); it != map.constEnd(); ++it )
601 return parts.join(
',' ).prepend(
'{' ).append(
'}' );
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(
'\'' );
624 void QgsProcessingUtils::parseDestinationString( QString &destination, QString &providerKey, QString &uri, QString &layerName, QString &format, QMap<QString, QVariant> &options,
bool &useWriter, QString &extension )
631 QRegularExpression splitRx( QStringLiteral(
"^(.{3,}?):(.*)$" ) );
632 QRegularExpressionMatch match = splitRx.match( destination );
633 if ( match.hasMatch() )
635 providerKey = match.captured( 1 );
636 uri = match.captured( 2 );
643 if ( providerKey == QLatin1String(
"postgis" ) )
645 providerKey = QStringLiteral(
"postgres" );
647 if ( providerKey == QLatin1String(
"ogr" ) )
650 if ( !dsUri.database().isEmpty() )
652 if ( !dsUri.table().isEmpty() )
654 layerName = dsUri.table();
655 options.insert( QStringLiteral(
"layerName" ), layerName );
657 uri = dsUri.database();
658 extension = QFileInfo( uri ).completeSuffix();
660 options.insert( QStringLiteral(
"driverName" ), format );
664 extension = QFileInfo( uri ).completeSuffix();
667 options.insert( QStringLiteral(
"update" ),
true );
674 providerKey = QStringLiteral(
"ogr" );
676 QRegularExpression splitRx( QStringLiteral(
"^(.*)\\.(.*?)$" ) );
677 QRegularExpressionMatch match = splitRx.match( destination );
678 if ( match.hasMatch() )
680 extension = match.captured( 2 );
684 if ( format.isEmpty() )
686 format = QStringLiteral(
"GPKG" );
687 destination = destination + QStringLiteral(
".gpkg" );
690 options.insert( QStringLiteral(
"driverName" ), format );
697 QVariantMap options = createOptions;
698 if ( !options.contains( QStringLiteral(
"fileEncoding" ) ) )
704 if ( destination.isEmpty() || destination.startsWith( QLatin1String(
"memory:" ) ) )
707 if ( destination.startsWith( QLatin1String(
"memory:" ) ) )
708 destination = destination.mid( 7 );
710 if ( destination.isEmpty() )
711 destination = QStringLiteral(
"output" );
715 if ( !layer || !layer->isValid() )
723 destination = layer->id();
726 std::unique_ptr< QgsProcessingFeatureSink > sink(
new QgsProcessingFeatureSink( layer->dataProvider(), destination, context ) );
729 return sink.release();
738 bool useWriter =
false;
739 parseDestinationString( destination, providerKey, uri, layerName, format, options, useWriter, extension );
742 if ( useWriter && providerKey == QLatin1String(
"ogr" ) )
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();
755 if ( remappingDefinition )
759 std::unique_ptr< QgsVectorLayer > vl = qgis::make_unique< QgsVectorLayer >( destination );
764 newFields = vl->fields();
774 if ( writer->hasError() )
776 throw QgsProcessingException( QObject::tr(
"Could not create layer %1: %2" ).arg( destination, writer->errorMessage() ) );
778 destination = finalFileName;
779 if ( !saveOptions.
layerName.isEmpty() && !finalLayerName.isEmpty() )
780 destination += QStringLiteral(
"|layername=%1" ).arg( finalLayerName );
782 if ( remappingDefinition )
784 std::unique_ptr< QgsRemappingProxyFeatureSink > remapSink = qgis::make_unique< QgsRemappingProxyFeatureSink >( *remappingDefinition, writer.release(),
true );
795 if ( remappingDefinition )
800 if ( !layerName.isEmpty() )
803 parts.insert( QStringLiteral(
"layerName" ), layerName );
807 std::unique_ptr< QgsVectorLayer > layer = qgis::make_unique<QgsVectorLayer>( uri, destination, providerKey, layerOptions );
809 destination = layer->id();
810 if ( layer->isValid() )
817 std::unique_ptr< QgsRemappingProxyFeatureSink > remapSink = qgis::make_unique< QgsRemappingProxyFeatureSink >( *remappingDefinition, layer->dataProvider(),
false );
827 std::unique_ptr< QgsVectorLayerExporter > exporter = qgis::make_unique<QgsVectorLayerExporter>( uri, providerKey, newFields, geometryType,
crs,
true, options, sinkFlags );
828 if ( exporter->errorCode() )
830 throw QgsProcessingException( QObject::tr(
"Could not create layer %1: %2" ).arg( destination, exporter->errorMessage() ) );
834 if ( !layerName.isEmpty() )
835 uri += QStringLiteral(
"|layername=%1" ).arg( layerName );
892 if ( !input.isValid() )
893 return QStringLiteral(
"memory:%1" ).arg(
id.toString() );
909 QString res = input.toString();
915 else if ( res.startsWith( QLatin1String(
"memory:" ) ) )
917 return QString( res +
'_' +
id.toString() );
923 int lastIndex = res.lastIndexOf(
'.' );
924 return QString( res.left( lastIndex ) +
'_' +
id.toString() + res.mid( lastIndex ) );
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() )
943 if ( sTempFolders.empty() )
945 const QString templatePath = QStringLiteral(
"%1/processing_XXXXXX" ).arg( QDir::tempPath() );
946 std::unique_ptr< QTemporaryDir >
tempFolder = qgis::make_unique< QTemporaryDir >( templatePath );
948 sTempFolders.emplace_back( std::move(
tempFolder ) );
951 else if ( sFolder.isEmpty() || !sFolder.startsWith( basePath ) || sTempFolders.empty() )
953 if ( !QDir().exists( basePath ) )
954 QDir().mkpath( basePath );
956 const QString templatePath = QStringLiteral(
"%1/processing_XXXXXX" ).arg( basePath );
957 std::unique_ptr< QTemporaryDir >
tempFolder = qgis::make_unique< QTemporaryDir >( templatePath );
959 sTempFolders.emplace_back( std::move(
tempFolder ) );
966 QString subPath = QUuid::createUuid().toString().remove(
'-' ).remove(
'{' ).remove(
'}' );
968 if ( !QDir( path ).exists() )
971 tmpDir.mkdir( path );
978 auto getText = [map](
const QString & key )->QString
980 if ( map.contains( key ) )
981 return map.value( key ).toString();
985 QString s = QObject::tr(
"<html><body><h2>Algorithm description</h2>\n" );
986 s += QStringLiteral(
"<p>" ) + getText( QStringLiteral(
"ALG_DESC" ) ) + QStringLiteral(
"</p>\n" );
993 inputs += QStringLiteral(
"<h3>" ) + def->description() + QStringLiteral(
"</h3>\n" );
994 inputs += QStringLiteral(
"<p>" ) + getText( def->name() ) + QStringLiteral(
"</p>\n" );
996 if ( !inputs.isEmpty() )
997 s += QObject::tr(
"<h2>Input parameters</h2>\n" ) + inputs;
1003 outputs += QStringLiteral(
"<h3>" ) + def->description() + QStringLiteral(
"</h3>\n" );
1004 outputs += QStringLiteral(
"<p>" ) + getText( def->name() ) + QStringLiteral(
"</p>\n" );
1006 if ( !outputs.isEmpty() )
1007 s += QObject::tr(
"<h2>Outputs</h2>\n" ) + outputs;
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" ) ) );
1017 s += QLatin1String(
"</body></html>" );
1022 long long featureLimit )
1024 bool requiresTranslation =
false;
1028 requiresTranslation = requiresTranslation || selectedFeaturesOnly;
1031 requiresTranslation = requiresTranslation || featureLimit != -1;
1036 requiresTranslation = requiresTranslation || vl->
providerType() != QLatin1String(
"ogr" );
1040 requiresTranslation = requiresTranslation || !vl->
subsetString().isEmpty();
1044 requiresTranslation = requiresTranslation || vl->
source().startsWith( QLatin1String(
"/vsi" ) );
1048 if ( !requiresTranslation )
1051 if ( parts.contains( QStringLiteral(
"path" ) ) )
1053 diskPath = parts.value( QStringLiteral(
"path" ) ).toString();
1054 QFileInfo fi( diskPath );
1055 requiresTranslation = !compatibleFormats.contains( fi.suffix(), Qt::CaseInsensitive );
1059 const QString srcLayerName = parts.value( QStringLiteral(
"layerName" ) ).toString();
1063 *layerName = srcLayerName;
1068 requiresTranslation = requiresTranslation || ( !srcLayerName.isEmpty() && srcLayerName != fi.baseName() );
1073 requiresTranslation =
true;
1077 if ( requiresTranslation )
1087 if ( featureLimit != -1 )
1089 if ( selectedFeaturesOnly )
1096 if ( selectedFeaturesOnly )
1124 return convertToCompatibleFormatInternal( layer, selectedFeaturesOnly, baseName, compatibleFormats, preferredFormat, context, feedback, &layerName, featureLimit );
1130 QSet< QString > usedNames;
1131 for (
const QgsField &f : fieldsA )
1133 usedNames.insert( f.name().toLower() );
1136 for (
const QgsField &f : fieldsB )
1139 newField.
setName( fieldsBPrefix + f.name() );
1140 if ( usedNames.contains( newField.
name().toLower() ) )
1143 QString newName = newField.
name() +
'_' + QString::number( idx );
1144 while ( usedNames.contains( newName.toLower() ) )
1147 newName = newField.
name() +
'_' + QString::number( idx );
1150 outFields.
append( newField );
1154 outFields.
append( newField );
1156 usedNames.insert( newField.
name() );
1166 if ( !fieldNames.isEmpty() )
1168 indices.reserve( fieldNames.count() );
1169 for (
const QString &f : fieldNames )
1173 indices.append( idx );
1178 indices.reserve( fields.
count() );
1179 for (
int i = 0; i < fields.
count(); ++i )
1180 indices.append( i );
1189 for (
int i : indices )
1190 fieldsSubset.
append( fields.
at( i ) );
1191 return fieldsSubset;
1197 const int setting = settings.
value( QStringLiteral(
"Processing/Configuration/DefaultOutputVectorLayerExt" ), -1 ).toInt();
1198 if ( setting == -1 )
1199 return QStringLiteral(
"gpkg" );
1206 const int setting = settings.
value( QStringLiteral(
"Processing/Configuration/DefaultOutputRasterLayerExt" ), -1 ).toInt();
1207 if ( setting == -1 )
1208 return QStringLiteral(
"tif" );
1217 : mSource( originalSource )
1218 , mOwnsSource( ownsOriginalSource )
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 )
1248 if ( mFeatureLimit != -1 && req.
limit() != -1 )
1249 req.
setLimit( std::min(
static_cast< long long >( req.
limit() ), mFeatureLimit ) );
1250 else if ( mFeatureLimit != -1 )
1262 return sourceAvailability;
1275 if ( mFeatureLimit != -1 && req.
limit() != -1 )
1276 req.
setLimit( std::min(
static_cast< long long >( req.
limit() ), mFeatureLimit ) );
1277 else if ( mFeatureLimit != -1 )
1290 return mSource->
fields();
1300 if ( mFeatureLimit == -1 )
1303 return std::min( mFeatureLimit,
static_cast< long long >( mSource->
featureCount() ) );
1350 return expressionContextScope;
1355 mInvalidGeometryCheck = method;
1356 switch ( mInvalidGeometryCheck )
1359 mInvalidGeometryCallback =
nullptr;
1363 mInvalidGeometryCallback = mInvalidGeometryCallbackSkip;
1367 mInvalidGeometryCallback = mInvalidGeometryCallbackAbort;
1379 , mContext( context )
1380 , mSinkName( sinkName )
1381 , mOwnsSink( ownsOriginalSink )
1393 if ( !result && mContext.
feedback() )
1396 if ( !error.isEmpty() )
1397 mContext.
feedback()->
reportError( QObject::tr(
"Feature could not be written to %1: %2" ).arg( mSinkName, error ) );
1399 mContext.
feedback()->
reportError( QObject::tr(
"Feature could not be written to %1" ).arg( mSinkName ) );
1407 if ( !result && mContext.
feedback() )
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 ) );
1413 mContext.
feedback()->
reportError( QObject::tr(
"%1 feature(s) could not be written to %2" ).arg( features.count() ).arg( mSinkName ) );
1421 if ( !result && mContext.
feedback() )
1424 if ( !error.isEmpty() )
1425 mContext.
feedback()->
reportError( QObject::tr(
"Features could not be written to %1: %2" ).arg( mSinkName, error ) );
1427 mContext.
feedback()->
reportError( QObject::tr(
"Features could not be written to %1" ).arg( mSinkName ) );
bool selectedFeaturesOnly
true if only selected features in the source should be used by algorithms.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
~QgsProcessingFeatureSource() override
QSet< QVariant > uniqueValues(int fieldIndex, int limit=-1) const override
Returns the set of unique values contained within the specified fieldIndex from this source.
QgsCoordinateReferenceSystem crs
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.
QVariant minimumValue(int fieldIndex) const override
Returns the minimum value for an attribute column or an invalid variant in case of error.
virtual QVariant minimumValue(int fieldIndex) const
Returns the minimum value for an attribute column or an invalid variant in case of error.
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.
virtual SpatialIndexPresence hasSpatialIndex() const
Returns an enum value representing the presence of a valid spatial index on the source,...
QVector< T > layers() const
Returns a list of registered map layers with a specified layer type.
static QString defaultVectorExtension()
Returns the default vector extension to use, in the absence of all other constraints (e....
Class for storing the component parts of a RDBMS data source URI (e.g.
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.
virtual QgsCoordinateReferenceSystem sourceCrs() const =0
Returns the coordinate reference system for features in the source.
QgsFeatureRequest & setInvalidGeometryCheck(InvalidGeometryCheck check)
Sets invalid geometry checking behavior.
Implements a map layer that is dedicated to rendering of vector tiles.
Contains information about the context in which a coordinate transform is executed.
Q_INVOKABLE QgsWkbTypes::Type wkbType() const FINAL
Returns the WKBType or WKBUnknown in case of error.
void setDestinationWkbType(QgsWkbTypes::Type type)
Sets the WKB geometry type for the destination.
Options to pass to writeAsVectorFormat()
A store for object properties.
QgsMapLayer * addMapLayer(QgsMapLayer *layer, bool takeOwnership=true)
Add a layer to the store.
@ GeometryAbortOnInvalid
Close iterator on encountering any features with invalid geometry. This requires a slow geometry vali...
static QgsProcessingFeatureSource * variantToSource(const QVariant &value, QgsProcessingContext &context, const QVariant &fallbackValue=QVariant())
Converts a variant value to a new feature source.
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle.
@ CreateOrOverwriteFile
Create or overwrite file.
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.
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
void setDestinationCrs(const QgsCoordinateReferenceSystem &destination)
Sets the destination crs used for reprojecting incoming features to the sink's destination CRS.
Defines the parameters used to remap features when creating a QgsRemappingProxyFeatureSink.
QgsProject * project() const
Returns the project in which the algorithm is being executed.
A QgsRectangle with associated coordinate reference system.
Base class for providing feedback from a processing algorithm.
QgsRectangle sourceExtent() const override
Returns the extent of all geometries from the source.
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
QgsFeatureSink * destinationSink()
Returns the destination QgsFeatureSink which the proxy will forward features to.
const QgsCoordinateReferenceSystem & crs
bool skipCrsValidation
Controls whether the layer is allowed to have an invalid/unknown CRS.
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
A simple feature sink which proxies feature addition on to another feature sink.
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.
@ TypeVectorPolygon
Vector polygon layers.
QgsProcessingFeatureSource(QgsFeatureSource *originalSource, const QgsProcessingContext &context, bool ownsOriginalSource=false, long long featureLimit=-1)
Constructor for QgsProcessingFeatureSource, accepting an original feature source originalSource and p...
static QString normalizeLayerSource(const QString &source)
Normalizes a layer source string for safe comparison across different operating system environments.
QgsExpressionContextScope * createExpressionContextScope() const
Returns an expression context scope suitable for this source.
QString encodeUri(const QString &providerKey, const QVariantMap &parts)
Reassembles a provider data source URI from its component paths (e.g.
int count() const
Returns number of items.
Container of fields for a vector layer.
double yMinimum() const SIP_HOLDGIL
Returns the y minimum value (bottom side of rectangle).
QString asExpression() const
Returns an expression string representing the state of the property, or an empty string if the proper...
static QgsFields indicesToFields(const QList< int > &indices, const QgsFields &fields)
Returns a subset of fields based on the indices of desired fields.
An interface for objects which provide features via a getFeatures method.
bool isSpatial() const FINAL
Returns true if this is a geometry layer and false in case of NoGeometry (table only) or UnknownGeome...
Flags flags
Flags which dictate source behavior.
QgsFeatureRequest & setInvalidGeometryCallback(const std::function< void(const QgsFeature &)> &callback)
Sets a callback function to use when encountering an invalid geometry and invalidGeometryCheck() is s...
QString layerName
Layer name. If let empty, it will be derived from the filename.
Base class for the definition of processing parameters.
@ TypeVectorLine
Vector line layers.
@ FlagSkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
This class is a composition of two QSettings instances:
void setFields(const QgsFields &fields)
Convenience function for setting a fields for the context.
Encapsulates settings relating to a feature sink or output raster layer for a processing algorithm.
Type
The WKB type describes the number of dimensions a geometry has.
virtual QSet< QVariant > uniqueValues(int fieldIndex, int limit=-1) const
Returns the set of unique values contained within the specified fieldIndex from this source.
QVariant maximumValue(int fieldIndex) const override
Returns the maximum value for an attribute column or an invalid variant in case of error.
Abstract interface for generating an expression context scope.
QgsFeatureRequest::InvalidGeometryCheck geometryCheck
Geometry check method to apply to this source.
LayerHint
Layer type hints.
InvalidGeometryCheck
Handling of features with invalid geometries.
@ GeometrySkipInvalid
Skip any features with invalid geometry. This requires a slow geometry validity check for every featu...
Type propertyType() const
Returns the property type.
static QString encodeProviderKeyAndUri(const QString &providerKey, const QString &uri)
Encodes a provider key and layer uri to a single string, for use with decodeProviderKeyAndUri()
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)
~QgsProcessingFeatureSink() override
@ TypeVectorPoint
Vector point layers.
static QString stringToPythonLiteral(const QString &string)
Converts a string to a Python string literal.
QgsProperty source
Source definition.
A rectangle specified with double values.
QVariant value(const QgsExpressionContext &context, const QVariant &defaultValue=QVariant(), bool *ok=nullptr) const
Calculates the current value of the property, including any transforms which are set for the property...
static 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).
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
@ Raster
Raster layer type.
Setting options for loading mesh layers.
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...
@ Mesh
Mesh layer type, since QGIS 3.6.
QString providerType() const
Returns the provider type (provider key) for this layer.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request, Flags flags) const
Returns an iterator for the features in the source, respecting the supplied feature flags.
QMap< QString, QgsMapLayer * > mapLayers() const
Returns a map of all layers by layer ID.
virtual QgsFeatureIds allFeatureIds() const
Returns a list of all feature IDs for features present in the source.
static QgsProperty fromValue(const QVariant &value, bool isActive=true)
Returns a new StaticProperty created from the specified value.
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a single feature to the sink.
virtual FeatureAvailability hasFeatures() const
Determines if there are any features available in the source.
QgsProcessingOutputDefinitions outputDefinitions() const
Returns an ordered list of output definitions utilized by the algorithm.
Base class for the definition of processing outputs.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
Encapsulates settings relating to a feature source input to a processing algorithm.
double xMaximum() const SIP_HOLDGIL
Returns the x maximum value (right side of rectangle).
A storage object for map layers, in which the layers are owned by the store and have their lifetime b...
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsMeshDataProvider * dataProvider() override
Returns the layer's data provider, it may be nullptr.
Custom exception class for Coordinate Reference System related exceptions.
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.
QgsFeatureSource subclass for the selected features from a QgsVectorLayer.
@ TypeVector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
static QStringList supportedFormatExtensions(RasterFormatOptions options=SortRecommended)
Returns a list of file extensions for supported formats.
bool addFeatures(QgsFeatureList &features, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a list of features to the sink.
QgsFeatureSource::FeatureAvailability hasFeatures() const override
Determines if there are any features available in the source.
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.
QString lastError() const override
Returns the most recent error encountered by the sink, e.g.
virtual QString sourceName() const =0
Returns a friendly display name for the source.
QgsFields fields() const override
Returns the fields associated with features in the source.
Contains information about the context in which a processing algorithm is executed.
bool addFeatures(QgsFeatureList &features, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a list of features to the sink.
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...
static QList< int > fieldNamesToIndices(const QStringList &fieldNames, const QgsFields &fields)
Returns a list of field indices parsed from the given list of field names.
QString fileEncoding
Encoding to use.
void setDestinationFields(const QgsFields &fields)
Sets the fields for the destination sink.
QString defaultEncoding() const
Returns the default encoding to use for newly created files.
Represents a mesh layer supporting display of data on structured or unstructured meshes.
SpatialIndexPresence
Enumeration of spatial index presence states.
@ TypeVectorAnyGeometry
Any vector layer with geometry.
QString authid() const
Returns the authority identifier for the CRS.
bool skipCrsValidation
Controls whether the layer is allowed to have an invalid/unknown CRS.
virtual QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const =0
Returns an iterator for the features in the source.
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)
QList< QgsFeature > QgsFeatureList
long featureCount() const override
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.
@ NoFeaturesAvailable
There are certainly no features available in this source.
QVariantMap decodeUri(const QString &providerKey, const QString &uri)
Breaks a provider data source URI into its component paths (e.g.
static QStringList supportedFormatExtensions(VectorFormatOptions options=SortRecommended)
Returns a list of file extensions for supported formats, e.g "shp", "gpkg".
static const QString TEMPORARY_OUTPUT
Constant used to indicate that a Processing algorithm output should be a temporary layer/file.
static bool decodeProviderKeyAndUri(const QString &string, QString &providerKey, QString &uri)
Decodes a provider key and layer uri from an encoded string, for use with encodeProviderKeyAndUri()
static void createFeatureSinkPython(QgsFeatureSink **sink, QString &destination, QgsProcessingContext &context, const QgsFields &fields, QgsWkbTypes::Type geometryType, const QgsCoordinateReferenceSystem &crs, const QVariantMap &createOptions=QVariantMap()) SIP_THROW(QgsProcessingException)
Creates a feature sink ready for adding features.
static QStringList defaultLayerOptions(const QString &driverName)
Returns a list of the default layer options for a specified driver.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
QgsProviderMetadata * providerMetadata(const QString &providerKey) const
Returns metadata of the provider or nullptr if not found.
static QString driverForExtension(const QString &extension)
Returns the OGR driver name for a specified file extension.
double xMinimum() const SIP_HOLDGIL
Returns the x minimum value (left side of rectangle).
QgsVectorFileWriter::ActionOnExistingFile actionOnExistingFile
Action on existing file.
Represents a raster layer.
virtual QgsRectangle sourceExtent() const
Returns the extent of all geometries from the source.
virtual void setTransformContext(const QgsCoordinateTransformContext &transformContext)=0
Sets the coordinate transform context to transformContext.
QSet< QgsFeatureId > QgsFeatureIds
@ RegeneratePrimaryKey
This flag indicates, that a primary key field cannot be guaranteed to be unique and the sink should i...
This class represents a coordinate reference system (CRS).
virtual QgsFields fields() const =0
Returns the fields associated with features in the source.
QgsMapLayerStore * temporaryLayerStore()
Returns a reference to the layer store used for storing temporary layers during algorithm execution.
A QgsPointXY with associated coordinate reference system.
Single scope for storing variables and functions for use within a QgsExpressionContext.
QStringList datasourceOptions
List of OGR data source creation options.
QgsRectangle extent() const FINAL
Returns the extent of the layer.
QgsProcessingFeedback * feedback()
Returns the associated feedback object.
virtual long featureCount() const =0
Returns the number of features contained in the source, or -1 if the feature count is unknown.
bool createFromString(const QString &definition)
Set up this CRS from a string definition.
A class to represent a 2D point.
void setInvalidGeometryCheck(QgsFeatureRequest::InvalidGeometryCheck method)
Overrides the default geometry check method for the source.
QgsProxyFeatureSink subclass which reports feature addition errors to a QgsProcessingContext.
QgsFeatureIterator getSelectedFeatures(QgsFeatureRequest request=QgsFeatureRequest()) const
Returns an iterator of the selected features.
bool isCanceled() const
Tells whether the operation has been canceled already.
@ AppendToLayerNoNewFields
Append features to existing layer, but do not create new fields.
Setting options for loading vector layers.
FeatureAvailability
Possible return value for hasFeatures() to determine if a source is empty.
QgsCoordinateReferenceSystem crs() const
Returns the associated coordinate reference system, or an invalid CRS if no reference system is set.
QString source() const
Returns the source for the layer.
@ Vector
Vector layer type.
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...
Setting options for loading raster layers.
bool loadDefaultStyle
Sets to true if the default layer style should be loaded.
double yMaximum() const SIP_HOLDGIL
Returns the y maximum value (top side of rectangle).
static QString generateTempFilename(const QString &basename)
Returns a temporary filename for a given file, putting it into a temporary folder (creating that fold...
Abstract base class for processing algorithms.
bool nextFeature(QgsFeature &f)
static QString tempFolder()
Returns a session specific processing temporary folder for use in processing algorithms.
virtual QgsWkbTypes::Type wkbType() const =0
Returns the geometry type for features returned by this source.
Represents a vector layer which manages a vector based data sets.
static QString variantToPythonLiteral(const QVariant &value)
Converts a variant to a Python literal.
QgsFeatureRequest & setLimit(long limit)
Set the maximum number of features to request.
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.
Base class for all map layer types.
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.
QgsExpressionContext & expressionContext()
Returns the expression context.
static QgsCoordinateReferenceSystem variantToCrs(const QVariant &value, QgsProcessingContext &context, const QVariant &fallbackValue=QVariant())
Converts a variant value to a coordinate reference system.
QgsFeatureSource subclass which proxies methods to an underlying QgsFeatureSource,...
SpatialIndexPresence hasSpatialIndex() const override
Returns an enum value representing the presence of a valid spatial index on the source,...
@ FeaturesMaybeAvailable
There may be features available in this source.
@ GeometryNoCheck
No invalid geometry checking.
static QgsRectangle combineLayerExtents(const QList< QgsMapLayer * > &layers, const QgsCoordinateReferenceSystem &crs, QgsProcessingContext &context)
Combines the extent of several map layers.
QgsProcessingParameterDefinitions parameterDefinitions() const
Returns an ordered list of parameter definitions utilized by the algorithm.
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.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
QgsProcessingFeatureSink(QgsFeatureSink *originalSink, const QString &sinkName, QgsProcessingContext &context, bool ownsOriginalSink=false)
Constructor for QgsProcessingFeatureSink, accepting an original feature sink originalSink and process...
Handles storage of information regarding WKB types and their properties.
QgsFeatureIds allFeatureIds() const override
Returns a list of all feature IDs for features present in the source.
QgsProperty sink
Sink/layer definition.
QgsVectorFileWriter::SymbologyExport symbologyExport
Symbology to export.
int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
QStringList layerOptions
List of OGR layer creation options.
QgsField at(int i) const
Gets field at particular index (must be in range 0..N-1)
QString table() const
Returns the table name stored in the URI.
@ StaticProperty
Static property (QgsStaticProperty)
QString driverName
OGR driver to use.
Wrapper for iterator of features from vector data provider or vector layer.
Q_INVOKABLE QgsWkbTypes::GeometryType geometryType() const
Returns point, line or polygon.
QgsCoordinateReferenceSystem sourceCrs() const override
Returns the coordinate reference system for features in the source.
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a single feature to the sink.
QString sourceName() const override
Returns a friendly display name for the source.
static QgsProviderRegistry * instance(const QString &pluginPath=QString())
Means of accessing canonical single instance.
static QStringList defaultDatasetOptions(const QString &driverName)
Returns a list of the default dataset options for a specified driver.
static QString defaultRasterExtension()
Returns the default raster extension to use, in the absence of all other constraints (e....
QgsWkbTypes::Type wkbType() const override
Returns the geometry type for features returned by this source.
QgsCoordinateReferenceSystem crs
Custom exception class for processing related exceptions.
virtual QgsExpressionContextScope * createExpressionContextScope() const =0
This method needs to be reimplemented in all classes which implement this interface and return an exp...
An interface for objects which accept features via addFeature(s) methods.
void setName(const QString &name)
Set the field name.
static QString stringToSafeFilename(const QString &string)
Converts a string to a safe filename, replacing characters which are not safe for filenames with an '...
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
@ UnknownType
Unknown layer type.
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.
long limit() const
Returns the maximum number of features to request, or -1 if no limit set.
Encapsulate a field in an attribute table or data source.