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