QGIS API Documentation 3.99.0-Master (26c88405ac0)
Loading...
Searching...
No Matches
qgsalgorithmextractlayoutmapextent.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmextractlayoutmapextent.cpp
3 ---------------------
4 begin : March 2019
5 copyright : (C) 2019 by Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
19
20#include "layout/qgslayout.h"
25
27
28QString QgsLayoutMapExtentToLayerAlgorithm::name() const
29{
30 return QStringLiteral( "printlayoutmapextenttolayer" );
31}
32
33QString QgsLayoutMapExtentToLayerAlgorithm::displayName() const
34{
35 return QObject::tr( "Print layout map extent to layer" );
36}
37
38QStringList QgsLayoutMapExtentToLayerAlgorithm::tags() const
39{
40 return QObject::tr( "layout,composer,composition,visible" ).split( ',' );
41}
42
43QString QgsLayoutMapExtentToLayerAlgorithm::group() const
44{
45 return QObject::tr( "Cartography" );
46}
47
48QString QgsLayoutMapExtentToLayerAlgorithm::groupId() const
49{
50 return QStringLiteral( "cartography" );
51}
52
53QString QgsLayoutMapExtentToLayerAlgorithm::shortDescription() const
54{
55 return QObject::tr( "Creates a polygon layer containing the extent of a print layout map item." );
56}
57
58void QgsLayoutMapExtentToLayerAlgorithm::initAlgorithm( const QVariantMap & )
59{
60 addParameter( new QgsProcessingParameterLayout( QStringLiteral( "LAYOUT" ), QObject::tr( "Print layout" ) ) );
61 addParameter( new QgsProcessingParameterLayoutItem( QStringLiteral( "MAP" ), QObject::tr( "Map item" ), QVariant(), QStringLiteral( "LAYOUT" ), QgsLayoutItemRegistry::LayoutMap, true ) );
62 auto crsParam = std::make_unique<QgsProcessingParameterCrs>( QStringLiteral( "CRS" ), QObject::tr( "Override CRS" ), QVariant(), true );
63 crsParam->setFlags( crsParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
64 addParameter( crsParam.release() );
65 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Extent" ), Qgis::ProcessingSourceType::VectorPolygon ) );
66 addOutput( new QgsProcessingOutputNumber( QStringLiteral( "WIDTH" ), QObject::tr( "Map width" ) ) );
67 addOutput( new QgsProcessingOutputNumber( QStringLiteral( "HEIGHT" ), QObject::tr( "Map height" ) ) );
68 addOutput( new QgsProcessingOutputNumber( QStringLiteral( "SCALE" ), QObject::tr( "Map scale" ) ) );
69 addOutput( new QgsProcessingOutputNumber( QStringLiteral( "ROTATION" ), QObject::tr( "Map rotation" ) ) );
70}
71
72Qgis::ProcessingAlgorithmFlags QgsLayoutMapExtentToLayerAlgorithm::flags() const
73{
75}
76
77QString QgsLayoutMapExtentToLayerAlgorithm::shortHelpString() const
78{
79 return QObject::tr( "This algorithm creates a polygon layer containing the extent of a print layout map item (or items), "
80 "with attributes specifying the map size (in layout units), scale and rotation.\n\n"
81 "If the map item parameter is specified, then only the matching map extent will be exported. If it "
82 "is not specified, all map extents from the layout will be exported.\n\n"
83 "Optionally, a specific output CRS can be specified. If it is not specified, the original map "
84 "item CRS will be used." );
85}
86
87QgsLayoutMapExtentToLayerAlgorithm *QgsLayoutMapExtentToLayerAlgorithm::createInstance() const
88{
89 return new QgsLayoutMapExtentToLayerAlgorithm();
90}
91
92bool QgsLayoutMapExtentToLayerAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
93{
94 // this needs to be done in main thread, layouts are not thread safe
95 QgsPrintLayout *layout = parameterAsLayout( parameters, QStringLiteral( "LAYOUT" ), context );
96 if ( !layout )
97 throw QgsProcessingException( QObject::tr( "Cannot find layout with name \"%1\"" ).arg( parameters.value( QStringLiteral( "LAYOUT" ) ).toString() ) );
98
99 QgsLayoutItemMap *map = qobject_cast<QgsLayoutItemMap *>( parameterAsLayoutItem( parameters, QStringLiteral( "MAP" ), context, layout ) );
100 if ( !map && parameters.value( QStringLiteral( "MAP" ) ).isValid() )
101 throw QgsProcessingException( QObject::tr( "Cannot find matching map item with ID %1" ).arg( parameters.value( QStringLiteral( "MAP" ) ).toString() ) );
102
103 QList<QgsLayoutItemMap *> maps;
104 if ( map )
105 maps << map;
106 else
107 layout->layoutItems( maps );
108
109 const QgsCoordinateReferenceSystem overrideCrs = parameterAsCrs( parameters, QStringLiteral( "CRS" ), context );
110
111 mFeatures.reserve( maps.size() );
112 for ( QgsLayoutItemMap *map : maps )
113 {
114 if ( !mCrs.isValid() )
115 mCrs = !overrideCrs.isValid() ? map->crs() : overrideCrs;
116
117 QgsGeometry extent = QgsGeometry::fromQPolygonF( map->visibleExtentPolygon() );
118 if ( map->crs() != mCrs )
119 {
120 try
121 {
122 extent.transform( QgsCoordinateTransform( map->crs(), mCrs, context.transformContext() ) );
123 }
124 catch ( QgsCsException & )
125 {
126 feedback->reportError( QObject::tr( "Error reprojecting map to destination CRS" ) );
127 continue;
128 }
129 }
130
131 mWidth = map->rect().width();
132 mHeight = map->rect().height();
133 mScale = map->scale();
134 mRotation = map->mapRotation();
135
136 QgsFeature f;
137 f.setAttributes( QgsAttributes() << map->displayName() << mWidth << mHeight << mScale << mRotation );
138 f.setGeometry( extent );
139
140 mFeatures << f;
141 }
142 return true;
143}
144
145QVariantMap QgsLayoutMapExtentToLayerAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
146{
147 QgsFields fields;
148 fields.append( QgsField( QStringLiteral( "map" ), QMetaType::Type::QString ) );
149 fields.append( QgsField( QStringLiteral( "width" ), QMetaType::Type::Double ) );
150 fields.append( QgsField( QStringLiteral( "height" ), QMetaType::Type::Double ) );
151 fields.append( QgsField( QStringLiteral( "scale" ), QMetaType::Type::Double ) );
152 fields.append( QgsField( QStringLiteral( "rotation" ), QMetaType::Type::Double ) );
153
154 QString dest;
155 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, Qgis::WkbType::Polygon, mCrs ) );
156 if ( !sink )
157 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
158
159 for ( QgsFeature &f : mFeatures )
160 {
161 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
162 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
163 }
164
165 sink->finalize();
166
167 feedback->setProgress( 100 );
168
169 QVariantMap outputs;
170 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
171 // these numeric outputs only have value for single-map layouts
172 outputs.insert( QStringLiteral( "WIDTH" ), mFeatures.size() == 1 ? mWidth : QVariant() );
173 outputs.insert( QStringLiteral( "HEIGHT" ), mFeatures.size() == 1 ? mHeight : QVariant() );
174 outputs.insert( QStringLiteral( "SCALE" ), mFeatures.size() == 1 ? mScale : QVariant() );
175 outputs.insert( QStringLiteral( "ROTATION" ), mFeatures.size() == 1 ? mRotation : QVariant() );
176 return outputs;
177}
178
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3536
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3609
@ Polygon
Polygon.
Definition qgis.h:281
@ RequiresProject
The algorithm requires that a valid QgsProject is available from the processing context in order to e...
Definition qgis.h:3596
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3763
A vector of attributes.
Represents a coordinate reference system (CRS).
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
Handles coordinate transforms between two coordinate systems.
Custom exception class for Coordinate Reference System related exceptions.
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:58
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:61
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:54
Container of fields for a vector layer.
Definition qgsfields.h:46
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:73
A geometry is the spatial representation of a feature.
static QgsGeometry fromQPolygonF(const QPolygonF &polygon)
Construct geometry from a QPolygonF.
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false)
Transforms this geometry as described by the coordinate transform ct.
Layout graphical items for displaying a map.
void layoutItems(QList< T * > &itemList) const
Returns a list of layout items of a specific type.
Definition qgslayout.h:121
Print layout, a QgsLayout subclass for static or atlas-based layouts.
virtual Qgis::ProcessingAlgorithmFlags flags() const
Returns the flags indicating how and when the algorithm operates and should be exposed to users.
Contains information about the context in which a processing algorithm is executed.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
A numeric output for processing algorithms.
A feature sink output for processing algorithms.
A print layout item parameter, allowing users to select a particular item from a print layout.
A print layout parameter, allowing users to select a print layout.