18 #include <QtAlgorithms> 34 : mComposition( composition )
36 , mHideCoverage( false )
37 , mFilenamePattern(
"'output_'||@atlas_featurenumber" )
38 , mCoverageLayer( nullptr )
39 , mSingleFile( false )
40 , mSortFeatures( false )
41 , mSortAscending( true )
42 , mCurrentFeatureNo( 0 )
43 , mFilterFeatures( false )
56 if ( enabled == mEnabled )
67 void QgsAtlasComposition::removeLayers(
const QStringList& layers )
69 if ( !mCoverageLayer )
74 Q_FOREACH (
const QString& layerId, layers )
76 if ( layerId == mCoverageLayer->
id() )
79 mCoverageLayer =
nullptr;
88 if ( layer == mCoverageLayer )
93 mCoverageLayer = layer;
99 if ( pageNumber < 0 || pageNumber >= mFeatureIds.
count() )
102 return mFeatureIds.
at( pageNumber ).second;
139 if ( !mCoverageLayer )
148 if ( mCoverageLayer )
151 if ( idx >= 0 && idx < fields.
count() )
153 mSortKeyAttributeName = fields[idx].name();
157 mSortKeyAttributeName =
"";
169 return mAscending ?
qgsVariantLessThan( mKeys.value( id1.first ), mKeys.value( id2.first ) )
182 if ( !mCoverageLayer )
189 updateFilenameExpression();
195 if ( mFilterFeatures && !mFeatureFilter.isEmpty() )
198 if ( filterExpression->hasParserError() )
200 mFilterParserError = filterExpression->parserErrorString();
207 mFilterParserError =
QString();
212 if ( !mPageNameExpression.isEmpty() )
215 if ( nameExpression->hasParserError() )
217 nameExpression.
reset(
nullptr );
219 nameExpression->prepare( &expressionContext );
226 mFeatureKeys.clear();
227 int sortIdx = mCoverageLayer->
fieldNameIndex( mSortKeyAttributeName );
234 if ( !nameExpression.
isNull() )
236 QVariant result = nameExpression->evaluate( &expressionContext );
237 if ( nameExpression->hasEvalError() )
244 mFeatureIds.
push_back( qMakePair( feat.
id(), pageName ) );
246 if ( mSortFeatures && sortIdx != -1 )
248 mFeatureKeys.insert( feat.
id(), feat.
attributes().
at( sortIdx ) );
253 if ( !mFeatureKeys.isEmpty() )
255 FieldSorter sorter( mFeatureKeys, mSortAscending );
256 qSort( mFeatureIds.begin(), mFeatureIds.end(), sorter );
268 return mFeatureIds.size();
278 if ( !mCoverageLayer )
286 if ( !featuresUpdated )
297 if ( !mCoverageLayer )
309 void QgsAtlasComposition::updateAtlasMaps()
313 mComposition->composerItems( maps );
328 return mFeatureIds.size();
333 int newFeatureNo = mCurrentFeatureNo + 1;
334 if ( newFeatureNo >= mFeatureIds.size() )
336 newFeatureNo = mFeatureIds.size() - 1;
344 int newFeatureNo = mCurrentFeatureNo - 1;
345 if ( newFeatureNo < 0 )
368 for ( ; it != mFeatureIds.
constEnd(); ++it, ++currentIdx )
370 if (( *it ).first == feat->
id() )
372 featureI = currentIdx;
393 if ( !mCoverageLayer )
398 if ( mFeatureIds.isEmpty() )
404 if ( featureI >= mFeatureIds.size() )
409 mCurrentFeatureNo = featureI;
412 mCoverageLayer->getFeatures(
QgsFeatureRequest().setFilterFid( mFeatureIds[ featureI ].first ) ).nextFeature( mCurrentFeature );
417 if ( !evalFeatureFilename( expressionContext ) )
423 mGeometryCache.clear();
427 if ( !mCurrentFeature.isValid() )
444 mComposition->composerItems( maps );
456 atlasMaps << currentMap;
467 computeExtent( atlasMaps[0] );
472 if (( *mit )->atlasDriven() )
503 if ( mTransformedFeatureBounds.isEmpty() )
507 computeExtent( map );
510 double xa1 = mTransformedFeatureBounds.xMinimum();
511 double xa2 = mTransformedFeatureBounds.xMaximum();
512 double ya1 = mTransformedFeatureBounds.yMinimum();
513 double ya2 = mTransformedFeatureBounds.yMaximum();
518 bool isPointLayer =
false;
519 switch ( mCoverageLayer->wkbType() )
528 isPointLayer =
false;
538 double geomCenterX = ( xa1 + xa2 ) / 2.0;
539 double geomCenterY = ( ya1 + ya2 ) / 2.0;
544 double xMin = geomCenterX - mOrigExtent.width() / 2.0;
545 double yMin = geomCenterY - mOrigExtent.height() / 2.0;
548 xMin + mOrigExtent.width(),
549 yMin + mOrigExtent.height() );
554 newExtent.
scale( originalScale / newScale );
559 double newWidth = mOrigExtent.width();
560 double newHeight = mOrigExtent.height();
562 for (
int i = 0; i < scales.
size(); i++ )
564 double ratio = scales[i] / originalScale;
565 newWidth = mOrigExtent.width() * ratio;
566 newHeight = mOrigExtent.height() * ratio;
569 double xMin = geomCenterX - newWidth / 2.0;
570 double yMin = geomCenterY - newHeight / 2.0;
579 newExtent.
scale( scales[i] / newScale );
581 if (( newExtent.
width() >= mTransformedFeatureBounds.width() ) && ( newExtent.
height() >= mTransformedFeatureBounds.height() ) )
593 double geomRatio = mTransformedFeatureBounds.width() / mTransformedFeatureBounds.height();
594 double mapRatio = mOrigExtent.width() / mOrigExtent.height();
597 if ( geomRatio < mapRatio )
600 double adjWidth = ( mapRatio * mTransformedFeatureBounds.height() - mTransformedFeatureBounds.width() ) / 2.0;
605 else if ( geomRatio > mapRatio )
608 double adjHeight = ( mTransformedFeatureBounds.width() / mapRatio - mTransformedFeatureBounds.height() ) / 2.0;
626 return mCurrentFilename;
632 atlasElem.
setAttribute(
"enabled", mEnabled ?
"true" :
"false" );
638 if ( mCoverageLayer )
640 atlasElem.
setAttribute(
"coverageLayer", mCoverageLayer->id() );
647 atlasElem.
setAttribute(
"hideCoverage", mHideCoverage ?
"true" :
"false" );
648 atlasElem.
setAttribute(
"singleFile", mSingleFile ?
"true" :
"false" );
649 atlasElem.
setAttribute(
"filenamePattern", mFilenamePattern );
650 atlasElem.
setAttribute(
"pageNameExpression", mPageNameExpression );
652 atlasElem.
setAttribute(
"sortFeatures", mSortFeatures ?
"true" :
"false" );
655 atlasElem.
setAttribute(
"sortKey", mSortKeyAttributeName );
656 atlasElem.
setAttribute(
"sortAscending", mSortAscending ?
"true" :
"false" );
658 atlasElem.
setAttribute(
"filterFeatures", mFilterFeatures ?
"true" :
"false" );
659 if ( mFilterFeatures )
661 atlasElem.
setAttribute(
"featureFilter", mFeatureFilter );
669 mEnabled = atlasElem.
attribute(
"enabled",
"false" ) ==
"true" ?
true :
false;
678 mCoverageLayer =
nullptr;
682 if ( it.key() == atlasElem.
attribute(
"coverageLayer" ) )
689 mPageNameExpression = atlasElem.
attribute(
"pageNameExpression",
QString() );
690 mSingleFile = atlasElem.
attribute(
"singleFile",
"false" ) ==
"true" ?
true :
false;
691 mFilenamePattern = atlasElem.
attribute(
"filenamePattern",
"" );
693 mSortFeatures = atlasElem.
attribute(
"sortFeatures",
"false" ) ==
"true" ?
true :
false;
696 mSortKeyAttributeName = atlasElem.
attribute(
"sortKey",
"" );
701 int idx = mSortKeyAttributeName.
toInt( &isIndex );
702 if ( isIndex && mCoverageLayer )
704 const QgsFields fields = mCoverageLayer->fields();
705 if ( idx >= 0 && idx < fields.
count() )
707 mSortKeyAttributeName = fields[idx].name();
710 mSortAscending = atlasElem.
attribute(
"sortAscending",
"true" ) ==
"true" ?
true :
false;
712 mFilterFeatures = atlasElem.
attribute(
"filterFeatures",
"false" ) ==
"true" ?
true :
false;
713 if ( mFilterFeatures )
715 mFeatureFilter = atlasElem.
attribute(
"featureFilter",
"" );
718 mHideCoverage = atlasElem.
attribute(
"hideCoverage",
"false" ) ==
"true" ?
true :
false;
727 int composerMapNo = elem.
attribute(
"composerMap",
"-1" ).
toInt();
729 if ( composerMapNo != -1 )
732 mComposition->composerItems( maps );
735 if (( *it )->id() == composerMapNo )
737 composerMap = ( *it );
751 if ( composerMap && fixedScale )
759 mHideCoverage = hide;
765 mComposition->update();
772 mFilenamePattern = pattern;
773 return updateFilenameExpression();
785 if ( mCoverageLayer )
790 return expressionContext;
793 bool QgsAtlasComposition::updateFilenameExpression()
795 if ( !mCoverageLayer )
802 if ( !mFilenamePattern.isEmpty() )
804 mFilenameExpr.reset(
new QgsExpression( mFilenamePattern ) );
807 if ( mFilenameExpr->hasParserError() )
809 mFilenameParserError = mFilenameExpr->parserErrorString();
814 mFilenameExpr->prepare( &expressionContext );
820 evalFeatureFilename( expressionContext );
828 if ( !mFilenamePattern.isEmpty() && !mFilenameExpr.isNull() )
830 QVariant filenameRes = mFilenameExpr->evaluate( &context );
831 if ( mFilenameExpr->hasEvalError() )
837 mCurrentFilename = filenameRes.
toString();
844 mPredefinedScales = scales;
846 qSort( mPredefinedScales.begin(), mPredefinedScales.end() );
900 if ( !mCoverageLayer || !mCurrentFeature.isValid() || !mCurrentFeature.constGeometry() )
908 return *mCurrentFeature.constGeometry();
912 if ( it != mGeometryCache.
constEnd() )
918 if ( mCoverageLayer->crs() == crs )
920 return *mCurrentFeature.constGeometry();
923 QgsGeometry transformed = *mCurrentFeature.constGeometry();
925 mGeometryCache[crs.
srsid()] = transformed;
bool prepareForFeature(const int i, const bool updateMaps=true)
Prepare the atlas map for the given feature.
QgsFeatureId id() const
Get the feature ID for this feature.
Class for parsing and evaluation of expressions (formerly called "search strings").
void setMapUnits(QGis::UnitType mapUnits)
Set the map units.
Wrapper for iterator of features from vector data provider or vector layer.
A rectangle specified with double values.
void renderEnded()
Is emitted when atlas rendering has ended.
double atlasMargin(const QgsComposerObject::PropertyValueType valueType=QgsComposerObject::EvaluatedValue)
Returns the margin size (percentage) used when the map is in atlas mode.
Q_DECL_DEPRECATED int sortKeyAttributeIndex() const
int fieldNameIndex(const QString &fieldName) const
Utility method to get attribute index from name.
QDomNode appendChild(const QDomNode &newChild)
static QgsExpressionContextScope * atlasScope(const QgsAtlasComposition *atlas)
Creates a new scope which contains variables and functions relating to a QgsAtlasComposition.
void setNewAtlasFeatureExtent(const QgsRectangle &extent)
Sets new Extent for the current atlas preview and changes width, height (and implicitely also scale)...
QgsAtlasComposition(QgsComposition *composition)
QString attribute(const QString &name, const QString &defValue) const
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
QgsFields fields() const
Returns the list of fields of this layer.
long srsid() const
Returns the SrsId, if available.
Q_DECL_DEPRECATED bool fixedScale() const
Returns whether the atlas map uses a fixed scale.
const QgsMapSettings & mapSettings() const
Return setting of QGIS map canvas.
QString nameForPage(int pageNumber) const
Returns the calculated name for a specified atlas page number.
void cache()
Create cache image.
const_iterator constEnd() const
void scale(double scaleFactor, const QgsPoint *c=nullptr)
Scale the rectangle around its center point.
#define Q_NOWARN_DEPRECATED_PUSH
void setDpi(double dpi)
Set the dpi to be used in scale calculations.
QgsComposition * composition()
bool enabled() const
Returns whether the atlas generation is enabled.
Container of fields for a vector layer.
A geometry is the spatial representation of a feature.
const_iterator constFind(const Key &key) const
void setFields(const QgsFields &fields)
Convenience function for setting a fields for the scope.
void toggled(bool)
Emitted when atlas is enabled or disabled.
void setHideCoverage(bool hide)
Sets whether the coverage layer should be hidden in map items in the composition. ...
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
QString currentPageName() const
Returns the name of the page for the current atlas feature.
bool qgsVariantGreaterThan(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether the first is greater than the second.
double toDouble(bool *ok) const
QString tr(const char *sourceText, const char *disambiguation, int n)
bool qgsDoubleNear(double a, double b, double epsilon=4 *DBL_EPSILON)
bool qgsVariantLessThan(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether the first is less than the second.
void endRender()
Ends the rendering.
void readXML(const QDomElement &elem, const QDomDocument &doc)
Reads general atlas settings from xml.
Q_DECL_DEPRECATED void setFixedScale(bool fixed)
Sets whether the atlas map should use a fixed scale.
Q_DECL_DEPRECATED float margin() const
Returns the margin for the atlas map.
void setAtlasMargin(double margin)
Sets the margin size (percentage) used when the map is in atlas mode.
bool setFilenamePattern(const QString &pattern)
Sets the filename expression used for generating output filenames for each atlas page.
Q_DECL_DEPRECATED void setSortKeyAttributeIndex(int idx)
void setCoverageLayer(QgsVectorLayer *layer)
Sets the coverage layer to use for the atlas features.
void setAtlasScalingMode(AtlasScalingMode mode)
Sets the current atlas scaling mode.
QgsExpressionContextScope * lastScope()
Returns the last scope added to the context.
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
bool beginRender()
Begins the rendering.
static QgsExpressionContextScope * globalScope()
Creates a new scope which contains variables and functions relating to the global QGIS context...
Q_DECL_DEPRECATED void setComposerMap(QgsComposerMap *map)
Sets the map used by the atlas.
double calculate(const QgsRectangle &mapExtent, int canvasWidth)
Calculate the scale denominator.
void prepareMap(QgsComposerMap *map)
Recalculates the bounds of an atlas driven map.
QgsAttributes attributes() const
Returns the feature's attributes.
void setAttribute(const QString &name, const QString &value)
void refreshFeature()
Refreshes the current atlas feature, by refetching its attributes from the vector layer provider...
const QgsComposition * composition() const
Returns the composition the item is attached to.
const QgsCoordinateReferenceSystem & destinationCrs() const
returns CRS of destination coordinate reference system
int toInt(bool *ok, int base) const
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
const_iterator constEnd() const
static void logMessage(const QString &message, const QString &tag=QString::null, MessageLevel level=WARNING)
add a message to the instance (and create it if necessary)
This class wraps a request for features to a vector layer (or directly its vector data provider)...
int numFeatures() const
Returns the number of features in the coverage layer.
QString id() const
Get this layer's unique ID, this ID is used to access this layer from map layer registry.
int count() const
Return number of items.
Q_DECL_DEPRECATED bool atlasFixedScale() const
Returns true if the map uses a fixed scale when in atlas mode.
void setEnabled(bool enabled)
Sets whether the atlas is enabled.
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the scope.
int updateFeatures()
Requeries the current atlas coverage layer and applies filtering and sorting.
void writeXML(QDomElement &elem, QDomDocument &doc) const
Graphics scene for map printing.
QString currentFilename() const
Returns the current filename.
Object representing map window.
QgsGeometry currentGeometry(const QgsCoordinateReferenceSystem &projectedTo=QgsCoordinateReferenceSystem()) const
Returns the current atlas geometry in the given projection system (default to the coverage layer's CR...
void featureChanged(QgsFeature *feature)
Is emitted when the current atlas feature changes.
void coverageLayerChanged(QgsVectorLayer *layer)
Is emitted when the coverage layer for an atlas changes.
Calculates scale for a given combination of canvas size, map extent, and monitor dpi.
bool setAtlasMode(const QgsComposition::AtlasMode mode)
Sets the current atlas mode of the composition.
#define Q_NOWARN_DEPRECATED_POP
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
const T & at(int i) const
const_iterator constBegin() const
void renderBegun()
Is emitted when atlas rendering has begun.
static QgsMapLayerRegistry * instance()
Returns the instance pointer, creating the object on the first call.
QgsRectangle extent() const
FieldSorter(QgsAtlasComposition::SorterKeys &keys, bool ascending=true)
Q_DECL_DEPRECATED QgsComposerMap * composerMap() const
Returns the map used by the atlas.
void readXMLMapSettings(const QDomElement &elem, const QDomDocument &doc)
Reads old (pre 2.2) map related atlas settings from xml.
Q_DECL_DEPRECATED void setMargin(float margin)
Sets the margin for the atlas map.
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
AtlasScalingMode atlasScalingMode() const
Returns the current atlas scaling mode.
Class for storing a coordinate reference system (CRS)
int count(const T &value) const
QString authid() const
Returns the authority identifier for the CRS, which includes both the authority (eg EPSG) and the CRS...
const QMap< QString, QgsMapLayer * > & mapLayers()
Retrieve the mapLayers collection (mainly intended for use by projection)
void parameterChanged()
Emitted when one of the parameters changes.
int transform(const QgsCoordinateTransform &ct)
Transform this geometry as described by CoordinateTransform ct.
void numberFeaturesChanged(int numFeatures)
Is emitted when the number of features for the atlas changes.
bool atlasDriven() const
Returns whether the map extent is set to follow the current atlas feature.
int currentFeatureNumber() const
Returns the current feature number, where a value of 0 corresponds to the first feature.
static QgsExpressionContextScope * projectScope()
Creates a new scope which contains variables and functions relating to the current QGIS project...
void setAtlasDriven(bool enabled)
Sets whether the map extent will follow the current atlas feature.
QDomElement createElement(const QString &tagName)
bool nextFeature(QgsFeature &f)
void composerItems(QList< T * > &itemList)
Return composer items of a specific type.
double width() const
Width of the rectangle.
bool connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type)
Represents a vector layer which manages a vector based data sets.
int fieldNameIndex(const QString &fieldName) const
Returns the index of a field name or -1 if the field does not exist.
void statusMsgChanged(const QString &message)
Is emitted when the atlas has an updated status bar message for the composer window.
void setPredefinedScales(const QVector< qreal > &scales)
Sets the list of predefined scales for the atlas.
bool operator()(const QPair< QgsFeatureId, QString > &id1, const QPair< QgsFeatureId, QString > &id2)
double height() const
Height of the rectangle.
const T value(const Key &key) const
static QgsExpressionContextScope * compositionScope(const QgsComposition *composition)
Creates a new scope which contains variables and functions relating to a QgsComposition.