QGIS API Documentation  3.18.1-Zürich (202f1bf7e5)
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
qgsvectorlayerrenderer.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsvectorlayerrenderer.cpp
3  --------------------------------------
4  Date : December 2013
5  Copyright : (C) 2013 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 
16 #include "qgsvectorlayerrenderer.h"
17 
18 #include "diagram/qgsdiagram.h"
19 
20 #include "qgsdiagramrenderer.h"
21 #include "qgsmessagelog.h"
22 #include "qgspallabeling.h"
23 #include "qgsrenderer.h"
24 #include "qgsrendercontext.h"
26 #include "qgssymbollayer.h"
27 #include "qgssymbollayerutils.h"
28 #include "qgssymbol.h"
29 #include "qgsvectorlayer.h"
32 #include "qgsvectorlayerlabeling.h"
34 #include "qgspainteffect.h"
36 #include "qgsexception.h"
37 #include "qgslogger.h"
38 #include "qgssettings.h"
42 #include "qgsmapclippingutils.h"
44 
45 #include <QPicture>
46 #include <QTimer>
47 
49  : QgsMapLayerRenderer( layer->id(), &context )
50  , mLayer( layer )
51  , mFields( layer->fields() )
52  , mLabeling( false )
53  , mDiagrams( false )
54 {
55  mSource = qgis::make_unique< QgsVectorLayerFeatureSource >( layer );
56 
57  std::unique_ptr< QgsFeatureRenderer > mainRenderer( layer->renderer() ? layer->renderer()->clone() : nullptr );
58 
59  if ( !mainRenderer )
60  return;
61 
62  QList< const QgsFeatureRendererGenerator * > generators = layer->featureRendererGenerators();
63  std::sort( generators.begin(), generators.end(), []( const QgsFeatureRendererGenerator * g1, const QgsFeatureRendererGenerator * g2 )
64  {
65  return g1->level() < g2->level();
66  } );
67 
68  bool insertedMainRenderer = false;
69  double prevLevel = std::numeric_limits< double >::lowest();
70  mRenderer = mainRenderer.get();
71  for ( const QgsFeatureRendererGenerator *generator : qgis::as_const( generators ) )
72  {
73  if ( generator->level() >= 0 && prevLevel < 0 && !insertedMainRenderer )
74  {
75  // insert main renderer when level changes from <0 to >0
76  mRenderers.emplace_back( std::move( mainRenderer ) );
77  insertedMainRenderer = true;
78  }
79  mRenderers.emplace_back( generator->createRenderer() );
80  prevLevel = generator->level();
81  }
82  // cppcheck-suppress accessMoved
83  if ( mainRenderer )
84  {
85  // cppcheck-suppress accessMoved
86  mRenderers.emplace_back( std::move( mainRenderer ) );
87  }
88 
90 
91  mDrawVertexMarkers = nullptr != layer->editBuffer();
92 
93  mGeometryType = layer->geometryType();
94 
96 
97  if ( context.isTemporal() )
98  {
99  QgsVectorLayerTemporalContext temporalContext;
100  temporalContext.setLayer( layer );
101  mTemporalFilter = qobject_cast< const QgsVectorLayerTemporalProperties * >( layer->temporalProperties() )->createFilterString( temporalContext, context.temporalRange() );
102  }
103 
104  // if there's already a simplification method specified via the context, we respect that. Otherwise, we fall back
105  // to the layer's individual setting
106  if ( renderContext()->vectorSimplifyMethod().simplifyHints() != QgsVectorSimplifyMethod::NoSimplification )
107  {
111  }
112  else
113  {
114  mSimplifyMethod = layer->simplifyMethod();
116  }
117 
118  QgsSettings settings;
119  mVertexMarkerOnlyForSelection = settings.value( QStringLiteral( "qgis/digitizing/marker_only_for_selected" ), true ).toBool();
120 
121  QString markerTypeString = settings.value( QStringLiteral( "qgis/digitizing/marker_style" ), "Cross" ).toString();
122  if ( markerTypeString == QLatin1String( "Cross" ) )
123  {
125  }
126  else if ( markerTypeString == QLatin1String( "SemiTransparentCircle" ) )
127  {
129  }
130  else
131  {
133  }
134 
135  mVertexMarkerSize = settings.value( QStringLiteral( "qgis/digitizing/marker_size_mm" ), 2.0 ).toDouble();
136 
137  QgsDebugMsgLevel( "rendering v2:\n " + mRenderer->dump(), 2 );
138 
139  if ( mDrawVertexMarkers )
140  {
141  // set editing vertex markers style (main renderer only)
143  }
145 
146  for ( const std::unique_ptr< QgsFeatureRenderer > &renderer : mRenderers )
147  {
148  mAttrNames.unite( renderer->usedAttributes( context ) );
149  }
150  if ( context.hasRenderedFeatureHandlers() )
151  {
152  const QList< QgsRenderedFeatureHandlerInterface * > handlers = context.renderedFeatureHandlers();
153  for ( QgsRenderedFeatureHandlerInterface *handler : handlers )
154  mAttrNames.unite( handler->usedAttributes( layer, context ) );
155  }
156 
157  //register label and diagram layer to the labeling engine
158  prepareLabeling( layer, mAttrNames );
159  prepareDiagrams( layer, mAttrNames );
160 
162 
163  for ( const std::unique_ptr< QgsFeatureRenderer > &renderer : mRenderers )
164  {
165  if ( renderer->forceRasterRender() )
166  {
167  //raster rendering is forced for this layer
168  mForceRasterRender = true;
169  break;
170  }
171  }
172 
174  ( ( layer->blendMode() != QPainter::CompositionMode_SourceOver )
175  || ( layer->featureBlendMode() != QPainter::CompositionMode_SourceOver )
176  || ( !qgsDoubleNear( layer->opacity(), 1.0 ) ) ) )
177  {
178  //layer properties require rasterization
179  mForceRasterRender = true;
180  }
181 
182  mReadyToCompose = false;
183 }
184 
186 
188 {
189  mRenderTimeHint = time;
190 }
191 
193 {
194  return mInterruptionChecker.get();
195 }
196 
198 {
199  return mForceRasterRender;
200 }
201 
203 {
205  {
206  mReadyToCompose = true;
207  return true;
208  }
209 
210  if ( mRenderers.empty() )
211  {
212  mReadyToCompose = true;
213  mErrors.append( QObject::tr( "No renderer for drawing." ) );
214  return false;
215  }
216 
217  // if the previous layer render was relatively quick (e.g. less than 3 seconds), the we show any previously
218  // cached version of the layer during rendering instead of the usual progressive updates
220  {
221  mBlockRenderUpdates = true;
222  mElapsedTimer.start();
223  }
224 
225  bool res = true;
226  for ( const std::unique_ptr< QgsFeatureRenderer > &renderer : mRenderers )
227  {
228  res = renderInternal( renderer.get() ) && res;
229  }
230 
231  mReadyToCompose = true;
232  return res && !renderContext()->renderingStopped();
233 }
234 
235 bool QgsVectorLayerRenderer::renderInternal( QgsFeatureRenderer *renderer )
236 {
237  const bool isMainRenderer = renderer == mRenderer;
238 
239  if ( renderer->type() == QLatin1String( "nullSymbol" ) )
240  {
241  // a little shortcut for the null symbol renderer - most of the time it is not going to render anything
242  // so we can even skip the whole loop to fetch features
243  if ( !isMainRenderer ||
245  return true;
246  }
247 
248  QgsRenderContext &context = *renderContext();
249 
250  QgsScopedQPainterState painterState( context.painter() );
251 
252  // MUST be created in the thread doing the rendering
253  mInterruptionChecker = qgis::make_unique< QgsVectorLayerRendererInterruptionChecker >( context );
254  bool usingEffect = false;
255  if ( renderer->paintEffect() && renderer->paintEffect()->enabled() )
256  {
257  usingEffect = true;
258  renderer->paintEffect()->begin( context );
259  }
260 
261  // Per feature blending mode
262  if ( context.useAdvancedEffects() && mFeatureBlendMode != QPainter::CompositionMode_SourceOver )
263  {
264  // set the painter to the feature blend mode, so that features drawn
265  // on this layer will interact and blend with each other
266  context.painter()->setCompositionMode( mFeatureBlendMode );
267  }
268 
269  renderer->startRender( context, mFields );
270 
271  QString rendererFilter = renderer->filter( mFields );
272 
273  QgsRectangle requestExtent = context.extent();
274  if ( !mClippingRegions.empty() )
275  {
277  requestExtent = requestExtent.intersect( mClipFilterGeom.boundingBox() );
278 
280 
281  bool needsPainterClipPath = false;
282  const QPainterPath path = QgsMapClippingUtils::calculatePainterClipRegion( mClippingRegions, context, QgsMapLayerType::VectorLayer, needsPainterClipPath );
283  if ( needsPainterClipPath )
284  context.painter()->setClipPath( path, Qt::IntersectClip );
285 
287 
288  if ( mDiagramProvider )
290  }
291  renderer->modifyRequestExtent( requestExtent, context );
292 
293  QgsFeatureRequest featureRequest = QgsFeatureRequest()
294  .setFilterRect( requestExtent )
297  if ( renderer->orderByEnabled() )
298  {
299  featureRequest.setOrderBy( renderer->orderBy() );
300  }
301 
302  const QgsFeatureFilterProvider *featureFilterProvider = context.featureFilterProvider();
303  if ( featureFilterProvider )
304  {
305  featureFilterProvider->filterFeatures( mLayer, featureRequest );
306  }
307  if ( !rendererFilter.isEmpty() && rendererFilter != QLatin1String( "TRUE" ) )
308  {
309  featureRequest.combineFilterExpression( rendererFilter );
310  }
311  if ( !mTemporalFilter.isEmpty() )
312  {
313  featureRequest.combineFilterExpression( mTemporalFilter );
314  }
315 
316  // enable the simplification of the geometries (Using the current map2pixel context) before send it to renderer engine.
317  if ( mSimplifyGeometry )
318  {
319  double map2pixelTol = mSimplifyMethod.threshold();
320  bool validTransform = true;
321 
322  const QgsMapToPixel &mtp = context.mapToPixel();
323  map2pixelTol *= mtp.mapUnitsPerPixel();
325 
326  // resize the tolerance using the change of size of an 1-BBOX from the source CoordinateSystem to the target CoordinateSystem
327  if ( ct.isValid() && !ct.isShortCircuited() )
328  {
329  try
330  {
331  QgsPointXY center = context.extent().center();
332  double rectSize = ct.sourceCrs().isGeographic() ? 0.0008983 /* ~100/(40075014/360=111319.4833) */ : 100;
333 
334  QgsRectangle sourceRect = QgsRectangle( center.x(), center.y(), center.x() + rectSize, center.y() + rectSize );
335  QgsRectangle targetRect = ct.transform( sourceRect );
336 
337  QgsDebugMsgLevel( QStringLiteral( "Simplify - SourceTransformRect=%1" ).arg( sourceRect.toString( 16 ) ), 4 );
338  QgsDebugMsgLevel( QStringLiteral( "Simplify - TargetTransformRect=%1" ).arg( targetRect.toString( 16 ) ), 4 );
339 
340  if ( !sourceRect.isEmpty() && sourceRect.isFinite() && !targetRect.isEmpty() && targetRect.isFinite() )
341  {
342  QgsPointXY minimumSrcPoint( sourceRect.xMinimum(), sourceRect.yMinimum() );
343  QgsPointXY maximumSrcPoint( sourceRect.xMaximum(), sourceRect.yMaximum() );
344  QgsPointXY minimumDstPoint( targetRect.xMinimum(), targetRect.yMinimum() );
345  QgsPointXY maximumDstPoint( targetRect.xMaximum(), targetRect.yMaximum() );
346 
347  double sourceHypothenuse = std::sqrt( minimumSrcPoint.sqrDist( maximumSrcPoint ) );
348  double targetHypothenuse = std::sqrt( minimumDstPoint.sqrDist( maximumDstPoint ) );
349 
350  QgsDebugMsgLevel( QStringLiteral( "Simplify - SourceHypothenuse=%1" ).arg( sourceHypothenuse ), 4 );
351  QgsDebugMsgLevel( QStringLiteral( "Simplify - TargetHypothenuse=%1" ).arg( targetHypothenuse ), 4 );
352 
353  if ( !qgsDoubleNear( targetHypothenuse, 0.0 ) )
354  map2pixelTol *= ( sourceHypothenuse / targetHypothenuse );
355  }
356  }
357  catch ( QgsCsException &cse )
358  {
359  QgsMessageLog::logMessage( QObject::tr( "Simplify transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
360  validTransform = false;
361  }
362  }
363 
364  if ( validTransform )
365  {
366  QgsSimplifyMethod simplifyMethod;
368  simplifyMethod.setTolerance( map2pixelTol );
369  simplifyMethod.setThreshold( mSimplifyMethod.threshold() );
371  featureRequest.setSimplifyMethod( simplifyMethod );
372 
374  vectorMethod.setTolerance( map2pixelTol );
375  context.setVectorSimplifyMethod( vectorMethod );
376  }
377  else
378  {
379  QgsVectorSimplifyMethod vectorMethod;
381  context.setVectorSimplifyMethod( vectorMethod );
382  }
383  }
384  else
385  {
386  QgsVectorSimplifyMethod vectorMethod;
388  context.setVectorSimplifyMethod( vectorMethod );
389  }
390 
391  QgsFeatureIterator fit = mSource->getFeatures( featureRequest );
392  // Attach an interruption checker so that iterators that have potentially
393  // slow fetchFeature() implementations, such as in the WFS provider, can
394  // check it, instead of relying on just the mContext.renderingStopped() check
395  // in drawRenderer()
397 
398  if ( ( renderer->capabilities() & QgsFeatureRenderer::SymbolLevels ) && renderer->usingSymbolLevels() )
399  drawRendererLevels( renderer, fit );
400  else
401  drawRenderer( renderer, fit );
402 
403  if ( !fit.isValid() )
404  {
405  mErrors.append( QStringLiteral( "Data source invalid" ) );
406  }
407 
408  if ( usingEffect )
409  {
410  renderer->paintEffect()->end( context );
411  }
412 
413  mInterruptionChecker.reset();
414  return true;
415 }
416 
417 
418 void QgsVectorLayerRenderer::drawRenderer( QgsFeatureRenderer *renderer, QgsFeatureIterator &fit )
419 {
420  const bool isMainRenderer = renderer == mRenderer;
421 
423  QgsRenderContext &context = *renderContext();
424  context.expressionContext().appendScope( symbolScope );
425 
426  std::unique_ptr< QgsGeometryEngine > clipEngine;
427  if ( mApplyClipFilter )
428  {
430  clipEngine->prepareGeometry();
431  }
432 
433  QgsFeature fet;
434  while ( fit.nextFeature( fet ) )
435  {
436  try
437  {
438  if ( context.renderingStopped() )
439  {
440  QgsDebugMsgLevel( QStringLiteral( "Drawing of vector layer %1 canceled." ).arg( layerId() ), 2 );
441  break;
442  }
443 
444  if ( !fet.hasGeometry() || fet.geometry().isEmpty() )
445  continue; // skip features without geometry
446 
447  if ( clipEngine && !clipEngine->intersects( fet.geometry().constGet() ) )
448  continue; // skip features outside of clipping region
449 
450  if ( mApplyClipGeometries )
452 
453  context.expressionContext().setFeature( fet );
454 
455  bool sel = isMainRenderer && context.showSelection() && mSelectedFeatureIds.contains( fet.id() );
456  bool drawMarker = isMainRenderer && ( mDrawVertexMarkers && context.drawEditingInformation() && ( !mVertexMarkerOnlyForSelection || sel ) );
457 
458  // render feature
459  bool rendered = renderer->renderFeature( fet, context, -1, sel, drawMarker );
460 
461  // labeling - register feature
462  if ( rendered )
463  {
464  // as soon as first feature is rendered, we can start showing layer updates.
465  // but if we are blocking render updates (so that a previously cached image is being shown), we wait
466  // at most e.g. 3 seconds before we start forcing progressive updates.
468  {
469  mReadyToCompose = true;
470  }
471 
472  // new labeling engine
473  if ( isMainRenderer && context.labelingEngine() && ( mLabelProvider || mDiagramProvider ) )
474  {
475  QgsGeometry obstacleGeometry;
476  QgsSymbolList symbols = renderer->originalSymbolsForFeature( fet, context );
477  QgsSymbol *symbol = nullptr;
478  if ( !symbols.isEmpty() && fet.geometry().type() == QgsWkbTypes::PointGeometry )
479  {
480  obstacleGeometry = QgsVectorLayerLabelProvider::getPointObstacleGeometry( fet, context, symbols );
481  }
482 
483  if ( !symbols.isEmpty() )
484  {
485  symbol = symbols.at( 0 );
486  QgsExpressionContextUtils::updateSymbolScope( symbol, symbolScope );
487  }
488 
491 
492  if ( mLabelProvider )
493  {
494  mLabelProvider->registerFeature( fet, context, obstacleGeometry, symbol );
495  }
496  if ( mDiagramProvider )
497  {
498  mDiagramProvider->registerFeature( fet, context, obstacleGeometry );
499  }
500 
502  context.setFeatureClipGeometry( QgsGeometry() );
503  }
504  }
505  }
506  catch ( const QgsCsException &cse )
507  {
508  Q_UNUSED( cse )
509  QgsDebugMsg( QStringLiteral( "Failed to transform a point while drawing a feature with ID '%1'. Ignoring this feature. %2" )
510  .arg( fet.id() ).arg( cse.what() ) );
511  }
512  }
513 
514  delete context.expressionContext().popScope();
515 
516  stopRenderer( renderer, nullptr );
517 }
518 
519 void QgsVectorLayerRenderer::drawRendererLevels( QgsFeatureRenderer *renderer, QgsFeatureIterator &fit )
520 {
521  const bool isMainRenderer = renderer == mRenderer;
522 
523  QHash< QgsSymbol *, QList<QgsFeature> > features; // key = symbol, value = array of features
524  QgsRenderContext &context = *renderContext();
525 
526  QgsSingleSymbolRenderer *selRenderer = nullptr;
527  if ( !mSelectedFeatureIds.isEmpty() )
528  {
530  selRenderer->symbol()->setColor( context.selectionColor() );
532  selRenderer->startRender( context, mFields );
533  }
534 
536  std::unique_ptr< QgsExpressionContextScopePopper > scopePopper = qgis::make_unique< QgsExpressionContextScopePopper >( context.expressionContext(), symbolScope );
537 
538 
539  std::unique_ptr< QgsGeometryEngine > clipEngine;
540  if ( mApplyClipFilter )
541  {
543  clipEngine->prepareGeometry();
544  }
545 
548 
549  // 1. fetch features
550  QgsFeature fet;
551  while ( fit.nextFeature( fet ) )
552  {
553  if ( context.renderingStopped() )
554  {
555  qDebug( "rendering stop!" );
556  stopRenderer( renderer, selRenderer );
557  return;
558  }
559 
560  if ( !fet.hasGeometry() )
561  continue; // skip features without geometry
562 
563  if ( clipEngine && !clipEngine->intersects( fet.geometry().constGet() ) )
564  continue; // skip features outside of clipping region
565 
566  context.expressionContext().setFeature( fet );
567  QgsSymbol *sym = renderer->symbolForFeature( fet, context );
568  if ( !sym )
569  {
570  continue;
571  }
572 
573  if ( !features.contains( sym ) )
574  {
575  features.insert( sym, QList<QgsFeature>() );
576  }
577  features[sym].append( fet );
578 
579  // new labeling engine
580  if ( isMainRenderer && context.labelingEngine() && ( mLabelProvider || mDiagramProvider ) )
581  {
582  QgsGeometry obstacleGeometry;
583  QgsSymbolList symbols = renderer->originalSymbolsForFeature( fet, context );
584  QgsSymbol *symbol = nullptr;
585  if ( !symbols.isEmpty() && fet.geometry().type() == QgsWkbTypes::PointGeometry )
586  {
587  obstacleGeometry = QgsVectorLayerLabelProvider::getPointObstacleGeometry( fet, context, symbols );
588  }
589 
590  if ( !symbols.isEmpty() )
591  {
592  symbol = symbols.at( 0 );
593  QgsExpressionContextUtils::updateSymbolScope( symbol, symbolScope );
594  }
595 
596  if ( mLabelProvider )
597  {
598  mLabelProvider->registerFeature( fet, context, obstacleGeometry, symbol );
599  }
600  if ( mDiagramProvider )
601  {
602  mDiagramProvider->registerFeature( fet, context, obstacleGeometry );
603  }
604  }
605  }
606 
608  context.setFeatureClipGeometry( QgsGeometry() );
609 
610  scopePopper.reset();
611 
612  if ( features.empty() )
613  {
614  // nothing to draw
615  stopRenderer( renderer, selRenderer );
616  return;
617  }
618 
619  // find out the order
620  QgsSymbolLevelOrder levels;
621  QgsSymbolList symbols = renderer->symbols( context );
622  for ( int i = 0; i < symbols.count(); i++ )
623  {
624  QgsSymbol *sym = symbols[i];
625  for ( int j = 0; j < sym->symbolLayerCount(); j++ )
626  {
627  int level = sym->symbolLayer( j )->renderingPass();
628  if ( level < 0 || level >= 1000 ) // ignore invalid levels
629  continue;
630  QgsSymbolLevelItem item( sym, j );
631  while ( level >= levels.count() ) // append new empty levels
632  levels.append( QgsSymbolLevel() );
633  levels[level].append( item );
634  }
635  }
636 
637  if ( mApplyClipGeometries )
639 
640  // 2. draw features in correct order
641  for ( int l = 0; l < levels.count(); l++ )
642  {
643  QgsSymbolLevel &level = levels[l];
644  for ( int i = 0; i < level.count(); i++ )
645  {
646  QgsSymbolLevelItem &item = level[i];
647  if ( !features.contains( item.symbol() ) )
648  {
649  QgsDebugMsg( QStringLiteral( "level item's symbol not found!" ) );
650  continue;
651  }
652  int layer = item.layer();
653  QList<QgsFeature> &lst = features[item.symbol()];
654  QList<QgsFeature>::iterator fit;
655  for ( fit = lst.begin(); fit != lst.end(); ++fit )
656  {
657  if ( context.renderingStopped() )
658  {
659  stopRenderer( renderer, selRenderer );
660  return;
661  }
662 
663  bool sel = isMainRenderer && context.showSelection() && mSelectedFeatureIds.contains( fit->id() );
664  // maybe vertex markers should be drawn only during the last pass...
665  bool drawMarker = isMainRenderer && ( mDrawVertexMarkers && context.drawEditingInformation() && ( !mVertexMarkerOnlyForSelection || sel ) );
666 
667  context.expressionContext().setFeature( *fit );
668 
669  try
670  {
671  renderer->renderFeature( *fit, context, layer, sel, drawMarker );
672 
673  // as soon as first feature is rendered, we can start showing layer updates.
674  // but if we are blocking render updates (so that a previously cached image is being shown), we wait
675  // at most e.g. 3 seconds before we start forcing progressive updates.
677  {
678  mReadyToCompose = true;
679  }
680  }
681  catch ( const QgsCsException &cse )
682  {
683  Q_UNUSED( cse )
684  QgsDebugMsg( QStringLiteral( "Failed to transform a point while drawing a feature with ID '%1'. Ignoring this feature. %2" )
685  .arg( fet.id() ).arg( cse.what() ) );
686  }
687  }
688  }
689  }
690 
691  stopRenderer( renderer, selRenderer );
692 }
693 
694 void QgsVectorLayerRenderer::stopRenderer( QgsFeatureRenderer *renderer, QgsSingleSymbolRenderer *selRenderer )
695 {
696  QgsRenderContext &context = *renderContext();
697  renderer->stopRender( context );
698  if ( selRenderer )
699  {
700  selRenderer->stopRender( context );
701  delete selRenderer;
702  }
703 }
704 
705 void QgsVectorLayerRenderer::prepareLabeling( QgsVectorLayer *layer, QSet<QString> &attributeNames )
706 {
707  QgsRenderContext &context = *renderContext();
708  // TODO: add attributes for geometry generator
709  if ( QgsLabelingEngine *engine2 = context.labelingEngine() )
710  {
711  if ( layer->labelsEnabled() )
712  {
713  mLabelProvider = layer->labeling()->provider( layer );
714  if ( mLabelProvider )
715  {
716  engine2->addProvider( mLabelProvider );
717  if ( !mLabelProvider->prepare( context, attributeNames ) )
718  {
719  engine2->removeProvider( mLabelProvider );
720  mLabelProvider = nullptr; // deleted by engine
721  }
722  }
723  }
724  }
725 
726 #if 0 // TODO: limit of labels, font not found
727  QgsPalLayerSettings &palyr = mContext.labelingEngine()->layer( mLayerID );
728 
729  // see if feature count limit is set for labeling
730  if ( palyr.limitNumLabels && palyr.maxNumLabels > 0 )
731  {
732  QgsFeatureIterator fit = getFeatures( QgsFeatureRequest()
733  .setFilterRect( mContext.extent() )
734  .setNoAttributes() );
735 
736  // total number of features that may be labeled
737  QgsFeature f;
738  int nFeatsToLabel = 0;
739  while ( fit.nextFeature( f ) )
740  {
741  nFeatsToLabel++;
742  }
743  palyr.mFeaturesToLabel = nFeatsToLabel;
744  }
745 
746  // notify user about any font substitution
747  if ( !palyr.mTextFontFound && !mLabelFontNotFoundNotified )
748  {
749  emit labelingFontNotFound( this, palyr.mTextFontFamily );
750  mLabelFontNotFoundNotified = true;
751  }
752 #endif
753 }
754 
755 void QgsVectorLayerRenderer::prepareDiagrams( QgsVectorLayer *layer, QSet<QString> &attributeNames )
756 {
757  QgsRenderContext &context = *renderContext();
758  if ( QgsLabelingEngine *engine2 = context.labelingEngine() )
759  {
760  if ( layer->diagramsEnabled() )
761  {
763  // need to be added before calling prepare() - uses map settings from engine
764  engine2->addProvider( mDiagramProvider );
765  if ( !mDiagramProvider->prepare( context, attributeNames ) )
766  {
767  engine2->removeProvider( mDiagramProvider );
768  mDiagramProvider = nullptr; // deleted by engine
769  }
770  }
771  }
772 }
773 
774 /* ----------------------------------------- */
775 /* QgsVectorLayerRendererInterruptionChecker */
776 /* ----------------------------------------- */
777 
779 ( const QgsRenderContext &context )
780  : mContext( context )
781  , mTimer( new QTimer( this ) )
782 {
783  connect( mTimer, &QTimer::timeout, this, [ = ]
784  {
785  if ( mContext.renderingStopped() )
786  {
787  mTimer->stop();
788  cancel();
789  }
790  } );
791  mTimer->start( 50 );
792 
793 }
virtual QgsVectorLayerLabelProvider * provider(QgsVectorLayer *layer) const
Factory for label provider implementation.
Class for doing transforms between two map coordinate systems.
QgsCoordinateReferenceSystem sourceCrs() const
Returns the source coordinate reference system, which the transform will transform coordinates from.
QgsPointXY transform(const QgsPointXY &point, TransformDirection direction=ForwardTransform) const SIP_THROW(QgsCsException)
Transform the point from the source CRS to the destination CRS.
bool isShortCircuited() const
Returns true if the transform short circuits because the source and destination are equivalent.
bool isValid() const
Returns true if the coordinate transform is valid, ie both the source and destination CRS have been s...
Custom exception class for Coordinate Reference System related exceptions.
Definition: qgsexception.h:66
QString what() const
Definition: qgsexception.h:48
Single scope for storing variables and functions for use within a QgsExpressionContext.
static QgsExpressionContextScope * updateSymbolScope(const QgsSymbol *symbol, QgsExpressionContextScope *symbolScope=nullptr)
Updates a symbol scope related to a QgsSymbol to an expression context.
static QgsExpressionContextScope * layerScope(const QgsMapLayer *layer)
Creates a new scope which contains variables and functions relating to a QgsMapLayer.
QgsExpressionContextScope * popScope()
Removes the last scope from the expression context and return it.
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.
Abstract interface for use by classes that filter the features or attributes of a layer.
virtual void filterFeatures(const QgsVectorLayer *layer, QgsFeatureRequest &featureRequest) const =0
Add additional filters to the feature request to further restrict the features returned by the reques...
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
void setInterruptionChecker(QgsFeedback *interruptionChecker)
Attach an object that can be queried regularly by the iterator to check if it must stopped.
bool isValid() const
Will return if this iterator is valid.
An interface for objects which generate feature renderers for vector layers.
virtual QgsFeatureRenderer * clone() const =0
Create a deep copy of this renderer.
virtual void modifyRequestExtent(QgsRectangle &extent, QgsRenderContext &context)
Allows for a renderer to modify the extent of a feature request prior to rendering.
virtual QString filter(const QgsFields &fields=QgsFields())
If a renderer does not require all the features this method may be overridden and return an expressio...
Definition: qgsrenderer.h:205
QgsPaintEffect * paintEffect() const
Returns the current paint effect for the renderer.
virtual QgsSymbolList symbols(QgsRenderContext &context) const
Returns list of symbols used by the renderer.
virtual void stopRender(QgsRenderContext &context)
Must be called when a render cycle has finished, to allow the renderer to clean up.
virtual QgsSymbol * symbolForFeature(const QgsFeature &feature, QgsRenderContext &context) const =0
To be overridden.
QString type() const
Definition: qgsrenderer.h:141
void setVertexMarkerAppearance(int type, double size)
Sets type and size of editing vertex markers for subsequent rendering.
bool usingSymbolLevels() const
Definition: qgsrenderer.h:283
virtual QString dump() const
Returns debug information about this renderer.
virtual QgsFeatureRenderer::Capabilities capabilities()
Returns details about internals of this renderer.
Definition: qgsrenderer.h:274
@ SymbolLevels
Rendering with symbol levels (i.e. implements symbols(), symbolForFeature())
Definition: qgsrenderer.h:254
bool orderByEnabled() const
Returns whether custom ordering will be applied before features are processed by this renderer.
virtual void startRender(QgsRenderContext &context, const QgsFields &fields)
Must be called when a new render cycle is started.
Definition: qgsrenderer.cpp:94
virtual bool renderFeature(const QgsFeature &feature, QgsRenderContext &context, int layer=-1, bool selected=false, bool drawVertexMarker=false) SIP_THROW(QgsCsException)
Render a feature using this renderer in the given context.
QgsFeatureRequest::OrderBy orderBy() const
Gets the order in which features shall be processed by this renderer.
virtual QgsSymbolList originalSymbolsForFeature(const QgsFeature &feature, QgsRenderContext &context) const
Equivalent of originalSymbolsForFeature() call extended to support renderers that may use more symbol...
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setSimplifyMethod(const QgsSimplifyMethod &simplifyMethod)
Set a simplification method for geometries that will be fetched.
QgsFeatureRequest & combineFilterExpression(const QString &expression)
Modifies the existing filter expression to add an additional expression filter.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QgsFeatureRequest & setExpressionContext(const QgsExpressionContext &context)
Sets the expression context used to evaluate filter expressions.
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
QgsFeatureRequest & setOrderBy(const OrderBy &orderBy)
Set a list of order by clauses.
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:56
QgsGeometry geometry
Definition: qgsfeature.h:67
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Definition: qgsfeature.cpp:204
Q_GADGET QgsFeatureId id
Definition: qgsfeature.h:64
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition: qgsfeedback.h:45
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:124
const QgsAbstractGeometry * constGet() const SIP_HOLDGIL
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsWkbTypes::GeometryType type
Definition: qgsgeometry.h:127
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry)
Creates and returns a new geometry engine.
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
The QgsLabelingEngine class provides map labeling functionality.
static QList< QgsMapClippingRegion > collectClippingRegionsForLayer(const QgsRenderContext &context, const QgsMapLayer *layer)
Collects the list of map clipping regions from a context which apply to a map layer.
static QPainterPath calculatePainterClipRegion(const QList< QgsMapClippingRegion > &regions, const QgsRenderContext &context, QgsMapLayerType layerType, bool &shouldClip)
Returns a QPainterPath representing the intersection of clipping regions from context which should be...
static QgsGeometry calculateLabelIntersectionGeometry(const QList< QgsMapClippingRegion > &regions, const QgsRenderContext &context, bool &shouldClip)
Returns the geometry representing the intersection of clipping regions from context which should be u...
static QgsGeometry calculateFeatureIntersectionGeometry(const QList< QgsMapClippingRegion > &regions, const QgsRenderContext &context, bool &shouldClip)
Returns the geometry representing the intersection of clipping regions from context which should be u...
static QgsGeometry calculateFeatureRequestGeometry(const QList< QgsMapClippingRegion > &regions, const QgsRenderContext &context, bool &shouldFilter)
Returns the geometry representing the intersection of clipping regions from context.
Base class for utility classes that encapsulate information necessary for rendering of map layers.
bool mReadyToCompose
The flag must be set to false in renderer's constructor if wants to use the smarter map redraws funct...
static constexpr int MAX_TIME_TO_USE_CACHED_PREVIEW_IMAGE
Maximum time (in ms) to allow display of a previously cached preview image while rendering layers,...
QString layerId() const
Gets access to the ID of the layer rendered by this class.
QgsRenderContext * renderContext()
Returns the render context associated with the renderer.
QPainter::CompositionMode blendMode() const
Returns the current blending mode for a layer.
double opacity
Definition: qgsmaplayer.h:94
Perform transforms between map coordinates and device coordinates.
Definition: qgsmaptopixel.h:39
double mapUnitsPerPixel() const
Returns current map units per pixel.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
virtual void begin(QgsRenderContext &context)
Begins intercepting paint operations to a render context.
virtual void end(QgsRenderContext &context)
Ends interception of paint operations to a render context, and draws the result to the render context...
bool enabled() const
Returns whether the effect is enabled.
Contains settings for how a map layer will be labeled.
A class to represent a 2D point.
Definition: qgspointxy.h:44
double y
Definition: qgspointxy.h:48
Q_GADGET double x
Definition: qgspointxy.h:47
A rectangle specified with double values.
Definition: qgsrectangle.h:42
QString toString(int precision=16) const
Returns a string representation of form xmin,ymin : xmax,ymax Coordinates will be truncated to the sp...
double yMaximum() const SIP_HOLDGIL
Returns the y maximum value (top side of rectangle).
Definition: qgsrectangle.h:172
double xMaximum() const SIP_HOLDGIL
Returns the x maximum value (right side of rectangle).
Definition: qgsrectangle.h:162
double xMinimum() const SIP_HOLDGIL
Returns the x minimum value (left side of rectangle).
Definition: qgsrectangle.h:167
double yMinimum() const SIP_HOLDGIL
Returns the y minimum value (bottom side of rectangle).
Definition: qgsrectangle.h:177
bool isEmpty() const
Returns true if the rectangle is empty.
Definition: qgsrectangle.h:437
QgsRectangle intersect(const QgsRectangle &rect) const
Returns the intersection with the given rectangle.
Definition: qgsrectangle.h:312
bool isFinite() const
Returns true if the rectangle has finite boundaries.
Definition: qgsrectangle.h:527
QgsPointXY center() const SIP_HOLDGIL
Returns the center point of the rectangle.
Definition: qgsrectangle.h:230
Contains information about the context of a rendering operation.
bool useAdvancedEffects() const
Returns true if advanced effects such as blend modes such be used.
bool hasRenderedFeatureHandlers() const
Returns true if the context has any rendered feature handlers.
QPainter * painter()
Returns the destination QPainter for the render operation.
QgsExpressionContext & expressionContext()
Gets the expression context.
const QgsMapToPixel & mapToPixel() const
Returns the context's map to pixel transform, which transforms between map coordinates and device coo...
void setVectorSimplifyMethod(const QgsVectorSimplifyMethod &simplifyMethod)
Sets the simplification setting to use when rendering vector layers.
void setFeatureClipGeometry(const QgsGeometry &geometry)
Sets a geometry to use to clip features at render time.
const QgsFeatureFilterProvider * featureFilterProvider() const
Gets the filter feature provider used for additional filtering of rendered features.
QList< QgsRenderedFeatureHandlerInterface * > renderedFeatureHandlers() const
Returns the list of rendered feature handlers to use while rendering map layers.
bool showSelection() const
Returns true if vector selections should be shown in the rendered map.
QColor selectionColor() const
Returns the color to use when rendering selected features.
QgsLabelingEngine * labelingEngine() const
Gets access to new labeling engine (may be nullptr)
@ UseAdvancedEffects
Enable layer opacity and blending effects.
bool drawEditingInformation() const
Returns true if edit markers should be drawn during the render operation.
bool renderingStopped() const
Returns true if the rendering operation has been stopped and any ongoing rendering should be canceled...
bool testFlag(Flag flag) const
Check whether a particular flag is enabled.
QgsCoordinateTransform coordinateTransform() const
Returns the current coordinate transform for the context.
const QgsRectangle & extent() const
When rendering a map layer, calling this method returns the "clipping" extent for the layer (in the l...
const QgsVectorSimplifyMethod & vectorSimplifyMethod() const
Returns the simplification settings to use when rendering vector layers.
An interface for classes which provider custom handlers for features rendered as part of a map render...
Scoped object for saving and restoring a QPainter object's state.
This class is a composition of two QSettings instances:
Definition: qgssettings.h:62
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
This class contains information about how to simplify geometries fetched from a QgsFeatureIterator.
void setTolerance(double tolerance)
Sets the tolerance of simplification in map units. Represents the maximum distance in map units betwe...
void setThreshold(float threshold)
Sets the simplification threshold in pixels. Represents the maximum distance in pixels between two co...
void setForceLocalOptimization(bool localOptimization)
Sets whether the simplification executes after fetch the geometries from provider,...
void setMethodType(MethodType methodType)
Sets the simplification type.
@ OptimizeForRendering
Simplify using the map2pixel data to optimize the rendering of geometries.
QgsSymbol * symbol() const
Returns the symbol which will be rendered for every feature.
void stopRender(QgsRenderContext &context) override
Must be called when a render cycle has finished, to allow the renderer to clean up.
void startRender(QgsRenderContext &context, const QgsFields &fields) override
Must be called when a new render cycle is started.
int renderingPass() const
Specifies the rendering pass in which this symbol layer should be rendered.
int layer() const
The layer of this symbol level.
QgsSymbol * symbol() const
The symbol of this symbol level.
Abstract base class for all rendered symbols.
Definition: qgssymbol.h:65
QgsSymbolLayer * symbolLayer(int layer)
Returns the symbol layer at the specified index.
Definition: qgssymbol.cpp:411
static QgsSymbol * defaultSymbol(QgsWkbTypes::GeometryType geomType)
Returns a new default symbol for the specified geometry type.
Definition: qgssymbol.cpp:346
void setColor(const QColor &color)
Sets the color for the symbol.
Definition: qgssymbol.cpp:532
int symbolLayerCount() const
Returns the total number of symbol layers contained in the symbol.
Definition: qgssymbol.h:199
const QgsDateTimeRange & temporalRange() const
Returns the datetime range for the object.
bool isTemporal() const
Returns true if the object's temporal range is enabled, and the object will be filtered when renderin...
The QgsVectorLayerDiagramProvider class implements support for diagrams within the labeling engine.
virtual bool prepare(const QgsRenderContext &context, QSet< QString > &attributeNames)
Prepare for registration of features.
virtual void registerFeature(QgsFeature &feature, QgsRenderContext &context, const QgsGeometry &obstacleGeometry=QgsGeometry())
Register a feature for labeling as one or more QgsLabelFeature objects stored into mFeatures.
void setClipFeatureGeometry(const QgsGeometry &geometry)
Sets a geometry to use to clip features to when registering them as diagrams.
virtual bool prepare(QgsRenderContext &context, QSet< QString > &attributeNames)
Prepare for registration of features.
static QgsGeometry getPointObstacleGeometry(QgsFeature &fet, QgsRenderContext &context, const QgsSymbolList &symbols)
Returns the geometry for a point feature which should be used as an obstacle for labels.
virtual void registerFeature(const QgsFeature &feature, QgsRenderContext &context, const QgsGeometry &obstacleGeometry=QgsGeometry(), const QgsSymbol *symbol=nullptr)
Register a feature for labeling as one or more QgsLabelFeature objects stored into mLabels.
QgsVectorLayerRendererInterruptionChecker(const QgsRenderContext &context)
Constructor.
std::vector< std::unique_ptr< QgsFeatureRenderer > > mRenderers
QgsVectorLayerLabelProvider * mLabelProvider
used with new labeling engine (QgsLabelingEngine): provider for labels.
bool forceRasterRender() const override
Returns true if the renderer must be rendered to a raster paint device (e.g.
QgsVectorSimplifyMethod mSimplifyMethod
QgsVectorLayerRenderer(QgsVectorLayer *layer, QgsRenderContext &context)
QPainter::CompositionMode mFeatureBlendMode
~QgsVectorLayerRenderer() override
QgsVectorLayer * mLayer
The rendered layer.
QgsWkbTypes::GeometryType mGeometryType
void setLayerRenderingTimeHint(int time) override
Sets approximate render time (in ms) for the layer to render.
bool render() override
Do the rendering (based on data stored in the class).
QgsFeatureRenderer * mRenderer
QList< QgsMapClippingRegion > mClippingRegions
QgsFeedback * feedback() const override
Access to feedback object of the layer renderer (may be nullptr)
std::unique_ptr< QgsVectorLayerRendererInterruptionChecker > mInterruptionChecker
std::unique_ptr< QgsVectorLayerFeatureSource > mSource
QgsVectorLayerDiagramProvider * mDiagramProvider
used with new labeling engine (QgsLabelingEngine): provider for diagrams.
Encapsulates the context in which a QgsVectorLayer's temporal capabilities will be applied.
void setLayer(QgsVectorLayer *layer)
Sets the associated layer.
Represents a vector layer which manages a vector based data sets.
bool labelsEnabled() const
Returns whether the layer contains labels which are enabled and should be drawn.
Q_INVOKABLE QgsWkbTypes::GeometryType geometryType() const
Returns point, line or polygon.
QgsMapLayerTemporalProperties * temporalProperties() override
Returns temporal properties associated with the vector layer.
QPainter::CompositionMode featureBlendMode() const
Returns the current blending mode for features.
bool diagramsEnabled() const
Returns whether the layer contains diagrams which are enabled and should be drawn.
Q_INVOKABLE const QgsFeatureIds & selectedFeatureIds() const
Returns a list of the selected features IDs in this layer.
bool simplifyDrawingCanbeApplied(const QgsRenderContext &renderContext, QgsVectorSimplifyMethod::SimplifyHint simplifyHint) const
Returns whether the VectorLayer can apply the specified simplification hint.
const QgsAbstractVectorLayerLabeling * labeling() const
Access to const labeling configuration.
Q_INVOKABLE QgsVectorLayerEditBuffer * editBuffer()
Buffer with uncommitted editing operations. Only valid after editing has been turned on.
QList< const QgsFeatureRendererGenerator * > featureRendererGenerators() const
Returns a list of the feature renderer generators owned by the layer.
const QgsVectorSimplifyMethod & simplifyMethod() const
Returns the simplification settings for fast rendering of features.
QgsFeatureRenderer * renderer()
Returns the feature renderer used for rendering the features in the layer in 2D map views.
This class contains information how to simplify geometries fetched from a vector layer.
bool forceLocalOptimization() const
Gets where the simplification executes, after fetch the geometries from provider, or when supported,...
void setSimplifyHints(SimplifyHints simplifyHints)
Sets the simplification hints of the vector layer managed.
SimplifyHints simplifyHints() const
Gets the simplification hints of the vector layer managed.
void setTolerance(double tolerance)
Sets the tolerance of simplification in map units. Represents the maximum distance in map units betwe...
float threshold() const
Gets the simplification threshold of the vector layer managed.
@ GeometrySimplification
The geometries can be simplified using the current map2pixel context state.
@ FullSimplification
All simplification hints can be applied ( Geometry + AA-disabling )
@ NoSimplification
No simplification can be applied.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition: qgis.h:316
#define QgsDebugMsgLevel(str, level)
Definition: qgslogger.h:39
#define QgsDebugMsg(str)
Definition: qgslogger.h:38
QList< QgsSymbolLevel > QgsSymbolLevelOrder
Definition: qgsrenderer.h:89
QList< QgsSymbolLevelItem > QgsSymbolLevel
Definition: qgsrenderer.h:85
QList< QgsSymbol * > QgsSymbolList
Definition: qgsrenderer.h:45