QGIS API Documentation 3.40.0-Bratislava (b56115d8743)
Loading...
Searching...
No Matches
qgstextdocument.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgstextdocument.cpp
3 -----------------
4 begin : May 2020
5 copyright : (C) Nyall Dawson
6 email : nyall dot dawson 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 "qgstextdocument.h"
17#include "qgis.h"
18#include "qgsstringutils.h"
19#include "qgstextblock.h"
20#include "qgstextfragment.h"
21#include "qgstextformat.h"
22
23#include <QTextDocument>
24#include <QTextBlock>
25
26
28
30
32{
33 mBlocks.append( block );
34}
35
37{
38 mBlocks.append( QgsTextBlock( fragment ) );
39}
40
42{
43 QgsTextDocument document;
44 document.reserve( lines.size() );
45 for ( const QString &line : lines )
46 {
47 document.append( QgsTextBlock::fromPlainText( line ) );
48 }
49 return document;
50}
51
52// Note -- must start and end with spaces, so that a tab character within
53// a html or css tag doesn't mess things up. Instead, Qt will just silently
54// ignore html attributes it doesn't know about, like this replacement string
55#define TAB_REPLACEMENT_MARKER " ignore_me_i_am_a_tab "
56
57QgsTextDocument QgsTextDocument::fromHtml( const QStringList &lines )
58{
59 QgsTextDocument document;
60
61 document.reserve( lines.size() );
62
63 for ( const QString &l : std::as_const( lines ) )
64 {
65 QString line = l;
66 // QTextDocument is a very heavy way of parsing HTML + css (it's heavily geared toward an editable text document,
67 // and includes a LOT of calculations we don't need, when all we're after is a HTML + CSS style parser).
68 // TODO - try to find an alternative library we can use here
69
70 QTextDocument sourceDoc;
71
72 // QTextDocument will replace tab characters with a space. We need to hack around this
73 // by first replacing it with a string which QTextDocument won't mess with, and then
74 // handle these markers as tab characters in the parsed HTML document.
75 line.replace( QString( '\t' ), QStringLiteral( TAB_REPLACEMENT_MARKER ) );
76
77 // cheat a little. Qt css requires word-spacing to have the "px" suffix. But we don't treat word spacing
78 // as pixels, because that doesn't scale well with different dpi render targets! So let's instead use just instead treat the suffix as
79 // optional, and ignore ANY unit suffix the user has put, and then replace it with "px" so that Qt's css parsing engine can process it
80 // correctly...
81 const thread_local QRegularExpression sRxWordSpacingFix( QStringLiteral( "word-spacing:\\s*(-?\\d+(?:\\.\\d+)?)([a-zA-Z]*)" ) );
82 line.replace( sRxWordSpacingFix, QStringLiteral( "word-spacing: \\1px" ) );
83
84 sourceDoc.setHtml( line );
85
86 QTextBlock sourceBlock = sourceDoc.firstBlock();
87
88 while ( true )
89 {
90 const int headingLevel = sourceBlock.blockFormat().headingLevel();
91 QgsTextCharacterFormat blockFormat;
92 if ( headingLevel > 0 )
93 {
94 switch ( headingLevel )
95 {
96 case 1:
97 blockFormat.setFontPercentageSize( 21.0 / 12 );
98 break;
99 case 2:
100 blockFormat.setFontPercentageSize( 16.0 / 12 );
101 break;
102 case 3:
103 blockFormat.setFontPercentageSize( 13.0 / 12 );
104 break;
105 case 4:
106 blockFormat.setFontPercentageSize( 11.0 / 12 );
107 break;
108 case 5:
109 blockFormat.setFontPercentageSize( 8.0 / 12 );
110 break;
111 case 6:
112 blockFormat.setFontPercentageSize( 7.0 / 12 );
113 break;
114 default:
115 break;
116 }
117 }
118
119 auto it = sourceBlock.begin();
120 QgsTextBlock block;
121 block.setBlockFormat( QgsTextBlockFormat( sourceBlock.blockFormat() ) );
122 while ( !it.atEnd() )
123 {
124 const QTextFragment fragment = it.fragment();
125 if ( fragment.isValid() )
126 {
127 // Search for line breaks in the fragment
128 const QString fragmentText = fragment.text();
129 if ( fragmentText.contains( QStringLiteral( "\u2028" ) ) )
130 {
131 // Split fragment text into lines
132 const QStringList splitLines = fragmentText.split( QStringLiteral( "\u2028" ), Qt::SplitBehaviorFlags::SkipEmptyParts );
133
134 for ( const QString &splitLine : std::as_const( splitLines ) )
135 {
136 const QgsTextCharacterFormat *previousFormat = nullptr;
137
138 // If the splitLine is not the first, inherit style from previous fragment
139 if ( splitLine != splitLines.first() && document.size() > 0 )
140 {
141 previousFormat = &document.at( document.size() - 1 ).at( 0 ).characterFormat();
142 }
143
144 if ( splitLine.contains( QStringLiteral( TAB_REPLACEMENT_MARKER ) ) )
145 {
146 // split line by tab characters, each tab should be a
147 // fragment by itself
148 QgsTextFragment splitFragment( fragment );
149 QgsTextCharacterFormat newFormat { splitFragment.characterFormat() };
150 newFormat.overrideWith( blockFormat );
151 if ( previousFormat )
152 {
153 // Apply overrides from previous fragment
154 newFormat.overrideWith( *previousFormat );
155 splitFragment.setCharacterFormat( newFormat );
156 }
157 splitFragment.setCharacterFormat( newFormat );
158
159 const QStringList tabSplit = splitLine.split( QStringLiteral( TAB_REPLACEMENT_MARKER ) );
160 int index = 0;
161 for ( const QString &part : tabSplit )
162 {
163 if ( !part.isEmpty() )
164 {
165 splitFragment.setText( part );
166 block.append( splitFragment );
167 }
168 if ( index != tabSplit.size() - 1 )
169 {
170 block.append( QgsTextFragment( QString( '\t' ) ) );
171 }
172 index++;
173 }
174 }
175 else
176 {
177 QgsTextFragment splitFragment( fragment );
178 splitFragment.setText( splitLine );
179
180 QgsTextCharacterFormat newFormat { splitFragment.characterFormat() };
181 newFormat.overrideWith( blockFormat );
182 if ( previousFormat )
183 {
184 // Apply overrides from previous fragment
185 newFormat.overrideWith( *previousFormat );
186 }
187 splitFragment.setCharacterFormat( newFormat );
188
189 block.append( splitFragment );
190 }
191
192 document.append( block );
193 block = QgsTextBlock();
194 block.setBlockFormat( QgsTextBlockFormat( sourceBlock.blockFormat() ) );
195 }
196 }
197 else if ( fragmentText.contains( QStringLiteral( TAB_REPLACEMENT_MARKER ) ) )
198 {
199 // split line by tab characters, each tab should be a
200 // fragment by itself
201 QgsTextFragment tmpFragment( fragment );
202
203 QgsTextCharacterFormat newFormat { tmpFragment.characterFormat() };
204 newFormat.overrideWith( blockFormat );
205 tmpFragment.setCharacterFormat( newFormat );
206
207 const QStringList tabSplit = fragmentText.split( QStringLiteral( TAB_REPLACEMENT_MARKER ) );
208 int index = 0;
209 for ( const QString &part : tabSplit )
210 {
211 if ( !part.isEmpty() )
212 {
213 tmpFragment.setText( part );
214 block.append( tmpFragment );
215 }
216 if ( index != tabSplit.size() - 1 )
217 {
218 block.append( QgsTextFragment( QString( '\t' ) ) );
219 }
220 index++;
221 }
222 }
223 else
224 {
225 QgsTextFragment tmpFragment( fragment );
226 QgsTextCharacterFormat newFormat { tmpFragment.characterFormat() };
227 newFormat.overrideWith( blockFormat );
228 tmpFragment.setCharacterFormat( newFormat );
229
230 block.append( tmpFragment );
231 }
232 }
233 it++;
234 }
235
236 if ( !block.empty() )
237 document.append( block );
238
239 sourceBlock = sourceBlock.next();
240 if ( !sourceBlock.isValid() )
241 break;
242 }
243 }
244
245 return document;
246}
247
248QgsTextDocument QgsTextDocument::fromTextAndFormat( const QStringList &lines, const QgsTextFormat &format )
249{
250 QgsTextDocument doc;
251 if ( !format.allowHtmlFormatting() || lines.isEmpty() )
252 {
253 doc = QgsTextDocument::fromPlainText( lines );
254 }
255 else
256 {
257 doc = QgsTextDocument::fromHtml( lines );
258 }
259 if ( doc.size() > 0 )
260 doc.applyCapitalization( format.capitalization() );
261 return doc;
262}
263
265{
266 mBlocks.append( block );
267}
268
270{
271 mBlocks.push_back( block );
272}
273
274void QgsTextDocument::insert( int index, const QgsTextBlock &block )
275{
276 mBlocks.insert( index, block );
277}
278
279void QgsTextDocument::insert( int index, QgsTextBlock &&block )
280{
281 mBlocks.insert( index, block );
282}
283
285{
286 mBlocks.reserve( count );
287}
288
290{
291 return mBlocks.at( i );
292}
293
295{
296 return mBlocks[i];
297}
298
300{
301 return mBlocks.size();
302}
303
305{
306 QStringList textLines;
307 textLines.reserve( mBlocks.size() );
308 for ( const QgsTextBlock &block : mBlocks )
309 {
310 QString line;
311 for ( const QgsTextFragment &fragment : block )
312 {
313 line.append( fragment.text() );
314 }
315 textLines << line;
316 }
317 return textLines;
318}
319
320void QgsTextDocument::splitLines( const QString &wrapCharacter, int autoWrapLength, bool useMaxLineLengthWhenAutoWrapping )
321{
322 const QVector< QgsTextBlock > prevBlocks = mBlocks;
323 mBlocks.clear();
324 mBlocks.reserve( prevBlocks.size() );
325 for ( const QgsTextBlock &block : prevBlocks )
326 {
327 QgsTextBlock destinationBlock;
328 destinationBlock.setBlockFormat( block.blockFormat() );
329 for ( const QgsTextFragment &fragment : block )
330 {
331 QStringList thisParts;
332 if ( !wrapCharacter.isEmpty() && wrapCharacter != QLatin1String( "\n" ) )
333 {
334 //wrap on both the wrapchr and new line characters
335 const QStringList lines = fragment.text().split( wrapCharacter );
336 for ( const QString &line : lines )
337 {
338 thisParts.append( line.split( '\n' ) );
339 }
340 }
341 else
342 {
343 thisParts = fragment.text().split( '\n' );
344 }
345
346 // apply auto wrapping to each manually created line
347 if ( autoWrapLength != 0 )
348 {
349 QStringList autoWrappedLines;
350 autoWrappedLines.reserve( thisParts.count() );
351 for ( const QString &line : std::as_const( thisParts ) )
352 {
353 autoWrappedLines.append( QgsStringUtils::wordWrap( line, autoWrapLength, useMaxLineLengthWhenAutoWrapping ).split( '\n' ) );
354 }
355 thisParts = autoWrappedLines;
356 }
357
358 if ( thisParts.empty() )
359 continue;
360 else if ( thisParts.size() == 1 )
361 destinationBlock.append( fragment );
362 else
363 {
364 if ( !thisParts.at( 0 ).isEmpty() )
365 destinationBlock.append( QgsTextFragment( thisParts.at( 0 ), fragment.characterFormat() ) );
366
367 append( destinationBlock );
368 destinationBlock.clear();
369 for ( int i = 1 ; i < thisParts.size() - 1; ++i )
370 {
371 QgsTextBlock partBlock( QgsTextFragment( thisParts.at( i ), fragment.characterFormat() ) );
372 partBlock.setBlockFormat( block.blockFormat() );
373 append( partBlock );
374 }
375 destinationBlock.append( QgsTextFragment( thisParts.at( thisParts.size() - 1 ), fragment.characterFormat() ) );
376 }
377 }
378 append( destinationBlock );
379 }
380}
381
383{
384 for ( QgsTextBlock &block : mBlocks )
385 {
386 block.applyCapitalization( capitalization );
387 }
388}
389
391QVector< QgsTextBlock >::const_iterator QgsTextDocument::begin() const
392{
393 return mBlocks.begin();
394}
395
396QVector< QgsTextBlock >::const_iterator QgsTextDocument::end() const
397{
398 return mBlocks.end();
399}
Capitalization
String capitalization options.
Definition qgis.h:3132
static QString wordWrap(const QString &string, int length, bool useMaxLineLength=true, const QString &customDelimiter=QString())
Automatically wraps a string by inserting new line characters at appropriate locations in the string.
Stores information relating to individual block formatting.
Represents a block of text consisting of one or more QgsTextFragment objects.
void clear()
Clears the block, removing all its contents.
static QgsTextBlock fromPlainText(const QString &text, const QgsTextCharacterFormat &format=QgsTextCharacterFormat())
Constructor for QgsTextBlock consisting of a plain text, and optional character format.
void setBlockFormat(const QgsTextBlockFormat &format)
Sets the block format for the fragment.
void append(const QgsTextFragment &fragment)
Appends a fragment to the block.
bool empty() const
Returns true if the block is empty.
Stores information relating to individual character formatting.
void overrideWith(const QgsTextCharacterFormat &other)
Override all the default/unset properties of the current character format with the settings from anot...
void setFontPercentageSize(double size)
Sets the font percentage size (as fraction of inherited font size).
Represents a document consisting of one or more QgsTextBlock objects.
void splitLines(const QString &wrapCharacter, int autoWrapLength=0, bool useMaxLineLengthWhenAutoWrapping=true)
Splits lines of text in the document to separate lines, using a specified wrap character (wrapCharact...
QgsTextBlock & operator[](int index)
Returns the block at the specified index.
const QgsTextBlock & at(int index) const
Returns the block at the specified index.
void reserve(int count)
Reserves the specified count of blocks for optimised block appending.
QStringList toPlainText() const
Returns a list of plain text lines of text representing the document.
int size() const
Returns the number of blocks in the document.
static QgsTextDocument fromHtml(const QStringList &lines)
Constructor for QgsTextDocument consisting of a set of HTML formatted lines.
static QgsTextDocument fromPlainText(const QStringList &lines)
Constructor for QgsTextDocument consisting of a set of plain text lines.
void append(const QgsTextBlock &block)
Appends a block to the document.
void insert(int index, const QgsTextBlock &block)
Inserts a block into the document, at the specified index.
static QgsTextDocument fromTextAndFormat(const QStringList &lines, const QgsTextFormat &format)
Constructor for QgsTextDocument consisting of a set of lines, respecting settings from a text format.
void applyCapitalization(Qgis::Capitalization capitalization)
Applies a capitalization style to the document's text.
Container for all settings relating to text rendering.
Qgis::Capitalization capitalization() const
Returns the text capitalization style.
bool allowHtmlFormatting() const
Returns true if text should be treated as a HTML document and HTML tags should be used for formatting...
Stores a fragment of document along with formatting overrides to be used when rendering the fragment.
void setText(const QString &text)
Sets the text content of the fragment.
void setCharacterFormat(const QgsTextCharacterFormat &format)
Sets the character format for the fragment.
const QgsTextCharacterFormat & characterFormat() const
Returns the character formatting for the fragment.
#define TAB_REPLACEMENT_MARKER