QGIS API Documentation 3.30.0-'s-Hertogenbosch (f186b8efe0)
qgstextlabelfeature.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgstextlabelfeature.cpp
3 ---------------------
4 begin : December 2015
5 copyright : (C) 2015 by Martin Dobias
6 email : wonder dot sk at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
16#include "qgstextlabelfeature.h"
17
18#include "qgspallabeling.h"
19#include "qgsmaptopixel.h"
21#include "qgstextfragment.h"
22#include "qgstextblock.h"
23
24// to match QTextEngine handling of superscript/subscript font sizes
26
27
29 : QgsLabelFeature( id, std::move( geometry ), size )
30{
31 mDefinedFont = QFont();
32}
33
35
36QString QgsTextLabelFeature::text( int partId ) const
37{
38 if ( partId == -1 )
39 return mLabelText;
40 else
41 return mTextMetrics->grapheme( partId );
42}
43
45{
46 return mTextMetrics.has_value() ? mTextMetrics->graphemeFormat( partId ) : QgsTextCharacterFormat();
47}
48
50{
51 return mTextMetrics.has_value() && partId < mTextMetrics->graphemeFormatCount();
52}
53
54QgsPrecalculatedTextMetrics QgsTextLabelFeature::calculateTextMetrics( const QgsMapToPixel *xform, const QgsRenderContext &context, const QFont &baseFont, const QFontMetricsF &fontMetrics, double letterSpacing, double wordSpacing, const QString &text, QgsTextDocument *document, QgsTextDocumentMetrics * )
55{
56 // create label info!
57 const double mapScale = xform->mapUnitsPerPixel();
58 QStringList graphemes;
59 QVector< QgsTextCharacterFormat > graphemeFormats;
60
61 if ( document )
62 {
63 for ( const QgsTextBlock &block : std::as_const( *document ) )
64 {
65 for ( const QgsTextFragment &fragment : block )
66 {
67 const QStringList fragmentGraphemes = QgsPalLabeling::splitToGraphemes( fragment.text() );
68 for ( const QString &grapheme : fragmentGraphemes )
69 {
70 graphemes.append( grapheme );
71 graphemeFormats.append( fragment.characterFormat() );
72 }
73 }
74 }
75 }
76 else
77 {
78 //split string by valid grapheme boundaries - required for certain scripts (see #6883)
80 }
81
82 QVector< double > characterWidths( graphemes.count() );
83 QVector< double > characterHeights( graphemes.count() );
84 QVector< double > characterDescents( graphemes.count() );
85
86 QFont previousNonSuperSubScriptFont;
87
88 for ( int i = 0; i < graphemes.count(); i++ )
89 {
90 // reconstruct how Qt creates word spacing, then adjust per individual stored character
91 // this will allow PAL to create each candidate width = character width + correct spacing
92
93 double graphemeFirstCharHorizontalAdvanceWithLetterSpacing = 0;
94 double graphemeFirstCharHorizontalAdvance = 0;
95 double graphemeHorizontalAdvance = 0;
96 double characterDescent = 0;
97 double characterHeight = 0;
98 if ( const QgsTextCharacterFormat *graphemeFormat = !graphemeFormats.empty() ? &graphemeFormats[i] : nullptr )
99 {
100 QFont graphemeFont = baseFont;
101 graphemeFormat->updateFontForFormat( graphemeFont, context, 1 );
102
103 if ( i == 0 )
104 previousNonSuperSubScriptFont = graphemeFont;
105
106 if ( graphemeFormat->hasVerticalAlignmentSet() )
107 {
108 switch ( graphemeFormat->verticalAlignment() )
109 {
111 previousNonSuperSubScriptFont = graphemeFont;
112 break;
113
116 {
117 if ( graphemeFormat->fontPointSize() < 0 )
118 {
119 // if fragment has no explicit font size set, then we scale the inherited font size to 60% of base font size
120 // this allows for easier use of super/subscript in labels as "my text<sup>2</sup>" will automatically render
121 // the superscript in a smaller font size. BUT if the fragment format HAS a non -1 font size then it indicates
122 // that the document has an explicit font size for the super/subscript element, eg "my text<sup style="font-size: 6pt">2</sup>"
123 // which we should respect
124 graphemeFont.setPixelSize( static_cast< int >( std::round( graphemeFont.pixelSize() * SUPERSCRIPT_SUBSCRIPT_FONT_SIZE_SCALING_FACTOR ) ) );
125 }
126 break;
127 }
128 }
129 }
130 else
131 {
132 previousNonSuperSubScriptFont = graphemeFont;
133 }
134
135 const QFontMetricsF graphemeFontMetrics( graphemeFont );
136 graphemeFirstCharHorizontalAdvance = graphemeFontMetrics.horizontalAdvance( QString( graphemes[i].at( 0 ) ) );
137 graphemeFirstCharHorizontalAdvanceWithLetterSpacing = graphemeFontMetrics.horizontalAdvance( graphemes[i].at( 0 ) ) + letterSpacing;
138 graphemeHorizontalAdvance = graphemeFontMetrics.horizontalAdvance( QString( graphemes[i] ) );
139 characterDescent = graphemeFontMetrics.descent();
140 characterHeight = graphemeFontMetrics.height();
141 }
142 else
143 {
144 graphemeFirstCharHorizontalAdvance = fontMetrics.horizontalAdvance( QString( graphemes[i].at( 0 ) ) );
145 graphemeFirstCharHorizontalAdvanceWithLetterSpacing = fontMetrics.horizontalAdvance( graphemes[i].at( 0 ) ) + letterSpacing;
146 graphemeHorizontalAdvance = fontMetrics.horizontalAdvance( QString( graphemes[i] ) );
147 characterDescent = fontMetrics.descent();
148 characterHeight = fontMetrics.height();
149 }
150
151 qreal wordSpaceFix = qreal( 0.0 );
152 if ( graphemes[i] == QLatin1String( " " ) )
153 {
154 // word spacing only gets added once at end of consecutive run of spaces, see QTextEngine::shapeText()
155 int nxt = i + 1;
156 wordSpaceFix = ( nxt < graphemes.count() && graphemes[nxt] != QLatin1String( " " ) ) ? wordSpacing : qreal( 0.0 );
157 }
158
159 // this workaround only works for clusters with a single character. Not sure how it should be handled
160 // with multi-character clusters.
161 if ( graphemes[i].length() == 1 &&
162 !qgsDoubleNear( graphemeFirstCharHorizontalAdvance, graphemeFirstCharHorizontalAdvanceWithLetterSpacing ) )
163 {
164 // word spacing applied when it shouldn't be
165 wordSpaceFix -= wordSpacing;
166 }
167
168 const double charWidth = graphemeHorizontalAdvance + wordSpaceFix;
169 characterWidths[i] = mapScale * charWidth;
170 characterHeights[i] = mapScale * characterHeight;
171 characterDescents[i] = mapScale * characterDescent;
172 }
173
174 QgsPrecalculatedTextMetrics res( graphemes, std::move( characterWidths ), std::move( characterHeights ), std::move( characterDescents ) );
175 res.setGraphemeFormats( graphemeFormats );
176 return res;
177}
178
180{
181 return mDocument;
182}
183
185{
186 return mDocumentMetrics;
187}
188
190{
192 mDocumentMetrics = metrics;
193}
@ Normal
Adjacent characters are positioned in the standard way for text in the writing system in use.
@ SubScript
Characters are placed below the base line for normal text.
@ SuperScript
Characters are placed above the base line for normal text.
The QgsLabelFeature class describes a feature that should be used within the labeling engine.
QString mLabelText
text of the label
Perform transforms between map coordinates and device coordinates.
Definition: qgsmaptopixel.h:39
double mapUnitsPerPixel() const
Returns the current map units per pixel.
static QStringList splitToGraphemes(const QString &text)
Splits a text string to a list of graphemes, which are the smallest allowable character divisions in ...
Contains precalculated properties regarding text metrics for text to be renderered at a later stage.
void setGraphemeFormats(const QVector< QgsTextCharacterFormat > &formats)
Sets the character formats associated with the text graphemes().
Contains information about the context of a rendering operation.
Represents a block of text consisting of one or more QgsTextFragment objects.
Definition: qgstextblock.h:36
Stores information relating to individual character formatting.
Contains pre-calculated metrics of a QgsTextDocument.
Represents a document consisting of one or more QgsTextBlock objects.
Stores a fragment of text along with formatting overrides to be used when rendering the fragment.
QgsTextLabelFeature(QgsFeatureId id, geos::unique_ptr geometry, QSizeF size)
Construct text label feature.
QgsTextDocument document() const
Returns the document for the label.
static QgsPrecalculatedTextMetrics calculateTextMetrics(const QgsMapToPixel *xform, const QgsRenderContext &context, const QFont &baseFont, const QFontMetricsF &fontMetrics, double letterSpacing, double wordSpacing, const QString &text=QString(), QgsTextDocument *document=nullptr, QgsTextDocumentMetrics *metrics=nullptr)
Calculate text metrics for later retrieval via textMetrics().
QgsTextDocument mDocument
~QgsTextLabelFeature() override
Clean up.
QgsTextCharacterFormat characterFormat(int partId) const
Returns the character format corresponding to the specified label part.
QFont mDefinedFont
Font for rendering.
QgsTextDocumentMetrics mDocumentMetrics
QgsTextDocumentMetrics documentMetrics() const
Returns the document metrics for the label.
QString text(int partId) const
Returns the text component corresponding to a specified label part.
bool hasCharacterFormat(int partId) const
Returns true if the feature contains specific character formatting for the part with matching ID.
std::optional< QgsPrecalculatedTextMetrics > mTextMetrics
void setDocument(const QgsTextDocument &document, const QgsTextDocumentMetrics &metrics)
Sets the document and document metrics for the label.
std::unique_ptr< GEOSGeometry, GeosDeleter > unique_ptr
Scoped GEOS pointer.
Definition: qgsgeos.h:74
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition: qgis.h:3509
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
Definition: qgsfeatureid.h:28
constexpr double SUPERSCRIPT_SUBSCRIPT_FONT_SIZE_SCALING_FACTOR