QGIS API Documentation 3.34.0-Prizren (ffbdd678812)
Loading...
Searching...
No Matches
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"
26
27#include "qgswmsutils.h"
28#include "qgswmsrequest.h"
31#include "qgswmsrenderer.h"
33#include "qgsmapsettings.h"
34
35#include <QImage>
36#include <QJsonObject>
37#include <QJsonDocument>
38
39namespace QgsWms
40{
41 void writeGetLegendGraphics( QgsServerInterface *serverIface, const QgsProject *project,
42 const QgsWmsRequest &request,
43 QgsServerResponse &response )
44 {
45 // get parameters from query
46 QgsWmsParameters parameters = request.wmsParameters();
47
48 // check parameters validity
49 // FIXME fail with png + mode
50 checkParameters( parameters );
51
52 // init render context
53 QgsWmsRenderContext context( project, serverIface );
56 context.setParameters( parameters );
57
58 // get the requested output format
59 QgsWmsParameters::Format format = parameters.format();
60
61 // parameters.format() returns NONE if the requested format is image/png with a
62 // mode (e.g. image/png;mode=16bit), so in that case we use parseImageFormat to
63 // give the requested format another chance
64
65 QString imageSaveFormat;
66 QString imageContentType;
67 if ( format == QgsWmsParameters::Format::PNG )
68 {
69 imageContentType = "image/png";
70 imageSaveFormat = "PNG";
71 }
72 else if ( format == QgsWmsParameters::Format::JPG )
73 {
74 imageContentType = "image/jpeg";
75 imageSaveFormat = "JPEG";
76 }
77 else if ( format == QgsWmsParameters::Format::NONE )
78 {
79 switch ( parseImageFormat( parameters.formatAsString() ) )
80 {
86 imageContentType = "image/png";
87 imageSaveFormat = "PNG";
88 break;
90 break;
91
92 // not possible
95 break;
96 }
97 }
98
99 if ( format == QgsWmsParameters::Format::NONE )
100 {
102 QStringLiteral( "Output format '%1' is not supported in the GetLegendGraphic request" ).arg( parameters.formatAsString() ) );
103 }
104
105 // Get cached image
106#ifdef HAVE_SERVER_PYTHON_PLUGINS
107 QgsAccessControl *accessControl = serverIface->accessControls();
108 QgsServerCacheManager *cacheManager = serverIface->cacheManager();
109 if ( cacheManager && !imageSaveFormat.isEmpty() )
110 {
111 QImage image;
112 const QByteArray content = cacheManager->getCachedImage( project, request, accessControl );
113 if ( !content.isEmpty() && image.loadFromData( content ) )
114 {
115 response.setHeader( QStringLiteral( "Content-Type" ), imageContentType );
116 image.save( response.io(), qPrintable( imageSaveFormat ) );
117 return;
118 }
119 }
120#endif
121 QgsRenderer renderer( context );
122
123 // retrieve legend settings and model
124 bool addLegendGroups = QgsServerProjectUtils::wmsAddLegendGroupsLegendGraphic( *project ) || parameters.addLayerGroups();
125 std::unique_ptr<QgsLayerTree> tree( addLegendGroups ? layerTreeWithGroups( context, QgsProject::instance()->layerTreeRoot() ) : layerTree( context ) );
126 const std::unique_ptr<QgsLayerTreeModel> model( legendModel( context, *tree.get() ) );
127
128 // rendering
129 if ( format == QgsWmsParameters::Format::JSON )
130 {
131 QJsonObject result;
132 if ( !parameters.rule().isEmpty() )
133 {
135 QStringLiteral( "RULE cannot be used with JSON format" ) );
136 }
137 else
138 {
139 result = renderer.getLegendGraphicsAsJson( *model.get() );
140 }
141 tree->clear();
142 response.setHeader( QStringLiteral( "Content-Type" ), parameters.formatAsString() );
143 const QJsonDocument doc( result );
144 response.write( doc.toJson( QJsonDocument::Compact ) );
145 }
146 else
147 {
148 std::unique_ptr<QImage> result;
149 if ( !parameters.rule().isEmpty() )
150 {
151 QgsLayerTreeModelLegendNode *node = legendNode( parameters.rule(), *model.get() );
152 if ( ! node )
153 {
154 throw QgsException( QStringLiteral( "Could not get a legend node for the requested RULE" ) );
155 }
156 result.reset( renderer.getLegendGraphics( *node ) );
157 }
158 else
159 {
160 result.reset( renderer.getLegendGraphics( *model.get() ) );
161 }
162 tree->clear();
163 if ( result )
164 {
165 writeImage( response, *result, parameters.formatAsString(), context.imageQuality() );
166#ifdef HAVE_SERVER_PYTHON_PLUGINS
167 if ( cacheManager )
168 {
169 const QByteArray content = response.data();
170 if ( !content.isEmpty() )
171 cacheManager->setCachedImage( &content, project, request, accessControl );
172 }
173#endif
174 }
175 else
176 {
177 throw QgsException( QStringLiteral( "Failed to compute GetLegendGraphics image" ) );
178 }
179 }
180 }
181
183 {
184 if ( parameters.allLayersNickname().isEmpty() )
185 {
187 parameters[QgsWmsParameter::LAYERS] );
188 }
189
190 if ( parameters.format() == QgsWmsParameters::Format::NONE )
191 {
193 parameters[QgsWmsParameter::FORMAT] );
194 }
195
196 if ( ! parameters.bbox().isEmpty() && !parameters.rule().isEmpty() )
197 {
199 QStringLiteral( "BBOX parameter cannot be combined with RULE." ) );
200 }
201
202 if ( ! parameters.bbox().isEmpty() && parameters.bboxAsRectangle().isEmpty() )
203 {
205 parameters[QgsWmsParameter::BBOX] );
206 }
207 // If we have a contextual legend (BBOX is set)
208 // make sure (SRC)WIDTH and (SRC)HEIGHT are set, default to 800px width
209 // height is calculated from that value, respecting the aspect
210 if ( ! parameters.bbox().isEmpty() )
211 {
212 // Calculate ratio from bbox
213 QgsRectangle bbox { parameters.bboxAsRectangle() };
214 const QString crs = parameters.crs();
215 if ( crs.compare( QStringLiteral( "CRS:84" ), Qt::CaseInsensitive ) == 0 )
216 {
217 bbox.invert();
218 }
220 if ( parameters.versionAsNumber() >= QgsProjectVersion( 1, 3, 0 ) &&
222 {
223 bbox.invert();
224 }
225 const double ratio { bbox.width() / bbox.height() };
226 const int defaultHeight { static_cast<int>( 800 / ratio ) };
227 if ( parameters.width().isEmpty() && parameters.srcWidth().isEmpty() )
228 {
229 parameters.set( QgsWmsParameter::SRCWIDTH, 800 );
230 }
231 if ( parameters.height().isEmpty() && parameters.srcHeight().isEmpty() )
232 {
233 parameters.set( QgsWmsParameter::SRCHEIGHT, defaultHeight );
234 }
235 }
236 }
237
239 {
240
241 const QgsWmsParameters parameters = context.parameters();
242 std::unique_ptr<QgsLayerTreeModel> model( new QgsLayerTreeModel( &tree ) );
243 std::unique_ptr<QgsMapSettings> mapSettings;
244
245 if ( context.scaleDenominator() > 0 )
246 {
247 model->setLegendFilterByScale( context.scaleDenominator() );
248 }
249
250 // content based legend
251 if ( ! parameters.bbox().isEmpty() )
252 {
253 mapSettings = std::make_unique<QgsMapSettings>();
254 mapSettings->setOutputSize( context.mapSize() );
255 // Inverted axis?
256 QgsRectangle bbox { parameters.bboxAsRectangle() };
257 const QString crs = parameters.crs();
258 if ( crs.compare( QStringLiteral( "CRS:84" ), Qt::CaseInsensitive ) == 0 )
259 {
260 bbox.invert();
261 }
263 if ( parameters.versionAsNumber() >= QgsProjectVersion( 1, 3, 0 ) &&
265 {
266 bbox.invert();
267 }
268 mapSettings->setDestinationCrs( outputCrs );
269 mapSettings->setExtent( bbox );
270 QgsRenderer renderer( context );
271 QList<QgsMapLayer *> layers = context.layersToRender();
272 renderer.configureLayers( layers, mapSettings.get() );
273 mapSettings->setLayers( context.layersToRender() );
274
275 QgsLayerTreeFilterSettings filterSettings( *mapSettings );
276 filterSettings.setLayerFilterExpressionsFromLayerTree( model->rootGroup() );
277 model->setFilterSettings( &filterSettings );
278 }
279
280 // if legend is not based on rendering rules
281 if ( parameters.rule().isEmpty() )
282 {
283 const QList<QgsLayerTreeNode *> children = tree.children();
284 const QString ruleLabel = parameters.ruleLabel();
285 for ( QgsLayerTreeNode *node : children )
286 {
287 if ( ! QgsLayerTree::isLayer( node ) )
288 continue;
289
290 QgsLayerTreeLayer *nodeLayer = QgsLayerTree::toLayer( node );
291
292 // layer titles - hidden or not
294 // rule item titles
295 if ( !parameters.ruleLabelAsBool() )
296 {
297 for ( QgsLayerTreeModelLegendNode *legendNode : model->layerLegendNodes( nodeLayer ) )
298 {
299 // empty string = no override, so let's use one space
300 legendNode->setUserLabel( QStringLiteral( " " ) );
301 }
302 }
303 else if ( ruleLabel.compare( QStringLiteral( "AUTO" ), Qt::CaseInsensitive ) == 0 )
304 {
305 for ( QgsLayerTreeModelLegendNode *legendNode : model->layerLegendNodes( nodeLayer ) )
306 {
307 //clearing label for single symbol
310 }
311 }
312 }
313 }
314
315 return model.release();
316 }
317
319 {
320 std::unique_ptr<QgsLayerTree> tree( new QgsLayerTree() );
321
322 QList<QgsVectorLayerFeatureCounter *> counters;
323 for ( QgsMapLayer *ml : context.layersToRender() )
324 {
325 QgsLayerTreeLayer *lt = tree->addLayer( ml );
326 lt->setUseLayerName( false ); // do not modify underlying layer
327
328 // name
329 if ( !ml->title().isEmpty() )
330 lt->setName( ml->title() );
331
332 // show feature count
333 const bool showFeatureCount = context.parameters().showFeatureCountAsBool();
334 const QString property = QStringLiteral( "showFeatureCount" );
335 lt->setCustomProperty( property, showFeatureCount );
336
337 if ( ml->type() != Qgis::LayerType::Vector || !showFeatureCount )
338 continue;
339
340 QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( ml );
342 if ( !counter )
343 continue;
344
345 counters.append( counter );
346 }
347
348 for ( QgsVectorLayerFeatureCounter *counter : counters )
349 {
350 counter->waitForFinished();
351 }
352
353 return tree.release();
354 }
355
357 {
358 if ( !projectRoot )
359 {
360 return 0;
361 }
362
363 std::unique_ptr<QgsLayerTree> tree( new QgsLayerTree() );
364
365 QgsWmsParameters wmsParams = context.parameters();
366 QStringList layerNicknames = wmsParams.allLayersNickname();
367 for ( int i = 0; i < layerNicknames.size(); ++i )
368 {
369 QString nickname = layerNicknames.at( i );
370
371 //single layer
372 QgsMapLayer *layer = context.layer( nickname );
373 if ( layer )
374 {
375 tree->addLayer( layer );
376 }
377 else //nickname refers to a group
378 {
379 QgsLayerTreeGroup *group = projectRoot->findGroup( nickname );
380 if ( group )
381 {
382 tree->insertChildNode( i, group->clone() );
383 }
384 }
385 }
386
387 return tree.release();
388 }
389
391 {
392 for ( QgsLayerTreeLayer *layer : model.rootGroup()->findLayers() )
393 {
394 for ( QgsLayerTreeModelLegendNode *node : model.layerLegendNodes( layer ) )
395 {
396 if ( node->data( Qt::DisplayRole ).toString().compare( rule ) == 0 )
397 return node;
398 }
399 }
400 return nullptr;
401 }
402} // namespace QgsWms
@ Vector
Vector layer.
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 the axis order is inverted for the CRS compared to the order east/north (longitude/la...
Defines a QGIS exception class.
Contains settings relating to filtering the contents of QgsLayerTreeModel and views.
void setLayerFilterExpressionsFromLayerTree(QgsLayerTree *tree)
Sets layer filter expressions using a layer tree.
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.
static QgsLayerTreeLayer * toLayer(QgsLayerTreeNode *node)
Cast node to a layer.
static bool isLayer(const QgsLayerTreeNode *node)
Check whether the node is a valid layer node.
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:74
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:107
static QgsProject * instance()
Returns the QgsProject singleton instance.
A rectangle specified with double values.
bool isEmpty() const
Returns true if the rectangle has no area.
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.
const QgsWmsParameters & wmsParameters() const
Returns the parameters interpreted for the WMS service.
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.
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