QGIS API Documentation 3.99.0-Master (2fe06baccd8)
Loading...
Searching...
No Matches
qgsbookmarkalgorithms.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsbookmarkalgorithms.cpp
3 ---------------------
4 begin : September 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 "qgsapplication.h"
21
23
24//
25// QgsBookmarksToLayerAlgorithm
26//
27
28void QgsBookmarksToLayerAlgorithm::initAlgorithm( const QVariantMap & )
29{
30 auto sourceParam = std::make_unique<QgsProcessingParameterEnum>( QStringLiteral( "SOURCE" ), QObject::tr( "Bookmark source" ), QStringList() << QObject::tr( "Project bookmarks" ) << QObject::tr( "User bookmarks" ), true, QVariantList() << 0 << 1 );
31 QVariantMap wrapperMetadata;
32 wrapperMetadata.insert( QStringLiteral( "useCheckBoxes" ), true );
33 QVariantMap metadata;
34 metadata.insert( QStringLiteral( "widget_wrapper" ), wrapperMetadata );
35 sourceParam->setMetadata( metadata );
36 addParameter( sourceParam.release() );
37 addParameter( new QgsProcessingParameterCrs( QStringLiteral( "CRS" ), QObject::tr( "Output CRS" ), QgsCoordinateReferenceSystem( QStringLiteral( "EPSG:4326" ) ) ) );
38 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Output" ), Qgis::ProcessingSourceType::VectorPolygon ) );
39}
40
41QString QgsBookmarksToLayerAlgorithm::name() const
42{
43 return QStringLiteral( "bookmarkstolayer" );
44}
45
46QString QgsBookmarksToLayerAlgorithm::displayName() const
47{
48 return QObject::tr( "Convert spatial bookmarks to layer" );
49}
50
51QStringList QgsBookmarksToLayerAlgorithm::tags() const
52{
53 return QObject::tr( "save,extract" ).split( ',' );
54}
55
56QString QgsBookmarksToLayerAlgorithm::group() const
57{
58 return QObject::tr( "Vector general" );
59}
60
61QString QgsBookmarksToLayerAlgorithm::groupId() const
62{
63 return QStringLiteral( "vectorgeneral" );
64}
65
66QString QgsBookmarksToLayerAlgorithm::shortHelpString() const
67{
68 return QObject::tr( "This algorithm creates a new layer containing polygon features for stored spatial bookmarks.\n\n"
69 "The export can be filtered to only bookmarks belonging to the current project, to all user bookmarks, or a combination of both." );
70}
71
72QString QgsBookmarksToLayerAlgorithm::shortDescription() const
73{
74 return QObject::tr( "Converts stored spatial bookmarks to a polygon layer." );
75}
76
77QIcon QgsBookmarksToLayerAlgorithm::icon() const
78{
79 return QgsApplication::getThemeIcon( QStringLiteral( "mActionShowBookmarks.svg" ) );
80}
81
82QString QgsBookmarksToLayerAlgorithm::svgIconPath() const
83{
84 return QgsApplication::iconPath( QStringLiteral( "mActionShowBookmarks.svg" ) );
85}
86
87QgsBookmarksToLayerAlgorithm *QgsBookmarksToLayerAlgorithm::createInstance() const
88{
89 return new QgsBookmarksToLayerAlgorithm();
90}
91
92bool QgsBookmarksToLayerAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
93{
94 QList<int> sources = parameterAsEnums( parameters, QStringLiteral( "SOURCE" ), context );
95 if ( sources.contains( 0 ) )
96 {
97 if ( !context.project() )
98 throw QgsProcessingException( QObject::tr( "No project is available for bookmark extraction" ) );
99 mBookmarks.append( context.project()->bookmarkManager()->bookmarks() );
100 }
101 if ( sources.contains( 1 ) )
102 mBookmarks.append( QgsApplication::bookmarkManager()->bookmarks() );
103
104 return true;
105}
106
107QVariantMap QgsBookmarksToLayerAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
108{
109 const QgsCoordinateReferenceSystem crs = parameterAsCrs( parameters, QStringLiteral( "CRS" ), context );
110 QgsFields fields;
111 fields.append( QgsField( QStringLiteral( "name" ), QMetaType::Type::QString ) );
112 fields.append( QgsField( QStringLiteral( "group" ), QMetaType::Type::QString ) );
113 QString dest;
114 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, Qgis::WkbType::Polygon, crs ) );
115 if ( !sink )
116 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
117
118 int count = mBookmarks.count();
119 int current = 0;
120 double step = count > 0 ? 100.0 / count : 1;
121
122 for ( const QgsBookmark &b : std::as_const( mBookmarks ) )
123 {
124 if ( feedback->isCanceled() )
125 {
126 break;
127 }
128
129 QgsFeature feat;
130 feat.setAttributes( QgsAttributes() << b.name() << b.group() );
131
132 QgsGeometry geom = QgsGeometry::fromRect( b.extent() );
133 if ( b.extent().crs() != crs )
134 {
135 QgsCoordinateTransform xform( b.extent().crs(), crs, context.transformContext() );
136 geom = geom.densifyByCount( 20 );
137 try
138 {
139 geom.transform( xform );
140 }
141 catch ( QgsCsException & )
142 {
143 feedback->reportError( QObject::tr( "Could not reproject bookmark %1 to destination CRS" ).arg( b.name() ) );
144 feedback->setProgress( current++ * step );
145 continue;
146 }
147 }
148
149 feat.setGeometry( geom );
150
151 if ( !sink->addFeature( feat, QgsFeatureSink::FastInsert ) )
152 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
153
154 feedback->setProgress( current++ * step );
155 }
156
157 sink->finalize();
158
159 QVariantMap outputs;
160 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
161 return outputs;
162}
163
164
165//
166// QgsLayerToBookmarksAlgorithm
167//
168
169void QgsLayerToBookmarksAlgorithm::initAlgorithm( const QVariantMap & )
170{
171 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ) ) );
172
173 auto sourceParam = std::make_unique<QgsProcessingParameterEnum>( QStringLiteral( "DESTINATION" ), QObject::tr( "Bookmark destination" ), QStringList() << QObject::tr( "Project bookmarks" ) << QObject::tr( "User bookmarks" ), false, 0 );
174 addParameter( sourceParam.release() );
175
176 addParameter( new QgsProcessingParameterExpression( QStringLiteral( "NAME_EXPRESSION" ), QObject::tr( "Name field" ), QVariant(), QStringLiteral( "INPUT" ) ) );
177 addParameter( new QgsProcessingParameterExpression( QStringLiteral( "GROUP_EXPRESSION" ), QObject::tr( "Group field" ), QVariant(), QStringLiteral( "INPUT" ), true ) );
178
179 addOutput( new QgsProcessingOutputNumber( QStringLiteral( "COUNT" ), QObject::tr( "Count of bookmarks added" ) ) );
180}
181
182QString QgsLayerToBookmarksAlgorithm::name() const
183{
184 return QStringLiteral( "layertobookmarks" );
185}
186
187QString QgsLayerToBookmarksAlgorithm::displayName() const
188{
189 return QObject::tr( "Convert layer to spatial bookmarks" );
190}
191
192QStringList QgsLayerToBookmarksAlgorithm::tags() const
193{
194 return QObject::tr( "save,extract,store" ).split( ',' );
195}
196
197QString QgsLayerToBookmarksAlgorithm::group() const
198{
199 return QObject::tr( "Vector general" );
200}
201
202QString QgsLayerToBookmarksAlgorithm::groupId() const
203{
204 return QStringLiteral( "vectorgeneral" );
205}
206
207QString QgsLayerToBookmarksAlgorithm::shortHelpString() const
208{
209 return QObject::tr( "This algorithm creates spatial bookmarks corresponding to the extent of features contained in a layer." );
210}
211
212QString QgsLayerToBookmarksAlgorithm::shortDescription() const
213{
214 return QObject::tr( "Converts feature extents to stored spatial bookmarks." );
215}
216
217QIcon QgsLayerToBookmarksAlgorithm::icon() const
218{
219 return QgsApplication::getThemeIcon( QStringLiteral( "mActionShowBookmarks.svg" ) );
220}
221
222QString QgsLayerToBookmarksAlgorithm::svgIconPath() const
223{
224 return QgsApplication::iconPath( QStringLiteral( "mActionShowBookmarks.svg" ) );
225}
226
227QgsLayerToBookmarksAlgorithm *QgsLayerToBookmarksAlgorithm::createInstance() const
228{
229 return new QgsLayerToBookmarksAlgorithm();
230}
231
232QVariantMap QgsLayerToBookmarksAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
233{
234 mDest = parameterAsEnum( parameters, QStringLiteral( "DESTINATION" ), context );
235 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
236 if ( !source )
237 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
238
239
240 QString nameExpressionString = parameterAsExpression( parameters, QStringLiteral( "NAME_EXPRESSION" ), context );
241 QString groupExpressionString = parameterAsExpression( parameters, QStringLiteral( "GROUP_EXPRESSION" ), context );
242
243 QgsExpressionContext expressionContext = context.expressionContext();
244 expressionContext.appendScope( source->createExpressionContextScope() );
245
246 QgsExpression nameExpression = QgsExpression( nameExpressionString );
247 if ( !nameExpression.prepare( &expressionContext ) )
248 throw QgsProcessingException( QObject::tr( "Invalid name expression: %1" ).arg( nameExpression.parserErrorString() ) );
249
250 QSet<QString> requiredColumns = nameExpression.referencedColumns();
251
252 std::unique_ptr<QgsExpression> groupExpression;
253 if ( !groupExpressionString.isEmpty() )
254 {
255 groupExpression = std::make_unique<QgsExpression>( groupExpressionString );
256 if ( !groupExpression->prepare( &expressionContext ) )
257 throw QgsProcessingException( QObject::tr( "Invalid group expression: %1" ).arg( groupExpression->parserErrorString() ) );
258 requiredColumns.unite( groupExpression->referencedColumns() );
259 }
260
262 req.setSubsetOfAttributes( requiredColumns, source->fields() );
263
264 double step = source->featureCount() > 0 ? 100.0 / source->featureCount() : 1;
266 QgsFeature f;
267 int current = 0;
268 while ( fi.nextFeature( f ) )
269 {
270 if ( feedback->isCanceled() )
271 {
272 break;
273 }
274
275 if ( f.hasGeometry() )
276 {
277 const QgsReferencedRectangle extent( f.geometry().boundingBox(), source->sourceCrs() );
278 expressionContext.setFeature( f );
279 const QString name = nameExpression.evaluate( &expressionContext ).toString();
280 if ( !nameExpression.evalErrorString().isEmpty() )
281 {
282 feedback->reportError( QObject::tr( "Error evaluating name expression: %1" ).arg( nameExpression.evalErrorString() ) );
283 feedback->setProgress( current * step );
284 current++;
285 continue;
286 }
287 QString group;
288 if ( groupExpression )
289 {
290 group = groupExpression->evaluate( &expressionContext ).toString();
291 if ( !groupExpression->evalErrorString().isEmpty() )
292 {
293 feedback->reportError( QObject::tr( "Error evaluating group expression: %1" ).arg( groupExpression->evalErrorString() ) );
294 feedback->setProgress( current * step );
295 current++;
296 continue;
297 }
298 }
299
300 QgsBookmark b;
301 b.setName( name );
302 b.setGroup( group );
303 b.setExtent( extent );
304 mBookmarks << b;
305 }
306 feedback->setProgress( current * step );
307 current++;
308 }
309
310 return QVariantMap();
311}
312
313QVariantMap QgsLayerToBookmarksAlgorithm::postProcessAlgorithm( QgsProcessingContext &context, QgsProcessingFeedback * )
314{
315 QgsBookmarkManager *dest = nullptr;
316 switch ( mDest )
317 {
318 case 0:
319 dest = context.project()->bookmarkManager();
320 break;
321
322 case 1:
324 break;
325
326 default:
327 throw QgsProcessingException( QObject::tr( "Invalid bookmark destination" ) );
328 }
329
330 for ( const QgsBookmark &b : std::as_const( mBookmarks ) )
331 dest->addBookmark( b );
332
333 QVariantMap res;
334 res.insert( QStringLiteral( "COUNT" ), mBookmarks.size() );
335 return res;
336}
337
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3536
@ VectorLine
Vector line layers.
Definition qgis.h:3535
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
Definition qgis.h:3711
@ Polygon
Polygon.
Definition qgis.h:281
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
static QgsBookmarkManager * bookmarkManager()
Returns the application's bookmark manager, used for storing installation-wide bookmarks.
static QString iconPath(const QString &iconFile)
Returns path to the desired icon file.
A vector of attributes.
Manages storage of a set of bookmarks.
QString addBookmark(const QgsBookmark &bookmark, bool *ok=nullptr)
Adds a bookmark to the manager.
QList< QgsBookmark > bookmarks() const
Returns a list of all bookmarks contained in the manager.
Represents a spatial bookmark, with a name, CRS and extent.
void setGroup(const QString &group)
Sets the bookmark's group, which is a user-visible string identifying the bookmark's category.
void setExtent(const QgsReferencedRectangle &extent)
Sets the bookmark's spatial extent.
void setName(const QString &name)
Sets the bookmark's name, which is a user-visible string identifying the bookmark.
Represents a coordinate reference system (CRS).
Handles coordinate transforms between two coordinate systems.
Custom exception class for Coordinate Reference System related exceptions.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
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").
bool prepare(const QgsExpressionContext *context)
Gets the expression ready for evaluation - find out column indexes.
QString evalErrorString() const
Returns evaluation error.
QString parserErrorString() const
Returns parser error.
QSet< QString > referencedColumns() const
Gets list of columns referenced by the expression.
QVariant evaluate()
Evaluate the feature and return the result.
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 & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
@ 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.
QgsGeometry geometry
Definition qgsfeature.h:69
bool hasGeometry() const
Returns true if the feature has an associated geometry.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:53
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.
QgsGeometry densifyByCount(int extraNodesPerSegment) const
Returns a copy of the geometry which has been densified by adding the specified number of extra nodes...
static QgsGeometry fromRect(const QgsRectangle &rect)
Creates a new geometry from a QgsRectangle.
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.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
Contains information about the context in which a processing algorithm is executed.
QgsExpressionContext & expressionContext()
Returns the expression context.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
QgsProject * project() const
Returns the project in which the algorithm is being executed.
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 coordinate reference system parameter for processing algorithms.
An expression parameter for processing algorithms.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
const QgsBookmarkManager * bookmarkManager() const
Returns the project's bookmark manager, which manages bookmarks within the project.
A QgsRectangle with associated coordinate reference system.