18#include "moc_qgslabelingengine.cpp"
40static bool _palIsCanceled(
void *ctx )
42 return (
reinterpret_cast< QgsRenderContext *
>( ctx ) )->renderingStopped();
56 explicit QgsLabelSorter(
const QStringList &layerRenderingOrderIds )
57 : mLayerRenderingOrderIds( layerRenderingOrderIds )
69 int layer1Pos = mLayerRenderingOrderIds.indexOf( lf1->
provider()->
layerId() );
70 int layer2Pos = mLayerRenderingOrderIds.indexOf( lf2->
provider()->
layerId() );
71 if ( layer1Pos != layer2Pos && layer1Pos >= 0 && layer2Pos >= 0 )
72 return layer1Pos > layer2Pos;
75 return lf1->
size().width() * lf1->
size().height() > lf2->
size().width() * lf2->
size().height();
80 const QStringList mLayerRenderingOrderIds;
113 if ( !rule->active() || !rule->isAvailable() )
116 std::unique_ptr< QgsAbstractLabelingEngineRule > ruleClone( rule->clone() );
117 res = ruleClone->prepare( context ) && res;
125 QList< QgsMapLayer * > layers;
128 QList< QgsAbstractLabelProvider * > providersByZ =
mProviders;
129 std::sort( providersByZ.begin(), providersByZ.end(),
132 const QgsVectorLayerLabelProvider *providerA = dynamic_cast<const QgsVectorLayerLabelProvider *>( a );
133 const QgsVectorLayerLabelProvider *providerB = dynamic_cast<const QgsVectorLayerLabelProvider *>( b );
135 if ( providerA && providerB )
137 return providerA->settings().zIndex < providerB->settings().zIndex ;
142 QList< QgsAbstractLabelProvider * > subProvidersByZ = mSubProviders;
143 std::sort( subProvidersByZ.begin(), subProvidersByZ.end(),
146 const QgsVectorLayerLabelProvider *providerA = dynamic_cast<const QgsVectorLayerLabelProvider *>( a );
147 const QgsVectorLayerLabelProvider *providerB = dynamic_cast<const QgsVectorLayerLabelProvider *>( b );
149 if ( providerA && providerB )
151 return providerA->settings().zIndex < providerB->settings().zIndex ;
158 if ( provider->layer() && !layers.contains( provider->layer() ) )
159 layers << provider->layer();
163 if ( provider->layer() && !layers.contains( provider->layer() ) )
164 layers << provider->layer();
174 QList< QgsAbstractLabelProvider * > providersByZ =
mProviders;
175 std::sort( providersByZ.begin(), providersByZ.end(),
178 const QgsVectorLayerLabelProvider *providerA = dynamic_cast<const QgsVectorLayerLabelProvider *>( a );
179 const QgsVectorLayerLabelProvider *providerB = dynamic_cast<const QgsVectorLayerLabelProvider *>( b );
181 if ( providerA && providerB )
183 return providerA->settings().zIndex < providerB->settings().zIndex ;
188 QList< QgsAbstractLabelProvider * > subProvidersByZ = mSubProviders;
189 std::sort( subProvidersByZ.begin(), subProvidersByZ.end(),
192 const QgsVectorLayerLabelProvider *providerA = dynamic_cast<const QgsVectorLayerLabelProvider *>( a );
193 const QgsVectorLayerLabelProvider *providerB = dynamic_cast<const QgsVectorLayerLabelProvider *>( b );
195 if ( providerA && providerB )
197 return providerA->settings().zIndex < providerB->settings().zIndex ;
204 if ( !layers.contains( provider->layerId() ) )
205 layers << provider->layerId();
209 if ( !layers.contains( provider->layerId() ) )
210 layers << provider->layerId();
219 const QString
id = QUuid::createUuid().toString( QUuid::WithoutBraces );
263 const QList<QgsLabelFeature *> features = provider->
labelFeatures( context );
271 catch ( std::exception &e )
274 QgsDebugMsgLevel( QStringLiteral(
"Ignoring feature %1 due PAL exception:" ).arg( feature->id() ) + QString::fromLatin1( e.what() ), 4 );
290 std::unique_ptr< QgsScopedRuntimeProfile > registeringProfile;
293 registeringProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr(
"Registering labels" ), QStringLiteral(
"rendering" ) );
299 feedback->emit labelRegistrationAboutToBegin();
303 mPal = std::make_unique< pal::Pal >();
311 QList< QgsAbstractLabelingEngineRule * > rules;
312 rules.reserve(
static_cast< int >(
mEngineRules.size() ) );
315 rules.append( it.get() );
317 mPal->setRules( rules );
326 feedback->emit providerRegistrationAboutToBegin( provider );
330 std::unique_ptr< QgsExpressionContextScopePopper > layerScopePopper;
331 if ( provider->layerExpressionContextScope() )
337 feedback->emit providerRegistrationFinished( provider );
340 feedback->emit labelRegistrationFinished();
345 Q_ASSERT(
mPal.get() );
350 QPainter *painter = context.
painter();
357 visiblePoly.append( visiblePoly.at( 0 ) );
366 mapBoundaryGeom = mapBoundaryGeom.
difference( region.geometry );
374 QVariantMap properties;
375 properties.insert( QStringLiteral(
"style" ), QStringLiteral(
"no" ) );
376 properties.insert( QStringLiteral(
"style_border" ), QStringLiteral(
"solid" ) );
377 properties.insert( QStringLiteral(
"color_border" ), QStringLiteral(
"#0000ff" ) );
378 properties.insert( QStringLiteral(
"width_border" ), QStringLiteral(
"0.3" ) );
379 properties.insert( QStringLiteral(
"joinstyle" ), QStringLiteral(
"miter" ) );
381 boundarySymbol->startRender( context );
382 boundarySymbol->renderFeature( f, context );
383 boundarySymbol->stopRender( context );
396 mPal->registerCancellationCallback( &_palIsCanceled,
reinterpret_cast< void *
>( &context ) );
404 mProblem =
mPal->extractProblem( extent, mapBoundaryGeom, context );
406 catch ( std::exception &e )
409 QgsDebugMsgLevel(
"PAL EXCEPTION :-( " + QString::fromLatin1( e.what() ), 4 );
435 painter->setBrush( Qt::NoBrush );
436 for (
int i = 0; i < static_cast< int >(
mProblem->featureCount() ); i++ )
438 for (
int j = 0; j <
mProblem->featureCandidateCount( i ); j++ )
454 std::sort(
mLabels.begin(),
mLabels.end(), QgsLabelSorter( mLayerRenderingOrderIds ) );
456 QgsDebugMsgLevel( QStringLiteral(
"LABELING work: %1 ms ... labels# %2" ).arg( t.elapsed() ).arg(
mLabels.size() ), 4 );
464 std::unique_ptr< QgsScopedRuntimeProfile > drawingProfile;
467 drawingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr(
"Rendering labels" ), QStringLiteral(
"rendering" ) );
473 QPainter *painter = context.
painter();
478 if ( !layerId.isEmpty() && provider->layerId() != layerId )
486 provider->startRender( context );
490 std::unique_ptr< QgsExpressionContextScopePopper > symbolScopePopper = std::make_unique< QgsExpressionContextScopePopper >( context.
expressionContext(), symbolScope );
577 symbolScopePopper.reset();
582 if ( !layerId.isEmpty() && provider->layerId() != layerId )
585 provider->stopRender( context );
589 painter->setCompositionMode( QPainter::CompositionMode_SourceOver );
591 QgsDebugMsgLevel( QStringLiteral(
"LABELING draw: %1 ms" ).arg( t.elapsed() ), 4 );
687 : mLayerId( layer ? layer->id() : QString() )
689 , mProviderId( providerId )
693 mLayerExpressionContextScope.reset( vl->createExpressionContextScope() );
695 mLayerReferenceScale = renderer->referenceScale();
714 subProvider->startRender( context );
723 subProvider->stopRender( context );
729 return mLayerExpressionContextScope.get();
738 QStringList predefinedOrderString;
739 const auto constPositions = positions;
745 predefinedOrderString << QStringLiteral(
"TL" );
748 predefinedOrderString << QStringLiteral(
"TSL" );
751 predefinedOrderString << QStringLiteral(
"T" );
754 predefinedOrderString << QStringLiteral(
"TSR" );
757 predefinedOrderString << QStringLiteral(
"TR" );
760 predefinedOrderString << QStringLiteral(
"L" );
763 predefinedOrderString << QStringLiteral(
"R" );
766 predefinedOrderString << QStringLiteral(
"BL" );
769 predefinedOrderString << QStringLiteral(
"BSL" );
772 predefinedOrderString << QStringLiteral(
"B" );
775 predefinedOrderString << QStringLiteral(
"BSR" );
778 predefinedOrderString << QStringLiteral(
"BR" );
781 predefinedOrderString << QStringLiteral(
"O" );
785 return predefinedOrderString.join(
',' );
790 QVector<Qgis::LabelPredefinedPointPosition> result;
791 const QStringList predefinedOrderList = positionString.split(
',' );
792 result.reserve( predefinedOrderList.size() );
793 for (
const QString &position : predefinedOrderList )
795 QString cleaned = position.trimmed().toUpper();
796 if ( cleaned == QLatin1String(
"TL" ) )
798 else if ( cleaned == QLatin1String(
"TSL" ) )
800 else if ( cleaned == QLatin1String(
"T" ) )
802 else if ( cleaned == QLatin1String(
"TSR" ) )
804 else if ( cleaned == QLatin1String(
"TR" ) )
806 else if ( cleaned == QLatin1String(
"L" ) )
808 else if ( cleaned == QLatin1String(
"R" ) )
810 else if ( cleaned == QLatin1String(
"BL" ) )
812 else if ( cleaned == QLatin1String(
"BSL" ) )
814 else if ( cleaned == QLatin1String(
"B" ) )
816 else if ( cleaned == QLatin1String(
"BSR" ) )
818 else if ( cleaned == QLatin1String(
"BR" ) )
820 else if ( cleaned == QLatin1String(
"O" ) )
830 parts << QStringLiteral(
"OL" );
832 parts << QStringLiteral(
"AL" );
834 parts << QStringLiteral(
"BL" );
836 parts << QStringLiteral(
"LO" );
837 return parts.join(
',' );
843 const QStringList flagList =
string.split(
',' );
844 bool foundLineOrientationFlag =
false;
845 for (
const QString &flag : flagList )
847 QString cleaned = flag.trimmed().toUpper();
848 if ( cleaned == QLatin1String(
"OL" ) )
850 else if ( cleaned == QLatin1String(
"AL" ) )
852 else if ( cleaned == QLatin1String(
"BL" ) )
854 else if ( cleaned == QLatin1String(
"LO" ) )
855 foundLineOrientationFlag =
true;
857 if ( !foundLineOrientationFlag )
@ BelowLine
Labels can be placed below a line feature. Unless MapOrientation is also specified this mode respects...
@ MapOrientation
Signifies that the AboveLine and BelowLine flags should respect the map's orientation rather than the...
@ OnLine
Labels can be placed directly over a line feature.
@ AboveLine
Labels can be placed above a line feature. Unless MapOrientation is also specified this mode respects...
QFlags< LabelLinePlacementFlag > LabelLinePlacementFlags
Line placement flags, which control how candidates are generated for a linear feature.
@ DrawCandidates
Whether to draw rectangles of generated candidates (good for debugging)
@ 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.
@ 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.
@ Millimeters
Millimeters.
@ RecordProfile
Enable run-time profiling while rendering.
LabelPredefinedPointPosition
Positions for labels when using the Qgis::LabelPlacement::OrderedPositionsAroundPoint placement mode.
@ OverPoint
Label directly centered over point.
@ MiddleLeft
Label on left of point.
@ TopRight
Label on top-right of point.
@ MiddleRight
Label on right of point.
@ TopSlightlyRight
Label on top of point, slightly right of center.
@ TopMiddle
Label directly above point.
@ BottomSlightlyLeft
Label below point, slightly left of center.
@ BottomRight
Label on bottom right of point.
@ BottomLeft
Label on bottom-left of point.
@ BottomSlightlyRight
Label below point, slightly right of center.
@ TopLeft
Label on top-left of point.
@ BottomMiddle
Label directly below point.
@ TopSlightlyLeft
Label on top of point, slightly left of center.
The QgsAbstractLabelProvider class is an interface class.
QgsExpressionContextScope * layerExpressionContextScope() const
Returns the expression context scope created from the layer associated with this provider.
virtual QList< QgsLabelFeature * > labelFeatures(QgsRenderContext &context)=0
Returns list of label features (they are owned by the provider and thus deleted on its destruction)
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.
virtual QList< QgsAbstractLabelProvider * > subProviders()
Returns list of child providers - useful if the provider needs to put labels into more layers with di...
Qgis::LabelPlacement placement() const
What placement strategy to use for the labels.
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.
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.
double layerReferenceScale() const
Returns the symbology reference scale of the layer associated with this provider.
QgsMapLayer * layer() const
Returns the associated layer, or nullptr if no layer is associated with the provider.
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.
@ 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.
QString layerId() const
Returns ID of associated layer, or empty string if no layer is associated with the provider.
Qgis::UpsideDownLabelHandling upsidedownLabels() const
How to handle labels that would be upside down.
QgsAbstractLabelProvider(QgsMapLayer *layer, const QString &providerId=QString())
Construct the provider with default values.
Abstract base class for labeling engine rules.
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.
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.
Abstract base class for all 2D vector feature renderers.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
void setProgress(double progress)
Sets the current progress for the feedback object.
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.
static QgsGeometry fromRect(const QgsRectangle &rect)
Creates a new geometry from a QgsRectangle.
QgsGeometry difference(const QgsGeometry &geometry, const QgsGeometryParameters ¶meters=QgsGeometryParameters()) const
Returns a geometry representing the points making up this geometry that do not make up other.
static QgsGeometry fromQPolygonF(const QPolygonF &polygon)
Construct geometry from a QPolygonF.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
Qgis::GeometryOperationResult rotate(double rotation, const QgsPointXY ¢er)
Rotate this geometry around the Z axis.
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.
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.
const QgsSymbol * symbol() const
Returns the feature symbol associated with this label.
QgsFeedback subclass for granular reporting of labeling engine progress.
Stores global configuration for labeling engine.
Qgis::LabelPlacementEngineVersion placementVersion() const
Returns the placement engine version, which dictates how the label placement problem is solved.
bool testFlag(Qgis::LabelingFlag f) const
Test whether a particular flag is enabled.
Qgis::LabelingFlags flags() const
Gets flags of the labeling engine.
QList< QgsAbstractLabelingEngineRule * > rules()
Returns a list of labeling engine rules which must be satifisfied while placing labels.
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.
bool prepare(QgsRenderContext &context)
Prepares the engine for rendering in the specified context.
void solve(QgsRenderContext &context)
Solves the label problem.
QList< pal::LabelPosition * > mUnlabeled
std::vector< std::unique_ptr< QgsAbstractLabelingEngineRule > > mEngineRules
std::unique_ptr< pal::Problem > mProblem
QString addProvider(QgsAbstractLabelProvider *provider)
Adds a provider of label features.
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
List of labeling engine rules (owned by the labeling engine)
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)
QgsAbstractLabelProvider * providerById(const QString &id)
Returns the provider with matching id, where id corresponds to the value returned by the addProvider(...
QgsLabelingEngine()
Construct the labeling engine with default settings.
QHash< QString, QgsAbstractLabelProvider * > mProvidersById
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 QString encodePredefinedPositionOrder(const QVector< Qgis::LabelPredefinedPointPosition > &positions)
Encodes an ordered list of predefined point label positions to a string.
static QVector< Qgis::LabelPredefinedPointPosition > decodePredefinedPositionOrder(const QString &positionString)
Decodes a string to an ordered list of predefined point label positions.
static Qgis::LabelLinePlacementFlags decodeLinePlacementFlags(const QString &string)
Decodes a string to set of line placement flags.
static QString encodeLinePlacementFlags(Qgis::LabelLinePlacementFlags flags)
Encodes line placement flags to a string.
Base class for all map layer types.
The QgsMapSettings class contains configuration for rendering of the map.
const QgsLabelingEngineSettings & labelingEngineSettings() const
Returns the global configuration of the labeling engine.
QgsGeometry labelBoundaryGeometry() const
Returns the label boundary geometry, which restricts where in the rendered map labels are permitted t...
QStringList layerIds(bool expandGroupLayers=false) const
Returns the list of layer IDs which will be rendered in the map.
const QgsMapToPixel & mapToPixel() const
QList< QgsLabelBlockingRegion > labelBlockingRegions() const
Returns the list of regions to avoid placing labels within.
double extentBuffer() const
Returns the buffer in map units to use around the visible extent for rendering symbols whose correspo...
QgsRectangle visibleExtent() const
Returns the actual extent derived from requested extent that takes output image size into account.
double rotation() const
Returns the rotation of the resulting map image, in degrees clockwise.
QPolygonF visiblePolygonWithBuffer() const
Returns the visible area as a polygon (may be rotated) with extent buffer included.
Perform transforms between map coordinates and device coordinates.
void setMapRotation(double degrees, double cx, double cy)
Sets map rotation in degrees (clockwise).
static void drawLabelCandidateRect(pal::LabelPosition *lp, QPainter *painter, const QgsMapToPixel *xform, QList< QgsLabelCandidate > *candidates=nullptr)
A rectangle specified with double values.
void grow(double delta)
Grows the rectangle in place by the specified amount.
Contains information about the context of a rendering operation.
double convertToMapUnits(double size, Qgis::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale()) const
Converts a size from the specified units to map units.
QPainter * painter()
Returns the destination QPainter for the render operation.
void setPainterFlagsUsingContext(QPainter *painter=nullptr) const
Sets relevant flags on a destination painter, using the flags and settings currently defined for the ...
QgsExpressionContext & expressionContext()
Gets the expression context.
QgsFeedback * feedback() const
Returns the feedback object that can be queried regularly during rendering to check if rendering shou...
bool renderingStopped() const
Returns true if the rendering operation has been stopped and any ongoing rendering should be canceled...
Qgis::RenderContextFlags flags() const
Returns combination of flags used for rendering.
Scoped object for temporary override of the symbologyReferenceScale property of a QgsRenderContext.
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...
Represents a vector layer which manages a vector based data sets.
QgsLabelFeature * feature()
Returns the parent feature.
LabelPosition is a candidate feature label position.
FeaturePart * getFeaturePart() const
Returns the feature corresponding to this labelposition.
A set of features which influence the labeling process.
void setUpsidedownLabels(Qgis::UpsideDownLabelHandling ud)
Sets how upside down labels will be handled within the layer.
bool registerFeature(QgsLabelFeature *label)
Register a feature in the layer.
QgsAbstractLabelProvider * provider() const
Returns pointer to the associated provider.
void setObstacleType(QgsLabelObstacleSettings::ObstacleType obstacleType)
Sets the obstacle type, which controls how features within the layer act as obstacles for labels.
void setMergeConnectedLines(bool merge)
Sets whether connected lines should be merged before labeling.
void setCentroidInside(bool forceInside)
Sets whether labels placed at the centroid of features within the layer are forced to be placed insid...
Layer * addLayer(QgsAbstractLabelProvider *provider, const QString &layerName, Qgis::LabelPlacement arrangement, double defaultPriority, bool active, bool toLabel)
add a new layer
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
#define QgsDebugMsgLevel(str, level)