QGIS API Documentation  3.10.0-A Coruña (6c816b4204)
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 
32 // helper function for checking for job cancellation within PAL
33 static bool _palIsCanceled( void *ctx )
34 {
35  return ( reinterpret_cast< QgsRenderContext * >( ctx ) )->renderingStopped();
36 }
37 
44 {
45  public:
46 
47  explicit QgsLabelSorter( const QgsMapSettings &mapSettings )
48  : mMapSettings( mapSettings )
49  {}
50 
52  {
53  QgsLabelFeature *lf1 = lp1->getFeaturePart()->feature();
54  QgsLabelFeature *lf2 = lp2->getFeaturePart()->feature();
55 
56  if ( !qgsDoubleNear( lf1->zIndex(), lf2->zIndex() ) )
57  return lf1->zIndex() < lf2->zIndex();
58 
59  //equal z-index, so fallback to respecting layer render order
60  QStringList layerIds = mMapSettings.layerIds();
61  int layer1Pos = layerIds.indexOf( lf1->provider()->layerId() );
62  int layer2Pos = layerIds.indexOf( lf2->provider()->layerId() );
63  if ( layer1Pos != layer2Pos && layer1Pos >= 0 && layer2Pos >= 0 )
64  return layer1Pos > layer2Pos; //higher positions are rendered first
65 
66  //same layer, so render larger labels first
67  return lf1->size().width() * lf1->size().height() > lf2->size().width() * lf2->size().height();
68  }
69 
70  private:
71 
72  const QgsMapSettings &mMapSettings;
73 };
74 
75 //
76 // QgsLabelingEngine
77 //
78 
80  : mResults( new QgsLabelingResults )
81 {}
82 
84 {
85  qDeleteAll( mProviders );
86  qDeleteAll( mSubProviders );
87 }
88 
90 {
92  if ( mResults )
93  mResults->setMapSettings( mapSettings );
94 }
95 
96 QList< QgsMapLayer * > QgsLabelingEngine::participatingLayers() const
97 {
98  QList< QgsMapLayer * > layers;
99 
100  // try to return layers sorted in the desired z order for rendering
101  QList< QgsAbstractLabelProvider * > providersByZ = mProviders;
102  std::sort( providersByZ.begin(), providersByZ.end(),
103  []( const QgsAbstractLabelProvider * a, const QgsAbstractLabelProvider * b ) -> bool
104  {
105  const QgsVectorLayerLabelProvider *providerA = dynamic_cast<const QgsVectorLayerLabelProvider *>( a );
106  const QgsVectorLayerLabelProvider *providerB = dynamic_cast<const QgsVectorLayerLabelProvider *>( b );
107 
108  if ( providerA && providerB )
109  {
110  return providerA->settings().zIndex < providerB->settings().zIndex ;
111  }
112  return false;
113  } );
114 
115  QList< QgsAbstractLabelProvider * > subProvidersByZ = mSubProviders;
116  std::sort( subProvidersByZ.begin(), subProvidersByZ.end(),
117  []( const QgsAbstractLabelProvider * a, const QgsAbstractLabelProvider * b ) -> bool
118  {
119  const QgsVectorLayerLabelProvider *providerA = dynamic_cast<const QgsVectorLayerLabelProvider *>( a );
120  const QgsVectorLayerLabelProvider *providerB = dynamic_cast<const QgsVectorLayerLabelProvider *>( b );
121 
122  if ( providerA && providerB )
123  {
124  return providerA->settings().zIndex < providerB->settings().zIndex ;
125  }
126  return false;
127  } );
128 
129  for ( QgsAbstractLabelProvider *provider : qgis::as_const( providersByZ ) )
130  {
131  if ( provider->layer() && !layers.contains( provider->layer() ) )
132  layers << provider->layer();
133  }
134  for ( QgsAbstractLabelProvider *provider : qgis::as_const( subProvidersByZ ) )
135  {
136  if ( provider->layer() && !layers.contains( provider->layer() ) )
137  layers << provider->layer();
138  }
139  return layers;
140 }
141 
143 {
144  QStringList layers;
145 
146  // try to return layers sorted in the desired z order for rendering
147  QList< QgsAbstractLabelProvider * > providersByZ = mProviders;
148  std::sort( providersByZ.begin(), providersByZ.end(),
149  []( const QgsAbstractLabelProvider * a, const QgsAbstractLabelProvider * b ) -> bool
150  {
151  const QgsVectorLayerLabelProvider *providerA = dynamic_cast<const QgsVectorLayerLabelProvider *>( a );
152  const QgsVectorLayerLabelProvider *providerB = dynamic_cast<const QgsVectorLayerLabelProvider *>( b );
153 
154  if ( providerA && providerB )
155  {
156  return providerA->settings().zIndex < providerB->settings().zIndex ;
157  }
158  return false;
159  } );
160 
161  QList< QgsAbstractLabelProvider * > subProvidersByZ = mSubProviders;
162  std::sort( subProvidersByZ.begin(), subProvidersByZ.end(),
163  []( const QgsAbstractLabelProvider * a, const QgsAbstractLabelProvider * b ) -> bool
164  {
165  const QgsVectorLayerLabelProvider *providerA = dynamic_cast<const QgsVectorLayerLabelProvider *>( a );
166  const QgsVectorLayerLabelProvider *providerB = dynamic_cast<const QgsVectorLayerLabelProvider *>( b );
167 
168  if ( providerA && providerB )
169  {
170  return providerA->settings().zIndex < providerB->settings().zIndex ;
171  }
172  return false;
173  } );
174 
175  for ( QgsAbstractLabelProvider *provider : qgis::as_const( providersByZ ) )
176  {
177  if ( !layers.contains( provider->layerId() ) )
178  layers << provider->layerId();
179  }
180  for ( QgsAbstractLabelProvider *provider : qgis::as_const( subProvidersByZ ) )
181  {
182  if ( !layers.contains( provider->layerId() ) )
183  layers << provider->layerId();
184  }
185  return layers;
186 }
187 
189 {
190  provider->setEngine( this );
191  mProviders << provider;
192 }
193 
195 {
196  int idx = mProviders.indexOf( provider );
197  if ( idx >= 0 )
198  {
199  delete mProviders.takeAt( idx );
200  }
201 }
202 
204 {
205  QgsAbstractLabelProvider::Flags flags = provider->flags();
206 
207  // create the pal layer
208  pal::Layer *l = p.addLayer( provider,
209  provider->name(),
210  provider->placement(),
211  provider->priority(),
212  true,
213  flags.testFlag( QgsAbstractLabelProvider::DrawLabels ),
214  flags.testFlag( QgsAbstractLabelProvider::DrawAllLabels ) );
215 
216  // set whether adjacent lines should be merged
218 
219  // set obstacle type
220  l->setObstacleType( provider->obstacleType() );
221 
222  // set whether location of centroid must be inside of polygons
224 
225  // set how to show upside-down labels
227  switch ( provider->upsidedownLabels() )
228  {
230  upsdnlabels = pal::Layer::Upright;
231  break;
233  upsdnlabels = pal::Layer::ShowDefined;
234  break;
236  upsdnlabels = pal::Layer::ShowAll;
237  break;
238  }
239  l->setUpsidedownLabels( upsdnlabels );
240 
241 
242  const QList<QgsLabelFeature *> features = provider->labelFeatures( context );
243 
244  for ( QgsLabelFeature *feature : features )
245  {
246  try
247  {
248  l->registerFeature( feature );
249  }
250  catch ( std::exception &e )
251  {
252  Q_UNUSED( e )
253  QgsDebugMsgLevel( QStringLiteral( "Ignoring feature %1 due PAL exception:" ).arg( feature->id() ) + QString::fromLatin1( e.what() ), 4 );
254  continue;
255  }
256  }
257 
258  // any sub-providers?
259  const auto subproviders = provider->subProviders();
260  for ( QgsAbstractLabelProvider *subProvider : subproviders )
261  {
262  mSubProviders << subProvider;
263  processProvider( subProvider, context, p );
264  }
265 }
266 
268 {
270 
271  mPal = qgis::make_unique< pal::Pal >();
272 
273  // set number of candidates generated per feature
274  int candPoint, candLine, candPolygon;
275  settings.numCandidatePositions( candPoint, candLine, candPolygon );
276  mPal->setPointP( candPoint );
277  mPal->setLineP( candLine );
278  mPal->setPolyP( candPolygon );
279 
280  mPal->setShowPartial( settings.testFlag( QgsLabelingEngineSettings::UsePartialCandidates ) );
281 
282 
283  // for each provider: get labels and register them in PAL
284  for ( QgsAbstractLabelProvider *provider : qgis::as_const( mProviders ) )
285  {
286  std::unique_ptr< QgsExpressionContextScopePopper > layerScopePopper;
287  if ( QgsMapLayer *ml = provider->layer() )
288  {
289  layerScopePopper = qgis::make_unique< QgsExpressionContextScopePopper >( context.expressionContext(), QgsExpressionContextUtils::layerScope( ml ) );
290  }
291  processProvider( provider, context, *mPal );
292  }
293 }
294 
296 {
297  Q_ASSERT( mPal.get() );
298 
299  // NOW DO THE LAYOUT (from QgsPalLabeling::drawLabeling)
301 
302  QPainter *painter = context.painter();
303 
305  QPolygonF visiblePoly = mMapSettings.visiblePolygon();
306  visiblePoly.append( visiblePoly.at( 0 ) ); //close polygon
307 
308  // get map label boundary geometry - if one hasn't been explicitly set, we use the whole of the map's visible polygon
310 
311  // label blocking regions work by "chopping away" those regions from the permissible labeling area
312  const QList< QgsLabelBlockingRegion > blockingRegions = mMapSettings.labelBlockingRegions();
313  for ( const QgsLabelBlockingRegion &region : blockingRegions )
314  {
315  mapBoundaryGeom = mapBoundaryGeom.difference( region.geometry );
316  }
317 
318  if ( settings.flags() & QgsLabelingEngineSettings::DrawCandidates )
319  {
320  // draw map boundary
321  QgsFeature f;
322  f.setGeometry( mapBoundaryGeom );
323  QgsStringMap properties;
324  properties.insert( QStringLiteral( "style" ), QStringLiteral( "no" ) );
325  properties.insert( QStringLiteral( "style_border" ), QStringLiteral( "solid" ) );
326  properties.insert( QStringLiteral( "color_border" ), QStringLiteral( "#0000ff" ) );
327  properties.insert( QStringLiteral( "width_border" ), QStringLiteral( "0.3" ) );
328  properties.insert( QStringLiteral( "joinstyle" ), QStringLiteral( "miter" ) );
329  std::unique_ptr< QgsFillSymbol > boundarySymbol( QgsFillSymbol::createSimple( properties ) );
330  boundarySymbol->startRender( context );
331  boundarySymbol->renderFeature( f, context );
332  boundarySymbol->stopRender( context );
333  }
334 
335  if ( !qgsDoubleNear( mMapSettings.rotation(), 0.0 ) )
336  {
337  //PAL features are prerotated, so extent also needs to be unrotated
339  // yes - this is rotated in the opposite direction... phew, this is confusing!
340  mapBoundaryGeom.rotate( mMapSettings.rotation(), mMapSettings.visibleExtent().center() );
341  }
342 
343  QgsRectangle extent = extentGeom.boundingBox();
344 
345  mPal->registerCancellationCallback( &_palIsCanceled, reinterpret_cast< void * >( &context ) );
346 
347  QTime t;
348  t.start();
349 
350  // do the labeling itself
351  try
352  {
353  mProblem = mPal->extractProblem( extent, mapBoundaryGeom );
354  }
355  catch ( std::exception &e )
356  {
357  Q_UNUSED( e )
358  QgsDebugMsgLevel( "PAL EXCEPTION :-( " + QString::fromLatin1( e.what() ), 4 );
359  return;
360  }
361 
362  if ( context.renderingStopped() )
363  {
364  return; // it has been canceled
365  }
366 
367 #if 1 // XXX strk
368  // features are pre-rotated but not scaled/translated,
369  // so we only disable rotation here. Ideally, they'd be
370  // also pre-scaled/translated, as suggested here:
371  // https://github.com/qgis/QGIS/issues/20071
373  xform.setMapRotation( 0, 0, 0 );
374 #else
375  const QgsMapToPixel &xform = mMapSettings->mapToPixel();
376 #endif
377 
378  // draw rectangles with all candidates
379  // this is done before actual solution of the problem
380  // before number of candidates gets reduced
381  // TODO mCandidates.clear();
382  if ( settings.testFlag( QgsLabelingEngineSettings::DrawCandidates ) && mProblem )
383  {
384  painter->setBrush( Qt::NoBrush );
385  for ( int i = 0; i < mProblem->getNumFeatures(); i++ )
386  {
387  for ( int j = 0; j < mProblem->getFeatureCandidateCount( i ); j++ )
388  {
389  pal::LabelPosition *lp = mProblem->getFeatureCandidate( i, j );
390 
391  QgsPalLabeling::drawLabelCandidateRect( lp, painter, &xform );
392  }
393  }
394  }
395 
396  // find the solution
397  mLabels = mPal->solveProblem( mProblem.get(), settings.testFlag( QgsLabelingEngineSettings::UseAllLabels ), settings.testFlag( QgsLabelingEngineSettings::DrawUnplacedLabels ) ? &mUnlabeled : nullptr );
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  QTime t;
408  t.start();
409 
411  QPainter *painter = context.painter();
412  painter->setRenderHint( QPainter::Antialiasing );
413 
414  // prepare for rendering
415  for ( QgsAbstractLabelProvider *provider : qgis::as_const( mProviders ) )
416  {
417  if ( !layerId.isEmpty() && provider->layerId() != layerId )
418  continue;
419 
420  // provider will require the correct layer scope for expression preparation - at this stage, the existing expression context
421  // only contains generic scopes
423  provider->startRender( context );
424  }
425 
427  std::unique_ptr< QgsExpressionContextScopePopper > symbolScopePopper = qgis::make_unique< QgsExpressionContextScopePopper >( context.expressionContext(), symbolScope );
428 
429  // draw label backgrounds
430  for ( pal::LabelPosition *label : qgis::as_const( mLabels ) )
431  {
432  if ( context.renderingStopped() )
433  break;
434 
435  QgsLabelFeature *lf = label->getFeaturePart()->feature();
436  if ( !lf )
437  {
438  continue;
439  }
440 
441  if ( !layerId.isEmpty() && lf->provider()->layerId() != layerId )
442  continue;
443 
444  context.expressionContext().setFeature( lf->feature() );
445  context.expressionContext().setFields( lf->feature().fields() );
446  if ( lf->symbol() )
447  {
448  symbolScope = QgsExpressionContextUtils::updateSymbolScope( lf->symbol(), symbolScope );
449  }
450  lf->provider()->drawLabelBackground( context, label );
451  }
452 
453  // draw the labels
454  for ( pal::LabelPosition *label : qgis::as_const( mLabels ) )
455  {
456  if ( context.renderingStopped() )
457  break;
458 
459  QgsLabelFeature *lf = label->getFeaturePart()->feature();
460  if ( !lf )
461  {
462  continue;
463  }
464 
465  if ( !layerId.isEmpty() && lf->provider()->layerId() != layerId )
466  continue;
467 
468  context.expressionContext().setFeature( lf->feature() );
469  context.expressionContext().setFields( lf->feature().fields() );
470  if ( lf->symbol() )
471  {
472  symbolScope = QgsExpressionContextUtils::updateSymbolScope( lf->symbol(), symbolScope );
473  }
474  lf->provider()->drawLabel( context, label );
475  // finished with symbol -- we can't keep it around after this, it may be deleted
476  lf->setSymbol( nullptr );
477  }
478 
479  // draw unplaced labels. These are always rendered on top
481  {
482  for ( pal::LabelPosition *label : qgis::as_const( mUnlabeled ) )
483  {
484  if ( context.renderingStopped() )
485  break;
486  QgsLabelFeature *lf = label->getFeaturePart()->feature();
487  if ( !lf )
488  {
489  continue;
490  }
491 
492  if ( !layerId.isEmpty() && lf->provider()->layerId() != layerId )
493  continue;
494 
495  context.expressionContext().setFeature( lf->feature() );
496  context.expressionContext().setFields( lf->feature().fields() );
497  if ( lf->symbol() )
498  {
499  symbolScope = QgsExpressionContextUtils::updateSymbolScope( lf->symbol(), symbolScope );
500  }
501  lf->provider()->drawUnplacedLabel( context, label );
502  // finished with symbol -- we can't keep it around after this, it may be deleted
503  lf->setSymbol( nullptr );
504  }
505  }
506 
507  symbolScopePopper.reset();
508 
509  // cleanup
510  for ( QgsAbstractLabelProvider *provider : qgis::as_const( mProviders ) )
511  {
512  if ( !layerId.isEmpty() && provider->layerId() != layerId )
513  continue;
514 
515  provider->stopRender( context );
516  }
517 
518  // Reset composition mode for further drawing operations
519  painter->setCompositionMode( QPainter::CompositionMode_SourceOver );
520 
521  QgsDebugMsgLevel( QStringLiteral( "LABELING draw: %1 ms" ).arg( t.elapsed() ), 4 );
522 }
523 
525 {
526  mUnlabeled.clear();
527  mLabels.clear();
528  mProblem.reset();
529  mPal.reset();
530 }
531 
533 {
534  return mResults.release();
535 }
536 
537 
538 //
539 // QgsDefaultLabelingEngine
540 //
541 
544 {
545 
546 }
547 
549 {
550  registerLabels( context );
551  if ( context.renderingStopped() )
552  {
553  cleanup();
554  return; // it has been canceled
555  }
556 
557  solve( context );
558  if ( context.renderingStopped() )
559  {
560  cleanup();
561  return;
562  }
563 
564  drawLabels( context );
565  cleanup();
566 }
567 
568 
569 //
570 // QgsStagedRenderLabelingEngine
571 //
572 
575 {
576 
577 }
578 
580 {
581  registerLabels( context );
582  if ( context.renderingStopped() )
583  {
584  cleanup();
585  return; // it has been canceled
586  }
587 
588  solve( context );
589  if ( context.renderingStopped() )
590  {
591  cleanup();
592  return;
593  }
594 }
595 
596 
598 {
599  drawLabels( context, layerId );
600 }
601 
603 {
604  cleanup();
605 }
606 
607 
609 
611 {
612  return mLayer ? mLayer->provider() : nullptr;
613 
614 }
615 
617  : mLayerId( layer ? layer->id() : QString() )
618  , mLayer( layer )
619  , mProviderId( providerId )
620  , mFlags( DrawLabels )
621  , mPlacement( QgsPalLayerSettings::AroundPoint )
622  , mPriority( 0.5 )
623  , mObstacleType( QgsPalLayerSettings::PolygonInterior )
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( pal::LineArrangementFlags flags )
746 {
747  QStringList parts;
748  if ( flags & pal::FLAG_ON_LINE )
749  parts << QStringLiteral( "OL" );
750  if ( flags & pal::FLAG_ABOVE_LINE )
751  parts << QStringLiteral( "AL" );
752  if ( flags & pal::FLAG_BELOW_LINE )
753  parts << QStringLiteral( "BL" );
754  if ( !( flags & pal::FLAG_MAP_ORIENTATION ) )
755  parts << QStringLiteral( "LO" );
756  return parts.join( ',' );
757 }
758 
759 pal::LineArrangementFlags QgsLabelingUtils::decodeLinePlacementFlags( const QString &string )
760 {
761  pal::LineArrangementFlags flags = nullptr;
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 |= pal::FLAG_ON_LINE;
769  else if ( cleaned == QLatin1String( "AL" ) )
770  flags |= pal::FLAG_ABOVE_LINE;
771  else if ( cleaned == QLatin1String( "BL" ) )
772  flags |= pal::FLAG_BELOW_LINE;
773  else if ( cleaned == QLatin1String( "LO" ) )
774  foundLineOrientationFlag = true;
775  }
776  if ( !foundLineOrientationFlag )
777  flags |= pal::FLAG_MAP_ORIENTATION;
778  return flags;
779 }
780 
Label on bottom right of point.
void setSymbol(const QgsSymbol *symbol)
Sets the feature symbol associated with this label.
void processProvider(QgsAbstractLabelProvider *provider, QgsRenderContext &context, pal::Pal &p)
static QgsExpressionContextScope * updateSymbolScope(const QgsSymbol *symbol, QgsExpressionContextScope *symbolScope=nullptr)
Updates a symbol scope related to a QgsSymbol to an expression context.
QList< pal::LabelPosition * > mLabels
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:81
std::unique_ptr< pal::Pal > mPal
A rectangle specified with double values.
Definition: qgsrectangle.h:41
Base class for all map layer types.
Definition: qgsmaplayer.h:79
Label on bottom-left of point.
Label on top of point, slightly left of center.
virtual void drawLabelBackground(QgsRenderContext &context, pal::LabelPosition *label) const
Draw the background for the specified label.
void setMapRotation(double degrees, double cx, double cy)
Set map rotation in degrees (clockwise)
void addProvider(QgsAbstractLabelProvider *provider)
Add provider of label features. Takes ownership of the provider.
QList< QgsAbstractLabelProvider * > mProviders
List of providers (the are owned by the labeling engine)
void removeProvider(QgsAbstractLabelProvider *provider)
Remove provider if the provider&#39;s initialization failed. Provider instance is deleted.
QgsLabelFeature * feature()
Returns the parent feature.
Definition: feature.h:118
double rotation() const
Returns the rotation of the resulting map image, in degrees clockwise.
QgsDefaultLabelingEngine()
Construct the labeling engine with default settings.
QStringList layerIds() const
Gets list of layer IDs for map rendering The layers are stored in the reverse order of how they are r...
QgsAbstractLabelProvider * provider() const
Returns provider of this instance.
Label on top-left of point.
QgsAbstractLabelProvider(QgsMapLayer *layer, const QString &providerId=QString())
Construct the provider with default values.
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
QStringList participatingLayerIds() const
Returns a list of layer IDs for layers with providers in the engine.
static void drawLabelCandidateRect(pal::LabelPosition *lp, QPainter *painter, const QgsMapToPixel *xform, QList< QgsLabelCandidate > *candidates=nullptr)
A set of features which influence the labeling process.
Definition: layer.h:63
PredefinedPointPosition
Positions for labels when using the QgsPalLabeling::OrderedPositionsAroundPoint placement mode...
void drawLabels(QgsRenderContext &context, const QString &layerId=QString())
Draws labels to the specified render context.
static QgsFillSymbol * createSimple(const QgsStringMap &properties)
Create a fill symbol with one symbol layer: SimpleFill with specified properties. ...
Definition: qgssymbol.cpp:1251
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition: qgis.h:280
OperationResult rotate(double rotation, const QgsPointXY &center)
Rotate this geometry around the Z axis.
const QgsSymbol * symbol()
Returns the feature symbol associated with this label.
QgsPalLayerSettings::ObstacleType obstacleType() const
How the feature geometries will work as obstacles.
Whether to use also label candidates that are partially outside of the map view.
QgsLabelingEngine()
Construct the labeling engine with default settings.
QList< QgsAbstractLabelProvider * > mSubProviders
bool renderingStopped() const
Returns true if the rendering operation has been stopped and any ongoing rendering should be canceled...
Main Pal labeling class.
Definition: pal.h:87
UpsideDownLabels
Definition: layer.h:73
Label on top-right of point.
The QgsVectorLayerLabelProvider class implements a label provider for vector layers.
void setMapSettings(const QgsMapSettings &mapSettings)
Associate map settings instance.
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:122
void setUpsidedownLabels(UpsideDownLabels ud)
Sets how upside down labels will be handled within the layer.
Definition: layer.h:259
QList< pal::LabelPosition * > mUnlabeled
FeaturePart * getFeaturePart()
Returns the feature corresponding to this labelposition.
QgsFeature feature() const
Returns the original feature associated with this label.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:55
virtual QList< QgsLabelFeature * > labelFeatures(QgsRenderContext &context)=0
Returns list of label features (they are owned by the provider and thus deleted on its destruction) ...
QgsFields fields
Definition: qgsfeature.h:66
void setObstacleType(QgsPalLayerSettings::ObstacleType obstacleType)
Sets the obstacle type, which controls how features within the layer act as obstacles for labels...
Definition: layer.h:224
QMap< QString, QString > QgsStringMap
Definition: qgis.h:612
QgsRectangle visibleExtent() const
Returns the actual extent derived from requested extent that takes takes output image size into accou...
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:274
double zIndex
Z-Index of label, where labels with a higher z-index are rendered on top of labels with a lower z-ind...
void finalize()
Finalizes and cleans up the engine following the rendering of labels for the last layer to be labeled...
Whether adjacent lines (with the same label text) should be merged.
The QgsMapSettings class contains configuration for rendering of the map.
Perform transforms between map coordinates and device coordinates.
Definition: qgsmaptopixel.h:37
Whether to draw all labels even if there would be collisions.
static QgsGeometry fromRect(const QgsRectangle &rect)
Creates a new geometry from a QgsRectangle.
QgsGeometry labelBoundaryGeometry() const
Returns the label boundary geometry, which restricts where in the rendered map labels are permitted t...
static pal::LineArrangementFlags decodeLinePlacementFlags(const QString &string)
Decodes a string to set of line placement flags.
double zIndex() const
Returns the label&#39;s z-index.
Label on left of point.
Whether to render unplaced labels as an indicator/warning for users.
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...
QgsStagedRenderLabelingEngine()
Construct the labeling engine with default settings.
#define QgsDebugMsgLevel(str, level)
Definition: qgslogger.h:39
Show upside down for all labels, including dynamic ones.
virtual void drawUnplacedLabel(QgsRenderContext &context, pal::LabelPosition *label) const
Draw an unplaced label.
bool operator()(pal::LabelPosition *lp1, pal::LabelPosition *lp2) const
const QgsPalLayerSettings & settings() const
Returns the layer&#39;s settings.
Whether location of centroid must be inside of polygons.
Upside-down labels (90 <= angle < 270) are shown upright.
QList< QgsMapLayer *> participatingLayers() const
Returns a list of layers with providers in the engine.
Label below point, slightly right of center.
Whether all features will be labelled even though overlaps occur.
Label blocking region (in map coordinates and CRS).
Single scope for storing variables and functions for use within a QgsExpressionContext.
void cleanup()
Cleans up the engine following a call to registerLabels() or solve().
QgsPalLayerSettings::Placement placement() const
What placement strategy to use for the labels.
const QgsMapToPixel & mapToPixel() const
The QgsAbstractLabelProvider class is an interface class.
Whether to draw rectangles of generated candidates (good for debugging)
static QString encodeLinePlacementFlags(pal::LineArrangementFlags flags)
Encodes line placement flags to a string.
void setFields(const QgsFields &fields)
Convenience function for setting a fields for the context.
QString layerId() const
Returns ID of associated layer, or empty string if no layer is associated with the provider...
QgsPalLayerSettings::UpsideDownLabels upsidedownLabels() const
How to handle labels that would be upside down.
void numCandidatePositions(int &candPoint, int &candLine, int &candPolygon) const
Gets number of candidate positions that will be generated for each label feature (default to 8) ...
QgsLabelSorter(const QgsMapSettings &mapSettings)
QgsExpressionContext & expressionContext()
Gets the expression context.
virtual ~QgsLabelingEngine()
Clean up everything (especially the registered providers)
bool registerFeature(QgsLabelFeature *label)
Register a feature in the layer.
Definition: layer.cpp:91
Flags flags() const
Flags associated with the provider.
static QString encodePredefinedPositionOrder(const QVector< QgsPalLayerSettings::PredefinedPointPosition > &positions)
Encodes an ordered list of predefined point label positions to a string.
The QgsLabelingEngine class provides map labeling functionality.
virtual QList< QgsAbstractLabelProvider * > subProviders()
Returns list of child providers - useful if the provider needs to put labels into more layers with di...
Contains information about the context of a rendering operation.
std::unique_ptr< pal::Problem > mProblem
void run(QgsRenderContext &context) override
Runs the labeling job.
QPainter * painter()
Returns the destination QPainter for the render operation.
The QgsLabelFeature class describes a feature that should be used within the labeling engine...
QString name() const
Name of the layer (for statistics, debugging etc.) - does not need to be unique.
std::unique_ptr< QgsLabelingResults > mResults
Resulting labeling layout.
Label below point, slightly left of center.
QgsMapSettings mMapSettings
Associated map settings instance.
QgsLabelingResults * takeResults()
Returns pointer to recently computed results and pass the ownership of results to the caller...
Stores global configuration for labeling engine.
Label on top of point, slightly right of center.
const QgsMapSettings & mapSettings() const
Gets associated map settings.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
Label directly below point.
Helper class for sorting labels into correct draw order.
void setGeometry(const QgsGeometry &geometry)
Set the feature&#39;s geometry.
Definition: qgsfeature.cpp:137
double priority() const
Default priority of labels (may be overridden by individual labels)
QSizeF size(double angle=0.0) const
Size of the label (in map units)
bool testFlag(Flag f) const
Test whether a particular flag is enabled.
static QgsGeometry fromQPolygonF(const QPolygonF &polygon)
Construct geometry from a QPolygonF.
LabelPosition is a candidate feature label position.
Definition: labelposition.h:55
virtual void startRender(QgsRenderContext &context)
To be called before rendering of labels begins.
Label directly above point.
Label on right of point.
Whether the labels should be rendered.
Class that stores computed placement from labeling engine.
QPolygonF visiblePolygon() const
Returns the visible area as a polygon (may be rotated)
static QVector< QgsPalLayerSettings::PredefinedPointPosition > decodePredefinedPositionOrder(const QString &positionString)
Decodes a string to an ordered list of predefined point label positions.
QgsPointXY center() const
Returns the center point of the rectangle.
Definition: qgsrectangle.h:230
static QgsExpressionContextScope * layerScope(const QgsMapLayer *layer)
Creates a new scope which contains variables and functions relating to a QgsMapLayer.
Show upside down when rotation is layer- or data-defined.
virtual void drawLabel(QgsRenderContext &context, pal::LabelPosition *label) const =0
Draw this label at the position determined by the labeling engine.
virtual void stopRender(QgsRenderContext &context)
To be called after rendering is complete.
void solve(QgsRenderContext &context)
Solves the label problem.
QList< QgsLabelBlockingRegion > labelBlockingRegions() const
Returns the list of regions to avoid placing labels within.
RAII class to pop scope from an expression context on destruction.
void registerLabels(QgsRenderContext &context)
Runs the label registration step.
void setEngine(const QgsLabelingEngine *engine)
Associate provider with a labeling engine (should be only called internally from QgsLabelingEngine) ...
void run(QgsRenderContext &context) override
Runs the labeling job.
const QgsLabelingEngineSettings & labelingEngineSettings() const
Returns the global configuration of the labeling engine.
void setMergeConnectedLines(bool merge)
Sets whether connected lines should be merged before labeling.
Definition: layer.h:246
QgsGeometry difference(const QgsGeometry &geometry) const
Returns a geometry representing the points making up this geometry that do not make up other...