32#include <QtAlgorithms>
34#include "moc_qgslayoutatlas.cpp"
39 , mFilenameExpressionString( QStringLiteral(
"'output_'||@atlas_featurenumber" ) )
46 mLayout->setCustomProperty( QStringLiteral(
"singleFile" ),
true );
51 return QStringLiteral(
"atlas" );
61 return mLayout.data();
66 QDomElement atlasElem = document.createElement( QStringLiteral(
"Atlas" ) );
67 atlasElem.setAttribute( QStringLiteral(
"enabled" ), mEnabled ? QStringLiteral(
"1" ) : QStringLiteral(
"0" ) );
71 atlasElem.setAttribute( QStringLiteral(
"coverageLayer" ), mCoverageLayer.layerId );
72 atlasElem.setAttribute( QStringLiteral(
"coverageLayerName" ), mCoverageLayer.name );
73 atlasElem.setAttribute( QStringLiteral(
"coverageLayerSource" ), mCoverageLayer.source );
74 atlasElem.setAttribute( QStringLiteral(
"coverageLayerProvider" ), mCoverageLayer.provider );
78 atlasElem.setAttribute( QStringLiteral(
"coverageLayer" ), QString() );
81 if ( mLimitCoverageLayerRenderToCurrentFeature )
82 atlasElem.setAttribute( QStringLiteral(
"limitCoverageLayerRenderToCurrentFeature" ), QStringLiteral(
"1" ) );
84 atlasElem.setAttribute( QStringLiteral(
"hideCoverage" ), mHideCoverage ? QStringLiteral(
"1" ) : QStringLiteral(
"0" ) );
85 atlasElem.setAttribute( QStringLiteral(
"filenamePattern" ), mFilenameExpressionString );
86 atlasElem.setAttribute( QStringLiteral(
"pageNameExpression" ), mPageNameExpression );
88 atlasElem.setAttribute( QStringLiteral(
"sortFeatures" ), mSortFeatures ? QStringLiteral(
"1" ) : QStringLiteral(
"0" ) );
91 atlasElem.setAttribute( QStringLiteral(
"sortKey" ), mSortExpression );
92 atlasElem.setAttribute( QStringLiteral(
"sortAscending" ), mSortAscending ? QStringLiteral(
"1" ) : QStringLiteral(
"0" ) );
94 atlasElem.setAttribute( QStringLiteral(
"filterFeatures" ), mFilterFeatures ? QStringLiteral(
"1" ) : QStringLiteral(
"0" ) );
95 if ( mFilterFeatures )
97 atlasElem.setAttribute( QStringLiteral(
"featureFilter" ), mFilterExpression );
100 parentElement.appendChild( atlasElem );
107 mEnabled = atlasElem.attribute( QStringLiteral(
"enabled" ), QStringLiteral(
"0" ) ).toInt();
110 const QString layerId = atlasElem.attribute( QStringLiteral(
"coverageLayer" ) );
111 const QString layerName = atlasElem.attribute( QStringLiteral(
"coverageLayerName" ) );
112 const QString layerSource = atlasElem.attribute( QStringLiteral(
"coverageLayerSource" ) );
113 const QString layerProvider = atlasElem.attribute( QStringLiteral(
"coverageLayerProvider" ) );
115 mCoverageLayer =
QgsVectorLayerRef( layerId, layerName, layerSource, layerProvider );
116 mCoverageLayer.resolveWeakly( mLayout->project() );
117 mLayout->reportContext().setLayer( mCoverageLayer.get() );
119 mPageNameExpression = atlasElem.attribute( QStringLiteral(
"pageNameExpression" ), QString() );
121 setFilenameExpression( atlasElem.attribute( QStringLiteral(
"filenamePattern" ), QString() ), error );
123 mSortFeatures = atlasElem.attribute( QStringLiteral(
"sortFeatures" ), QStringLiteral(
"0" ) ).toInt();
124 mSortExpression = atlasElem.attribute( QStringLiteral(
"sortKey" ) );
125 mSortAscending = atlasElem.attribute( QStringLiteral(
"sortAscending" ), QStringLiteral(
"1" ) ).toInt();
126 mFilterFeatures = atlasElem.attribute( QStringLiteral(
"filterFeatures" ), QStringLiteral(
"0" ) ).toInt();
127 mFilterExpression = atlasElem.attribute( QStringLiteral(
"featureFilter" ) );
129 mLimitCoverageLayerRenderToCurrentFeature = atlasElem.attribute( QStringLiteral(
"limitCoverageLayerRenderToCurrentFeature" ), QStringLiteral(
"0" ) ).toInt();
131 mHideCoverage = atlasElem.attribute( QStringLiteral(
"hideCoverage" ), QStringLiteral(
"0" ) ).toInt();
151void QgsLayoutAtlas::removeLayers(
const QStringList &layers )
153 if ( !mCoverageLayer )
158 for (
const QString &layerId : layers )
160 if ( layerId == mCoverageLayer.layerId )
163 mCoverageLayer.setLayer(
nullptr );
172 if ( layer == mCoverageLayer.get() )
177 mCoverageLayer.setLayer( layer );
183 if ( mPageNameExpression == expression )
186 mPageNameExpression = expression;
192 if ( pageNumber < 0 || pageNumber >= mFeatureIds.count() )
195 return mFeatureIds.at( pageNumber ).second;
200 if ( mSortFeatures ==
enabled )
209 if ( mSortAscending == ascending )
212 mSortAscending = ascending;
218 if ( mSortExpression == expression )
221 mSortExpression = expression;
227 if ( mFilterFeatures == filtered )
230 mFilterFeatures = filtered;
237 const bool hasChanged = mFilterExpression != expression;
238 mFilterExpression = expression;
254class AtlasFeatureSorter
257 AtlasFeatureSorter( QgsLayoutAtlas::SorterKeys &keys,
bool ascending =
true )
259 , mAscending( ascending )
262 bool operator()(
const QPair< QgsFeatureId, QString > &id1,
const QPair< QgsFeatureId, QString > &id2 )
264 return mAscending ?
qgsVariantLessThan( mKeys.value( id1.first ), mKeys.value( id2.first ) )
269 QgsLayoutAtlas::SorterKeys &mKeys;
277 mCurrentFeatureNo = -1;
278 if ( !mCoverageLayer )
286 updateFilenameExpression( error );
293 mFilterParserError.clear();
294 if ( mFilterFeatures && !mFilterExpression.isEmpty() )
307#ifdef HAVE_SERVER_PYTHON_PLUGINS
308 if ( mLayout->renderContext().featureFilterProvider() )
312 if ( mLayout->renderContext().featureFilterProvider()->isFilterThreadSafe() )
314 mLayout->renderContext().featureFilterProvider()->filterFeatures( mCoverageLayer.get()->id(), req );
318 mLayout->renderContext().featureFilterProvider()->filterFeatures( mCoverageLayer.get(), req );
327 std::unique_ptr<QgsExpression> nameExpression;
328 if ( !mPageNameExpression.isEmpty() )
330 nameExpression = std::make_unique< QgsExpression >( mPageNameExpression );
331 if ( nameExpression->hasParserError() )
333 nameExpression.reset(
nullptr );
337 nameExpression->prepare( &expressionContext );
345 mFeatureKeys.clear();
348 if ( mSortFeatures && !mSortExpression.isEmpty() )
350 sortExpression = std::make_unique< QgsExpression >( mSortExpression );
366 if ( nameExpression )
368 const QVariant result = nameExpression->evaluate( &expressionContext );
369 if ( nameExpression->hasEvalError() )
373 pageName = result.toString();
376 mFeatureIds.push_back( qMakePair( feat.
id(), pageName ) );
380 const QVariant result =
sortExpression->evaluate( &expressionContext );
385 mFeatureKeys.insert( feat.
id(), result );
390 if ( !mFeatureKeys.isEmpty() )
393 std::sort( mFeatureIds.begin(), mFeatureIds.end(), sorter );
397 return mFeatureIds.size();
402 if ( !mCoverageLayer )
427 return mFeatureIds.size();
432 const QFileInfo fi( baseFilePath );
433 const QDir dir = fi.dir();
434 QString base = dir.filePath( mCurrentFilename );
435 if ( !extension.startsWith(
'.' ) )
443 const int newFeatureNo = mCurrentFeatureNo + 1;
444 if ( newFeatureNo >= mFeatureIds.size() )
449 return prepareForFeature( newFeatureNo );
454 const int newFeatureNo = mCurrentFeatureNo - 1;
455 if ( newFeatureNo < 0 )
460 return prepareForFeature( newFeatureNo );
465 return prepareForFeature( 0 );
470 return prepareForFeature( mFeatureIds.size() - 1 );
475 return prepareForFeature( feature );
481 auto it = mFeatureIds.constBegin();
482 for (
int currentIdx = 0; it != mFeatureIds.constEnd(); ++it, ++currentIdx )
484 if ( ( *it ).first == feature.
id() )
502 prepareForFeature( mCurrentFeatureNo );
508 if ( hide == mHideCoverage )
511 mHideCoverage = hide;
519 if ( limit == mLimitCoverageLayerRenderToCurrentFeature )
522 mLimitCoverageLayerRenderToCurrentFeature = limit;
529 const bool hasChanged = mFilenameExpressionString != pattern;
530 mFilenameExpressionString = pattern;
535 return updateFilenameExpression( errorString );
540 return mCurrentFilename;
553 if ( mCoverageLayer )
554 expressionContext.
appendScope( mCoverageLayer->createExpressionContextScope() );
556 if ( mLayout && mEnabled )
558 if ( mCurrentFeature.isValid() )
562 else if ( mCoverageLayer )
564 QgsFeature feature{ mCoverageLayer->fields() };
569 return expressionContext;
572bool QgsLayoutAtlas::updateFilenameExpression( QString &error )
574 if ( !mCoverageLayer )
580 bool evalResult {
true };
582 if ( !mFilenameExpressionString.isEmpty() )
600 evalResult = evalFeatureFilename( expressionContext );
605 error = mFilenameExpressionError;
614 mFilenameExpressionError.clear();
615 if ( !mFilenameExpressionString.isEmpty() )
627 mCurrentFilename = filenameRes.toString();
632bool QgsLayoutAtlas::prepareForFeature(
const int featureI )
634 if ( !mCoverageLayer )
639 if ( mFeatureIds.isEmpty() )
645 if ( featureI >= mFeatureIds.size() )
650 mCurrentFeatureNo = featureI;
653 if ( !mCoverageLayer->getFeatures( QgsFeatureRequest().setFilterFid( mFeatureIds[ featureI ].
first ) ).nextFeature( mCurrentFeature ) )
656 mLayout->reportContext().blockSignals(
true );
657 mLayout->reportContext().setLayer( mCoverageLayer.get() );
658 mLayout->reportContext().blockSignals(
false );
659 mLayout->reportContext().setFeature( mCurrentFeature );
665 if ( !evalFeatureFilename( expressionContext ) )
672 emit
messagePushed( tr(
"Atlas feature %1 of %2" ).arg( featureI + 1 ).arg( mFeatureIds.size() ) );
674 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