QGIS API Documentation  3.20.0-Odense (decaadbb31)
qgslabelingengine.cpp
Go to the documentation of this file.
1 
2 /***************************************************************************
3  qgslabelingengine.cpp
4  --------------------------------------
5  Date : September 2015
6  Copyright : (C) 2015 by Martin Dobias
7  Email : wonder dot sk at gmail dot com
8  ***************************************************************************
9  * *
10  * This program is free software; you can redistribute it and/or modify *
11  * it under the terms of the GNU General Public License as published by *
12  * the Free Software Foundation; either version 2 of the License, or *
13  * (at your option) any later version. *
14  * *
15  ***************************************************************************/
16 
17 #include "qgslabelingengine.h"
18 
19 #include "qgslogger.h"
20 
21 #include "feature.h"
22 #include "labelposition.h"
23 #include "layer.h"
24 #include "pal.h"
25 #include "problem.h"
26 #include "qgsrendercontext.h"
27 #include "qgsmaplayer.h"
28 #include "qgssymbol.h"
31 #include "qgslabelingresults.h"
32 #include "qgsfillsymbol.h"
33 
34 // helper function for checking for job cancellation within PAL
35 static bool _palIsCanceled( void *ctx )
36 {
37  return ( reinterpret_cast< QgsRenderContext * >( ctx ) )->renderingStopped();
38 }
39 
46 {
47  public:
48 
49  explicit QgsLabelSorter( const QgsMapSettings &mapSettings )
50  : mMapSettings( mapSettings )
51  {}
52 
54  {
55  QgsLabelFeature *lf1 = lp1->getFeaturePart()->feature();
56  QgsLabelFeature *lf2 = lp2->getFeaturePart()->feature();
57 
58  if ( !qgsDoubleNear( lf1->zIndex(), lf2->zIndex() ) )
59  return lf1->zIndex() < lf2->zIndex();
60 
61  //equal z-index, so fallback to respecting layer render order
62  QStringList layerIds = mMapSettings.layerIds();
63  int layer1Pos = layerIds.indexOf( lf1->provider()->layerId() );
64  int layer2Pos = layerIds.indexOf( lf2->provider()->layerId() );
65  if ( layer1Pos != layer2Pos && layer1Pos >= 0 && layer2Pos >= 0 )
66  return layer1Pos > layer2Pos; //higher positions are rendered first
67 
68  //same layer, so render larger labels first
69  return lf1->size().width() * lf1->size().height() > lf2->size().width() * lf2->size().height();
70  }
71 
72  private:
73 
74  const QgsMapSettings &mMapSettings;
75 };
76 
77 //
78 // QgsLabelingEngine
79 //
80 
82  : mResults( new QgsLabelingResults )
83 {}
84 
86 {
87  qDeleteAll( mProviders );
88  qDeleteAll( mSubProviders );
89 }
90 
92 {
94  if ( mResults )
95  mResults->setMapSettings( mapSettings );
96 }
97 
98 QList< QgsMapLayer * > QgsLabelingEngine::participatingLayers() const
99 {
100  QList< QgsMapLayer * > layers;
101 
102  // try to return layers sorted in the desired z order for rendering
103  QList< QgsAbstractLabelProvider * > providersByZ = mProviders;
104  std::sort( providersByZ.begin(), providersByZ.end(),
105  []( const QgsAbstractLabelProvider * a, const QgsAbstractLabelProvider * b ) -> bool
106  {
107  const QgsVectorLayerLabelProvider *providerA = dynamic_cast<const QgsVectorLayerLabelProvider *>( a );
108  const QgsVectorLayerLabelProvider *providerB = dynamic_cast<const QgsVectorLayerLabelProvider *>( b );
109 
110  if ( providerA && providerB )
111  {
112  return providerA->settings().zIndex < providerB->settings().zIndex ;
113  }
114  return false;
115  } );
116 
117  QList< QgsAbstractLabelProvider * > subProvidersByZ = mSubProviders;
118  std::sort( subProvidersByZ.begin(), subProvidersByZ.end(),
119  []( const QgsAbstractLabelProvider * a, const QgsAbstractLabelProvider * b ) -> bool
120  {
121  const QgsVectorLayerLabelProvider *providerA = dynamic_cast<const QgsVectorLayerLabelProvider *>( a );
122  const QgsVectorLayerLabelProvider *providerB = dynamic_cast<const QgsVectorLayerLabelProvider *>( b );
123 
124  if ( providerA && providerB )
125  {
126  return providerA->settings().zIndex < providerB->settings().zIndex ;
127  }
128  return false;
129  } );
130 
131  for ( QgsAbstractLabelProvider *provider : std::as_const( providersByZ ) )
132  {
133  if ( provider->layer() && !layers.contains( provider->layer() ) )
134  layers << provider->layer();
135  }
136  for ( QgsAbstractLabelProvider *provider : std::as_const( subProvidersByZ ) )
137  {
138  if ( provider->layer() && !layers.contains( provider->layer() ) )
139  layers << provider->layer();
140  }
141  return layers;
142 }
143 
145 {
146  QStringList layers;
147 
148  // try to return layers sorted in the desired z order for rendering
149  QList< QgsAbstractLabelProvider * > providersByZ = mProviders;
150  std::sort( providersByZ.begin(), providersByZ.end(),
151  []( const QgsAbstractLabelProvider * a, const QgsAbstractLabelProvider * b ) -> bool
152  {
153  const QgsVectorLayerLabelProvider *providerA = dynamic_cast<const QgsVectorLayerLabelProvider *>( a );
154  const QgsVectorLayerLabelProvider *providerB = dynamic_cast<const QgsVectorLayerLabelProvider *>( b );
155 
156  if ( providerA && providerB )
157  {
158  return providerA->settings().zIndex < providerB->settings().zIndex ;
159  }
160  return false;
161  } );
162 
163  QList< QgsAbstractLabelProvider * > subProvidersByZ = mSubProviders;
164  std::sort( subProvidersByZ.begin(), subProvidersByZ.end(),
165  []( const QgsAbstractLabelProvider * a, const QgsAbstractLabelProvider * b ) -> bool
166  {
167  const QgsVectorLayerLabelProvider *providerA = dynamic_cast<const QgsVectorLayerLabelProvider *>( a );
168  const QgsVectorLayerLabelProvider *providerB = dynamic_cast<const QgsVectorLayerLabelProvider *>( b );
169 
170  if ( providerA && providerB )
171  {
172  return providerA->settings().zIndex < providerB->settings().zIndex ;
173  }
174  return false;
175  } );
176 
177  for ( QgsAbstractLabelProvider *provider : std::as_const( providersByZ ) )
178  {
179  if ( !layers.contains( provider->layerId() ) )
180  layers << provider->layerId();
181  }
182  for ( QgsAbstractLabelProvider *provider : std::as_const( subProvidersByZ ) )
183  {
184  if ( !layers.contains( provider->layerId() ) )
185  layers << provider->layerId();
186  }
187  return layers;
188 }
189 
191 {
192  provider->setEngine( this );
193  mProviders << provider;
194 }
195 
197 {
198  int idx = mProviders.indexOf( provider );
199  if ( idx >= 0 )
200  {
201  delete mProviders.takeAt( idx );
202  }
203 }
204 
206 {
207  QgsAbstractLabelProvider::Flags flags = provider->flags();
208 
209  // create the pal layer
210  pal::Layer *l = p.addLayer( provider,
211  provider->name(),
212  provider->placement(),
213  provider->priority(),
214  true,
215  flags.testFlag( QgsAbstractLabelProvider::DrawLabels ),
216  flags.testFlag( QgsAbstractLabelProvider::DrawAllLabels ) );
217 
218  // set whether adjacent lines should be merged
220 
221  // set obstacle type
222  l->setObstacleType( provider->obstacleType() );
223 
224  // set whether location of centroid must be inside of polygons
226 
227  // set how to show upside-down labels
229  switch ( provider->upsidedownLabels() )
230  {
232  upsdnlabels = pal::Layer::Upright;
233  break;
235  upsdnlabels = pal::Layer::ShowDefined;
236  break;
238  upsdnlabels = pal::Layer::ShowAll;
239  break;
240  }
241  l->setUpsidedownLabels( upsdnlabels );
242 
243 
244  const QList<QgsLabelFeature *> features = provider->labelFeatures( context );
245 
246  for ( QgsLabelFeature *feature : features )
247  {
248  try
249  {
250  l->registerFeature( feature );
251  }
252  catch ( std::exception &e )
253  {
254  Q_UNUSED( e )
255  QgsDebugMsgLevel( QStringLiteral( "Ignoring feature %1 due PAL exception:" ).arg( feature->id() ) + QString::fromLatin1( e.what() ), 4 );
256  continue;
257  }
258  }
259 
260  // any sub-providers?
261  const auto subproviders = provider->subProviders();
262  for ( QgsAbstractLabelProvider *subProvider : subproviders )
263  {
264  mSubProviders << subProvider;
265  processProvider( subProvider, context, p );
266  }
267 }
268 
270 {
272 
273  mPal = std::make_unique< pal::Pal >();
274 
275  mPal->setMaximumLineCandidatesPerMapUnit( settings.maximumLineCandidatesPerCm() / context.convertToMapUnits( 10, QgsUnitTypes::RenderMillimeters ) );
276  mPal->setMaximumPolygonCandidatesPerMapUnitSquared( settings.maximumPolygonCandidatesPerCmSquared() / std::pow( context.convertToMapUnits( 10, QgsUnitTypes::RenderMillimeters ), 2 ) );
277 
278  mPal->setShowPartialLabels( settings.testFlag( QgsLabelingEngineSettings::UsePartialCandidates ) );
279  mPal->setPlacementVersion( settings.placementVersion() );
280 
281  // for each provider: get labels and register them in PAL
282  for ( QgsAbstractLabelProvider *provider : std::as_const( mProviders ) )
283  {
284  std::unique_ptr< QgsExpressionContextScopePopper > layerScopePopper;
285  if ( QgsMapLayer *ml = provider->layer() )
286  {
287  layerScopePopper = std::make_unique< QgsExpressionContextScopePopper >( context.expressionContext(), QgsExpressionContextUtils::layerScope( ml ) );
288  }
289  processProvider( provider, context, *mPal );
290  }
291 }
292 
294 {
295  Q_ASSERT( mPal.get() );
296 
297  // NOW DO THE LAYOUT (from QgsPalLabeling::drawLabeling)
299 
300  QPainter *painter = context.painter();
301 
303  QPolygonF visiblePoly = mMapSettings.visiblePolygon();
304  visiblePoly.append( visiblePoly.at( 0 ) ); //close polygon
305 
306  // get map label boundary geometry - if one hasn't been explicitly set, we use the whole of the map's visible polygon
308 
309  // label blocking regions work by "chopping away" those regions from the permissible labeling area
310  const QList< QgsLabelBlockingRegion > blockingRegions = mMapSettings.labelBlockingRegions();
311  for ( const QgsLabelBlockingRegion &region : blockingRegions )
312  {
313  mapBoundaryGeom = mapBoundaryGeom.difference( region.geometry );
314  }
315 
317  {
318  // draw map boundary
319  QgsFeature f;
320  f.setGeometry( mapBoundaryGeom );
321  QVariantMap properties;
322  properties.insert( QStringLiteral( "style" ), QStringLiteral( "no" ) );
323  properties.insert( QStringLiteral( "style_border" ), QStringLiteral( "solid" ) );
324  properties.insert( QStringLiteral( "color_border" ), QStringLiteral( "#0000ff" ) );
325  properties.insert( QStringLiteral( "width_border" ), QStringLiteral( "0.3" ) );
326  properties.insert( QStringLiteral( "joinstyle" ), QStringLiteral( "miter" ) );
327  std::unique_ptr< QgsFillSymbol > boundarySymbol( QgsFillSymbol::createSimple( properties ) );
328  boundarySymbol->startRender( context );
329  boundarySymbol->renderFeature( f, context );
330  boundarySymbol->stopRender( context );
331  }
332 
333  if ( !qgsDoubleNear( mMapSettings.rotation(), 0.0 ) )
334  {
335  //PAL features are prerotated, so extent also needs to be unrotated
337  // yes - this is rotated in the opposite direction... phew, this is confusing!
338  mapBoundaryGeom.rotate( mMapSettings.rotation(), mMapSettings.visibleExtent().center() );
339  }
340 
341  QgsRectangle extent = extentGeom.boundingBox();
342 
343  mPal->registerCancellationCallback( &_palIsCanceled, reinterpret_cast< void * >( &context ) );
344 
345  QElapsedTimer t;
346  t.start();
347 
348  // do the labeling itself
349  try
350  {
351  mProblem = mPal->extractProblem( extent, mapBoundaryGeom );
352  }
353  catch ( std::exception &e )
354  {
355  Q_UNUSED( e )
356  QgsDebugMsgLevel( "PAL EXCEPTION :-( " + QString::fromLatin1( e.what() ), 4 );
357  return;
358  }
359 
360  if ( context.renderingStopped() )
361  {
362  return; // it has been canceled
363  }
364 
365 #if 1 // XXX strk
366  // features are pre-rotated but not scaled/translated,
367  // so we only disable rotation here. Ideally, they'd be
368  // also pre-scaled/translated, as suggested here:
369  // https://github.com/qgis/QGIS/issues/20071
371  xform.setMapRotation( 0, 0, 0 );
372 #else
373  const QgsMapToPixel &xform = mMapSettings->mapToPixel();
374 #endif
375 
376  // draw rectangles with all candidates
377  // this is done before actual solution of the problem
378  // before number of candidates gets reduced
379  // TODO mCandidates.clear();
381  {
382  painter->setBrush( Qt::NoBrush );
383  for ( int i = 0; i < static_cast< int >( mProblem->featureCount() ); i++ )
384  {
385  for ( int j = 0; j < mProblem->featureCandidateCount( i ); j++ )
386  {
387  pal::LabelPosition *lp = mProblem->featureCandidate( i, j );
388 
389  QgsPalLabeling::drawLabelCandidateRect( lp, painter, &xform );
390  }
391  }
392  }
393 
394  // find the solution
395  mLabels = mPal->solveProblem( mProblem.get(),
398 
399  // sort labels
400  std::sort( mLabels.begin(), mLabels.end(), QgsLabelSorter( mMapSettings ) );
401 
402  QgsDebugMsgLevel( QStringLiteral( "LABELING work: %1 ms ... labels# %2" ).arg( t.elapsed() ).arg( mLabels.size() ), 4 );
403 }
404 
405 void QgsLabelingEngine::drawLabels( QgsRenderContext &context, const QString &layerId )
406 {
407  QElapsedTimer t;
408  t.start();
409 
411 
412  context.setPainterFlagsUsingContext();
413  QPainter *painter = context.painter();
414 
415  // prepare for rendering
416  for ( QgsAbstractLabelProvider *provider : std::as_const( mProviders ) )
417  {
418  if ( !layerId.isEmpty() && provider->layerId() != layerId )
419  continue;
420 
421  // provider will require the correct layer scope for expression preparation - at this stage, the existing expression context
422  // only contains generic scopes
424  provider->startRender( context );
425  }
426 
428  std::unique_ptr< QgsExpressionContextScopePopper > symbolScopePopper = std::make_unique< QgsExpressionContextScopePopper >( context.expressionContext(), symbolScope );
429 
430  // draw label backgrounds
431  for ( pal::LabelPosition *label : std::as_const( mLabels ) )
432  {
433  if ( context.renderingStopped() )
434  break;
435 
436  QgsLabelFeature *lf = label->getFeaturePart()->feature();
437  if ( !lf )
438  {
439  continue;
440  }
441 
442  if ( !layerId.isEmpty() && lf->provider()->layerId() != layerId )
443  continue;
444 
445  context.expressionContext().setFeature( lf->feature() );
446  context.expressionContext().setFields( lf->feature().fields() );
447  if ( lf->symbol() )
448  {
449  symbolScope = QgsExpressionContextUtils::updateSymbolScope( lf->symbol(), symbolScope );
450  }
451  lf->provider()->drawLabelBackground( context, label );
452  }
453 
454  // draw the labels
455  for ( pal::LabelPosition *label : std::as_const( mLabels ) )
456  {
457  if ( context.renderingStopped() )
458  break;
459 
460  QgsLabelFeature *lf = label->getFeaturePart()->feature();
461  if ( !lf )
462  {
463  continue;
464  }
465 
466  if ( !layerId.isEmpty() && lf->provider()->layerId() != layerId )
467  continue;
468 
469  context.expressionContext().setFeature( lf->feature() );
470  context.expressionContext().setFields( lf->feature().fields() );
471  if ( lf->symbol() )
472  {
473  symbolScope = QgsExpressionContextUtils::updateSymbolScope( lf->symbol(), symbolScope );
474  }
475  lf->provider()->drawLabel( context, label );
476  // finished with symbol -- we can't keep it around after this, it may be deleted
477  lf->setSymbol( nullptr );
478  }
479 
480  // draw unplaced labels. These are always rendered on top
482  {
483  for ( pal::LabelPosition *label : std::as_const( mUnlabeled ) )
484  {
485  if ( context.renderingStopped() )
486  break;
487  QgsLabelFeature *lf = label->getFeaturePart()->feature();
488  if ( !lf )
489  {
490  continue;
491  }
492 
493  if ( !layerId.isEmpty() && lf->provider()->layerId() != layerId )
494  continue;
495 
496  context.expressionContext().setFeature( lf->feature() );
497  context.expressionContext().setFields( lf->feature().fields() );
498  if ( lf->symbol() )
499  {
500  symbolScope = QgsExpressionContextUtils::updateSymbolScope( lf->symbol(), symbolScope );
501  }
502  lf->provider()->drawUnplacedLabel( context, label );
503  // finished with symbol -- we can't keep it around after this, it may be deleted
504  lf->setSymbol( nullptr );
505  }
506  }
507 
508  symbolScopePopper.reset();
509 
510  // cleanup
511  for ( QgsAbstractLabelProvider *provider : std::as_const( mProviders ) )
512  {
513  if ( !layerId.isEmpty() && provider->layerId() != layerId )
514  continue;
515 
516  provider->stopRender( context );
517  }
518 
519  // Reset composition mode for further drawing operations
520  painter->setCompositionMode( QPainter::CompositionMode_SourceOver );
521 
522  QgsDebugMsgLevel( QStringLiteral( "LABELING draw: %1 ms" ).arg( t.elapsed() ), 4 );
523 }
524 
526 {
527  mUnlabeled.clear();
528  mLabels.clear();
529  mProblem.reset();
530  mPal.reset();
531 }
532 
534 {
535  return mResults.release();
536 }
537 
538 
539 //
540 // QgsDefaultLabelingEngine
541 //
542 
545 {
546 
547 }
548 
550 {
551  registerLabels( context );
552  if ( context.renderingStopped() )
553  {
554  cleanup();
555  return; // it has been canceled
556  }
557 
558  solve( context );
559  if ( context.renderingStopped() )
560  {
561  cleanup();
562  return;
563  }
564 
565  drawLabels( context );
566  cleanup();
567 }
568 
569 
570 //
571 // QgsStagedRenderLabelingEngine
572 //
573 
576 {
577 
578 }
579 
581 {
582  registerLabels( context );
583  if ( context.renderingStopped() )
584  {
585  cleanup();
586  return; // it has been canceled
587  }
588 
589  solve( context );
590  if ( context.renderingStopped() )
591  {
592  cleanup();
593  return;
594  }
595 }
596 
597 
599 {
600  drawLabels( context, layerId );
601 }
602 
604 {
605  cleanup();
606 }
607 
608 
610 
612 {
613  return mLayer ? mLayer->provider() : nullptr;
614 
615 }
616 
618  : mLayerId( layer ? layer->id() : QString() )
619  , mLayer( layer )
620  , mProviderId( providerId )
621  , mFlags( DrawLabels )
622  , mPlacement( QgsPalLayerSettings::AroundPoint )
623  , mPriority( 0.5 )
624  , mUpsidedownLabels( QgsPalLayerSettings::Upright )
625 {
626 }
627 
629 {
630 
631 }
632 
634 {
635 
636 }
637 
639 {
640  const auto subproviders = subProviders();
641  for ( QgsAbstractLabelProvider *subProvider : subproviders )
642  {
643  subProvider->startRender( context );
644  }
645 }
646 
648 {
649  const auto subproviders = subProviders();
650  for ( QgsAbstractLabelProvider *subProvider : subproviders )
651  {
652  subProvider->stopRender( context );
653  }
654 }
655 
656 //
657 // QgsLabelingUtils
658 //
659 
660 QString QgsLabelingUtils::encodePredefinedPositionOrder( const QVector<QgsPalLayerSettings::PredefinedPointPosition> &positions )
661 {
662  QStringList predefinedOrderString;
663  const auto constPositions = positions;
664  for ( QgsPalLayerSettings::PredefinedPointPosition position : constPositions )
665  {
666  switch ( position )
667  {
669  predefinedOrderString << QStringLiteral( "TL" );
670  break;
672  predefinedOrderString << QStringLiteral( "TSL" );
673  break;
675  predefinedOrderString << QStringLiteral( "T" );
676  break;
678  predefinedOrderString << QStringLiteral( "TSR" );
679  break;
681  predefinedOrderString << QStringLiteral( "TR" );
682  break;
684  predefinedOrderString << QStringLiteral( "L" );
685  break;
687  predefinedOrderString << QStringLiteral( "R" );
688  break;
690  predefinedOrderString << QStringLiteral( "BL" );
691  break;
693  predefinedOrderString << QStringLiteral( "BSL" );
694  break;
696  predefinedOrderString << QStringLiteral( "B" );
697  break;
699  predefinedOrderString << QStringLiteral( "BSR" );
700  break;
702  predefinedOrderString << QStringLiteral( "BR" );
703  break;
704  }
705  }
706  return predefinedOrderString.join( ',' );
707 }
708 
709 QVector<QgsPalLayerSettings::PredefinedPointPosition> QgsLabelingUtils::decodePredefinedPositionOrder( const QString &positionString )
710 {
711  QVector<QgsPalLayerSettings::PredefinedPointPosition> result;
712  const QStringList predefinedOrderList = positionString.split( ',' );
713  result.reserve( predefinedOrderList.size() );
714  for ( const QString &position : predefinedOrderList )
715  {
716  QString cleaned = position.trimmed().toUpper();
717  if ( cleaned == QLatin1String( "TL" ) )
719  else if ( cleaned == QLatin1String( "TSL" ) )
721  else if ( cleaned == QLatin1String( "T" ) )
723  else if ( cleaned == QLatin1String( "TSR" ) )
725  else if ( cleaned == QLatin1String( "TR" ) )
727  else if ( cleaned == QLatin1String( "L" ) )
729  else if ( cleaned == QLatin1String( "R" ) )
731  else if ( cleaned == QLatin1String( "BL" ) )
733  else if ( cleaned == QLatin1String( "BSL" ) )
735  else if ( cleaned == QLatin1String( "B" ) )
737  else if ( cleaned == QLatin1String( "BSR" ) )
739  else if ( cleaned == QLatin1String( "BR" ) )
741  }
742  return result;
743 }
744 
745 QString QgsLabelingUtils::encodeLinePlacementFlags( QgsLabeling::LinePlacementFlags flags )
746 {
747  QStringList parts;
748  if ( flags & QgsLabeling::LinePlacementFlag::OnLine )
749  parts << QStringLiteral( "OL" );
750  if ( flags & QgsLabeling::LinePlacementFlag::AboveLine )
751  parts << QStringLiteral( "AL" );
752  if ( flags & QgsLabeling::LinePlacementFlag::BelowLine )
753  parts << QStringLiteral( "BL" );
754  if ( !( flags & QgsLabeling::LinePlacementFlag::MapOrientation ) )
755  parts << QStringLiteral( "LO" );
756  return parts.join( ',' );
757 }
758 
759 QgsLabeling::LinePlacementFlags QgsLabelingUtils::decodeLinePlacementFlags( const QString &string )
760 {
761  QgsLabeling::LinePlacementFlags flags = QgsLabeling::LinePlacementFlags();
762  const QStringList flagList = string.split( ',' );
763  bool foundLineOrientationFlag = false;
764  for ( const QString &flag : flagList )
765  {
766  QString cleaned = flag.trimmed().toUpper();
767  if ( cleaned == QLatin1String( "OL" ) )
768  flags |= QgsLabeling::LinePlacementFlag::OnLine;
769  else if ( cleaned == QLatin1String( "AL" ) )
770  flags |= QgsLabeling::LinePlacementFlag::AboveLine;
771  else if ( cleaned == QLatin1String( "BL" ) )
772  flags |= QgsLabeling::LinePlacementFlag::BelowLine;
773  else if ( cleaned == QLatin1String( "LO" ) )
774  foundLineOrientationFlag = true;
775  }
776  if ( !foundLineOrientationFlag )
777  flags |= QgsLabeling::LinePlacementFlag::MapOrientation;
778  return flags;
779 }
780 
The QgsAbstractLabelProvider class is an interface class.
virtual void drawUnplacedLabel(QgsRenderContext &context, pal::LabelPosition *label) const
Draw an unplaced label.
virtual void stopRender(QgsRenderContext &context)
To be called after rendering is complete.
void setEngine(const QgsLabelingEngine *engine)
Associate provider with a labeling engine (should be only called internally from QgsLabelingEngine)
virtual void drawLabel(QgsRenderContext &context, pal::LabelPosition *label) const =0
Draw this label at the position determined by the labeling engine.
QgsPalLayerSettings::Placement placement() const
What placement strategy to use for the labels.
virtual QList< QgsLabelFeature * > labelFeatures(QgsRenderContext &context)=0
Returns list of label features (they are owned by the provider and thus deleted on its destruction)
double priority() const
Default priority of labels (may be overridden by individual labels)
virtual void drawLabelBackground(QgsRenderContext &context, pal::LabelPosition *label) const
Draw the background for the specified label.
QString name() const
Name of the layer (for statistics, debugging etc.) - does not need to be unique.
virtual void startRender(QgsRenderContext &context)
To be called before rendering of labels begins.
Flags flags() const
Flags associated with the provider.
QgsLabelObstacleSettings::ObstacleType obstacleType() const
How the feature geometries will work as obstacles.
@ DrawAllLabels
Whether all features will be labelled even though overlaps occur.
@ MergeConnectedLines
Whether adjacent lines (with the same label text) should be merged.
@ DrawLabels
Whether the labels should be rendered.
@ CentroidMustBeInside
Whether location of centroid must be inside of polygons.
QgsPalLayerSettings::UpsideDownLabels upsidedownLabels() const
How to handle labels that would be upside down.
virtual QList< QgsAbstractLabelProvider * > subProviders()
Returns list of child providers - useful if the provider needs to put labels into more layers with di...
QString layerId() const
Returns ID of associated layer, or empty string if no layer is associated with the provider.
QgsAbstractLabelProvider(QgsMapLayer *layer, const QString &providerId=QString())
Construct the provider with default values.
QgsDefaultLabelingEngine()
Construct the labeling engine with default settings.
void run(QgsRenderContext &context) override
Runs the labeling job.
RAII class to pop scope from an expression context on destruction.
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.
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
void setFields(const QgsFields &fields)
Convenience function for setting a fields for the context.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition: qgsfeature.h:56
QgsFields fields
Definition: qgsfeature.h:66
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Definition: qgsfeature.cpp:145
static QgsFillSymbol * createSimple(const QVariantMap &properties)
Create a fill symbol with one symbol layer: SimpleFill with specified properties.
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:124
QgsGeometry difference(const QgsGeometry &geometry) const
Returns a geometry representing the points making up this geometry that do not make up other.
OperationResult rotate(double rotation, const QgsPointXY &center)
Rotate this geometry around the Z axis.
static QgsGeometry fromQPolygonF(const QPolygonF &polygon)
Construct geometry from a QPolygonF.
Q_GADGET bool isNull
Definition: qgsgeometry.h:126
static QgsGeometry fromRect(const QgsRectangle &rect) SIP_HOLDGIL
Creates a new geometry from a QgsRectangle.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
Label blocking region (in map coordinates and CRS).
The QgsLabelFeature class describes a feature that should be used within the labeling engine.
QSizeF size(double angle=0.0) const
Size of the label (in map units)
QgsAbstractLabelProvider * provider() const
Returns provider of this instance.
const QgsSymbol * symbol()
Returns the feature symbol associated with this label.
void setSymbol(const QgsSymbol *symbol)
Sets the feature symbol associated with this label.
pal::Layer * mLayer
Pointer to PAL layer (assigned when registered to PAL)
QgsFeature feature() const
Returns the original feature associated with this label.
double zIndex() const
Returns the label's z-index.
Helper class for sorting labels into correct draw order.
QgsLabelSorter(const QgsMapSettings &mapSettings)
bool operator()(pal::LabelPosition *lp1, pal::LabelPosition *lp2) const
Stores global configuration for labeling engine.
bool testFlag(Flag f) const
Test whether a particular flag is enabled.
Flags flags() const
Gets flags of the labeling engine.
@ UseAllLabels
Whether to draw all labels even if there would be collisions.
@ UsePartialCandidates
Whether to use also label candidates that are partially outside of the map view.
@ CollectUnplacedLabels
Whether unplaced labels should be collected in the labeling results (regardless of whether they are b...
@ DrawUnplacedLabels
Whether to render unplaced labels as an indicator/warning for users.
@ DrawCandidates
Whether to draw rectangles of generated candidates (good for debugging)
PlacementEngineVersion placementVersion() const
Returns the placement engine version, which dictates how the label placement problem is solved.
double maximumPolygonCandidatesPerCmSquared() const
Returns the maximum number of polygon label candidate positions per centimeter squared.
double maximumLineCandidatesPerCm() const
Returns the maximum number of line label candidate positions per centimeter.
The QgsLabelingEngine class provides map labeling functionality.
std::unique_ptr< pal::Pal > mPal
std::unique_ptr< QgsLabelingResults > mResults
Resulting labeling layout.
QgsMapSettings mMapSettings
Associated map settings instance.
void solve(QgsRenderContext &context)
Solves the label problem.
QList< pal::LabelPosition * > mUnlabeled
std::unique_ptr< pal::Problem > mProblem
const QgsMapSettings & mapSettings() const
Gets associated map settings.
QList< pal::LabelPosition * > mLabels
QgsLabelingResults * takeResults()
Returns pointer to recently computed results and pass the ownership of results to the caller.
void cleanup()
Cleans up the engine following a call to registerLabels() or solve().
void setMapSettings(const QgsMapSettings &mapSettings)
Associate map settings instance.
void registerLabels(QgsRenderContext &context)
Runs the label registration step.
QList< QgsAbstractLabelProvider * > mSubProviders
void addProvider(QgsAbstractLabelProvider *provider)
Add provider of label features. Takes ownership of the provider.
void drawLabels(QgsRenderContext &context, const QString &layerId=QString())
Draws labels to the specified render context.
QStringList participatingLayerIds() const
Returns a list of layer IDs for layers with providers in the engine.
QList< QgsMapLayer * > participatingLayers() const
Returns a list of layers with providers in the engine.
void processProvider(QgsAbstractLabelProvider *provider, QgsRenderContext &context, pal::Pal &p)
QgsLabelingEngine()
Construct the labeling engine with default settings.
void removeProvider(QgsAbstractLabelProvider *provider)
Remove provider if the provider's initialization failed. Provider instance is deleted.
QList< QgsAbstractLabelProvider * > mProviders
List of providers (the are owned by the labeling engine)
virtual ~QgsLabelingEngine()
Clean up everything (especially the registered providers)
Class that stores computed placement from labeling engine.
static QVector< QgsPalLayerSettings::PredefinedPointPosition > decodePredefinedPositionOrder(const QString &positionString)
Decodes a string to an ordered list of predefined point label positions.
static QString encodeLinePlacementFlags(QgsLabeling::LinePlacementFlags flags)
Encodes line placement flags to a string.
static QString encodePredefinedPositionOrder(const QVector< QgsPalLayerSettings::PredefinedPointPosition > &positions)
Encodes an ordered list of predefined point label positions to a string.
static QgsLabeling::LinePlacementFlags decodeLinePlacementFlags(const QString &string)
Decodes a string to set of line placement flags.
Base class for all map layer types.
Definition: qgsmaplayer.h:70
The QgsMapSettings class contains configuration for rendering of the map.
QPolygonF visiblePolygon() const
Returns the visible area as a polygon (may be rotated)
QStringList layerIds() const
Returns the list of layer IDs which will be rendered in the map.
QgsGeometry labelBoundaryGeometry() const
Returns the label boundary geometry, which restricts where in the rendered map labels are permitted t...
QList< QgsLabelBlockingRegion > labelBlockingRegions() const
Returns the list of regions to avoid placing labels within.
const QgsMapToPixel & mapToPixel() const
QgsRectangle visibleExtent() const
Returns the actual extent derived from requested extent that takes takes output image size into accou...
const QgsLabelingEngineSettings & labelingEngineSettings() const
Returns the global configuration of the labeling engine.
double rotation() const
Returns the rotation of the resulting map image, in degrees clockwise.
Perform transforms between map coordinates and device coordinates.
Definition: qgsmaptopixel.h:39
void setMapRotation(double degrees, double cx, double cy)
Set map rotation in degrees (clockwise)
static void drawLabelCandidateRect(pal::LabelPosition *lp, QPainter *painter, const QgsMapToPixel *xform, QList< QgsLabelCandidate > *candidates=nullptr)
Contains settings for how a map layer will be labeled.
@ ShowDefined
Show upside down when rotation is layer- or data-defined.
@ Upright
Upside-down labels (90 <= angle < 270) are shown upright.
@ ShowAll
Show upside down for all labels, including dynamic ones.
PredefinedPointPosition
Positions for labels when using the QgsPalLabeling::OrderedPositionsAroundPoint placement mode.
@ BottomSlightlyLeft
Label below point, slightly left of center.
@ BottomMiddle
Label directly below point.
@ BottomSlightlyRight
Label below point, slightly right of center.
@ MiddleLeft
Label on left of point.
@ TopSlightlyRight
Label on top of point, slightly right of center.
@ TopSlightlyLeft
Label on top of point, slightly left of center.
@ MiddleRight
Label on right of point.
@ TopMiddle
Label directly above point.
@ BottomRight
Label on bottom right of point.
@ BottomLeft
Label on bottom-left of point.
@ TopRight
Label on top-right of point.
@ TopLeft
Label on top-left of point.
A rectangle specified with double values.
Definition: qgsrectangle.h:42
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.
QPainter * painter()
Returns the destination QPainter for the render operation.
QgsExpressionContext & expressionContext()
Gets the expression context.
void setPainterFlagsUsingContext(QPainter *painter=nullptr) const
Sets relevant flags on a destination painter, using the flags and settings currently defined for the ...
double convertToMapUnits(double size, QgsUnitTypes::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale()) const
Converts a size from the specified units to map units.
bool renderingStopped() const
Returns true if the rendering operation has been stopped and any ongoing rendering should be canceled...
void finalize()
Finalizes and cleans up the engine following the rendering of labels for the last layer to be labeled...
void run(QgsRenderContext &context) override
Runs the labeling job.
QgsStagedRenderLabelingEngine()
Construct the labeling engine with default settings.
void renderLabelsForLayer(QgsRenderContext &context, const QString &layerId)
Renders all the labels which belong only to the layer with matching layerId to the specified render c...
@ RenderMillimeters
Millimeters.
Definition: qgsunittypes.h:169
QgsLabelFeature * feature()
Returns the parent feature.
Definition: feature.h:94
LabelPosition is a candidate feature label position.
Definition: labelposition.h:56
FeaturePart * getFeaturePart() const
Returns the feature corresponding to this labelposition.
A set of features which influence the labeling process.
Definition: layer.h:62
void setUpsidedownLabels(UpsideDownLabels ud)
Sets how upside down labels will be handled within the layer.
Definition: layer.h:272
bool registerFeature(QgsLabelFeature *label)
Register a feature in the layer.
Definition: layer.cpp:84
void setObstacleType(QgsLabelObstacleSettings::ObstacleType obstacleType)
Sets the obstacle type, which controls how features within the layer act as obstacles for labels.
Definition: layer.h:237
void setMergeConnectedLines(bool merge)
Sets whether connected lines should be merged before labeling.
Definition: layer.h:259
QgsAbstractLabelProvider * provider() const
Returns pointer to the associated provider.
Definition: layer.h:166
UpsideDownLabels
Definition: layer.h:72
@ ShowAll
Definition: layer.h:75
@ Upright
Definition: layer.h:73
@ ShowDefined
Definition: layer.h:74
void setCentroidInside(bool forceInside)
Sets whether labels placed at the centroid of features within the layer are forced to be placed insid...
Definition: layer.h:287
Main Pal labeling class.
Definition: pal.h:80
Layer * addLayer(QgsAbstractLabelProvider *provider, const QString &layerName, QgsPalLayerSettings::Placement arrangement, double defaultPriority, bool active, bool toLabel, bool displayAll=false)
add a new layer
Definition: pal.cpp:78
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