QGIS API Documentation 3.39.0-Master (d85f3c2a281)
Loading...
Searching...
No Matches
qgsannotationlinetextitem.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsannotationlinetextitem.cpp
3 ----------------
4 begin : March 2023
5 copyright : (C) 2023 by Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
21#include "qgsrendercontext.h"
22#include "qgscurve.h"
23#include "qgslinestring.h"
24#include "qgstextrenderer.h"
25#include "qgsunittypes.h"
26#include "qgssymbollayerutils.h"
27
30 , mText( text )
31 , mCurve( curve )
32{
33
34}
35
37{
38 // in truth this should depend on whether the text format is scale dependent or not!
41}
42
44
46{
47 return QStringLiteral( "linetext" );
48}
49
51{
52 // TODO -- expose as an option!
53 QgsGeometry smoothed( mCurve->clone() );
54 smoothed = smoothed.smooth( );
55
56 QPolygonF pts = smoothed.asQPolygonF();
57
58 //transform the QPolygonF to screen coordinates
59 if ( context.coordinateTransform().isValid() )
60 {
61 try
62 {
64 }
65 catch ( QgsCsException & )
66 {
67 // we don't abort the rendering here, instead we remove any invalid points and just plot those which ARE valid
68 }
69 }
70
71 // remove non-finite points, e.g. infinite or NaN points caused by reprojecting errors
72 pts.erase( std::remove_if( pts.begin(), pts.end(),
73 []( const QPointF point )
74 {
75 return !std::isfinite( point.x() ) || !std::isfinite( point.y() );
76 } ), pts.end() );
77
78 QPointF *ptr = pts.data();
79 for ( int i = 0; i < pts.size(); ++i, ++ptr )
80 {
81 context.mapToPixel().transformInPlace( ptr->rx(), ptr->ry() );
82 }
83
84 const QString displayText = QgsExpression::replaceExpressionText( mText, &context.expressionContext(), &context.distanceArea() );
85
86 const double offsetFromLine = context.convertToPainterUnits( mOffsetFromLineDistance, mOffsetFromLineUnit, mOffsetFromLineScale );
87
88 QgsTextRenderer::drawTextOnLine( pts, displayText, context, mTextFormat, 0, offsetFromLine );
89}
90
91bool QgsAnnotationLineTextItem::writeXml( QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context ) const
92{
93 element.setAttribute( QStringLiteral( "wkt" ), mCurve->asWkt() );
94 element.setAttribute( QStringLiteral( "text" ), mText );
95
96 element.setAttribute( QStringLiteral( "offsetFromLine" ), qgsDoubleToString( mOffsetFromLineDistance ) );
97 element.setAttribute( QStringLiteral( "offsetFromLineUnit" ), QgsUnitTypes::encodeUnit( mOffsetFromLineUnit ) );
98 element.setAttribute( QStringLiteral( "offsetFromLineScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetFromLineScale ) );
99
100 QDomElement textFormatElem = document.createElement( QStringLiteral( "lineTextFormat" ) );
101 textFormatElem.appendChild( mTextFormat.writeXml( document, context ) );
102 element.appendChild( textFormatElem );
103
104 writeCommonProperties( element, document, context );
105
106 return true;
107}
108
109QList<QgsAnnotationItemNode> QgsAnnotationLineTextItem::nodesV2( const QgsAnnotationItemEditContext & ) const
110{
111 QList< QgsAnnotationItemNode > res;
112 int i = 0;
113 for ( auto it = mCurve->vertices_begin(); it != mCurve->vertices_end(); ++it, ++i )
114 {
115 res.append( QgsAnnotationItemNode( it.vertexId(), QgsPointXY( ( *it ).x(), ( *it ).y() ), Qgis::AnnotationItemNodeType::VertexHandle ) );
116 }
117 return res;
118}
119
121{
122 switch ( operation->type() )
123 {
125 {
126 QgsAnnotationItemEditOperationMoveNode *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationMoveNode * >( operation );
127 if ( mCurve->moveVertex( moveOperation->nodeId(), QgsPoint( moveOperation->after() ) ) )
129 break;
130 }
131
133 {
134 QgsAnnotationItemEditOperationDeleteNode *deleteOperation = qgis::down_cast< QgsAnnotationItemEditOperationDeleteNode * >( operation );
135 if ( mCurve->deleteVertex( deleteOperation->nodeId() ) )
137 break;
138 }
139
141 {
142 QgsAnnotationItemEditOperationAddNode *addOperation = qgis::down_cast< QgsAnnotationItemEditOperationAddNode * >( operation );
143
144 QgsPoint segmentPoint;
145 QgsVertexId endOfSegmentVertex;
146 mCurve->closestSegment( addOperation->point(), segmentPoint, endOfSegmentVertex );
147 if ( mCurve->insertVertex( endOfSegmentVertex, segmentPoint ) )
149 break;
150 }
151
153 {
154 QgsAnnotationItemEditOperationTranslateItem *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationTranslateItem * >( operation );
155 const QTransform transform = QTransform::fromTranslate( moveOperation->translationX(), moveOperation->translationY() );
156 mCurve->transform( transform );
158 }
159 }
160
162}
163
165{
166 switch ( operation->type() )
167 {
169 {
170 QgsAnnotationItemEditOperationMoveNode *moveOperation = dynamic_cast< QgsAnnotationItemEditOperationMoveNode * >( operation );
171 std::unique_ptr< QgsCurve > modifiedCurve( mCurve->clone() );
172 if ( modifiedCurve->moveVertex( moveOperation->nodeId(), QgsPoint( moveOperation->after() ) ) )
173 {
174 return new QgsAnnotationItemEditOperationTransientResults( QgsGeometry( std::move( modifiedCurve ) ) );
175 }
176 break;
177 }
178
180 {
181 QgsAnnotationItemEditOperationTranslateItem *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationTranslateItem * >( operation );
182 const QTransform transform = QTransform::fromTranslate( moveOperation->translationX(), moveOperation->translationY() );
183 std::unique_ptr< QgsCurve > modifiedCurve( mCurve->clone() );
184 modifiedCurve->transform( transform );
185 return new QgsAnnotationItemEditOperationTransientResults( QgsGeometry( std::move( modifiedCurve ) ) );
186 }
187
190 break;
191 }
192 return nullptr;
193}
194
199
200bool QgsAnnotationLineTextItem::readXml( const QDomElement &element, const QgsReadWriteContext &context )
201{
202 const QString wkt = element.attribute( QStringLiteral( "wkt" ) );
204 if ( const QgsCurve *curve = qgsgeometry_cast< const QgsCurve * >( geometry.constGet() ) )
205 mCurve.reset( curve->clone() );
206
207 mText = element.attribute( QStringLiteral( "text" ) );
208 const QDomElement textFormatElem = element.firstChildElement( QStringLiteral( "lineTextFormat" ) );
209 if ( !textFormatElem.isNull() )
210 {
211 const QDomNodeList textFormatNodeList = textFormatElem.elementsByTagName( QStringLiteral( "text-style" ) );
212 const QDomElement textFormatElem = textFormatNodeList.at( 0 ).toElement();
213 mTextFormat.readXml( textFormatElem, context );
214 }
215
216 mOffsetFromLineDistance = element.attribute( QStringLiteral( "offsetFromLine" ) ).toDouble();
217 bool ok = false;
218 mOffsetFromLineUnit = QgsUnitTypes::decodeRenderUnit( element.attribute( QStringLiteral( "offsetFromLineUnit" ) ), &ok );
219 if ( !ok )
220 mOffsetFromLineUnit = Qgis::RenderUnit::Millimeters;
221
222 mOffsetFromLineScale = QgsSymbolLayerUtils::decodeMapUnitScale( element.attribute( QStringLiteral( "offsetFromLineScale" ) ) );
223
224 readCommonProperties( element, context );
225
226 return true;
227}
228
230{
231 return mCurve->boundingBox();
232}
233
235{
236 const QString displayText = QgsExpression::replaceExpressionText( mText, &context.expressionContext(), &context.distanceArea() );
237
238 const double lineOffsetInMapUnits = std::fabs( context.convertToMapUnits( mOffsetFromLineDistance, mOffsetFromLineUnit, mOffsetFromLineScale ) );
239
240 const double heightInPixels = QgsTextRenderer::textHeight( context, mTextFormat, { displayText} );
241
242 // text size has already been calculated using any symbology reference scale factor above -- we need
243 // to temporarily remove the reference scale here or we'll be undoing the scaling
244 QgsScopedRenderContextReferenceScaleOverride resetScaleFactor( context, -1.0 );
245 const double heightInMapUnits = context.convertToMapUnits( heightInPixels, Qgis::RenderUnit::Pixels );
246
247 return mCurve->boundingBox().buffered( heightInMapUnits + lineOffsetInMapUnits );
248}
249
251{
252 std::unique_ptr< QgsAnnotationLineTextItem > item = std::make_unique< QgsAnnotationLineTextItem >( mText, mCurve->clone() );
253 item->setFormat( mTextFormat );
254 item->setOffsetFromLine( mOffsetFromLineDistance );
255 item->setOffsetFromLineUnit( mOffsetFromLineUnit );
256 item->setOffsetFromLineMapUnitScale( mOffsetFromLineScale );
257 item->copyCommonProperties( this );
258 return item.release();
259}
260
262{
263 mCurve.reset( geometry );
264}
265
267{
268 return mTextFormat;
269}
270
272{
273 mTextFormat = format;
274}
@ VertexHandle
Node is a handle for manipulating vertices.
@ ScaleDependentBoundingBox
Item's bounding box will vary depending on map scale.
@ SupportsReferenceScale
Item supports reference scale based rendering.
AnnotationItemEditOperationResult
Results from an edit operation on an annotation item.
Definition qgis.h:2351
@ Invalid
Operation has invalid parameters for the item, no change occurred.
@ Success
Item was modified successfully.
@ ItemCleared
The operation results in the item being cleared, and the item should be removed from the layer as a r...
QFlags< AnnotationItemFlag > AnnotationItemFlags
Annotation item flags.
Definition qgis.h:2302
@ Millimeters
Millimeters.
Abstract base class for annotation item edit operations.
@ TranslateItem
Translate (move) an item.
virtual Type type() const =0
Returns the operation type.
Encapsulates the context for an annotation item edit operation.
Annotation item edit operation consisting of adding a node.
QgsPoint point() const
Returns the node position (in layer coordinates).
Annotation item edit operation consisting of deleting a node.
QgsVertexId nodeId() const
Returns the deleted node ID.
Annotation item edit operation consisting of moving a node.
QgsPoint after() const
Returns the node position after the move occurred (in layer coordinates).
QgsVertexId nodeId() const
Returns the associated node ID.
Encapsulates the transient results of an in-progress annotation edit operation.
Annotation item edit operation consisting of translating (moving) an item.
double translationY() const
Returns the y-axis translation, in layer units.
double translationX() const
Returns the x-axis translation, in layer units.
Contains information about a node used for editing an annotation item.
Abstract base class for annotation items which are drawn with QgsAnnotationLayers.
virtual bool writeCommonProperties(QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context) const
Writes common properties from the base class into an XML element.
virtual bool readCommonProperties(const QDomElement &element, const QgsReadWriteContext &context)
Reads common properties from the base class from the given DOM element.
An annotation item which renders text along a line geometry.
double offsetFromLine() const
Returns the offset distance from the line geometry() to the text's baseline.
void setGeometry(QgsCurve *geometry)
Sets the geometry of the item.
void render(QgsRenderContext &context, QgsFeedback *feedback) override
Renders the item to the specified render context.
QgsRectangle boundingBox() const override
Returns the bounding box of the item's geographic location, in the parent layer's coordinate referenc...
const QgsCurve * geometry() const
Returns the geometry of the item.
QgsAnnotationItemEditOperationTransientResults * transientEditResultsV2(QgsAbstractAnnotationItemEditOperation *operation, const QgsAnnotationItemEditContext &context) override
Retrieves the results of a transient (in progress) edit operation on the item.
QString type() const override
Returns a unique (untranslated) string identifying the type of item.
static QgsAnnotationLineTextItem * create()
Creates a new linestring annotation item.
QgsAnnotationLineTextItem * clone() const override
Returns a clone of the item.
QList< QgsAnnotationItemNode > nodesV2(const QgsAnnotationItemEditContext &context) const override
Returns the nodes for the item, used for editing the item.
QgsAnnotationLineTextItem(const QString &text, QgsCurve *curve)
Constructor for QgsAnnotationLineTextItem, with the specified curve and text.
bool writeXml(QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context) const override
Writes the item's state into an XML element.
~QgsAnnotationLineTextItem() override
Qgis::AnnotationItemFlags flags() const override
Returns item flags.
void setFormat(const QgsTextFormat &format)
Sets the text format used to render the text.
Qgis::AnnotationItemEditOperationResult applyEditV2(QgsAbstractAnnotationItemEditOperation *operation, const QgsAnnotationItemEditContext &context) override
Applies an edit operation to the item.
QgsTextFormat format() const
Returns the text format used to render the text.
bool readXml(const QDomElement &element, const QgsReadWriteContext &context) override
Reads the item's state from the given DOM element.
void transformPolygon(QPolygonF &polygon, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward) const
Transforms a polygon to the destination coordinate system.
bool isValid() const
Returns true if the coordinate transform is valid, ie both the source and destination CRS have been s...
Custom exception class for Coordinate Reference System related exceptions.
Abstract base class for curved geometry type.
Definition qgscurve.h:35
static QString replaceExpressionText(const QString &action, const QgsExpressionContext *context, const QgsDistanceArea *distanceArea=nullptr)
This function replaces each expression between [% and %] in the string with the result of its evaluat...
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition qgsfeedback.h:44
A geometry is the spatial representation of a feature.
QPolygonF asQPolygonF() const
Returns contents of the geometry as a QPolygonF.
static Q_INVOKABLE QgsGeometry fromWkt(const QString &wkt)
Creates a new geometry from a WKT string.
QgsGeometry smooth(unsigned int iterations=1, double offset=0.25, double minimumDistance=-1.0, double maxAngle=180.0) const
Smooths a geometry by rounding off corners using the Chaikin algorithm.
Line string geometry type, with support for z-dimension and m-values.
void transformInPlace(double &x, double &y) const
Transforms map coordinates to device coordinates.
A class to represent a 2D point.
Definition qgspointxy.h:60
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:49
The class is used as a container of context for various read/write operations on other objects.
A rectangle specified with double values.
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.
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).
const QgsDistanceArea & distanceArea() const
A general purpose distance and area calculator, capable of performing ellipsoid based calculations.
QgsExpressionContext & expressionContext()
Gets the expression context.
const QgsMapToPixel & mapToPixel() const
Returns the context's map to pixel transform, which transforms between map coordinates and device coo...
QgsCoordinateTransform coordinateTransform() const
Returns the current coordinate transform for the context.
Scoped object for temporary override of the symbologyReferenceScale property of a QgsRenderContext.
static QString encodeMapUnitScale(const QgsMapUnitScale &mapUnitScale)
static QgsMapUnitScale decodeMapUnitScale(const QString &str)
Container for all settings relating to text rendering.
void readXml(const QDomElement &elem, const QgsReadWriteContext &context)
Read settings from a DOM element.
QDomElement writeXml(QDomDocument &doc, const QgsReadWriteContext &context) const
Write settings into a DOM element.
static void drawTextOnLine(const QPolygonF &line, const QString &text, QgsRenderContext &context, const QgsTextFormat &format, double offsetAlongLine=0, double offsetFromLine=0)
Draws text along a line using the specified settings.
static double textHeight(const QgsRenderContext &context, const QgsTextFormat &format, const QStringList &textLines, Qgis::TextLayoutMode mode=Qgis::TextLayoutMode::Point, QFontMetricsF *fontMetrics=nullptr, Qgis::TextRendererFlags flags=Qgis::TextRendererFlags(), double maxLineWidth=0)
Returns the height of a text based on a given format.
static Q_INVOKABLE Qgis::RenderUnit decodeRenderUnit(const QString &string, bool *ok=nullptr)
Decodes a render unit from a string.
static Q_INVOKABLE QString encodeUnit(Qgis::DistanceUnit unit)
Encodes a distance unit to a string.
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
Definition qgis.h:5774
Utility class for identifying a unique vertex within a geometry.
Definition qgsvertexid.h:30