43#include <QTextDocument>
44#include <QTextFragment>
56 mName = layerName.isEmpty() ?
layer->id() : layerName;
58 if ( withFeatureLoop )
60 mSource = std::make_unique<QgsVectorLayerFeatureSource>(
layer );
74 mName = layerName.isEmpty() ?
layer->id() : layerName;
86 if (
mSettings.lineSettings().mergeLines() && !
mSettings.lineSettings().addDirectionSymbol() )
141 QSet<QString> attrNames;
142 if ( !
prepare( ctx, attrNames ) )
143 return QList<QgsLabelFeature *>();
176 if ( !symbols.isEmpty() )
178 symbol = symbols.at( 0 );
197 std::unique_ptr< QgsLabelFeature > label =
mSettings.registerFeatureWithDetails( feature, context, obstacleGeometry, symbol );
198 QList< QgsLabelFeature * > res;
213 std::unique_ptr< QgsAbstractGeometry > obstacleGeom;
215 obstacleGeom = std::make_unique< QgsMultiPolygon >();
218 for (
int i = 0; i < fet.
geometry().constGet()->nCoordinates(); ++i )
241 const auto constSymbols = symbols;
246 if ( bounds.isValid() )
247 bounds = bounds.united(
static_cast< QgsMarkerSymbol *
>( symbol )->bounds( pt, context, fet ) );
249 bounds =
static_cast< QgsMarkerSymbol *
>( symbol )->bounds( pt, context, fet );
254 QVector< double > bX;
255 bX << bounds.left() << bounds.right() << bounds.right() << bounds.left();
256 QVector< double > bY;
257 bY << bounds.top() << bounds.top() << bounds.bottom() << bounds.bottom();
258 auto boundLineString = std::make_unique< QgsLineString >( bX, bY );
262 for (
int i = 0; i < boundLineString->numPoints(); ++i )
265 static_cast<int>( boundLineString->yAt( i ) ) );
266 boundLineString->setXAt( i, point.
x() );
267 boundLineString->setYAt( i, point.
y() );
280 boundLineString->close();
285 boundLineString->filterVertices( [](
const QgsPoint & point )->
bool
287 return std::isfinite( point.
x() ) && std::isfinite( point.
y() );
289 if ( !boundLineString->isRing() )
293 auto obstaclePolygon = std::make_unique< QgsPolygon >();
294 obstaclePolygon->setExteriorRing( boundLineString.release() );
302 obstacleGeom = std::move( obstaclePolygon );
317 drawCallout( context, label );
335 QRectF rect( outPt.x(), outPt.y(), outPt2.
x() - outPt.x(), outPt2.
y() - outPt.y() );
339 QgsCallout::QgsCalloutContext calloutContext;
342 mSettings.callout()->render( context, rect, label->
getAlpha() * 180 / M_PI, g, calloutContext );
344 const QList< QgsCalloutPosition > renderedPositions = calloutContext.
positions();
346 for ( QgsCalloutPosition position : renderedPositions )
351 mEngine->results()->mLabelSearchTree->insertCallout( position );
371 const QMap< QgsPalLayerSettings::Property, QVariant > &ddValues = lf->
dataDefinedValues();
376 QgsDebugMsgLevel( QStringLiteral(
"PAL font definedFont: %1, Style: %2" ).arg( dFont.toString(), dFont.styleName() ), 4 );
383 format.
setSize( dFont.pixelSize() );
411 QgsPalLabeling::dataDefinedTextStyle( tmpLyr, ddValues );
414 QgsPalLabeling::dataDefinedTextBuffer( tmpLyr, ddValues );
417 QgsPalLabeling::dataDefinedTextMask( tmpLyr, ddValues );
420 QgsPalLabeling::dataDefinedTextFormatting( tmpLyr, ddValues );
423 QgsPalLabeling::dataDefinedShapeBackground( tmpLyr, ddValues );
426 QgsPalLabeling::dataDefinedDropShadow( tmpLyr, ddValues );
434 drawCallout( context, label );
513 components = drawType;
526 QgsTextRenderer::Component component;
527 component.dpiRatio = dpiRatio;
528 component.origin = outPt;
529 component.rotation = label->
getAlpha();
534 QPointF centerPt( outPt );
538 double xc = outPt2.
x() - outPt.x();
539 double yc = outPt2.
y() - outPt.y();
541 double angle = -component.rotation;
542 double xd = xc * std::cos( angle ) - yc * std::sin( angle );
543 double yd = xc * std::sin( angle ) + yc * std::cos( angle );
545 centerPt.setX( centerPt.x() + xd );
546 centerPt.setY( centerPt.y() + yd );
548 component.center = centerPt;
559 component.size = QSizeF( labelWidthPx, labelHeightPx );
587 std::optional< QgsTextDocument > newDocument;
588 std::optional< QgsTextDocumentMetrics > newDocumentMetrics;
592 newDocument.emplace( *document );
593 bool prependSymb =
false;
645 document = &newDocument.value();
646 documentMetrics = &newDocumentMetrics.value();
657 QgsTextRenderer::Component component;
658 component.origin = outPt;
659 component.rotation = label->
getAlpha();
671 for (
const QString &line : multiLineList )
678 QgsTextRenderer::drawTextInternal( components, context, tmpLyr.
format(), component, document,
693 component.origin.ry() += verticalAlignOffset;
695 QgsTextRenderer::drawTextInternal( components, context, tmpLyr.
format(), component, *document,
@ OverPoint
Arranges candidates over a point (or centroid of a polygon), or at a preset offset from the point....
@ Curved
Arranges candidates following the curvature of a line feature. Applies to line layers only.
@ AroundPoint
Arranges candidates in a circle around a point (or centroid of a polygon). Applies to point or polygo...
@ Line
Arranges candidates parallel to a generalised line representing the feature or parallel to a polygon'...
@ Free
Arranges candidates scattered throughout a polygon feature. Candidates are rotated to respect the pol...
@ OrderedPositionsAroundPoint
Candidates are placed in predefined positions around a point. Preference is given to positions with g...
@ Horizontal
Arranges horizontal candidates scattered throughout a polygon feature. Applies to polygon layers only...
@ PerimeterCurved
Arranges candidates following the curvature of a polygon's boundary. Applies to polygon layers only.
@ OutsidePolygons
Candidates are placed outside of polygon boundaries. Applies to polygon layers only.
@ Labeling
Labeling-specific layout mode.
@ NeverShow
Never show unplaced labels, regardless of the engine setting.
@ DrawUnplacedLabels
Whether to render unplaced labels as an indicator/warning for users.
GeometryType
The geometry types are used to group Qgis::WkbType in a coarse way.
@ FollowPlacement
Alignment follows placement of label, e.g., labels to the left of a feature will be drawn with right ...
QFlags< TextComponent > TextComponents
Text components.
TextHorizontalAlignment
Text horizontal alignment.
TextComponent
Text components.
@ Buffer
Buffer component.
@ Background
Background shape.
@ Reverse
Reverse/inverse transform (from destination to source).
virtual int nCoordinates() const
Returns the number of nodes contained in the geometry.
virtual QgsPoint vertexAt(QgsVertexId id) const =0
Returns the point corresponding to a specified vertex id.
QgsLabelObstacleSettings::ObstacleType mObstacleType
Type of the obstacle of feature geometries.
QString mName
Name of the layer.
virtual void stopRender(QgsRenderContext &context)
To be called after rendering is complete.
QString mLayerId
Associated layer's ID, if applicable.
double mPriority
Default priority of labels. 0 = highest priority, 1 = lowest priority.
const QgsLabelingEngine * mEngine
Associated labeling engine.
QgsMapLayer * layer() const
Returns the associated layer, or nullptr if no layer is associated with the provider.
Flags mFlags
Flags altering drawing and registration of features.
virtual void startRender(QgsRenderContext &context)
To be called before rendering of labels begins.
Qgis::LabelPlacement mPlacement
Placement strategy.
@ 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 mUpsidedownLabels
How to handle labels that would be upside down.
QString providerId() const
Returns provider ID - useful in case there is more than one label provider within a layer (e....
QgsAbstractLabelProvider(QgsMapLayer *layer, const QString &providerId=QString())
Construct the provider with default values.
QString mProviderId
Associated provider ID (one layer may have multiple providers, e.g. in rule-based labeling).
bool valueAsBool(int key, const QgsExpressionContext &context, bool defaultValue=false, bool *ok=nullptr) const
Calculates the current value of the property with the specified key and interprets it as an boolean.
bool allFeaturePartsLabeled
true if all parts of associated feature were labeled
QList< QgsCalloutPosition > positions() const
Returns the list of rendered callout positions.
QgsCoordinateReferenceSystem originalFeatureCrs
Contains the CRS of the original feature associated with this callout.
@ OrderBelowIndividualLabels
Render callouts below their individual associated labels, some callouts may be drawn over other label...
@ OrderBelowAllLabels
Render callouts below all labels.
bool enabled() const
Returns true if the the callout is enabled.
Represents a coordinate reference system (CRS).
Custom exception class for Coordinate Reference System related exceptions.
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.
QgsExpressionContextScope * popScope()
Removes the last scope from the expression context and return it.
void setOriginalValueVariable(const QVariant &value)
Sets the original value variable value for the context.
QgsExpressionContextScope * lastScope()
Returns the last scope added to the context.
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
Wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Container of fields for a vector layer.
A geometry is the spatial representation of a feature.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
static std::unique_ptr< QgsAbstractGeometry > fromGeos(const GEOSGeometry *geos)
Create a geometry from a GEOSGeometry.
QgsCoordinateReferenceSystem originalFeatureCrs() const
Returns the original layer CRS of the feature associated with the label.
GEOSGeometry * geometry() const
Gets access to the associated geometry.
bool hasFixedPosition() const
Whether the label should use a fixed position instead of being automatically placed.
QString labelText() const
Text of the label.
bool labelAllParts() const
Returns true if all parts of the feature should be labeled.
bool reverseDirectionSymbol() const
Returns true if direction symbols should be reversed.
DirectionSymbolPlacement directionSymbolPlacement() const
Returns the placement for direction symbols.
QString leftDirectionSymbol() const
Returns the string to use for left direction arrows.
@ SymbolLeftRight
Place direction symbols on left/right of label.
@ SymbolAbove
Place direction symbols on above label.
@ SymbolBelow
Place direction symbols on below label.
QString rightDirectionSymbol() const
Returns the string to use for right direction arrows.
bool addDirectionSymbol() const
Returns true if '<' or '>' (or custom strings set via leftDirectionSymbol and rightDirectionSymbol) w...
@ PolygonWhole
Avoid placing labels over ANY part of polygon. Where PolygonInterior will prefer to place labels with...
Base class for all map layer types.
Contains configuration for rendering maps.
Perform transforms between map coordinates and device coordinates.
void setMapRotation(double degrees, double cx, double cy)
Sets map rotation in degrees (clockwise).
QgsPointXY toMapCoordinates(int x, int y) const
Transforms device coordinates to map (world) coordinates.
QgsPointXY transform(const QgsPointXY &p) const
Transforms a point p from map (world) coordinates to device coordinates.
void transformInPlace(double &x, double &y) const
Transforms map coordinates to device coordinates.
Struct for storing maximum and minimum scales for measurements in map units.
A marker symbol type, for rendering Point and MultiPoint geometries.
Multi polygon geometry collection.
bool addGeometry(QgsAbstractGeometry *g) override
Adds a geometry and takes ownership. Returns true in case of success.
static QStringList splitToLines(const QString &text, const QString &wrapCharacter, int autoWrapLength=0, bool useMaxLineLengthWhenAutoWrapping=true)
Splits a text string to a list of separate lines, using a specified wrap character (wrapCharacter).
Contains settings for how a map layer will be labeled.
void setFormat(const QgsTextFormat &format)
Sets the label text formatting settings, e.g., font settings, buffer settings, etc.
QString wrapChar
Wrapping character string.
Qgis::LabelPlacement placement
Label placement mode.
QgsPropertyCollection & dataDefinedProperties()
Returns a reference to the label's property collection, used for data defined overrides.
Qgis::LabelMultiLineAlignment multilineAlign
Horizontal alignment of multi-line labels.
QgsCallout * callout() const
Returns the label callout renderer, responsible for drawing label callouts.
const QgsLabelLineSettings & lineSettings() const
Returns the label line settings, which contain settings related to how the label engine places and fo...
@ CalloutDraw
Show callout.
const QgsTextFormat & format() const
Returns the label text formatting settings, e.g., font settings, buffer settings, etc.
int autoWrapLength
If non-zero, indicates that label text should be automatically wrapped to (ideally) the specified num...
bool useMaxLineLengthForAutoWrap
If true, indicates that when auto wrapping label text the autoWrapLength length indicates the maximum...
QPointF toQPointF() const
Converts a point to a QPointF.
Point geometry type, with support for z-dimension and m-values.
bool isActive(int key) const final
Returns true if the collection contains an active property with the specified key.
A rectangle specified with double values.
Contains information about the context of a rendering operation.
const QgsMaskIdProvider * maskIdProvider() const
Returns the mask id provider attached to the context.
double convertToPainterUnits(double size, Qgis::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale(), Qgis::RenderSubcomponentProperty property=Qgis::RenderSubcomponentProperty::Generic) const
Converts a size from the specified units to painter units (pixels).
QgsExpressionContext & expressionContext()
Gets the expression context.
const QgsRectangle & extent() const
When rendering a map layer, calling this method returns the "clipping" extent for the layer (in the l...
void setCurrentMaskId(int id)
Stores a mask id as the "current" one.
const QgsMapToPixel & mapToPixel() const
Returns the context's map to pixel transform, which transforms between map coordinates and device coo...
QgsCoordinateTransform coordinateTransform() const
Returns the current coordinate transform for the context.
Scoped object for temporary override of the symbologyReferenceScale property of a QgsRenderContext.
Abstract base class for all rendered symbols.
bool enabled() const
Returns whether the background is enabled.
ShapeType type() const
Returns the type of background shape (e.g., square, ellipse, SVG).
@ ShapeMarkerSymbol
Marker symbol.
Represents a block of text consisting of one or more QgsTextFragment objects.
void insert(int index, const QgsTextFragment &fragment)
Inserts a fragment into the block, at the specified index.
static QgsTextBlock fromPlainText(const QString &text, const QgsTextCharacterFormat &format=QgsTextCharacterFormat())
Constructor for QgsTextBlock consisting of a plain text, and optional character format.
void append(const QgsTextFragment &fragment)
Appends a fragment to the block.
bool enabled() const
Returns whether the buffer is enabled.
Stores information relating to individual character formatting.
Contains pre-calculated metrics of a QgsTextDocument.
static QgsTextDocumentMetrics calculateMetrics(const QgsTextDocument &document, const QgsTextFormat &format, const QgsRenderContext &context, double scaleFactor=1.0, const QgsTextDocumentRenderContext &documentContext=QgsTextDocumentRenderContext())
Returns precalculated text metrics for a text document, when rendered using the given base format and...
double blockVerticalMargin(int blockIndex) const
Returns the vertical margin for the specified block index.
Represents a document consisting of one or more QgsTextBlock objects.
int size() const
Returns the number of blocks in the document.
void append(const QgsTextBlock &block)
Appends a block to the document.
Container for all settings relating to text rendering.
void setColor(const QColor &color)
Sets the color that text will be rendered in.
void setSize(double size)
Sets the size for rendered text.
void setFont(const QFont &font)
Sets the font used for rendering text.
void setSizeUnit(Qgis::RenderUnit unit)
Sets the units for the size of rendered text.
QgsTextBackgroundSettings & background()
Returns a reference to the text background settings.
QgsTextShadowSettings & shadow()
Returns a reference to the text drop shadow settings.
QFont font() const
Returns the font used for rendering text.
QgsTextBufferSettings & buffer()
Returns a reference to the text buffer settings.
Stores a fragment of document along with formatting overrides to be used when rendering the fragment.
Adds extra information to QgsLabelFeature for text labels.
QFont definedFont() const
Font to be used for rendering.
const QgsTextDocumentMetrics & documentMetrics() const
Returns the document metrics for the label.
const QgsTextDocument & document() const
Returns the document for the label.
QgsTextCharacterFormat characterFormat(int partId) const
Returns the character format corresponding to the specified label part.
const QMap< QgsPalLayerSettings::Property, QVariant > & dataDefinedValues() const
Gets data-defined values.
QString text(int partId) const
Returns the text component corresponding to a specified label part.
bool enabled() const
Returns whether the shadow is enabled.
void setShadowPlacement(QgsTextShadowSettings::ShadowPlacement placement)
Sets the placement for the drop shadow.
@ ShadowBuffer
Draw shadow under buffer.
@ ShadowShape
Draw shadow under background shape.
@ ShadowLowest
Draw shadow below all text components.
@ ShadowText
Draw shadow under text.
QgsTextShadowSettings::ShadowPlacement shadowPlacement() const
Returns the placement for the drop shadow.
void stopRender(QgsRenderContext &context) override
To be called after rendering is complete.
QgsCoordinateReferenceSystem mCrs
Layer's CRS.
virtual bool prepare(QgsRenderContext &context, QSet< QString > &attributeNames)
Prepare for registration of features.
void drawUnplacedLabel(QgsRenderContext &context, pal::LabelPosition *label) const override
Draw an unplaced label.
QgsFields mFields
Layer's fields.
QList< QgsLabelFeature * > mLabels
List of generated.
QgsVectorLayerLabelProvider(QgsVectorLayer *layer, const QString &providerId, bool withFeatureLoop, const QgsPalLayerSettings *settings, const QString &layerName=QString())
Convenience constructor to initialize the provider from given vector layer.
void startRender(QgsRenderContext &context) override
To be called before rendering of labels begins.
~QgsVectorLayerLabelProvider() override
const QgsPalLayerSettings & settings() const
Returns the layer's settings.
void drawLabelPrivate(pal::LabelPosition *label, QgsRenderContext &context, QgsPalLayerSettings &tmpLyr, Qgis::TextComponent drawType, double dpiRatio=1.0) const
Internal label drawing method.
Qgis::GeometryType mLayerGeometryType
Geometry type of layer.
static QgsGeometry getPointObstacleGeometry(QgsFeature &fet, QgsRenderContext &context, const QgsSymbolList &symbols)
Returns the geometry for a point feature which should be used as an obstacle for labels.
QgsPalLayerSettings mSettings
Layer's labeling configuration.
std::unique_ptr< QgsAbstractFeatureSource > mSource
Layer's feature source.
QList< QgsLabelFeature * > labelFeatures(QgsRenderContext &context) override
Returns list of label features (they are owned by the provider and thus deleted on its destruction).
QgsFeatureRenderer * mRenderer
virtual QList< QgsLabelFeature * > registerFeature(const QgsFeature &feature, QgsRenderContext &context, const QgsGeometry &obstacleGeometry=QgsGeometry(), const QgsSymbol *symbol=nullptr)
Register a feature for labeling as one or more QgsLabelFeature objects stored into mLabels.
void init()
initialization method - called from constructors
void setFields(const QgsFields &fields)
Sets fields of this label provider.
void drawLabel(QgsRenderContext &context, pal::LabelPosition *label) const override
Draw this label at the position determined by the labeling engine.
void drawLabelBackground(QgsRenderContext &context, pal::LabelPosition *label) const override
Draw the background for the specified label.
Represents a vector layer which manages a vector based dataset.
QgsFeatureId featureId() const
Returns the unique ID of the feature.
QgsLabelFeature * feature()
Returns the parent feature.
Layer * layer()
Returns the layer that feature belongs to.
LabelPosition is a candidate feature label position.
double getAlpha() const
Returns the angle to rotate text (in radians).
bool isReversedFromLineDirection() const
Returns true if the label direction is the reversed from the line or polygon ring direction.
Qgis::LabelQuadrantPosition quadrant() const
Returns the quadrant associated with this label position.
FeaturePart * getFeaturePart() const
Returns the feature corresponding to this labelposition.
double getX(int i=0) const
Returns the down-left x coordinate.
double getY(int i=0) const
Returns the down-left y coordinate.
LabelPosition * nextPart() const
Returns the next part of this label position (i.e.
QgsAbstractLabelProvider * provider() const
Returns pointer to the associated provider.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
#define QgsDebugMsgLevel(str, level)
QList< QgsSymbol * > QgsSymbolList
Utility class for identifying a unique vertex within a geometry.