40#include <QRegularExpression> 
   46  return compatibleMapLayers< QgsRasterLayer >( project, sort );
 
 
   52    return QList<QgsVectorLayer *>();
 
   54  QList<QgsVectorLayer *> layers;
 
   58    if ( canUseLayer( l, geometryTypes ) )
 
   66      return QString::localeAwareCompare( a->name(), b->name() ) < 0;
 
 
   74  return compatibleMapLayers< QgsMeshLayer >( project, sort );
 
 
   79  return compatibleMapLayers< QgsPluginLayer >( project, sort );
 
 
   84  return compatibleMapLayers< QgsPointCloudLayer >( project, sort );
 
 
   90  QList<QgsAnnotationLayer *> res = compatibleMapLayers< QgsAnnotationLayer >( project, 
false );
 
   98      return QString::localeAwareCompare( a->name(), b->name() ) < 0;
 
 
  107  return compatibleMapLayers< QgsVectorTileLayer >( project, sort );
 
 
  112  return compatibleMapLayers< QgsTiledSceneLayer >( project, sort );
 
 
  115template<
typename T> QList<T *> QgsProcessingUtils::compatibleMapLayers( 
QgsProject *project, 
bool sort )
 
  121  const auto projectLayers = project->
layers<T *>();
 
  122  for ( T *l : projectLayers )
 
  124    if ( canUseLayer( l ) )
 
  130    std::sort( layers.begin(), layers.end(), []( 
const T * a, 
const T * b ) -> 
bool 
  132      return QString::localeAwareCompare( a->name(), b->name() ) < 0;
 
  141    return QList<QgsMapLayer *>();
 
  143  QList<QgsMapLayer *> layers;
 
  145  const auto rasterLayers = compatibleMapLayers< QgsRasterLayer >( project, 
false );
 
  153  const auto meshLayers = compatibleMapLayers< QgsMeshLayer >( project, 
false );
 
  157  const auto pointCloudLayers = compatibleMapLayers< QgsPointCloudLayer >( project, 
false );
 
  161  const auto annotationLayers = compatibleMapLayers< QgsAnnotationLayer >( project, 
false );
 
  166  const auto vectorTileLayers = compatibleMapLayers< QgsVectorTileLayer >( project, 
false );
 
  170  const auto tiledSceneLayers = compatibleMapLayers< QgsTiledSceneLayer >( project, 
false );
 
  174  const auto pluginLayers = compatibleMapLayers< QgsPluginLayer >( project, 
false );
 
  182      return QString::localeAwareCompare( a->name(), b->name() ) < 0;
 
 
  190  return QStringLiteral( 
"%1://%2" ).arg( providerKey, uri );
 
 
  195  const thread_local QRegularExpression re( QStringLiteral( 
"^(\\w+?):\\/\\/(.+)$" ) );
 
  196  const QRegularExpressionMatch match = re.match( 
string );
 
  197  if ( !match.hasMatch() )
 
  200  providerKey = match.captured( 1 );
 
  201  uri = match.captured( 2 );
 
 
  209  if ( !store || 
string.isEmpty() )
 
  212  QList< QgsMapLayer * > layers = store->
mapLayers().values();
 
  214  layers.erase( std::remove_if( layers.begin(), layers.end(), []( 
QgsMapLayer * layer )
 
  216    switch ( layer->type() )
 
  218      case Qgis::LayerType::Vector:
 
  219        return !canUseLayer( qobject_cast< QgsVectorLayer * >( layer ) );
 
  220      case Qgis::LayerType::Raster:
 
  221        return !canUseLayer( qobject_cast< QgsRasterLayer * >( layer ) );
 
  222      case Qgis::LayerType::Plugin:
 
  223      case Qgis::LayerType::Group:
 
  225      case Qgis::LayerType::Mesh:
 
  226        return !canUseLayer( qobject_cast< QgsMeshLayer * >( layer ) );
 
  227      case Qgis::LayerType::VectorTile:
 
  228        return !canUseLayer( qobject_cast< QgsVectorTileLayer * >( layer ) );
 
  229      case Qgis::LayerType::TiledScene:
 
  230        return !canUseLayer( qobject_cast< QgsTiledSceneLayer * >( layer ) );
 
  231      case Qgis::LayerType::PointCloud:
 
  232        return !canUseLayer( qobject_cast< QgsPointCloudLayer * >( layer ) );
 
  233      case Qgis::LayerType::Annotation:
 
  234        return !canUseLayer( qobject_cast< QgsAnnotationLayer * >( layer ) );
 
  239  auto isCompatibleType = [typeHint]( 
QgsMapLayer * l ) -> 
bool 
  243      case LayerHint::UnknownType:
 
  246      case LayerHint::Vector:
 
  249      case LayerHint::Raster:
 
  252      case LayerHint::Mesh:
 
  255      case LayerHint::PointCloud:
 
  258      case LayerHint::Annotation:
 
  261      case LayerHint::VectorTile:
 
  264      case LayerHint::TiledScene:
 
  272    if ( isCompatibleType( l ) && l->id() == 
string )
 
  277    if ( isCompatibleType( l ) && l->name() == 
string )
 
  282    if ( isCompatibleType( l ) && normalizeLayerSource( l->source() ) == normalizeLayerSource( 
string ) )
 
  299  if ( providerMetadata )
 
  302    const QVariantMap parts = providerMetadata->
decodeUri( uri );
 
  303    const QString layerName = parts.value( QStringLiteral( 
"layerName" ) ).toString();
 
  305    if ( !layerName.isEmpty() )
 
  309    else if ( 
const QString path = parts.value( QStringLiteral( 
"path" ) ).toString(); !path.isEmpty() )
 
  311      name = QFileInfo( path ).baseName();
 
  316    const QStringList components = uri.split( 
'|' );
 
  317    if ( components.isEmpty() )
 
  320    if ( QFileInfo fi( components.at( 0 ) ); fi.isFile() )
 
  321      name = fi.baseName();
 
  323      name = QFileInfo( uri ).baseName();
 
  326  if ( name.isEmpty() )
 
  330  if ( name.isEmpty() )
 
  335  QList< Qgis::LayerType > candidateTypes;
 
  340      if ( providerMetadata )
 
  374    options.loadDefaultStyle = 
false;
 
  375    options.skipCrsValidation = 
true;
 
  377    std::unique_ptr< QgsVectorLayer > layer;
 
  378    if ( providerMetadata )
 
  380      layer = std::make_unique<QgsVectorLayer>( uri, name, providerMetadata->
key(), options );
 
  385      layer = std::make_unique<QgsVectorLayer>( uri, name, QStringLiteral( 
"ogr" ), options );
 
  387    if ( layer->isValid() )
 
  389      return layer.release();
 
  398    std::unique_ptr< QgsRasterLayer > rasterLayer;
 
  399    if ( providerMetadata )
 
  401      rasterLayer = std::make_unique< QgsRasterLayer >( uri, name, providerMetadata->
key(), rasterOptions );
 
  406      rasterLayer = std::make_unique< QgsRasterLayer >( uri, name, QStringLiteral( 
"gdal" ), rasterOptions );
 
  409    if ( rasterLayer->isValid() )
 
  411      return rasterLayer.release();
 
  419    std::unique_ptr< QgsMeshLayer > meshLayer;
 
  420    if ( providerMetadata )
 
  422      meshLayer = std::make_unique< QgsMeshLayer >( uri, name, providerMetadata->
key(), meshOptions );
 
  426      meshLayer = std::make_unique< QgsMeshLayer >( uri, name, QStringLiteral( 
"mdal" ), meshOptions );
 
  428    if ( meshLayer->isValid() )
 
  430      return meshLayer.release();
 
  443    std::unique_ptr< QgsPointCloudLayer > pointCloudLayer;
 
  444    if ( providerMetadata )
 
  446      pointCloudLayer = std::make_unique< QgsPointCloudLayer >( uri, name, providerMetadata->
key(), pointCloudOptions );
 
  451      if ( !preferredProviders.empty() )
 
  453        pointCloudLayer = std::make_unique< QgsPointCloudLayer >( uri, name, preferredProviders.at( 0 ).metadata()->key(), pointCloudOptions );
 
  456    if ( pointCloudLayer && pointCloudLayer->isValid() )
 
  458      return pointCloudLayer.release();
 
  464    dsUri.
setParam( 
"type", 
"mbtiles" );
 
  467    std::unique_ptr< QgsVectorTileLayer > tileLayer;
 
  468    tileLayer = std::make_unique< QgsVectorTileLayer >( dsUri.
encodedUri(), name );
 
  470    if ( tileLayer->isValid() )
 
  472      return tileLayer.release();
 
  480    std::unique_ptr< QgsTiledSceneLayer > tiledSceneLayer;
 
  481    if ( providerMetadata )
 
  483      tiledSceneLayer = std::make_unique< QgsTiledSceneLayer >( uri, name, providerMetadata->
key(), tiledSceneOptions );
 
  488      if ( !preferredProviders.empty() )
 
  490        tiledSceneLayer = std::make_unique< QgsTiledSceneLayer >( uri, name, preferredProviders.at( 0 ).metadata()->key(), tiledSceneOptions );
 
  493    if ( tiledSceneLayer && tiledSceneLayer->isValid() )
 
  495      return tiledSceneLayer.release();
 
  503  if ( 
string.isEmpty() )
 
  511  if ( 
auto *lProject = context.
project() )
 
  513    QgsMapLayer *layer = mapLayerFromStore( 
string, lProject->layerStore(), typeHint );
 
  522  if ( !allowLoadingNewLayers )
 
  525  layer = loadMapLayerFromString( 
string, context.
transformContext(), typeHint, flags );
 
 
  539  QVariant val = value;
 
  540  bool selectedFeaturesOnly = 
false;
 
  541  long long featureLimit = -1;
 
  542  QString filterExpression;
 
  543  bool overrideGeometryCheck = 
false;
 
  545  if ( val.userType() == QMetaType::type( 
"QgsProcessingFeatureSourceDefinition" ) )
 
  556  else if ( val.userType() == QMetaType::type( 
"QgsProcessingOutputLayerDefinition" ) )
 
  563  if ( 
QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( qvariant_cast<QObject *>( val ) ) )
 
  565    std::unique_ptr< QgsProcessingFeatureSource> source = std::make_unique< QgsProcessingFeatureSource >( layer, context, 
false, featureLimit, filterExpression );
 
  566    if ( overrideGeometryCheck )
 
  567      source->setInvalidGeometryCheck( geometryCheck );
 
  568    return source.release();
 
  572  if ( val.userType() == QMetaType::type( 
"QgsProperty" ) )
 
  576  else if ( !val.isValid() || val.toString().isEmpty() )
 
  579    if ( 
QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( qvariant_cast<QObject *>( fallbackValue ) ) )
 
  581      std::unique_ptr< QgsProcessingFeatureSource> source = std::make_unique< QgsProcessingFeatureSource >( layer, context, 
false, featureLimit, filterExpression );
 
  582      if ( overrideGeometryCheck )
 
  583        source->setInvalidGeometryCheck( geometryCheck );
 
  584      return source.release();
 
  587    layerRef = fallbackValue.toString();
 
  591    layerRef = val.toString();
 
  594  if ( layerRef.isEmpty() )
 
  601  std::unique_ptr< QgsProcessingFeatureSource> source;
 
  602  if ( selectedFeaturesOnly )
 
  608    source = std::make_unique< QgsProcessingFeatureSource >( vl, context, 
false, featureLimit, filterExpression );
 
  611  if ( overrideGeometryCheck )
 
  612    source->setInvalidGeometryCheck( geometryCheck );
 
  613  return source.release();
 
 
  618  QVariant val = value;
 
  620  if ( val.userType() == QMetaType::type( 
"QgsCoordinateReferenceSystem" ) )
 
  625  else if ( val.userType() == QMetaType::type( 
"QgsProcessingFeatureSourceDefinition" ) )
 
  631  else if ( val.userType() == QMetaType::type( 
"QgsProcessingOutputLayerDefinition" ) )
 
  644  if ( 
QgsMapLayer *layer = qobject_cast< QgsMapLayer * >( qvariant_cast<QObject *>( val ) ) )
 
  647  if ( val.userType() == QMetaType::type( 
"QgsProperty" ) )
 
  650  if ( !val.isValid() )
 
  656  QString crsText = val.toString();
 
  657  if ( crsText.isEmpty() )
 
  658    crsText = fallbackValue.toString();
 
  660  if ( crsText.isEmpty() )
 
  664  if ( context.
project() && crsText.compare( QLatin1String( 
"ProjectCrs" ), Qt::CaseInsensitive ) == 0 )
 
 
  677bool QgsProcessingUtils::canUseLayer( 
const QgsMeshLayer *layer )
 
  682bool QgsProcessingUtils::canUseLayer( 
const QgsPluginLayer *layer )
 
  684  return layer && layer->
isValid();
 
  689  return layer && layer->
isValid();
 
  692bool QgsProcessingUtils::canUseLayer( 
const QgsRasterLayer *layer )
 
  694  return layer && layer->
isValid();
 
  699  return layer && layer->
isValid();
 
  704  return layer && layer->
isValid();
 
  709  return layer && layer->
isValid();
 
  712bool QgsProcessingUtils::canUseLayer( 
const QgsVectorLayer *layer, 
const QList<int> &sourceTypes )
 
  714  return layer && layer->
isValid() &&
 
  715         ( sourceTypes.isEmpty()
 
  726  QString normalized = source;
 
  727  normalized.replace( 
'\\', 
'/' );
 
  728  return normalized.trimmed();
 
 
  737  if ( !source.isEmpty() )
 
  742    if ( provider.compare( QLatin1String( 
"gdal" ), Qt::CaseInsensitive ) == 0
 
  743         || provider.compare( QLatin1String( 
"ogr" ), Qt::CaseInsensitive ) == 0
 
  744         || provider.compare( QLatin1String( 
"mdal" ), Qt::CaseInsensitive ) == 0 )
 
  747    return QStringLiteral( 
"%1://%2" ).arg( provider, source );
 
 
  754  if ( !value.isValid() )
 
  755    return QStringLiteral( 
"None" );
 
  757  if ( value.userType() == QMetaType::type( 
"QgsProperty" ) )
 
  758    return QStringLiteral( 
"QgsProperty.fromExpression('%1')" ).arg( value.value< 
QgsProperty >().
asExpression() );
 
  759  else if ( value.userType() == QMetaType::type( 
"QgsCoordinateReferenceSystem" ) )
 
  762      return QStringLiteral( 
"QgsCoordinateReferenceSystem()" );
 
  766  else if ( value.userType() == QMetaType::type( 
"QgsRectangle" ) )
 
  774  else if ( value.userType() == QMetaType::type( 
"QgsReferencedRectangle" ) )
 
  782  else if ( value.userType() == QMetaType::type( 
"QgsPointXY" ) )
 
  788  else if ( value.userType() == QMetaType::type( 
"QgsReferencedPointXY" ) )
 
  796  switch ( value.type() )
 
  799      return value.toBool() ? QStringLiteral( 
"True" ) : QStringLiteral( 
"False" );
 
  801    case QVariant::Double:
 
  802      return QString::number( value.toDouble() );
 
  806      return QString::number( value.toInt() );
 
  808    case QVariant::LongLong:
 
  809    case QVariant::ULongLong:
 
  810      return QString::number( value.toLongLong() );
 
  815      const QVariantList vl = value.toList();
 
  816      for ( 
const QVariant &v : vl )
 
  820      return parts.join( 
',' ).prepend( 
'[' ).append( 
']' );
 
  825      const QVariantMap map = value.toMap();
 
  827      parts.reserve( map.size() );
 
  828      for ( 
auto it = map.constBegin(); it != map.constEnd(); ++it )
 
  832      return parts.join( 
',' ).prepend( 
'{' ).append( 
'}' );
 
  835    case QVariant::DateTime:
 
  837      const QDateTime dateTime = value.toDateTime();
 
  838      return QStringLiteral( 
"QDateTime(QDate(%1, %2, %3), QTime(%4, %5, %6))" )
 
  839             .arg( dateTime.date().year() )
 
  840             .arg( dateTime.date().month() )
 
  841             .arg( dateTime.date().day() )
 
  842             .arg( dateTime.time().hour() )
 
  843             .arg( dateTime.time().minute() )
 
  844             .arg( dateTime.time().second() );
 
 
  857  s.replace( 
'\\', QLatin1String( 
"\\\\" ) );
 
  858  s.replace( 
'\n', QLatin1String( 
"\\n" ) );
 
  859  s.replace( 
'\r', QLatin1String( 
"\\r" ) );
 
  860  s.replace( 
'\t', QLatin1String( 
"\\t" ) );
 
  862  if ( s.contains( 
'\'' ) && !s.contains( 
'\"' ) )
 
  864    s = s.prepend( 
'"' ).append( 
'"' );
 
  868    s.replace( 
'\'', QLatin1String( 
"\\\'" ) );
 
  869    s = s.prepend( 
'\'' ).append( 
'\'' );
 
 
  874void QgsProcessingUtils::parseDestinationString( QString &destination, QString &providerKey, QString &uri, QString &layerName, QString &format, QMap<QString, QVariant> &options, 
bool &useWriter, QString &extension )
 
  881    const thread_local QRegularExpression splitRx( QStringLiteral( 
"^(.{3,}?):(.*)$" ) );
 
  882    QRegularExpressionMatch match = splitRx.match( destination );
 
  883    if ( match.hasMatch() )
 
  885      providerKey = match.captured( 1 );
 
  886      uri = match.captured( 2 );
 
  893    if ( providerKey == QLatin1String( 
"postgis" ) ) 
 
  895      providerKey = QStringLiteral( 
"postgres" );
 
  897    if ( providerKey == QLatin1String( 
"ogr" ) )
 
  902        if ( !dsUri.
table().isEmpty() )
 
  904          layerName = dsUri.
table();
 
  905          options.insert( QStringLiteral( 
"layerName" ), layerName );
 
  908        extension = QFileInfo( uri ).completeSuffix();
 
  910        options.insert( QStringLiteral( 
"driverName" ), format );
 
  914        extension = QFileInfo( uri ).completeSuffix();
 
  917      options.insert( QStringLiteral( 
"update" ), 
true );
 
  924    providerKey = QStringLiteral( 
"ogr" );
 
  926    const thread_local QRegularExpression splitRx( QStringLiteral( 
"^(.*)\\.(.*?)$" ) );
 
  927    QRegularExpressionMatch match = splitRx.match( destination );
 
  928    if ( match.hasMatch() )
 
  930      extension = match.captured( 2 );
 
  934    if ( format.isEmpty() )
 
  936      format = QStringLiteral( 
"GPKG" );
 
  937      destination = destination + QStringLiteral( 
".gpkg" );
 
  940    options.insert( QStringLiteral( 
"driverName" ), format );
 
  947  QVariantMap options = createOptions;
 
  948  if ( !options.contains( QStringLiteral( 
"fileEncoding" ) ) )
 
  954  if ( destination.isEmpty() || destination.startsWith( QLatin1String( 
"memory:" ) ) )
 
  957    if ( destination.startsWith( QLatin1String( 
"memory:" ) ) )
 
  958      destination = destination.mid( 7 );
 
  960    if ( destination.isEmpty() )
 
  961      destination = QStringLiteral( 
"output" );
 
  965    if ( !layer || !layer->isValid() )
 
  972      for ( 
const QgsField &field : fields )
 
  975        if ( !field.alias().isEmpty() )
 
  976          feedback->pushWarning( QObject::tr( 
"%1: Aliases are not compatible with scratch layers" ).arg( field.name() ) );
 
  977        if ( !field.alias().isEmpty() )
 
  978          feedback->pushWarning( QObject::tr( 
"%1: Comments are not compatible with scratch layers" ).arg( field.name() ) );
 
  985    destination = layer->id();
 
  988    std::unique_ptr< QgsProcessingFeatureSink > sink( 
new QgsProcessingFeatureSink( layer->dataProvider(), destination, context ) );
 
  991    return sink.release();
 
 1000    bool useWriter = 
false;
 
 1001    parseDestinationString( destination, providerKey, uri, layerName, format, options, useWriter, extension );
 
 1004    if ( useWriter && providerKey == QLatin1String( 
"ogr" ) )
 
 1008      QString finalFileName;
 
 1009      QString finalLayerName;
 
 1011      saveOptions.
fileEncoding = options.value( QStringLiteral( 
"fileEncoding" ) ).toString();
 
 1012      saveOptions.
layerName = !layerName.isEmpty() ? layerName : options.value( QStringLiteral( 
"layerName" ) ).toString();
 
 1017      if ( remappingDefinition )
 
 1021        std::unique_ptr< QgsVectorLayer > vl = std::make_unique< QgsVectorLayer >( destination );
 
 1022        if ( vl->isValid() )
 
 1026          newFields = vl->fields();
 
 1036      if ( writer->hasError() )
 
 1038        throw QgsProcessingException( QObject::tr( 
"Could not create layer %1: %2" ).arg( destination, writer->errorMessage() ) );
 
 1043        for ( 
const QgsField &field : fields )
 
 1046            feedback->pushWarning( QObject::tr( 
"%1: Aliases are not supported by %2" ).arg( field.name(), writer->driverLongName() ) );
 
 1048            feedback->pushWarning( QObject::tr( 
"%1: Comments are not supported by %2" ).arg( field.name(), writer->driverLongName() ) );
 
 1052      destination = finalFileName;
 
 1053      if ( !saveOptions.
layerName.isEmpty() && !finalLayerName.isEmpty() )
 
 1054        destination += QStringLiteral( 
"|layername=%1" ).arg( finalLayerName );
 
 1056      if ( remappingDefinition )
 
 1058        std::unique_ptr< QgsRemappingProxyFeatureSink > remapSink = std::make_unique< QgsRemappingProxyFeatureSink >( *remappingDefinition, writer.release(), 
true );
 
 1069      if ( remappingDefinition )
 
 1074        if ( !layerName.isEmpty() )
 
 1077          parts.insert( QStringLiteral( 
"layerName" ), layerName );
 
 1081        std::unique_ptr< QgsVectorLayer > layer = std::make_unique<QgsVectorLayer>( uri, destination, providerKey, layerOptions );
 
 1083        destination = layer->id();
 
 1084        if ( layer->isValid() )
 
 1093          const Qgis::VectorDataProviderAttributeEditCapabilities capabilities = layer->dataProvider() ? layer->dataProvider()->attributeEditCapabilities() : Qgis::VectorDataProviderAttributeEditCapabilities();
 
 1094          for ( 
const QgsField &field : fields )
 
 1097              feedback->pushWarning( QObject::tr( 
"%1: Aliases are not supported by the %2 provider" ).arg( field.name(), providerKey ) );
 
 1099              feedback->pushWarning( QObject::tr( 
"%1: Comments are not supported by the %2 provider" ).arg( field.name(), providerKey ) );
 
 1103        std::unique_ptr< QgsRemappingProxyFeatureSink > remapSink = std::make_unique< QgsRemappingProxyFeatureSink >( *remappingDefinition, layer->dataProvider(), 
false );
 
 1113        std::unique_ptr< QgsVectorLayerExporter > exporter = std::make_unique<QgsVectorLayerExporter>( uri, providerKey, newFields, geometryType, 
crs, 
true, options, sinkFlags );
 
 1116          throw QgsProcessingException( QObject::tr( 
"Could not create layer %1: %2" ).arg( destination, exporter->errorMessage() ) );
 
 1120        if ( !layerName.isEmpty() )
 
 1122          uri += QStringLiteral( 
"|layername=%1" ).arg( layerName );
 
 1129          for ( 
const QgsField &field : fields )
 
 1132              feedback->pushWarning( QObject::tr( 
"%1: Aliases are not supported by the %2 provider" ).arg( field.name(), providerKey ) );
 
 1134              feedback->pushWarning( QObject::tr( 
"%1: Comments are not supported by the %2 provider" ).arg( field.name(), providerKey ) );
 
 
 1192  if ( !input.isValid() )
 
 1193    return QStringLiteral( 
"memory:%1" ).arg( 
id.toString() );
 
 1195  if ( input.userType() == QMetaType::type( 
"QgsProcessingOutputLayerDefinition" ) )
 
 1202  else if ( input.userType() == QMetaType::type( 
"QgsProperty" ) )
 
 1209    QString res = input.toString();
 
 1215    else if ( res.startsWith( QLatin1String( 
"memory:" ) ) )
 
 1217      return QString( res + 
'_' + 
id.toString() );
 
 1223      int lastIndex = res.lastIndexOf( 
'.' );
 
 1224      return lastIndex >= 0 ? QString( res.left( lastIndex ) + 
'_' + 
id.toString() + res.mid( lastIndex ) ) : QString( res + 
'_' + 
id.toString() );
 
 
 1235  static std::vector< std::unique_ptr< QTemporaryDir > > sTempFolders;
 
 1236  static QString sFolder;
 
 1237  static QMutex sMutex;
 
 1238  QMutexLocker locker( &sMutex );
 
 1243  if ( basePath.isEmpty() )
 
 1246  if ( basePath.isEmpty() )
 
 1249    if ( sTempFolders.empty() )
 
 1251      const QString templatePath = QStringLiteral( 
"%1/processing_XXXXXX" ).arg( QDir::tempPath() );
 
 1252      std::unique_ptr< QTemporaryDir > 
tempFolder = std::make_unique< QTemporaryDir >( templatePath );
 
 1254      sTempFolders.emplace_back( std::move( 
tempFolder ) );
 
 1257  else if ( sFolder.isEmpty() || !sFolder.startsWith( basePath ) || sTempFolders.empty() )
 
 1259    if ( !QDir().exists( basePath ) )
 
 1260      QDir().mkpath( basePath );
 
 1262    const QString templatePath = QStringLiteral( 
"%1/processing_XXXXXX" ).arg( basePath );
 
 1263    std::unique_ptr< QTemporaryDir > 
tempFolder = std::make_unique< QTemporaryDir >( templatePath );
 
 1265    sTempFolders.emplace_back( std::move( 
tempFolder ) );
 
 
 1272  QString subPath = QUuid::createUuid().toString().remove( 
'-' ).remove( 
'{' ).remove( 
'}' );
 
 1273  QString path = 
tempFolder( context ) + 
'/' + subPath;
 
 1274  if ( !QDir( path ).exists() ) 
 
 1277    tmpDir.mkdir( path );
 
 
 1284  auto getText = [map]( 
const QString & key )->QString
 
 1286    if ( map.contains( key ) )
 
 1287      return map.value( key ).toString();
 
 1292  s += QStringLiteral( 
"<html><body><p>" ) + getText( QStringLiteral( 
"ALG_DESC" ) ) + QStringLiteral( 
"</p>\n" );
 
 1301    if ( !getText( def->name() ).isEmpty() )
 
 1303      inputs += QStringLiteral( 
"<h3>" ) + def->description() + QStringLiteral( 
"</h3>\n" );
 
 1304      inputs += QStringLiteral( 
"<p>" ) + getText( def->name() ) + QStringLiteral( 
"</p>\n" );
 
 1307  if ( !inputs.isEmpty() )
 
 1308    s += QStringLiteral( 
"<h2>" ) + QObject::tr( 
"Input parameters" ) + QStringLiteral( 
"</h2>\n" ) + inputs;
 
 1314    if ( !getText( def->name() ).isEmpty() )
 
 1316      outputs += QStringLiteral( 
"<h3>" ) + def->description() + QStringLiteral( 
"</h3>\n" );
 
 1317      outputs += QStringLiteral( 
"<p>" ) + getText( def->name() ) + QStringLiteral( 
"</p>\n" );
 
 1320  if ( !outputs.isEmpty() )
 
 1321    s += QStringLiteral( 
"<h2>" ) + QObject::tr( 
"Outputs" ) + QStringLiteral( 
"</h2>\n" ) + outputs;
 
 1323  if ( !map.value( QStringLiteral( 
"EXAMPLES" ) ).toString().isEmpty() )
 
 1324    s += QStringLiteral( 
"<h2>%1</h2>\n<p>%2</p>" ).arg( QObject::tr( 
"Examples" ), getText( QStringLiteral( 
"EXAMPLES" ) ) );
 
 1326  s += QLatin1String( 
"<br>" );
 
 1327  if ( !map.value( QStringLiteral( 
"ALG_CREATOR" ) ).toString().isEmpty() )
 
 1328    s += QStringLiteral( 
"<p align=\"right\">" ) + QObject::tr( 
"Algorithm author:" ) + QStringLiteral( 
" " ) + getText( QStringLiteral( 
"ALG_CREATOR" ) ) + QStringLiteral( 
"</p>" );
 
 1329  if ( !map.value( QStringLiteral( 
"ALG_HELP_CREATOR" ) ).toString().isEmpty() )
 
 1330    s += QStringLiteral( 
"<p align=\"right\">" ) + QObject::tr( 
"Help author:" ) + QStringLiteral( 
" " ) + getText( QStringLiteral( 
"ALG_HELP_CREATOR" ) ) + QStringLiteral( 
"</p>" );
 
 1331  if ( !map.value( QStringLiteral( 
"ALG_VERSION" ) ).toString().isEmpty() )
 
 1332    s += QStringLiteral( 
"<p align=\"right\">" ) + QObject::tr( 
"Algorithm version:" ) + QStringLiteral( 
" " ) + getText( QStringLiteral( 
"ALG_VERSION" ) ) + QStringLiteral( 
"</p>" );
 
 1334  s += QLatin1String( 
"</body></html>" );
 
 
 1339    long long featureLimit, 
const QString &filterExpression )
 
 1341  bool requiresTranslation = 
false;
 
 1345  requiresTranslation = requiresTranslation || selectedFeaturesOnly;
 
 1348  requiresTranslation = requiresTranslation || featureLimit != -1 || !filterExpression.isEmpty();
 
 1353  requiresTranslation = requiresTranslation || vl->
providerType() != QLatin1String( 
"ogr" );
 
 1357  requiresTranslation = requiresTranslation || !vl->
subsetString().isEmpty();
 
 1361  requiresTranslation = requiresTranslation || vl->
source().startsWith( QLatin1String( 
"/vsi" ) );
 
 1365  if ( !requiresTranslation )
 
 1368    if ( parts.contains( QStringLiteral( 
"path" ) ) )
 
 1370      diskPath = parts.value( QStringLiteral( 
"path" ) ).toString();
 
 1371      QFileInfo fi( diskPath );
 
 1372      requiresTranslation = !compatibleFormats.contains( fi.suffix(), Qt::CaseInsensitive );
 
 1376      const QString srcLayerName = parts.value( QStringLiteral( 
"layerName" ) ).toString();
 
 1380        *layerName = srcLayerName;
 
 1385        requiresTranslation = requiresTranslation || ( !srcLayerName.isEmpty() && srcLayerName != fi.baseName() );
 
 1390      requiresTranslation = 
true; 
 
 1394  if ( requiresTranslation )
 
 1405    if ( featureLimit != -1 )
 
 1409    if ( !filterExpression.isEmpty() )
 
 1414    if ( selectedFeaturesOnly )
 
 
 1435  return convertToCompatibleFormatInternal( vl, selectedFeaturesOnly, baseName, compatibleFormats, preferredFormat, context, feedback, 
nullptr, featureLimit, filterExpression );
 
 
 1441  return convertToCompatibleFormatInternal( layer, selectedFeaturesOnly, baseName, compatibleFormats, preferredFormat, context, feedback, &layerName, featureLimit, filterExpression );
 
 
 1447  QSet< QString > usedNames;
 
 1448  for ( 
const QgsField &f : fieldsA )
 
 1450    usedNames.insert( f.name().toLower() );
 
 1453  for ( 
const QgsField &f : fieldsB )
 
 1456    newField.
setName( fieldsBPrefix + f.name() );
 
 1457    if ( usedNames.contains( newField.
name().toLower() ) )
 
 1460      QString newName = newField.
name() + 
'_' + QString::number( idx );
 
 1461      while ( usedNames.contains( newName.toLower() ) || fieldsB.
indexOf( newName ) != -1 )
 
 1464        newName = newField.
name() + 
'_' + QString::number( idx );
 
 1467      outFields.
append( newField );
 
 1471      outFields.
append( newField );
 
 1473    usedNames.insert( newField.
name() );
 
 
 1483  if ( !fieldNames.isEmpty() )
 
 1485    indices.reserve( fieldNames.count() );
 
 1486    for ( 
const QString &f : fieldNames )
 
 1490        indices.append( idx );
 
 1495    indices.reserve( fields.
count() );
 
 1496    for ( 
int i = 0; i < fields.
count(); ++i )
 
 1497      indices.append( i );
 
 
 1506  for ( 
int i : indices )
 
 1507    fieldsSubset.
append( fields.
at( i ) );
 
 1508  return fieldsSubset;
 
 
 1514  if ( setting == -1 )
 
 1515    return QStringLiteral( 
"gpkg" );
 
 
 1522  if ( setting == -1 )
 
 1523    return QStringLiteral( 
"tif" );
 
 
 1529  return QStringLiteral( 
"las" );
 
 
 1534  return QStringLiteral( 
"mbtiles" );
 
 
 1539  auto layerPointerToString = []( 
QgsMapLayer * layer ) -> QString
 
 1541    if ( layer && layer->
providerType() == QLatin1String( 
"memory" ) )
 
 1549  auto cleanPointerValues = [&layerPointerToString]( 
const QVariant & value ) -> QVariant
 
 1551    if ( 
QgsMapLayer *layer = qobject_cast< QgsMapLayer * >( value.value< QObject * >() ) )
 
 1554      return layerPointerToString( layer );
 
 1556    else if ( value.userType() == QMetaType::type( 
"QPointer< QgsMapLayer >" ) )
 
 1559      return layerPointerToString( value.value< QPointer< QgsMapLayer > >().data() );
 
 1568  for ( 
auto it = map.constBegin(); it != map.constEnd(); ++it )
 
 1570    if ( it->type() == QVariant::Map )
 
 1574    else if ( it->type() == QVariant::List )
 
 1577      const QVariantList source = it.value().toList();
 
 1578      dest.reserve( source.size() );
 
 1579      for ( 
const QVariant &v : source )
 
 1581        dest.append( cleanPointerValues( v ) );
 
 1583      res.insert( it.key(), dest );
 
 1587      res.insert( it.key(), cleanPointerValues( it.value() ) );
 
 
 1597  for ( 
auto it = parameters.constBegin(); it != parameters.constEnd(); ++it )
 
 1599    if ( it.value().type() == QVariant::Map )
 
 1601      const QVariantMap value = it.value().toMap();
 
 1602      if ( value.value( QStringLiteral( 
"type" ) ).toString() == QLatin1String( 
"data_defined" ) )
 
 1604        const QString expression = value.value( QStringLiteral( 
"expression" ) ).toString();
 
 1605        const QString field = value.value( QStringLiteral( 
"field" ) ).toString();
 
 1606        if ( !expression.isEmpty() )
 
 1610        else if ( !field.isEmpty() )
 
 1617          error = QObject::tr( 
"Invalid data defined parameter for %1, requires 'expression' or 'field' values." ).arg( it.key() );
 
 1622        output.insert( it.key(), it.value() );
 
 1625    else if ( it.value().type() == QVariant::String )
 
 1627      const QString stringValue = it.value().toString();
 
 1629      if ( stringValue.startsWith( QLatin1String( 
"field:" ) ) )
 
 1633      else if ( stringValue.startsWith( QLatin1String( 
"expression:" ) ) )
 
 1639        output.insert( it.key(), it.value() );
 
 1644      output.insert( it.key(), it.value() );
 
 
 1652  if ( ! QTextCodec::availableCodecs().contains( defaultEncoding.toLatin1() ) )
 
 1654    const QString systemCodec = QTextCodec::codecForLocale()->name();
 
 1655    if ( ! systemCodec.isEmpty() )
 
 1659    return QString( 
"UTF-8" );
 
 1662  return defaultEncoding;
 
 
 1670  : mSource( originalSource )
 
 1671  , mOwnsSource( ownsOriginalSource )
 
 1672  , mSourceCrs( mSource->sourceCrs() )
 
 1673  , mSourceFields( mSource->fields() )
 
 1674  , mSourceWkbType( mSource->wkbType() )
 
 1675  , mSourceName( mSource->sourceName() )
 
 1676  , mSourceExtent( mSource->sourceExtent() )
 
 1677  , mSourceSpatialIndexPresence( mSource->hasSpatialIndex() )
 
 1678  , mInvalidGeometryCheck( 
QgsWkbTypes::geometryType( mSource->wkbType() ) == 
Qgis::GeometryType::Point
 
 1679                           ? 
Qgis::InvalidGeometryCheck::NoCheck 
 
 1680                           : context.invalidGeometryCheck() )
 
 1681  , mInvalidGeometryCallback( context.invalidGeometryCallback( originalSource ) )
 
 1682  , mTransformErrorCallback( context.transformErrorCallback() )
 
 1683  , mInvalidGeometryCallbackSkip( context.defaultInvalidGeometryCallbackForCheck( 
Qgis::InvalidGeometryCheck::SkipInvalid, originalSource ) )
 
 1684  , mInvalidGeometryCallbackAbort( context.defaultInvalidGeometryCallbackForCheck( 
Qgis::InvalidGeometryCheck::AbortOnInvalid, originalSource ) )
 
 1685  , mFeatureLimit( featureLimit )
 
 1686  , mFilterExpression( filterExpression )
 
 
 1708  if ( mFeatureLimit != -1 && req.
limit() != -1 )
 
 1709    req.
setLimit( std::min( 
static_cast< long long >( req.
limit() ), mFeatureLimit ) );
 
 1710  else if ( mFeatureLimit != -1 )
 
 1713  if ( !mFilterExpression.isEmpty() )
 
 
 1725    return sourceAvailability;
 
 
 1738  if ( mFeatureLimit != -1 && req.
limit() != -1 )
 
 1739    req.
setLimit( std::min( 
static_cast< long long >( req.
limit() ), mFeatureLimit ) );
 
 1740  else if ( mFeatureLimit != -1 )
 
 1743  if ( !mFilterExpression.isEmpty() )
 
 
 1756  return mSourceFields;
 
 
 1761  return mSourceWkbType;
 
 
 1766  if ( !mFilterExpression.isEmpty() )
 
 1769  if ( mFeatureLimit == -1 )
 
 1772    return std::min( mFeatureLimit, mSource->
featureCount() );
 
 
 1782  if ( mFilterExpression.isEmpty() )
 
 1787  if ( fieldIndex < 0 || fieldIndex >= 
fields().count() )
 
 1788    return QSet<QVariant>();
 
 1795  QSet<QVariant> values;
 
 1800    values.insert( f.
attribute( fieldIndex ) );
 
 1801    if ( limit > 0 && values.size() >= limit )
 
 
 1809  if ( mFilterExpression.isEmpty() )
 
 1814  if ( fieldIndex < 0 || fieldIndex >= 
fields().count() )
 
 1826    const QVariant v = f.
attribute( fieldIndex );
 
 
 1837  if ( mFilterExpression.isEmpty() )
 
 1842  if ( fieldIndex < 0 || fieldIndex >= 
fields().count() )
 
 1854    const QVariant v = f.
attribute( fieldIndex );
 
 
 1865  return mSourceExtent;
 
 
 1870  if ( mFilterExpression.isEmpty() )
 
 1876                                        .setFilterExpression( mFilterExpression ) );
 
 
 1891  return mSourceSpatialIndexPresence;
 
 
 1902  return expressionContextScope;
 
 
 1907  mInvalidGeometryCheck = method;
 
 1908  switch ( mInvalidGeometryCheck )
 
 1911      mInvalidGeometryCallback = 
nullptr;
 
 1915      mInvalidGeometryCallback = mInvalidGeometryCallbackSkip;
 
 1919      mInvalidGeometryCallback = mInvalidGeometryCallbackAbort;
 
 
 1927  return mInvalidGeometryCheck;
 
 
 1936  , mContext( context )
 
 1937  , mSinkName( sinkName )
 
 1938  , mOwnsSink( ownsOriginalSink )
 
 
 1950  if ( !result && mContext.
feedback() )
 
 1953    if ( !error.isEmpty() )
 
 1954      mContext.
feedback()->
reportError( QObject::tr( 
"Feature could not be written to %1: %2" ).arg( mSinkName, error ) );
 
 1956      mContext.
feedback()->
reportError( QObject::tr( 
"Feature could not be written to %1" ).arg( mSinkName ) );
 
 
 1964  if ( !result && mContext.
feedback() )
 
 1967    if ( !error.isEmpty() )
 
 1968      mContext.
feedback()->
reportError( QObject::tr( 
"%n feature(s) could not be written to %1: %2", 
nullptr, features.count() ).arg( mSinkName, error ) );
 
 1970      mContext.
feedback()->
reportError( QObject::tr( 
"%n feature(s) could not be written to %1", 
nullptr, features.count() ).arg( mSinkName ) );
 
 
 1978  if ( !result && mContext.
feedback() )
 
 1981    if ( !error.isEmpty() )
 
 1982      mContext.
feedback()->
reportError( QObject::tr( 
"Features could not be written to %1: %2" ).arg( mSinkName, error ) );
 
 1984      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.
@ 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.
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.
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)
Fetch next feature and stores in f, returns true on success.
This class 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.
@ 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 QSet< QVariant > uniqueValues(int fieldIndex, int limit=-1) const
Returns the set of unique values contained within the specified fieldIndex from this source.
virtual Qgis::FeatureAvailability hasFeatures() const
Determines if there are any features available in the 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 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.
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
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.
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 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 QString layerToStringIdentifier(const QgsMapLayer *layer)
Returns a string representation of the source for a layer.
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 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 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.
@ 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.
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.
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 xMinimum() const
Returns the x minimum value (left side of rectangle).
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
double xMaximum() const
Returns the x maximum value (right side of rectangle).
double yMaximum() const
Returns the y maximum value (top 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.
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.
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 tiled scene layers.
bool skipCrsValidation
Controls whether the layer is allowed to have an invalid/unknown CRS.
Setting options for loading vector layers.