19#include "moc_qgsprocessingmodelalgorithm.cpp"
36#include <QRegularExpression>
39QgsProcessingModelAlgorithm::QgsProcessingModelAlgorithm(
const QString &name,
const QString &group,
const QString &groupId )
40 : mModelName( name.isEmpty() ? QObject::tr(
"model" ) : name )
41 , mModelGroup( group )
42 , mModelGroupId( groupId )
45void QgsProcessingModelAlgorithm::initAlgorithm(
const QVariantMap & )
54 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
55 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
66QString QgsProcessingModelAlgorithm::name()
const
71QString QgsProcessingModelAlgorithm::displayName()
const
76QString QgsProcessingModelAlgorithm::group()
const
81QString QgsProcessingModelAlgorithm::groupId()
const
86QIcon QgsProcessingModelAlgorithm::icon()
const
91QString QgsProcessingModelAlgorithm::svgIconPath()
const
96QString QgsProcessingModelAlgorithm::shortHelpString()
const
98 if ( mHelpContent.empty() )
104QString QgsProcessingModelAlgorithm::shortDescription()
const
106 return mHelpContent.value( QStringLiteral(
"SHORT_DESCRIPTION" ) ).toString();
109QString QgsProcessingModelAlgorithm::helpUrl()
const
111 return mHelpContent.value( QStringLiteral(
"HELP_URL" ) ).toString();
114QVariantMap QgsProcessingModelAlgorithm::parametersForChildAlgorithm(
const QgsProcessingModelChildAlgorithm &child,
const QVariantMap &modelParameters,
const QVariantMap &results,
const QgsExpressionContext &expressionContext, QString &error,
const QgsProcessingContext *context )
const
119 const QgsProcessingModelChildParameterSources paramSources = child.parameterSources().value( def->name() );
121 QString expressionText;
122 QVariantList paramParts;
123 for (
const QgsProcessingModelChildParameterSource &source : paramSources )
125 switch ( source.source() )
128 paramParts << source.staticValue();
132 paramParts << modelParameters.value( source.parameterName() );
137 QVariantMap linkedChildResults = results.value( source.outputChildId() ).toMap();
138 paramParts << linkedChildResults.value( source.outputName() );
145 paramParts << exp.evaluate( &expressionContext );
146 if ( exp.hasEvalError() )
148 error = QObject::tr(
"Could not evaluate expression for parameter %1 for %2: %3" ).arg( def->name(), child.description(), exp.evalErrorString() );
163 if ( ! expressionText.isEmpty() )
165 return expressionText;
167 else if ( paramParts.count() == 1 )
168 return paramParts.at( 0 );
174 QVariantMap childParams;
175 const QList< const QgsProcessingParameterDefinition * > childParameterDefinitions = child.algorithm()->parameterDefinitions();
178 if ( !def->isDestination() )
180 if ( !child.parameterSources().contains( def->name() ) )
183 const QVariant value = evaluateSources( def );
184 childParams.insert( def->name(), value );
191 bool isFinalOutput =
false;
192 QMap<QString, QgsProcessingModelOutput> outputs = child.modelOutputs();
193 QMap<QString, QgsProcessingModelOutput>::const_iterator outputIt = outputs.constBegin();
194 for ( ; outputIt != outputs.constEnd(); ++outputIt )
196 if ( outputIt->childOutputName() == destParam->
name() )
198 QString paramName = child.childId() +
':' + outputIt.key();
199 bool foundParam =
false;
203 if ( modelParameters.contains( paramName ) )
205 value = modelParameters.value( paramName );
214 if ( modelParameters.contains( modelParam->name() ) )
216 value = modelParameters.value( modelParam->name() );
224 if ( value.userType() == qMetaTypeId<QgsProcessingOutputLayerDefinition>() )
229 value = QVariant::fromValue( fromVar );
232 childParams.insert( destParam->
name(), value );
234 isFinalOutput =
true;
239 bool hasExplicitDefinition =
false;
240 if ( !isFinalOutput && child.parameterSources().contains( def->name() ) )
243 const QVariant value = evaluateSources( def );
244 if ( value.isValid() )
246 childParams.insert( def->name(), value );
247 hasExplicitDefinition =
true;
251 if ( !isFinalOutput && !hasExplicitDefinition )
256 bool required =
true;
259 required = childOutputIsRequired( child.childId(), destParam->
name() );
271const QgsProcessingParameterDefinition *QgsProcessingModelAlgorithm::modelParameterFromChildIdAndOutputName(
const QString &childId,
const QString &childOutputName )
const
275 if ( !definition->isDestination() )
278 const QString modelChildId = definition->
metadata().value( QStringLiteral(
"_modelChildId" ) ).toString();
279 const QString modelOutputName = definition->metadata().value( QStringLiteral(
"_modelChildOutputName" ) ).toString();
281 if ( modelChildId == childId && modelOutputName == childOutputName )
287bool QgsProcessingModelAlgorithm::childOutputIsRequired(
const QString &childId,
const QString &outputName )
const
290 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
291 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
293 if ( childIt->childId() == childId || !childIt->isActive() )
297 QMap<QString, QgsProcessingModelChildParameterSources> candidateChildParams = childIt->parameterSources();
298 QMap<QString, QgsProcessingModelChildParameterSources>::const_iterator childParamIt = candidateChildParams.constBegin();
299 for ( ; childParamIt != candidateChildParams.constEnd(); ++childParamIt )
301 const auto constValue = childParamIt.value();
302 for (
const QgsProcessingModelChildParameterSource &source : constValue )
305 && source.outputChildId() == childId
306 && source.outputName() == outputName )
318 QSet< QString > toExecute;
319 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
320 QSet< QString > broken;
322 const bool useSubsetOfChildren = !childSubset.empty();
323 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
325 if ( childIt->isActive() && ( !useSubsetOfChildren || childSubset.contains( childIt->childId() ) ) )
327 if ( childIt->algorithm() )
328 toExecute.insert( childIt->childId() );
330 broken.insert( childIt->childId() );
334 if ( !broken.empty() )
335 throw QgsProcessingException( QCoreApplication::translate(
"QgsProcessingModelAlgorithm",
"Cannot run model, the following algorithms are not available on this system: %1" ).arg(
qgsSetJoin( broken, QLatin1String(
", " ) ) ) );
337 QElapsedTimer totalTime;
351 childInputs = config->initialChildInputs();
352 childResults = config->initialChildOutputs();
353 executed = config->previouslyExecutedChildAlgorithms();
357 if ( useSubsetOfChildren )
359 executed.subtract( childSubset );
362 QVariantMap finalResults;
364 bool executedAlg =
true;
365 int previousHtmlLogLength = feedback->
htmlLog().length();
366 int countExecuted = 0;
367 while ( executedAlg && countExecuted < toExecute.count() )
370 for (
const QString &childId : std::as_const( toExecute ) )
375 if ( executed.contains( childId ) )
378 bool canExecute =
true;
379 const QSet< QString > dependencies = dependsOnChildAlgorithms( childId );
380 for (
const QString &dependency : dependencies )
382 if ( !executed.contains( dependency ) )
394 const QgsProcessingModelChildAlgorithm &child = mChildAlgorithms[ childId ];
395 std::unique_ptr< QgsProcessingAlgorithm > childAlg( child.algorithm()->create( child.configuration() ) );
397 bool skipGenericLogging =
true;
402 skipGenericLogging =
true;
412 skipGenericLogging =
false;
416 if ( feedback && !skipGenericLogging )
417 feedback->
pushDebugInfo( QObject::tr(
"Prepare algorithm: %1" ).arg( childId ) );
421 << createExpressionContextScopeForChildAlgorithm( childId, context, parameters, childResults );
425 QVariantMap childParams = parametersForChildAlgorithm( child, parameters, childResults, expContext, error, &context );
426 if ( !error.isEmpty() )
429 if ( feedback && !skipGenericLogging )
430 feedback->
setProgressText( QObject::tr(
"Running %1 [%2/%3]" ).arg( child.description() ).arg( executed.count() + 1 ).arg( toExecute.count() ) );
435 childInputs.insert( childId, thisChildParams );
436 childResult.
setInputs( thisChildParams );
439 for (
auto childParamIt = childParams.constBegin(); childParamIt != childParams.constEnd(); ++childParamIt )
441 params << QStringLiteral(
"%1: %2" ).arg( childParamIt.key(),
442 child.algorithm()->parameterDefinition( childParamIt.key() )->valueAsPythonString( childParamIt.value(), context ) );
445 if ( feedback && !skipGenericLogging )
447 feedback->
pushInfo( QObject::tr(
"Input Parameters:" ) );
448 feedback->
pushCommandInfo( QStringLiteral(
"{ %1 }" ).arg( params.join( QLatin1String(
", " ) ) ) );
451 QElapsedTimer childTime;
456 QThread *modelThread = QThread::currentThread();
458 auto prepareOnMainThread = [modelThread, &ok, &childAlg, &childParams, &context, &modelFeedback]
460 Q_ASSERT_X( QThread::currentThread() == qApp->thread(),
"QgsProcessingModelAlgorithm::processAlgorithm",
"childAlg->prepare() must be run on the main thread" );
461 ok = childAlg->prepare( childParams, context, &modelFeedback );
462 context.pushToThread( modelThread );
466 if ( modelThread == qApp->thread() )
467 ok = childAlg->prepare( childParams, context, &modelFeedback );
470 context.pushToThread( qApp->thread() );
472#ifndef __clang_analyzer__
473 QMetaObject::invokeMethod( qApp, prepareOnMainThread, Qt::BlockingQueuedConnection );
477 Q_ASSERT_X( QThread::currentThread() == context.thread(),
"QgsProcessingModelAlgorithm::processAlgorithm",
"context was not transferred back to model thread" );
487 bool runResult =
false;
493 auto runOnMainThread = [modelThread, &context, &modelFeedback, &results, &childAlg, &childParams]
495 Q_ASSERT_X( QThread::currentThread() == qApp->thread(),
"QgsProcessingModelAlgorithm::processAlgorithm",
"childAlg->runPrepared() must be run on the main thread" );
496 results = childAlg->runPrepared( childParams, context, &modelFeedback );
497 context.pushToThread( modelThread );
500 if ( feedback && !skipGenericLogging && modelThread != qApp->thread() )
501 feedback->
pushWarning( QObject::tr(
"Algorithm “%1” cannot be run in a background thread, switching to main thread for this step" ).arg( childAlg->displayName() ) );
503 context.pushToThread( qApp->thread() );
505#ifndef __clang_analyzer__
506 QMetaObject::invokeMethod( qApp, runOnMainThread, Qt::BlockingQueuedConnection );
512 results = childAlg->runPrepared( childParams, context, &modelFeedback );
523 Q_ASSERT_X( QThread::currentThread() == context.thread(),
"QgsProcessingModelAlgorithm::processAlgorithm",
"context was not transferred back to model thread" );
526 auto postProcessOnMainThread = [modelThread, &ppRes, &childAlg, &context, &modelFeedback, runResult]
528 Q_ASSERT_X( QThread::currentThread() == qApp->thread(),
"QgsProcessingModelAlgorithm::processAlgorithm",
"childAlg->postProcess() must be run on the main thread" );
529 ppRes = childAlg->postProcess( context, &modelFeedback, runResult );
530 context.pushToThread( modelThread );
534 if ( modelThread == qApp->thread() )
535 ppRes = childAlg->postProcess( context, &modelFeedback, runResult );
538 context.pushToThread( qApp->thread() );
540#ifndef __clang_analyzer__
541 QMetaObject::invokeMethod( qApp, postProcessOnMainThread, Qt::BlockingQueuedConnection );
545 Q_ASSERT_X( QThread::currentThread() == context.thread(),
"QgsProcessingModelAlgorithm::processAlgorithm",
"context was not transferred back to model thread" );
547 if ( !ppRes.isEmpty() )
550 childResults.insert( childId, results );
555 if ( feedback && !skipGenericLogging )
558 QStringList formattedOutputs;
559 for (
auto displayOutputIt = displayOutputs.constBegin(); displayOutputIt != displayOutputs.constEnd(); ++displayOutputIt )
561 formattedOutputs << QStringLiteral(
"%1: %2" ).arg( displayOutputIt.key(),
564 feedback->
pushInfo( QObject::tr(
"Results:" ) );
565 feedback->
pushCommandInfo( QStringLiteral(
"{ %1 }" ).arg( formattedOutputs.join( QLatin1String(
", " ) ) ) );
570 const QMap<QString, QgsProcessingModelOutput> outputs = child.modelOutputs();
571 for (
auto outputIt = outputs.constBegin(); outputIt != outputs.constEnd(); ++outputIt )
573 const int outputSortKey = mOutputOrder.indexOf( QStringLiteral(
"%1:%2" ).arg( childId, outputIt->childOutputName() ) );
574 switch ( mInternalVersion )
576 case QgsProcessingModelAlgorithm::InternalVersion::Version1:
577 finalResults.insert( childId +
':' + outputIt->name(), results.value( outputIt->childOutputName() ) );
579 case QgsProcessingModelAlgorithm::InternalVersion::Version2:
582 finalResults.insert( modelParam->name(), results.value( outputIt->childOutputName() ) );
587 const QString outputLayer = results.value( outputIt->childOutputName() ).toString();
588 if ( !outputLayer.isEmpty() && context.willLoadLayerOnCompletion( outputLayer ) )
592 if ( outputSortKey > 0 )
597 executed.insert( childId );
599 std::function< void(
const QString &,
const QString & )> pruneAlgorithmBranchRecursive;
600 pruneAlgorithmBranchRecursive = [&](
const QString & id,
const QString &branch = QString() )
602 const QSet<QString> toPrune = dependentChildAlgorithms(
id, branch );
603 for (
const QString &targetId : toPrune )
605 if ( executed.contains( targetId ) )
608 executed.insert( targetId );
609 pruneAlgorithmBranchRecursive( targetId, branch );
619 pruneAlgorithmBranchRecursive( childId, outputDef->name() );
627 for (
const QString &candidateId : std::as_const( toExecute ) )
629 if ( executed.contains( candidateId ) )
634 const QgsProcessingModelChildAlgorithm &candidate = mChildAlgorithms[ candidateId ];
635 const QMap<QString, QgsProcessingModelChildParameterSources> candidateParams = candidate.parameterSources();
636 QMap<QString, QgsProcessingModelChildParameterSources>::const_iterator paramIt = candidateParams.constBegin();
638 for ( ; paramIt != candidateParams.constEnd(); ++paramIt )
640 for (
const QgsProcessingModelChildParameterSource &source : paramIt.value() )
645 if ( !results.contains( source.outputName() ) )
650 executed.insert( candidateId );
652 pruneAlgorithmBranchRecursive( candidateId, QString() );
663 childAlg.reset(
nullptr );
665 modelFeedback.setCurrentStep( countExecuted );
666 if ( feedback && !skipGenericLogging )
668 feedback->
pushInfo( QObject::tr(
"OK. Execution took %1 s (%n output(s)).",
nullptr, results.count() ).arg( childTime.elapsed() / 1000.0 ) );
673 const QString thisAlgorithmHtmlLog = feedback->
htmlLog().mid( previousHtmlLogLength );
674 previousHtmlLogLength = feedback->
htmlLog().length();
678 const QString formattedException = QStringLiteral(
"<span style=\"color:red\">%1</span><br/>" ).arg( error.toHtmlEscaped() ).replace(
'\n', QLatin1String(
"<br>" ) );
679 const QString formattedRunTime = QStringLiteral(
"<span style=\"color:red\">%1</span><br/>" ).arg( QObject::tr(
"Failed after %1 s." ).arg( childTime.elapsed() / 1000.0 ).toHtmlEscaped() ).replace(
'\n', QLatin1String(
"<br>" ) );
681 childResult.
setHtmlLog( thisAlgorithmHtmlLog + formattedException + formattedRunTime );
682 context.modelResult().childResults().insert( childId, childResult );
688 childResult.
setHtmlLog( thisAlgorithmHtmlLog );
689 context.modelResult().childResults().insert( childId, childResult );
697 feedback->
pushDebugInfo( QObject::tr(
"Model processed OK. Executed %n algorithm(s) total in %1 s.",
nullptr, countExecuted ).arg(
static_cast< double >( totalTime.elapsed() ) / 1000.0 ) );
699 mResults = finalResults;
700 mResults.insert( QStringLiteral(
"CHILD_RESULTS" ), childResults );
701 mResults.insert( QStringLiteral(
"CHILD_INPUTS" ), childInputs );
705QString QgsProcessingModelAlgorithm::sourceFilePath()
const
710void QgsProcessingModelAlgorithm::setSourceFilePath(
const QString &sourceFile )
712 mSourceFile = sourceFile;
715bool QgsProcessingModelAlgorithm::modelNameMatchesFilePath()
const
717 if ( mSourceFile.isEmpty() )
720 const QFileInfo fi( mSourceFile );
721 return fi.completeBaseName().compare( mModelName, Qt::CaseInsensitive ) == 0;
726 QStringList fileDocString;
727 fileDocString << QStringLiteral(
"\"\"\"" );
728 fileDocString << QStringLiteral(
"Model exported as python." );
729 fileDocString << QStringLiteral(
"Name : %1" ).arg( displayName() );
730 fileDocString << QStringLiteral(
"Group : %1" ).arg( group() );
731 fileDocString << QStringLiteral(
"With QGIS : %1" ).arg(
Qgis::versionInt() );
732 fileDocString << QStringLiteral(
"\"\"\"" );
733 fileDocString << QString();
736 QString indent = QString(
' ' ).repeated( indentSize );
737 QString currentIndent;
739 QMap< QString, QString> friendlyChildNames;
740 QMap< QString, QString> friendlyOutputNames;
741 auto uniqueSafeName = [](
const QString & name,
bool capitalize,
const QMap< QString, QString > &friendlyNames )->QString
743 const QString base = safeName( name, capitalize );
744 QString candidate = base;
746 while ( friendlyNames.contains( candidate ) )
749 candidate = QStringLiteral(
"%1_%2" ).arg( base ).arg( i );
754 const QString algorithmClassName = safeName( name(),
true );
756 QSet< QString > toExecute;
757 for (
auto childIt = mChildAlgorithms.constBegin(); childIt != mChildAlgorithms.constEnd(); ++childIt )
759 if ( childIt->isActive() && childIt->algorithm() )
761 toExecute.insert( childIt->childId() );
762 friendlyChildNames.insert( childIt->childId(), uniqueSafeName( childIt->description().isEmpty() ? childIt->childId() : childIt->description(), !childIt->description().isEmpty(), friendlyChildNames ) );
765 const int totalSteps = toExecute.count();
767 QStringList importLines;
768 switch ( outputType )
773 const auto params = parameterDefinitions();
774 importLines.reserve( params.count() + 3 );
775 importLines << QStringLiteral(
"from qgis.core import QgsProcessing" );
776 importLines << QStringLiteral(
"from qgis.core import QgsProcessingAlgorithm" );
777 importLines << QStringLiteral(
"from qgis.core import QgsProcessingMultiStepFeedback" );
779 bool hasAdvancedParams =
false;
783 hasAdvancedParams =
true;
786 if ( !importString.isEmpty() && !importLines.contains( importString ) )
787 importLines << importString;
790 if ( hasAdvancedParams )
791 importLines << QStringLiteral(
"from qgis.core import QgsProcessingParameterDefinition" );
793 lines << QStringLiteral(
"import processing" );
794 lines << QString() << QString();
796 lines << QStringLiteral(
"class %1(QgsProcessingAlgorithm):" ).arg( algorithmClassName );
800 lines << indent + QStringLiteral(
"def initAlgorithm(self, config=None):" );
801 if ( params.empty() )
803 lines << indent + indent + QStringLiteral(
"pass" );
807 lines.reserve( lines.size() + params.size() );
810 std::unique_ptr< QgsProcessingParameterDefinition > defClone( def->clone() );
812 if ( defClone->isDestination() )
814 const QString uniqueChildName = defClone->metadata().value( QStringLiteral(
"_modelChildId" ) ).toString() +
':' + defClone->metadata().value( QStringLiteral(
"_modelChildOutputName" ) ).toString();
815 const QString friendlyName = !defClone->description().isEmpty() ? uniqueSafeName( defClone->description(),
true, friendlyOutputNames ) : defClone->name();
816 friendlyOutputNames.insert( uniqueChildName, friendlyName );
817 defClone->setName( friendlyName );
821 if ( !mParameterComponents.value( defClone->name() ).comment()->description().isEmpty() )
823 const QStringList parts = mParameterComponents.value( defClone->name() ).comment()->description().split( QStringLiteral(
"\n" ) );
824 for (
const QString &part : parts )
826 lines << indent + indent + QStringLiteral(
"# %1" ).arg( part );
833 lines << indent + indent + QStringLiteral(
"param = %1" ).arg( defClone->asPythonString() );
834 lines << indent + indent + QStringLiteral(
"param.setFlags(param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)" );
835 lines << indent + indent + QStringLiteral(
"self.addParameter(param)" );
839 lines << indent + indent + QStringLiteral(
"self.addParameter(%1)" ).arg( defClone->asPythonString() );
845 lines << indent + QStringLiteral(
"def processAlgorithm(self, parameters, context, model_feedback):" );
846 currentIndent = indent + indent;
848 lines << currentIndent + QStringLiteral(
"# Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the" );
849 lines << currentIndent + QStringLiteral(
"# overall progress through the model" );
850 lines << currentIndent + QStringLiteral(
"feedback = QgsProcessingMultiStepFeedback(%1, model_feedback)" ).arg( totalSteps );
858 QMap< QString, QgsProcessingModelParameter >::const_iterator paramIt = mParameterComponents.constBegin();
859 for ( ; paramIt != mParameterComponents.constEnd(); ++paramIt )
861 QString name = paramIt.value().parameterName();
862 if ( parameterDefinition( name ) )
865 params.insert( name, parameterDefinition( name )->valueAsPythonString( parameterDefinition( name )->defaultValue(), context ) );
869 if ( !params.isEmpty() )
871 lines << QStringLiteral(
"parameters = {" );
872 for (
auto it = params.constBegin(); it != params.constEnd(); ++it )
874 lines << QStringLiteral(
" '%1':%2," ).arg( it.key(), it.value() );
876 lines << QStringLiteral(
"}" )
880 lines << QStringLiteral(
"context = QgsProcessingContext()" )
881 << QStringLiteral(
"context.setProject(QgsProject.instance())" )
882 << QStringLiteral(
"feedback = QgsProcessingFeedback()" )
891 lines << currentIndent + QStringLiteral(
"results = {}" );
892 lines << currentIndent + QStringLiteral(
"outputs = {}" );
895 QSet< QString > executed;
896 bool executedAlg =
true;
898 while ( executedAlg && executed.count() < toExecute.count() )
901 const auto constToExecute = toExecute;
902 for (
const QString &childId : constToExecute )
904 if ( executed.contains( childId ) )
907 bool canExecute =
true;
908 const auto constDependsOnChildAlgorithms = dependsOnChildAlgorithms( childId );
909 for (
const QString &dependency : constDependsOnChildAlgorithms )
911 if ( !executed.contains( dependency ) )
923 const QgsProcessingModelChildAlgorithm &child = mChildAlgorithms[ childId ];
930 if ( def->isDestination() )
935 bool isFinalOutput =
false;
936 QMap<QString, QgsProcessingModelOutput> outputs = child.modelOutputs();
937 QMap<QString, QgsProcessingModelOutput>::const_iterator outputIt = outputs.constBegin();
938 for ( ; outputIt != outputs.constEnd(); ++outputIt )
940 if ( outputIt->childOutputName() == destParam->
name() )
942 QString paramName = child.childId() +
':' + outputIt.key();
943 paramName = friendlyOutputNames.value( paramName, paramName );
944 childParams.insert( destParam->
name(), QStringLiteral(
"parameters['%1']" ).arg( paramName ) );
945 isFinalOutput =
true;
950 if ( !isFinalOutput )
955 bool required =
true;
958 required = childOutputIsRequired( child.childId(), destParam->
name() );
964 childParams.insert( destParam->
name(), QStringLiteral(
"QgsProcessing.TEMPORARY_OUTPUT" ) );
970 lines << child.asPythonCode( outputType, childParams, currentIndent.size(), indentSize, friendlyChildNames, friendlyOutputNames );
972 if ( currentStep < totalSteps )
975 lines << currentIndent + QStringLiteral(
"feedback.setCurrentStep(%1)" ).arg( currentStep );
976 lines << currentIndent + QStringLiteral(
"if feedback.isCanceled():" );
977 lines << currentIndent + indent + QStringLiteral(
"return {}" );
980 executed.insert( childId );
984 switch ( outputType )
987 lines << currentIndent + QStringLiteral(
"return results" );
991 lines << indent + QStringLiteral(
"def name(self):" );
992 lines << indent + indent + QStringLiteral(
"return '%1'" ).arg( mModelName );
994 lines << indent + QStringLiteral(
"def displayName(self):" );
995 lines << indent + indent + QStringLiteral(
"return '%1'" ).arg( mModelName );
999 lines << indent + QStringLiteral(
"def group(self):" );
1000 lines << indent + indent + QStringLiteral(
"return '%1'" ).arg( mModelGroup );
1002 lines << indent + QStringLiteral(
"def groupId(self):" );
1003 lines << indent + indent + QStringLiteral(
"return '%1'" ).arg( mModelGroupId );
1007 if ( !shortHelpString().isEmpty() )
1009 lines << indent + QStringLiteral(
"def shortHelpString(self):" );
1010 lines << indent + indent + QStringLiteral(
"return \"\"\"%1\"\"\"" ).arg( shortHelpString() );
1013 if ( !helpUrl().isEmpty() )
1015 lines << indent + QStringLiteral(
"def helpUrl(self):" );
1016 lines << indent + indent + QStringLiteral(
"return '%1'" ).arg( helpUrl() );
1021 lines << indent + QStringLiteral(
"def createInstance(self):" );
1022 lines << indent + indent + QStringLiteral(
"return %1()" ).arg( algorithmClassName );
1025 static QMap< QString, QString > sAdditionalImports
1027 { QStringLiteral(
"QgsCoordinateReferenceSystem" ), QStringLiteral(
"from qgis.core import QgsCoordinateReferenceSystem" ) },
1028 { QStringLiteral(
"QgsExpression" ), QStringLiteral(
"from qgis.core import QgsExpression" ) },
1029 { QStringLiteral(
"QgsRectangle" ), QStringLiteral(
"from qgis.core import QgsRectangle" ) },
1030 { QStringLiteral(
"QgsReferencedRectangle" ), QStringLiteral(
"from qgis.core import QgsReferencedRectangle" ) },
1031 { QStringLiteral(
"QgsPoint" ), QStringLiteral(
"from qgis.core import QgsPoint" ) },
1032 { QStringLiteral(
"QgsReferencedPoint" ), QStringLiteral(
"from qgis.core import QgsReferencedPoint" ) },
1033 { QStringLiteral(
"QgsProperty" ), QStringLiteral(
"from qgis.core import QgsProperty" ) },
1034 { QStringLiteral(
"QgsRasterLayer" ), QStringLiteral(
"from qgis.core import QgsRasterLayer" ) },
1035 { QStringLiteral(
"QgsMeshLayer" ), QStringLiteral(
"from qgis.core import QgsMeshLayer" ) },
1036 { QStringLiteral(
"QgsVectorLayer" ), QStringLiteral(
"from qgis.core import QgsVectorLayer" ) },
1037 { QStringLiteral(
"QgsMapLayer" ), QStringLiteral(
"from qgis.core import QgsMapLayer" ) },
1038 { QStringLiteral(
"QgsProcessingFeatureSourceDefinition" ), QStringLiteral(
"from qgis.core import QgsProcessingFeatureSourceDefinition" ) },
1039 { QStringLiteral(
"QgsPointXY" ), QStringLiteral(
"from qgis.core import QgsPointXY" ) },
1040 { QStringLiteral(
"QgsReferencedPointXY" ), QStringLiteral(
"from qgis.core import QgsReferencedPointXY" ) },
1041 { QStringLiteral(
"QgsGeometry" ), QStringLiteral(
"from qgis.core import QgsGeometry" ) },
1042 { QStringLiteral(
"QgsProcessingOutputLayerDefinition" ), QStringLiteral(
"from qgis.core import QgsProcessingOutputLayerDefinition" ) },
1043 { QStringLiteral(
"QColor" ), QStringLiteral(
"from qgis.PyQt.QtGui import QColor" ) },
1044 { QStringLiteral(
"QDateTime" ), QStringLiteral(
"from qgis.PyQt.QtCore import QDateTime" ) },
1045 { QStringLiteral(
"QDate" ), QStringLiteral(
"from qgis.PyQt.QtCore import QDate" ) },
1046 { QStringLiteral(
"QTime" ), QStringLiteral(
"from qgis.PyQt.QtCore import QTime" ) },
1049 for (
auto it = sAdditionalImports.constBegin(); it != sAdditionalImports.constEnd(); ++it )
1051 if ( importLines.contains( it.value() ) )
1058 for (
const QString &line : std::as_const( lines ) )
1060 if ( line.contains( it.key() ) )
1068 importLines << it.value();
1072 lines = fileDocString + importLines + lines;
1081QMap<QString, QgsProcessingModelAlgorithm::VariableDefinition> QgsProcessingModelAlgorithm::variablesForChildAlgorithm(
const QString &childId,
QgsProcessingContext *context,
const QVariantMap &modelParameters,
const QVariantMap &results )
const
1083 QMap<QString, QgsProcessingModelAlgorithm::VariableDefinition> variables;
1085 auto safeName = [](
const QString & name )->QString
1088 const thread_local QRegularExpression safeNameRe( QStringLiteral(
"[\\s'\"\\(\\):\\.]" ) );
1089 return s.replace( safeNameRe, QStringLiteral(
"_" ) );
1126 for (
const QgsProcessingModelChildParameterSource &source : std::as_const( sources ) )
1130 QString description;
1131 switch ( source.source() )
1135 name = source.parameterName();
1136 value = modelParameters.value( source.parameterName() );
1137 description = parameterDefinition( source.parameterName() )->description();
1142 const QgsProcessingModelChildAlgorithm &child = mChildAlgorithms.value( source.outputChildId() );
1143 name = QStringLiteral(
"%1_%2" ).arg( child.description().isEmpty() ?
1144 source.outputChildId() : child.description(), source.outputName() );
1147 description = QObject::tr(
"Output '%1' from algorithm '%2'" ).arg( alg->outputDefinition( source.outputName() )->description(),
1148 child.description() );
1150 value = results.value( source.outputChildId() ).toMap().value( source.outputName() );
1160 variables.insert( safeName( name ), VariableDefinition( value, source, description ) );
1164 sources = availableSourcesForChild( childId, QStringList()
1171 for (
const QgsProcessingModelChildParameterSource &source : std::as_const( sources ) )
1175 QString description;
1177 switch ( source.source() )
1181 name = source.parameterName();
1182 value = modelParameters.value( source.parameterName() );
1183 description = parameterDefinition( source.parameterName() )->description();
1188 const QgsProcessingModelChildAlgorithm &child = mChildAlgorithms.value( source.outputChildId() );
1189 name = QStringLiteral(
"%1_%2" ).arg( child.description().isEmpty() ?
1190 source.outputChildId() : child.description(), source.outputName() );
1191 value = results.value( source.outputChildId() ).toMap().value( source.outputName() );
1194 description = QObject::tr(
"Output '%1' from algorithm '%2'" ).arg( alg->outputDefinition( source.outputName() )->description(),
1195 child.description() );
1208 if ( value.userType() == qMetaTypeId<QgsProcessingOutputLayerDefinition>() )
1211 value = fromVar.
sink;
1212 if ( value.userType() == qMetaTypeId<QgsProperty>() && context )
1220 layer = qobject_cast< QgsMapLayer * >( qvariant_cast<QObject *>( value ) );
1225 variables.insert( safeName( name ), VariableDefinition( layer ? QVariant::fromValue(
QgsWeakMapLayerPointer( layer ) ) : QVariant(), source, description ) );
1226 variables.insert( safeName( QStringLiteral(
"%1_minx" ).arg( name ) ), VariableDefinition( layer ? layer->
extent().
xMinimum() : QVariant(), source, QObject::tr(
"Minimum X of %1" ).arg( description ) ) );
1227 variables.insert( safeName( QStringLiteral(
"%1_miny" ).arg( name ) ), VariableDefinition( layer ? layer->
extent().
yMinimum() : QVariant(), source, QObject::tr(
"Minimum Y of %1" ).arg( description ) ) );
1228 variables.insert( safeName( QStringLiteral(
"%1_maxx" ).arg( name ) ), VariableDefinition( layer ? layer->
extent().
xMaximum() : QVariant(), source, QObject::tr(
"Maximum X of %1" ).arg( description ) ) );
1229 variables.insert( safeName( QStringLiteral(
"%1_maxy" ).arg( name ) ), VariableDefinition( layer ? layer->
extent().
yMaximum() : QVariant(), source, QObject::tr(
"Maximum Y of %1" ).arg( description ) ) );
1232 sources = availableSourcesForChild( childId, QStringList()
1234 for (
const QgsProcessingModelChildParameterSource &source : std::as_const( sources ) )
1238 QString description;
1240 switch ( source.source() )
1244 name = source.parameterName();
1245 value = modelParameters.value( source.parameterName() );
1246 description = parameterDefinition( source.parameterName() )->description();
1251 const QgsProcessingModelChildAlgorithm &child = mChildAlgorithms.value( source.outputChildId() );
1252 name = QStringLiteral(
"%1_%2" ).arg( child.description().isEmpty() ?
1253 source.outputChildId() : child.description(), source.outputName() );
1254 value = results.value( source.outputChildId() ).toMap().value( source.outputName() );
1257 description = QObject::tr(
"Output '%1' from algorithm '%2'" ).arg( alg->outputDefinition( source.outputName() )->description(),
1258 child.description() );
1272 if ( value.userType() == qMetaTypeId<QgsProcessingFeatureSourceDefinition>() )
1277 else if ( value.userType() == qMetaTypeId<QgsProcessingOutputLayerDefinition>() )
1280 value = fromVar.
sink;
1281 if ( context && value.userType() == qMetaTypeId<QgsProperty>() )
1286 if (
QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( qvariant_cast<QObject *>( value ) ) )
1288 featureSource = layer;
1290 if ( context && !featureSource )
1296 variables.insert( safeName( name ), VariableDefinition( value, source, description ) );
1297 variables.insert( safeName( QStringLiteral(
"%1_minx" ).arg( name ) ), VariableDefinition( featureSource ? featureSource->
sourceExtent().
xMinimum() : QVariant(), source, QObject::tr(
"Minimum X of %1" ).arg( description ) ) );
1298 variables.insert( safeName( QStringLiteral(
"%1_miny" ).arg( name ) ), VariableDefinition( featureSource ? featureSource->
sourceExtent().
yMinimum() : QVariant(), source, QObject::tr(
"Minimum Y of %1" ).arg( description ) ) );
1299 variables.insert( safeName( QStringLiteral(
"%1_maxx" ).arg( name ) ), VariableDefinition( featureSource ? featureSource->
sourceExtent().
xMaximum() : QVariant(), source, QObject::tr(
"Maximum X of %1" ).arg( description ) ) );
1300 variables.insert( safeName( QStringLiteral(
"%1_maxy" ).arg( name ) ), VariableDefinition( featureSource ? featureSource->
sourceExtent().
yMaximum() : QVariant(), source, QObject::tr(
"Maximum Y of %1" ).arg( description ) ) );
1306QgsExpressionContextScope *QgsProcessingModelAlgorithm::createExpressionContextScopeForChildAlgorithm(
const QString &childId,
QgsProcessingContext &context,
const QVariantMap &modelParameters,
const QVariantMap &results )
const
1308 std::unique_ptr< QgsExpressionContextScope > scope(
new QgsExpressionContextScope( QStringLiteral(
"algorithm_inputs" ) ) );
1309 QMap< QString, QgsProcessingModelAlgorithm::VariableDefinition> variables = variablesForChildAlgorithm( childId, &context, modelParameters, results );
1310 QMap< QString, QgsProcessingModelAlgorithm::VariableDefinition>::const_iterator varIt = variables.constBegin();
1311 for ( ; varIt != variables.constEnd(); ++varIt )
1315 return scope.release();
1318QgsProcessingModelChildParameterSources QgsProcessingModelAlgorithm::availableSourcesForChild(
const QString &childId,
const QStringList ¶meterTypes,
const QStringList &outputTypes,
const QList<int> &dataTypes )
const
1320 QgsProcessingModelChildParameterSources sources;
1323 QMap< QString, QgsProcessingModelParameter >::const_iterator paramIt = mParameterComponents.constBegin();
1324 for ( ; paramIt != mParameterComponents.constEnd(); ++paramIt )
1330 if ( parameterTypes.contains( def->
type() ) )
1332 if ( !dataTypes.isEmpty() )
1348 bool ok = sourceDef->
dataTypes().isEmpty();
1349 const auto constDataTypes = sourceDef->
dataTypes();
1350 for (
int type : constDataTypes )
1365 sources << QgsProcessingModelChildParameterSource::fromModelParameter( paramIt->parameterName() );
1369 QSet< QString > dependents;
1370 if ( !childId.isEmpty() )
1372 dependents = dependentChildAlgorithms( childId );
1373 dependents << childId;
1376 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
1377 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
1379 if ( dependents.contains( childIt->childId() ) )
1389 if ( outputTypes.contains( out->type() ) )
1391 if ( !dataTypes.isEmpty() )
1397 if ( !vectorOutputIsCompatibleType( dataTypes, vectorOut->
dataType() ) )
1404 sources << QgsProcessingModelChildParameterSource::fromChildOutput( childIt->childId(), out->name() );
1412QVariantMap QgsProcessingModelAlgorithm::helpContent()
const
1414 return mHelpContent;
1417void QgsProcessingModelAlgorithm::setHelpContent(
const QVariantMap &helpContent )
1419 mHelpContent = helpContent;
1422void QgsProcessingModelAlgorithm::setName(
const QString &name )
1427void QgsProcessingModelAlgorithm::setGroup(
const QString &group )
1429 mModelGroup = group;
1432bool QgsProcessingModelAlgorithm::validate( QStringList &issues )
const
1437 if ( mChildAlgorithms.empty() )
1440 issues << QObject::tr(
"Model does not contain any algorithms" );
1443 for (
auto it = mChildAlgorithms.constBegin(); it != mChildAlgorithms.constEnd(); ++it )
1445 QStringList childIssues;
1446 res = validateChildAlgorithm( it->childId(), childIssues ) && res;
1448 for (
const QString &issue : std::as_const( childIssues ) )
1450 issues << QStringLiteral(
"<b>%1</b>: %2" ).arg( it->description(), issue );
1456QMap<QString, QgsProcessingModelChildAlgorithm> QgsProcessingModelAlgorithm::childAlgorithms()
const
1458 return mChildAlgorithms;
1461void QgsProcessingModelAlgorithm::setParameterComponents(
const QMap<QString, QgsProcessingModelParameter> ¶meterComponents )
1463 mParameterComponents = parameterComponents;
1466void QgsProcessingModelAlgorithm::setParameterComponent(
const QgsProcessingModelParameter &component )
1468 mParameterComponents.insert( component.parameterName(), component );
1471QgsProcessingModelParameter &QgsProcessingModelAlgorithm::parameterComponent(
const QString &name )
1473 if ( !mParameterComponents.contains( name ) )
1475 QgsProcessingModelParameter &component = mParameterComponents[ name ];
1476 component.setParameterName( name );
1479 return mParameterComponents[ name ];
1482QList< QgsProcessingModelParameter > QgsProcessingModelAlgorithm::orderedParameters()
const
1484 QList< QgsProcessingModelParameter > res;
1485 QSet< QString > found;
1486 for (
const QString ¶meter : mParameterOrder )
1488 if ( mParameterComponents.contains( parameter ) )
1490 res << mParameterComponents.value( parameter );
1496 for (
auto it = mParameterComponents.constBegin(); it != mParameterComponents.constEnd(); ++it )
1498 if ( !found.contains( it.key() ) )
1506void QgsProcessingModelAlgorithm::setParameterOrder(
const QStringList &order )
1508 mParameterOrder = order;
1511QList<QgsProcessingModelOutput> QgsProcessingModelAlgorithm::orderedOutputs()
const
1513 QList< QgsProcessingModelOutput > res;
1514 QSet< QString > found;
1516 for (
const QString &output : mOutputOrder )
1518 bool foundOutput =
false;
1519 for (
auto it = mChildAlgorithms.constBegin(); it != mChildAlgorithms.constEnd(); ++it )
1521 const QMap<QString, QgsProcessingModelOutput> outputs = it.value().modelOutputs();
1522 for (
auto outputIt = outputs.constBegin(); outputIt != outputs.constEnd(); ++outputIt )
1524 if ( output == QStringLiteral(
"%1:%2" ).arg( outputIt->childId(), outputIt->childOutputName() ) )
1526 res << outputIt.value();
1528 found.insert( QStringLiteral(
"%1:%2" ).arg( outputIt->childId(), outputIt->childOutputName() ) );
1537 for (
auto it = mChildAlgorithms.constBegin(); it != mChildAlgorithms.constEnd(); ++it )
1539 const QMap<QString, QgsProcessingModelOutput> outputs = it.value().modelOutputs();
1540 for (
auto outputIt = outputs.constBegin(); outputIt != outputs.constEnd(); ++outputIt )
1542 if ( !found.contains( QStringLiteral(
"%1:%2" ).arg( outputIt->childId(), outputIt->childOutputName() ) ) )
1544 res << outputIt.value();
1552void QgsProcessingModelAlgorithm::setOutputOrder(
const QStringList &order )
1554 mOutputOrder = order;
1557QString QgsProcessingModelAlgorithm::outputGroup()
const
1559 return mOutputGroup;
1562void QgsProcessingModelAlgorithm::setOutputGroup(
const QString &group )
1564 mOutputGroup = group;
1567void QgsProcessingModelAlgorithm::updateDestinationParameters()
1570 QMutableListIterator<const QgsProcessingParameterDefinition *> it( mParameters );
1571 while ( it.hasNext() )
1581 qDeleteAll( mOutputs );
1585 QSet< QString > usedFriendlyNames;
1586 auto uniqueSafeName = [&usedFriendlyNames ](
const QString & name )->QString
1588 const QString base = safeName( name,
false );
1589 QString candidate = base;
1591 while ( usedFriendlyNames.contains( candidate ) )
1594 candidate = QStringLiteral(
"%1_%2" ).arg( base ).arg( i );
1596 usedFriendlyNames.insert( candidate );
1600 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
1601 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
1603 QMap<QString, QgsProcessingModelOutput> outputs = childIt->modelOutputs();
1604 QMap<QString, QgsProcessingModelOutput>::const_iterator outputIt = outputs.constBegin();
1605 for ( ; outputIt != outputs.constEnd(); ++outputIt )
1607 if ( !childIt->isActive() || !childIt->algorithm() )
1615 std::unique_ptr< QgsProcessingParameterDefinition > param( source->
clone() );
1619 if ( outputIt->isMandatory() )
1621 if ( mInternalVersion != InternalVersion::Version1 && !outputIt->description().isEmpty() )
1623 QString friendlyName = uniqueSafeName( outputIt->description() );
1624 param->setName( friendlyName );
1628 param->setName( outputIt->childId() +
':' + outputIt->name() );
1631 param->metadata().insert( QStringLiteral(
"_modelChildId" ), outputIt->childId() );
1632 param->metadata().insert( QStringLiteral(
"_modelChildOutputName" ), outputIt->name() );
1633 param->metadata().insert( QStringLiteral(
"_modelChildProvider" ), childIt->algorithm()->provider() ? childIt->algorithm()->provider()->id() : QString() );
1635 param->setDescription( outputIt->description() );
1636 param->setDefaultValue( outputIt->defaultValue() );
1639 if ( addParameter( param.release() ) && newDestParam )
1646 newDestParam->mOriginalProvider = provider;
1653void QgsProcessingModelAlgorithm::addGroupBox(
const QgsProcessingModelGroupBox &groupBox )
1655 mGroupBoxes.insert( groupBox.uuid(), groupBox );
1658QList<QgsProcessingModelGroupBox> QgsProcessingModelAlgorithm::groupBoxes()
const
1660 return mGroupBoxes.values();
1663void QgsProcessingModelAlgorithm::removeGroupBox(
const QString &uuid )
1665 mGroupBoxes.remove( uuid );
1668QVariant QgsProcessingModelAlgorithm::toVariant()
const
1671 map.insert( QStringLiteral(
"model_name" ), mModelName );
1672 map.insert( QStringLiteral(
"model_group" ), mModelGroup );
1673 map.insert( QStringLiteral(
"help" ), mHelpContent );
1674 map.insert( QStringLiteral(
"internal_version" ),
qgsEnumValueToKey( mInternalVersion ) );
1676 QVariantMap childMap;
1677 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
1678 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
1680 childMap.insert( childIt.key(), childIt.value().toVariant() );
1682 map.insert( QStringLiteral(
"children" ), childMap );
1684 QVariantMap paramMap;
1685 QMap< QString, QgsProcessingModelParameter >::const_iterator paramIt = mParameterComponents.constBegin();
1686 for ( ; paramIt != mParameterComponents.constEnd(); ++paramIt )
1688 paramMap.insert( paramIt.key(), paramIt.value().toVariant() );
1690 map.insert( QStringLiteral(
"parameters" ), paramMap );
1692 QVariantMap paramDefMap;
1697 map.insert( QStringLiteral(
"parameterDefinitions" ), paramDefMap );
1699 QVariantList groupBoxDefs;
1700 for (
auto it = mGroupBoxes.constBegin(); it != mGroupBoxes.constEnd(); ++it )
1702 groupBoxDefs.append( it.value().toVariant() );
1704 map.insert( QStringLiteral(
"groupBoxes" ), groupBoxDefs );
1706 map.insert( QStringLiteral(
"modelVariables" ), mVariables );
1708 map.insert( QStringLiteral(
"designerParameterValues" ), mDesignerParameterValues );
1710 map.insert( QStringLiteral(
"parameterOrder" ), mParameterOrder );
1711 map.insert( QStringLiteral(
"outputOrder" ), mOutputOrder );
1712 map.insert( QStringLiteral(
"outputGroup" ), mOutputGroup );
1717bool QgsProcessingModelAlgorithm::loadVariant(
const QVariant &model )
1719 QVariantMap map = model.toMap();
1721 mModelName = map.value( QStringLiteral(
"model_name" ) ).toString();
1722 mModelGroup = map.value( QStringLiteral(
"model_group" ) ).toString();
1723 mModelGroupId = map.value( QStringLiteral(
"model_group" ) ).toString();
1724 mHelpContent = map.value( QStringLiteral(
"help" ) ).toMap();
1726 mInternalVersion =
qgsEnumKeyToValue( map.value( QStringLiteral(
"internal_version" ) ).toString(), InternalVersion::Version1 );
1728 mVariables = map.value( QStringLiteral(
"modelVariables" ) ).toMap();
1729 mDesignerParameterValues = map.value( QStringLiteral(
"designerParameterValues" ) ).toMap();
1731 mParameterOrder = map.value( QStringLiteral(
"parameterOrder" ) ).toStringList();
1732 mOutputOrder = map.value( QStringLiteral(
"outputOrder" ) ).toStringList();
1733 mOutputGroup = map.value( QStringLiteral(
"outputGroup" ) ).toString();
1735 mChildAlgorithms.clear();
1736 QVariantMap childMap = map.value( QStringLiteral(
"children" ) ).toMap();
1737 QVariantMap::const_iterator childIt = childMap.constBegin();
1738 for ( ; childIt != childMap.constEnd(); ++childIt )
1740 QgsProcessingModelChildAlgorithm child;
1744 if ( !child.loadVariant( childIt.value() ) )
1747 mChildAlgorithms.insert( child.childId(), child );
1750 mParameterComponents.clear();
1751 QVariantMap paramMap = map.value( QStringLiteral(
"parameters" ) ).toMap();
1752 QVariantMap::const_iterator paramIt = paramMap.constBegin();
1753 for ( ; paramIt != paramMap.constEnd(); ++paramIt )
1755 QgsProcessingModelParameter param;
1756 if ( !param.loadVariant( paramIt.value().toMap() ) )
1759 mParameterComponents.insert( param.parameterName(), param );
1762 qDeleteAll( mParameters );
1763 mParameters.clear();
1764 QVariantMap paramDefMap = map.value( QStringLiteral(
"parameterDefinitions" ) ).toMap();
1766 auto addParam = [
this](
const QVariant & value )
1774 if ( param->name() == QLatin1String(
"VERBOSE_LOG" ) )
1778 param->setHelp( mHelpContent.value( param->name() ).toString() );
1781 addParameter( param.release() );
1785 QVariantMap map = value.toMap();
1786 QString type = map.value( QStringLiteral(
"parameter_type" ) ).toString();
1787 QString name = map.value( QStringLiteral(
"name" ) ).toString();
1789 QgsMessageLog::logMessage( QCoreApplication::translate(
"Processing",
"Could not load parameter %1 of type %2." ).arg( name, type ), QCoreApplication::translate(
"Processing",
"Processing" ) );
1793 QSet< QString > loadedParams;
1795 for (
const QString &name : std::as_const( mParameterOrder ) )
1797 if ( paramDefMap.contains( name ) )
1799 addParam( paramDefMap.value( name ) );
1800 loadedParams << name;
1804 QVariantMap::const_iterator paramDefIt = paramDefMap.constBegin();
1805 for ( ; paramDefIt != paramDefMap.constEnd(); ++paramDefIt )
1807 if ( !loadedParams.contains( paramDefIt.key() ) )
1808 addParam( paramDefIt.value() );
1811 mGroupBoxes.clear();
1812 const QVariantList groupBoxList = map.value( QStringLiteral(
"groupBoxes" ) ).toList();
1813 for (
const QVariant &groupBoxDef : groupBoxList )
1815 QgsProcessingModelGroupBox groupBox;
1816 groupBox.loadVariant( groupBoxDef.toMap() );
1817 mGroupBoxes.insert( groupBox.uuid(), groupBox );
1820 updateDestinationParameters();
1825bool QgsProcessingModelAlgorithm::vectorOutputIsCompatibleType(
const QList<int> &acceptableDataTypes,
Qgis::ProcessingSourceType outputType )
1830 return ( acceptableDataTypes.empty()
1831 || acceptableDataTypes.contains(
static_cast< int >( outputType ) )
1842void QgsProcessingModelAlgorithm::reattachAlgorithms()
const
1844 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
1845 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
1847 if ( !childIt->algorithm() )
1848 childIt->reattach();
1852bool QgsProcessingModelAlgorithm::toFile(
const QString &path )
const
1854 QDomDocument doc = QDomDocument( QStringLiteral(
"model" ) );
1856 doc.appendChild( elem );
1859 if ( file.open( QFile::WriteOnly | QFile::Truncate ) )
1861 QTextStream stream( &file );
1862 doc.save( stream, 2 );
1869bool QgsProcessingModelAlgorithm::fromFile(
const QString &path )
1874 if ( file.open( QFile::ReadOnly ) )
1876 if ( !doc.setContent( &file ) )
1887 return loadVariant( props );
1890void QgsProcessingModelAlgorithm::setChildAlgorithms(
const QMap<QString, QgsProcessingModelChildAlgorithm> &childAlgorithms )
1892 mChildAlgorithms = childAlgorithms;
1893 updateDestinationParameters();
1896void QgsProcessingModelAlgorithm::setChildAlgorithm(
const QgsProcessingModelChildAlgorithm &
algorithm )
1899 updateDestinationParameters();
1902QString QgsProcessingModelAlgorithm::addChildAlgorithm( QgsProcessingModelChildAlgorithm &
algorithm )
1904 if (
algorithm.childId().isEmpty() || mChildAlgorithms.contains(
algorithm.childId() ) )
1908 updateDestinationParameters();
1912QgsProcessingModelChildAlgorithm &QgsProcessingModelAlgorithm::childAlgorithm(
const QString &childId )
1914 return mChildAlgorithms[ childId ];
1917bool QgsProcessingModelAlgorithm::removeChildAlgorithm(
const QString &
id )
1919 if ( !dependentChildAlgorithms(
id ).isEmpty() )
1922 mChildAlgorithms.remove(
id );
1923 updateDestinationParameters();
1927void QgsProcessingModelAlgorithm::deactivateChildAlgorithm(
const QString &
id )
1929 const auto constDependentChildAlgorithms = dependentChildAlgorithms(
id );
1930 for (
const QString &child : constDependentChildAlgorithms )
1932 childAlgorithm( child ).setActive(
false );
1934 childAlgorithm(
id ).setActive(
false );
1935 updateDestinationParameters();
1938bool QgsProcessingModelAlgorithm::activateChildAlgorithm(
const QString &
id )
1940 const auto constDependsOnChildAlgorithms = dependsOnChildAlgorithms(
id );
1941 for (
const QString &child : constDependsOnChildAlgorithms )
1943 if ( !childAlgorithm( child ).isActive() )
1946 childAlgorithm(
id ).setActive(
true );
1947 updateDestinationParameters();
1953 if ( addParameter( definition ) )
1954 mParameterComponents.insert( definition->
name(), component );
1959 removeParameter( definition->
name() );
1960 addParameter( definition );
1963void QgsProcessingModelAlgorithm::removeModelParameter(
const QString &name )
1965 removeParameter( name );
1966 mParameterComponents.remove( name );
1969void QgsProcessingModelAlgorithm::changeParameterName(
const QString &oldName,
const QString &newName )
1974 auto replaceExpressionVariable = [oldName, newName, &expressionContext](
const QString & expressionString ) -> std::tuple< bool, QString >
1977 expression.prepare( &expressionContext );
1978 QSet<QString> variables = expression.referencedVariables();
1979 if ( variables.contains( oldName ) )
1981 QString newExpression = expressionString;
1982 newExpression.replace( QStringLiteral(
"@%1" ).arg( oldName ), QStringLiteral(
"@%2" ).arg( newName ) );
1983 return {
true, newExpression };
1985 return {
false, QString() };
1988 QMap< QString, QgsProcessingModelChildAlgorithm >::iterator childIt = mChildAlgorithms.begin();
1989 for ( ; childIt != mChildAlgorithms.end(); ++childIt )
1991 bool changed =
false;
1992 QMap<QString, QgsProcessingModelChildParameterSources> childParams = childIt->parameterSources();
1993 QMap<QString, QgsProcessingModelChildParameterSources>::iterator paramIt = childParams.begin();
1994 for ( ; paramIt != childParams.end(); ++paramIt )
1996 QList< QgsProcessingModelChildParameterSource > &value = paramIt.value();
1997 for (
auto valueIt = value.begin(); valueIt != value.end(); ++valueIt )
1999 switch ( valueIt->source() )
2003 if ( valueIt->parameterName() == oldName )
2005 valueIt->setParameterName( newName );
2013 bool updatedExpression =
false;
2014 QString newExpression;
2015 std::tie( updatedExpression, newExpression ) = replaceExpressionVariable( valueIt->expression() );
2016 if ( updatedExpression )
2018 valueIt->setExpression( newExpression );
2026 if ( valueIt->staticValue().userType() == qMetaTypeId<QgsProperty>() )
2031 bool updatedExpression =
false;
2032 QString newExpression;
2033 std::tie( updatedExpression, newExpression ) = replaceExpressionVariable( property.expressionString() );
2034 if ( updatedExpression )
2036 property.setExpressionString( newExpression );
2037 valueIt->setStaticValue( property );
2053 childIt->setParameterSources( childParams );
2057bool QgsProcessingModelAlgorithm::childAlgorithmsDependOnParameter(
const QString &name )
const
2059 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
2060 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
2063 QMap<QString, QgsProcessingModelChildParameterSources> childParams = childIt->parameterSources();
2064 QMap<QString, QgsProcessingModelChildParameterSources>::const_iterator paramIt = childParams.constBegin();
2065 for ( ; paramIt != childParams.constEnd(); ++paramIt )
2067 const auto constValue = paramIt.value();
2068 for (
const QgsProcessingModelChildParameterSource &source : constValue )
2071 && source.parameterName() == name )
2081bool QgsProcessingModelAlgorithm::otherParametersDependOnParameter(
const QString &name )
const
2083 const auto constMParameters = mParameters;
2086 if ( def->
name() == name )
2095QMap<QString, QgsProcessingModelParameter> QgsProcessingModelAlgorithm::parameterComponents()
const
2097 return mParameterComponents;
2100void QgsProcessingModelAlgorithm::dependentChildAlgorithmsRecursive(
const QString &childId, QSet<QString> &depends,
const QString &branch )
const
2102 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
2103 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
2105 if ( depends.contains( childIt->childId() ) )
2109 const QList< QgsProcessingModelChildDependency > constDependencies = childIt->dependencies();
2110 bool hasDependency =
false;
2111 for (
const QgsProcessingModelChildDependency &dep : constDependencies )
2113 if ( dep.childId == childId && ( branch.isEmpty() || dep.conditionalBranch == branch ) )
2115 hasDependency =
true;
2120 if ( hasDependency )
2122 depends.insert( childIt->childId() );
2123 dependentChildAlgorithmsRecursive( childIt->childId(), depends, branch );
2128 QMap<QString, QgsProcessingModelChildParameterSources> childParams = childIt->parameterSources();
2129 QMap<QString, QgsProcessingModelChildParameterSources>::const_iterator paramIt = childParams.constBegin();
2130 for ( ; paramIt != childParams.constEnd(); ++paramIt )
2132 const auto constValue = paramIt.value();
2133 for (
const QgsProcessingModelChildParameterSource &source : constValue )
2136 && source.outputChildId() == childId )
2138 depends.insert( childIt->childId() );
2139 dependentChildAlgorithmsRecursive( childIt->childId(), depends, branch );
2147QSet<QString> QgsProcessingModelAlgorithm::dependentChildAlgorithms(
const QString &childId,
const QString &conditionalBranch )
const
2149 QSet< QString > algs;
2153 algs.insert( childId );
2155 dependentChildAlgorithmsRecursive( childId, algs, conditionalBranch );
2158 algs.remove( childId );
2164void QgsProcessingModelAlgorithm::dependsOnChildAlgorithmsRecursive(
const QString &childId, QSet< QString > &depends )
const
2166 const QgsProcessingModelChildAlgorithm &alg = mChildAlgorithms.value( childId );
2169 const QList< QgsProcessingModelChildDependency > constDependencies = alg.dependencies();
2170 for (
const QgsProcessingModelChildDependency &val : constDependencies )
2172 if ( !depends.contains( val.childId ) )
2174 depends.insert( val.childId );
2175 dependsOnChildAlgorithmsRecursive( val.childId, depends );
2180 QMap<QString, QgsProcessingModelChildParameterSources> childParams = alg.parameterSources();
2181 QMap<QString, QgsProcessingModelChildParameterSources>::const_iterator paramIt = childParams.constBegin();
2182 for ( ; paramIt != childParams.constEnd(); ++paramIt )
2184 const auto constValue = paramIt.value();
2185 for (
const QgsProcessingModelChildParameterSource &source : constValue )
2187 switch ( source.source() )
2190 if ( !depends.contains( source.outputChildId() ) )
2192 depends.insert( source.outputChildId() );
2193 dependsOnChildAlgorithmsRecursive( source.outputChildId(), depends );
2200 const QSet<QString> vars = exp.referencedVariables();
2205 const QMap<QString, QgsProcessingModelAlgorithm::VariableDefinition> availableVariables = variablesForChildAlgorithm( childId );
2206 for (
auto childVarIt = availableVariables.constBegin(); childVarIt != availableVariables.constEnd(); ++childVarIt )
2212 if ( !vars.contains( childVarIt.key() ) || depends.contains( childVarIt->source.outputChildId() ) )
2216 depends.insert( childVarIt->source.outputChildId() );
2217 dependsOnChildAlgorithmsRecursive( childVarIt->source.outputChildId(), depends );
2232QSet< QString > QgsProcessingModelAlgorithm::dependsOnChildAlgorithms(
const QString &childId )
const
2234 QSet< QString > algs;
2238 algs.insert( childId );
2240 dependsOnChildAlgorithmsRecursive( childId, algs );
2243 algs.remove( childId );
2248QList<QgsProcessingModelChildDependency> QgsProcessingModelAlgorithm::availableDependenciesForChildAlgorithm(
const QString &childId )
const
2250 QSet< QString > dependent;
2251 if ( !childId.isEmpty() )
2253 dependent.unite( dependentChildAlgorithms( childId ) );
2254 dependent.insert( childId );
2257 QList<QgsProcessingModelChildDependency> res;
2258 for (
auto it = mChildAlgorithms.constBegin(); it != mChildAlgorithms.constEnd(); ++it )
2260 if ( !dependent.contains( it->childId() ) )
2263 bool hasBranches =
false;
2264 if ( it->algorithm() )
2272 QgsProcessingModelChildDependency alg;
2273 alg.childId = it->childId();
2274 alg.conditionalBranch = def->
name();
2282 QgsProcessingModelChildDependency alg;
2283 alg.childId = it->childId();
2291bool QgsProcessingModelAlgorithm::validateChildAlgorithm(
const QString &childId, QStringList &issues )
const
2294 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constFind( childId );
2295 if ( childIt != mChildAlgorithms.constEnd() )
2297 if ( !childIt->algorithm() )
2299 issues << QObject::tr(
"Algorithm is not available: <i>%1</i>" ).arg( childIt->algorithmId() );
2308 if ( childIt->parameterSources().contains( def->
name() ) )
2311 const QList< QgsProcessingModelChildParameterSource > sources = childIt->parameterSources().value( def->
name() );
2312 for (
const QgsProcessingModelChildParameterSource &source : sources )
2314 switch ( source.source() )
2320 issues << QObject::tr(
"Value for <i>%1</i> is not acceptable for this parameter" ).arg( def->
name() );
2325 if ( !parameterComponents().contains( source.parameterName() ) )
2328 issues << QObject::tr(
"Model input <i>%1</i> used for parameter <i>%2</i> does not exist" ).arg( source.parameterName(), def->
name() );
2333 if ( !childAlgorithms().contains( source.outputChildId() ) )
2336 issues << QObject::tr(
"Child algorithm <i>%1</i> used for parameter <i>%2</i> does not exist" ).arg( source.outputChildId(), def->
name() );
2358 issues << QObject::tr(
"Parameter <i>%1</i> is mandatory" ).arg( def->
name() );
2367 issues << QObject::tr(
"Invalid child ID: <i>%1</i>" ).arg( childId );
2372bool QgsProcessingModelAlgorithm::canExecute( QString *errorMessage )
const
2374 reattachAlgorithms();
2375 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
2376 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
2378 if ( !childIt->algorithm() )
2382 *errorMessage = QObject::tr(
"The model you are trying to run contains an algorithm that is not available: <i>%1</i>" ).arg( childIt->algorithmId() );
2390QString QgsProcessingModelAlgorithm::asPythonCommand(
const QVariantMap ¶meters,
QgsProcessingContext &context )
const
2392 if ( mSourceFile.isEmpty() )
2407 QgsProcessingModelAlgorithm *alg =
new QgsProcessingModelAlgorithm();
2408 alg->loadVariant( toVariant() );
2409 alg->setProvider( provider() );
2410 alg->setSourceFilePath( sourceFilePath() );
2414QString QgsProcessingModelAlgorithm::safeName(
const QString &name,
bool capitalize )
2416 QString n = name.toLower().trimmed();
2417 const thread_local QRegularExpression rx( QStringLiteral(
"[^\\sa-z_A-Z0-9]" ) );
2418 n.replace( rx, QString() );
2419 const thread_local QRegularExpression rx2( QStringLiteral(
"^\\d*" ) );
2420 n.replace( rx2, QString() );
2422 n = n.replace(
' ',
'_' );
2426QVariantMap QgsProcessingModelAlgorithm::variables()
const
2431void QgsProcessingModelAlgorithm::setVariables(
const QVariantMap &variables )
2433 mVariables = variables;
2436QVariantMap QgsProcessingModelAlgorithm::designerParameterValues()
const
2438 return mDesignerParameterValues;
ProcessingSourceType
Processing data source types.
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
@ MapLayer
Any map layer type (raster, vector, mesh, point cloud, annotation or plugin layer)
@ VectorAnyGeometry
Any vector layer with geometry.
@ VectorPoint
Vector point layers.
@ VectorPolygon
Vector polygon layers.
@ VectorLine
Vector line layers.
@ Success
Child was successfully executed.
@ Failed
Child encountered an error while executing.
@ Expression
Expression based property.
@ UpperCamelCase
Convert the string to upper camel case. Note that this method does not unaccent characters.
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
static int versionInt()
Version number used for comparing versions using the "Check QGIS Version" function.
@ ExpressionText
Parameter value is taken from a text with expressions, evaluated just before the algorithm runs.
@ ModelOutput
Parameter value is linked to an output parameter for the model.
@ ChildOutput
Parameter value is taken from an output generated by a child algorithm.
@ ModelParameter
Parameter value is taken from a parent model parameter.
@ StaticValue
Parameter value is a static value.
@ Expression
Parameter value is taken from an expression, evaluated just before the algorithm runs.
@ SkipGenericModelLogging
When running as part of a model, the generic algorithm setup and results logging should be skipped.
@ CustomException
Algorithm raises custom exception notices, don't use the standard ones.
@ NoThreading
Algorithm is not thread safe and cannot be run in a background thread, e.g. for algorithms which mani...
@ PruneModelBranchesBasedOnAlgorithmResults
Algorithm results will cause remaining model branches to be pruned based on the results of running th...
@ SecurityRisk
The algorithm represents a potential security risk if executed with untrusted inputs.
@ Hidden
Parameter is hidden and should not be shown to users.
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
@ Optional
Parameter is optional.
@ DefaultLevel
Default logging level.
@ Verbose
Verbose logging.
@ ModelDebug
Model debug level logging. Includes verbose logging and other outputs useful for debugging models.
static QgsProcessingRegistry * processingRegistry()
Returns the application's processing registry, used for managing processing providers,...
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
static QString iconPath(const QString &iconFile)
Returns path to the desired icon file.
Single scope for storing variables and functions for use within a QgsExpressionContext.
static QgsExpressionContextScope * processingModelAlgorithmScope(const QgsProcessingModelAlgorithm *model, const QVariantMap ¶meters, QgsProcessingContext &context)
Creates a new scope which contains variables and functions relating to a processing model algorithm,...
static QgsExpressionContextScope * processingAlgorithmScope(const QgsProcessingAlgorithm *algorithm, const QVariantMap ¶meters, QgsProcessingContext &context)
Creates a new scope which contains variables and functions relating to a processing algorithm,...
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
Class for parsing and evaluation of expressions (formerly called "search strings").
static QString replaceExpressionText(const QString &action, const QgsExpressionContext *context, const QgsDistanceArea *distanceArea=nullptr)
This function replaces each expression between [% and %] in the string with the result of its evaluat...
An interface for objects which provide features via a getFeatures method.
virtual QgsRectangle sourceExtent() const
Returns the extent of all geometries from the source.
bool isCanceled() const
Tells whether the operation has been canceled already.
Base class for all map layer types.
virtual QgsRectangle extent() const
Returns the extent of the layer.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
Abstract base class for processing algorithms.
QgsProcessingOutputDefinitions outputDefinitions() const
Returns an ordered list of output definitions utilized by the algorithm.
virtual Qgis::ProcessingAlgorithmFlags flags() const
Returns the flags indicating how and when the algorithm operates and should be exposed to users.
virtual QgsExpressionContext createExpressionContext(const QVariantMap ¶meters, QgsProcessingContext &context, QgsProcessingFeatureSource *source=nullptr) const
Creates an expression context relating to the algorithm.
const QgsProcessingParameterDefinition * parameterDefinition(const QString &name) const
Returns a matching parameter by name.
virtual QString asPythonCommand(const QVariantMap ¶meters, QgsProcessingContext &context) const
Returns a Python command string which can be executed to run the algorithm using the specified parame...
QgsProcessingProvider * provider() const
Returns the provider to which this algorithm belongs.
Details for layers to load into projects.
int layerSortKey
Optional sorting key for sorting output layers when loading them into a project.
QString groupName
Optional name for a layer tree group under which to place the layer when loading it into a project.
Contains information about the context in which a processing algorithm is executed.
QgsExpressionContext & expressionContext()
Returns the expression context.
void setExpressionContext(const QgsExpressionContext &context)
Sets the expression context.
QgsProcessingModelResult modelResult() const
Returns the model results, populated when the context is used to run a model algorithm.
QgsProcessingModelInitialRunConfig * modelInitialRunConfig()
Returns a reference to the model initial run configuration, used to run a model algorithm.
Qgis::ProcessingLogLevel logLevel() const
Returns the logging level for algorithms to use when pushing feedback messages to users.
void setModelInitialRunConfig(std::unique_ptr< QgsProcessingModelInitialRunConfig > config)
Sets the model initial run configuration, used to run a model algorithm.
Base class for all parameter definitions which represent file or layer destinations,...
virtual QString generateTemporaryDestination(const QgsProcessingContext *context=nullptr) const
Generates a temporary destination value for this parameter.
void setSupportsNonFileBasedOutput(bool supportsNonFileBasedOutput)
Sets whether the destination parameter supports non filed-based outputs, such as memory layers or dir...
Custom exception class for processing related exceptions.
Encapsulates settings relating to a feature source input to a processing algorithm.
QgsProperty source
Source definition.
QgsFeatureSource subclass which proxies methods to an underlying QgsFeatureSource,...
Base class for providing feedback from a processing algorithm.
virtual void pushCommandInfo(const QString &info)
Pushes an informational message containing a command from the algorithm.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
virtual void pushWarning(const QString &warning)
Pushes a warning informational message from the algorithm.
virtual QString htmlLog() const
Returns the HTML formatted contents of the log, which contains all messages pushed to the feedback ob...
virtual void pushDebugInfo(const QString &info)
Pushes an informational message containing debugging helpers from the algorithm.
virtual void setProgressText(const QString &text)
Sets a progress report text string.
Encapsulates the results of running a child algorithm within a model.
void setOutputs(const QVariantMap &outputs)
Sets the outputs generated by child algorithm.
void setExecutionStatus(Qgis::ProcessingModelChildAlgorithmExecutionStatus status)
Sets the status of executing the child algorithm.
void setInputs(const QVariantMap &inputs)
Sets the inputs used for the child algorithm.
void setHtmlLog(const QString &log)
Sets the HTML formatted contents of logged messages which occurred while running the child.
Configuration settings which control how a Processing model is executed.
QSet< QString > childAlgorithmSubset() const
Returns the subset of child algorithms to run (by child ID).
QVariantMap & rawChildOutputs()
Returns a reference to the map of raw child algorithm outputs.
QVariantMap & rawChildInputs()
Returns a reference to the map of raw child algorithm inputs.
QSet< QString > & executedChildIds()
Returns a reference to the set of child algorithm IDs which were executed during the model execution.
Processing feedback object for multi-step operations.
static QString typeName()
Returns the type name for the output class.
static QString typeName()
Returns the type name for the output class.
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.
QString destinationName
Name to use for sink if it's to be loaded into a destination project.
static QString typeName()
Returns the type name for the output class.
static QString typeName()
Returns the type name for the output class.
static QString typeName()
Returns the type name for the output class.
static QString typeName()
Returns the type name for the output class.
static QString typeName()
Returns the type name for the output class.
A vector layer output for processing algorithms.
Qgis::ProcessingSourceType dataType() const
Returns the layer type for the output layer.
static QString typeName()
Returns the type name for the output class.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
Base class for the definition of processing parameters.
QgsProcessingAlgorithm * algorithm() const
Returns a pointer to the algorithm which owns this parameter.
QVariantMap metadata() const
Returns the parameter's freeform metadata.
virtual bool isDestination() const
Returns true if this parameter represents a file or layer destination, e.g.
virtual QgsProcessingParameterDefinition * clone() const =0
Creates a clone of the parameter definition.
virtual QString type() const =0
Unique parameter type name.
virtual QVariantMap toVariantMap() const
Saves this parameter to a QVariantMap.
QString name() const
Returns the name of the parameter.
virtual QStringList dependsOnOtherParameters() const
Returns a list of other parameter names on which this parameter is dependent (e.g.
Qgis::ProcessingParameterFlags flags() const
Returns any flags associated with the parameter.
virtual bool checkValueIsAcceptable(const QVariant &input, QgsProcessingContext *context=nullptr) const
Checks whether the specified input value is acceptable for the parameter.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
A vector layer or feature source field parameter for processing algorithms.
Qgis::ProcessingFieldParameterDataType dataType() const
Returns the acceptable data type for the field.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
Can be inherited by parameters which require limits to their acceptable data types.
QList< int > dataTypes() const
Returns the geometry types for sources acceptable by the parameter.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
virtual QString pythonImportString() const
Returns a valid Python import string for importing the corresponding parameter type,...
static QString typeName()
Returns the type name for the parameter class.
static QString typeName()
Returns the type name for the parameter class.
static QgsProcessingParameterDefinition * parameterFromVariantMap(const QVariantMap &map)
Creates a new QgsProcessingParameterDefinition using the configuration from a supplied variant map.
Abstract base class for processing providers.
const QgsProcessingAlgorithm * algorithm(const QString &name) const
Returns the matching algorithm by name, or nullptr if no matching algorithm is contained by this prov...
QgsProcessingParameterType * parameterType(const QString &id) const
Returns the parameter type registered for id.
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.
@ Vector
Vector layer type.
static QString variantToPythonLiteral(const QVariant &value)
Converts a variant to a Python literal.
static QVariantMap removePointerValuesFromMap(const QVariantMap &map)
Removes any raw pointer values from an input map, replacing them with appropriate string values where...
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.
PythonOutputType
Available Python output types.
@ PythonQgsProcessingAlgorithmSubclass
Full Python QgsProcessingAlgorithm subclass.
A store for object properties.
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...
QVariant staticValue() const
Returns the current static value for the property.
static QString capitalize(const QString &string, Qgis::Capitalization capitalization)
Converts a string by applying capitalization rules to the string.
Represents a vector layer which manages a vector based data sets.
static QDomElement writeVariant(const QVariant &value, QDomDocument &doc)
Write a QVariant to a QDomElement.
static QVariant readVariant(const QDomElement &element)
Read a QVariant from a QDomElement.
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
T qgsEnumKeyToValue(const QString &key, const T &defaultValue, bool tryValueAsKey=true, bool *returnOk=nullptr)
Returns the value corresponding to the given key of an enum.
QString qgsEnumValueToKey(const T &value, bool *returnOk=nullptr)
Returns the value for the given key of an enum.
QString qgsSetJoin(const QSet< T > &set, const QString &separator)
Joins all the set values into a single string with each element separated by the given separator.
QMap< QString, QString > QgsStringMap
QPointer< QgsMapLayer > QgsWeakMapLayerPointer
Weak pointer for QgsMapLayer.
QList< const QgsProcessingOutputDefinition * > QgsProcessingOutputDefinitions
List of processing parameters.
QList< const QgsProcessingParameterDefinition * > QgsProcessingParameterDefinitions
List of processing parameters.
Single variable definition for use within a QgsExpressionContextScope.