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;
346 QMap< QString, QgsProcessingModelChildAlgorithmResult > &contextChildResults = context.
modelResult().
childResults();
352 childInputs = config->initialChildInputs();
353 childResults = config->initialChildOutputs();
354 executed = config->previouslyExecutedChildAlgorithms();
358 if ( useSubsetOfChildren )
360 executed.subtract( childSubset );
363 QVariantMap finalResults;
365 bool executedAlg =
true;
366 int previousHtmlLogLength = feedback->
htmlLog().length();
367 int countExecuted = 0;
368 while ( executedAlg && countExecuted < toExecute.count() )
371 for (
const QString &childId : std::as_const( toExecute ) )
376 if ( executed.contains( childId ) )
381 bool canExecute =
true;
382 const QSet< QString > dependencies = dependsOnChildAlgorithms( childId );
383 for (
const QString &dependency : dependencies )
385 if ( !executed.contains( dependency ) )
399 const QgsProcessingModelChildAlgorithm &child = mChildAlgorithms[ childId ];
400 std::unique_ptr< QgsProcessingAlgorithm > childAlg( child.algorithm()->create( child.configuration() ) );
402 bool skipGenericLogging =
true;
407 skipGenericLogging =
true;
417 skipGenericLogging =
false;
421 if ( feedback && !skipGenericLogging )
422 feedback->
pushDebugInfo( QObject::tr(
"Prepare algorithm: %1" ).arg( childId ) );
426 << createExpressionContextScopeForChildAlgorithm( childId, context, parameters, childResults );
430 QVariantMap childParams = parametersForChildAlgorithm( child, parameters, childResults, expContext, error, &context );
431 if ( !error.isEmpty() )
434 if ( feedback && !skipGenericLogging )
435 feedback->
setProgressText( QObject::tr(
"Running %1 [%2/%3]" ).arg( child.description() ).arg( executed.count() + 1 ).arg( toExecute.count() ) );
440 childInputs.insert( childId, thisChildParams );
441 childResult.
setInputs( thisChildParams );
444 for (
auto childParamIt = childParams.constBegin(); childParamIt != childParams.constEnd(); ++childParamIt )
446 params << QStringLiteral(
"%1: %2" ).arg( childParamIt.key(),
447 child.algorithm()->parameterDefinition( childParamIt.key() )->valueAsPythonString( childParamIt.value(), context ) );
450 if ( feedback && !skipGenericLogging )
452 feedback->
pushInfo( QObject::tr(
"Input Parameters:" ) );
453 feedback->
pushCommandInfo( QStringLiteral(
"{ %1 }" ).arg( params.join( QLatin1String(
", " ) ) ) );
456 QElapsedTimer childTime;
459 QVariantMap outerScopeChildInputs = childInputs;
460 QVariantMap outerScopePrevChildResults = childResults;
461 QSet< QString > outerScopeExecuted = executed;
462 QMap< QString, QgsProcessingModelChildAlgorithmResult > outerScopeContextChildResult = contextChildResults;
463 if (
dynamic_cast< QgsProcessingModelAlgorithm *
>( childAlg.get() ) )
467 childResults.clear();
469 contextChildResults.clear();
474 QThread *modelThread = QThread::currentThread();
476 auto prepareOnMainThread = [modelThread, &ok, &childAlg, &childParams, &context, &modelFeedback]
478 Q_ASSERT_X( QThread::currentThread() == qApp->thread(),
"QgsProcessingModelAlgorithm::processAlgorithm",
"childAlg->prepare() must be run on the main thread" );
479 ok = childAlg->prepare( childParams, context, &modelFeedback );
480 context.pushToThread( modelThread );
484 if ( modelThread == qApp->thread() )
485 ok = childAlg->prepare( childParams, context, &modelFeedback );
488 context.pushToThread( qApp->thread() );
490#ifndef __clang_analyzer__
491 QMetaObject::invokeMethod( qApp, prepareOnMainThread, Qt::BlockingQueuedConnection );
495 Q_ASSERT_X( QThread::currentThread() == context.thread(),
"QgsProcessingModelAlgorithm::processAlgorithm",
"context was not transferred back to model thread" );
505 bool runResult =
false;
511 auto runOnMainThread = [modelThread, &context, &modelFeedback, &results, &childAlg, &childParams]
513 Q_ASSERT_X( QThread::currentThread() == qApp->thread(),
"QgsProcessingModelAlgorithm::processAlgorithm",
"childAlg->runPrepared() must be run on the main thread" );
514 results = childAlg->runPrepared( childParams, context, &modelFeedback );
515 context.pushToThread( modelThread );
518 if ( feedback && !skipGenericLogging && modelThread != qApp->thread() )
519 feedback->
pushWarning( QObject::tr(
"Algorithm “%1” cannot be run in a background thread, switching to main thread for this step" ).arg( childAlg->displayName() ) );
521 context.pushToThread( qApp->thread() );
523#ifndef __clang_analyzer__
524 QMetaObject::invokeMethod( qApp, runOnMainThread, Qt::BlockingQueuedConnection );
530 results = childAlg->runPrepared( childParams, context, &modelFeedback );
541 Q_ASSERT_X( QThread::currentThread() == context.thread(),
"QgsProcessingModelAlgorithm::processAlgorithm",
"context was not transferred back to model thread" );
544 auto postProcessOnMainThread = [modelThread, &ppRes, &childAlg, &context, &modelFeedback, runResult]
546 Q_ASSERT_X( QThread::currentThread() == qApp->thread(),
"QgsProcessingModelAlgorithm::processAlgorithm",
"childAlg->postProcess() must be run on the main thread" );
547 ppRes = childAlg->postProcess( context, &modelFeedback, runResult );
548 context.pushToThread( modelThread );
552 if ( modelThread == qApp->thread() )
553 ppRes = childAlg->postProcess( context, &modelFeedback, runResult );
556 context.pushToThread( qApp->thread() );
558#ifndef __clang_analyzer__
559 QMetaObject::invokeMethod( qApp, postProcessOnMainThread, Qt::BlockingQueuedConnection );
563 Q_ASSERT_X( QThread::currentThread() == context.thread(),
"QgsProcessingModelAlgorithm::processAlgorithm",
"context was not transferred back to model thread" );
565 if ( !ppRes.isEmpty() )
568 if (
dynamic_cast< QgsProcessingModelAlgorithm *
>( childAlg.get() ) )
570 childInputs = outerScopeChildInputs;
571 childResults = outerScopePrevChildResults;
572 executed = outerScopeExecuted;
573 contextChildResults = outerScopeContextChildResult;
576 childResults.insert( childId, results );
581 if ( feedback && !skipGenericLogging )
584 QStringList formattedOutputs;
585 for (
auto displayOutputIt = displayOutputs.constBegin(); displayOutputIt != displayOutputs.constEnd(); ++displayOutputIt )
587 formattedOutputs << QStringLiteral(
"%1: %2" ).arg( displayOutputIt.key(),
590 feedback->
pushInfo( QObject::tr(
"Results:" ) );
591 feedback->
pushCommandInfo( QStringLiteral(
"{ %1 }" ).arg( formattedOutputs.join( QLatin1String(
", " ) ) ) );
596 const QMap<QString, QgsProcessingModelOutput> outputs = child.modelOutputs();
597 for (
auto outputIt = outputs.constBegin(); outputIt != outputs.constEnd(); ++outputIt )
599 const int outputSortKey = mOutputOrder.indexOf( QStringLiteral(
"%1:%2" ).arg( childId, outputIt->childOutputName() ) );
600 switch ( mInternalVersion )
602 case QgsProcessingModelAlgorithm::InternalVersion::Version1:
603 finalResults.insert( childId +
':' + outputIt->name(), results.value( outputIt->childOutputName() ) );
605 case QgsProcessingModelAlgorithm::InternalVersion::Version2:
608 finalResults.insert( modelParam->name(), results.value( outputIt->childOutputName() ) );
613 const QString outputLayer = results.value( outputIt->childOutputName() ).toString();
614 if ( !outputLayer.isEmpty() && context.willLoadLayerOnCompletion( outputLayer ) )
618 if ( outputSortKey > 0 )
623 executed.insert( childId );
625 std::function< void(
const QString &,
const QString & )> pruneAlgorithmBranchRecursive;
626 pruneAlgorithmBranchRecursive = [&](
const QString & id,
const QString &branch = QString() )
628 const QSet<QString> toPrune = dependentChildAlgorithms(
id, branch );
629 for (
const QString &targetId : toPrune )
631 if ( executed.contains( targetId ) )
634 executed.insert( targetId );
635 pruneAlgorithmBranchRecursive( targetId, branch );
645 pruneAlgorithmBranchRecursive( childId, outputDef->name() );
653 for (
const QString &candidateId : std::as_const( toExecute ) )
655 if ( executed.contains( candidateId ) )
660 const QgsProcessingModelChildAlgorithm &candidate = mChildAlgorithms[ candidateId ];
661 const QMap<QString, QgsProcessingModelChildParameterSources> candidateParams = candidate.parameterSources();
662 QMap<QString, QgsProcessingModelChildParameterSources>::const_iterator paramIt = candidateParams.constBegin();
664 for ( ; paramIt != candidateParams.constEnd(); ++paramIt )
666 for (
const QgsProcessingModelChildParameterSource &source : paramIt.value() )
671 if ( !results.contains( source.outputName() ) )
676 executed.insert( candidateId );
678 pruneAlgorithmBranchRecursive( candidateId, QString() );
689 childAlg.reset(
nullptr );
691 modelFeedback.setCurrentStep( countExecuted );
692 if ( feedback && !skipGenericLogging )
694 feedback->
pushInfo( QObject::tr(
"OK. Execution took %1 s (%n output(s)).",
nullptr, results.count() ).arg( childTime.elapsed() / 1000.0 ) );
699 const QString thisAlgorithmHtmlLog = feedback->
htmlLog().mid( previousHtmlLogLength );
700 previousHtmlLogLength = feedback->
htmlLog().length();
704 const QString formattedException = QStringLiteral(
"<span style=\"color:red\">%1</span><br/>" ).arg( error.toHtmlEscaped() ).replace(
'\n', QLatin1String(
"<br>" ) );
705 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>" ) );
707 childResult.
setHtmlLog( thisAlgorithmHtmlLog + formattedException + formattedRunTime );
708 context.modelResult().childResults().insert( childId, childResult );
714 childResult.
setHtmlLog( thisAlgorithmHtmlLog );
715 context.modelResult().childResults().insert( childId, childResult );
723 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 ) );
725 mResults = finalResults;
726 mResults.insert( QStringLiteral(
"CHILD_RESULTS" ), childResults );
727 mResults.insert( QStringLiteral(
"CHILD_INPUTS" ), childInputs );
731QString QgsProcessingModelAlgorithm::sourceFilePath()
const
736void QgsProcessingModelAlgorithm::setSourceFilePath(
const QString &sourceFile )
738 mSourceFile = sourceFile;
741bool QgsProcessingModelAlgorithm::modelNameMatchesFilePath()
const
743 if ( mSourceFile.isEmpty() )
746 const QFileInfo fi( mSourceFile );
747 return fi.completeBaseName().compare( mModelName, Qt::CaseInsensitive ) == 0;
752 QStringList fileDocString;
753 fileDocString << QStringLiteral(
"\"\"\"" );
754 fileDocString << QStringLiteral(
"Model exported as python." );
755 fileDocString << QStringLiteral(
"Name : %1" ).arg( displayName() );
756 fileDocString << QStringLiteral(
"Group : %1" ).arg( group() );
757 fileDocString << QStringLiteral(
"With QGIS : %1" ).arg(
Qgis::versionInt() );
758 fileDocString << QStringLiteral(
"\"\"\"" );
759 fileDocString << QString();
762 QString indent = QString(
' ' ).repeated( indentSize );
763 QString currentIndent;
765 QMap< QString, QString> friendlyChildNames;
766 QMap< QString, QString> friendlyOutputNames;
767 auto uniqueSafeName = [](
const QString & name,
bool capitalize,
const QMap< QString, QString > &friendlyNames )->QString
769 const QString base = safeName( name, capitalize );
770 QString candidate = base;
773 while ( std::find( friendlyNames.cbegin(), friendlyNames.cend(), candidate ) != friendlyNames.cend() )
776 candidate = QStringLiteral(
"%1_%2" ).arg( base ).arg( i );
781 const QString algorithmClassName = safeName( name(),
true );
783 QSet< QString > toExecute;
784 for (
auto childIt = mChildAlgorithms.constBegin(); childIt != mChildAlgorithms.constEnd(); ++childIt )
786 if ( childIt->isActive() && childIt->algorithm() )
788 toExecute.insert( childIt->childId() );
789 friendlyChildNames.insert( childIt->childId(), uniqueSafeName( childIt->description().isEmpty() ? childIt->childId() : childIt->description(), !childIt->description().isEmpty(), friendlyChildNames ) );
792 const int totalSteps = toExecute.count();
794 QStringList importLines;
795 switch ( outputType )
800 const auto params = parameterDefinitions();
801 importLines.reserve( params.count() + 6 );
802 importLines << QStringLiteral(
"from typing import Any, Optional" );
803 importLines << QString();
804 importLines << QStringLiteral(
"from qgis.core import QgsProcessing" );
805 importLines << QStringLiteral(
"from qgis.core import QgsProcessingAlgorithm" );
806 importLines << QStringLiteral(
"from qgis.core import QgsProcessingContext" );
807 importLines << QStringLiteral(
"from qgis.core import QgsProcessingFeedback, QgsProcessingMultiStepFeedback" );
809 bool hasAdvancedParams =
false;
813 hasAdvancedParams =
true;
816 if ( !importString.isEmpty() && !importLines.contains( importString ) )
817 importLines << importString;
820 if ( hasAdvancedParams )
821 importLines << QStringLiteral(
"from qgis.core import QgsProcessingParameterDefinition" );
823 lines << QStringLiteral(
"from qgis import processing" );
824 lines << QString() << QString();
826 lines << QStringLiteral(
"class %1(QgsProcessingAlgorithm):" ).arg( algorithmClassName );
830 lines << indent + QStringLiteral(
"def initAlgorithm(self, config: Optional[dict[str, Any]] = None):" );
831 if ( params.empty() )
833 lines << indent + indent + QStringLiteral(
"pass" );
837 lines.reserve( lines.size() + params.size() );
840 std::unique_ptr< QgsProcessingParameterDefinition > defClone( def->clone() );
842 if ( defClone->isDestination() )
844 const QString uniqueChildName = defClone->metadata().value( QStringLiteral(
"_modelChildId" ) ).toString() +
':' + defClone->metadata().value( QStringLiteral(
"_modelChildOutputName" ) ).toString();
845 const QString friendlyName = !defClone->description().isEmpty() ? uniqueSafeName( defClone->description(),
true, friendlyOutputNames ) : defClone->name();
846 friendlyOutputNames.insert( uniqueChildName, friendlyName );
847 defClone->setName( friendlyName );
851 if ( !mParameterComponents.value( defClone->name() ).comment()->description().isEmpty() )
853 const QStringList parts = mParameterComponents.value( defClone->name() ).comment()->description().split( QStringLiteral(
"\n" ) );
854 for (
const QString &part : parts )
856 lines << indent + indent + QStringLiteral(
"# %1" ).arg( part );
863 lines << indent + indent + QStringLiteral(
"param = %1" ).arg( defClone->asPythonString() );
864 lines << indent + indent + QStringLiteral(
"param.setFlags(param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)" );
865 lines << indent + indent + QStringLiteral(
"self.addParameter(param)" );
869 lines << indent + indent + QStringLiteral(
"self.addParameter(%1)" ).arg( defClone->asPythonString() );
875 lines << indent + QStringLiteral(
"def processAlgorithm(self, parameters: dict[str, Any], context: QgsProcessingContext, model_feedback: QgsProcessingFeedback) -> dict[str, Any]:" );
876 currentIndent = indent + indent;
878 lines << currentIndent + QStringLiteral(
"# Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the" );
879 lines << currentIndent + QStringLiteral(
"# overall progress through the model" );
880 lines << currentIndent + QStringLiteral(
"feedback = QgsProcessingMultiStepFeedback(%1, model_feedback)" ).arg( totalSteps );
888 QMap< QString, QgsProcessingModelParameter >::const_iterator paramIt = mParameterComponents.constBegin();
889 for ( ; paramIt != mParameterComponents.constEnd(); ++paramIt )
891 QString name = paramIt.value().parameterName();
892 if ( parameterDefinition( name ) )
895 params.insert( name, parameterDefinition( name )->valueAsPythonString( parameterDefinition( name )->defaultValue(), context ) );
899 if ( !params.isEmpty() )
901 lines << QStringLiteral(
"parameters = {" );
902 for (
auto it = params.constBegin(); it != params.constEnd(); ++it )
904 lines << QStringLiteral(
" '%1':%2," ).arg( it.key(), it.value() );
906 lines << QStringLiteral(
"}" )
910 lines << QStringLiteral(
"context = QgsProcessingContext()" )
911 << QStringLiteral(
"context.setProject(QgsProject.instance())" )
912 << QStringLiteral(
"feedback = QgsProcessingFeedback()" )
921 lines << currentIndent + QStringLiteral(
"results = {}" );
922 lines << currentIndent + QStringLiteral(
"outputs = {}" );
925 QSet< QString > executed;
926 bool executedAlg =
true;
928 while ( executedAlg && executed.count() < toExecute.count() )
931 const auto constToExecute = toExecute;
932 for (
const QString &childId : constToExecute )
934 if ( executed.contains( childId ) )
937 bool canExecute =
true;
938 const auto constDependsOnChildAlgorithms = dependsOnChildAlgorithms( childId );
939 for (
const QString &dependency : constDependsOnChildAlgorithms )
941 if ( !executed.contains( dependency ) )
953 const QgsProcessingModelChildAlgorithm &child = mChildAlgorithms[ childId ];
960 if ( def->isDestination() )
965 bool isFinalOutput =
false;
966 QMap<QString, QgsProcessingModelOutput> outputs = child.modelOutputs();
967 QMap<QString, QgsProcessingModelOutput>::const_iterator outputIt = outputs.constBegin();
968 for ( ; outputIt != outputs.constEnd(); ++outputIt )
970 if ( outputIt->childOutputName() == destParam->
name() )
972 QString paramName = child.childId() +
':' + outputIt.key();
973 paramName = friendlyOutputNames.value( paramName, paramName );
974 childParams.insert( destParam->
name(), QStringLiteral(
"parameters['%1']" ).arg( paramName ) );
975 isFinalOutput =
true;
980 if ( !isFinalOutput )
985 bool required =
true;
988 required = childOutputIsRequired( child.childId(), destParam->
name() );
994 childParams.insert( destParam->
name(), QStringLiteral(
"QgsProcessing.TEMPORARY_OUTPUT" ) );
1000 lines << child.asPythonCode( outputType, childParams, currentIndent.size(), indentSize, friendlyChildNames, friendlyOutputNames );
1002 if ( currentStep < totalSteps )
1005 lines << currentIndent + QStringLiteral(
"feedback.setCurrentStep(%1)" ).arg( currentStep );
1006 lines << currentIndent + QStringLiteral(
"if feedback.isCanceled():" );
1007 lines << currentIndent + indent + QStringLiteral(
"return {}" );
1010 executed.insert( childId );
1014 switch ( outputType )
1017 lines << currentIndent + QStringLiteral(
"return results" );
1021 lines << indent + QStringLiteral(
"def name(self) -> str:" );
1022 lines << indent + indent + QStringLiteral(
"return '%1'" ).arg( mModelName );
1024 lines << indent + QStringLiteral(
"def displayName(self) -> str:" );
1025 lines << indent + indent + QStringLiteral(
"return '%1'" ).arg( mModelName );
1029 lines << indent + QStringLiteral(
"def group(self) -> str:" );
1030 lines << indent + indent + QStringLiteral(
"return '%1'" ).arg( mModelGroup );
1032 lines << indent + QStringLiteral(
"def groupId(self) -> str:" );
1033 lines << indent + indent + QStringLiteral(
"return '%1'" ).arg( mModelGroupId );
1037 if ( !shortHelpString().isEmpty() )
1039 lines << indent + QStringLiteral(
"def shortHelpString(self) -> str:" );
1040 lines << indent + indent + QStringLiteral(
"return \"\"\"%1\"\"\"" ).arg( shortHelpString() );
1043 if ( !helpUrl().isEmpty() )
1045 lines << indent + QStringLiteral(
"def helpUrl(self) -> str:" );
1046 lines << indent + indent + QStringLiteral(
"return '%1'" ).arg( helpUrl() );
1051 lines << indent + QStringLiteral(
"def createInstance(self):" );
1052 lines << indent + indent + QStringLiteral(
"return self.__class__()" );
1055 static QMap< QString, QString > sAdditionalImports
1057 { QStringLiteral(
"QgsCoordinateReferenceSystem" ), QStringLiteral(
"from qgis.core import QgsCoordinateReferenceSystem" ) },
1058 { QStringLiteral(
"QgsExpression" ), QStringLiteral(
"from qgis.core import QgsExpression" ) },
1059 { QStringLiteral(
"QgsRectangle" ), QStringLiteral(
"from qgis.core import QgsRectangle" ) },
1060 { QStringLiteral(
"QgsReferencedRectangle" ), QStringLiteral(
"from qgis.core import QgsReferencedRectangle" ) },
1061 { QStringLiteral(
"QgsPoint" ), QStringLiteral(
"from qgis.core import QgsPoint" ) },
1062 { QStringLiteral(
"QgsReferencedPoint" ), QStringLiteral(
"from qgis.core import QgsReferencedPoint" ) },
1063 { QStringLiteral(
"QgsProperty" ), QStringLiteral(
"from qgis.core import QgsProperty" ) },
1064 { QStringLiteral(
"QgsRasterLayer" ), QStringLiteral(
"from qgis.core import QgsRasterLayer" ) },
1065 { QStringLiteral(
"QgsMeshLayer" ), QStringLiteral(
"from qgis.core import QgsMeshLayer" ) },
1066 { QStringLiteral(
"QgsVectorLayer" ), QStringLiteral(
"from qgis.core import QgsVectorLayer" ) },
1067 { QStringLiteral(
"QgsMapLayer" ), QStringLiteral(
"from qgis.core import QgsMapLayer" ) },
1068 { QStringLiteral(
"QgsProcessingFeatureSourceDefinition" ), QStringLiteral(
"from qgis.core import QgsProcessingFeatureSourceDefinition" ) },
1069 { QStringLiteral(
"QgsPointXY" ), QStringLiteral(
"from qgis.core import QgsPointXY" ) },
1070 { QStringLiteral(
"QgsReferencedPointXY" ), QStringLiteral(
"from qgis.core import QgsReferencedPointXY" ) },
1071 { QStringLiteral(
"QgsGeometry" ), QStringLiteral(
"from qgis.core import QgsGeometry" ) },
1072 { QStringLiteral(
"QgsProcessingOutputLayerDefinition" ), QStringLiteral(
"from qgis.core import QgsProcessingOutputLayerDefinition" ) },
1073 { QStringLiteral(
"QColor" ), QStringLiteral(
"from qgis.PyQt.QtGui import QColor" ) },
1074 { QStringLiteral(
"QDateTime" ), QStringLiteral(
"from qgis.PyQt.QtCore import QDateTime" ) },
1075 { QStringLiteral(
"QDate" ), QStringLiteral(
"from qgis.PyQt.QtCore import QDate" ) },
1076 { QStringLiteral(
"QTime" ), QStringLiteral(
"from qgis.PyQt.QtCore import QTime" ) },
1079 for (
auto it = sAdditionalImports.constBegin(); it != sAdditionalImports.constEnd(); ++it )
1081 if ( importLines.contains( it.value() ) )
1088 for (
const QString &line : std::as_const( lines ) )
1090 if ( line.contains( it.key() ) )
1098 importLines << it.value();
1102 lines = fileDocString + importLines + lines;
1111QMap<QString, QgsProcessingModelAlgorithm::VariableDefinition> QgsProcessingModelAlgorithm::variablesForChildAlgorithm(
const QString &childId,
QgsProcessingContext *context,
const QVariantMap &modelParameters,
const QVariantMap &results )
const
1113 QMap<QString, QgsProcessingModelAlgorithm::VariableDefinition> variables;
1115 auto safeName = [](
const QString & name )->QString
1118 const thread_local QRegularExpression safeNameRe( QStringLiteral(
"[\\s'\"\\(\\):\\.]" ) );
1119 return s.replace( safeNameRe, QStringLiteral(
"_" ) );
1156 for (
const QgsProcessingModelChildParameterSource &source : std::as_const( sources ) )
1160 QString description;
1161 switch ( source.source() )
1165 name = source.parameterName();
1166 value = modelParameters.value( source.parameterName() );
1167 description = parameterDefinition( source.parameterName() )->description();
1172 const QgsProcessingModelChildAlgorithm &child = mChildAlgorithms.value( source.outputChildId() );
1173 name = QStringLiteral(
"%1_%2" ).arg( child.description().isEmpty() ?
1174 source.outputChildId() : child.description(), source.outputName() );
1177 description = QObject::tr(
"Output '%1' from algorithm '%2'" ).arg( alg->outputDefinition( source.outputName() )->description(),
1178 child.description() );
1180 value = results.value( source.outputChildId() ).toMap().value( source.outputName() );
1190 variables.insert( safeName( name ), VariableDefinition( value, source, description ) );
1194 sources = availableSourcesForChild( childId, QStringList()
1201 for (
const QgsProcessingModelChildParameterSource &source : std::as_const( sources ) )
1205 QString description;
1207 switch ( source.source() )
1211 name = source.parameterName();
1212 value = modelParameters.value( source.parameterName() );
1213 description = parameterDefinition( source.parameterName() )->description();
1218 const QgsProcessingModelChildAlgorithm &child = mChildAlgorithms.value( source.outputChildId() );
1219 name = QStringLiteral(
"%1_%2" ).arg( child.description().isEmpty() ?
1220 source.outputChildId() : child.description(), source.outputName() );
1221 value = results.value( source.outputChildId() ).toMap().value( source.outputName() );
1224 description = QObject::tr(
"Output '%1' from algorithm '%2'" ).arg( alg->outputDefinition( source.outputName() )->description(),
1225 child.description() );
1238 if ( value.userType() == qMetaTypeId<QgsProcessingOutputLayerDefinition>() )
1241 value = fromVar.
sink;
1242 if ( value.userType() == qMetaTypeId<QgsProperty>() && context )
1250 layer = qobject_cast< QgsMapLayer * >( qvariant_cast<QObject *>( value ) );
1255 variables.insert( safeName( name ), VariableDefinition( layer ? QVariant::fromValue(
QgsWeakMapLayerPointer( layer ) ) : QVariant(), source, description ) );
1256 variables.insert( safeName( QStringLiteral(
"%1_minx" ).arg( name ) ), VariableDefinition( layer ? layer->
extent().
xMinimum() : QVariant(), source, QObject::tr(
"Minimum X of %1" ).arg( description ) ) );
1257 variables.insert( safeName( QStringLiteral(
"%1_miny" ).arg( name ) ), VariableDefinition( layer ? layer->
extent().
yMinimum() : QVariant(), source, QObject::tr(
"Minimum Y of %1" ).arg( description ) ) );
1258 variables.insert( safeName( QStringLiteral(
"%1_maxx" ).arg( name ) ), VariableDefinition( layer ? layer->
extent().
xMaximum() : QVariant(), source, QObject::tr(
"Maximum X of %1" ).arg( description ) ) );
1259 variables.insert( safeName( QStringLiteral(
"%1_maxy" ).arg( name ) ), VariableDefinition( layer ? layer->
extent().
yMaximum() : QVariant(), source, QObject::tr(
"Maximum Y of %1" ).arg( description ) ) );
1262 sources = availableSourcesForChild( childId, QStringList()
1264 for (
const QgsProcessingModelChildParameterSource &source : std::as_const( sources ) )
1268 QString description;
1270 switch ( source.source() )
1274 name = source.parameterName();
1275 value = modelParameters.value( source.parameterName() );
1276 description = parameterDefinition( source.parameterName() )->description();
1281 const QgsProcessingModelChildAlgorithm &child = mChildAlgorithms.value( source.outputChildId() );
1282 name = QStringLiteral(
"%1_%2" ).arg( child.description().isEmpty() ?
1283 source.outputChildId() : child.description(), source.outputName() );
1284 value = results.value( source.outputChildId() ).toMap().value( source.outputName() );
1287 description = QObject::tr(
"Output '%1' from algorithm '%2'" ).arg( alg->outputDefinition( source.outputName() )->description(),
1288 child.description() );
1302 if ( value.userType() == qMetaTypeId<QgsProcessingFeatureSourceDefinition>() )
1307 else if ( value.userType() == qMetaTypeId<QgsProcessingOutputLayerDefinition>() )
1310 value = fromVar.
sink;
1311 if ( context && value.userType() == qMetaTypeId<QgsProperty>() )
1316 if (
QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( qvariant_cast<QObject *>( value ) ) )
1318 featureSource = layer;
1320 if ( context && !featureSource )
1326 variables.insert( safeName( name ), VariableDefinition( value, source, description ) );
1327 variables.insert( safeName( QStringLiteral(
"%1_minx" ).arg( name ) ), VariableDefinition( featureSource ? featureSource->
sourceExtent().
xMinimum() : QVariant(), source, QObject::tr(
"Minimum X of %1" ).arg( description ) ) );
1328 variables.insert( safeName( QStringLiteral(
"%1_miny" ).arg( name ) ), VariableDefinition( featureSource ? featureSource->
sourceExtent().
yMinimum() : QVariant(), source, QObject::tr(
"Minimum Y of %1" ).arg( description ) ) );
1329 variables.insert( safeName( QStringLiteral(
"%1_maxx" ).arg( name ) ), VariableDefinition( featureSource ? featureSource->
sourceExtent().
xMaximum() : QVariant(), source, QObject::tr(
"Maximum X of %1" ).arg( description ) ) );
1330 variables.insert( safeName( QStringLiteral(
"%1_maxy" ).arg( name ) ), VariableDefinition( featureSource ? featureSource->
sourceExtent().
yMaximum() : QVariant(), source, QObject::tr(
"Maximum Y of %1" ).arg( description ) ) );
1336QgsExpressionContextScope *QgsProcessingModelAlgorithm::createExpressionContextScopeForChildAlgorithm(
const QString &childId,
QgsProcessingContext &context,
const QVariantMap &modelParameters,
const QVariantMap &results )
const
1338 auto scope = std::make_unique<QgsExpressionContextScope>( QStringLiteral(
"algorithm_inputs" ) );
1339 QMap< QString, QgsProcessingModelAlgorithm::VariableDefinition> variables = variablesForChildAlgorithm( childId, &context, modelParameters, results );
1340 QMap< QString, QgsProcessingModelAlgorithm::VariableDefinition>::const_iterator varIt = variables.constBegin();
1341 for ( ; varIt != variables.constEnd(); ++varIt )
1345 return scope.release();
1348QgsProcessingModelChildParameterSources QgsProcessingModelAlgorithm::availableSourcesForChild(
const QString &childId,
const QgsProcessingParameterDefinition *param )
const
1352 return QgsProcessingModelChildParameterSources();
1356QgsProcessingModelChildParameterSources QgsProcessingModelAlgorithm::availableSourcesForChild(
const QString &childId,
const QStringList ¶meterTypes,
const QStringList &outputTypes,
const QList<int> &dataTypes )
const
1358 QgsProcessingModelChildParameterSources sources;
1361 QMap< QString, QgsProcessingModelParameter >::const_iterator paramIt = mParameterComponents.constBegin();
1362 for ( ; paramIt != mParameterComponents.constEnd(); ++paramIt )
1368 if ( parameterTypes.contains( def->
type() ) )
1370 if ( !dataTypes.isEmpty() )
1386 bool ok = sourceDef->
dataTypes().isEmpty();
1387 const auto constDataTypes = sourceDef->
dataTypes();
1388 for (
int type : constDataTypes )
1403 sources << QgsProcessingModelChildParameterSource::fromModelParameter( paramIt->parameterName() );
1407 QSet< QString > dependents;
1408 if ( !childId.isEmpty() )
1410 dependents = dependentChildAlgorithms( childId );
1411 dependents << childId;
1414 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
1415 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
1417 if ( dependents.contains( childIt->childId() ) )
1427 if ( outputTypes.contains( out->type() ) )
1429 if ( !dataTypes.isEmpty() )
1435 if ( !vectorOutputIsCompatibleType( dataTypes, vectorOut->
dataType() ) )
1442 sources << QgsProcessingModelChildParameterSource::fromChildOutput( childIt->childId(), out->name() );
1450QVariantMap QgsProcessingModelAlgorithm::helpContent()
const
1452 return mHelpContent;
1455void QgsProcessingModelAlgorithm::setHelpContent(
const QVariantMap &helpContent )
1457 mHelpContent = helpContent;
1460void QgsProcessingModelAlgorithm::setName(
const QString &name )
1465void QgsProcessingModelAlgorithm::setGroup(
const QString &group )
1467 mModelGroup = group;
1470bool QgsProcessingModelAlgorithm::validate( QStringList &issues )
const
1475 if ( mChildAlgorithms.empty() )
1478 issues << QObject::tr(
"Model does not contain any algorithms" );
1481 for (
auto it = mChildAlgorithms.constBegin(); it != mChildAlgorithms.constEnd(); ++it )
1483 QStringList childIssues;
1484 res = validateChildAlgorithm( it->childId(), childIssues ) && res;
1486 for (
const QString &issue : std::as_const( childIssues ) )
1488 issues << QStringLiteral(
"<b>%1</b>: %2" ).arg( it->description(), issue );
1494QMap<QString, QgsProcessingModelChildAlgorithm> QgsProcessingModelAlgorithm::childAlgorithms()
const
1496 return mChildAlgorithms;
1499void QgsProcessingModelAlgorithm::setParameterComponents(
const QMap<QString, QgsProcessingModelParameter> ¶meterComponents )
1501 mParameterComponents = parameterComponents;
1504void QgsProcessingModelAlgorithm::setParameterComponent(
const QgsProcessingModelParameter &component )
1506 mParameterComponents.insert( component.parameterName(), component );
1509QgsProcessingModelParameter &QgsProcessingModelAlgorithm::parameterComponent(
const QString &name )
1511 if ( !mParameterComponents.contains( name ) )
1513 QgsProcessingModelParameter &component = mParameterComponents[ name ];
1514 component.setParameterName( name );
1517 return mParameterComponents[ name ];
1520QList< QgsProcessingModelParameter > QgsProcessingModelAlgorithm::orderedParameters()
const
1522 QList< QgsProcessingModelParameter > res;
1523 QSet< QString > found;
1524 for (
const QString ¶meter : mParameterOrder )
1526 if ( mParameterComponents.contains( parameter ) )
1528 res << mParameterComponents.value( parameter );
1534 for (
auto it = mParameterComponents.constBegin(); it != mParameterComponents.constEnd(); ++it )
1536 if ( !found.contains( it.key() ) )
1544void QgsProcessingModelAlgorithm::setParameterOrder(
const QStringList &order )
1546 mParameterOrder = order;
1549QList<QgsProcessingModelOutput> QgsProcessingModelAlgorithm::orderedOutputs()
const
1551 QList< QgsProcessingModelOutput > res;
1552 QSet< QString > found;
1554 for (
const QString &output : mOutputOrder )
1556 bool foundOutput =
false;
1557 for (
auto it = mChildAlgorithms.constBegin(); it != mChildAlgorithms.constEnd(); ++it )
1559 const QMap<QString, QgsProcessingModelOutput> outputs = it.value().modelOutputs();
1560 for (
auto outputIt = outputs.constBegin(); outputIt != outputs.constEnd(); ++outputIt )
1562 if ( output == QStringLiteral(
"%1:%2" ).arg( outputIt->childId(), outputIt->childOutputName() ) )
1564 res << outputIt.value();
1566 found.insert( QStringLiteral(
"%1:%2" ).arg( outputIt->childId(), outputIt->childOutputName() ) );
1575 for (
auto it = mChildAlgorithms.constBegin(); it != mChildAlgorithms.constEnd(); ++it )
1577 const QMap<QString, QgsProcessingModelOutput> outputs = it.value().modelOutputs();
1578 for (
auto outputIt = outputs.constBegin(); outputIt != outputs.constEnd(); ++outputIt )
1580 if ( !found.contains( QStringLiteral(
"%1:%2" ).arg( outputIt->childId(), outputIt->childOutputName() ) ) )
1582 res << outputIt.value();
1590void QgsProcessingModelAlgorithm::setOutputOrder(
const QStringList &order )
1592 mOutputOrder = order;
1595QString QgsProcessingModelAlgorithm::outputGroup()
const
1597 return mOutputGroup;
1600void QgsProcessingModelAlgorithm::setOutputGroup(
const QString &group )
1602 mOutputGroup = group;
1605void QgsProcessingModelAlgorithm::updateDestinationParameters()
1608 QMutableListIterator<const QgsProcessingParameterDefinition *> it( mParameters );
1609 while ( it.hasNext() )
1619 qDeleteAll( mOutputs );
1623 QSet< QString > usedFriendlyNames;
1624 auto uniqueSafeName = [&usedFriendlyNames ](
const QString & name )->QString
1626 const QString base = safeName( name,
false );
1627 QString candidate = base;
1629 while ( usedFriendlyNames.contains( candidate ) )
1632 candidate = QStringLiteral(
"%1_%2" ).arg( base ).arg( i );
1634 usedFriendlyNames.insert( candidate );
1638 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
1639 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
1641 QMap<QString, QgsProcessingModelOutput> outputs = childIt->modelOutputs();
1642 QMap<QString, QgsProcessingModelOutput>::const_iterator outputIt = outputs.constBegin();
1643 for ( ; outputIt != outputs.constEnd(); ++outputIt )
1645 if ( !childIt->isActive() || !childIt->algorithm() )
1653 std::unique_ptr< QgsProcessingParameterDefinition > param( source->
clone() );
1657 if ( outputIt->isMandatory() )
1659 if ( mInternalVersion != InternalVersion::Version1 && !outputIt->description().isEmpty() )
1661 QString friendlyName = uniqueSafeName( outputIt->description() );
1662 param->
setName( friendlyName );
1666 param->
setName( outputIt->childId() +
':' + outputIt->name() );
1669 param->
metadata().insert( QStringLiteral(
"_modelChildId" ), outputIt->childId() );
1670 param->
metadata().insert( QStringLiteral(
"_modelChildOutputName" ), outputIt->name() );
1671 param->
metadata().insert( QStringLiteral(
"_modelChildProvider" ), childIt->algorithm()->provider() ? childIt->algorithm()->provider()->id() : QString() );
1677 if ( addParameter( param.release() ) && newDestParam )
1684 newDestParam->mOriginalProvider = provider;
1691void QgsProcessingModelAlgorithm::addGroupBox(
const QgsProcessingModelGroupBox &groupBox )
1693 mGroupBoxes.insert( groupBox.uuid(), groupBox );
1696QList<QgsProcessingModelGroupBox> QgsProcessingModelAlgorithm::groupBoxes()
const
1698 return mGroupBoxes.values();
1701void QgsProcessingModelAlgorithm::removeGroupBox(
const QString &uuid )
1703 mGroupBoxes.remove( uuid );
1706QVariant QgsProcessingModelAlgorithm::toVariant()
const
1709 map.insert( QStringLiteral(
"model_name" ), mModelName );
1710 map.insert( QStringLiteral(
"model_group" ), mModelGroup );
1711 map.insert( QStringLiteral(
"help" ), mHelpContent );
1712 map.insert( QStringLiteral(
"internal_version" ),
qgsEnumValueToKey( mInternalVersion ) );
1714 QVariantMap childMap;
1715 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
1716 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
1718 childMap.insert( childIt.key(), childIt.value().toVariant() );
1720 map.insert( QStringLiteral(
"children" ), childMap );
1722 QVariantMap paramMap;
1723 QMap< QString, QgsProcessingModelParameter >::const_iterator paramIt = mParameterComponents.constBegin();
1724 for ( ; paramIt != mParameterComponents.constEnd(); ++paramIt )
1726 paramMap.insert( paramIt.key(), paramIt.value().toVariant() );
1728 map.insert( QStringLiteral(
"parameters" ), paramMap );
1730 QVariantMap paramDefMap;
1735 map.insert( QStringLiteral(
"parameterDefinitions" ), paramDefMap );
1737 QVariantList groupBoxDefs;
1738 for (
auto it = mGroupBoxes.constBegin(); it != mGroupBoxes.constEnd(); ++it )
1740 groupBoxDefs.append( it.value().toVariant() );
1742 map.insert( QStringLiteral(
"groupBoxes" ), groupBoxDefs );
1744 map.insert( QStringLiteral(
"modelVariables" ), mVariables );
1746 map.insert( QStringLiteral(
"designerParameterValues" ), mDesignerParameterValues );
1748 map.insert( QStringLiteral(
"parameterOrder" ), mParameterOrder );
1749 map.insert( QStringLiteral(
"outputOrder" ), mOutputOrder );
1750 map.insert( QStringLiteral(
"outputGroup" ), mOutputGroup );
1755bool QgsProcessingModelAlgorithm::loadVariant(
const QVariant &model )
1757 QVariantMap map = model.toMap();
1759 mModelName = map.value( QStringLiteral(
"model_name" ) ).toString();
1760 mModelGroup = map.value( QStringLiteral(
"model_group" ) ).toString();
1761 mModelGroupId = map.value( QStringLiteral(
"model_group" ) ).toString();
1762 mHelpContent = map.value( QStringLiteral(
"help" ) ).toMap();
1764 mInternalVersion =
qgsEnumKeyToValue( map.value( QStringLiteral(
"internal_version" ) ).toString(), InternalVersion::Version1 );
1766 mVariables = map.value( QStringLiteral(
"modelVariables" ) ).toMap();
1767 mDesignerParameterValues = map.value( QStringLiteral(
"designerParameterValues" ) ).toMap();
1769 mParameterOrder = map.value( QStringLiteral(
"parameterOrder" ) ).toStringList();
1770 mOutputOrder = map.value( QStringLiteral(
"outputOrder" ) ).toStringList();
1771 mOutputGroup = map.value( QStringLiteral(
"outputGroup" ) ).toString();
1773 mChildAlgorithms.clear();
1774 QVariantMap childMap = map.value( QStringLiteral(
"children" ) ).toMap();
1775 QVariantMap::const_iterator childIt = childMap.constBegin();
1776 for ( ; childIt != childMap.constEnd(); ++childIt )
1778 QgsProcessingModelChildAlgorithm child;
1782 if ( !child.loadVariant( childIt.value() ) )
1785 mChildAlgorithms.insert( child.childId(), child );
1788 mParameterComponents.clear();
1789 QVariantMap paramMap = map.value( QStringLiteral(
"parameters" ) ).toMap();
1790 QVariantMap::const_iterator paramIt = paramMap.constBegin();
1791 for ( ; paramIt != paramMap.constEnd(); ++paramIt )
1793 QgsProcessingModelParameter param;
1794 if ( !param.loadVariant( paramIt.value().toMap() ) )
1797 mParameterComponents.insert( param.parameterName(), param );
1800 qDeleteAll( mParameters );
1801 mParameters.clear();
1802 QVariantMap paramDefMap = map.value( QStringLiteral(
"parameterDefinitions" ) ).toMap();
1804 auto addParam = [
this](
const QVariant & value )
1812 if ( param->name() == QLatin1String(
"VERBOSE_LOG" ) )
1816 param->setHelp( mHelpContent.value( param->name() ).toString() );
1819 addParameter( param.release() );
1823 QVariantMap map = value.toMap();
1824 QString type = map.value( QStringLiteral(
"parameter_type" ) ).toString();
1825 QString name = map.value( QStringLiteral(
"name" ) ).toString();
1827 QgsMessageLog::logMessage( QCoreApplication::translate(
"Processing",
"Could not load parameter %1 of type %2." ).arg( name, type ), QCoreApplication::translate(
"Processing",
"Processing" ) );
1831 QSet< QString > loadedParams;
1833 for (
const QString &name : std::as_const( mParameterOrder ) )
1835 if ( paramDefMap.contains( name ) )
1837 addParam( paramDefMap.value( name ) );
1838 loadedParams << name;
1842 QVariantMap::const_iterator paramDefIt = paramDefMap.constBegin();
1843 for ( ; paramDefIt != paramDefMap.constEnd(); ++paramDefIt )
1845 if ( !loadedParams.contains( paramDefIt.key() ) )
1846 addParam( paramDefIt.value() );
1849 mGroupBoxes.clear();
1850 const QVariantList groupBoxList = map.value( QStringLiteral(
"groupBoxes" ) ).toList();
1851 for (
const QVariant &groupBoxDef : groupBoxList )
1853 QgsProcessingModelGroupBox groupBox;
1854 groupBox.loadVariant( groupBoxDef.toMap() );
1855 mGroupBoxes.insert( groupBox.uuid(), groupBox );
1858 updateDestinationParameters();
1863bool QgsProcessingModelAlgorithm::vectorOutputIsCompatibleType(
const QList<int> &acceptableDataTypes,
Qgis::ProcessingSourceType outputType )
1868 return ( acceptableDataTypes.empty()
1869 || acceptableDataTypes.contains(
static_cast< int >( outputType ) )
1880void QgsProcessingModelAlgorithm::reattachAlgorithms()
const
1882 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
1883 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
1885 if ( !childIt->algorithm() )
1886 childIt->reattach();
1890bool QgsProcessingModelAlgorithm::toFile(
const QString &path )
const
1892 QDomDocument doc = QDomDocument( QStringLiteral(
"model" ) );
1894 doc.appendChild( elem );
1897 if ( file.open( QFile::WriteOnly | QFile::Truncate ) )
1899 QTextStream stream( &file );
1900 doc.save( stream, 2 );
1907bool QgsProcessingModelAlgorithm::fromFile(
const QString &path )
1912 if ( file.open( QFile::ReadOnly ) )
1914 if ( !doc.setContent( &file ) )
1925 return loadVariant( props );
1928void QgsProcessingModelAlgorithm::setChildAlgorithms(
const QMap<QString, QgsProcessingModelChildAlgorithm> &childAlgorithms )
1930 mChildAlgorithms = childAlgorithms;
1931 updateDestinationParameters();
1934void QgsProcessingModelAlgorithm::setChildAlgorithm(
const QgsProcessingModelChildAlgorithm &
algorithm )
1937 updateDestinationParameters();
1940QString QgsProcessingModelAlgorithm::addChildAlgorithm( QgsProcessingModelChildAlgorithm &
algorithm )
1942 if (
algorithm.childId().isEmpty() || mChildAlgorithms.contains(
algorithm.childId() ) )
1946 updateDestinationParameters();
1950QgsProcessingModelChildAlgorithm &QgsProcessingModelAlgorithm::childAlgorithm(
const QString &childId )
1952 return mChildAlgorithms[ childId ];
1955bool QgsProcessingModelAlgorithm::removeChildAlgorithm(
const QString &
id )
1957 if ( !dependentChildAlgorithms(
id ).isEmpty() )
1960 mChildAlgorithms.remove(
id );
1961 updateDestinationParameters();
1965void QgsProcessingModelAlgorithm::deactivateChildAlgorithm(
const QString &
id )
1967 const auto constDependentChildAlgorithms = dependentChildAlgorithms(
id );
1968 for (
const QString &child : constDependentChildAlgorithms )
1970 childAlgorithm( child ).setActive(
false );
1972 childAlgorithm(
id ).setActive(
false );
1973 updateDestinationParameters();
1976bool QgsProcessingModelAlgorithm::activateChildAlgorithm(
const QString &
id )
1978 const auto constDependsOnChildAlgorithms = dependsOnChildAlgorithms(
id );
1979 for (
const QString &child : constDependsOnChildAlgorithms )
1981 if ( !childAlgorithm( child ).isActive() )
1984 childAlgorithm(
id ).setActive(
true );
1985 updateDestinationParameters();
1991 if ( addParameter( definition ) )
1992 mParameterComponents.insert( definition->
name(), component );
1997 removeParameter( definition->
name() );
1998 addParameter( definition );
2001void QgsProcessingModelAlgorithm::removeModelParameter(
const QString &name )
2003 removeParameter( name );
2004 mParameterComponents.remove( name );
2007void QgsProcessingModelAlgorithm::changeParameterName(
const QString &oldName,
const QString &newName )
2012 auto replaceExpressionVariable = [oldName, newName, &expressionContext](
const QString & expressionString ) -> std::tuple< bool, QString >
2015 expression.prepare( &expressionContext );
2016 QSet<QString> variables = expression.referencedVariables();
2017 if ( variables.contains( oldName ) )
2019 QString newExpression = expressionString;
2020 newExpression.replace( QStringLiteral(
"@%1" ).arg( oldName ), QStringLiteral(
"@%2" ).arg( newName ) );
2021 return {
true, newExpression };
2023 return {
false, QString() };
2026 QMap< QString, QgsProcessingModelChildAlgorithm >::iterator childIt = mChildAlgorithms.begin();
2027 for ( ; childIt != mChildAlgorithms.end(); ++childIt )
2029 bool changed =
false;
2030 QMap<QString, QgsProcessingModelChildParameterSources> childParams = childIt->parameterSources();
2031 QMap<QString, QgsProcessingModelChildParameterSources>::iterator paramIt = childParams.begin();
2032 for ( ; paramIt != childParams.end(); ++paramIt )
2034 QList< QgsProcessingModelChildParameterSource > &value = paramIt.value();
2035 for (
auto valueIt = value.begin(); valueIt != value.end(); ++valueIt )
2037 switch ( valueIt->source() )
2041 if ( valueIt->parameterName() == oldName )
2043 valueIt->setParameterName( newName );
2051 bool updatedExpression =
false;
2052 QString newExpression;
2053 std::tie( updatedExpression, newExpression ) = replaceExpressionVariable( valueIt->expression() );
2054 if ( updatedExpression )
2056 valueIt->setExpression( newExpression );
2064 if ( valueIt->staticValue().userType() == qMetaTypeId<QgsProperty>() )
2069 bool updatedExpression =
false;
2070 QString newExpression;
2071 std::tie( updatedExpression, newExpression ) = replaceExpressionVariable( property.expressionString() );
2072 if ( updatedExpression )
2074 property.setExpressionString( newExpression );
2075 valueIt->setStaticValue( property );
2091 childIt->setParameterSources( childParams );
2095bool QgsProcessingModelAlgorithm::childAlgorithmsDependOnParameter(
const QString &name )
const
2097 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
2098 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
2101 QMap<QString, QgsProcessingModelChildParameterSources> childParams = childIt->parameterSources();
2102 QMap<QString, QgsProcessingModelChildParameterSources>::const_iterator paramIt = childParams.constBegin();
2103 for ( ; paramIt != childParams.constEnd(); ++paramIt )
2105 const auto constValue = paramIt.value();
2106 for (
const QgsProcessingModelChildParameterSource &source : constValue )
2109 && source.parameterName() == name )
2119bool QgsProcessingModelAlgorithm::otherParametersDependOnParameter(
const QString &name )
const
2121 const auto constMParameters = mParameters;
2124 if ( def->
name() == name )
2133QMap<QString, QgsProcessingModelParameter> QgsProcessingModelAlgorithm::parameterComponents()
const
2135 return mParameterComponents;
2138void QgsProcessingModelAlgorithm::dependentChildAlgorithmsRecursive(
const QString &childId, QSet<QString> &depends,
const QString &branch )
const
2140 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
2141 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
2143 if ( depends.contains( childIt->childId() ) )
2147 const QList< QgsProcessingModelChildDependency > constDependencies = childIt->dependencies();
2148 bool hasDependency =
false;
2149 for (
const QgsProcessingModelChildDependency &dep : constDependencies )
2151 if ( dep.childId == childId && ( branch.isEmpty() || dep.conditionalBranch == branch ) )
2153 hasDependency =
true;
2158 if ( hasDependency )
2160 depends.insert( childIt->childId() );
2161 dependentChildAlgorithmsRecursive( childIt->childId(), depends, branch );
2166 QMap<QString, QgsProcessingModelChildParameterSources> childParams = childIt->parameterSources();
2167 QMap<QString, QgsProcessingModelChildParameterSources>::const_iterator paramIt = childParams.constBegin();
2168 for ( ; paramIt != childParams.constEnd(); ++paramIt )
2170 const auto constValue = paramIt.value();
2171 for (
const QgsProcessingModelChildParameterSource &source : constValue )
2174 && source.outputChildId() == childId )
2176 depends.insert( childIt->childId() );
2177 dependentChildAlgorithmsRecursive( childIt->childId(), depends, branch );
2185QSet<QString> QgsProcessingModelAlgorithm::dependentChildAlgorithms(
const QString &childId,
const QString &conditionalBranch )
const
2187 QSet< QString > algs;
2191 algs.insert( childId );
2193 dependentChildAlgorithmsRecursive( childId, algs, conditionalBranch );
2196 algs.remove( childId );
2202void QgsProcessingModelAlgorithm::dependsOnChildAlgorithmsRecursive(
const QString &childId, QSet< QString > &depends )
const
2204 const QgsProcessingModelChildAlgorithm &alg = mChildAlgorithms.value( childId );
2207 const QList< QgsProcessingModelChildDependency > constDependencies = alg.dependencies();
2208 for (
const QgsProcessingModelChildDependency &val : constDependencies )
2210 if ( !depends.contains( val.childId ) )
2212 depends.insert( val.childId );
2213 dependsOnChildAlgorithmsRecursive( val.childId, depends );
2218 QMap<QString, QgsProcessingModelChildParameterSources> childParams = alg.parameterSources();
2219 QMap<QString, QgsProcessingModelChildParameterSources>::const_iterator paramIt = childParams.constBegin();
2220 for ( ; paramIt != childParams.constEnd(); ++paramIt )
2222 const auto constValue = paramIt.value();
2223 for (
const QgsProcessingModelChildParameterSource &source : constValue )
2225 switch ( source.source() )
2228 if ( !depends.contains( source.outputChildId() ) )
2230 depends.insert( source.outputChildId() );
2231 dependsOnChildAlgorithmsRecursive( source.outputChildId(), depends );
2238 const QSet<QString> vars = exp.referencedVariables();
2243 const QMap<QString, QgsProcessingModelAlgorithm::VariableDefinition> availableVariables = variablesForChildAlgorithm( childId );
2244 for (
auto childVarIt = availableVariables.constBegin(); childVarIt != availableVariables.constEnd(); ++childVarIt )
2250 if ( !vars.contains( childVarIt.key() ) || depends.contains( childVarIt->source.outputChildId() ) )
2254 depends.insert( childVarIt->source.outputChildId() );
2255 dependsOnChildAlgorithmsRecursive( childVarIt->source.outputChildId(), depends );
2270QSet< QString > QgsProcessingModelAlgorithm::dependsOnChildAlgorithms(
const QString &childId )
const
2272 QSet< QString > algs;
2276 algs.insert( childId );
2278 dependsOnChildAlgorithmsRecursive( childId, algs );
2281 algs.remove( childId );
2286QList<QgsProcessingModelChildDependency> QgsProcessingModelAlgorithm::availableDependenciesForChildAlgorithm(
const QString &childId )
const
2288 QSet< QString > dependent;
2289 if ( !childId.isEmpty() )
2291 dependent.unite( dependentChildAlgorithms( childId ) );
2292 dependent.insert( childId );
2295 QList<QgsProcessingModelChildDependency> res;
2296 for (
auto it = mChildAlgorithms.constBegin(); it != mChildAlgorithms.constEnd(); ++it )
2298 if ( !dependent.contains( it->childId() ) )
2301 bool hasBranches =
false;
2302 if ( it->algorithm() )
2310 QgsProcessingModelChildDependency alg;
2311 alg.childId = it->childId();
2312 alg.conditionalBranch = def->
name();
2320 QgsProcessingModelChildDependency alg;
2321 alg.childId = it->childId();
2329bool QgsProcessingModelAlgorithm::validateChildAlgorithm(
const QString &childId, QStringList &issues )
const
2332 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constFind( childId );
2333 if ( childIt != mChildAlgorithms.constEnd() )
2335 if ( !childIt->algorithm() )
2337 issues << QObject::tr(
"Algorithm is not available: <i>%1</i>" ).arg( childIt->algorithmId() );
2346 if ( childIt->parameterSources().contains( def->
name() ) )
2349 const QList< QgsProcessingModelChildParameterSource > sources = childIt->parameterSources().value( def->
name() );
2350 for (
const QgsProcessingModelChildParameterSource &source : sources )
2352 switch ( source.source() )
2358 issues << QObject::tr(
"Value for <i>%1</i> is not acceptable for this parameter" ).arg( def->
name() );
2363 if ( !parameterComponents().contains( source.parameterName() ) )
2366 issues << QObject::tr(
"Model input <i>%1</i> used for parameter <i>%2</i> does not exist" ).arg( source.parameterName(), def->
name() );
2371 if ( !childAlgorithms().contains( source.outputChildId() ) )
2374 issues << QObject::tr(
"Child algorithm <i>%1</i> used for parameter <i>%2</i> does not exist" ).arg( source.outputChildId(), def->
name() );
2396 issues << QObject::tr(
"Parameter <i>%1</i> is mandatory" ).arg( def->
name() );
2405 issues << QObject::tr(
"Invalid child ID: <i>%1</i>" ).arg( childId );
2410bool QgsProcessingModelAlgorithm::canExecute( QString *errorMessage )
const
2412 reattachAlgorithms();
2413 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
2414 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
2416 if ( !childIt->algorithm() )
2420 *errorMessage = QObject::tr(
"The model you are trying to run contains an algorithm that is not available: <i>%1</i>" ).arg( childIt->algorithmId() );
2428QString QgsProcessingModelAlgorithm::asPythonCommand(
const QVariantMap ¶meters,
QgsProcessingContext &context )
const
2430 if ( mSourceFile.isEmpty() )
2445 QgsProcessingModelAlgorithm *alg =
new QgsProcessingModelAlgorithm();
2446 alg->loadVariant( toVariant() );
2447 alg->setProvider( provider() );
2448 alg->setSourceFilePath( sourceFilePath() );
2452QString QgsProcessingModelAlgorithm::safeName(
const QString &name,
bool capitalize )
2454 QString n = name.toLower().trimmed();
2455 const thread_local QRegularExpression rx( QStringLiteral(
"[^\\sa-z_A-Z0-9]" ) );
2456 n.replace( rx, QString() );
2457 const thread_local QRegularExpression rx2( QStringLiteral(
"^\\d*" ) );
2458 n.replace( rx2, QString() );
2460 n = n.replace(
' ',
'_' );
2464QVariantMap QgsProcessingModelAlgorithm::variables()
const
2469void QgsProcessingModelAlgorithm::setVariables(
const QVariantMap &variables )
2471 mVariables = variables;
2474QVariantMap QgsProcessingModelAlgorithm::designerParameterValues()
const
2476 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...
Handles 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, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE())
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.
QMap< QString, QgsProcessingModelChildAlgorithmResult > childResults() const
Returns the map of child algorithm results.
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.
void setDefaultValue(const QVariant &value)
Sets the default value for the parameter.
QgsProcessingAlgorithm * algorithm() const
Returns a pointer to the algorithm which owns this parameter.
void setFlags(Qgis::ProcessingParameterFlags flags)
Sets the flags associated with the 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.
void setDescription(const QString &description)
Sets the description for the parameter.
void setName(const QString &name)
Sets the name of the parameter.
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.
Makes metadata of processing parameters available.
virtual QStringList acceptedOutputTypes() const =0
Returns a list of compatible Processing output types for inputs for this parameter type.
virtual QList< int > acceptedDataTypes(const QgsProcessingParameterDefinition *parameter) const
Returns a list of compatible Processing data types for inputs for this parameter type for the specifi...
virtual QStringList acceptedParameterTypes() const =0
Returns a list of compatible Processing parameter types for inputs for this parameter type.
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 dataset.
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.