QGIS API Documentation  3.20.0-Odense (decaadbb31)
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 "qgssettingsregistrycore.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 = std::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 : std::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  mVertexMarkerOnlyForSelection = QgsSettingsRegistryCore::settingsDigitizingMarkerOnlyForSelected.value();
119 
120  QString markerTypeString = QgsSettingsRegistryCore::settingsDigitizingMarkerStyle.value();
121  if ( markerTypeString == QLatin1String( "Cross" ) )
122  {
124  }
125  else if ( markerTypeString == QLatin1String( "SemiTransparentCircle" ) )
126  {
128  }
129  else
130  {
132  }
133 
134  mVertexMarkerSize = QgsSettingsRegistryCore::settingsDigitizingMarkerSizeMm.value();
135 
136  QgsDebugMsgLevel( "rendering v2:\n " + mRenderer->dump(), 2 );
137 
138  if ( mDrawVertexMarkers )
139  {
140  // set editing vertex markers style (main renderer only)
142  }
144 
145  for ( const std::unique_ptr< QgsFeatureRenderer > &renderer : mRenderers )
146  {
147  mAttrNames.unite( renderer->usedAttributes( context ) );
148  }
149  if ( context.hasRenderedFeatureHandlers() )
150  {
151  const QList< QgsRenderedFeatureHandlerInterface * > handlers = context.renderedFeatureHandlers();
152  for ( QgsRenderedFeatureHandlerInterface *handler : handlers )
153  mAttrNames.unite( handler->usedAttributes( layer, context ) );
154  }
155 
156  //register label and diagram layer to the labeling engine
157  prepareLabeling( layer, mAttrNames );
158  prepareDiagrams( layer, mAttrNames );
159 
161 
162  for ( const std::unique_ptr< QgsFeatureRenderer > &renderer : mRenderers )
163  {
164  if ( renderer->forceRasterRender() )
165  {
166  //raster rendering is forced for this layer
167  mForceRasterRender = true;
168  break;
169  }
170  }
171 
173  ( ( layer->blendMode() != QPainter::CompositionMode_SourceOver )
174  || ( layer->featureBlendMode() != QPainter::CompositionMode_SourceOver )
175  || ( !qgsDoubleNear( layer->opacity(), 1.0 ) ) ) )
176  {
177  //layer properties require rasterization
178  mForceRasterRender = true;
179  }
180 
181  mReadyToCompose = false;
182 }
183 
185 
187 {
188  mRenderTimeHint = time;
189 }
190 
192 {
193  return mInterruptionChecker.get();
194 }
195 
197 {
198  return mForceRasterRender;
199 }
200 
202 {
204  {
205  mReadyToCompose = true;
206  return true;
207  }
208 
209  if ( mRenderers.empty() )
210  {
211  mReadyToCompose = true;
212  mErrors.append( QObject::tr( "No renderer for drawing." ) );
213  return false;
214  }
215 
216  // if the previous layer render was relatively quick (e.g. less than 3 seconds), the we show any previously
217  // cached version of the layer during rendering instead of the usual progressive updates
219  {
220  mBlockRenderUpdates = true;
221  mElapsedTimer.start();
222  }
223 
224  bool res = true;
225  for ( const std::unique_ptr< QgsFeatureRenderer > &renderer : mRenderers )
226  {
227  res = renderInternal( renderer.get() ) && res;
228  }
229 
230  mReadyToCompose = true;
231  return res && !renderContext()->renderingStopped();
232 }
233 
234 bool QgsVectorLayerRenderer::renderInternal( QgsFeatureRenderer *renderer )
235 {
236  const bool isMainRenderer = renderer == mRenderer;
237 
238  if ( renderer->type() == QLatin1String( "nullSymbol" ) )
239  {
240  // a little shortcut for the null symbol renderer - most of the time it is not going to render anything
241  // so we can even skip the whole loop to fetch features
242  if ( !isMainRenderer ||
244  return true;
245  }
246 
247  QgsRenderContext &context = *renderContext();
248 
249  QgsScopedQPainterState painterState( context.painter() );
250 
251  // MUST be created in the thread doing the rendering
252  mInterruptionChecker = std::make_unique< QgsVectorLayerRendererInterruptionChecker >( context );
253  bool usingEffect = false;
254  if ( renderer->paintEffect() && renderer->paintEffect()->enabled() )
255  {
256  usingEffect = true;
257  renderer->paintEffect()->begin( context );
258  }
259 
260  // Per feature blending mode
261  if ( context.useAdvancedEffects() && mFeatureBlendMode != QPainter::CompositionMode_SourceOver )
262  {
263  // set the painter to the feature blend mode, so that features drawn
264  // on this layer will interact and blend with each other
265  context.painter()->setCompositionMode( mFeatureBlendMode );
266  }
267 
268  renderer->startRender( context, mFields );
269 
270  QString rendererFilter = renderer->filter( mFields );
271 
272  QgsRectangle requestExtent = context.extent();
273  if ( !mClippingRegions.empty() )
274  {
276  requestExtent = requestExtent.intersect( mClipFilterGeom.boundingBox() );
277 
279 
280  bool needsPainterClipPath = false;
281  const QPainterPath path = QgsMapClippingUtils::calculatePainterClipRegion( mClippingRegions, context, QgsMapLayerType::VectorLayer, needsPainterClipPath );
282  if ( needsPainterClipPath )
283  context.painter()->setClipPath( path, Qt::IntersectClip );
284 
286 
287  if ( mDiagramProvider )
289  }
290  renderer->modifyRequestExtent( requestExtent, context );
291 
292  QgsFeatureRequest featureRequest = QgsFeatureRequest()
293  .setFilterRect( requestExtent )
296  if ( renderer->orderByEnabled() )
297  {
298  featureRequest.setOrderBy( renderer->orderBy() );
299  }
300 
301  const QgsFeatureFilterProvider *featureFilterProvider = context.featureFilterProvider();
302  if ( featureFilterProvider )
303  {
304  featureFilterProvider->filterFeatures( mLayer, featureRequest );
305  }
306  if ( !rendererFilter.isEmpty() && rendererFilter != QLatin1String( "TRUE" ) )
307  {
308  featureRequest.combineFilterExpression( rendererFilter );
309  }
310  if ( !mTemporalFilter.isEmpty() )
311  {
312  featureRequest.combineFilterExpression( mTemporalFilter );
313  }
314 
315  if ( renderer->usesEmbeddedSymbols() )
316  {
317  featureRequest.setFlags( featureRequest.flags() | QgsFeatureRequest::EmbeddedSymbols );
318  }
319 
320  // enable the simplification of the geometries (Using the current map2pixel context) before send it to renderer engine.
321  if ( mSimplifyGeometry )
322  {
323  double map2pixelTol = mSimplifyMethod.threshold();
324  bool validTransform = true;
325 
326  const QgsMapToPixel &mtp = context.mapToPixel();
327  map2pixelTol *= mtp.mapUnitsPerPixel();
329 
330  // resize the tolerance using the change of size of an 1-BBOX from the source CoordinateSystem to the target CoordinateSystem
331  if ( ct.isValid() && !ct.isShortCircuited() )
332  {
333  try
334  {
335  QgsPointXY center = context.extent().center();
336  double rectSize = ct.sourceCrs().isGeographic() ? 0.0008983 /* ~100/(40075014/360=111319.4833) */ : 100;
337 
338  QgsRectangle sourceRect = QgsRectangle( center.x(), center.y(), center.x() + rectSize, center.y() + rectSize );
339  QgsRectangle targetRect = ct.transform( sourceRect );
340 
341  QgsDebugMsgLevel( QStringLiteral( "Simplify - SourceTransformRect=%1" ).arg( sourceRect.toString( 16 ) ), 4 );
342  QgsDebugMsgLevel( QStringLiteral( "Simplify - TargetTransformRect=%1" ).arg( targetRect.toString( 16 ) ), 4 );
343 
344  if ( !sourceRect.isEmpty() && sourceRect.isFinite() && !targetRect.isEmpty() && targetRect.isFinite() )
345  {
346  QgsPointXY minimumSrcPoint( sourceRect.xMinimum(), sourceRect.yMinimum() );
347  QgsPointXY maximumSrcPoint( sourceRect.xMaximum(), sourceRect.yMaximum() );
348  QgsPointXY minimumDstPoint( targetRect.xMinimum(), targetRect.yMinimum() );
349  QgsPointXY maximumDstPoint( targetRect.xMaximum(), targetRect.yMaximum() );
350 
351  double sourceHypothenuse = std::sqrt( minimumSrcPoint.sqrDist( maximumSrcPoint ) );
352  double targetHypothenuse = std::sqrt( minimumDstPoint.sqrDist( maximumDstPoint ) );
353 
354  QgsDebugMsgLevel( QStringLiteral( "Simplify - SourceHypothenuse=%1" ).arg( sourceHypothenuse ), 4 );
355  QgsDebugMsgLevel( QStringLiteral( "Simplify - TargetHypothenuse=%1" ).arg( targetHypothenuse ), 4 );
356 
357  if ( !qgsDoubleNear( targetHypothenuse, 0.0 ) )
358  map2pixelTol *= ( sourceHypothenuse / targetHypothenuse );
359  }
360  }
361  catch ( QgsCsException &cse )
362  {
363  QgsMessageLog::logMessage( QObject::tr( "Simplify transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
364  validTransform = false;
365  }
366  }
367 
368  if ( validTransform )
369  {
370  QgsSimplifyMethod simplifyMethod;
372  simplifyMethod.setTolerance( map2pixelTol );
373  simplifyMethod.setThreshold( mSimplifyMethod.threshold() );
375  featureRequest.setSimplifyMethod( simplifyMethod );
376 
378  vectorMethod.setTolerance( map2pixelTol );
379  context.setVectorSimplifyMethod( vectorMethod );
380  }
381  else
382  {
383  QgsVectorSimplifyMethod vectorMethod;
385  context.setVectorSimplifyMethod( vectorMethod );
386  }
387  }
388  else
389  {
390  QgsVectorSimplifyMethod vectorMethod;
392  context.setVectorSimplifyMethod( vectorMethod );
393  }
394 
395  QgsFeatureIterator fit = mSource->getFeatures( featureRequest );
396  // Attach an interruption checker so that iterators that have potentially
397  // slow fetchFeature() implementations, such as in the WFS provider, can
398  // check it, instead of relying on just the mContext.renderingStopped() check
399  // in drawRenderer()
401 
402  if ( ( renderer->capabilities() & QgsFeatureRenderer::SymbolLevels ) && renderer->usingSymbolLevels() )
403  drawRendererLevels( renderer, fit );
404  else
405  drawRenderer( renderer, fit );
406 
407  if ( !fit.isValid() )
408  {
409  mErrors.append( QStringLiteral( "Data source invalid" ) );
410  }
411 
412  if ( usingEffect )
413  {
414  renderer->paintEffect()->end( context );
415  }
416 
417  mInterruptionChecker.reset();
418  return true;
419 }
420 
421 
422 void QgsVectorLayerRenderer::drawRenderer( QgsFeatureRenderer *renderer, QgsFeatureIterator &fit )
423 {
424  const bool isMainRenderer = renderer == mRenderer;
425 
427  QgsRenderContext &context = *renderContext();
428  context.expressionContext().appendScope( symbolScope );
429 
430  std::unique_ptr< QgsGeometryEngine > clipEngine;
431  if ( mApplyClipFilter )
432  {
434  clipEngine->prepareGeometry();
435  }
436 
437  QgsFeature fet;
438  while ( fit.nextFeature( fet ) )
439  {
440  try
441  {
442  if ( context.renderingStopped() )
443  {
444  QgsDebugMsgLevel( QStringLiteral( "Drawing of vector layer %1 canceled." ).arg( layerId() ), 2 );
445  break;
446  }
447 
448  if ( !fet.hasGeometry() || fet.geometry().isEmpty() )
449  continue; // skip features without geometry
450 
451  if ( clipEngine && !clipEngine->intersects( fet.geometry().constGet() ) )
452  continue; // skip features outside of clipping region
453 
454  if ( mApplyClipGeometries )
456 
457  context.expressionContext().setFeature( fet );
458 
459  bool sel = isMainRenderer && context.showSelection() && mSelectedFeatureIds.contains( fet.id() );
460  bool drawMarker = isMainRenderer && ( mDrawVertexMarkers && context.drawEditingInformation() && ( !mVertexMarkerOnlyForSelection || sel ) );
461 
462  // render feature
463  bool rendered = renderer->renderFeature( fet, context, -1, sel, drawMarker );
464 
465  // labeling - register feature
466  if ( rendered )
467  {
468  // as soon as first feature is rendered, we can start showing layer updates.
469  // but if we are blocking render updates (so that a previously cached image is being shown), we wait
470  // at most e.g. 3 seconds before we start forcing progressive updates.
472  {
473  mReadyToCompose = true;
474  }
475 
476  // new labeling engine
477  if ( isMainRenderer && context.labelingEngine() && ( mLabelProvider || mDiagramProvider ) )
478  {
479  QgsGeometry obstacleGeometry;
480  QgsSymbolList symbols = renderer->originalSymbolsForFeature( fet, context );
481  QgsSymbol *symbol = nullptr;
482  if ( !symbols.isEmpty() && fet.geometry().type() == QgsWkbTypes::PointGeometry )
483  {
484  obstacleGeometry = QgsVectorLayerLabelProvider::getPointObstacleGeometry( fet, context, symbols );
485  }
486 
487  if ( !symbols.isEmpty() )
488  {
489  symbol = symbols.at( 0 );
490  QgsExpressionContextUtils::updateSymbolScope( symbol, symbolScope );
491  }
492 
495 
496  if ( mLabelProvider )
497  {
498  mLabelProvider->registerFeature( fet, context, obstacleGeometry, symbol );
499  }
500  if ( mDiagramProvider )
501  {
502  mDiagramProvider->registerFeature( fet, context, obstacleGeometry );
503  }
504 
506  context.setFeatureClipGeometry( QgsGeometry() );
507  }
508  }
509  }
510  catch ( const QgsCsException &cse )
511  {
512  Q_UNUSED( cse )
513  QgsDebugMsg( QStringLiteral( "Failed to transform a point while drawing a feature with ID '%1'. Ignoring this feature. %2" )
514  .arg( fet.id() ).arg( cse.what() ) );
515  }
516  }
517 
518  delete context.expressionContext().popScope();
519 
520  stopRenderer( renderer, nullptr );
521 }
522 
523 void QgsVectorLayerRenderer::drawRendererLevels( QgsFeatureRenderer *renderer, QgsFeatureIterator &fit )
524 {
525  const bool isMainRenderer = renderer == mRenderer;
526 
527  QHash< QgsSymbol *, QList<QgsFeature> > features; // key = symbol, value = array of features
528  QgsRenderContext &context = *renderContext();
529 
530  QgsSingleSymbolRenderer *selRenderer = nullptr;
531  if ( !mSelectedFeatureIds.isEmpty() )
532  {
534  selRenderer->symbol()->setColor( context.selectionColor() );
536  selRenderer->startRender( context, mFields );
537  }
538 
540  std::unique_ptr< QgsExpressionContextScopePopper > scopePopper = std::make_unique< QgsExpressionContextScopePopper >( context.expressionContext(), symbolScope );
541 
542 
543  std::unique_ptr< QgsGeometryEngine > clipEngine;
544  if ( mApplyClipFilter )
545  {
547  clipEngine->prepareGeometry();
548  }
549 
552 
553  // 1. fetch features
554  QgsFeature fet;
555  while ( fit.nextFeature( fet ) )
556  {
557  if ( context.renderingStopped() )
558  {
559  qDebug( "rendering stop!" );
560  stopRenderer( renderer, selRenderer );
561  return;
562  }
563 
564  if ( !fet.hasGeometry() )
565  continue; // skip features without geometry
566 
567  if ( clipEngine && !clipEngine->intersects( fet.geometry().constGet() ) )
568  continue; // skip features outside of clipping region
569 
570  context.expressionContext().setFeature( fet );
571  QgsSymbol *sym = renderer->symbolForFeature( fet, context );
572  if ( !sym )
573  {
574  continue;
575  }
576 
577  if ( !features.contains( sym ) )
578  {
579  features.insert( sym, QList<QgsFeature>() );
580  }
581  features[sym].append( fet );
582 
583  // new labeling engine
584  if ( isMainRenderer && context.labelingEngine() && ( mLabelProvider || mDiagramProvider ) )
585  {
586  QgsGeometry obstacleGeometry;
587  QgsSymbolList symbols = renderer->originalSymbolsForFeature( fet, context );
588  QgsSymbol *symbol = nullptr;
589  if ( !symbols.isEmpty() && fet.geometry().type() == QgsWkbTypes::PointGeometry )
590  {
591  obstacleGeometry = QgsVectorLayerLabelProvider::getPointObstacleGeometry( fet, context, symbols );
592  }
593 
594  if ( !symbols.isEmpty() )
595  {
596  symbol = symbols.at( 0 );
597  QgsExpressionContextUtils::updateSymbolScope( symbol, symbolScope );
598  }
599 
600  if ( mLabelProvider )
601  {
602  mLabelProvider->registerFeature( fet, context, obstacleGeometry, symbol );
603  }
604  if ( mDiagramProvider )
605  {
606  mDiagramProvider->registerFeature( fet, context, obstacleGeometry );
607  }
608  }
609  }
610 
612  context.setFeatureClipGeometry( QgsGeometry() );
613 
614  scopePopper.reset();
615 
616  if ( features.empty() )
617  {
618  // nothing to draw
619  stopRenderer( renderer, selRenderer );
620  return;
621  }
622 
623  // find out the order
624  QgsSymbolLevelOrder levels;
625  QgsSymbolList symbols = renderer->symbols( context );
626  for ( int i = 0; i < symbols.count(); i++ )
627  {
628  QgsSymbol *sym = symbols[i];
629  for ( int j = 0; j < sym->symbolLayerCount(); j++ )
630  {
631  int level = sym->symbolLayer( j )->renderingPass();
632  if ( level < 0 || level >= 1000 ) // ignore invalid levels
633  continue;
634  QgsSymbolLevelItem item( sym, j );
635  while ( level >= levels.count() ) // append new empty levels
636  levels.append( QgsSymbolLevel() );
637  levels[level].append( item );
638  }
639  }
640 
641  if ( mApplyClipGeometries )
643 
644  // 2. draw features in correct order
645  for ( int l = 0; l < levels.count(); l++ )
646  {
647  QgsSymbolLevel &level = levels[l];
648  for ( int i = 0; i < level.count(); i++ )
649  {
650  QgsSymbolLevelItem &item = level[i];
651  if ( !features.contains( item.symbol() ) )
652  {
653  QgsDebugMsg( QStringLiteral( "level item's symbol not found!" ) );
654  continue;
655  }
656  int layer = item.layer();
657  QList<QgsFeature> &lst = features[item.symbol()];
658  QList<QgsFeature>::iterator fit;
659  for ( fit = lst.begin(); fit != lst.end(); ++fit )
660  {
661  if ( context.renderingStopped() )
662  {
663  stopRenderer( renderer, selRenderer );
664  return;
665  }
666 
667  bool sel = isMainRenderer && context.showSelection() && mSelectedFeatureIds.contains( fit->id() );
668  // maybe vertex markers should be drawn only during the last pass...
669  bool drawMarker = isMainRenderer && ( mDrawVertexMarkers && context.drawEditingInformation() && ( !mVertexMarkerOnlyForSelection || sel ) );
670 
671  context.expressionContext().setFeature( *fit );
672 
673  try
674  {
675  renderer->renderFeature( *fit, context, layer, sel, drawMarker );
676 
677  // as soon as first feature is rendered, we can start showing layer updates.
678  // but if we are blocking render updates (so that a previously cached image is being shown), we wait
679  // at most e.g. 3 seconds before we start forcing progressive updates.
681  {
682  mReadyToCompose = true;
683  }
684  }
685  catch ( const QgsCsException &cse )
686  {
687  Q_UNUSED( cse )
688  QgsDebugMsg( QStringLiteral( "Failed to transform a point while drawing a feature with ID '%1'. Ignoring this feature. %2" )
689  .arg( fet.id() ).arg( cse.what() ) );
690  }
691  }
692  }
693  }
694 
695  stopRenderer( renderer, selRenderer );
696 }
697 
698 void QgsVectorLayerRenderer::stopRenderer( QgsFeatureRenderer *renderer, QgsSingleSymbolRenderer *selRenderer )
699 {
700  QgsRenderContext &context = *renderContext();
701  renderer->stopRender( context );
702  if ( selRenderer )
703  {
704  selRenderer->stopRender( context );
705  delete selRenderer;
706  }
707 }
708 
709 void QgsVectorLayerRenderer::prepareLabeling( QgsVectorLayer *layer, QSet<QString> &attributeNames )
710 {
711  QgsRenderContext &context = *renderContext();
712  // TODO: add attributes for geometry generator
713  if ( QgsLabelingEngine *engine2 = context.labelingEngine() )
714  {
715  if ( layer->labelsEnabled() )
716  {
717  mLabelProvider = layer->labeling()->provider( layer );
718  if ( mLabelProvider )
719  {
720  engine2->addProvider( mLabelProvider );
721  if ( !mLabelProvider->prepare( context, attributeNames ) )
722  {
723  engine2->removeProvider( mLabelProvider );
724  mLabelProvider = nullptr; // deleted by engine
725  }
726  }
727  }
728  }
729 
730 #if 0 // TODO: limit of labels, font not found
731  QgsPalLayerSettings &palyr = mContext.labelingEngine()->layer( mLayerID );
732 
733  // see if feature count limit is set for labeling
734  if ( palyr.limitNumLabels && palyr.maxNumLabels > 0 )
735  {
736  QgsFeatureIterator fit = getFeatures( QgsFeatureRequest()
737  .setFilterRect( mContext.extent() )
738  .setNoAttributes() );
739 
740  // total number of features that may be labeled
741  QgsFeature f;
742  int nFeatsToLabel = 0;
743  while ( fit.nextFeature( f ) )
744  {
745  nFeatsToLabel++;
746  }
747  palyr.mFeaturesToLabel = nFeatsToLabel;
748  }
749 
750  // notify user about any font substitution
751  if ( !palyr.mTextFontFound && !mLabelFontNotFoundNotified )
752  {
753  emit labelingFontNotFound( this, palyr.mTextFontFamily );
754  mLabelFontNotFoundNotified = true;
755  }
756 #endif
757 }
758 
759 void QgsVectorLayerRenderer::prepareDiagrams( QgsVectorLayer *layer, QSet<QString> &attributeNames )
760 {
761  QgsRenderContext &context = *renderContext();
762  if ( QgsLabelingEngine *engine2 = context.labelingEngine() )
763  {
764  if ( layer->diagramsEnabled() )
765  {
767  // need to be added before calling prepare() - uses map settings from engine
768  engine2->addProvider( mDiagramProvider );
769  if ( !mDiagramProvider->prepare( context, attributeNames ) )
770  {
771  engine2->removeProvider( mDiagramProvider );
772  mDiagramProvider = nullptr; // deleted by engine
773  }
774  }
775  }
776 }
777 
778 /* ----------------------------------------- */
779 /* QgsVectorLayerRendererInterruptionChecker */
780 /* ----------------------------------------- */
781 
783 ( const QgsRenderContext &context )
784  : mContext( context )
785  , mTimer( new QTimer( this ) )
786 {
787  connect( mTimer, &QTimer::timeout, this, [ = ]
788  {
789  if ( mContext.renderingStopped() )
790  {
791  mTimer->stop();
792  cancel();
793  }
794  } );
795  mTimer->start( 50 );
796 
797 }
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
virtual bool usesEmbeddedSymbols() const
Returns true if the renderer uses embedded symbols for features.
void setVertexMarkerAppearance(int type, double size)
Sets type and size of editing vertex markers for subsequent rendering.
bool usingSymbolLevels() const
Definition: qgsrenderer.h:291
virtual QString dump() const
Returns debug information about this renderer.
virtual QgsFeatureRenderer::Capabilities capabilities()
Returns details about internals of this renderer.
Definition: qgsrenderer.h:282
@ SymbolLevels
Rendering with symbol levels (i.e. implements symbols(), symbolForFeature())
Definition: qgsrenderer.h:262
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 & setFlags(QgsFeatureRequest::Flags flags)
Sets flags that affect how features will be fetched.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
@ EmbeddedSymbols
Retrieve any embedded feature symbology (since QGIS 3.20)
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.
const Flags & flags() const
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
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:205
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 representing the specified geometry.
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:79
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::MessageLevel::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:59
double y
Definition: qgspointxy.h:63
Q_GADGET double x
Definition: qgspointxy.h:62
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:193
double xMaximum() const SIP_HOLDGIL
Returns the x maximum value (right side of rectangle).
Definition: qgsrectangle.h:183
double xMinimum() const SIP_HOLDGIL
Returns the x minimum value (left side of rectangle).
Definition: qgsrectangle.h:188
double yMinimum() const SIP_HOLDGIL
Returns the y minimum value (bottom side of rectangle).
Definition: qgsrectangle.h:198
bool isEmpty() const
Returns true if the rectangle is empty.
Definition: qgsrectangle.h:469
QgsRectangle intersect(const QgsRectangle &rect) const
Returns the intersection with the given rectangle.
Definition: qgsrectangle.h:333
bool isFinite() const
Returns true if the rectangle has finite boundaries.
Definition: qgsrectangle.h:559
QgsPointXY center() const SIP_HOLDGIL
Returns the center point of the rectangle.
Definition: qgsrectangle.h:251
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 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:38
QgsSymbolLayer * symbolLayer(int layer)
Returns the symbol layer at the specified index.
Definition: qgssymbol.cpp:420
static QgsSymbol * defaultSymbol(QgsWkbTypes::GeometryType geomType)
Returns a new default symbol for the specified geometry type.
Definition: qgssymbol.cpp:355
void setColor(const QColor &color)
Sets the color for the symbol.
Definition: qgssymbol.cpp:541
int symbolLayerCount() const
Returns the total number of symbol layers contained in the symbol.
Definition: qgssymbol.h:160
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:598
#define QgsDebugMsgLevel(str, level)
Definition: qgslogger.h:39
#define QgsDebugMsg(str)
Definition: qgslogger.h:38
QList< QgsSymbolLevel > QgsSymbolLevelOrder
Definition: qgsrenderer.h:87
QList< QgsSymbolLevelItem > QgsSymbolLevel
Definition: qgsrenderer.h:83
QList< QgsSymbol * > QgsSymbolList
Definition: qgsrenderer.h:43