42#include <QImageWriter>
43#include <QRegularExpression>
48#include "moc_qgsprocessingutils.cpp"
50using namespace Qt::StringLiterals;
54 return compatibleMapLayers< QgsRasterLayer >( project, sort );
60 return QList<QgsVectorLayer *>();
62 QList<QgsVectorLayer *> layers;
66 if ( canUseLayer( l, geometryTypes ) )
72 std::sort( layers.begin(), layers.end(), [](
const QgsVectorLayer *a,
const QgsVectorLayer *b ) ->
bool { return QString::localeAwareCompare( a->name(), b->name() ) < 0; } );
79 return compatibleMapLayers< QgsMeshLayer >( project, sort );
84 return compatibleMapLayers< QgsPluginLayer >( project, sort );
89 return compatibleMapLayers< QgsPointCloudLayer >( project, sort );
95 QList<QgsAnnotationLayer *> res = compatibleMapLayers< QgsAnnotationLayer >( project,
false );
101 std::sort( res.begin(), res.end(), [](
const QgsAnnotationLayer *a,
const QgsAnnotationLayer *b ) ->
bool { return QString::localeAwareCompare( a->name(), b->name() ) < 0; } );
109 return compatibleMapLayers< QgsVectorTileLayer >( project, sort );
114 return compatibleMapLayers< QgsTiledSceneLayer >( project, sort );
117template<
typename T> QList<T *> QgsProcessingUtils::compatibleMapLayers(
QgsProject *project,
bool sort )
123 const auto projectLayers = project->
layers<T *>();
124 for ( T *l : projectLayers )
126 if ( canUseLayer( l ) )
132 std::sort( layers.begin(), layers.end(), [](
const T *a,
const T *b ) ->
bool { return QString::localeAwareCompare( a->name(), b->name() ) < 0; } );
140 return QList<QgsMapLayer *>();
142 QList<QgsMapLayer *> layers;
144 const auto rasterLayers = compatibleMapLayers< QgsRasterLayer >( project,
false );
152 const auto meshLayers = compatibleMapLayers< QgsMeshLayer >( project,
false );
156 const auto pointCloudLayers = compatibleMapLayers< QgsPointCloudLayer >( project,
false );
160 const auto annotationLayers = compatibleMapLayers< QgsAnnotationLayer >( project,
false );
165 const auto vectorTileLayers = compatibleMapLayers< QgsVectorTileLayer >( project,
false );
169 const auto tiledSceneLayers = compatibleMapLayers< QgsTiledSceneLayer >( project,
false );
173 const auto pluginLayers = compatibleMapLayers< QgsPluginLayer >( project,
false );
179 std::sort( layers.begin(), layers.end(), [](
const QgsMapLayer *a,
const QgsMapLayer *b ) ->
bool { return QString::localeAwareCompare( a->name(), b->name() ) < 0; } );
186 return u
"%1://%2"_s.arg( providerKey, uri );
191 const thread_local QRegularExpression re( u
"^(\\w+?):\\/\\/(.+)$"_s );
192 const QRegularExpressionMatch match = re.match(
string );
193 if ( !match.hasMatch() )
196 providerKey = match.captured( 1 );
197 uri = match.captured( 2 );
205 if ( !store ||
string.isEmpty() )
208 QList< QgsMapLayer * > layers = store->
mapLayers().values();
215 switch ( layer->type() )
217 case Qgis::LayerType::Vector:
218 return !canUseLayer( qobject_cast< QgsVectorLayer * >( layer ) );
219 case Qgis::LayerType::Raster:
220 return !canUseLayer( qobject_cast< QgsRasterLayer * >( layer ) );
221 case Qgis::LayerType::Plugin:
222 case Qgis::LayerType::Group:
224 case Qgis::LayerType::Mesh:
225 return !canUseLayer( qobject_cast< QgsMeshLayer * >( layer ) );
226 case Qgis::LayerType::VectorTile:
227 return !canUseLayer( qobject_cast< QgsVectorTileLayer * >( layer ) );
228 case Qgis::LayerType::TiledScene:
229 return !canUseLayer( qobject_cast< QgsTiledSceneLayer * >( layer ) );
230 case Qgis::LayerType::PointCloud:
231 return !canUseLayer( qobject_cast< QgsPointCloudLayer * >( layer ) );
232 case Qgis::LayerType::Annotation:
233 return !canUseLayer( qobject_cast< QgsAnnotationLayer * >( layer ) );
241 auto isCompatibleType = [typeHint](
QgsMapLayer *l ) ->
bool {
244 case LayerHint::UnknownType:
247 case LayerHint::Vector:
250 case LayerHint::Raster:
253 case LayerHint::Mesh:
256 case LayerHint::PointCloud:
259 case LayerHint::Annotation:
262 case LayerHint::VectorTile:
265 case LayerHint::TiledScene:
273 if ( isCompatibleType( l ) && l->id() ==
string )
278 if ( isCompatibleType( l ) && l->name() ==
string )
283 if ( isCompatibleType( l ) && normalizeLayerSource( l->source() ) == normalizeLayerSource(
string ) )
300 if ( providerMetadata )
303 const QVariantMap parts = providerMetadata->
decodeUri( uri );
304 const QString layerName = parts.value( u
"layerName"_s ).toString();
306 if ( !layerName.isEmpty() )
310 else if (
const QString path = parts.value( u
"path"_s ).toString(); !path.isEmpty() )
312 name = QFileInfo( path ).baseName();
317 const QStringList components = uri.split(
'|' );
318 if ( components.isEmpty() )
321 if ( QFileInfo fi( components.at( 0 ) ); fi.isFile() )
322 name = fi.baseName();
324 name = QFileInfo( uri ).baseName();
327 if ( name.isEmpty() )
329 name = QgsDataSourceUri( uri ).table();
331 if ( name.isEmpty() )
336 QList< Qgis::LayerType > candidateTypes;
341 if ( providerMetadata )
374 QgsVectorLayer::LayerOptions options { transformContext };
378 std::unique_ptr< QgsVectorLayer > layer;
379 if ( providerMetadata )
381 layer = std::make_unique<QgsVectorLayer>( uri, name, providerMetadata->
key(), options );
386 layer = std::make_unique<QgsVectorLayer>( uri, name, u
"ogr"_s, options );
388 if ( layer->isValid() )
390 return layer.release();
395 QgsRasterLayer::LayerOptions rasterOptions;
399 std::unique_ptr< QgsRasterLayer > rasterLayer;
400 if ( providerMetadata )
402 rasterLayer = std::make_unique< QgsRasterLayer >( uri, name, providerMetadata->
key(), rasterOptions );
407 rasterLayer = std::make_unique< QgsRasterLayer >( uri, name, u
"gdal"_s, rasterOptions );
410 if ( rasterLayer->isValid() )
412 return rasterLayer.release();
417 QgsMeshLayer::LayerOptions meshOptions;
420 std::unique_ptr< QgsMeshLayer > meshLayer;
421 if ( providerMetadata )
423 meshLayer = std::make_unique< QgsMeshLayer >( uri, name, providerMetadata->
key(), meshOptions );
427 meshLayer = std::make_unique< QgsMeshLayer >( uri, name, u
"mdal"_s, meshOptions );
429 if ( meshLayer->isValid() )
431 return meshLayer.release();
436 QgsPointCloudLayer::LayerOptions pointCloudOptions;
444 std::unique_ptr< QgsPointCloudLayer > pointCloudLayer;
445 if ( providerMetadata )
447 pointCloudLayer = std::make_unique< QgsPointCloudLayer >( uri, name, providerMetadata->
key(), pointCloudOptions );
452 if ( !preferredProviders.empty() )
454 pointCloudLayer = std::make_unique< QgsPointCloudLayer >( uri, name, preferredProviders.at( 0 ).metadata()->key(), pointCloudOptions );
464 pointCloudLayer = std::make_unique< QgsPointCloudLayer >( uri, name, u
"pdal"_s, pointCloudOptions );
468 if ( pointCloudLayer && pointCloudLayer->isValid() )
470 return pointCloudLayer.release();
475 QgsDataSourceUri dsUri;
476 dsUri.
setParam(
"type",
"mbtiles" );
479 std::unique_ptr< QgsVectorTileLayer > tileLayer;
480 tileLayer = std::make_unique< QgsVectorTileLayer >( dsUri.
encodedUri(), name );
482 if ( tileLayer->isValid() )
484 return tileLayer.release();
489 QgsTiledSceneLayer::LayerOptions tiledSceneOptions;
492 std::unique_ptr< QgsTiledSceneLayer > tiledSceneLayer;
493 if ( providerMetadata )
495 tiledSceneLayer = std::make_unique< QgsTiledSceneLayer >( uri, name, providerMetadata->
key(), tiledSceneOptions );
500 if ( !preferredProviders.empty() )
502 tiledSceneLayer = std::make_unique< QgsTiledSceneLayer >( uri, name, preferredProviders.at( 0 ).metadata()->key(), tiledSceneOptions );
505 if ( tiledSceneLayer && tiledSceneLayer->isValid() )
507 return tiledSceneLayer.release();
515 if (
string.isEmpty() )
523 if (
auto *lProject = context.
project() )
525 QgsMapLayer *layer = mapLayerFromStore(
string, lProject->layerStore(), typeHint );
539 if ( !allowLoadingNewLayers )
542 layer = loadMapLayerFromString(
string, context.
transformContext(), typeHint, flags );
556 QVariant val = value;
557 bool selectedFeaturesOnly =
false;
558 long long featureLimit = -1;
559 QString filterExpression;
560 bool overrideGeometryCheck =
false;
562 if ( val.userType() == qMetaTypeId<QgsProcessingFeatureSourceDefinition>() )
573 else if ( val.userType() == qMetaTypeId<QgsProcessingOutputLayerDefinition>() )
580 if (
QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( qvariant_cast<QObject *>( val ) ) )
582 auto source = std::make_unique< QgsProcessingFeatureSource >( layer, context,
false, featureLimit, filterExpression );
583 if ( overrideGeometryCheck )
584 source->setInvalidGeometryCheck( geometryCheck );
585 return source.release();
589 if ( val.userType() == qMetaTypeId<QgsProperty>() )
593 else if ( !val.isValid() || val.toString().isEmpty() )
596 if (
QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( qvariant_cast<QObject *>( fallbackValue ) ) )
598 auto source = std::make_unique< QgsProcessingFeatureSource >( layer, context,
false, featureLimit, filterExpression );
599 if ( overrideGeometryCheck )
600 source->setInvalidGeometryCheck( geometryCheck );
601 return source.release();
604 layerRef = fallbackValue.toString();
608 layerRef = val.toString();
611 if ( layerRef.isEmpty() )
618 std::unique_ptr< QgsProcessingFeatureSource> source;
619 if ( selectedFeaturesOnly )
625 source = std::make_unique< QgsProcessingFeatureSource >( vl, context,
false, featureLimit, filterExpression );
628 if ( overrideGeometryCheck )
629 source->setInvalidGeometryCheck( geometryCheck );
630 return source.release();
635 QVariant val = value;
637 if ( val.userType() == qMetaTypeId<QgsCoordinateReferenceSystem>() )
642 else if ( val.userType() == qMetaTypeId<QgsProcessingFeatureSourceDefinition>() )
648 else if ( val.userType() == qMetaTypeId<QgsProcessingOutputLayerDefinition>() )
661 if (
QgsMapLayer *layer = qobject_cast< QgsMapLayer * >( qvariant_cast<QObject *>( val ) ) )
664 if ( val.userType() == qMetaTypeId<QgsProperty>() )
667 if ( !val.isValid() )
673 QString crsText = val.toString();
674 if ( crsText.isEmpty() )
675 crsText = fallbackValue.toString();
677 if ( crsText.isEmpty() )
681 if ( context.
project() && crsText.compare(
"ProjectCrs"_L1, Qt::CaseInsensitive ) == 0 )
697bool QgsProcessingUtils::canUseLayer(
const QgsMeshLayer *layer )
702bool QgsProcessingUtils::canUseLayer(
const QgsPluginLayer *layer )
704 return layer && layer->
isValid();
709 return layer && layer->
isValid();
712bool QgsProcessingUtils::canUseLayer(
const QgsRasterLayer *layer )
714 return layer && layer->
isValid();
719 return layer && layer->
isValid();
724 return layer && layer->
isValid();
729 return layer && layer->
isValid();
732bool QgsProcessingUtils::canUseLayer(
const QgsVectorLayer *layer,
const QList<int> &sourceTypes )
734 return layer && layer->
isValid() &&
735 ( sourceTypes.isEmpty()
746 QString normalized = source;
747 normalized.replace(
'\\',
'/' );
748 return normalized.trimmed();
757 if ( !source.isEmpty() )
762 if ( provider.compare(
"gdal"_L1, Qt::CaseInsensitive ) == 0 || provider.compare(
"ogr"_L1, Qt::CaseInsensitive ) == 0 || provider.compare(
"mdal"_L1, Qt::CaseInsensitive ) == 0 )
765 return u
"%1://%2"_s.arg( provider, source );
778 if ( !value.isValid() )
781 if ( value.userType() == qMetaTypeId<QgsProperty>() )
783 else if ( value.userType() == qMetaTypeId<QgsCoordinateReferenceSystem>() )
786 return u
"QgsCoordinateReferenceSystem()"_s;
790 else if ( value.userType() == qMetaTypeId<QgsRectangle>() )
795 else if ( value.userType() == qMetaTypeId<QgsReferencedRectangle>() )
800 else if ( value.userType() == qMetaTypeId<QgsPointXY>() )
805 else if ( value.userType() == qMetaTypeId<QgsReferencedPointXY>() )
811 switch ( value.userType() )
813 case QMetaType::Type::Bool:
814 return value.toBool() ? u
"True"_s : u
"False"_s;
816 case QMetaType::Type::Double:
817 return QString::number( value.toDouble() );
819 case QMetaType::Type::Int:
820 case QMetaType::Type::UInt:
821 return QString::number( value.toInt() );
823 case QMetaType::Type::LongLong:
824 case QMetaType::Type::ULongLong:
825 return QString::number( value.toLongLong() );
827 case QMetaType::Type::QVariantList:
830 const QVariantList vl = value.toList();
831 for (
const QVariant &v : vl )
835 return parts.join(
',' ).prepend(
'[' ).append(
']' );
838 case QMetaType::Type::QVariantMap:
840 const QVariantMap map = value.toMap();
842 parts.reserve( map.size() );
843 for (
auto it = map.constBegin(); it != map.constEnd(); ++it )
847 return parts.join(
',' ).prepend(
'{' ).append(
'}' );
850 case QMetaType::Type::QDateTime:
852 const QDateTime dateTime = value.toDateTime();
853 return u
"QDateTime(QDate(%1, %2, %3), QTime(%4, %5, %6))"_s.arg( dateTime.date().year() )
854 .arg( dateTime.date().month() )
855 .arg( dateTime.date().day() )
856 .arg( dateTime.time().hour() )
857 .arg( dateTime.time().minute() )
858 .arg( dateTime.time().second() );
871 s.replace(
'\\',
"\\\\"_L1 );
872 s.replace(
'\n',
"\\n"_L1 );
873 s.replace(
'\r',
"\\r"_L1 );
874 s.replace(
'\t',
"\\t"_L1 );
876 if ( s.contains(
'\'' ) && !s.contains(
'\"' ) )
878 s = s.prepend(
'"' ).append(
'"' );
882 s.replace(
'\'',
"\\\'"_L1 );
883 s = s.prepend(
'\'' ).append(
'\'' );
888void QgsProcessingUtils::parseDestinationString(
889 QString &destination, QString &providerKey, QString &uri, QString &layerName, QString &format, QMap<QString, QVariant> &options,
bool &useWriter, QString &extension
897 const thread_local QRegularExpression splitRx( u
"^(.{3,}?):(.*)$"_s );
898 QRegularExpressionMatch match = splitRx.match( destination );
899 if ( match.hasMatch() )
901 providerKey = match.captured( 1 );
902 uri = match.captured( 2 );
909 if ( providerKey ==
"postgis"_L1 )
911 providerKey = u
"postgres"_s;
913 if ( providerKey ==
"ogr"_L1 )
915 QgsDataSourceUri dsUri( uri );
918 if ( !dsUri.
table().isEmpty() )
920 layerName = dsUri.
table();
921 options.insert( u
"layerName"_s, layerName );
924 extension = QFileInfo( uri ).completeSuffix();
926 options.insert( u
"driverName"_s, format );
930 extension = QFileInfo( uri ).completeSuffix();
933 options.insert( u
"update"_s,
true );
940 providerKey = u
"ogr"_s;
942 const thread_local QRegularExpression splitRx( u
"^(.*)\\.(.*?)$"_s );
943 QRegularExpressionMatch match = splitRx.match( destination );
944 if ( match.hasMatch() )
946 extension = match.captured( 2 );
950 if ( format.isEmpty() )
953 destination = destination + u
".gpkg"_s;
956 options.insert( u
"driverName"_s, format );
962 QString &destination,
967 const QVariantMap &createOptions,
968 const QStringList &datasourceOptions,
969 const QStringList &layerOptions,
974 QVariantMap options = createOptions;
975 if ( !options.contains( u
"fileEncoding"_s ) )
981 if ( destination.isEmpty() || destination.startsWith(
"memory:"_L1 ) )
984 if ( destination.startsWith(
"memory:"_L1 ) )
985 destination = destination.mid( 7 );
987 if ( destination.isEmpty() )
988 destination = u
"output"_s;
992 if ( !layer || !layer->isValid() )
999 for (
const QgsField &field : fields )
1002 if ( !field.alias().isEmpty() )
1003 feedback->pushWarning( QObject::tr(
"%1: Aliases are not compatible with scratch layers" ).arg( field.name() ) );
1004 if ( !field.alias().isEmpty() )
1005 feedback->pushWarning( QObject::tr(
"%1: Comments are not compatible with scratch layers" ).arg( field.name() ) );
1012 destination = layer->id();
1015 auto sink = std::make_unique<QgsProcessingFeatureSink>( layer->dataProvider(), destination, context );
1018 return sink.release();
1022 QString providerKey;
1027 bool useWriter =
false;
1028 parseDestinationString( destination, providerKey, uri, layerName, format, options, useWriter, extension );
1031 if ( useWriter && providerKey ==
"ogr"_L1 )
1035 QString finalFileName;
1036 QString finalLayerName;
1038 saveOptions.
fileEncoding = options.value( u
"fileEncoding"_s ).toString();
1039 saveOptions.
layerName = !layerName.isEmpty() ? layerName : options.value( u
"layerName"_s ).toString();
1044 if ( remappingDefinition )
1048 auto vl = std::make_unique< QgsVectorLayer >( destination );
1049 if ( vl->isValid() )
1053 newFields = vl->fields();
1062 std::unique_ptr< QgsVectorFileWriter > writer(
1065 if ( writer->hasError() )
1067 throw QgsProcessingException( QObject::tr(
"Could not create layer %1: %2" ).arg( destination, writer->errorMessage() ) );
1072 for (
const QgsField &field : fields )
1075 feedback->pushWarning( QObject::tr(
"%1: Aliases are not supported by %2" ).arg( field.name(), writer->driverLongName() ) );
1077 feedback->pushWarning( QObject::tr(
"%1: Comments are not supported by %2" ).arg( field.name(), writer->driverLongName() ) );
1081 destination = finalFileName;
1082 if ( !saveOptions.
layerName.isEmpty() && !finalLayerName.isEmpty() )
1083 destination += u
"|layername=%1"_s.arg( finalLayerName );
1085 if ( remappingDefinition )
1087 auto remapSink = std::make_unique< QgsRemappingProxyFeatureSink >( *remappingDefinition, writer.release(),
true );
1098 if ( remappingDefinition )
1103 if ( !layerName.isEmpty() )
1106 parts.insert( u
"layerName"_s, layerName );
1110 auto layer = std::make_unique<QgsVectorLayer>( uri, destination, providerKey, layerOptions );
1112 destination = layer->
id();
1124 for (
const QgsField &field : fields )
1127 feedback->pushWarning( QObject::tr(
"%1: Aliases are not supported by the %2 provider" ).arg( field.name(), providerKey ) );
1129 feedback->pushWarning( QObject::tr(
"%1: Comments are not supported by the %2 provider" ).arg( field.name(), providerKey ) );
1133 auto remapSink = std::make_unique< QgsRemappingProxyFeatureSink >( *remappingDefinition, layer->
dataProvider(),
false );
1143 auto exporter = std::make_unique<QgsVectorLayerExporter>( uri, providerKey, newFields, geometryType, crs,
true, options, sinkFlags );
1146 throw QgsProcessingException( QObject::tr(
"Could not create layer %1: %2" ).arg( destination, exporter->errorMessage() ) );
1150 if ( !layerName.isEmpty() )
1152 uri += u
"|layername=%1"_s.arg( layerName );
1159 for (
const QgsField &field : fields )
1162 feedback->pushWarning( QObject::tr(
"%1: Aliases are not supported by the %2 provider" ).arg( field.name(), providerKey ) );
1164 feedback->pushWarning( QObject::tr(
"%1: Comments are not supported by the %2 provider" ).arg( field.name(), providerKey ) );
1178 *sink =
createFeatureSink( destination, context, fields, geometryType, crs, options );
1223 if ( !input.isValid() )
1224 return u
"memory:%1"_s.arg(
id.toString() );
1226 if ( input.userType() == qMetaTypeId<QgsProcessingOutputLayerDefinition>() )
1233 else if ( input.userType() == qMetaTypeId<QgsProperty>() )
1240 QString res = input.toString();
1246 else if ( res.startsWith(
"memory:"_L1 ) )
1248 return QString( res +
'_' +
id.toString() );
1254 int lastIndex = res.lastIndexOf(
'.' );
1255 return lastIndex >= 0 ? QString( res.left( lastIndex ) +
'_' +
id.toString() + res.mid( lastIndex ) ) : QString( res +
'_' +
id.toString() );
1266 static std::vector< std::unique_ptr< QTemporaryDir > > sTempFolders;
1267 static QString sFolder;
1268 static QMutex sMutex;
1269 QMutexLocker locker( &sMutex );
1274 if ( basePath.isEmpty() )
1277 if ( basePath.isEmpty() )
1280 if ( sTempFolders.empty() )
1282 const QString templatePath = u
"%1/processing_XXXXXX"_s.arg( QDir::tempPath() );
1283 auto tempFolder = std::make_unique< QTemporaryDir >( templatePath );
1285 sTempFolders.emplace_back( std::move(
tempFolder ) );
1288 else if ( sFolder.isEmpty() || !sFolder.startsWith( basePath ) || sTempFolders.empty() )
1290 if ( !QDir().exists( basePath ) )
1291 QDir().mkpath( basePath );
1293 const QString templatePath = u
"%1/processing_XXXXXX"_s.arg( basePath );
1294 auto tempFolder = std::make_unique< QTemporaryDir >( templatePath );
1296 sTempFolders.emplace_back( std::move(
tempFolder ) );
1303 QString subPath = QUuid::createUuid().toString().remove(
'-' ).remove(
'{' ).remove(
'}' );
1304 QString path =
tempFolder( context ) +
'/' + subPath;
1305 if ( !QDir( path ).exists() )
1308 tmpDir.mkdir( path );
1315 auto getText = [map](
const QString &key ) -> QString {
1316 if ( map.contains( key ) )
1317 return map.value( key ).toString();
1322 s += u
"<html><body><p>"_s + getText( u
"ALG_DESC"_s ) + u
"</p>\n"_s;
1325 const auto parameterDefinitions =
algorithm->parameterDefinitions();
1331 if ( !getText( def->name() ).isEmpty() )
1333 inputs += u
"<h3>"_s + def->description() + u
"</h3>\n"_s;
1334 inputs += u
"<p>"_s + getText( def->name() ) + u
"</p>\n"_s;
1337 if ( !inputs.isEmpty() )
1338 s += u
"<h2>"_s + QObject::tr(
"Input parameters" ) + u
"</h2>\n"_s + inputs;
1341 const auto outputDefinitions =
algorithm->outputDefinitions();
1344 if ( !getText( def->name() ).isEmpty() )
1346 outputs += u
"<h3>"_s + def->description() + u
"</h3>\n"_s;
1347 outputs += u
"<p>"_s + getText( def->name() ) + u
"</p>\n"_s;
1350 if ( !outputs.isEmpty() )
1351 s += u
"<h2>"_s + QObject::tr(
"Outputs" ) + u
"</h2>\n"_s + outputs;
1353 if ( !map.value( u
"EXAMPLES"_s ).toString().isEmpty() )
1354 s += u
"<h2>%1</h2>\n<p>%2</p>"_s.arg( QObject::tr(
"Examples" ), getText( u
"EXAMPLES"_s ) );
1357 if ( !map.value( u
"ALG_CREATOR"_s ).toString().isEmpty() )
1358 s += u
"<p align=\"right\">"_s + QObject::tr(
"Algorithm author:" ) + u
" "_s + getText( u
"ALG_CREATOR"_s ) + u
"</p>"_s;
1359 if ( !map.value( u
"ALG_HELP_CREATOR"_s ).toString().isEmpty() )
1360 s += u
"<p align=\"right\">"_s + QObject::tr(
"Help author:" ) + u
" "_s + getText( u
"ALG_HELP_CREATOR"_s ) + u
"</p>"_s;
1361 if ( !map.value( u
"ALG_VERSION"_s ).toString().isEmpty() )
1362 s += u
"<p align=\"right\">"_s + QObject::tr(
"Algorithm version:" ) + u
" "_s + getText( u
"ALG_VERSION"_s ) + u
"</p>"_s;
1364 s +=
"</body></html>"_L1;
1373 if ( def->name().compare( name, Qt::CaseInsensitive ) == 0 )
1385 if ( def->name().compare( name, Qt::CaseInsensitive ) == 0 )
1394 bool selectedFeaturesOnly,
1395 const QString &baseName,
1396 const QStringList &compatibleFormats,
1397 const QString &preferredFormat,
1401 long long featureLimit,
1402 const QString &filterExpression,
1406 bool requiresTranslation =
false;
1410 requiresTranslation = requiresTranslation || selectedFeaturesOnly;
1413 requiresTranslation = requiresTranslation || featureLimit != -1 || !filterExpression.isEmpty();
1418 requiresTranslation = requiresTranslation || vl->
providerType() !=
"ogr"_L1;
1422 requiresTranslation = requiresTranslation || !vl->
subsetString().isEmpty();
1426 requiresTranslation = requiresTranslation || vl->
source().startsWith(
"/vsi"_L1 );
1430 if ( !requiresTranslation )
1433 if ( parts.contains( u
"path"_s ) )
1435 diskPath = parts.value( u
"path"_s ).toString();
1436 QFileInfo fi( diskPath );
1437 requiresTranslation = !compatibleFormats.contains( fi.suffix(), Qt::CaseInsensitive );
1441 const QString srcLayerName = parts.value( u
"layerName"_s ).toString();
1445 *layerName = srcLayerName;
1450 requiresTranslation = requiresTranslation || ( !srcLayerName.isEmpty() && srcLayerName != fi.baseName() );
1455 requiresTranslation =
true;
1459 if ( requiresTranslation )
1469 const int fidIndex = fields.
lookupField( u
"fid"_s );
1470 if ( fidIndex >= 0 )
1471 fields.
rename( fidIndex, u
"OLD_FID"_s );
1477 if ( featureLimit != -1 )
1481 if ( !filterExpression.isEmpty() )
1486 if ( selectedFeaturesOnly )
1491 constexpr int maxErrors { 10 };
1492 unsigned long errorCounter { 0 };
1500 const QString errorMessage = writer->errorMessage();
1501 if ( !renameFid && saveOptions.
driverName ==
"GPKG"_L1 && errorMessage.contains(
"fid", Qt::CaseInsensitive ) )
1504 feedback->
reportError( QObject::tr(
"Cannot store existing FID values in temporary GeoPackage layer, these will be moved to \"OLD_FID\" instead." ),
false );
1505 return convertToCompatibleFormatInternal( vl, selectedFeaturesOnly, baseName, compatibleFormats, preferredFormat, context, feedback, layerName, featureLimit, filterExpression,
true );
1509 if ( errorCounter++ < maxErrors )
1511 errorText = QObject::tr(
"Error writing feature # %1 to output layer: %2" ).arg( QString::number( f.
id() ), errorMessage );
1517 if ( errorCounter >= maxErrors )
1519 feedback->
reportError( QObject::tr(
"There were %1 errors writing features, only the first %2 have been reported." ).arg( QString::number( errorCounter ), QString::number( maxErrors ) ) );
1531 bool selectedFeaturesOnly,
1532 const QString &baseName,
1533 const QStringList &compatibleFormats,
1534 const QString &preferredFormat,
1537 long long featureLimit,
1538 const QString &filterExpression
1541 return convertToCompatibleFormatInternal( vl, selectedFeaturesOnly, baseName, compatibleFormats, preferredFormat, context, feedback,
nullptr, featureLimit, filterExpression,
false );
1546 bool selectedFeaturesOnly,
1547 const QString &baseName,
1548 const QStringList &compatibleFormats,
1549 const QString &preferredFormat,
1553 long long featureLimit,
1554 const QString &filterExpression
1558 return convertToCompatibleFormatInternal( layer, selectedFeaturesOnly, baseName, compatibleFormats, preferredFormat, context, feedback, &layerName, featureLimit, filterExpression,
false );
1564 QSet< QString > usedNames;
1565 for (
const QgsField &f : fieldsA )
1567 usedNames.insert( f.name().toLower() );
1570 for (
const QgsField &f : fieldsB )
1573 newField.
setName( fieldsBPrefix + f.name() );
1574 if ( usedNames.contains( newField.
name().toLower() ) )
1577 QString newName = newField.
name() +
'_' + QString::number( idx );
1578 while ( usedNames.contains( newName.toLower() ) || fieldsB.
indexOf( newName ) != -1 )
1581 newName = newField.
name() +
'_' + QString::number( idx );
1584 outFields.
append( newField );
1588 outFields.
append( newField );
1590 usedNames.insert( newField.
name() );
1599 if ( !fieldNames.isEmpty() )
1601 indices.reserve( fieldNames.count() );
1602 for (
const QString &f : fieldNames )
1606 indices.append( idx );
1611 indices.reserve( fields.
count() );
1612 for (
int i = 0; i < fields.
count(); ++i )
1613 indices.append( i );
1621 for (
int i : indices )
1622 fieldsSubset.
append( fields.
at( i ) );
1623 return fieldsSubset;
1629 if ( setting.isEmpty() )
1632 if ( setting.startsWith(
'.' ) )
1633 setting = setting.mid( 1 );
1636 if ( !supportedFormats.contains( setting, Qt::CaseInsensitive ) )
1645 if ( setting.isEmpty() )
1651 if ( detail.driverName.compare( setting, Qt::CaseInsensitive ) == 0 )
1652 return detail.driverName;
1662 if ( !extensions.isEmpty() )
1663 return extensions[0];
1675 return u
"mbtiles"_s;
1680 auto layerPointerToString = [](
QgsMapLayer *layer ) -> QString {
1689 auto cleanPointerValues = [&layerPointerToString](
const QVariant &value ) -> QVariant {
1690 if (
QgsMapLayer *layer = qobject_cast< QgsMapLayer * >( value.value< QObject * >() ) )
1693 return layerPointerToString( layer );
1695 else if ( value.userType() == QMetaType::type(
"QPointer< QgsMapLayer >" ) )
1698 return layerPointerToString( value.value< QPointer< QgsMapLayer > >().data() );
1707 for (
auto it = map.constBegin(); it != map.constEnd(); ++it )
1709 if ( it->userType() == QMetaType::Type::QVariantMap )
1713 else if ( it->userType() == QMetaType::Type::QVariantList )
1716 const QVariantList source = it.value().toList();
1717 dest.reserve( source.size() );
1718 for (
const QVariant &v : source )
1720 dest.append( cleanPointerValues( v ) );
1722 res.insert( it.key(), dest );
1726 res.insert( it.key(), cleanPointerValues( it.value() ) );
1736 for (
auto it = parameters.constBegin(); it != parameters.constEnd(); ++it )
1738 if ( it.value().userType() == QMetaType::Type::QVariantMap )
1740 const QVariantMap value = it.value().toMap();
1741 if ( value.value( u
"type"_s ).toString() ==
"data_defined"_L1 )
1743 const QString expression = value.value( u
"expression"_s ).toString();
1744 const QString field = value.value( u
"field"_s ).toString();
1745 if ( !expression.isEmpty() )
1749 else if ( !field.isEmpty() )
1756 error = QObject::tr(
"Invalid data defined parameter for %1, requires 'expression' or 'field' values." ).arg( it.key() );
1761 output.insert( it.key(), it.value() );
1764 else if ( it.value().userType() == QMetaType::Type::QString )
1766 const QString stringValue = it.value().toString();
1768 if ( stringValue.startsWith(
"field:"_L1 ) )
1772 else if ( stringValue.startsWith(
"expression:"_L1 ) )
1778 output.insert( it.key(), it.value() );
1783 output.insert( it.key(), it.value() );
1791 if ( !QTextCodec::availableCodecs().contains( defaultEncoding.toLatin1() ) )
1793 const QString systemCodec = QTextCodec::codecForLocale()->name();
1794 if ( !systemCodec.isEmpty() )
1798 return QString(
"UTF-8" );
1801 return defaultEncoding;
1806 const QList<QByteArray> supportedFormats = QImageWriter::supportedImageFormats();
1807 QStringList formats;
1808 formats.reserve( supportedFormats.size() );
1810 for (
const QByteArray &format : supportedFormats )
1812 if ( format ==
"svg" )
1816 formats.append( QString::fromUtf8( format ).toUpper() );
1819 std::sort( formats.begin(), formats.end(), [](
const QString &a,
const QString &b ) ->
bool {
1820 if ( a ==
"PNG"_L1 )
1824 if ( b ==
"PNG"_L1 )
1828 return a.localeAwareCompare( b ) < 0;
1837 QStringList fileFilters;
1838 fileFilters.reserve( formats.size() );
1840 for (
const QString &format : formats )
1842 const QString longName = format + QObject::tr(
" format" );
1843 const QString glob = u
"*."_s + format;
1845 fileFilters.append( u
"%1 (%2 %3)"_s.arg( longName, glob.toLower(), glob ) );
1848 return fileFilters.join(
";;"_L1 );
1856 : mSource( originalSource )
1857 , mOwnsSource( ownsOriginalSource )
1859 , mSourceFields( mSource->
fields() )
1860 , mSourceWkbType( mSource->
wkbType() )
1864 , mInvalidGeometryCheck(
1868 , mInvalidGeometryCallback( context.invalidGeometryCallback( originalSource ) )
1869 , mTransformErrorCallback( context.transformErrorCallback() )
1870 , mInvalidGeometryCallbackSkip( context.defaultInvalidGeometryCallbackForCheck(
Qgis::InvalidGeometryCheck::SkipInvalid, originalSource ) )
1871 , mInvalidGeometryCallbackAbort( context.defaultInvalidGeometryCallbackForCheck(
Qgis::InvalidGeometryCheck::AbortOnInvalid, originalSource ) )
1872 , mFeatureLimit( featureLimit )
1873 , mFilterExpression( filterExpression )
1895 if ( mFeatureLimit != -1 && req.
limit() != -1 )
1896 req.
setLimit( std::min(
static_cast< long long >( req.
limit() ), mFeatureLimit ) );
1897 else if ( mFeatureLimit != -1 )
1900 if ( !mFilterExpression.isEmpty() )
1903 return mSource->getFeatures( req );
1912 return sourceAvailability;
1925 if ( mFeatureLimit != -1 && req.
limit() != -1 )
1926 req.
setLimit( std::min(
static_cast< long long >( req.
limit() ), mFeatureLimit ) );
1927 else if ( mFeatureLimit != -1 )
1930 if ( !mFilterExpression.isEmpty() )
1933 return mSource->getFeatures( req );
1943 return mSourceFields;
1948 return mSourceWkbType;
1953 if ( !mFilterExpression.isEmpty() )
1956 if ( mFeatureLimit == -1 )
1957 return mSource->featureCount();
1959 return std::min( mFeatureLimit, mSource->featureCount() );
1969 if ( mFilterExpression.isEmpty() )
1970 return mSource->uniqueValues( fieldIndex, limit );
1974 if ( fieldIndex < 0 || fieldIndex >=
fields().count() )
1975 return QSet<QVariant>();
1982 QSet<QVariant> values;
1987 values.insert( f.
attribute( fieldIndex ) );
1988 if ( limit > 0 && values.size() >= limit )
1996 if ( mFilterExpression.isEmpty() )
1997 return mSource->minimumValue( fieldIndex );
2001 if ( fieldIndex < 0 || fieldIndex >=
fields().count() )
2013 const QVariant v = f.
attribute( fieldIndex );
2024 if ( mFilterExpression.isEmpty() )
2025 return mSource->maximumValue( fieldIndex );
2029 if ( fieldIndex < 0 || fieldIndex >=
fields().count() )
2041 const QVariant v = f.
attribute( fieldIndex );
2052 return mSourceExtent;
2057 if ( mFilterExpression.isEmpty() )
2058 return mSource->allFeatureIds();
2075 return mSourceSpatialIndexPresence;
2086 return expressionContextScope;
2091 mInvalidGeometryCheck = method;
2092 switch ( mInvalidGeometryCheck )
2095 mInvalidGeometryCallback =
nullptr;
2099 mInvalidGeometryCallback = mInvalidGeometryCallbackSkip;
2103 mInvalidGeometryCallback = mInvalidGeometryCallbackAbort;
2110 return mInvalidGeometryCheck;
2119 , mContext( context )
2120 , mSinkName( sinkName )
2121 , mOwnsSink( ownsOriginalSink )
2128 mContext.feedback()->reportError(
lastError() );
2149 if ( !result && mContext.feedback() )
2152 if ( !error.isEmpty() )
2153 mContext.feedback()->reportError( QObject::tr(
"Feature could not be written to %1: %2" ).arg( mSinkName, error ) );
2155 mContext.feedback()->reportError( QObject::tr(
"Feature could not be written to %1" ).arg( mSinkName ) );
2163 if ( !result && mContext.feedback() )
2166 if ( !error.isEmpty() )
2167 mContext.feedback()->reportError( QObject::tr(
"%n feature(s) could not be written to %1: %2",
nullptr, features.count() ).arg( mSinkName, error ) );
2169 mContext.feedback()->reportError( QObject::tr(
"%n feature(s) could not be written to %1",
nullptr, features.count() ).arg( mSinkName ) );
2177 if ( !result && mContext.feedback() )
2180 if ( !error.isEmpty() )
2181 mContext.feedback()->reportError( QObject::tr(
"Features could not be written to %1: %2" ).arg( mSinkName, error ) );
2183 mContext.feedback()->reportError( QObject::tr(
"Features could not be written to %1" ).arg( mSinkName ) );
Provides global constants and enumerations for use throughout the application.
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
@ VectorAnyGeometry
Any vector layer with geometry.
@ VectorPoint
Vector point layers.
@ VectorPolygon
Vector polygon layers.
@ VectorLine
Vector line layers.
@ FieldComments
Writer can support field comments.
@ FieldAliases
Writer can support field aliases.
SpatialIndexPresence
Enumeration of spatial index presence states.
@ Success
No errors were encountered.
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
FeatureAvailability
Possible return value for QgsFeatureSource::hasFeatures() to determine if a source is empty.
@ FeaturesMaybeAvailable
There may be features available in this source.
@ NoFeaturesAvailable
There are certainly no features available in this source.
@ TiledScene
Tiled scene layer. Added in QGIS 3.34.
@ Annotation
Contains freeform, georeferenced annotations. Added in QGIS 3.16.
@ VectorTile
Vector tile layer. Added in QGIS 3.14.
@ Mesh
Mesh layer. Added in QGIS 3.2.
@ PointCloud
Point cloud layer. Added in QGIS 3.18.
@ EditAlias
Allows editing aliases.
@ EditComment
Allows editing comments.
QFlags< VectorDataProviderAttributeEditCapability > VectorDataProviderAttributeEditCapabilities
Attribute editing capabilities which may be supported by vector data providers.
InvalidGeometryCheck
Methods for handling of features with invalid geometries.
@ NoCheck
No invalid geometry checking.
@ AbortOnInvalid
Close iterator on encountering any features with invalid geometry. This requires a slow geometry vali...
@ SkipInvalid
Skip any features with invalid geometry. This requires a slow geometry validity check for every featu...
@ OverrideDefaultGeometryCheck
If set, the default geometry check method (as dictated by QgsProcessingContext) will be overridden fo...
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
WkbType
The WKB type describes the number of dimensions a geometry has.
@ Hidden
Parameter is hidden and should not be shown to users.
@ NoSymbology
Export only data.
QFlags< ProcessingFeatureSourceFlag > ProcessingFeatureSourceFlags
Flags which control how QgsProcessingFeatureSource fetches features.
Represents a map layer containing a set of georeferenced annotations, e.g.
Represents a coordinate reference system (CRS).
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
Contains information about the context in which a coordinate transform is executed.
Custom exception class for Coordinate Reference System related exceptions.
QByteArray encodedUri() const
Returns the complete encoded URI as a byte array.
QString table() const
Returns the table name stored in the URI.
void setParam(const QString &key, const QString &value)
Sets a generic parameter value on the URI.
QString database() const
Returns the database name stored in the URI.
Abstract interface for generating an expression context scope.
virtual QgsExpressionContextScope * createExpressionContextScope() const =0
This method needs to be reimplemented in all classes which implement this interface and return an exp...
Single scope for storing variables and functions for use within a QgsExpressionContext.
void setFields(const QgsFields &fields)
Convenience function for setting a fields for the context.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
Wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFlags(Qgis::FeatureRequestFlags flags)
Sets flags that affect how features will be fetched.
QgsFeatureRequest & setLimit(long long limit)
Set the maximum number of features to request.
long long limit() const
Returns the maximum number of features to request, or -1 if no limit set.
QgsFeatureRequest & combineFilterExpression(const QString &expression)
Modifies the existing filter expression to add an additional expression filter.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QgsFeatureRequest & setInvalidGeometryCheck(Qgis::InvalidGeometryCheck check)
Sets invalid geometry checking behavior.
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
QgsFeatureRequest & setInvalidGeometryCallback(const std::function< void(const QgsFeature &)> &callback)
Sets a callback function to use when encountering an invalid geometry and invalidGeometryCheck() is s...
QgsFeatureRequest & setTransformErrorCallback(const std::function< void(const QgsFeature &)> &callback)
Sets a callback function to use when encountering a transform error when iterating features and a des...
An interface for objects which accept features via addFeature(s) methods.
QFlags< SinkFlag > SinkFlags
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
@ RegeneratePrimaryKey
This flag indicates, that a primary key field cannot be guaranteed to be unique and the sink should i...
An interface for objects which provide features via a getFeatures method.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
bool isCanceled() const
Tells whether the operation has been canceled already.
Encapsulate a field in an attribute table or data source.
void setName(const QString &name)
Set the field name.
Container of fields for a vector layer.
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Q_INVOKABLE int indexOf(const QString &fieldName) const
Gets the field index from the field name.
QgsField at(int i) const
Returns the field at particular index (must be in range 0..N-1).
Q_INVOKABLE int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
bool rename(int fieldIdx, const QString &name)
Renames a name of field.
static QString stringToSafeFilename(const QString &string)
Converts a string to a safe filename, replacing characters which are not safe for filenames with an '...
A storage object for map layers, in which the layers are owned by the store and have their lifetime b...
QMap< QString, QgsMapLayer * > mapLayers() const
Returns a map of all layers by layer ID.
QgsMapLayer * addMapLayer(QgsMapLayer *layer, bool takeOwnership=true)
Add a layer to the store.
Base class for all map layer types.
QString source() const
Returns the source for the layer.
QString providerType() const
Returns the provider type (provider key) for this layer.
QgsCoordinateReferenceSystem crs
virtual void setTransformContext(const QgsCoordinateTransformContext &transformContext)=0
Sets the coordinate transform context to transformContext.
static QgsVectorLayer * createMemoryLayer(const QString &name, const QgsFields &fields, Qgis::WkbType geometryType=Qgis::WkbType::NoGeometry, const QgsCoordinateReferenceSystem &crs=QgsCoordinateReferenceSystem(), bool loadDefaultStyle=true) SIP_FACTORY
Creates a new memory layer using the specified parameters.
Represents a mesh layer supporting display of data on structured or unstructured meshes.
QgsMeshDataProvider * dataProvider() override
Returns the layer's data provider, it may be nullptr.
Base class for plugin layers.
Represents a map layer supporting display of point clouds.
Abstract base class for processing algorithms.
Contains information about the context in which a processing algorithm is executed.
QString defaultEncoding() const
Returns the default encoding to use for newly created files.
QgsProcessingFeedback * feedback()
Returns the associated feedback object.
QgsExpressionContext & expressionContext()
Returns the expression context.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
QgsProject * project() const
Returns the project in which the algorithm is being executed.
QgsMapLayerStore * temporaryLayerStore()
Returns a reference to the layer store used for storing temporary layers during algorithm execution.
QString temporaryFolder() const
Returns the (optional) temporary folder to use when running algorithms.
Custom exception class for processing related exceptions.
QgsProxyFeatureSink subclass which reports feature addition errors to a QgsProcessingContext.
void finalize() override
Finalizes the sink, flushing any buffered features to the destination.
~QgsProcessingFeatureSink() override
QgsProcessingFeatureSink(QgsFeatureSink *originalSink, const QString &sinkName, QgsProcessingContext &context, bool ownsOriginalSink=false)
Constructor for QgsProcessingFeatureSink, accepting an original feature sink originalSink and process...
bool addFeatures(QgsFeatureList &features, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a list of features to the sink.
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a single feature to the sink.
Encapsulates settings relating to a feature source input to a processing algorithm.
bool selectedFeaturesOnly
true if only selected features in the source should be used by algorithms.
QgsProperty source
Source definition.
Qgis::InvalidGeometryCheck geometryCheck
Geometry check method to apply to this source.
Qgis::ProcessingFeatureSourceDefinitionFlags flags
Flags which dictate source behavior.
long long featureLimit
If set to a value > 0, places a limit on the maximum number of features which will be read from the s...
QString filterExpression
Optional expression filter to use for filtering features which will be read from the source.
QgsFeatureSource subclass which proxies methods to an underlying QgsFeatureSource,...
QgsRectangle sourceExtent() const override
Returns the extent of all geometries from the source.
QSet< QVariant > uniqueValues(int fieldIndex, int limit=-1) const override
Returns the set of unique values contained within the specified fieldIndex from this source.
QgsExpressionContextScope * createExpressionContextScope() const
Returns an expression context scope suitable for this source.
QgsProcessingFeatureSource(QgsFeatureSource *originalSource, const QgsProcessingContext &context, bool ownsOriginalSource=false, long long featureLimit=-1, const QString &filterExpression=QString())
Constructor for QgsProcessingFeatureSource, accepting an original feature source originalSource and p...
void setInvalidGeometryCheck(Qgis::InvalidGeometryCheck method)
Overrides the default geometry check method for the source.
Qgis::InvalidGeometryCheck invalidGeometryCheck() const
Returns the geometry check method for the source.
QVariant maximumValue(int fieldIndex) const override
Returns the maximum value for an attribute column or an invalid variant in case of error.
~QgsProcessingFeatureSource() override
QgsCoordinateReferenceSystem sourceCrs() const override
Returns the coordinate reference system for features in the source.
Qgis::WkbType wkbType() const override
Returns the geometry type for features returned by this source.
QVariant minimumValue(int fieldIndex) const override
Returns the minimum value for an attribute column or an invalid variant in case of error.
long long featureCount() const override
Returns the number of features contained in the source, or -1 if the feature count is unknown.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request, Qgis::ProcessingFeatureSourceFlags flags) const
Returns an iterator for the features in the source, respecting the supplied feature flags.
Qgis::FeatureAvailability hasFeatures() const override
Determines if there are any features available in the source.
QString sourceName() const override
Returns a friendly display name for the source.
QgsFeatureIds allFeatureIds() const override
Returns a list of all feature IDs for features present in the source.
Qgis::SpatialIndexPresence hasSpatialIndex() const override
Returns an enum value representing the presence of a valid spatial index on the source,...
QgsFields fields() const override
Returns the fields associated with features in the source.
Base class for providing feedback from a processing algorithm.
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
Base class for the definition of processing outputs.
Encapsulates settings relating to a feature sink or output raster layer for a processing algorithm.
QgsProperty sink
Sink/layer definition.
Base class for the definition of processing parameters.
static QList< QgsTiledSceneLayer * > compatibleTiledSceneLayers(QgsProject *project, bool sort=true)
Returns a list of tiled scene layers from a project which are compatible with the processing framewor...
static QString stringToPythonLiteral(const QString &string)
Converts a string to a Python string literal.
static QString defaultVectorExtension()
Returns the default vector extension to use, in the absence of all other constraints (e....
static QVariant generateIteratingDestination(const QVariant &input, const QVariant &id, QgsProcessingContext &context)
Converts an input parameter value for use in source iterating mode, where one individual sink is crea...
static QgsFields indicesToFields(const QList< int > &indices, const QgsFields &fields)
Returns a subset of fields based on the indices of desired fields.
static QList< int > fieldNamesToIndices(const QStringList &fieldNames, const QgsFields &fields)
Returns a list of field indices parsed from the given list of field names.
static QString layerToStringIdentifier(const QgsMapLayer *layer, const QString &layerName=QString())
Returns a string representation of the source for a layer.
static QVariantMap preprocessQgisProcessParameters(const QVariantMap ¶meters, bool &ok, QString &error)
Pre-processes a set of parameter values for the qgis_process command.
static QList< QgsAnnotationLayer * > compatibleAnnotationLayers(QgsProject *project, bool sort=true)
Returns a list of annotation layers from a project which are compatible with the processing framework...
static QString generateTempFilename(const QString &basename, const QgsProcessingContext *context=nullptr)
Returns a temporary filename for a given file, putting it into a temporary folder (creating that fold...
static QString normalizeLayerSource(const QString &source)
Normalizes a layer source string for safe comparison across different operating system environments.
static QString formatHelpMapAsHtml(const QVariantMap &map, const QgsProcessingAlgorithm *algorithm)
Returns a HTML formatted version of the help text encoded in a variant map for a specified algorithm.
static QgsFields combineFields(const QgsFields &fieldsA, const QgsFields &fieldsB, const QString &fieldsBPrefix=QString())
Combines two field lists, avoiding duplicate field names (in a case-insensitive manner).
static QString encodeProviderKeyAndUri(const QString &providerKey, const QString &uri)
Encodes a provider key and layer uri to a single string, for use with decodeProviderKeyAndUri().
LayerHint
Layer type hints.
@ TiledScene
Tiled scene layer type, since QGIS 3.34.
@ Annotation
Annotation layer type, since QGIS 3.22.
@ Vector
Vector layer type.
@ VectorTile
Vector tile layer type, since QGIS 3.32.
@ Mesh
Mesh layer type, since QGIS 3.6.
@ Raster
Raster layer type.
@ UnknownType
Unknown layer type.
@ PointCloud
Point cloud layer type, since QGIS 3.22.
static int parameterDefinitionIndex(const QgsProcessingAlgorithm *algorithm, const QString &name)
Returns the index of the parameter with matching name for a specified algorithm.
static QString defaultRasterFormat()
Returns the default raster format to use, in the absence of all other constraints (e....
static QgsProcessingFeatureSource * variantToSource(const QVariant &value, QgsProcessingContext &context, const QVariant &fallbackValue=QVariant())
Converts a variant value to a new feature source.
static QList< QgsRasterLayer * > compatibleRasterLayers(QgsProject *project, bool sort=true)
Returns a list of raster layers from a project which are compatible with the processing framework.
static int outputDefinitionIndex(const QgsProcessingAlgorithm *algorithm, const QString &name)
Returns the index of the output matching name for a specified algorithm.
static QgsRectangle combineLayerExtents(const QList< QgsMapLayer * > &layers, const QgsCoordinateReferenceSystem &crs, QgsProcessingContext &context)
Combines the extent of several map layers.
static QString resolveDefaultEncoding(const QString &defaultEncoding="System")
Returns the default encoding.
static QList< QgsPluginLayer * > compatiblePluginLayers(QgsProject *project, bool sort=true)
Returns a list of plugin layers from a project which are compatible with the processing framework.
static QString variantToPythonLiteral(const QVariant &value)
Converts a variant to a Python literal.
static QgsCoordinateReferenceSystem variantToCrs(const QVariant &value, QgsProcessingContext &context, const QVariant &fallbackValue=QVariant())
Converts a variant value to a coordinate reference system.
static QList< QgsVectorLayer * > compatibleVectorLayers(QgsProject *project, const QList< int > &sourceTypes=QList< int >(), bool sort=true)
Returns a list of vector layers from a project which are compatible with the processing framework.
static QVariantMap removePointerValuesFromMap(const QVariantMap &map)
Removes any raw pointer values from an input map, replacing them with appropriate string values where...
static bool decodeProviderKeyAndUri(const QString &string, QString &providerKey, QString &uri)
Decodes a provider key and layer uri from an encoded string, for use with encodeProviderKeyAndUri().
static void createFeatureSinkPython(QgsFeatureSink **sink, QString &destination, QgsProcessingContext &context, const QgsFields &fields, Qgis::WkbType geometryType, const QgsCoordinateReferenceSystem &crs, const QVariantMap &createOptions=QVariantMap())
Creates a feature sink ready for adding features.
static QList< QgsVectorTileLayer * > compatibleVectorTileLayers(QgsProject *project, bool sort=true)
Returns a list of vector tile layers from a project which are compatible with the processing framewor...
static QString convertToCompatibleFormatAndLayerName(const QgsVectorLayer *layer, bool selectedFeaturesOnly, const QString &baseName, const QStringList &compatibleFormats, const QString &preferredFormat, QgsProcessingContext &context, QgsProcessingFeedback *feedback, QString &layerName, long long featureLimit=-1, const QString &filterExpression=QString())
Converts a source vector layer to a file path and layer name of a vector layer of compatible format.
static QList< QgsMapLayer * > compatibleLayers(QgsProject *project, bool sort=true)
Returns a list of map layers from a project which are compatible with the processing framework.
static QString convertToCompatibleFormat(const QgsVectorLayer *layer, bool selectedFeaturesOnly, const QString &baseName, const QStringList &compatibleFormats, const QString &preferredFormat, QgsProcessingContext &context, QgsProcessingFeedback *feedback, long long featureLimit=-1, const QString &filterExpression=QString())
Converts a source vector layer to a file path of a vector layer of compatible format.
static QgsFeatureSink * createFeatureSink(QString &destination, QgsProcessingContext &context, const QgsFields &fields, Qgis::WkbType geometryType, const QgsCoordinateReferenceSystem &crs, const QVariantMap &createOptions=QVariantMap(), const QStringList &datasourceOptions=QStringList(), const QStringList &layerOptions=QStringList(), QgsFeatureSink::SinkFlags sinkFlags=QgsFeatureSink::SinkFlags(), QgsRemappingSinkDefinition *remappingDefinition=nullptr)
Creates a feature sink ready for adding features.
static QString defaultRasterExtension()
Returns the default raster extension to use, in the absence of all other constraints (e....
static QString defaultVectorTileExtension()
Returns the default vector tile extension to use, in the absence of all other constraints (e....
static QgsMapLayer * mapLayerFromString(const QString &string, QgsProcessingContext &context, bool allowLoadingNewLayers=true, QgsProcessingUtils::LayerHint typeHint=QgsProcessingUtils::LayerHint::UnknownType, QgsProcessing::LayerOptionsFlags flags=QgsProcessing::LayerOptionsFlags())
Interprets a string as a map layer within the supplied context.
static QString defaultPointCloudExtension()
Returns the default point cloud extension to use, in the absence of all other constraints (e....
static QList< QgsPointCloudLayer * > compatiblePointCloudLayers(QgsProject *project, bool sort=true)
Returns a list of point cloud layers from a project which are compatible with the processing framewor...
static QStringList supportedImageFormats()
Returns a list of image format extensions supported by QImageWriter.
static QString supportedImageFileFilters()
Returns a file filter string of all supported image formats, suitable for use in file picker dialogs.
static QList< QgsMeshLayer * > compatibleMeshLayers(QgsProject *project, bool sort=true)
Returns a list of mesh layers from a project which are compatible with the processing framework.
static QString tempFolder(const QgsProcessingContext *context=nullptr)
Returns a session specific processing temporary folder for use in processing algorithms.
static const QgsSettingsEntryString * settingsDefaultOutputRasterLayerFormat
Settings entry default output raster layer format.
QFlags< LayerOptionsFlag > LayerOptionsFlags
static const QgsSettingsEntryString * settingsTempPath
Settings entry temp path.
static const QString TEMPORARY_OUTPUT
Constant used to indicate that a Processing algorithm output should be a temporary layer/file.
static const QgsSettingsEntryString * settingsDefaultOutputVectorLayerExt
Settings entry default output vector layer ext.
@ SkipIndexGeneration
Do not generate index when creating a layer. Makes sense only for point cloud layers.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
QgsAnnotationLayer * mainAnnotationLayer()
Returns the main annotation layer associated with the project.
QVector< T > layers() const
Returns a list of registered map layers with a specified layer type.
QgsCoordinateReferenceSystem crs
A store for object properties.
QString asExpression() const
Returns an expression string representing the state of the property, or an empty string if the proper...
Qgis::PropertyType propertyType() const
Returns the property type.
static QgsProperty fromExpression(const QString &expression, bool isActive=true)
Returns a new ExpressionBasedProperty created from the specified expression.
static QgsProperty fromField(const QString &fieldName, bool isActive=true)
Returns a new FieldBasedProperty created from the specified field name.
static QgsProperty fromValue(const QVariant &value, bool isActive=true)
Returns a new StaticProperty created from the specified value.
QVariantMap decodeUri(const QString &providerKey, const QString &uri)
Breaks a provider data source URI into its component paths (e.g.
static QgsProviderRegistry * instance(const QString &pluginPath=QString())
Means of accessing canonical single instance.
QList< QgsProviderRegistry::ProviderCandidateDetails > preferredProvidersForUri(const QString &uri) const
Returns the details for the preferred provider(s) for opening the specified uri.
QString encodeUri(const QString &providerKey, const QVariantMap &parts)
Reassembles a provider data source URI from its component paths (e.g.
QgsProviderMetadata * providerMetadata(const QString &providerKey) const
Returns metadata of the provider or nullptr if not found.
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a single feature to the sink.
bool flushBuffer() override
Flushes any internal buffer which may exist in the sink, causing any buffered features to be added to...
QgsFeatureSink * mSink
Underlying destination sink.
QString lastError() const override
Returns the most recent error encountered by the sink, e.g.
bool addFeatures(QgsFeatureList &features, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a list of features to the sink.
QgsProxyFeatureSink(QgsFeatureSink *sink)
Constructs a new QgsProxyFeatureSink which forwards features onto a destination sink.
static QStringList extensionsForFormat(const QString &format)
Returns a list of known file extensions for the given GDAL driver format.
static QList< QgsRasterFileWriter::FilterFormatDetails > supportedFiltersAndFormats(RasterFormatOptions options=SortRecommended)
Returns a list or pairs, with format filter string as first element and GDAL format key as second ele...
Represents a raster layer.
A rectangle specified with double values.
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle.
QgsCoordinateReferenceSystem crs() const
Returns the associated coordinate reference system, or an invalid CRS if no reference system is set.
A QgsPointXY with associated coordinate reference system.
A QgsRectangle with associated coordinate reference system.
Defines the parameters used to remap features when creating a QgsRemappingProxyFeatureSink.
void setDestinationCrs(const QgsCoordinateReferenceSystem &destination)
Sets the destination crs used for reprojecting incoming features to the sink's destination CRS.
void setDestinationWkbType(Qgis::WkbType type)
Sets the WKB geometry type for the destination.
void setDestinationFields(const QgsFields &fields)
Sets the fields for the destination sink.
Represents a map layer supporting display of tiled scene objects.
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
virtual Qgis::VectorDataProviderAttributeEditCapabilities attributeEditCapabilities() const
Returns the provider's supported attribute editing capabilities.
Options to pass to QgsVectorFileWriter::writeAsVectorFormat().
QString fileEncoding
Encoding to use.
QString driverName
OGR driver to use.
QString layerName
Layer name. If let empty, it will be derived from the filename.
QStringList layerOptions
List of OGR layer creation options.
Qgis::FeatureSymbologyExport symbologyExport
Symbology to export.
QgsVectorFileWriter::ActionOnExistingFile actionOnExistingFile
Action on existing file.
QStringList datasourceOptions
List of OGR data source creation options.
static QStringList defaultLayerOptions(const QString &driverName)
Returns a list of the default layer options for a specified driver.
static QString driverForExtension(const QString &extension)
Returns the OGR driver name for a specified file extension.
static QgsVectorFileWriter * create(const QString &fileName, const QgsFields &fields, Qgis::WkbType geometryType, const QgsCoordinateReferenceSystem &srs, const QgsCoordinateTransformContext &transformContext, const QgsVectorFileWriter::SaveVectorOptions &options, QgsFeatureSink::SinkFlags sinkFlags=QgsFeatureSink::SinkFlags(), QString *newFilename=nullptr, QString *newLayer=nullptr)
Create a new vector file writer.
static QStringList defaultDatasetOptions(const QString &driverName)
Returns a list of the default dataset options for a specified driver.
static QStringList supportedFormatExtensions(VectorFormatOptions options=SortRecommended)
Returns a list of file extensions for supported formats, e.g "shp", "gpkg".
@ CreateOrOverwriteFile
Create or overwrite file.
@ AppendToLayerNoNewFields
Append features to existing layer, but do not create new fields.
QgsFeatureSource subclass for the selected features from a QgsVectorLayer.
Represents a vector layer which manages a vector based dataset.
bool isSpatial() const final
Returns true if this is a geometry layer and false in case of NoGeometry (table only) or UnknownGeome...
QgsRectangle extent() const final
Returns the extent of the layer.
Q_INVOKABLE Qgis::WkbType wkbType() const final
Returns the WKBType or WKBUnknown in case of error.
QgsFeatureIterator getSelectedFeatures(QgsFeatureRequest request=QgsFeatureRequest()) const
Returns an iterator of the selected features.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const final
Queries the layer for features specified in request.
Q_INVOKABLE Qgis::GeometryType geometryType() const
Returns point, line or polygon.
QgsVectorDataProvider * dataProvider() final
Returns the layer's data provider, it may be nullptr.
Implements a map layer that is dedicated to rendering of vector tiles.
Handles storage of information regarding WKB types and their properties.
@ UnknownCount
Provider returned an unknown feature count.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into allowing algorithms to be written in pure substantial changes are required in order to port existing x Processing algorithms for QGIS x The most significant changes are outlined not GeoAlgorithm For algorithms which operate on features one by consider subclassing the QgsProcessingFeatureBasedAlgorithm class This class allows much of the boilerplate code for looping over features from a vector layer to be bypassed and instead requires implementation of a processFeature method Ensure that your algorithm(or algorithm 's parent class) implements the new pure virtual createInstance(self) call
bool qgsVariantLessThan(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether the first is less than the second.
bool qgsVariantGreaterThan(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether the first is greater than the second.
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
QList< QgsFeature > QgsFeatureList
QSet< QgsFeatureId > QgsFeatureIds
QList< int > QgsAttributeList
QString convertToCompatibleFormatInternal(const QgsVectorLayer *vl, bool selectedFeaturesOnly, const QString &baseName, const QStringList &compatibleFormats, const QString &preferredFormat, QgsProcessingContext &context, QgsProcessingFeedback *feedback, QString *layerName, long long featureLimit, const QString &filterExpression, bool renameFid)
bool skipCrsValidation
Controls whether the layer is allowed to have an invalid/unknown CRS.
bool skipCrsValidation
Controls whether the layer is allowed to have an invalid/unknown CRS.
bool skipIndexGeneration
Set to true if point cloud index generation should be skipped.
bool skipCrsValidation
Controls whether the layer is allowed to have an invalid/unknown CRS.
bool loadDefaultStyle
Sets to true if the default layer style should be loaded.
bool skipCrsValidation
Controls whether the layer is allowed to have an invalid/unknown CRS.
Setting options for loading vector layers.
bool skipCrsValidation
Controls whether the layer is allowed to have an invalid/unknown CRS.
bool loadDefaultStyle
Set to true if the default layer style should be loaded.