33#include <QtAlgorithms>
35#include "moc_qgslayoutatlas.cpp"
37using namespace Qt::StringLiterals;
42 , mFilenameExpressionString( u
"'output_'||@atlas_featurenumber"_s )
49 mLayout->setCustomProperty( u
"singleFile"_s,
true );
64 return mLayout.data();
69 QDomElement atlasElem = document.createElement( u
"Atlas"_s );
70 atlasElem.setAttribute( u
"enabled"_s, mEnabled ? u
"1"_s : u
"0"_s );
74 atlasElem.setAttribute( u
"coverageLayer"_s, mCoverageLayer.layerId );
75 atlasElem.setAttribute( u
"coverageLayerName"_s, mCoverageLayer.name );
76 atlasElem.setAttribute( u
"coverageLayerSource"_s, mCoverageLayer.source );
77 atlasElem.setAttribute( u
"coverageLayerProvider"_s, mCoverageLayer.provider );
81 atlasElem.setAttribute( u
"coverageLayer"_s, QString() );
84 if ( mLimitCoverageLayerRenderToCurrentFeature )
85 atlasElem.setAttribute( u
"limitCoverageLayerRenderToCurrentFeature"_s, u
"1"_s );
87 atlasElem.setAttribute( u
"hideCoverage"_s, mHideCoverage ? u
"1"_s : u
"0"_s );
88 atlasElem.setAttribute( u
"filenamePattern"_s, mFilenameExpressionString );
89 atlasElem.setAttribute( u
"pageNameExpression"_s, mPageNameExpression );
91 atlasElem.setAttribute( u
"sortFeatures"_s, mSortFeatures ? u
"1"_s : u
"0"_s );
94 atlasElem.setAttribute( u
"sortKey"_s, mSortExpression );
95 atlasElem.setAttribute( u
"sortAscending"_s, mSortAscending ? u
"1"_s : u
"0"_s );
97 atlasElem.setAttribute( u
"filterFeatures"_s, mFilterFeatures ? u
"1"_s : u
"0"_s );
98 if ( mFilterFeatures )
100 atlasElem.setAttribute( u
"featureFilter"_s, mFilterExpression );
103 parentElement.appendChild( atlasElem );
110 mEnabled = atlasElem.attribute( u
"enabled"_s, u
"0"_s ).toInt();
113 const QString layerId = atlasElem.attribute( u
"coverageLayer"_s );
114 const QString layerName = atlasElem.attribute( u
"coverageLayerName"_s );
115 const QString layerSource = atlasElem.attribute( u
"coverageLayerSource"_s );
116 const QString layerProvider = atlasElem.attribute( u
"coverageLayerProvider"_s );
118 mCoverageLayer =
QgsVectorLayerRef( layerId, layerName, layerSource, layerProvider );
119 mCoverageLayer.resolveWeakly( mLayout->project() );
120 mLayout->reportContext().setLayer( mCoverageLayer.get() );
122 mPageNameExpression = atlasElem.attribute( u
"pageNameExpression"_s, QString() );
126 mSortFeatures = atlasElem.attribute( u
"sortFeatures"_s, u
"0"_s ).toInt();
127 mSortExpression = atlasElem.attribute( u
"sortKey"_s );
128 mSortAscending = atlasElem.attribute( u
"sortAscending"_s, u
"1"_s ).toInt();
129 mFilterFeatures = atlasElem.attribute( u
"filterFeatures"_s, u
"0"_s ).toInt();
130 mFilterExpression = atlasElem.attribute( u
"featureFilter"_s );
132 mLimitCoverageLayerRenderToCurrentFeature = atlasElem.attribute( u
"limitCoverageLayerRenderToCurrentFeature"_s, u
"0"_s ).toInt();
134 mHideCoverage = atlasElem.attribute( u
"hideCoverage"_s, u
"0"_s ).toInt();
154void QgsLayoutAtlas::removeLayers(
const QStringList &layers )
156 if ( !mCoverageLayer )
161 for (
const QString &layerId : layers )
163 if ( layerId == mCoverageLayer.layerId )
166 mCoverageLayer.setLayer(
nullptr );
175 if ( layer == mCoverageLayer.get() )
180 mCoverageLayer.setLayer( layer );
186 if ( mPageNameExpression == expression )
189 mPageNameExpression = expression;
195 if ( pageNumber < 0 || pageNumber >= mFeatureIds.count() )
198 return mFeatureIds.at( pageNumber ).second;
203 if ( mSortFeatures ==
enabled )
212 if ( mSortAscending == ascending )
215 mSortAscending = ascending;
221 if ( mSortExpression == expression )
224 mSortExpression = expression;
230 if ( mFilterFeatures == filtered )
233 mFilterFeatures = filtered;
240 const bool hasChanged = mFilterExpression != expression;
241 mFilterExpression = expression;
257class AtlasFeatureSorter
260 AtlasFeatureSorter( QgsLayoutAtlas::SorterKeys &keys,
bool ascending =
true )
262 , mAscending( ascending )
265 bool operator()(
const QPair< QgsFeatureId, QString > &id1,
const QPair< QgsFeatureId, QString > &id2 )
267 return mAscending ?
qgsVariantLessThan( mKeys.value( id1.first ), mKeys.value( id2.first ) )
272 QgsLayoutAtlas::SorterKeys &mKeys;
280 mCurrentFeatureNo = -1;
281 if ( !mCoverageLayer )
289 updateFilenameExpression( error );
296 mFilterParserError.clear();
297 if ( mFilterFeatures && !mFilterExpression.isEmpty() )
310#ifdef HAVE_SERVER_PYTHON_PLUGINS
311 if ( mLayout->renderContext().featureFilterProvider() )
315 if ( mLayout->renderContext().featureFilterProvider()->isFilterThreadSafe() )
317 mLayout->renderContext().featureFilterProvider()->filterFeatures( mCoverageLayer.get()->id(), req );
321 mLayout->renderContext().featureFilterProvider()->filterFeatures( mCoverageLayer.get(), req );
330 std::unique_ptr<QgsExpression> nameExpression;
331 if ( !mPageNameExpression.isEmpty() )
333 nameExpression = std::make_unique< QgsExpression >( mPageNameExpression );
334 if ( nameExpression->hasParserError() )
336 nameExpression.reset(
nullptr );
340 nameExpression->prepare( &expressionContext );
348 mFeatureKeys.clear();
351 if ( mSortFeatures && !mSortExpression.isEmpty() )
353 sortExpression = std::make_unique< QgsExpression >( mSortExpression );
369 if ( nameExpression )
371 const QVariant result = nameExpression->evaluate( &expressionContext );
372 if ( nameExpression->hasEvalError() )
376 pageName = result.toString();
379 mFeatureIds.push_back( qMakePair( feat.
id(), pageName ) );
383 const QVariant result =
sortExpression->evaluate( &expressionContext );
388 mFeatureKeys.insert( feat.
id(), result );
393 if ( !mFeatureKeys.isEmpty() )
396 std::sort( mFeatureIds.begin(), mFeatureIds.end(), sorter );
400 return mFeatureIds.size();
405 if ( !mCoverageLayer )
430 return mFeatureIds.size();
435 const QFileInfo fi( baseFilePath );
436 const QDir dir = fi.dir();
437 QString base = dir.filePath( mCurrentFilename );
438 if ( !extension.startsWith(
'.' ) )
446 const int newFeatureNo = mCurrentFeatureNo + 1;
447 if ( newFeatureNo >= mFeatureIds.size() )
452 return prepareForFeature( newFeatureNo );
457 const int newFeatureNo = mCurrentFeatureNo - 1;
458 if ( newFeatureNo < 0 )
463 return prepareForFeature( newFeatureNo );
468 return prepareForFeature( 0 );
473 return prepareForFeature( mFeatureIds.size() - 1 );
478 return prepareForFeature( feature );
484 auto it = mFeatureIds.constBegin();
485 for (
int currentIdx = 0; it != mFeatureIds.constEnd(); ++it, ++currentIdx )
487 if ( ( *it ).first == feature.
id() )
505 prepareForFeature( mCurrentFeatureNo );
511 if ( hide == mHideCoverage )
514 mHideCoverage = hide;
522 if ( limit == mLimitCoverageLayerRenderToCurrentFeature )
525 mLimitCoverageLayerRenderToCurrentFeature = limit;
532 const bool hasChanged = mFilenameExpressionString != pattern;
533 mFilenameExpressionString = pattern;
538 return updateFilenameExpression( errorString );
543 return mCurrentFilename;
556 if ( mCoverageLayer )
557 expressionContext.
appendScope( mCoverageLayer->createExpressionContextScope() );
559 if ( mLayout && mEnabled )
561 if ( mCurrentFeature.isValid() )
565 else if ( mCoverageLayer )
567 QgsFeature feature{ mCoverageLayer->fields() };
572 return expressionContext;
575bool QgsLayoutAtlas::updateFilenameExpression( QString &error )
577 if ( !mCoverageLayer )
583 bool evalResult {
true };
585 if ( !mFilenameExpressionString.isEmpty() )
603 evalResult = evalFeatureFilename( expressionContext );
608 error = mFilenameExpressionError;
617 mFilenameExpressionError.clear();
618 if ( !mFilenameExpressionString.isEmpty() )
630 mCurrentFilename = filenameRes.toString();
635bool QgsLayoutAtlas::prepareForFeature(
const int featureI )
637 if ( !mCoverageLayer )
642 if ( mFeatureIds.isEmpty() )
648 if ( featureI >= mFeatureIds.size() )
653 mCurrentFeatureNo = featureI;
656 if ( !mCoverageLayer->getFeatures( QgsFeatureRequest().setFilterFid( mFeatureIds[ featureI ].
first ) ).nextFeature( mCurrentFeature ) )
659 mLayout->reportContext().blockSignals(
true );
660 mLayout->reportContext().setLayer( mCoverageLayer.get() );
661 mLayout->reportContext().blockSignals(
false );
662 mLayout->reportContext().setFeature( mCurrentFeature );
668 if ( !evalFeatureFilename( expressionContext ) )
675 emit
messagePushed( tr(
"Atlas feature %1 of %2" ).arg( featureI + 1 ).arg( mFeatureIds.size() ) );
677 return mCurrentFeature.isValid();
@ LimitCoverageLayerRenderToCurrentFeature
Limit coverage layer rendering to the current atlas feature.
@ HideCoverageLayer
Hide coverage layer in outputs.
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the scope.
static QgsExpressionContextScope * layoutScope(const QgsLayout *layout)
Creates a new scope which contains variables and functions relating to a QgsLayout layout.
static QgsExpressionContextScope * projectScope(const QgsProject *project)
Creates a new scope which contains variables and functions relating to a QGIS project.
static QgsExpressionContextScope * atlasScope(const QgsLayoutAtlas *atlas)
Creates a new scope which contains variables and functions relating to a QgsLayoutAtlas.
static QgsExpressionContextScope * globalScope()
Creates a new scope which contains variables and functions relating to the global QGIS context.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
QgsExpressionContextScope * lastScope()
Returns the last scope added to the context.
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
Handles parsing and evaluation of expressions (formerly called "search strings").
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
Wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
QgsFeatureRequest & setExpressionContext(const QgsExpressionContext &context)
Sets the expression context used to evaluate filter expressions.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
void setValid(bool validity)
Sets the validity of the feature.
QString nameForPage(int page) const
Returns the calculated name for a specified atlas page number.
QString sortExpression() const
Returns the expression (or field name) to use for sorting features.
bool writeXml(QDomElement &parentElement, QDomDocument &document, const QgsReadWriteContext &context) const override
Stores the objects's state in a DOM element.
QString filenameExpression() const
Returns the filename expression used for generating output filenames for each atlas page.
void toggled(bool enabled)
Emitted when atlas is enabled or disabled.
void setCoverageLayer(QgsVectorLayer *layer)
Sets the coverage layer to use for the atlas features.
bool beginRender() override
Called when rendering begins, before iteration commences.
bool setFilterExpression(const QString &expression, QString &errorString)
Sets the expression used for filtering features in the coverage layer.
void setSortAscending(bool ascending)
Sets whether features should be sorted in an ascending order.
bool seekTo(int feature)
Seeks to the specified feature number.
void featureChanged(const QgsFeature &feature)
Emitted when the current atlas feature changes.
void setEnabled(bool enabled)
Sets whether the atlas is enabled.
friend class AtlasFeatureSorter
void setPageNameExpression(const QString &expression)
Sets the expression (or field name) used for calculating the page name.
bool first()
Seeks to the first feature, returning false if no feature was found.
QString filterExpression() const
Returns the expression used for filtering features in the coverage layer.
QgsLayout * layout() override
Returns the layout associated with the iterator.
bool enabled() const
Returns whether the atlas generation is enabled.
bool setFilenameExpression(const QString &expression, QString &errorString)
Sets the filename expression used for generating output filenames for each atlas page.
QgsExpressionContext createExpressionContext() const override
This method needs to be reimplemented in all classes which implement this interface and return an exp...
void setLimitCoverageLayerRenderToCurrentFeature(bool limit)
Sets whether the rendering of the coverage layer should be limited to the current feature.
void setSortFeatures(bool enabled)
Sets whether features should be sorted in the atlas.
QString filePath(const QString &baseFilePath, const QString &extension) override
Returns the file path for the current feature, based on a specified base file path and extension.
QString currentFilename() const
Returns the current feature filename.
bool readXml(const QDomElement &element, const QDomDocument &document, const QgsReadWriteContext &context) override
Sets the objects's state from a DOM element.
bool last()
Seeks to the last feature, returning false if no feature was found.
QgsLayoutAtlas(QgsLayout *layout)
Constructor for new QgsLayoutAtlas.
int count() const override
Returns the number of features to iterate over.
void numberFeaturesChanged(int numFeatures)
Emitted when the number of features for the atlas changes.
void messagePushed(const QString &message)
Emitted when the atlas has an updated status bar message.
void setSortExpression(const QString &expression)
Sets the expression (or field name) to use for sorting features.
void coverageLayerChanged(QgsVectorLayer *layer)
Emitted when the coverage layer for the atlas changes.
void setFilterFeatures(bool filtered)
Sets whether features should be filtered in the coverage layer.
void renderBegun()
Emitted when atlas rendering has begun.
void renderEnded()
Emitted when atlas rendering has ended.
void changed()
Emitted when one of the atlas parameters changes.
bool previous()
Iterates to the previous feature, returning false if no previous feature exists.
void refreshCurrentFeature()
Refreshes the current atlas feature, by refetching its attributes from the vector layer provider.
bool endRender() override
Ends the render, performing any required cleanup tasks.
int updateFeatures()
Requeries the current atlas coverage layer and applies filtering and sorting.
QString stringType() const override
Returns the object type as a string.
void setHideCoverage(bool hide)
Sets whether the coverage layer should be hidden in map items in the layouts.
Base class for layouts, which can contain items such as maps, labels, scalebars, etc.
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).
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
void layersWillBeRemoved(const QStringList &layerIds)
Emitted when one or more layers are about to be removed from the registry.
A container for the context for various read/write operations on objects.
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
Represents a vector layer which manages a vector based dataset.
bool qgsVariantLessThan(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether the first is less than the second.
bool qgsVariantGreaterThan(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether the first is greater than the second.
#define Q_NOWARN_DEPRECATED_POP
#define Q_NOWARN_DEPRECATED_PUSH
_LayerRef< QgsVectorLayer > QgsVectorLayerRef