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;
772 while ( friendlyNames.contains( candidate ) )
775 candidate = QStringLiteral(
"%1_%2" ).arg( base ).arg( i );
780 const QString algorithmClassName = safeName( name(),
true );
782 QSet< QString > toExecute;
783 for (
auto childIt = mChildAlgorithms.constBegin(); childIt != mChildAlgorithms.constEnd(); ++childIt )
785 if ( childIt->isActive() && childIt->algorithm() )
787 toExecute.insert( childIt->childId() );
788 friendlyChildNames.insert( childIt->childId(), uniqueSafeName( childIt->description().isEmpty() ? childIt->childId() : childIt->description(), !childIt->description().isEmpty(), friendlyChildNames ) );
791 const int totalSteps = toExecute.count();
793 QStringList importLines;
794 switch ( outputType )
799 const auto params = parameterDefinitions();
800 importLines.reserve( params.count() + 6 );
801 importLines << QStringLiteral(
"from typing import Any, Optional" );
802 importLines << QString();
803 importLines << QStringLiteral(
"from qgis.core import QgsProcessing" );
804 importLines << QStringLiteral(
"from qgis.core import QgsProcessingAlgorithm" );
805 importLines << QStringLiteral(
"from qgis.core import QgsProcessingContext" );
806 importLines << QStringLiteral(
"from qgis.core import QgsProcessingFeedback, QgsProcessingMultiStepFeedback" );
808 bool hasAdvancedParams =
false;
812 hasAdvancedParams =
true;
815 if ( !importString.isEmpty() && !importLines.contains( importString ) )
816 importLines << importString;
819 if ( hasAdvancedParams )
820 importLines << QStringLiteral(
"from qgis.core import QgsProcessingParameterDefinition" );
822 lines << QStringLiteral(
"from qgis import processing" );
823 lines << QString() << QString();
825 lines << QStringLiteral(
"class %1(QgsProcessingAlgorithm):" ).arg( algorithmClassName );
829 lines << indent + QStringLiteral(
"def initAlgorithm(self, config: Optional[dict[str, Any]] = None):" );
830 if ( params.empty() )
832 lines << indent + indent + QStringLiteral(
"pass" );
836 lines.reserve( lines.size() + params.size() );
839 std::unique_ptr< QgsProcessingParameterDefinition > defClone( def->clone() );
841 if ( defClone->isDestination() )
843 const QString uniqueChildName = defClone->metadata().value( QStringLiteral(
"_modelChildId" ) ).toString() +
':' + defClone->metadata().value( QStringLiteral(
"_modelChildOutputName" ) ).toString();
844 const QString friendlyName = !defClone->description().isEmpty() ? uniqueSafeName( defClone->description(),
true, friendlyOutputNames ) : defClone->name();
845 friendlyOutputNames.insert( uniqueChildName, friendlyName );
846 defClone->setName( friendlyName );
850 if ( !mParameterComponents.value( defClone->name() ).comment()->description().isEmpty() )
852 const QStringList parts = mParameterComponents.value( defClone->name() ).comment()->description().split( QStringLiteral(
"\n" ) );
853 for (
const QString &part : parts )
855 lines << indent + indent + QStringLiteral(
"# %1" ).arg( part );
862 lines << indent + indent + QStringLiteral(
"param = %1" ).arg( defClone->asPythonString() );
863 lines << indent + indent + QStringLiteral(
"param.setFlags(param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)" );
864 lines << indent + indent + QStringLiteral(
"self.addParameter(param)" );
868 lines << indent + indent + QStringLiteral(
"self.addParameter(%1)" ).arg( defClone->asPythonString() );
874 lines << indent + QStringLiteral(
"def processAlgorithm(self, parameters: dict[str, Any], context: QgsProcessingContext, model_feedback: QgsProcessingFeedback) -> dict[str, Any]:" );
875 currentIndent = indent + indent;
877 lines << currentIndent + QStringLiteral(
"# Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the" );
878 lines << currentIndent + QStringLiteral(
"# overall progress through the model" );
879 lines << currentIndent + QStringLiteral(
"feedback = QgsProcessingMultiStepFeedback(%1, model_feedback)" ).arg( totalSteps );
887 QMap< QString, QgsProcessingModelParameter >::const_iterator paramIt = mParameterComponents.constBegin();
888 for ( ; paramIt != mParameterComponents.constEnd(); ++paramIt )
890 QString name = paramIt.value().parameterName();
891 if ( parameterDefinition( name ) )
894 params.insert( name, parameterDefinition( name )->valueAsPythonString( parameterDefinition( name )->defaultValue(), context ) );
898 if ( !params.isEmpty() )
900 lines << QStringLiteral(
"parameters = {" );
901 for (
auto it = params.constBegin(); it != params.constEnd(); ++it )
903 lines << QStringLiteral(
" '%1':%2," ).arg( it.key(), it.value() );
905 lines << QStringLiteral(
"}" )
909 lines << QStringLiteral(
"context = QgsProcessingContext()" )
910 << QStringLiteral(
"context.setProject(QgsProject.instance())" )
911 << QStringLiteral(
"feedback = QgsProcessingFeedback()" )
920 lines << currentIndent + QStringLiteral(
"results = {}" );
921 lines << currentIndent + QStringLiteral(
"outputs = {}" );
924 QSet< QString > executed;
925 bool executedAlg =
true;
927 while ( executedAlg && executed.count() < toExecute.count() )
930 const auto constToExecute = toExecute;
931 for (
const QString &childId : constToExecute )
933 if ( executed.contains( childId ) )
936 bool canExecute =
true;
937 const auto constDependsOnChildAlgorithms = dependsOnChildAlgorithms( childId );
938 for (
const QString &dependency : constDependsOnChildAlgorithms )
940 if ( !executed.contains( dependency ) )
952 const QgsProcessingModelChildAlgorithm &child = mChildAlgorithms[ childId ];
959 if ( def->isDestination() )
964 bool isFinalOutput =
false;
965 QMap<QString, QgsProcessingModelOutput> outputs = child.modelOutputs();
966 QMap<QString, QgsProcessingModelOutput>::const_iterator outputIt = outputs.constBegin();
967 for ( ; outputIt != outputs.constEnd(); ++outputIt )
969 if ( outputIt->childOutputName() == destParam->
name() )
971 QString paramName = child.childId() +
':' + outputIt.key();
972 paramName = friendlyOutputNames.value( paramName, paramName );
973 childParams.insert( destParam->
name(), QStringLiteral(
"parameters['%1']" ).arg( paramName ) );
974 isFinalOutput =
true;
979 if ( !isFinalOutput )
984 bool required =
true;
987 required = childOutputIsRequired( child.childId(), destParam->
name() );
993 childParams.insert( destParam->
name(), QStringLiteral(
"QgsProcessing.TEMPORARY_OUTPUT" ) );
999 lines << child.asPythonCode( outputType, childParams, currentIndent.size(), indentSize, friendlyChildNames, friendlyOutputNames );
1001 if ( currentStep < totalSteps )
1004 lines << currentIndent + QStringLiteral(
"feedback.setCurrentStep(%1)" ).arg( currentStep );
1005 lines << currentIndent + QStringLiteral(
"if feedback.isCanceled():" );
1006 lines << currentIndent + indent + QStringLiteral(
"return {}" );
1009 executed.insert( childId );
1013 switch ( outputType )
1016 lines << currentIndent + QStringLiteral(
"return results" );
1020 lines << indent + QStringLiteral(
"def name(self) -> str:" );
1021 lines << indent + indent + QStringLiteral(
"return '%1'" ).arg( mModelName );
1023 lines << indent + QStringLiteral(
"def displayName(self) -> str:" );
1024 lines << indent + indent + QStringLiteral(
"return '%1'" ).arg( mModelName );
1028 lines << indent + QStringLiteral(
"def group(self) -> str:" );
1029 lines << indent + indent + QStringLiteral(
"return '%1'" ).arg( mModelGroup );
1031 lines << indent + QStringLiteral(
"def groupId(self) -> str:" );
1032 lines << indent + indent + QStringLiteral(
"return '%1'" ).arg( mModelGroupId );
1036 if ( !shortHelpString().isEmpty() )
1038 lines << indent + QStringLiteral(
"def shortHelpString(self) -> str:" );
1039 lines << indent + indent + QStringLiteral(
"return \"\"\"%1\"\"\"" ).arg( shortHelpString() );
1042 if ( !helpUrl().isEmpty() )
1044 lines << indent + QStringLiteral(
"def helpUrl(self) -> str:" );
1045 lines << indent + indent + QStringLiteral(
"return '%1'" ).arg( helpUrl() );
1050 lines << indent + QStringLiteral(
"def createInstance(self):" );
1051 lines << indent + indent + QStringLiteral(
"return self.__class__()" );
1054 static QMap< QString, QString > sAdditionalImports
1056 { QStringLiteral(
"QgsCoordinateReferenceSystem" ), QStringLiteral(
"from qgis.core import QgsCoordinateReferenceSystem" ) },
1057 { QStringLiteral(
"QgsExpression" ), QStringLiteral(
"from qgis.core import QgsExpression" ) },
1058 { QStringLiteral(
"QgsRectangle" ), QStringLiteral(
"from qgis.core import QgsRectangle" ) },
1059 { QStringLiteral(
"QgsReferencedRectangle" ), QStringLiteral(
"from qgis.core import QgsReferencedRectangle" ) },
1060 { QStringLiteral(
"QgsPoint" ), QStringLiteral(
"from qgis.core import QgsPoint" ) },
1061 { QStringLiteral(
"QgsReferencedPoint" ), QStringLiteral(
"from qgis.core import QgsReferencedPoint" ) },
1062 { QStringLiteral(
"QgsProperty" ), QStringLiteral(
"from qgis.core import QgsProperty" ) },
1063 { QStringLiteral(
"QgsRasterLayer" ), QStringLiteral(
"from qgis.core import QgsRasterLayer" ) },
1064 { QStringLiteral(
"QgsMeshLayer" ), QStringLiteral(
"from qgis.core import QgsMeshLayer" ) },
1065 { QStringLiteral(
"QgsVectorLayer" ), QStringLiteral(
"from qgis.core import QgsVectorLayer" ) },
1066 { QStringLiteral(
"QgsMapLayer" ), QStringLiteral(
"from qgis.core import QgsMapLayer" ) },
1067 { QStringLiteral(
"QgsProcessingFeatureSourceDefinition" ), QStringLiteral(
"from qgis.core import QgsProcessingFeatureSourceDefinition" ) },
1068 { QStringLiteral(
"QgsPointXY" ), QStringLiteral(
"from qgis.core import QgsPointXY" ) },
1069 { QStringLiteral(
"QgsReferencedPointXY" ), QStringLiteral(
"from qgis.core import QgsReferencedPointXY" ) },
1070 { QStringLiteral(
"QgsGeometry" ), QStringLiteral(
"from qgis.core import QgsGeometry" ) },
1071 { QStringLiteral(
"QgsProcessingOutputLayerDefinition" ), QStringLiteral(
"from qgis.core import QgsProcessingOutputLayerDefinition" ) },
1072 { QStringLiteral(
"QColor" ), QStringLiteral(
"from qgis.PyQt.QtGui import QColor" ) },
1073 { QStringLiteral(
"QDateTime" ), QStringLiteral(
"from qgis.PyQt.QtCore import QDateTime" ) },
1074 { QStringLiteral(
"QDate" ), QStringLiteral(
"from qgis.PyQt.QtCore import QDate" ) },
1075 { QStringLiteral(
"QTime" ), QStringLiteral(
"from qgis.PyQt.QtCore import QTime" ) },
1078 for (
auto it = sAdditionalImports.constBegin(); it != sAdditionalImports.constEnd(); ++it )
1080 if ( importLines.contains( it.value() ) )
1087 for (
const QString &line : std::as_const( lines ) )
1089 if ( line.contains( it.key() ) )
1097 importLines << it.value();
1101 lines = fileDocString + importLines + lines;
1110QMap<QString, QgsProcessingModelAlgorithm::VariableDefinition> QgsProcessingModelAlgorithm::variablesForChildAlgorithm(
const QString &childId,
QgsProcessingContext *context,
const QVariantMap &modelParameters,
const QVariantMap &results )
const
1112 QMap<QString, QgsProcessingModelAlgorithm::VariableDefinition> variables;
1114 auto safeName = [](
const QString & name )->QString
1117 const thread_local QRegularExpression safeNameRe( QStringLiteral(
"[\\s'\"\\(\\):\\.]" ) );
1118 return s.replace( safeNameRe, QStringLiteral(
"_" ) );
1155 for (
const QgsProcessingModelChildParameterSource &source : std::as_const( sources ) )
1159 QString description;
1160 switch ( source.source() )
1164 name = source.parameterName();
1165 value = modelParameters.value( source.parameterName() );
1166 description = parameterDefinition( source.parameterName() )->description();
1171 const QgsProcessingModelChildAlgorithm &child = mChildAlgorithms.value( source.outputChildId() );
1172 name = QStringLiteral(
"%1_%2" ).arg( child.description().isEmpty() ?
1173 source.outputChildId() : child.description(), source.outputName() );
1176 description = QObject::tr(
"Output '%1' from algorithm '%2'" ).arg( alg->outputDefinition( source.outputName() )->description(),
1177 child.description() );
1179 value = results.value( source.outputChildId() ).toMap().value( source.outputName() );
1189 variables.insert( safeName( name ), VariableDefinition( value, source, description ) );
1193 sources = availableSourcesForChild( childId, QStringList()
1200 for (
const QgsProcessingModelChildParameterSource &source : std::as_const( sources ) )
1204 QString description;
1206 switch ( source.source() )
1210 name = source.parameterName();
1211 value = modelParameters.value( source.parameterName() );
1212 description = parameterDefinition( source.parameterName() )->description();
1217 const QgsProcessingModelChildAlgorithm &child = mChildAlgorithms.value( source.outputChildId() );
1218 name = QStringLiteral(
"%1_%2" ).arg( child.description().isEmpty() ?
1219 source.outputChildId() : child.description(), source.outputName() );
1220 value = results.value( source.outputChildId() ).toMap().value( source.outputName() );
1223 description = QObject::tr(
"Output '%1' from algorithm '%2'" ).arg( alg->outputDefinition( source.outputName() )->description(),
1224 child.description() );
1237 if ( value.userType() == qMetaTypeId<QgsProcessingOutputLayerDefinition>() )
1240 value = fromVar.
sink;
1241 if ( value.userType() == qMetaTypeId<QgsProperty>() && context )
1249 layer = qobject_cast< QgsMapLayer * >( qvariant_cast<QObject *>( value ) );
1254 variables.insert( safeName( name ), VariableDefinition( layer ? QVariant::fromValue(
QgsWeakMapLayerPointer( layer ) ) : QVariant(), source, description ) );
1255 variables.insert( safeName( QStringLiteral(
"%1_minx" ).arg( name ) ), VariableDefinition( layer ? layer->
extent().
xMinimum() : QVariant(), source, QObject::tr(
"Minimum X of %1" ).arg( description ) ) );
1256 variables.insert( safeName( QStringLiteral(
"%1_miny" ).arg( name ) ), VariableDefinition( layer ? layer->
extent().
yMinimum() : QVariant(), source, QObject::tr(
"Minimum Y of %1" ).arg( description ) ) );
1257 variables.insert( safeName( QStringLiteral(
"%1_maxx" ).arg( name ) ), VariableDefinition( layer ? layer->
extent().
xMaximum() : QVariant(), source, QObject::tr(
"Maximum X of %1" ).arg( description ) ) );
1258 variables.insert( safeName( QStringLiteral(
"%1_maxy" ).arg( name ) ), VariableDefinition( layer ? layer->
extent().
yMaximum() : QVariant(), source, QObject::tr(
"Maximum Y of %1" ).arg( description ) ) );
1261 sources = availableSourcesForChild( childId, QStringList()
1263 for (
const QgsProcessingModelChildParameterSource &source : std::as_const( sources ) )
1267 QString description;
1269 switch ( source.source() )
1273 name = source.parameterName();
1274 value = modelParameters.value( source.parameterName() );
1275 description = parameterDefinition( source.parameterName() )->description();
1280 const QgsProcessingModelChildAlgorithm &child = mChildAlgorithms.value( source.outputChildId() );
1281 name = QStringLiteral(
"%1_%2" ).arg( child.description().isEmpty() ?
1282 source.outputChildId() : child.description(), source.outputName() );
1283 value = results.value( source.outputChildId() ).toMap().value( source.outputName() );
1286 description = QObject::tr(
"Output '%1' from algorithm '%2'" ).arg( alg->outputDefinition( source.outputName() )->description(),
1287 child.description() );
1301 if ( value.userType() == qMetaTypeId<QgsProcessingFeatureSourceDefinition>() )
1306 else if ( value.userType() == qMetaTypeId<QgsProcessingOutputLayerDefinition>() )
1309 value = fromVar.
sink;
1310 if ( context && value.userType() == qMetaTypeId<QgsProperty>() )
1315 if (
QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( qvariant_cast<QObject *>( value ) ) )
1317 featureSource = layer;
1319 if ( context && !featureSource )
1325 variables.insert( safeName( name ), VariableDefinition( value, source, description ) );
1326 variables.insert( safeName( QStringLiteral(
"%1_minx" ).arg( name ) ), VariableDefinition( featureSource ? featureSource->
sourceExtent().
xMinimum() : QVariant(), source, QObject::tr(
"Minimum X of %1" ).arg( description ) ) );
1327 variables.insert( safeName( QStringLiteral(
"%1_miny" ).arg( name ) ), VariableDefinition( featureSource ? featureSource->
sourceExtent().
yMinimum() : QVariant(), source, QObject::tr(
"Minimum Y of %1" ).arg( description ) ) );
1328 variables.insert( safeName( QStringLiteral(
"%1_maxx" ).arg( name ) ), VariableDefinition( featureSource ? featureSource->
sourceExtent().
xMaximum() : QVariant(), source, QObject::tr(
"Maximum X of %1" ).arg( description ) ) );
1329 variables.insert( safeName( QStringLiteral(
"%1_maxy" ).arg( name ) ), VariableDefinition( featureSource ? featureSource->
sourceExtent().
yMaximum() : QVariant(), source, QObject::tr(
"Maximum Y of %1" ).arg( description ) ) );
1335QgsExpressionContextScope *QgsProcessingModelAlgorithm::createExpressionContextScopeForChildAlgorithm(
const QString &childId,
QgsProcessingContext &context,
const QVariantMap &modelParameters,
const QVariantMap &results )
const
1337 auto scope = std::make_unique<QgsExpressionContextScope>( QStringLiteral(
"algorithm_inputs" ) );
1338 QMap< QString, QgsProcessingModelAlgorithm::VariableDefinition> variables = variablesForChildAlgorithm( childId, &context, modelParameters, results );
1339 QMap< QString, QgsProcessingModelAlgorithm::VariableDefinition>::const_iterator varIt = variables.constBegin();
1340 for ( ; varIt != variables.constEnd(); ++varIt )
1344 return scope.release();
1347QgsProcessingModelChildParameterSources QgsProcessingModelAlgorithm::availableSourcesForChild(
const QString &childId,
const QgsProcessingParameterDefinition *param )
const
1351 return QgsProcessingModelChildParameterSources();
1355QgsProcessingModelChildParameterSources QgsProcessingModelAlgorithm::availableSourcesForChild(
const QString &childId,
const QStringList ¶meterTypes,
const QStringList &outputTypes,
const QList<int> &dataTypes )
const
1357 QgsProcessingModelChildParameterSources sources;
1360 QMap< QString, QgsProcessingModelParameter >::const_iterator paramIt = mParameterComponents.constBegin();
1361 for ( ; paramIt != mParameterComponents.constEnd(); ++paramIt )
1367 if ( parameterTypes.contains( def->
type() ) )
1369 if ( !dataTypes.isEmpty() )
1385 bool ok = sourceDef->
dataTypes().isEmpty();
1386 const auto constDataTypes = sourceDef->
dataTypes();
1387 for (
int type : constDataTypes )
1402 sources << QgsProcessingModelChildParameterSource::fromModelParameter( paramIt->parameterName() );
1406 QSet< QString > dependents;
1407 if ( !childId.isEmpty() )
1409 dependents = dependentChildAlgorithms( childId );
1410 dependents << childId;
1413 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
1414 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
1416 if ( dependents.contains( childIt->childId() ) )
1426 if ( outputTypes.contains( out->type() ) )
1428 if ( !dataTypes.isEmpty() )
1434 if ( !vectorOutputIsCompatibleType( dataTypes, vectorOut->
dataType() ) )
1441 sources << QgsProcessingModelChildParameterSource::fromChildOutput( childIt->childId(), out->name() );
1449QVariantMap QgsProcessingModelAlgorithm::helpContent()
const
1451 return mHelpContent;
1454void QgsProcessingModelAlgorithm::setHelpContent(
const QVariantMap &helpContent )
1456 mHelpContent = helpContent;
1459void QgsProcessingModelAlgorithm::setName(
const QString &name )
1464void QgsProcessingModelAlgorithm::setGroup(
const QString &group )
1466 mModelGroup = group;
1469bool QgsProcessingModelAlgorithm::validate( QStringList &issues )
const
1474 if ( mChildAlgorithms.empty() )
1477 issues << QObject::tr(
"Model does not contain any algorithms" );
1480 for (
auto it = mChildAlgorithms.constBegin(); it != mChildAlgorithms.constEnd(); ++it )
1482 QStringList childIssues;
1483 res = validateChildAlgorithm( it->childId(), childIssues ) && res;
1485 for (
const QString &issue : std::as_const( childIssues ) )
1487 issues << QStringLiteral(
"<b>%1</b>: %2" ).arg( it->description(), issue );
1493QMap<QString, QgsProcessingModelChildAlgorithm> QgsProcessingModelAlgorithm::childAlgorithms()
const
1495 return mChildAlgorithms;
1498void QgsProcessingModelAlgorithm::setParameterComponents(
const QMap<QString, QgsProcessingModelParameter> ¶meterComponents )
1500 mParameterComponents = parameterComponents;
1503void QgsProcessingModelAlgorithm::setParameterComponent(
const QgsProcessingModelParameter &component )
1505 mParameterComponents.insert( component.parameterName(), component );
1508QgsProcessingModelParameter &QgsProcessingModelAlgorithm::parameterComponent(
const QString &name )
1510 if ( !mParameterComponents.contains( name ) )
1512 QgsProcessingModelParameter &component = mParameterComponents[ name ];
1513 component.setParameterName( name );
1516 return mParameterComponents[ name ];
1519QList< QgsProcessingModelParameter > QgsProcessingModelAlgorithm::orderedParameters()
const
1521 QList< QgsProcessingModelParameter > res;
1522 QSet< QString > found;
1523 for (
const QString ¶meter : mParameterOrder )
1525 if ( mParameterComponents.contains( parameter ) )
1527 res << mParameterComponents.value( parameter );
1533 for (
auto it = mParameterComponents.constBegin(); it != mParameterComponents.constEnd(); ++it )
1535 if ( !found.contains( it.key() ) )
1543void QgsProcessingModelAlgorithm::setParameterOrder(
const QStringList &order )
1545 mParameterOrder = order;
1548QList<QgsProcessingModelOutput> QgsProcessingModelAlgorithm::orderedOutputs()
const
1550 QList< QgsProcessingModelOutput > res;
1551 QSet< QString > found;
1553 for (
const QString &output : mOutputOrder )
1555 bool foundOutput =
false;
1556 for (
auto it = mChildAlgorithms.constBegin(); it != mChildAlgorithms.constEnd(); ++it )
1558 const QMap<QString, QgsProcessingModelOutput> outputs = it.value().modelOutputs();
1559 for (
auto outputIt = outputs.constBegin(); outputIt != outputs.constEnd(); ++outputIt )
1561 if ( output == QStringLiteral(
"%1:%2" ).arg( outputIt->childId(), outputIt->childOutputName() ) )
1563 res << outputIt.value();
1565 found.insert( QStringLiteral(
"%1:%2" ).arg( outputIt->childId(), outputIt->childOutputName() ) );
1574 for (
auto it = mChildAlgorithms.constBegin(); it != mChildAlgorithms.constEnd(); ++it )
1576 const QMap<QString, QgsProcessingModelOutput> outputs = it.value().modelOutputs();
1577 for (
auto outputIt = outputs.constBegin(); outputIt != outputs.constEnd(); ++outputIt )
1579 if ( !found.contains( QStringLiteral(
"%1:%2" ).arg( outputIt->childId(), outputIt->childOutputName() ) ) )
1581 res << outputIt.value();
1589void QgsProcessingModelAlgorithm::setOutputOrder(
const QStringList &order )
1591 mOutputOrder = order;
1594QString QgsProcessingModelAlgorithm::outputGroup()
const
1596 return mOutputGroup;
1599void QgsProcessingModelAlgorithm::setOutputGroup(
const QString &group )
1601 mOutputGroup = group;
1604void QgsProcessingModelAlgorithm::updateDestinationParameters()
1607 QMutableListIterator<const QgsProcessingParameterDefinition *> it( mParameters );
1608 while ( it.hasNext() )
1618 qDeleteAll( mOutputs );
1622 QSet< QString > usedFriendlyNames;
1623 auto uniqueSafeName = [&usedFriendlyNames ](
const QString & name )->QString
1625 const QString base = safeName( name,
false );
1626 QString candidate = base;
1628 while ( usedFriendlyNames.contains( candidate ) )
1631 candidate = QStringLiteral(
"%1_%2" ).arg( base ).arg( i );
1633 usedFriendlyNames.insert( candidate );
1637 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
1638 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
1640 QMap<QString, QgsProcessingModelOutput> outputs = childIt->modelOutputs();
1641 QMap<QString, QgsProcessingModelOutput>::const_iterator outputIt = outputs.constBegin();
1642 for ( ; outputIt != outputs.constEnd(); ++outputIt )
1644 if ( !childIt->isActive() || !childIt->algorithm() )
1652 std::unique_ptr< QgsProcessingParameterDefinition > param( source->
clone() );
1656 if ( outputIt->isMandatory() )
1658 if ( mInternalVersion != InternalVersion::Version1 && !outputIt->description().isEmpty() )
1660 QString friendlyName = uniqueSafeName( outputIt->description() );
1661 param->
setName( friendlyName );
1665 param->
setName( outputIt->childId() +
':' + outputIt->name() );
1668 param->
metadata().insert( QStringLiteral(
"_modelChildId" ), outputIt->childId() );
1669 param->
metadata().insert( QStringLiteral(
"_modelChildOutputName" ), outputIt->name() );
1670 param->
metadata().insert( QStringLiteral(
"_modelChildProvider" ), childIt->algorithm()->provider() ? childIt->algorithm()->provider()->id() : QString() );
1676 if ( addParameter( param.release() ) && newDestParam )
1683 newDestParam->mOriginalProvider = provider;
1690void QgsProcessingModelAlgorithm::addGroupBox(
const QgsProcessingModelGroupBox &groupBox )
1692 mGroupBoxes.insert( groupBox.uuid(), groupBox );
1695QList<QgsProcessingModelGroupBox> QgsProcessingModelAlgorithm::groupBoxes()
const
1697 return mGroupBoxes.values();
1700void QgsProcessingModelAlgorithm::removeGroupBox(
const QString &uuid )
1702 mGroupBoxes.remove( uuid );
1705QVariant QgsProcessingModelAlgorithm::toVariant()
const
1708 map.insert( QStringLiteral(
"model_name" ), mModelName );
1709 map.insert( QStringLiteral(
"model_group" ), mModelGroup );
1710 map.insert( QStringLiteral(
"help" ), mHelpContent );
1711 map.insert( QStringLiteral(
"internal_version" ),
qgsEnumValueToKey( mInternalVersion ) );
1713 QVariantMap childMap;
1714 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
1715 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
1717 childMap.insert( childIt.key(), childIt.value().toVariant() );
1719 map.insert( QStringLiteral(
"children" ), childMap );
1721 QVariantMap paramMap;
1722 QMap< QString, QgsProcessingModelParameter >::const_iterator paramIt = mParameterComponents.constBegin();
1723 for ( ; paramIt != mParameterComponents.constEnd(); ++paramIt )
1725 paramMap.insert( paramIt.key(), paramIt.value().toVariant() );
1727 map.insert( QStringLiteral(
"parameters" ), paramMap );
1729 QVariantMap paramDefMap;
1734 map.insert( QStringLiteral(
"parameterDefinitions" ), paramDefMap );
1736 QVariantList groupBoxDefs;
1737 for (
auto it = mGroupBoxes.constBegin(); it != mGroupBoxes.constEnd(); ++it )
1739 groupBoxDefs.append( it.value().toVariant() );
1741 map.insert( QStringLiteral(
"groupBoxes" ), groupBoxDefs );
1743 map.insert( QStringLiteral(
"modelVariables" ), mVariables );
1745 map.insert( QStringLiteral(
"designerParameterValues" ), mDesignerParameterValues );
1747 map.insert( QStringLiteral(
"parameterOrder" ), mParameterOrder );
1748 map.insert( QStringLiteral(
"outputOrder" ), mOutputOrder );
1749 map.insert( QStringLiteral(
"outputGroup" ), mOutputGroup );
1754bool QgsProcessingModelAlgorithm::loadVariant(
const QVariant &model )
1756 QVariantMap map = model.toMap();
1758 mModelName = map.value( QStringLiteral(
"model_name" ) ).toString();
1759 mModelGroup = map.value( QStringLiteral(
"model_group" ) ).toString();
1760 mModelGroupId = map.value( QStringLiteral(
"model_group" ) ).toString();
1761 mHelpContent = map.value( QStringLiteral(
"help" ) ).toMap();
1763 mInternalVersion =
qgsEnumKeyToValue( map.value( QStringLiteral(
"internal_version" ) ).toString(), InternalVersion::Version1 );
1765 mVariables = map.value( QStringLiteral(
"modelVariables" ) ).toMap();
1766 mDesignerParameterValues = map.value( QStringLiteral(
"designerParameterValues" ) ).toMap();
1768 mParameterOrder = map.value( QStringLiteral(
"parameterOrder" ) ).toStringList();
1769 mOutputOrder = map.value( QStringLiteral(
"outputOrder" ) ).toStringList();
1770 mOutputGroup = map.value( QStringLiteral(
"outputGroup" ) ).toString();
1772 mChildAlgorithms.clear();
1773 QVariantMap childMap = map.value( QStringLiteral(
"children" ) ).toMap();
1774 QVariantMap::const_iterator childIt = childMap.constBegin();
1775 for ( ; childIt != childMap.constEnd(); ++childIt )
1777 QgsProcessingModelChildAlgorithm child;
1781 if ( !child.loadVariant( childIt.value() ) )
1784 mChildAlgorithms.insert( child.childId(), child );
1787 mParameterComponents.clear();
1788 QVariantMap paramMap = map.value( QStringLiteral(
"parameters" ) ).toMap();
1789 QVariantMap::const_iterator paramIt = paramMap.constBegin();
1790 for ( ; paramIt != paramMap.constEnd(); ++paramIt )
1792 QgsProcessingModelParameter param;
1793 if ( !param.loadVariant( paramIt.value().toMap() ) )
1796 mParameterComponents.insert( param.parameterName(), param );
1799 qDeleteAll( mParameters );
1800 mParameters.clear();
1801 QVariantMap paramDefMap = map.value( QStringLiteral(
"parameterDefinitions" ) ).toMap();
1803 auto addParam = [
this](
const QVariant & value )
1811 if ( param->name() == QLatin1String(
"VERBOSE_LOG" ) )
1815 param->setHelp( mHelpContent.value( param->name() ).toString() );
1818 addParameter( param.release() );
1822 QVariantMap map = value.toMap();
1823 QString type = map.value( QStringLiteral(
"parameter_type" ) ).toString();
1824 QString name = map.value( QStringLiteral(
"name" ) ).toString();
1826 QgsMessageLog::logMessage( QCoreApplication::translate(
"Processing",
"Could not load parameter %1 of type %2." ).arg( name, type ), QCoreApplication::translate(
"Processing",
"Processing" ) );
1830 QSet< QString > loadedParams;
1832 for (
const QString &name : std::as_const( mParameterOrder ) )
1834 if ( paramDefMap.contains( name ) )
1836 addParam( paramDefMap.value( name ) );
1837 loadedParams << name;
1841 QVariantMap::const_iterator paramDefIt = paramDefMap.constBegin();
1842 for ( ; paramDefIt != paramDefMap.constEnd(); ++paramDefIt )
1844 if ( !loadedParams.contains( paramDefIt.key() ) )
1845 addParam( paramDefIt.value() );
1848 mGroupBoxes.clear();
1849 const QVariantList groupBoxList = map.value( QStringLiteral(
"groupBoxes" ) ).toList();
1850 for (
const QVariant &groupBoxDef : groupBoxList )
1852 QgsProcessingModelGroupBox groupBox;
1853 groupBox.loadVariant( groupBoxDef.toMap() );
1854 mGroupBoxes.insert( groupBox.uuid(), groupBox );
1857 updateDestinationParameters();
1862bool QgsProcessingModelAlgorithm::vectorOutputIsCompatibleType(
const QList<int> &acceptableDataTypes,
Qgis::ProcessingSourceType outputType )
1867 return ( acceptableDataTypes.empty()
1868 || acceptableDataTypes.contains(
static_cast< int >( outputType ) )
1879void QgsProcessingModelAlgorithm::reattachAlgorithms()
const
1881 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
1882 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
1884 if ( !childIt->algorithm() )
1885 childIt->reattach();
1889bool QgsProcessingModelAlgorithm::toFile(
const QString &path )
const
1891 QDomDocument doc = QDomDocument( QStringLiteral(
"model" ) );
1893 doc.appendChild( elem );
1896 if ( file.open( QFile::WriteOnly | QFile::Truncate ) )
1898 QTextStream stream( &file );
1899 doc.save( stream, 2 );
1906bool QgsProcessingModelAlgorithm::fromFile(
const QString &path )
1911 if ( file.open( QFile::ReadOnly ) )
1913 if ( !doc.setContent( &file ) )
1924 return loadVariant( props );
1927void QgsProcessingModelAlgorithm::setChildAlgorithms(
const QMap<QString, QgsProcessingModelChildAlgorithm> &childAlgorithms )
1929 mChildAlgorithms = childAlgorithms;
1930 updateDestinationParameters();
1933void QgsProcessingModelAlgorithm::setChildAlgorithm(
const QgsProcessingModelChildAlgorithm &
algorithm )
1936 updateDestinationParameters();
1939QString QgsProcessingModelAlgorithm::addChildAlgorithm( QgsProcessingModelChildAlgorithm &
algorithm )
1941 if (
algorithm.childId().isEmpty() || mChildAlgorithms.contains(
algorithm.childId() ) )
1945 updateDestinationParameters();
1949QgsProcessingModelChildAlgorithm &QgsProcessingModelAlgorithm::childAlgorithm(
const QString &childId )
1951 return mChildAlgorithms[ childId ];
1954bool QgsProcessingModelAlgorithm::removeChildAlgorithm(
const QString &
id )
1956 if ( !dependentChildAlgorithms(
id ).isEmpty() )
1959 mChildAlgorithms.remove(
id );
1960 updateDestinationParameters();
1964void QgsProcessingModelAlgorithm::deactivateChildAlgorithm(
const QString &
id )
1966 const auto constDependentChildAlgorithms = dependentChildAlgorithms(
id );
1967 for (
const QString &child : constDependentChildAlgorithms )
1969 childAlgorithm( child ).setActive(
false );
1971 childAlgorithm(
id ).setActive(
false );
1972 updateDestinationParameters();
1975bool QgsProcessingModelAlgorithm::activateChildAlgorithm(
const QString &
id )
1977 const auto constDependsOnChildAlgorithms = dependsOnChildAlgorithms(
id );
1978 for (
const QString &child : constDependsOnChildAlgorithms )
1980 if ( !childAlgorithm( child ).isActive() )
1983 childAlgorithm(
id ).setActive(
true );
1984 updateDestinationParameters();
1990 if ( addParameter( definition ) )
1991 mParameterComponents.insert( definition->
name(), component );
1996 removeParameter( definition->
name() );
1997 addParameter( definition );
2000void QgsProcessingModelAlgorithm::removeModelParameter(
const QString &name )
2002 removeParameter( name );
2003 mParameterComponents.remove( name );
2006void QgsProcessingModelAlgorithm::changeParameterName(
const QString &oldName,
const QString &newName )
2011 auto replaceExpressionVariable = [oldName, newName, &expressionContext](
const QString & expressionString ) -> std::tuple< bool, QString >
2014 expression.prepare( &expressionContext );
2015 QSet<QString> variables = expression.referencedVariables();
2016 if ( variables.contains( oldName ) )
2018 QString newExpression = expressionString;
2019 newExpression.replace( QStringLiteral(
"@%1" ).arg( oldName ), QStringLiteral(
"@%2" ).arg( newName ) );
2020 return {
true, newExpression };
2022 return {
false, QString() };
2025 QMap< QString, QgsProcessingModelChildAlgorithm >::iterator childIt = mChildAlgorithms.begin();
2026 for ( ; childIt != mChildAlgorithms.end(); ++childIt )
2028 bool changed =
false;
2029 QMap<QString, QgsProcessingModelChildParameterSources> childParams = childIt->parameterSources();
2030 QMap<QString, QgsProcessingModelChildParameterSources>::iterator paramIt = childParams.begin();
2031 for ( ; paramIt != childParams.end(); ++paramIt )
2033 QList< QgsProcessingModelChildParameterSource > &value = paramIt.value();
2034 for (
auto valueIt = value.begin(); valueIt != value.end(); ++valueIt )
2036 switch ( valueIt->source() )
2040 if ( valueIt->parameterName() == oldName )
2042 valueIt->setParameterName( newName );
2050 bool updatedExpression =
false;
2051 QString newExpression;
2052 std::tie( updatedExpression, newExpression ) = replaceExpressionVariable( valueIt->expression() );
2053 if ( updatedExpression )
2055 valueIt->setExpression( newExpression );
2063 if ( valueIt->staticValue().userType() == qMetaTypeId<QgsProperty>() )
2068 bool updatedExpression =
false;
2069 QString newExpression;
2070 std::tie( updatedExpression, newExpression ) = replaceExpressionVariable( property.expressionString() );
2071 if ( updatedExpression )
2073 property.setExpressionString( newExpression );
2074 valueIt->setStaticValue( property );
2090 childIt->setParameterSources( childParams );
2094bool QgsProcessingModelAlgorithm::childAlgorithmsDependOnParameter(
const QString &name )
const
2096 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
2097 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
2100 QMap<QString, QgsProcessingModelChildParameterSources> childParams = childIt->parameterSources();
2101 QMap<QString, QgsProcessingModelChildParameterSources>::const_iterator paramIt = childParams.constBegin();
2102 for ( ; paramIt != childParams.constEnd(); ++paramIt )
2104 const auto constValue = paramIt.value();
2105 for (
const QgsProcessingModelChildParameterSource &source : constValue )
2108 && source.parameterName() == name )
2118bool QgsProcessingModelAlgorithm::otherParametersDependOnParameter(
const QString &name )
const
2120 const auto constMParameters = mParameters;
2123 if ( def->
name() == name )
2132QMap<QString, QgsProcessingModelParameter> QgsProcessingModelAlgorithm::parameterComponents()
const
2134 return mParameterComponents;
2137void QgsProcessingModelAlgorithm::dependentChildAlgorithmsRecursive(
const QString &childId, QSet<QString> &depends,
const QString &branch )
const
2139 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
2140 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
2142 if ( depends.contains( childIt->childId() ) )
2146 const QList< QgsProcessingModelChildDependency > constDependencies = childIt->dependencies();
2147 bool hasDependency =
false;
2148 for (
const QgsProcessingModelChildDependency &dep : constDependencies )
2150 if ( dep.childId == childId && ( branch.isEmpty() || dep.conditionalBranch == branch ) )
2152 hasDependency =
true;
2157 if ( hasDependency )
2159 depends.insert( childIt->childId() );
2160 dependentChildAlgorithmsRecursive( childIt->childId(), depends, branch );
2165 QMap<QString, QgsProcessingModelChildParameterSources> childParams = childIt->parameterSources();
2166 QMap<QString, QgsProcessingModelChildParameterSources>::const_iterator paramIt = childParams.constBegin();
2167 for ( ; paramIt != childParams.constEnd(); ++paramIt )
2169 const auto constValue = paramIt.value();
2170 for (
const QgsProcessingModelChildParameterSource &source : constValue )
2173 && source.outputChildId() == childId )
2175 depends.insert( childIt->childId() );
2176 dependentChildAlgorithmsRecursive( childIt->childId(), depends, branch );
2184QSet<QString> QgsProcessingModelAlgorithm::dependentChildAlgorithms(
const QString &childId,
const QString &conditionalBranch )
const
2186 QSet< QString > algs;
2190 algs.insert( childId );
2192 dependentChildAlgorithmsRecursive( childId, algs, conditionalBranch );
2195 algs.remove( childId );
2201void QgsProcessingModelAlgorithm::dependsOnChildAlgorithmsRecursive(
const QString &childId, QSet< QString > &depends )
const
2203 const QgsProcessingModelChildAlgorithm &alg = mChildAlgorithms.value( childId );
2206 const QList< QgsProcessingModelChildDependency > constDependencies = alg.dependencies();
2207 for (
const QgsProcessingModelChildDependency &val : constDependencies )
2209 if ( !depends.contains( val.childId ) )
2211 depends.insert( val.childId );
2212 dependsOnChildAlgorithmsRecursive( val.childId, depends );
2217 QMap<QString, QgsProcessingModelChildParameterSources> childParams = alg.parameterSources();
2218 QMap<QString, QgsProcessingModelChildParameterSources>::const_iterator paramIt = childParams.constBegin();
2219 for ( ; paramIt != childParams.constEnd(); ++paramIt )
2221 const auto constValue = paramIt.value();
2222 for (
const QgsProcessingModelChildParameterSource &source : constValue )
2224 switch ( source.source() )
2227 if ( !depends.contains( source.outputChildId() ) )
2229 depends.insert( source.outputChildId() );
2230 dependsOnChildAlgorithmsRecursive( source.outputChildId(), depends );
2237 const QSet<QString> vars = exp.referencedVariables();
2242 const QMap<QString, QgsProcessingModelAlgorithm::VariableDefinition> availableVariables = variablesForChildAlgorithm( childId );
2243 for (
auto childVarIt = availableVariables.constBegin(); childVarIt != availableVariables.constEnd(); ++childVarIt )
2249 if ( !vars.contains( childVarIt.key() ) || depends.contains( childVarIt->source.outputChildId() ) )
2253 depends.insert( childVarIt->source.outputChildId() );
2254 dependsOnChildAlgorithmsRecursive( childVarIt->source.outputChildId(), depends );
2269QSet< QString > QgsProcessingModelAlgorithm::dependsOnChildAlgorithms(
const QString &childId )
const
2271 QSet< QString > algs;
2275 algs.insert( childId );
2277 dependsOnChildAlgorithmsRecursive( childId, algs );
2280 algs.remove( childId );
2285QList<QgsProcessingModelChildDependency> QgsProcessingModelAlgorithm::availableDependenciesForChildAlgorithm(
const QString &childId )
const
2287 QSet< QString > dependent;
2288 if ( !childId.isEmpty() )
2290 dependent.unite( dependentChildAlgorithms( childId ) );
2291 dependent.insert( childId );
2294 QList<QgsProcessingModelChildDependency> res;
2295 for (
auto it = mChildAlgorithms.constBegin(); it != mChildAlgorithms.constEnd(); ++it )
2297 if ( !dependent.contains( it->childId() ) )
2300 bool hasBranches =
false;
2301 if ( it->algorithm() )
2309 QgsProcessingModelChildDependency alg;
2310 alg.childId = it->childId();
2311 alg.conditionalBranch = def->
name();
2319 QgsProcessingModelChildDependency alg;
2320 alg.childId = it->childId();
2328bool QgsProcessingModelAlgorithm::validateChildAlgorithm(
const QString &childId, QStringList &issues )
const
2331 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constFind( childId );
2332 if ( childIt != mChildAlgorithms.constEnd() )
2334 if ( !childIt->algorithm() )
2336 issues << QObject::tr(
"Algorithm is not available: <i>%1</i>" ).arg( childIt->algorithmId() );
2345 if ( childIt->parameterSources().contains( def->
name() ) )
2348 const QList< QgsProcessingModelChildParameterSource > sources = childIt->parameterSources().value( def->
name() );
2349 for (
const QgsProcessingModelChildParameterSource &source : sources )
2351 switch ( source.source() )
2357 issues << QObject::tr(
"Value for <i>%1</i> is not acceptable for this parameter" ).arg( def->
name() );
2362 if ( !parameterComponents().contains( source.parameterName() ) )
2365 issues << QObject::tr(
"Model input <i>%1</i> used for parameter <i>%2</i> does not exist" ).arg( source.parameterName(), def->
name() );
2370 if ( !childAlgorithms().contains( source.outputChildId() ) )
2373 issues << QObject::tr(
"Child algorithm <i>%1</i> used for parameter <i>%2</i> does not exist" ).arg( source.outputChildId(), def->
name() );
2395 issues << QObject::tr(
"Parameter <i>%1</i> is mandatory" ).arg( def->
name() );
2404 issues << QObject::tr(
"Invalid child ID: <i>%1</i>" ).arg( childId );
2409bool QgsProcessingModelAlgorithm::canExecute( QString *errorMessage )
const
2411 reattachAlgorithms();
2412 QMap< QString, QgsProcessingModelChildAlgorithm >::const_iterator childIt = mChildAlgorithms.constBegin();
2413 for ( ; childIt != mChildAlgorithms.constEnd(); ++childIt )
2415 if ( !childIt->algorithm() )
2419 *errorMessage = QObject::tr(
"The model you are trying to run contains an algorithm that is not available: <i>%1</i>" ).arg( childIt->algorithmId() );
2427QString QgsProcessingModelAlgorithm::asPythonCommand(
const QVariantMap ¶meters,
QgsProcessingContext &context )
const
2429 if ( mSourceFile.isEmpty() )
2444 QgsProcessingModelAlgorithm *alg =
new QgsProcessingModelAlgorithm();
2445 alg->loadVariant( toVariant() );
2446 alg->setProvider( provider() );
2447 alg->setSourceFilePath( sourceFilePath() );
2451QString QgsProcessingModelAlgorithm::safeName(
const QString &name,
bool capitalize )
2453 QString n = name.toLower().trimmed();
2454 const thread_local QRegularExpression rx( QStringLiteral(
"[^\\sa-z_A-Z0-9]" ) );
2455 n.replace( rx, QString() );
2456 const thread_local QRegularExpression rx2( QStringLiteral(
"^\\d*" ) );
2457 n.replace( rx2, QString() );
2459 n = n.replace(
' ',
'_' );
2463QVariantMap QgsProcessingModelAlgorithm::variables()
const
2468void QgsProcessingModelAlgorithm::setVariables(
const QVariantMap &variables )
2470 mVariables = variables;
2473QVariantMap QgsProcessingModelAlgorithm::designerParameterValues()
const
2475 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.