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