39#include <QRegularExpression>
44 return compatibleMapLayers< QgsRasterLayer >( project, sort );
50 return QList<QgsVectorLayer *>();
52 QList<QgsVectorLayer *> layers;
56 if ( canUseLayer( l, geometryTypes ) )
64 return QString::localeAwareCompare( a->name(), b->name() ) < 0;
72 return compatibleMapLayers< QgsMeshLayer >( project, sort );
77 return compatibleMapLayers< QgsPluginLayer >( project, sort );
82 return compatibleMapLayers< QgsPointCloudLayer >( project, sort );
88 QList<QgsAnnotationLayer *> res = compatibleMapLayers< QgsAnnotationLayer >( project,
false );
96 return QString::localeAwareCompare( a->name(), b->name() ) < 0;
105 return compatibleMapLayers< QgsVectorTileLayer >( project, sort );
108template<
typename T> QList<T *> QgsProcessingUtils::compatibleMapLayers(
QgsProject *project,
bool sort )
114 const auto projectLayers = project->
layers<T *>();
115 for ( T *l : projectLayers )
117 if ( canUseLayer( l ) )
123 std::sort( layers.begin(), layers.end(), [](
const T * a,
const T * b ) ->
bool
125 return QString::localeAwareCompare( a->name(), b->name() ) < 0;
134 return QList<QgsMapLayer *>();
136 QList<QgsMapLayer *> layers;
138 const auto rasterLayers = compatibleMapLayers< QgsRasterLayer >( project,
false );
146 const auto meshLayers = compatibleMapLayers< QgsMeshLayer >( project,
false );
150 const auto pointCloudLayers = compatibleMapLayers< QgsPointCloudLayer >( project,
false );
154 const auto annotationLayers = compatibleMapLayers< QgsAnnotationLayer >( project,
false );
159 const auto vectorTileLayers = compatibleMapLayers< QgsVectorTileLayer >( project,
false );
163 const auto pluginLayers = compatibleMapLayers< QgsPluginLayer >( project,
false );
171 return QString::localeAwareCompare( a->name(), b->name() ) < 0;
179 return QStringLiteral(
"%1://%2" ).arg( providerKey, uri );
184 const thread_local QRegularExpression re( QStringLiteral(
"^(\\w+?):\\/\\/(.+)$" ) );
185 const QRegularExpressionMatch match = re.match(
string );
186 if ( !match.hasMatch() )
189 providerKey = match.captured( 1 );
190 uri = match.captured( 2 );
198 if ( !store ||
string.isEmpty() )
201 QList< QgsMapLayer * > layers = store->
mapLayers().values();
203 layers.erase( std::remove_if( layers.begin(), layers.end(), [](
QgsMapLayer * layer )
205 switch ( layer->type() )
207 case Qgis::LayerType::Vector:
208 return !canUseLayer( qobject_cast< QgsVectorLayer * >( layer ) );
209 case Qgis::LayerType::Raster:
210 return !canUseLayer( qobject_cast< QgsRasterLayer * >( layer ) );
211 case Qgis::LayerType::Plugin:
212 case Qgis::LayerType::Group:
214 case Qgis::LayerType::Mesh:
215 return !canUseLayer( qobject_cast< QgsMeshLayer * >( layer ) );
216 case Qgis::LayerType::VectorTile:
217 return !canUseLayer( qobject_cast< QgsVectorTileLayer * >( layer ) );
218 case Qgis::LayerType::PointCloud:
219 return !canUseLayer( qobject_cast< QgsPointCloudLayer * >( layer ) );
220 case Qgis::LayerType::Annotation:
221 return !canUseLayer( qobject_cast< QgsAnnotationLayer * >( layer ) );
226 auto isCompatibleType = [typeHint](
QgsMapLayer * l ) ->
bool
230 case LayerHint::UnknownType:
233 case LayerHint::Vector:
234 return l->type() == Qgis::LayerType::Vector;
236 case LayerHint::Raster:
237 return l->type() == Qgis::LayerType::Raster;
239 case LayerHint::Mesh:
240 return l->type() == Qgis::LayerType::Mesh;
242 case LayerHint::PointCloud:
243 return l->type() == Qgis::LayerType::PointCloud;
245 case LayerHint::Annotation:
246 return l->type() == Qgis::LayerType::Annotation;
248 case LayerHint::VectorTile:
249 return l->type() == Qgis::LayerType::VectorTile;
256 if ( isCompatibleType( l ) && l->id() == string )
261 if ( isCompatibleType( l ) && l->name() == string )
266 if ( isCompatibleType( l ) && normalizeLayerSource( l->source() ) == normalizeLayerSource(
string ) )
282 if ( !useProvider || ( provider == QLatin1String(
"ogr" ) || provider == QLatin1String(
"gdal" ) || provider == QLatin1String(
"mdal" ) || provider == QLatin1String(
"pdal" ) || provider == QLatin1String(
"ept" ) || provider == QLatin1String(
"copc" ) ) )
284 QStringList components = uri.split(
'|' );
285 if ( components.isEmpty() )
289 if ( QFileInfo::exists( uri ) )
290 fi = QFileInfo( uri );
291 else if ( QFileInfo::exists( components.at( 0 ) ) )
292 fi = QFileInfo( components.at( 0 ) );
295 name = fi.baseName();
306 options.loadDefaultStyle =
false;
307 options.skipCrsValidation =
true;
309 std::unique_ptr< QgsVectorLayer > layer;
312 layer = std::make_unique<QgsVectorLayer>( uri, name, provider, options );
317 layer = std::make_unique<QgsVectorLayer>( uri, name, QStringLiteral(
"ogr" ), options );
319 if ( layer->isValid() )
321 return layer.release();
330 std::unique_ptr< QgsRasterLayer > rasterLayer;
333 rasterLayer = std::make_unique< QgsRasterLayer >( uri, name, provider, rasterOptions );
338 rasterLayer = std::make_unique< QgsRasterLayer >( uri, name, QStringLiteral(
"gdal" ), rasterOptions );
341 if ( rasterLayer->isValid() )
343 return rasterLayer.release();
351 std::unique_ptr< QgsMeshLayer > meshLayer;
354 meshLayer = std::make_unique< QgsMeshLayer >( uri, name, provider, meshOptions );
358 meshLayer = std::make_unique< QgsMeshLayer >( uri, name, QStringLiteral(
"mdal" ), meshOptions );
360 if ( meshLayer->isValid() )
362 return meshLayer.release();
375 std::unique_ptr< QgsPointCloudLayer > pointCloudLayer;
378 pointCloudLayer = std::make_unique< QgsPointCloudLayer >( uri, name, provider, pointCloudOptions );
383 if ( !preferredProviders.empty() )
385 pointCloudLayer = std::make_unique< QgsPointCloudLayer >( uri, name, preferredProviders.at( 0 ).metadata()->key(), pointCloudOptions );
388 if ( pointCloudLayer && pointCloudLayer->isValid() )
390 return pointCloudLayer.release();
396 dsUri.
setParam(
"type",
"mbtiles" );
399 std::unique_ptr< QgsVectorTileLayer > tileLayer;
400 tileLayer = std::make_unique< QgsVectorTileLayer >( dsUri.
encodedUri(), name );
402 if ( tileLayer->isValid() )
404 return tileLayer.release();
412 if (
string.isEmpty() )
420 if (
auto *lProject = context.
project() )
422 QgsMapLayer *layer = mapLayerFromStore(
string, lProject->layerStore(), typeHint );
431 if ( !allowLoadingNewLayers )
434 layer = loadMapLayerFromString(
string, context.
transformContext(), typeHint, flags );
448 QVariant val = value;
449 bool selectedFeaturesOnly =
false;
450 long long featureLimit = -1;
451 QString filterExpression;
452 bool overrideGeometryCheck =
false;
454 if ( val.userType() == QMetaType::type(
"QgsProcessingFeatureSourceDefinition" ) )
462 overrideGeometryCheck = fromVar.
flags & QgsProcessingFeatureSourceDefinition::Flag::FlagOverrideDefaultGeometryCheck;
465 else if ( val.userType() == QMetaType::type(
"QgsProcessingOutputLayerDefinition" ) )
472 if (
QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( qvariant_cast<QObject *>( val ) ) )
474 std::unique_ptr< QgsProcessingFeatureSource> source = std::make_unique< QgsProcessingFeatureSource >( layer, context,
false, featureLimit, filterExpression );
475 if ( overrideGeometryCheck )
476 source->setInvalidGeometryCheck( geometryCheck );
477 return source.release();
481 if ( val.userType() == QMetaType::type(
"QgsProperty" ) )
485 else if ( !val.isValid() || val.toString().isEmpty() )
488 if (
QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( qvariant_cast<QObject *>( fallbackValue ) ) )
490 std::unique_ptr< QgsProcessingFeatureSource> source = std::make_unique< QgsProcessingFeatureSource >( layer, context,
false, featureLimit, filterExpression );
491 if ( overrideGeometryCheck )
492 source->setInvalidGeometryCheck( geometryCheck );
493 return source.release();
496 layerRef = fallbackValue.toString();
500 layerRef = val.toString();
503 if ( layerRef.isEmpty() )
510 std::unique_ptr< QgsProcessingFeatureSource> source;
511 if ( selectedFeaturesOnly )
517 source = std::make_unique< QgsProcessingFeatureSource >( vl, context,
false, featureLimit, filterExpression );
520 if ( overrideGeometryCheck )
521 source->setInvalidGeometryCheck( geometryCheck );
522 return source.release();
527 QVariant val = value;
529 if ( val.userType() == QMetaType::type(
"QgsCoordinateReferenceSystem" ) )
534 else if ( val.userType() == QMetaType::type(
"QgsProcessingFeatureSourceDefinition" ) )
540 else if ( val.userType() == QMetaType::type(
"QgsProcessingOutputLayerDefinition" ) )
553 if (
QgsMapLayer *layer = qobject_cast< QgsMapLayer * >( qvariant_cast<QObject *>( val ) ) )
556 if ( val.userType() == QMetaType::type(
"QgsProperty" ) )
559 if ( !val.isValid() )
565 QString crsText = val.toString();
566 if ( crsText.isEmpty() )
567 crsText = fallbackValue.toString();
569 if ( crsText.isEmpty() )
573 if ( context.
project() && crsText.compare( QLatin1String(
"ProjectCrs" ), Qt::CaseInsensitive ) == 0 )
586bool QgsProcessingUtils::canUseLayer(
const QgsMeshLayer *layer )
591bool QgsProcessingUtils::canUseLayer(
const QgsPluginLayer *layer )
593 return layer && layer->
isValid();
598 return layer && layer->
isValid();
601bool QgsProcessingUtils::canUseLayer(
const QgsRasterLayer *layer )
603 return layer && layer->
isValid();
608 return layer && layer->
isValid();
613 return layer && layer->
isValid();
616bool QgsProcessingUtils::canUseLayer(
const QgsVectorLayer *layer,
const QList<int> &sourceTypes )
618 return layer && layer->
isValid() &&
619 ( sourceTypes.isEmpty()
630 QString normalized = source;
631 normalized.replace(
'\\',
'/' );
632 return normalized.trimmed();
637 if ( !value.isValid() )
638 return QStringLiteral(
"None" );
640 if ( value.userType() == QMetaType::type(
"QgsProperty" ) )
641 return QStringLiteral(
"QgsProperty.fromExpression('%1')" ).arg( value.value<
QgsProperty >().
asExpression() );
642 else if ( value.userType() == QMetaType::type(
"QgsCoordinateReferenceSystem" ) )
645 return QStringLiteral(
"QgsCoordinateReferenceSystem()" );
649 else if ( value.userType() == QMetaType::type(
"QgsRectangle" ) )
657 else if ( value.userType() == QMetaType::type(
"QgsReferencedRectangle" ) )
665 else if ( value.userType() == QMetaType::type(
"QgsPointXY" ) )
671 else if ( value.userType() == QMetaType::type(
"QgsReferencedPointXY" ) )
679 switch ( value.type() )
682 return value.toBool() ? QStringLiteral(
"True" ) : QStringLiteral(
"False" );
684 case QVariant::Double:
685 return QString::number( value.toDouble() );
689 return QString::number( value.toInt() );
691 case QVariant::LongLong:
692 case QVariant::ULongLong:
693 return QString::number( value.toLongLong() );
698 const QVariantList vl = value.toList();
699 for (
const QVariant &v : vl )
703 return parts.join(
',' ).prepend(
'[' ).append(
']' );
708 const QVariantMap map = value.toMap();
710 parts.reserve( map.size() );
711 for (
auto it = map.constBegin(); it != map.constEnd(); ++it )
715 return parts.join(
',' ).prepend(
'{' ).append(
'}' );
718 case QVariant::DateTime:
720 const QDateTime dateTime = value.toDateTime();
721 return QStringLiteral(
"QDateTime(QDate(%1, %2, %3), QTime(%4, %5, %6))" )
722 .arg( dateTime.date().year() )
723 .arg( dateTime.date().month() )
724 .arg( dateTime.date().day() )
725 .arg( dateTime.time().hour() )
726 .arg( dateTime.time().minute() )
727 .arg( dateTime.time().second() );
740 s.replace(
'\\', QLatin1String(
"\\\\" ) );
741 s.replace(
'\n', QLatin1String(
"\\n" ) );
742 s.replace(
'\r', QLatin1String(
"\\r" ) );
743 s.replace(
'\t', QLatin1String(
"\\t" ) );
745 if ( s.contains(
'\'' ) && !s.contains(
'\"' ) )
747 s = s.prepend(
'"' ).append(
'"' );
751 s.replace(
'\'', QLatin1String(
"\\\'" ) );
752 s = s.prepend(
'\'' ).append(
'\'' );
757void QgsProcessingUtils::parseDestinationString( QString &destination, QString &providerKey, QString &uri, QString &layerName, QString &format, QMap<QString, QVariant> &options,
bool &useWriter, QString &extension )
764 const thread_local QRegularExpression splitRx( QStringLiteral(
"^(.{3,}?):(.*)$" ) );
765 QRegularExpressionMatch match = splitRx.match( destination );
766 if ( match.hasMatch() )
768 providerKey = match.captured( 1 );
769 uri = match.captured( 2 );
776 if ( providerKey == QLatin1String(
"postgis" ) )
778 providerKey = QStringLiteral(
"postgres" );
780 if ( providerKey == QLatin1String(
"ogr" ) )
785 if ( !dsUri.
table().isEmpty() )
787 layerName = dsUri.
table();
788 options.insert( QStringLiteral(
"layerName" ), layerName );
791 extension = QFileInfo( uri ).completeSuffix();
793 options.insert( QStringLiteral(
"driverName" ), format );
797 extension = QFileInfo( uri ).completeSuffix();
800 options.insert( QStringLiteral(
"update" ),
true );
807 providerKey = QStringLiteral(
"ogr" );
809 const thread_local QRegularExpression splitRx( QStringLiteral(
"^(.*)\\.(.*?)$" ) );
810 QRegularExpressionMatch match = splitRx.match( destination );
811 if ( match.hasMatch() )
813 extension = match.captured( 2 );
817 if ( format.isEmpty() )
819 format = QStringLiteral(
"GPKG" );
820 destination = destination + QStringLiteral(
".gpkg" );
823 options.insert( QStringLiteral(
"driverName" ), format );
830 QVariantMap options = createOptions;
831 if ( !options.contains( QStringLiteral(
"fileEncoding" ) ) )
837 if ( destination.isEmpty() || destination.startsWith( QLatin1String(
"memory:" ) ) )
840 if ( destination.startsWith( QLatin1String(
"memory:" ) ) )
841 destination = destination.mid( 7 );
843 if ( destination.isEmpty() )
844 destination = QStringLiteral(
"output" );
848 if ( !layer || !layer->isValid() )
859 feedback->pushWarning( QObject::tr(
"%1: Aliases are not compatible with scratch layers" ).arg(
field.
name() ) );
861 feedback->pushWarning( QObject::tr(
"%1: Comments are not compatible with scratch layers" ).arg(
field.
name() ) );
868 destination = layer->id();
871 std::unique_ptr< QgsProcessingFeatureSink > sink(
new QgsProcessingFeatureSink( layer->dataProvider(), destination, context ) );
874 return sink.release();
883 bool useWriter =
false;
884 parseDestinationString( destination, providerKey, uri, layerName, format, options, useWriter, extension );
887 if ( useWriter && providerKey == QLatin1String(
"ogr" ) )
891 QString finalFileName;
892 QString finalLayerName;
894 saveOptions.
fileEncoding = options.value( QStringLiteral(
"fileEncoding" ) ).toString();
895 saveOptions.
layerName = !layerName.isEmpty() ? layerName : options.value( QStringLiteral(
"layerName" ) ).toString();
900 if ( remappingDefinition )
904 std::unique_ptr< QgsVectorLayer > vl = std::make_unique< QgsVectorLayer >( destination );
909 newFields = vl->fields();
919 if ( writer->hasError() )
921 throw QgsProcessingException( QObject::tr(
"Could not create layer %1: %2" ).arg( destination, writer->errorMessage() ) );
929 feedback->pushWarning( QObject::tr(
"%1: Aliases are not supported by %2" ).arg(
field.
name(), writer->driverLongName() ) );
931 feedback->pushWarning( QObject::tr(
"%1: Comments are not supported by %2" ).arg(
field.
name(), writer->driverLongName() ) );
935 destination = finalFileName;
936 if ( !saveOptions.
layerName.isEmpty() && !finalLayerName.isEmpty() )
937 destination += QStringLiteral(
"|layername=%1" ).arg( finalLayerName );
939 if ( remappingDefinition )
941 std::unique_ptr< QgsRemappingProxyFeatureSink > remapSink = std::make_unique< QgsRemappingProxyFeatureSink >( *remappingDefinition, writer.release(),
true );
952 if ( remappingDefinition )
957 if ( !layerName.isEmpty() )
960 parts.insert( QStringLiteral(
"layerName" ), layerName );
964 std::unique_ptr< QgsVectorLayer > layer = std::make_unique<QgsVectorLayer>( uri, destination, providerKey, layerOptions );
966 destination = layer->id();
967 if ( layer->isValid() )
976 const Qgis::VectorDataProviderAttributeEditCapabilities capabilities = layer->dataProvider() ? layer->dataProvider()->attributeEditCapabilities() : Qgis::VectorDataProviderAttributeEditCapabilities();
980 feedback->pushWarning( QObject::tr(
"%1: Aliases are not supported by the %2 provider" ).arg(
field.
name(), providerKey ) );
982 feedback->pushWarning( QObject::tr(
"%1: Comments are not supported by the %2 provider" ).arg(
field.
name(), providerKey ) );
986 std::unique_ptr< QgsRemappingProxyFeatureSink > remapSink = std::make_unique< QgsRemappingProxyFeatureSink >( *remappingDefinition, layer->dataProvider(),
false );
996 std::unique_ptr< QgsVectorLayerExporter > exporter = std::make_unique<QgsVectorLayerExporter>( uri, providerKey, newFields, geometryType,
crs,
true, options, sinkFlags );
997 if ( exporter->errorCode() != Qgis::VectorExportResult::Success )
999 throw QgsProcessingException( QObject::tr(
"Could not create layer %1: %2" ).arg( destination, exporter->errorMessage() ) );
1003 if ( !layerName.isEmpty() )
1005 uri += QStringLiteral(
"|layername=%1" ).arg( layerName );
1015 feedback->pushWarning( QObject::tr(
"%1: Aliases are not supported by the %2 provider" ).arg(
field.
name(), providerKey ) );
1017 feedback->pushWarning( QObject::tr(
"%1: Comments are not supported by the %2 provider" ).arg(
field.
name(), providerKey ) );
1075 if ( !input.isValid() )
1076 return QStringLiteral(
"memory:%1" ).arg(
id.toString() );
1078 if ( input.userType() == QMetaType::type(
"QgsProcessingOutputLayerDefinition" ) )
1085 else if ( input.userType() == QMetaType::type(
"QgsProperty" ) )
1092 QString res = input.toString();
1098 else if ( res.startsWith( QLatin1String(
"memory:" ) ) )
1100 return QString( res +
'_' +
id.toString() );
1106 int lastIndex = res.lastIndexOf(
'.' );
1107 return lastIndex >= 0 ? QString( res.left( lastIndex ) +
'_' +
id.toString() + res.mid( lastIndex ) ) : QString( res +
'_' +
id.toString() );
1118 static std::vector< std::unique_ptr< QTemporaryDir > > sTempFolders;
1119 static QString sFolder;
1120 static QMutex sMutex;
1121 QMutexLocker locker( &sMutex );
1126 if ( basePath.isEmpty() )
1129 if ( basePath.isEmpty() )
1132 if ( sTempFolders.empty() )
1134 const QString templatePath = QStringLiteral(
"%1/processing_XXXXXX" ).arg( QDir::tempPath() );
1135 std::unique_ptr< QTemporaryDir >
tempFolder = std::make_unique< QTemporaryDir >( templatePath );
1137 sTempFolders.emplace_back( std::move(
tempFolder ) );
1140 else if ( sFolder.isEmpty() || !sFolder.startsWith( basePath ) || sTempFolders.empty() )
1142 if ( !QDir().exists( basePath ) )
1143 QDir().mkpath( basePath );
1145 const QString templatePath = QStringLiteral(
"%1/processing_XXXXXX" ).arg( basePath );
1146 std::unique_ptr< QTemporaryDir >
tempFolder = std::make_unique< QTemporaryDir >( templatePath );
1148 sTempFolders.emplace_back( std::move(
tempFolder ) );
1155 QString subPath = QUuid::createUuid().toString().remove(
'-' ).remove(
'{' ).remove(
'}' );
1156 QString path =
tempFolder( context ) +
'/' + subPath;
1157 if ( !QDir( path ).exists() )
1160 tmpDir.mkdir( path );
1167 auto getText = [map](
const QString & key )->QString
1169 if ( map.contains( key ) )
1170 return map.value( key ).toString();
1175 s += QStringLiteral(
"<html><body><p>" ) + getText( QStringLiteral(
"ALG_DESC" ) ) + QStringLiteral(
"</p>\n" );
1184 if ( !getText( def->name() ).isEmpty() )
1186 inputs += QStringLiteral(
"<h3>" ) + def->description() + QStringLiteral(
"</h3>\n" );
1187 inputs += QStringLiteral(
"<p>" ) + getText( def->name() ) + QStringLiteral(
"</p>\n" );
1190 if ( !inputs.isEmpty() )
1191 s += QStringLiteral(
"<h2>" ) + QObject::tr(
"Input parameters" ) + QStringLiteral(
"</h2>\n" ) + inputs;
1197 if ( !getText( def->name() ).isEmpty() )
1199 outputs += QStringLiteral(
"<h3>" ) + def->description() + QStringLiteral(
"</h3>\n" );
1200 outputs += QStringLiteral(
"<p>" ) + getText( def->name() ) + QStringLiteral(
"</p>\n" );
1203 if ( !outputs.isEmpty() )
1204 s += QStringLiteral(
"<h2>" ) + QObject::tr(
"Outputs" ) + QStringLiteral(
"</h2>\n" ) + outputs;
1206 if ( !map.value( QStringLiteral(
"EXAMPLES" ) ).toString().isEmpty() )
1207 s += QStringLiteral(
"<h2>%1</h2>\n<p>%2</p>" ).arg( QObject::tr(
"Examples" ), getText( QStringLiteral(
"EXAMPLES" ) ) );
1209 s += QLatin1String(
"<br>" );
1210 if ( !map.value( QStringLiteral(
"ALG_CREATOR" ) ).toString().isEmpty() )
1211 s += QStringLiteral(
"<p align=\"right\">" ) + QObject::tr(
"Algorithm author:" ) + QStringLiteral(
" " ) + getText( QStringLiteral(
"ALG_CREATOR" ) ) + QStringLiteral(
"</p>" );
1212 if ( !map.value( QStringLiteral(
"ALG_HELP_CREATOR" ) ).toString().isEmpty() )
1213 s += QStringLiteral(
"<p align=\"right\">" ) + QObject::tr(
"Help author:" ) + QStringLiteral(
" " ) + getText( QStringLiteral(
"ALG_HELP_CREATOR" ) ) + QStringLiteral(
"</p>" );
1214 if ( !map.value( QStringLiteral(
"ALG_VERSION" ) ).toString().isEmpty() )
1215 s += QStringLiteral(
"<p align=\"right\">" ) + QObject::tr(
"Algorithm version:" ) + QStringLiteral(
" " ) + getText( QStringLiteral(
"ALG_VERSION" ) ) + QStringLiteral(
"</p>" );
1217 s += QLatin1String(
"</body></html>" );
1222 long long featureLimit,
const QString &filterExpression )
1224 bool requiresTranslation =
false;
1228 requiresTranslation = requiresTranslation || selectedFeaturesOnly;
1231 requiresTranslation = requiresTranslation || featureLimit != -1 || !filterExpression.isEmpty();
1236 requiresTranslation = requiresTranslation || vl->
providerType() != QLatin1String(
"ogr" );
1240 requiresTranslation = requiresTranslation || !vl->
subsetString().isEmpty();
1244 requiresTranslation = requiresTranslation || vl->
source().startsWith( QLatin1String(
"/vsi" ) );
1248 if ( !requiresTranslation )
1251 if ( parts.contains( QStringLiteral(
"path" ) ) )
1253 diskPath = parts.value( QStringLiteral(
"path" ) ).toString();
1254 QFileInfo fi( diskPath );
1255 requiresTranslation = !compatibleFormats.contains( fi.suffix(), Qt::CaseInsensitive );
1259 const QString srcLayerName = parts.value( QStringLiteral(
"layerName" ) ).toString();
1263 *layerName = srcLayerName;
1268 requiresTranslation = requiresTranslation || ( !srcLayerName.isEmpty() && srcLayerName != fi.baseName() );
1273 requiresTranslation =
true;
1277 if ( requiresTranslation )
1288 if ( featureLimit != -1 )
1292 if ( !filterExpression.isEmpty() )
1297 if ( selectedFeaturesOnly )
1318 return convertToCompatibleFormatInternal( vl, selectedFeaturesOnly, baseName, compatibleFormats, preferredFormat, context, feedback,
nullptr, featureLimit, filterExpression );
1324 return convertToCompatibleFormatInternal( layer, selectedFeaturesOnly, baseName, compatibleFormats, preferredFormat, context, feedback, &layerName, featureLimit, filterExpression );
1330 QSet< QString > usedNames;
1331 for (
const QgsField &f : fieldsA )
1333 usedNames.insert( f.name().toLower() );
1336 for (
const QgsField &f : fieldsB )
1339 newField.
setName( fieldsBPrefix + f.name() );
1340 if ( usedNames.contains( newField.
name().toLower() ) )
1343 QString newName = newField.
name() +
'_' + QString::number( idx );
1344 while ( usedNames.contains( newName.toLower() ) || fieldsB.
indexOf( newName ) != -1 )
1347 newName = newField.
name() +
'_' + QString::number( idx );
1350 outFields.
append( newField );
1354 outFields.
append( newField );
1356 usedNames.insert( newField.
name() );
1366 if ( !fieldNames.isEmpty() )
1368 indices.reserve( fieldNames.count() );
1369 for (
const QString &f : fieldNames )
1373 indices.append( idx );
1378 indices.reserve( fields.
count() );
1379 for (
int i = 0; i < fields.
count(); ++i )
1380 indices.append( i );
1389 for (
int i : indices )
1390 fieldsSubset.
append( fields.
at( i ) );
1391 return fieldsSubset;
1397 if ( setting == -1 )
1398 return QStringLiteral(
"gpkg" );
1405 if ( setting == -1 )
1406 return QStringLiteral(
"tif" );
1412 return QStringLiteral(
"las" );
1417 return QStringLiteral(
"mbtiles" );
1422 auto layerPointerToString = [](
QgsMapLayer * layer ) -> QString
1424 if ( layer && layer->
providerType() == QLatin1String(
"memory" ) )
1432 auto cleanPointerValues = [&layerPointerToString](
const QVariant & value ) -> QVariant
1434 if (
QgsMapLayer *layer = qobject_cast< QgsMapLayer * >( value.value< QObject * >() ) )
1437 return layerPointerToString( layer );
1439 else if ( value.userType() == QMetaType::type(
"QPointer< QgsMapLayer >" ) )
1442 return layerPointerToString( value.value< QPointer< QgsMapLayer > >().data() );
1451 for (
auto it = map.constBegin(); it != map.constEnd(); ++it )
1453 if ( it->type() == QVariant::Map )
1457 else if ( it->type() == QVariant::List )
1460 const QVariantList source = it.value().toList();
1461 dest.reserve( source.size() );
1462 for (
const QVariant &v : source )
1464 dest.append( cleanPointerValues( v ) );
1466 res.insert( it.key(), dest );
1470 res.insert( it.key(), cleanPointerValues( it.value() ) );
1480 for (
auto it = parameters.constBegin(); it != parameters.constEnd(); ++it )
1482 if ( it.value().type() == QVariant::Map )
1484 const QVariantMap value = it.value().toMap();
1485 if ( value.value( QStringLiteral(
"type" ) ).toString() == QLatin1String(
"data_defined" ) )
1487 const QString expression = value.value( QStringLiteral(
"expression" ) ).toString();
1488 const QString
field = value.value( QStringLiteral(
"field" ) ).toString();
1489 if ( !expression.isEmpty() )
1493 else if ( !
field.isEmpty() )
1500 error = QObject::tr(
"Invalid data defined parameter for %1, requires 'expression' or 'field' values." ).arg( it.key() );
1505 output.insert( it.key(), it.value() );
1508 else if ( it.value().type() == QVariant::String )
1510 const QString stringValue = it.value().toString();
1512 if ( stringValue.startsWith( QLatin1String(
"field:" ) ) )
1516 else if ( stringValue.startsWith( QLatin1String(
"expression:" ) ) )
1522 output.insert( it.key(), it.value() );
1527 output.insert( it.key(), it.value() );
1538 : mSource( originalSource )
1539 , mOwnsSource( ownsOriginalSource )
1540 , mInvalidGeometryCheck(
QgsWkbTypes::geometryType( mSource->wkbType() ) ==
Qgis::GeometryType::Point
1542 : context.invalidGeometryCheck() )
1543 , mInvalidGeometryCallback( context.invalidGeometryCallback( originalSource ) )
1544 , mTransformErrorCallback( context.transformErrorCallback() )
1545 , mInvalidGeometryCallbackSkip( context.defaultInvalidGeometryCallbackForCheck(
QgsFeatureRequest::GeometrySkipInvalid, originalSource ) )
1546 , mInvalidGeometryCallbackAbort( context.defaultInvalidGeometryCallbackForCheck(
QgsFeatureRequest::GeometryAbortOnInvalid, originalSource ) )
1547 , mFeatureLimit( featureLimit )
1548 , mFilterExpression( filterExpression )
1570 if ( mFeatureLimit != -1 && req.
limit() != -1 )
1571 req.
setLimit( std::min(
static_cast< long long >( req.
limit() ), mFeatureLimit ) );
1572 else if ( mFeatureLimit != -1 )
1575 if ( !mFilterExpression.isEmpty() )
1587 return sourceAvailability;
1600 if ( mFeatureLimit != -1 && req.
limit() != -1 )
1601 req.
setLimit( std::min(
static_cast< long long >( req.
limit() ), mFeatureLimit ) );
1602 else if ( mFeatureLimit != -1 )
1605 if ( !mFilterExpression.isEmpty() )
1618 return mSource->
fields();
1628 if ( !mFilterExpression.isEmpty() )
1631 if ( mFeatureLimit == -1 )
1634 return std::min( mFeatureLimit, mSource->
featureCount() );
1644 if ( mFilterExpression.isEmpty() )
1649 if ( fieldIndex < 0 || fieldIndex >=
fields().count() )
1650 return QSet<QVariant>();
1657 QSet<QVariant> values;
1662 values.insert( f.
attribute( fieldIndex ) );
1663 if ( limit > 0 && values.size() >= limit )
1671 if ( mFilterExpression.isEmpty() )
1676 if ( fieldIndex < 0 || fieldIndex >=
fields().count() )
1688 const QVariant v = f.
attribute( fieldIndex );
1699 if ( mFilterExpression.isEmpty() )
1704 if ( fieldIndex < 0 || fieldIndex >=
fields().count() )
1716 const QVariant v = f.
attribute( fieldIndex );
1732 if ( mFilterExpression.isEmpty() )
1738 .setFilterExpression( mFilterExpression ) );
1764 return expressionContextScope;
1769 mInvalidGeometryCheck = method;
1770 switch ( mInvalidGeometryCheck )
1773 mInvalidGeometryCallback =
nullptr;
1777 mInvalidGeometryCallback = mInvalidGeometryCallbackSkip;
1781 mInvalidGeometryCallback = mInvalidGeometryCallbackAbort;
1793 , mContext( context )
1794 , mSinkName( sinkName )
1795 , mOwnsSink( ownsOriginalSink )
1807 if ( !result && mContext.
feedback() )
1810 if ( !error.isEmpty() )
1811 mContext.
feedback()->
reportError( QObject::tr(
"Feature could not be written to %1: %2" ).arg( mSinkName, error ) );
1813 mContext.
feedback()->
reportError( QObject::tr(
"Feature could not be written to %1" ).arg( mSinkName ) );
1821 if ( !result && mContext.
feedback() )
1824 if ( !error.isEmpty() )
1825 mContext.
feedback()->
reportError( QObject::tr(
"%n feature(s) could not be written to %1: %2",
nullptr, features.count() ).arg( mSinkName, error ) );
1827 mContext.
feedback()->
reportError( QObject::tr(
"%n feature(s) could not be written to %1",
nullptr, features.count() ).arg( mSinkName ) );
1835 if ( !result && mContext.
feedback() )
1838 if ( !error.isEmpty() )
1839 mContext.
feedback()->
reportError( QObject::tr(
"Features could not be written to %1: %2" ).arg( mSinkName, error ) );
1841 mContext.
feedback()->
reportError( QObject::tr(
"Features could not be written to %1" ).arg( mSinkName ) );
The Qgis class provides global constants for use throughout the application.
@ FieldComments
Writer can support field comments.
@ FieldAliases
Writer can support field aliases.
@ EditAlias
Allows editing aliases.
@ EditComment
Allows editing comments.
WkbType
The WKB type describes the number of dimensions a geometry has.
@ NoSymbology
Export only data.
Represents a map layer containing a set of georeferenced annotations, e.g.
This class represents a coordinate reference system (CRS).
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
bool createFromString(const QString &definition)
Set up this CRS from a string definition.
Contains information about the context in which a coordinate transform is executed.
Custom exception class for Coordinate Reference System related exceptions.
Class for storing the component parts of a RDBMS data source URI (e.g.
QByteArray encodedUri() const
Returns the complete encoded URI as a byte array.
QString table() const
Returns the table name stored in the URI.
void setParam(const QString &key, const QString &value)
Sets a generic parameter value on the URI.
QString database() const
Returns the database name stored in the URI.
Abstract interface for generating an expression context scope.
virtual QgsExpressionContextScope * createExpressionContextScope() const =0
This method needs to be reimplemented in all classes which implement this interface and return an exp...
Single scope for storing variables and functions for use within a QgsExpressionContext.
void setFields(const QgsFields &fields)
Convenience function for setting a fields for the context.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setLimit(long long limit)
Set the maximum number of features to request.
InvalidGeometryCheck
Handling of features with invalid geometries.
@ GeometryNoCheck
No invalid geometry checking.
@ GeometryAbortOnInvalid
Close iterator on encountering any features with invalid geometry. This requires a slow geometry vali...
@ GeometrySkipInvalid
Skip any features with invalid geometry. This requires a slow geometry validity check for every featu...
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 & setFlags(QgsFeatureRequest::Flags flags)
Sets flags that affect how features will be fetched.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
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 & setInvalidGeometryCheck(InvalidGeometryCheck check)
Sets invalid geometry checking behavior.
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.
@ 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.
virtual QgsFields fields() const =0
Returns the fields associated with features in the source.
virtual QSet< QVariant > uniqueValues(int fieldIndex, int limit=-1) const
Returns the set of unique values contained within the specified fieldIndex from this source.
virtual QgsCoordinateReferenceSystem sourceCrs() const =0
Returns the coordinate reference system for features in the source.
SpatialIndexPresence
Enumeration of spatial index presence states.
virtual Qgis::WkbType wkbType() const =0
Returns the geometry type for features returned by this source.
virtual FeatureAvailability hasFeatures() const
Determines if there are any features available in the source.
FeatureAvailability
Possible return value for 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.
virtual QVariant minimumValue(int fieldIndex) const
Returns the minimum value for an attribute column or an invalid variant in case of error.
virtual QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const =0
Returns an iterator for the features in the source.
virtual QString sourceName() const =0
Returns a friendly display name for the source.
virtual QVariant maximumValue(int fieldIndex) const
Returns the maximum value for an attribute column or an invalid variant in case of error.
virtual long long featureCount() const =0
Returns the number of features contained in the source, or -1 if the feature count is unknown.
virtual QgsFeatureIds allFeatureIds() const
Returns a list of all feature IDs for features present in the source.
virtual SpatialIndexPresence hasSpatialIndex() const
Returns an enum value representing the presence of a valid spatial index on the source,...
virtual QgsRectangle sourceExtent() const
Returns the extent of all geometries from the source.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
bool isCanceled() const SIP_HOLDGIL
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, FieldOrigin origin=OriginProvider, int originIndex=-1)
Appends a field. The field must have unique name, otherwise it is rejected (returns false)
int indexOf(const QString &fieldName) const
Gets the field index from the field name.
int count() const
Returns number of items.
QgsField at(int i) const
Returns the field at particular index (must be in range 0..N-1).
int lookupField(const QString &fieldName) const
Looks up field's index from 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 '...
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
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
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.
A class to represent a 2D point.
Abstract base class for processing algorithms.
QgsProcessingOutputDefinitions outputDefinitions() const
Returns an ordered list of output definitions utilized by the algorithm.
QgsProcessingParameterDefinitions parameterDefinitions() const
Returns an ordered list of parameter definitions utilized by the algorithm.
Contains information about the context in which a processing algorithm is executed.
QString defaultEncoding() const
Returns the default encoding to use for newly created files.
QgsProcessingFeedback * feedback()
Returns the associated feedback object.
QgsExpressionContext & expressionContext()
Returns the expression context.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
QgsProject * project() const
Returns the project in which the algorithm is being executed.
QgsMapLayerStore * temporaryLayerStore()
Returns a reference to the layer store used for storing temporary layers during algorithm execution.
QString temporaryFolder() const
Returns the (optional) temporary folder to use when running algorithms.
Custom exception class for processing related exceptions.
QgsProxyFeatureSink subclass which reports feature addition errors to a QgsProcessingContext.
~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.
Flags flags
Flags which dictate source behavior.
bool selectedFeaturesOnly
true if only selected features in the source should be used by algorithms.
QgsFeatureRequest::InvalidGeometryCheck geometryCheck
Geometry check method to apply to this source.
QgsProperty source
Source definition.
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...
QgsFeatureSource::FeatureAvailability hasFeatures() const override
Determines if there are any features available in 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
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request, Flags flags) const
Returns an iterator for the features in the source, respecting the supplied feature flags.
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.
@ FlagSkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
QString sourceName() const override
Returns a friendly display name for the source.
SpatialIndexPresence hasSpatialIndex() const override
Returns an enum value representing the presence of a valid spatial index on the source,...
QgsFeatureIds allFeatureIds() const override
Returns a list of all feature IDs for features present in the source.
QgsFields fields() const override
Returns the fields associated with features in the source.
void setInvalidGeometryCheck(QgsFeatureRequest::InvalidGeometryCheck method)
Overrides the default geometry check method for 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.
@ FlagHidden
Parameter is hidden and should not be shown to users.
static QString stringToPythonLiteral(const QString &string)
Converts a string to a Python string literal.
static QString defaultVectorExtension()
Returns the default vector extension to use, in the absence of all other constraints (e....
static QVariant generateIteratingDestination(const QVariant &input, const QVariant &id, QgsProcessingContext &context)
Converts an input parameter value for use in source iterating mode, where one individual sink is crea...
static QgsFields indicesToFields(const QList< int > &indices, const QgsFields &fields)
Returns a subset of fields based on the indices of desired fields.
static QList< int > fieldNamesToIndices(const QStringList &fieldNames, const QgsFields &fields)
Returns a list of field indices parsed from the given list of field names.
static QVariantMap preprocessQgisProcessParameters(const QVariantMap ¶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.
@ 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 QgsProcessingFeatureSource * variantToSource(const QVariant &value, QgsProcessingContext &context, const QVariant &fallbackValue=QVariant())
Converts a variant value to a new feature source.
static QList< QgsRasterLayer * > compatibleRasterLayers(QgsProject *project, bool sort=true)
Returns a list of raster layers from a project which are compatible with the processing framework.
static QgsRectangle combineLayerExtents(const QList< QgsMapLayer * > &layers, const QgsCoordinateReferenceSystem &crs, QgsProcessingContext &context)
Combines the extent of several map layers.
static 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 void createFeatureSinkPython(QgsFeatureSink **sink, QString &destination, QgsProcessingContext &context, const QgsFields &fields, Qgis::WkbType geometryType, const QgsCoordinateReferenceSystem &crs, const QVariantMap &createOptions=QVariantMap()) SIP_THROW(QgsProcessingException)
Creates a feature sink ready for adding features.
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 QList< QgsVectorTileLayer * > compatibleVectorTileLayers(QgsProject *project, bool sort=true)
Returns a list of vector tile layers from a project which are compatible with the processing framewor...
static QString convertToCompatibleFormatAndLayerName(const QgsVectorLayer *layer, bool selectedFeaturesOnly, const QString &baseName, const QStringList &compatibleFormats, const QString &preferredFormat, QgsProcessingContext &context, QgsProcessingFeedback *feedback, QString &layerName, long long featureLimit=-1, const QString &filterExpression=QString())
Converts a source vector layer to a file path and layer name of a vector layer of compatible format.
static QList< QgsMapLayer * > compatibleLayers(QgsProject *project, bool sort=true)
Returns a list of map layers from a project which are compatible with the processing framework.
static QString convertToCompatibleFormat(const QgsVectorLayer *layer, bool selectedFeaturesOnly, const QString &baseName, const QStringList &compatibleFormats, const QString &preferredFormat, QgsProcessingContext &context, QgsProcessingFeedback *feedback, long long featureLimit=-1, const QString &filterExpression=QString())
Converts a source vector layer to a file path of a vector layer of compatible format.
static QgsFeatureSink * createFeatureSink(QString &destination, QgsProcessingContext &context, const QgsFields &fields, Qgis::WkbType geometryType, const QgsCoordinateReferenceSystem &crs, const QVariantMap &createOptions=QVariantMap(), const QStringList &datasourceOptions=QStringList(), const QStringList &layerOptions=QStringList(), QgsFeatureSink::SinkFlags sinkFlags=QgsFeatureSink::SinkFlags(), QgsRemappingSinkDefinition *remappingDefinition=nullptr)
Creates a feature sink ready for adding features.
static QString defaultRasterExtension()
Returns the default raster extension to use, in the absence of all other constraints (e....
static QString defaultVectorTileExtension()
Returns the default vector tile extension to use, in the absence of all other constraints (e....
static QgsMapLayer * mapLayerFromString(const QString &string, QgsProcessingContext &context, bool allowLoadingNewLayers=true, QgsProcessingUtils::LayerHint typeHint=QgsProcessingUtils::LayerHint::UnknownType, QgsProcessing::LayerOptionsFlags flags=QgsProcessing::LayerOptionsFlags())
Interprets a string as a map layer within the supplied context.
static QString defaultPointCloudExtension()
Returns the default point cloud extension to use, in the absence of all other constraints (e....
static QList< QgsPointCloudLayer * > compatiblePointCloudLayers(QgsProject *project, bool sort=true)
Returns a list of point cloud layers from a project which are compatible with the processing framewor...
static QList< QgsMeshLayer * > compatibleMeshLayers(QgsProject *project, bool sort=true)
Returns a list of mesh layers from a project which are compatible with the processing framework.
static QString tempFolder(const QgsProcessingContext *context=nullptr)
Returns a session specific processing temporary folder for use in processing algorithms.
static const QgsSettingsEntryInteger * settingsDefaultOutputRasterLayerExt
Settings entry default output raster layer ext.
static const QgsSettingsEntryInteger * settingsDefaultOutputVectorLayerExt
Settings entry default output vector layer ext.
static const QgsSettingsEntryString * settingsTempPath
Settings entry temp path.
static const QString TEMPORARY_OUTPUT
Constant used to indicate that a Processing algorithm output should be a temporary layer/file.
@ TypeVectorLine
Vector line layers.
@ TypeVectorPolygon
Vector polygon layers.
@ TypeVector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
@ TypeVectorPoint
Vector point layers.
@ TypeVectorAnyGeometry
Any vector layer with geometry.
@ 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.
@ StaticProperty
Static property (QgsStaticProperty)
QString asExpression() const
Returns an expression string representing the state of the property, or an empty string if the proper...
QVariant value(const QgsExpressionContext &context, const QVariant &defaultValue=QVariant(), bool *ok=nullptr) const
Calculates the current value of the property, including any transforms which are set for the property...
static QgsProperty fromExpression(const QString &expression, bool isActive=true)
Returns a new ExpressionBasedProperty created from the specified expression.
Type propertyType() const
Returns the property type.
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.
A simple feature sink which proxies feature addition on to another feature sink.
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a single feature to the sink.
QString lastError() const override
Returns the most recent error encountered by the sink, e.g.
QgsFeatureSink * destinationSink()
Returns the destination QgsFeatureSink which the proxy will forward features to.
bool addFeatures(QgsFeatureList &features, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a list of features to the sink.
static QStringList supportedFormatExtensions(RasterFormatOptions options=SortRecommended)
Returns a list of file extensions for supported formats.
Represents a raster layer.
A rectangle specified with double values.
double yMaximum() const SIP_HOLDGIL
Returns the y maximum value (top side of rectangle).
double xMaximum() const SIP_HOLDGIL
Returns the x maximum value (right side of rectangle).
double xMinimum() const SIP_HOLDGIL
Returns the x minimum value (left side of rectangle).
double yMinimum() const SIP_HOLDGIL
Returns the y minimum value (bottom side of rectangle).
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.
T value(const QString &dynamicKeyPart=QString()) const
Returns settings value.
static bool isNull(const QVariant &variant)
Returns true if the specified variant should be considered a NULL value.
Options to pass to 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 data sets.
bool isSpatial() const FINAL
Returns true if this is a geometry layer and false in case of NoGeometry (table only) or UnknownGeome...
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
Q_INVOKABLE Qgis::WkbType wkbType() const FINAL
Returns the WKBType or WKBUnknown in case of error.
QgsFeatureIterator getSelectedFeatures(QgsFeatureRequest request=QgsFeatureRequest()) const
Returns an iterator of the selected features.
Q_INVOKABLE Qgis::GeometryType geometryType() const
Returns point, line or polygon.
QgsRectangle extent() const FINAL
Returns the extent of the layer.
Implements a map layer that is dedicated to rendering of vector tiles.
Handles storage of information regarding WKB types and their properties.
@ 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)
const QgsCoordinateReferenceSystem & crs
Setting options for loading mesh layers.
bool skipCrsValidation
Controls whether the layer is allowed to have an invalid/unknown CRS.
Setting options for loading point cloud layers.
bool skipCrsValidation
Controls whether the layer is allowed to have an invalid/unknown CRS.
bool skipIndexGeneration
Set to true if point cloud index generation should be skipped.
Setting options for loading raster layers.
bool skipCrsValidation
Controls whether the layer is allowed to have an invalid/unknown CRS.
bool loadDefaultStyle
Sets to true if the default layer style should be loaded.
Setting options for loading vector layers.