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