QGIS API Documentation 3.29.0-Master (006c3c0232)
qgswmsgetlegendgraphics.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgswmsgetlegendgraphics.cpp
3 -------------------------
4 begin : December 20 , 2016
5 copyright : (C) 2007 by Marco Hugentobler (original code)
6 (C) 2014 by Alessandro Pasotti (original code)
7 (C) 2016 by David Marteau
8 email : marco dot hugentobler at karto dot baug dot ethz dot ch
9 a dot pasotti at itopen dot it
10 david dot marteau at 3liz dot com
11 ***************************************************************************/
12
13/***************************************************************************
14 * *
15 * This program is free software; you can redistribute it and/or modify *
16 * it under the terms of the GNU General Public License as published by *
17 * the Free Software Foundation; either version 2 of the License, or *
18 * (at your option) any later version. *
19 * *
20 ***************************************************************************/
21#include "qgslayertree.h"
22#include "qgslegendrenderer.h"
23#include "qgsvectorlayer.h"
25
26#include "qgswmsutils.h"
27#include "qgswmsrequest.h"
30#include "qgswmsrenderer.h"
32
33#include <QImage>
34#include <QJsonObject>
35#include <QJsonDocument>
36
37namespace QgsWms
38{
39 void writeGetLegendGraphics( QgsServerInterface *serverIface, const QgsProject *project,
40 const QgsWmsRequest &request,
41 QgsServerResponse &response )
42 {
43 // get parameters from query
44 QgsWmsParameters parameters = request.wmsParameters();
45
46 // check parameters validity
47 // FIXME fail with png + mode
48 checkParameters( parameters );
49
50 // init render context
51 QgsWmsRenderContext context( project, serverIface );
54 context.setParameters( parameters );
55
56 // get the requested output format
57 QgsWmsParameters::Format format = parameters.format();
58
59 // parameters.format() returns NONE if the requested format is image/png with a
60 // mode (e.g. image/png;mode=16bit), so in that case we use parseImageFormat to
61 // give the requested format another chance
62
63 QString imageSaveFormat;
64 QString imageContentType;
65 if ( format == QgsWmsParameters::Format::PNG )
66 {
67 imageContentType = "image/png";
68 imageSaveFormat = "PNG";
69 }
70 else if ( format == QgsWmsParameters::Format::JPG )
71 {
72 imageContentType = "image/jpeg";
73 imageSaveFormat = "JPEG";
74 }
75 else if ( format == QgsWmsParameters::Format::NONE )
76 {
77 switch ( parseImageFormat( parameters.formatAsString() ) )
78 {
83 format = QgsWmsParameters::Format::PNG;
84 imageContentType = "image/png";
85 imageSaveFormat = "PNG";
86 break;
88 break;
89
90 // not possible
93 break;
94 }
95 }
96
97 if ( format == QgsWmsParameters::Format::NONE )
98 {
100 QStringLiteral( "Output format '%1' is not supported in the GetLegendGraphic request" ).arg( parameters.formatAsString() ) );
101 }
102
103 // Get cached image
104#ifdef HAVE_SERVER_PYTHON_PLUGINS
105 QgsAccessControl *accessControl = serverIface->accessControls();
106 QgsServerCacheManager *cacheManager = serverIface->cacheManager();
107 if ( cacheManager && !imageSaveFormat.isEmpty() )
108 {
109 QImage image;
110 const QByteArray content = cacheManager->getCachedImage( project, request, accessControl );
111 if ( !content.isEmpty() && image.loadFromData( content ) )
112 {
113 response.setHeader( QStringLiteral( "Content-Type" ), imageContentType );
114 image.save( response.io(), qPrintable( imageSaveFormat ) );
115 return;
116 }
117 }
118#endif
119 QgsRenderer renderer( context );
120
121 // retrieve legend settings and model
122 bool addLegendGroups = QgsServerProjectUtils::wmsAddLegendGroupsLegendGraphic( *project ) || parameters.addLayerGroups();
123 std::unique_ptr<QgsLayerTree> tree( addLegendGroups ? layerTreeWithGroups( context, QgsProject::instance()->layerTreeRoot() ) : layerTree( context ) );
124 const std::unique_ptr<QgsLayerTreeModel> model( legendModel( context, *tree.get() ) );
125
126 // rendering
127 if ( format == QgsWmsParameters::Format::JSON )
128 {
129 QJsonObject result;
130 if ( !parameters.rule().isEmpty() )
131 {
133 QStringLiteral( "RULE cannot be used with JSON format" ) );
134 }
135 else
136 {
137 result = renderer.getLegendGraphicsAsJson( *model.get() );
138 }
139 tree->clear();
140 response.setHeader( QStringLiteral( "Content-Type" ), parameters.formatAsString() );
141 const QJsonDocument doc( result );
142 response.write( doc.toJson( QJsonDocument::Compact ) );
143 }
144 else
145 {
146 std::unique_ptr<QImage> result;
147 if ( !parameters.rule().isEmpty() )
148 {
149 QgsLayerTreeModelLegendNode *node = legendNode( parameters.rule(), *model.get() );
150 if ( ! node )
151 {
152 throw QgsException( QStringLiteral( "Could not get a legend node for the requested RULE" ) );
153 }
154 result.reset( renderer.getLegendGraphics( *node ) );
155 }
156 else
157 {
158 result.reset( renderer.getLegendGraphics( *model.get() ) );
159 }
160 tree->clear();
161 if ( result )
162 {
163 writeImage( response, *result, parameters.formatAsString(), context.imageQuality() );
164#ifdef HAVE_SERVER_PYTHON_PLUGINS
165 if ( cacheManager )
166 {
167 const QByteArray content = response.data();
168 if ( !content.isEmpty() )
169 cacheManager->setCachedImage( &content, project, request, accessControl );
170 }
171#endif
172 }
173 else
174 {
175 throw QgsException( QStringLiteral( "Failed to compute GetLegendGraphics image" ) );
176 }
177 }
178 }
179
181 {
182 if ( parameters.allLayersNickname().isEmpty() )
183 {
185 parameters[QgsWmsParameter::LAYERS] );
186 }
187
188 if ( parameters.format() == QgsWmsParameters::Format::NONE )
189 {
191 parameters[QgsWmsParameter::FORMAT] );
192 }
193
194 if ( ! parameters.bbox().isEmpty() && !parameters.rule().isEmpty() )
195 {
197 QStringLiteral( "BBOX parameter cannot be combined with RULE." ) );
198 }
199
200 if ( ! parameters.bbox().isEmpty() && parameters.bboxAsRectangle().isEmpty() )
201 {
203 parameters[QgsWmsParameter::BBOX] );
204 }
205 // If we have a contextual legend (BBOX is set)
206 // make sure (SRC)WIDTH and (SRC)HEIGHT are set, default to 800px width
207 // height is calculated from that value, respecting the aspect
208 if ( ! parameters.bbox().isEmpty() )
209 {
210 // Calculate ratio from bbox
211 QgsRectangle bbox { parameters.bboxAsRectangle() };
212 const QString crs = parameters.crs();
213 if ( crs.compare( QStringLiteral( "CRS:84" ), Qt::CaseInsensitive ) == 0 )
214 {
215 bbox.invert();
216 }
218 if ( parameters.versionAsNumber() >= QgsProjectVersion( 1, 3, 0 ) &&
220 {
221 bbox.invert();
222 }
223 const double ratio { bbox.width() / bbox.height() };
224 const int defaultHeight { static_cast<int>( 800 / ratio ) };
225 if ( parameters.width().isEmpty() && parameters.srcWidth().isEmpty() )
226 {
227 parameters.set( QgsWmsParameter::SRCWIDTH, 800 );
228 }
229 if ( parameters.height().isEmpty() && parameters.srcHeight().isEmpty() )
230 {
231 parameters.set( QgsWmsParameter::SRCHEIGHT, defaultHeight );
232 }
233 }
234 }
235
237 {
238
239 const QgsWmsParameters parameters = context.parameters();
240 std::unique_ptr<QgsLayerTreeModel> model( new QgsLayerTreeModel( &tree ) );
241 std::unique_ptr<QgsMapSettings> mapSettings;
242
243 if ( context.scaleDenominator() > 0 )
244 {
245 model->setLegendFilterByScale( context.scaleDenominator() );
246 }
247
248 // content based legend
249 if ( ! parameters.bbox().isEmpty() )
250 {
251 mapSettings = std::make_unique<QgsMapSettings>();
252 mapSettings->setOutputSize( context.mapSize() );
253 // Inverted axis?
254 QgsRectangle bbox { parameters.bboxAsRectangle() };
255 const QString crs = parameters.crs();
256 if ( crs.compare( QStringLiteral( "CRS:84" ), Qt::CaseInsensitive ) == 0 )
257 {
258 bbox.invert();
259 }
261 if ( parameters.versionAsNumber() >= QgsProjectVersion( 1, 3, 0 ) &&
263 {
264 bbox.invert();
265 }
266 mapSettings->setDestinationCrs( outputCrs );
267 mapSettings->setExtent( bbox );
268 QgsRenderer renderer( context );
269 QList<QgsMapLayer *> layers = context.layersToRender();
270 renderer.configureLayers( layers, mapSettings.get() );
271 mapSettings->setLayers( context.layersToRender() );
272 model->setLegendFilterByMap( mapSettings.get() );
273 }
274
275 // if legend is not based on rendering rules
276 if ( parameters.rule().isEmpty() )
277 {
278 const QList<QgsLayerTreeNode *> children = tree.children();
279 const QString ruleLabel = parameters.ruleLabel();
280 for ( QgsLayerTreeNode *node : children )
281 {
282 if ( ! QgsLayerTree::isLayer( node ) )
283 continue;
284
285 QgsLayerTreeLayer *nodeLayer = QgsLayerTree::toLayer( node );
286
287 // layer titles - hidden or not
289 // rule item titles
290 if ( !parameters.ruleLabelAsBool() )
291 {
292 for ( QgsLayerTreeModelLegendNode *legendNode : model->layerLegendNodes( nodeLayer ) )
293 {
294 // empty string = no override, so let's use one space
295 legendNode->setUserLabel( QStringLiteral( " " ) );
296 }
297 }
298 else if ( ruleLabel.compare( QStringLiteral( "AUTO" ), Qt::CaseInsensitive ) == 0 )
299 {
300 for ( QgsLayerTreeModelLegendNode *legendNode : model->layerLegendNodes( nodeLayer ) )
301 {
302 //clearing label for single symbol
305 }
306 }
307 }
308 }
309
310 return model.release();
311 }
312
314 {
315 std::unique_ptr<QgsLayerTree> tree( new QgsLayerTree() );
316
317 QList<QgsVectorLayerFeatureCounter *> counters;
318 for ( QgsMapLayer *ml : context.layersToRender() )
319 {
320 QgsLayerTreeLayer *lt = tree->addLayer( ml );
321 lt->setUseLayerName( false ); // do not modify underlying layer
322
323 // name
324 if ( !ml->title().isEmpty() )
325 lt->setName( ml->title() );
326
327 // show feature count
328 const bool showFeatureCount = context.parameters().showFeatureCountAsBool();
329 const QString property = QStringLiteral( "showFeatureCount" );
330 lt->setCustomProperty( property, showFeatureCount );
331
332 if ( ml->type() != QgsMapLayerType::VectorLayer || !showFeatureCount )
333 continue;
334
335 QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( ml );
337 if ( !counter )
338 continue;
339
340 counters.append( counter );
341 }
342
343 for ( QgsVectorLayerFeatureCounter *counter : counters )
344 {
345 counter->waitForFinished();
346 }
347
348 return tree.release();
349 }
350
352 {
353 if ( !projectRoot )
354 {
355 return 0;
356 }
357
358 std::unique_ptr<QgsLayerTree> tree( new QgsLayerTree() );
359
360 QgsWmsParameters wmsParams = context.parameters();
361 QStringList layerNicknames = wmsParams.allLayersNickname();
362 for ( int i = 0; i < layerNicknames.size(); ++i )
363 {
364 QString nickname = layerNicknames.at( i );
365
366 //single layer
367 QgsMapLayer *layer = context.layer( nickname );
368 if ( layer )
369 {
370 tree->addLayer( layer );
371 }
372 else //nickname refers to a group
373 {
374 QgsLayerTreeGroup *group = projectRoot->findGroup( nickname );
375 if ( group )
376 {
377 tree->insertChildNode( i, group->clone() );
378 }
379 }
380 }
381
382 return tree.release();
383 }
384
386 {
387 for ( QgsLayerTreeLayer *layer : model.rootGroup()->findLayers() )
388 {
389 for ( QgsLayerTreeModelLegendNode *node : model.layerLegendNodes( layer ) )
390 {
391 if ( node->data( Qt::DisplayRole ).toString().compare( rule ) == 0 )
392 return node;
393 }
394 }
395 return nullptr;
396 }
397} // namespace QgsWms
A helper class that centralizes restrictions given by all the access control filter plugins.
This class represents a coordinate reference system (CRS).
static QgsCoordinateReferenceSystem fromOgcWmsCrs(const QString &ogcCrs)
Creates a CRS from a given OGC WMS-format Coordinate Reference System string.
bool hasAxisInverted() const
Returns whether axis is inverted (e.g., for WMS 1.3) for the CRS.
Defines a QGIS exception class.
Definition: qgsexception.h:35
Layer tree group node serves as a container for layers and further groups.
void insertChildNode(int index, QgsLayerTreeNode *node)
Insert existing node at specified position.
QgsLayerTreeGroup * findGroup(const QString &name)
Find group node with specified name.
QgsLayerTreeGroup * clone() const override
Returns a clone of the group.
QList< QgsLayerTreeLayer * > findLayers() const
Find all layer nodes.
Layer tree node points to a map layer.
void setName(const QString &n) override
Sets the layer's name.
void setUseLayerName(bool use=true)
Uses the layer's name if use is true, or the name manually set if false.
The QgsLegendRendererItem class is abstract interface for legend items returned from QgsMapLayerLegen...
virtual void setEmbeddedInParent(bool embedded)
virtual void setUserLabel(const QString &userLabel)
The QgsLayerTreeModel class is model implementation for Qt item views framework.
QList< QgsLayerTreeModelLegendNode * > layerLegendNodes(QgsLayerTreeLayer *nodeLayer, bool skipNodeEmbeddedInParent=false)
Returns filtered list of active legend nodes attached to a particular layer node (by default it retur...
QgsLayerTree * rootGroup() const
Returns pointer to the root node of the layer tree. Always a non nullptr value.
This class is a base class for nodes in a layer tree.
void setCustomProperty(const QString &key, const QVariant &value)
Sets a custom property for the node. Properties are stored in a map and saved in project file.
QList< QgsLayerTreeNode * > children()
Gets list of children of the node. Children are owned by the parent.
Namespace with helper functions for layer tree operations.
Definition: qgslayertree.h:33
static QgsLayerTreeLayer * toLayer(QgsLayerTreeNode *node)
Cast node to a layer.
Definition: qgslayertree.h:75
static bool isLayer(const QgsLayerTreeNode *node)
Check whether the node is a valid layer node.
Definition: qgslayertree.h:53
static void setNodeLegendStyle(QgsLayerTreeNode *node, QgsLegendStyle::Style style)
Sets the style of a node.
@ Subgroup
Legend subgroup title.
@ Hidden
Special style, item is hidden including margins around.
Base class for all map layer types.
Definition: qgsmaplayer.h:73
A class to describe the version of a project.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
Definition: qgsproject.h:105
static QgsProject * instance()
Returns the QgsProject singleton instance.
Definition: qgsproject.cpp:476
A rectangle specified with double values.
Definition: qgsrectangle.h:42
bool isEmpty() const
Returns true if the rectangle is empty.
Definition: qgsrectangle.h:469
A helper class that centralizes caches accesses given by all the server cache filter plugins.
bool setCachedImage(const QByteArray *img, const QgsProject *project, const QgsServerRequest &request, QgsAccessControl *accessControl) const
Updates or inserts the image in cache like tiles.
QByteArray getCachedImage(const QgsProject *project, const QgsServerRequest &request, QgsAccessControl *accessControl) const
Returns cached image (or 0 if image not in cache) like tiles.
QgsServerInterface Class defining interfaces exposed by QGIS Server and made available to plugins.
virtual QgsServerCacheManager * cacheManager() const =0
Gets the registered server cache filters.
virtual QgsAccessControl * accessControls() const =0
Gets the registered access control filters.
QgsServerResponse Class defining response interface passed to services QgsService::executeRequest() m...
virtual void write(const QString &data)
Write string This is a convenient method that will write directly to the underlying I/O device.
virtual QByteArray data() const =0
Gets the data written so far.
virtual void setHeader(const QString &key, const QString &value)=0
Set Header entry Add Header entry to the response Note that it is usually an error to set Header afte...
virtual QIODevice * io()=0
Returns the underlying QIODevice.
bool waitForFinished(int timeout=30000)
Blocks the current thread until the task finishes or a maximum of timeout milliseconds.
Counts the features in a QgsVectorLayer in task.
Represents a vector layer which manages a vector based data sets.
QgsVectorLayerFeatureCounter * countSymbolFeatures(bool storeSymbolFids=false)
Count features for symbols.
Exception thrown in case of malformed request.
Map renderer for WMS requests.
void configureLayers(QList< QgsMapLayer * > &layers, QgsMapSettings *settings=nullptr)
Configures layers for rendering optionally considering the map settings.
QJsonObject getLegendGraphicsAsJson(QgsLayerTreeModel &model)
Returns the map legend as a JSON object.
QImage * getLegendGraphics(QgsLayerTreeModel &model)
Returns the map legend as an image (or nullptr in case of error).
Provides an interface to retrieve and manipulate WMS parameters received from the client.
QString rule() const
Returns RULE parameter or an empty string if none is defined.
QStringList allLayersNickname() const
Returns nickname of layers found in LAYER and LAYERS parameters.
QString formatAsString() const
Returns FORMAT parameter as a string.
QgsProjectVersion versionAsNumber() const
Returns VERSION parameter if defined or its default value.
QString ruleLabel() const
Returns RULELABEL parameter or an empty string if none is defined.
QgsRectangle bboxAsRectangle() const
Returns BBOX as a rectangle if defined and valid.
void set(QgsWmsParameter::Name name, const QVariant &value)
Sets a parameter value thanks to its name.
QString srcHeight() const
Returns SRCHEIGHT parameter or an empty string if not defined.
bool showFeatureCountAsBool() const
Returns SHOWFEATURECOUNT as a bool.
QString bbox() const
Returns BBOX if defined or an empty string.
Format format() const
Returns format.
bool ruleLabelAsBool() const
Returns RULELABEL as a bool.
QString srcWidth() const
Returns SRCWIDTH parameter or an empty string if not defined.
QString height() const
Returns HEIGHT parameter or an empty string if not defined.
QString crs() const
Returns CRS or an empty string if none is defined.
bool layerTitleAsBool() const
Returns LAYERTITLE as a bool or its default value if not defined.
bool addLayerGroups() const
Returns true if layer groups shall be added to GetLegendGraphic results.
Format
Output format for the response.
QString width() const
Returns WIDTH parameter or an empty string if not defined.
Rendering context for the WMS renderer.
QSize mapSize(bool aspectRatio=true) const
Returns the size (in pixels) of the map to render, according to width and height WMS parameters as we...
void setParameters(const QgsWmsParameters &parameters)
Sets WMS parameters.
QList< QgsMapLayer * > layersToRender() const
Returns a list of all layers to actually render according to the current configuration.
QgsMapLayer * layer(const QString &nickname) const
Returns the layer corresponding to the nickname, or a nullptr if not found or if the layer do not nee...
void setFlag(Flag flag, bool on=true)
Sets or unsets a rendering flag according to the on value.
QgsWmsParameters parameters() const
Returns WMS parameters.
double scaleDenominator() const
Returns the scale denominator to use for rendering according to the current configuration.
int imageQuality() const
Returns the image quality to use for rendering according to the current configuration.
Class defining request interface passed to WMS service.
Definition: qgswmsrequest.h:35
const QgsWmsParameters & wmsParameters() const
Returns the parameters interpreted for the WMS service.
@ VectorLayer
Vector layer.
SERVER_EXPORT bool wmsAddLegendGroupsLegendGraphic(const QgsProject &project)
Returns if legend groups should be in the legend graphic response if GetLegendGraphic is called on a ...
Median cut implementation.
void writeImage(QgsServerResponse &response, QImage &img, const QString &formatStr, int imageQuality)
Write image response.
void writeGetLegendGraphics(QgsServerInterface *serverIface, const QgsProject *project, const QgsWmsRequest &request, QgsServerResponse &response)
Output GetLegendGRaphics response.
QgsLayerTree * layerTree(const QgsWmsRenderContext &context)
QgsLayerTreeModelLegendNode * legendNode(const QString &rule, QgsLayerTreeModel &model)
QgsLayerTreeModel * legendModel(const QgsWmsRenderContext &context, QgsLayerTree &tree)
QgsLayerTree * layerTreeWithGroups(const QgsWmsRenderContext &context, QgsLayerTree *projectRoot)
@ Unknown
Unknown/invalid format.
ImageOutputFormat parseImageFormat(const QString &format)
Parse image format parameter.
Definition: qgswmsutils.cpp:74
void checkParameters(QgsWmsParameters &parameters)
checkParameters checks request parameters and sets SRCHEIGHT and SRCWIDTH to default values in case B...
const QgsCoordinateReferenceSystem & outputCrs
const QgsCoordinateReferenceSystem & crs