QGIS API Documentation 4.3.0-Master (0978c174f8e)
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
19
22#include "qgscurve.h"
23#include "qgslinestring.h"
24#include "qgsrendercontext.h"
25#include "qgssymbollayerutils.h"
26#include "qgstextrenderer.h"
27#include "qgsunittypes.h"
28
29#include <QString>
30
31using namespace Qt::StringLiterals;
32
35 , mText( text )
36 , mCurve( curve )
37{}
38
40{
41 // in truth this should depend on whether the text format is scale dependent or not!
43}
44
46
48{
49 return u"linetext"_s;
50}
51
53{
54 // TODO -- expose as an option!
55 QgsGeometry smoothed( mCurve->clone() );
56 smoothed = smoothed.smooth();
57
58 QPolygonF pts = smoothed.asQPolygonF();
59
60 //transform the QPolygonF to screen coordinates
61 if ( context.coordinateTransform().isValid() )
62 {
63 try
64 {
66 }
67 catch ( QgsCsException & )
68 {
69 // we don't abort the rendering here, instead we remove any invalid points and just plot those which ARE valid
70 }
71 }
72
73 // remove non-finite points, e.g. infinite or NaN points caused by reprojecting errors
74 pts.erase( std::remove_if( pts.begin(), pts.end(), []( const QPointF point ) { return !std::isfinite( point.x() ) || !std::isfinite( point.y() ); } ), pts.end() );
75
76 QPointF *ptr = pts.data();
77 for ( int i = 0; i < pts.size(); ++i, ++ptr )
78 {
79 context.mapToPixel().transformInPlace( ptr->rx(), ptr->ry() );
80 }
81
82 const QString displayText = QgsExpression::replaceExpressionText( mText, &context.expressionContext(), &context.distanceArea() );
83
84 const double offsetFromLine = context.convertToPainterUnits( mOffsetFromLineDistance, mOffsetFromLineUnit, mOffsetFromLineScale );
85
87}
88
89bool QgsAnnotationLineTextItem::writeXml( QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context ) const
90{
91 element.setAttribute( u"wkt"_s, mCurve->asWkt() );
92 element.setAttribute( u"text"_s, mText );
93
94 element.setAttribute( u"offsetFromLine"_s, qgsDoubleToString( mOffsetFromLineDistance ) );
95 element.setAttribute( u"offsetFromLineUnit"_s, QgsUnitTypes::encodeUnit( mOffsetFromLineUnit ) );
96 element.setAttribute( u"offsetFromLineScale"_s, QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetFromLineScale ) );
97
98 if ( mTextAnchor != Qgis::TextAnchorPoint::StartOfText )
99 {
100 element.setAttribute( u"textAnchor"_s, qgsEnumValueToKey( mTextAnchor ) );
101 }
102
103 QDomElement textFormatElem = document.createElement( u"lineTextFormat"_s );
104 textFormatElem.appendChild( mTextFormat.writeXml( document, context ) );
105 element.appendChild( textFormatElem );
106
107 writeCommonProperties( element, document, context );
108
109 return true;
110}
111
112QList<QgsAnnotationItemNode> QgsAnnotationLineTextItem::nodesV2( const QgsAnnotationItemEditContext & ) const
113{
114 QList< QgsAnnotationItemNode > res;
115 for ( auto it = mCurve->vertices_begin(); it != mCurve->vertices_end(); ++it )
116 {
117 res.append( QgsAnnotationItemNode( it.vertexId(), QgsPointXY( ( *it ).x(), ( *it ).y() ), Qgis::AnnotationItemNodeType::VertexHandle ) );
118 }
119 return res;
120}
121
123{
124 switch ( operation->type() )
125 {
127 {
128 QgsAnnotationItemEditOperationMoveNode *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationMoveNode * >( operation );
129 if ( mCurve->moveVertex( moveOperation->nodeId(), QgsPoint( moveOperation->after() ) ) )
131 break;
132 }
133
135 {
136 QgsAnnotationItemEditOperationDeleteNode *deleteOperation = qgis::down_cast< QgsAnnotationItemEditOperationDeleteNode * >( operation );
137 if ( mCurve->deleteVertex( deleteOperation->nodeId() ) )
139 break;
140 }
141
143 {
144 QgsAnnotationItemEditOperationAddNode *addOperation = qgis::down_cast< QgsAnnotationItemEditOperationAddNode * >( operation );
145
146 QgsPoint segmentPoint;
147 QgsVertexId endOfSegmentVertex;
148 mCurve->closestSegment( addOperation->point(), segmentPoint, endOfSegmentVertex );
149 if ( mCurve->insertVertex( endOfSegmentVertex, segmentPoint ) )
151 break;
152 }
153
155 {
156 QgsAnnotationItemEditOperationTranslateItem *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationTranslateItem * >( operation );
157 const QTransform transform = QTransform::fromTranslate( moveOperation->translationX(), moveOperation->translationY() );
158 mCurve->transform( transform );
160 }
161
163 {
164 QgsAnnotationItemEditOperationRotateItem *rotateOperation = qgis::down_cast< QgsAnnotationItemEditOperationRotateItem * >( operation );
165 QgsPointXY center = mCurve->boundingBox().center();
166 QTransform transform = QTransform::fromTranslate( center.x(), center.y() );
167 transform.rotate( -rotateOperation->angle() );
168 transform.translate( -center.x(), -center.y() );
169 mCurve->transform( transform );
171 }
172 }
173
175}
176
178{
179 switch ( operation->type() )
180 {
182 {
183 QgsAnnotationItemEditOperationMoveNode *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationMoveNode * >( operation );
184 std::unique_ptr< QgsCurve > modifiedCurve( mCurve->clone() );
185 if ( modifiedCurve->moveVertex( moveOperation->nodeId(), QgsPoint( moveOperation->after() ) ) )
186 {
187 return new QgsAnnotationItemEditOperationTransientResults( QgsGeometry( std::move( modifiedCurve ) ) );
188 }
189 break;
190 }
191
193 {
194 QgsAnnotationItemEditOperationTranslateItem *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationTranslateItem * >( operation );
195 const QTransform transform = QTransform::fromTranslate( moveOperation->translationX(), moveOperation->translationY() );
196 std::unique_ptr< QgsCurve > modifiedCurve( mCurve->clone() );
197 modifiedCurve->transform( transform );
198 return new QgsAnnotationItemEditOperationTransientResults( QgsGeometry( std::move( modifiedCurve ) ) );
199 }
200
202 {
203 QgsAnnotationItemEditOperationRotateItem *rotateOperation = qgis::down_cast< QgsAnnotationItemEditOperationRotateItem * >( operation );
204 std::unique_ptr< QgsCurve > modifiedCurve( mCurve->clone() );
205 QgsPointXY center = modifiedCurve->boundingBox().center();
206 QTransform transform = QTransform::fromTranslate( center.x(), center.y() );
207 transform.rotate( -rotateOperation->angle() );
208 transform.translate( -center.x(), -center.y() );
209 modifiedCurve->transform( transform );
210 return new QgsAnnotationItemEditOperationTransientResults( QgsGeometry( std::move( modifiedCurve ) ) );
211 }
212
215 break;
216 }
217 return nullptr;
218}
219
224
225bool QgsAnnotationLineTextItem::readXml( const QDomElement &element, const QgsReadWriteContext &context )
226{
227 const QString wkt = element.attribute( u"wkt"_s );
229 if ( const QgsCurve *curve = qgsgeometry_cast< const QgsCurve * >( geometry.constGet() ) )
230 mCurve.reset( curve->clone() );
231
232 mText = element.attribute( u"text"_s );
233 const QDomElement textFormatElem = element.firstChildElement( u"lineTextFormat"_s );
234 if ( !textFormatElem.isNull() )
235 {
236 const QDomNodeList textFormatNodeList = textFormatElem.elementsByTagName( u"text-style"_s );
237 const QDomElement textFormatElem = textFormatNodeList.at( 0 ).toElement();
238 mTextFormat.readXml( textFormatElem, context );
239 }
240
241 mOffsetFromLineDistance = element.attribute( u"offsetFromLine"_s ).toDouble();
242 bool ok = false;
243 mOffsetFromLineUnit = QgsUnitTypes::decodeRenderUnit( element.attribute( u"offsetFromLineUnit"_s ), &ok );
244 if ( !ok )
245 mOffsetFromLineUnit = Qgis::RenderUnit::Millimeters;
246
247 mOffsetFromLineScale = QgsSymbolLayerUtils::decodeMapUnitScale( element.attribute( u"offsetFromLineScale"_s ) );
248
249 mTextAnchor = qgsEnumKeyToValue( element.attribute( u"textAnchor"_s ), Qgis::TextAnchorPoint::StartOfText );
250
251 readCommonProperties( element, context );
252
253 return true;
254}
255
257{
258 return mCurve->boundingBox();
259}
260
262{
263 const QString displayText = QgsExpression::replaceExpressionText( mText, &context.expressionContext(), &context.distanceArea() );
264
265 const double lineOffsetInMapUnits = std::fabs( context.convertToMapUnits( mOffsetFromLineDistance, mOffsetFromLineUnit, mOffsetFromLineScale ) );
266
267 const double heightInPixels = QgsTextRenderer::textHeight( context, mTextFormat, { displayText } );
268
269 // text size has already been calculated using any symbology reference scale factor above -- we need
270 // to temporarily remove the reference scale here or we'll be undoing the scaling
271 QgsScopedRenderContextReferenceScaleOverride resetScaleFactor( context, -1.0 );
272 const double heightInMapUnits = context.convertToMapUnits( heightInPixels, Qgis::RenderUnit::Pixels );
273
274 return mCurve->boundingBox().buffered( heightInMapUnits + lineOffsetInMapUnits );
275}
276
278{
279 auto item = std::make_unique< QgsAnnotationLineTextItem >( mText, mCurve->clone() );
280 item->setFormat( mTextFormat );
281 item->setOffsetFromLine( mOffsetFromLineDistance );
282 item->setOffsetFromLineUnit( mOffsetFromLineUnit );
283 item->setOffsetFromLineMapUnitScale( mOffsetFromLineScale );
284 item->setTextAnchor( mTextAnchor );
285 item->copyCommonProperties( this );
286 return item.release();
287}
288
290{
291 mCurve.reset( geometry );
292}
293
295{
296 return mTextFormat;
297}
298
300{
301 mTextFormat = format;
302}
303
305{
306 return mTextAnchor;
307}
308
310{
311 mTextAnchor = anchor;
312}
@ VertexHandle
Node is a handle for manipulating vertices.
Definition qgis.h:2694
@ ScaleDependentBoundingBox
Item's bounding box will vary depending on map scale.
Definition qgis.h:2651
@ SupportsReferenceScale
Item supports reference scale based rendering.
Definition qgis.h:2652
TextAnchorPoint
Anchor point of label text.
Definition qgis.h:1475
@ StartOfText
Anchor using start of text.
Definition qgis.h:1476
AnnotationItemEditOperationResult
Results from an edit operation on an annotation item.
Definition qgis.h:2705
@ Invalid
Operation has invalid parameters for the item, no change occurred.
Definition qgis.h:2707
@ Success
Item was modified successfully.
Definition qgis.h:2706
@ ItemCleared
The operation results in the item being cleared, and the item should be removed from the layer as a r...
Definition qgis.h:2708
QFlags< AnnotationItemFlag > AnnotationItemFlags
Annotation item flags.
Definition qgis.h:2656
@ Millimeters
Millimeters.
Definition qgis.h:5651
@ Pixels
Pixels.
Definition qgis.h:5653
@ ExtendLineToFitText
When a string is too long for the line, extend the line's final segment to fit the entire string.
Definition qgis.h:3192
@ UseBaselinePlacement
Generate placement based on the character baselines instead of centers.
Definition qgis.h:3190
Abstract base class for annotation item edit operations.
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.
Annotation item edit operation consisting of rotating an item.
double angle() const
Returns the rotation angle value (in degrees clockwise).
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.
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.
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.
QString text() const
Returns the text rendered by the item.
~QgsAnnotationLineTextItem() override
void setTextAnchor(Qgis::TextAnchorPoint anchor)
Sets the text anchor, which dictates where the text will be placed on the line.
Qgis::TextAnchorPoint textAnchor() const
Returns the text anchor, which dictates where the text will be placed on the line.
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:36
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.
Represents a 2D point.
Definition qgspointxy.h:62
double y
Definition qgspointxy.h:66
double x
Definition qgspointxy.h:65
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:53
A container for the context for various read/write operations on 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.
static void drawTextOnLine(const QPolygonF &line, const QString &text, QgsRenderContext &context, const QgsTextFormat &format, double offsetAlongLine=0, double offsetFromLine=0, Qgis::CurvedTextFlags flags=Qgis::CurvedTextFlag::UseBaselinePlacement|Qgis::CurvedTextFlag::TruncateStringWhenLineIsTooShort, Qgis::TextAnchorPoint textAnchor=Qgis::TextAnchorPoint::StartOfText)
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.
T qgsEnumKeyToValue(const QString &key, const T &defaultValue, bool tryValueAsKey=true, bool *returnOk=nullptr)
Returns the value corresponding to the given key of an enum.
Definition qgis.h:7672
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
Definition qgis.h:7324
QString qgsEnumValueToKey(const T &value, bool *returnOk=nullptr)
Returns the value for the given key of an enum.
Definition qgis.h:7653
T qgsgeometry_cast(QgsAbstractGeometry *geom)
Utility class for identifying a unique vertex within a geometry.
Definition qgsvertexid.h:35