Make QgsProcessingAlgRunnerTask work correctly

It now safely can execute algorithms in background threads
without issues
This commit is contained in:
Nyall Dawson 2017-06-30 15:58:42 +10:00
parent e5b156b86a
commit e1184cd69a
3 changed files with 24 additions and 9 deletions

View File

@ -33,6 +33,15 @@ class QgsProcessingAlgRunnerTask : QgsTask
virtual void cancel();
signals:
void executed( bool successful, const QVariantMap &results );
%Docstring
Emitted when the algorithm has finished execution. If the algorithm completed
execution without errors then ``successful`` will be true. The ``results`` argument
contains the results reported by the algorithm.
%End
protected:
virtual bool run();

View File

@ -24,7 +24,6 @@
QgsProcessingAlgRunnerTask::QgsProcessingAlgRunnerTask( const QgsProcessingAlgorithm *algorithm, const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
: QgsTask( tr( "Running %1" ).arg( algorithm->name() ), QgsTask::CanCancel )
, mParameters( parameters )
, mContext( context )
, mFeedback( feedback )
, mAlgorithm( algorithm->create() )
@ -34,6 +33,8 @@ QgsProcessingAlgRunnerTask::QgsProcessingAlgRunnerTask( const QgsProcessingAlgor
mOwnedFeedback.reset( new QgsProcessingFeedback() );
mFeedback = mOwnedFeedback.get();
}
if ( !mAlgorithm->prepare( parameters, context, mFeedback ) )
cancel();
}
void QgsProcessingAlgRunnerTask::cancel()
@ -47,7 +48,7 @@ bool QgsProcessingAlgRunnerTask::run()
bool ok = false;
try
{
mResults = mAlgorithm->run( mParameters, mContext, mFeedback, &ok );
ok = mAlgorithm->runPrepared( mContext, mFeedback );
}
catch ( QgsProcessingException & )
{
@ -59,12 +60,9 @@ bool QgsProcessingAlgRunnerTask::run()
void QgsProcessingAlgRunnerTask::finished( bool result )
{
Q_UNUSED( result );
if ( !mResults.isEmpty() )
if ( result )
{
QgsMapLayer *layer = QgsProcessingUtils::mapLayerFromString( mResults.value( "OUTPUT_LAYER" ).toString(), mContext );
if ( layer )
{
mContext.project()->addMapLayer( mContext.temporaryLayerStore()->takeMapLayer( layer ) );
}
mResults = mAlgorithm->postProcess( mContext, mFeedback );
}
emit executed( result, mResults );
}

View File

@ -49,6 +49,15 @@ class CORE_EXPORT QgsProcessingAlgRunnerTask : public QgsTask
virtual void cancel() override;
signals:
/**
* Emitted when the algorithm has finished execution. If the algorithm completed
* execution without errors then \a successful will be true. The \a results argument
* contains the results reported by the algorithm.
*/
void executed( bool successful, const QVariantMap &results );
protected:
virtual bool run() override;
@ -56,7 +65,6 @@ class CORE_EXPORT QgsProcessingAlgRunnerTask : public QgsTask
private:
QVariantMap mParameters;
QVariantMap mResults;
QgsProcessingContext &mContext;
QgsProcessingFeedback *mFeedback = nullptr;