QGIS API Documentation  2.18.21-Las Palmas (9fba24a)
qgsmaphittest.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsmaphittest.cpp
3  ---------------------
4  begin : September 2014
5  copyright : (C) 2014 by Martin Dobias
6  email : wonder dot sk at gmail dot com
7  ***************************************************************************
8  * *
9  * This program is free software; you can redistribute it and/or modify *
10  * it under the terms of the GNU General Public License as published by *
11  * the Free Software Foundation; either version 2 of the License, or *
12  * (at your option) any later version. *
13  * *
14  ***************************************************************************/
15 #include <QScopedPointer>
16 
17 #include "qgsmaphittest.h"
18 
19 #include "qgsmaplayerregistry.h"
20 #include "qgsrendercontext.h"
22 #include "qgsrendererv2.h"
24 #include "qgsvectorlayer.h"
25 #include "qgssymbollayerv2utils.h"
26 #include "qgsgeometry.h"
27 #include "qgscrscache.h"
28 
29 QgsMapHitTest::QgsMapHitTest( const QgsMapSettings& settings, const QgsGeometry& polygon, const LayerFilterExpression& layerFilterExpression )
30  : mSettings( settings )
31  , mLayerFilterExpression( layerFilterExpression )
32  , mOnlyExpressions( false )
33 {
34  if ( !polygon.isEmpty() && polygon.type() == QGis::Polygon )
35  {
36  mPolygon = polygon;
37  }
38 }
39 
40 QgsMapHitTest::QgsMapHitTest( const QgsMapSettings& settings, const LayerFilterExpression& layerFilterExpression )
41  : mSettings( settings )
42  , mLayerFilterExpression( layerFilterExpression )
43  , mOnlyExpressions( true )
44 {
45 }
46 
48 {
49  // TODO: do we need this temp image?
51  tmpImage.setDotsPerMeterX( mSettings.outputDpi() * 25.4 );
52  tmpImage.setDotsPerMeterY( mSettings.outputDpi() * 25.4 );
53  QPainter painter( &tmpImage );
54 
56  context.setPainter( &painter ); // we are not going to draw anything, but we still need a working painter
57 
58  Q_FOREACH ( const QString& layerID, mSettings.layers() )
59  {
60  QgsVectorLayer* vl = qobject_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( layerID ) );
61  if ( !vl || !vl->rendererV2() )
62  continue;
63 
64  if ( !mOnlyExpressions )
65  {
66  if ( !vl->isInScaleRange( mSettings.scale() ) )
67  {
68  mHitTest[vl] = SymbolV2Set(); // no symbols -> will not be shown
70  continue;
71  }
72 
74  {
77  }
78  }
79 
81  SymbolV2Set& usedSymbols = mHitTest[vl];
82  SymbolV2Set& usedSymbolsRuleKey = mHitTestRuleKey[vl];
83  runHitTestLayer( vl, usedSymbols, usedSymbolsRuleKey, context );
84  }
85 
86  painter.end();
87 }
88 
90 {
91  if ( !symbol || !layer || !mHitTest.contains( layer ) )
92  return false;
93 
94  return mHitTest.value( layer ).contains( QgsSymbolLayerV2Utils::symbolProperties( symbol ) );
95 }
96 
97 bool QgsMapHitTest::legendKeyVisible( const QString& ruleKey, QgsVectorLayer* layer ) const
98 {
99  if ( !layer || !mHitTestRuleKey.contains( layer ) )
100  return false;
101 
102  return mHitTestRuleKey.value( layer ).contains( ruleKey );
103 }
104 
105 void QgsMapHitTest::runHitTestLayer( QgsVectorLayer* vl, SymbolV2Set& usedSymbols, SymbolV2Set& usedSymbolsRuleKey, QgsRenderContext& context )
106 {
107  bool hasStyleOverride = mSettings.layerStyleOverrides().contains( vl->id() );
108  if ( hasStyleOverride )
110 
111  QgsFeatureRendererV2* r = vl->rendererV2();
112  bool moreSymbolsPerFeature = r->capabilities() & QgsFeatureRendererV2::MoreSymbolsPerFeature;
113  r->startRender( context, vl->fields() );
114 
115  QgsGeometry transformedPolygon = mPolygon;
116  if ( !mOnlyExpressions && !mPolygon.isEmpty() )
117  {
118  if ( mSettings.destinationCrs() != vl->crs() )
119  {
121  transformedPolygon.transform( *ct );
122  }
123  }
124 
125  QgsFeature f;
126  QgsFeatureRequest request;
127  if ( !mOnlyExpressions )
128  {
129  if ( mPolygon.isEmpty() )
130  {
131  request.setFilterRect( context.extent() );
133  }
134  else
135  {
136  request.setFilterRect( transformedPolygon.boundingBox() );
137  }
138  }
139  QgsFeatureIterator fi = vl->getFeatures( request );
140 
141  SymbolV2Set lUsedSymbols;
142  SymbolV2Set lUsedSymbolsRuleKey;
143  bool allExpressionFalse = false;
144  bool hasExpression = mLayerFilterExpression.contains( vl->id() );
146  if ( hasExpression )
147  {
148  expr.reset( new QgsExpression( mLayerFilterExpression[vl->id()] ) );
149  expr->prepare( &context.expressionContext() );
150  }
151  while ( fi.nextFeature( f ) )
152  {
153  context.expressionContext().setFeature( f );
154  // filter out elements outside of the polygon
155  if ( !mOnlyExpressions && !mPolygon.isEmpty() )
156  {
157  if ( !transformedPolygon.intersects( f.constGeometry() ) )
158  {
159  continue;
160  }
161  }
162 
163  // filter out elements where the expression is false
164  if ( hasExpression )
165  {
166  if ( !expr->evaluate( &context.expressionContext() ).toBool() )
167  continue;
168  else
169  allExpressionFalse = false;
170  }
171 
172  //make sure we store string representation of symbol, not pointer
173  //otherwise layer style override changes will delete original symbols and leave hanging pointers
174  Q_FOREACH ( const QString& legendKey, r->legendKeysForFeature( f, context ) )
175  {
176  lUsedSymbolsRuleKey.insert( legendKey );
177  }
178 
179  if ( moreSymbolsPerFeature )
180  {
181  Q_FOREACH ( QgsSymbolV2* s, r->originalSymbolsForFeature( f, context ) )
182  {
183  if ( s )
184  lUsedSymbols.insert( QgsSymbolLayerV2Utils::symbolProperties( s ) );
185  }
186  }
187  else
188  {
189  QgsSymbolV2* s = r->originalSymbolForFeature( f, context );
190  if ( s )
191  lUsedSymbols.insert( QgsSymbolLayerV2Utils::symbolProperties( s ) );
192  }
193  }
194  r->stopRender( context );
195 
196  if ( !allExpressionFalse )
197  {
198  // QSet is implicitly shared => constant time
199  usedSymbols = lUsedSymbols;
200  usedSymbolsRuleKey = lUsedSymbolsRuleKey;
201  }
202 
203  if ( hasStyleOverride )
205 }
206 
bool restoreOverrideStyle()
Restore the original store after a call to setOverrideStyle()
HitTest mHitTest
The hit test.
Definition: qgsmaphittest.h:89
Class for parsing and evaluation of expressions (formerly called "search strings").
Wrapper for iterator of features from vector data provider or vector layer.
HitTest mHitTestRuleKey
The hit test, using legend rule keys.
Definition: qgsmaphittest.h:92
void setDotsPerMeterX(int x)
virtual QSet< QString > legendKeysForFeature(QgsFeature &feature, QgsRenderContext &context)
Return legend keys matching a specified feature.
bool intersects(const QgsRectangle &r) const
Test for intersection with a rectangle (uses GEOS)
bool end()
bool contains(const Key &key) const
Use exact geometry intersection (slower) instead of bounding boxes.
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
virtual Q_DECL_DEPRECATED QgsSymbolV2 * originalSymbolForFeature(QgsFeature &feature)
Return symbol for feature.
QgsMapLayer * mapLayer(const QString &theLayerId) const
Retrieve a pointer to a registered layer by layer ID.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest())
Query the provider for features specified in request.
const QgsCoordinateReferenceSystem & crs() const
Returns layer&#39;s spatial reference system.
bool hasCrsTransformEnabled() const
returns true if projections are enabled for this layer set
bool isInScaleRange(double scale) const
Tests whether the layer should be visible at the specified scale.
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:76
const QgsGeometry * constGeometry() const
Gets a const pointer to the geometry object associated with this feature.
Definition: qgsfeature.cpp:82
QgsMapHitTest(const QgsMapSettings &settings, const QgsGeometry &polygon=QgsGeometry(), const LayerFilterExpression &layerFilterExpression=LayerFilterExpression())
const_iterator insert(const T &value)
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:187
static QgsCoordinateTransformCache * instance()
Definition: qgscrscache.cpp:22
void setExtent(const QgsRectangle &extent)
QgsRectangle visibleExtent() const
Return the actual extent derived from requested extent that takes takes output image size into accoun...
virtual void startRender(QgsRenderContext &context, const QgsFields &fields)=0
Needs to be called when a new render cycle is started.
void reset(T *other)
QgsFields fields() const
Returns the list of fields of this layer.
The QgsMapSettings class contains configuration for rendering of the map.
virtual void stopRender(QgsRenderContext &context)=0
Needs to be called when a render cycle has finished to clean up.
void setCoordinateTransform(const QgsCoordinateTransform *t)
Sets coordinate transformation.
QgsMapLayerStyleManager * styleManager() const
Get access to the layer&#39;s style manager.
virtual Q_DECL_DEPRECATED QgsSymbolV2List originalSymbolsForFeature(QgsFeature &feat)
Equivalent of originalSymbolsForFeature() call extended to support renderers that may use more symbol...
const QgsCoordinateTransform * transform(const QString &srcAuthId, const QString &destAuthId, int srcDatumTransform=-1, int destDatumTransform=-1)
Returns coordinate transformation.
Definition: qgscrscache.cpp:41
QgsFeatureRendererV2 * rendererV2()
Return renderer V2.
QString id() const
Get this layer&#39;s unique ID, this ID is used to access this layer from map layer registry.
LayerFilterExpression mLayerFilterExpression
List of expression filter for each layer.
Definition: qgsmaphittest.h:95
const QgsRectangle & extent() const
double scale() const
Return the calculated scale of the map.
QSet< QString > SymbolV2Set
Definition: qgsmaphittest.h:70
QImage::Format outputImageFormat() const
format of internal QImage, default QImage::Format_ARGB32_Premultiplied
This class wraps a request for features to a vector layer (or directly its vector data provider)...
bool isEmpty() const
Returns true if the geometry is empty (ie, contains no underlying geometry accessible via geometry)...
void setPainter(QPainter *p)
QgsFeatureRequest & setFlags(const QgsFeatureRequest::Flags &flags)
Set flags that affect how features will be fetched.
const QgsCoordinateTransform * layerTransform(QgsMapLayer *layer) const
Return coordinate transform from layer&#39;s CRS to destination CRS.
QGis::GeometryType type() const
Returns type of the geometry as a QGis::GeometryType.
bool symbolVisible(QgsSymbolV2 *symbol, QgsVectorLayer *layer) const
Tests whether a symbol is visible for a specified layer.
QgsExpressionContext & expressionContext()
Gets the expression context.
double outputDpi() const
Return DPI used for conversion between real world units (e.g.
void run()
Runs the map hit test.
Contains information about the context of a rendering operation.
may use more than one symbol to render a feature: symbolsForFeature() will return them ...
QMap< QString, QString > layerStyleOverrides() const
Get map of map layer style overrides (key: layer ID, value: style name) where a different style shoul...
static QgsMapLayerRegistry * instance()
Returns the instance pointer, creating the object on the first call.
QgsGeometry mPolygon
Polygon used for filtering items. May be empty.
Definition: qgsmaphittest.h:98
static QgsRenderContext fromMapSettings(const QgsMapSettings &mapSettings)
create initialized QgsRenderContext instance from given QgsMapSettings
static QString symbolProperties(QgsSymbolV2 *symbol)
Returns a string representing the symbol.
QgsRectangle boundingBox() const
Returns the bounding box of this feature.
bool mOnlyExpressions
Whether to use only expressions during the filtering.
Class for doing transforms between two map coordinate systems.
int transform(const QgsCoordinateTransform &ct)
Transform this geometry as described by CoordinateTransform ct.
bool legendKeyVisible(const QString &ruleKey, QgsVectorLayer *layer) const
Tests whether a given legend key is visible for a specified layer.
bool setOverrideStyle(const QString &styleDef)
Temporarily apply a different style to the layer.
static QgsExpressionContextScope * layerScope(const QgsMapLayer *layer)
Creates a new scope which contains variables and functions relating to a QgsMapLayer.
virtual int capabilities()
returns bitwise OR-ed capabilities of the renderer
bool nextFeature(QgsFeature &f)
QStringList layers() const
Get list of layer IDs for map rendering The layers are stored in the reverse order of how they are re...
Represents a vector layer which manages a vector based data sets.
void runHitTestLayer(QgsVectorLayer *vl, SymbolV2Set &usedSymbols, SymbolV2Set &usedSymbolsRuleKey, QgsRenderContext &context)
Runs test for visible symbols within a layer.
QSize outputSize() const
Return the size of the resulting map image.
const QgsCoordinateReferenceSystem & destinationCrs() const
returns CRS of destination coordinate reference system
QgsRectangle outputExtentToLayerExtent(QgsMapLayer *theLayer, QgsRectangle extent) const
transform bounding box from output CRS to layer&#39;s CRS
QString authid() const
Returns the authority identifier for the CRS, which includes both the authority (eg EPSG) and the CRS...
QgsFeatureRequest & setFilterRect(const QgsRectangle &rect)
Set rectangle from which features will be taken.
QgsMapSettings mSettings
The initial map settings.
Definition: qgsmaphittest.h:86
const T value(const Key &key) const