Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qquicktextnodeengine.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
6
7#include <QtCore/qpoint.h>
8#include <QtGui/qabstracttextdocumentlayout.h>
9#include <QtGui/qrawfont.h>
10#include <QtGui/qtextdocument.h>
11#include <QtGui/qtextlayout.h>
12#include <QtGui/qtextobject.h>
13#include <QtGui/qtexttable.h>
14#include <QtGui/qtextlist.h>
15#include <QtGui/qimageiohandler.h>
16
17#include <private/qquicktext_p.h>
18#include <private/qtextdocumentlayout_p.h>
19#include <private/qtextimagehandler_p.h>
20#include <private/qrawfont_p.h>
21#include <private/qglyphrun_p.h>
22#include <private/qquickitem_p.h>
23#include <private/qsgdistancefieldglyphnode_p.h>
24
26
28 : fontEngine(QRawFontPrivate::get(node->glyphRun.rawFont())->fontEngine)
29 , clipNode(node->clipNode)
30 , color(node->color.rgba())
31 , selectionState(node->selectionState)
32{
33}
34
36 SelectionState selState,
37 const QRectF &brect,
38 const Decorations &decs,
39 const QColor &c,
40 const QColor &bc, const QColor &dc,
41 const QPointF &pos, qreal a)
42 : glyphRun(g)
45 , clipNode(nullptr)
47 , color(c)
50 , position(pos)
51 , ascent(a)
52 , leftChildIndex(-1)
53 , rightChildIndex(-1)
54{
55 QGlyphRunPrivate *d = QGlyphRunPrivate::get(g);
56 ranges.append(std::make_pair(d->textRangeStart, d->textRangeEnd));
57}
58
59
60void QQuickTextNodeEngine::BinaryTreeNode::insert(QVarLengthArray<BinaryTreeNode, 16> *binaryTree, const QGlyphRun &glyphRun, SelectionState selectionState,
61 Decorations decorations, const QColor &textColor,
62 const QColor &backgroundColor, const QColor &decorationColor, const QPointF &position)
63{
64 QRectF searchRect = glyphRun.boundingRect();
65 searchRect.translate(position);
66
67 if (qFuzzyIsNull(searchRect.width()) || qFuzzyIsNull(searchRect.height()))
68 return;
69
70 decorations |= (glyphRun.underline() ? Decoration::Underline : Decoration::NoDecoration);
71 decorations |= (glyphRun.overline() ? Decoration::Overline : Decoration::NoDecoration);
72 decorations |= (glyphRun.strikeOut() ? Decoration::StrikeOut : Decoration::NoDecoration);
73 decorations |= (backgroundColor.isValid() ? Decoration::Background : Decoration::NoDecoration);
74
75 qreal ascent = glyphRun.rawFont().ascent();
76 insert(binaryTree, BinaryTreeNode(glyphRun,
77 selectionState,
78 searchRect,
79 decorations,
80 textColor,
81 backgroundColor,
82 decorationColor,
83 position,
84 ascent));
85}
86
87void QQuickTextNodeEngine::BinaryTreeNode::insert(QVarLengthArray<BinaryTreeNode, 16> *binaryTree, const BinaryTreeNode &binaryTreeNode)
88{
89 int newIndex = binaryTree->size();
90 binaryTree->append(binaryTreeNode);
91 if (newIndex == 0)
92 return;
93
94 int searchIndex = 0;
95 forever {
96 BinaryTreeNode *node = binaryTree->data() + searchIndex;
97 if (binaryTreeNode.boundingRect.left() < node->boundingRect.left()) {
98 if (node->leftChildIndex < 0) {
99 node->leftChildIndex = newIndex;
100 break;
101 } else {
102 searchIndex = node->leftChildIndex;
103 }
104 } else {
105 if (node->rightChildIndex < 0) {
106 node->rightChildIndex = newIndex;
107 break;
108 } else {
109 searchIndex = node->rightChildIndex;
110 }
111 }
112 }
113}
114
115void QQuickTextNodeEngine::BinaryTreeNode::inOrder(const QVarLengthArray<BinaryTreeNode, 16> &binaryTree,
116 QVarLengthArray<int> *sortedIndexes, int currentIndex)
117{
118 Q_ASSERT(currentIndex < binaryTree.size());
119
120 const BinaryTreeNode *node = binaryTree.data() + currentIndex;
121 if (node->leftChildIndex >= 0)
122 inOrder(binaryTree, sortedIndexes, node->leftChildIndex);
123
124 sortedIndexes->append(currentIndex);
125
126 if (node->rightChildIndex >= 0)
127 inOrder(binaryTree, sortedIndexes, node->rightChildIndex);
128}
129
130
131int QQuickTextNodeEngine::addText(const QTextBlock &block,
132 const QTextCharFormat &charFormat,
133 const QColor &textColor,
134 const QVarLengthArray<QTextLayout::FormatRange> &colorChanges,
135 int textPos, int fragmentEnd,
136 int selectionStart, int selectionEnd)
137{
138 if (charFormat.foreground().style() != Qt::NoBrush)
139 setTextColor(charFormat.foreground().color());
140 else
141 setTextColor(textColor);
142
143 while (textPos < fragmentEnd) {
144 int blockRelativePosition = textPos - block.position();
145 QTextLine line = block.layout()->lineForTextPosition(blockRelativePosition);
146 if (!line.isValid())
147 break;
148 if (!currentLine().isValid()
149 || line.lineNumber() != currentLine().lineNumber()) {
151 }
152
153 Q_ASSERT(line.textLength() > 0);
154 int lineEnd = line.textStart() + block.position() + line.textLength();
155
156 int len = qMin(lineEnd - textPos, fragmentEnd - textPos);
157 Q_ASSERT(len > 0);
158
159 int currentStepEnd = textPos + len;
160
161 addGlyphsForRanges(colorChanges,
162 textPos - block.position(),
163 currentStepEnd - block.position(),
164 selectionStart - block.position(),
165 selectionEnd - block.position());
166
167 textPos = currentStepEnd;
168 }
169 return textPos;
170}
171
172void QQuickTextNodeEngine::addTextDecorations(const QVarLengthArray<TextDecoration> &textDecorations,
173 qreal offset, qreal thickness)
174{
175 for (auto textDecoration : textDecorations) {
176 QRectF &rect = textDecoration.rect;
177 rect.setY(qRound(rect.y() + m_currentLine.ascent() + offset));
178 rect.setHeight(thickness);
179
180 m_lines.append(textDecoration);
181 }
182}
183
184void QQuickTextNodeEngine::processCurrentLine()
185{
186 // No glyphs, do nothing
187 if (m_currentLineTree.isEmpty())
188 return;
189
190 // 1. Go through current line and get correct decoration position for each node based on
191 // neighbouring decorations. Add decoration to global list
192 // 2. Create clip nodes for all selected text. Try to merge as many as possible within
193 // the line.
194 // 3. Add QRects to a list of selection rects.
195 // 4. Add all nodes to a global processed list
196 QVarLengthArray<int> sortedIndexes; // Indexes in tree sorted by x position
197 BinaryTreeNode::inOrder(m_currentLineTree, &sortedIndexes);
198
199 Q_ASSERT(sortedIndexes.size() == m_currentLineTree.size());
200
201 SelectionState currentSelectionState = Unselected;
202 QRectF currentRect;
203
204 Decorations currentDecorations = Decoration::NoDecoration;
205 qreal underlineOffset = 0.0;
206 qreal underlineThickness = 0.0;
207
208 qreal overlineOffset = 0.0;
209 qreal overlineThickness = 0.0;
210
211 qreal strikeOutOffset = 0.0;
212 qreal strikeOutThickness = 0.0;
213
214 QRectF decorationRect = currentRect;
215
216 QColor lastColor;
217 QColor lastBackgroundColor;
218 QColor lastDecorationColor;
219
220 QVarLengthArray<TextDecoration> pendingUnderlines;
221 QVarLengthArray<TextDecoration> pendingOverlines;
222 QVarLengthArray<TextDecoration> pendingStrikeOuts;
223 if (!sortedIndexes.isEmpty()) {
224 QQuickDefaultClipNode *currentClipNode = m_hasSelection ? new QQuickDefaultClipNode(QRectF()) : nullptr;
225 bool currentClipNodeUsed = false;
226 for (int i=0; i<=sortedIndexes.size(); ++i) {
227 BinaryTreeNode *node = nullptr;
228 if (i < sortedIndexes.size()) {
229 int sortedIndex = sortedIndexes.at(i);
230 Q_ASSERT(sortedIndex < m_currentLineTree.size());
231
232 node = m_currentLineTree.data() + sortedIndex;
233 if (i == 0)
234 currentSelectionState = node->selectionState;
235 }
236
237 // Update decorations
238 if (currentDecorations != Decoration::NoDecoration) {
239 decorationRect.setY(m_position.y() + m_currentLine.y());
240 decorationRect.setHeight(m_currentLine.height());
241
242 if (node != nullptr)
243 decorationRect.setRight(node->boundingRect.left());
244
245 TextDecoration textDecoration(currentSelectionState, decorationRect, lastColor);
246 if (lastDecorationColor.isValid() &&
247 (currentDecorations.testFlag(Decoration::Underline) ||
248 currentDecorations.testFlag(Decoration::Overline) ||
249 currentDecorations.testFlag(Decoration::StrikeOut)))
250 textDecoration.color = lastDecorationColor;
251
252 if (currentDecorations & Decoration::Underline)
253 pendingUnderlines.append(textDecoration);
254
255 if (currentDecorations & Decoration::Overline)
256 pendingOverlines.append(textDecoration);
257
258 if (currentDecorations & Decoration::StrikeOut)
259 pendingStrikeOuts.append(textDecoration);
260
261 if (currentDecorations & Decoration::Background)
262 m_backgrounds.append(std::make_pair(decorationRect, lastBackgroundColor));
263 }
264
265 // If we've reached an unselected node from a selected node, we add the
266 // selection rect to the graph, and we add decoration every time the
267 // selection state changes, because that means the text color changes
268 if (node == nullptr || node->selectionState != currentSelectionState) {
269 currentRect.setY(m_position.y() + m_currentLine.y());
270 currentRect.setHeight(m_currentLine.height());
271
272 if (currentSelectionState == Selected)
273 m_selectionRects.append(currentRect);
274
275 if (currentClipNode != nullptr) {
276 if (!currentClipNodeUsed) {
277 delete currentClipNode;
278 } else {
279 currentClipNode->setIsRectangular(true);
280 currentClipNode->setRect(currentRect);
281 currentClipNode->update();
282 }
283 }
284
285 if (node != nullptr && m_hasSelection)
286 currentClipNode = new QQuickDefaultClipNode(QRectF());
287 else
288 currentClipNode = nullptr;
289 currentClipNodeUsed = false;
290
291 if (node != nullptr) {
292 currentSelectionState = node->selectionState;
293 currentRect = node->boundingRect;
294
295 // Make sure currentRect is valid, otherwise the unite won't work
296 if (currentRect.isNull())
297 currentRect.setSize(QSizeF(1, 1));
298 }
299 } else {
300 if (currentRect.isNull())
301 currentRect = node->boundingRect;
302 else
303 currentRect = currentRect.united(node->boundingRect);
304 }
305
306 if (node != nullptr) {
307 if (node->selectionState == Selected) {
308 node->clipNode = currentClipNode;
309 currentClipNodeUsed = true;
310 }
311
312 decorationRect = node->boundingRect;
313
314 // If previous item(s) had underline and current does not, then we add the
315 // pending lines to the lists and likewise for overlines and strikeouts
316 if (!pendingUnderlines.isEmpty()
317 && !(node->decorations & Decoration::Underline)) {
318 addTextDecorations(pendingUnderlines, underlineOffset, underlineThickness);
319
320 pendingUnderlines.clear();
321
322 underlineOffset = 0.0;
323 underlineThickness = 0.0;
324 }
325
326 // ### Add pending when overlineOffset/thickness changes to minimize number of
327 // nodes
328 if (!pendingOverlines.isEmpty()) {
329 addTextDecorations(pendingOverlines, overlineOffset, overlineThickness);
330
331 pendingOverlines.clear();
332
333 overlineOffset = 0.0;
334 overlineThickness = 0.0;
335 }
336
337 // ### Add pending when overlineOffset/thickness changes to minimize number of
338 // nodes
339 if (!pendingStrikeOuts.isEmpty()) {
340 addTextDecorations(pendingStrikeOuts, strikeOutOffset, strikeOutThickness);
341
342 pendingStrikeOuts.clear();
343
344 strikeOutOffset = 0.0;
345 strikeOutThickness = 0.0;
346 }
347
348 // Merge current values with previous. Prefer greatest thickness
349 QRawFont rawFont = node->glyphRun.rawFont();
350 if (node->decorations & Decoration::Underline) {
351 if (rawFont.lineThickness() > underlineThickness) {
352 underlineThickness = rawFont.lineThickness();
353 underlineOffset = rawFont.underlinePosition();
354 }
355 }
356
357 if (node->decorations & Decoration::Overline) {
358 overlineOffset = -rawFont.ascent();
359 overlineThickness = rawFont.lineThickness();
360 }
361
362 if (node->decorations & Decoration::StrikeOut) {
363 strikeOutThickness = rawFont.lineThickness();
364 strikeOutOffset = rawFont.ascent() / -3.0;
365 }
366
367 currentDecorations = node->decorations;
368 lastColor = node->color;
369 lastBackgroundColor = node->backgroundColor;
370 lastDecorationColor = node->decorationColor;
371 m_processedNodes.append(*node);
372 }
373 }
374
375 if (!pendingUnderlines.isEmpty())
376 addTextDecorations(pendingUnderlines, underlineOffset, underlineThickness);
377
378 if (!pendingOverlines.isEmpty())
379 addTextDecorations(pendingOverlines, overlineOffset, overlineThickness);
380
381 if (!pendingStrikeOuts.isEmpty())
382 addTextDecorations(pendingStrikeOuts, strikeOutOffset, strikeOutThickness);
383 }
384
385 m_currentLineTree.clear();
386 m_currentLine = QTextLine();
387 m_hasSelection = false;
388}
389
390void QQuickTextNodeEngine::addImage(const QRectF &rect, const QImage &image, qreal ascent,
391 SelectionState selectionState,
392 QTextFrameFormat::Position layoutPosition)
393{
394 QRectF searchRect = rect;
395 if (layoutPosition == QTextFrameFormat::InFlow) {
396 if (m_currentLineTree.isEmpty()) {
397 qreal y = m_currentLine.ascent() - ascent;
398 if (m_currentTextDirection == Qt::RightToLeft)
399 searchRect.moveTopRight(m_position + m_currentLine.rect().topRight() + QPointF(0, y));
400 else
401 searchRect.moveTopLeft(m_position + m_currentLine.position() + QPointF(0, y));
402 } else {
403 const BinaryTreeNode *lastNode = m_currentLineTree.data() + m_currentLineTree.size() - 1;
404 if (lastNode->glyphRun.isRightToLeft()) {
405 QPointF lastPos = lastNode->boundingRect.topLeft();
406 searchRect.moveTopRight(lastPos - QPointF(0, ascent - lastNode->ascent));
407 } else {
408 QPointF lastPos = lastNode->boundingRect.topRight();
409 searchRect.moveTopLeft(lastPos - QPointF(0, ascent - lastNode->ascent));
410 }
411 }
412 }
413
414 BinaryTreeNode::insert(&m_currentLineTree, searchRect, image, ascent, selectionState);
415 m_hasContents = true;
416}
417
418void QQuickTextNodeEngine::addTextObject(const QTextBlock &block, const QPointF &position, const QTextCharFormat &format,
419 SelectionState selectionState,
420 QTextDocument *textDocument, int pos,
421 QTextFrameFormat::Position layoutPosition)
422{
423 QTextObjectInterface *handler = textDocument->documentLayout()->handlerForObject(format.objectType());
424 if (handler != nullptr) {
425 QImage image;
426 QSizeF size = handler->intrinsicSize(textDocument, pos, format);
427
428 if (format.objectType() == QTextFormat::ImageObject) {
429 QTextImageFormat imageFormat = format.toImageFormat();
430 QTextImageHandler *imageHandler = static_cast<QTextImageHandler *>(handler);
431 image = imageHandler->image(textDocument, imageFormat);
432 }
433
434 if (image.isNull()) {
435 if (QImageIOHandler::allocateImage((size * m_devicePixelRatio).toSize(),
436 QImage::Format_ARGB32_Premultiplied,
437 &image)) {
438 image.setDevicePixelRatio(m_devicePixelRatio);
439 image.fill(Qt::transparent);
440 {
441 QPainter painter(&image);
442 handler->drawObject(&painter, QRectF({}, size), textDocument, pos, format);
443 }
444 }
445 }
446
447 // Use https://developer.mozilla.org/de/docs/Web/CSS/vertical-align as a reference
448 // The top/bottom positions are supposed to be higher/lower than the text and reference
449 // the line height, not the text height (using QFontMetrics)
450 qreal ascent;
451 QTextLine line = block.layout()->lineForTextPosition(pos - block.position());
452 switch (format.verticalAlignment())
453 {
454 case QTextCharFormat::AlignTop:
455 ascent = line.ascent();
456 break;
457 case QTextCharFormat::AlignMiddle:
458 // Middlepoint of line (height - descent) + Half object height
459 ascent = (line.ascent() + line.descent()) / 2 - line.descent() + size.height() / 2;
460 break;
461 case QTextCharFormat::AlignBottom:
462 ascent = size.height() - line.descent();
463 break;
464 case QTextCharFormat::AlignBaseline:
465 default:
466 ascent = size.height();
467 }
468
469 addImage(QRectF(position, size), image, ascent, selectionState, layoutPosition);
470 }
471}
472
473void QQuickTextNodeEngine::addUnselectedGlyphs(const QGlyphRun &glyphRun)
474{
475 BinaryTreeNode::insert(&m_currentLineTree,
476 glyphRun,
477 Unselected,
478 Decoration::NoDecoration,
479 m_textColor,
480 m_backgroundColor,
481 m_decorationColor,
482 m_position);
483}
484
485void QQuickTextNodeEngine::addSelectedGlyphs(const QGlyphRun &glyphRun)
486{
487 int currentSize = m_currentLineTree.size();
488 BinaryTreeNode::insert(&m_currentLineTree,
489 glyphRun,
490 Selected,
491 Decoration::NoDecoration,
492 m_textColor,
493 m_backgroundColor,
494 m_decorationColor,
495 m_position);
496 m_hasSelection = m_hasSelection || m_currentLineTree.size() > currentSize;
497}
498
499void QQuickTextNodeEngine::addGlyphsForRanges(const QVarLengthArray<QTextLayout::FormatRange> &ranges,
500 int start, int end,
501 int selectionStart, int selectionEnd)
502{
503 int currentPosition = start;
504 int remainingLength = end - start;
505 for (const QTextLayout::FormatRange &range : ranges) {
506 if (range.start + range.length > currentPosition
507 && range.start < currentPosition + remainingLength) {
508
509 if (range.start > currentPosition) {
510 addGlyphsInRange(currentPosition, range.start - currentPosition,
511 QColor(), QColor(), QColor(), selectionStart, selectionEnd);
512 }
513 int rangeEnd = qMin(range.start + range.length, currentPosition + remainingLength);
514 QColor rangeColor;
515 if (range.format.hasProperty(QTextFormat::ForegroundBrush))
516 rangeColor = range.format.foreground().color();
517 else if (range.format.isAnchor())
518 rangeColor = m_anchorColor;
519 QColor rangeBackgroundColor = range.format.hasProperty(QTextFormat::BackgroundBrush)
520 ? range.format.background().color()
521 : QColor();
522
523 QColor rangeDecorationColor = range.format.hasProperty(QTextFormat::TextUnderlineColor)
524 ? range.format.underlineColor()
525 : QColor();
526
527 addGlyphsInRange(range.start, rangeEnd - range.start,
528 rangeColor, rangeBackgroundColor, rangeDecorationColor,
529 selectionStart, selectionEnd);
530
531 currentPosition = range.start + range.length;
532 remainingLength = end - currentPosition;
533
534 } else if (range.start > currentPosition + remainingLength || remainingLength <= 0) {
535 break;
536 }
537 }
538
539 if (remainingLength > 0) {
540 addGlyphsInRange(currentPosition, remainingLength, QColor(), QColor(), QColor(),
541 selectionStart, selectionEnd);
542 }
543
544}
545
546void QQuickTextNodeEngine::addGlyphsInRange(int rangeStart, int rangeLength,
547 const QColor &color, const QColor &backgroundColor, const QColor &decorationColor,
548 int selectionStart, int selectionEnd)
549{
550 QColor oldColor;
551 if (color.isValid()) {
552 oldColor = m_textColor;
553 m_textColor = color;
554 }
555
556 QColor oldBackgroundColor = m_backgroundColor;
557 if (backgroundColor.isValid()) {
558 oldBackgroundColor = m_backgroundColor;
559 m_backgroundColor = backgroundColor;
560 }
561
562 QColor oldDecorationColor = m_decorationColor;
563 if (decorationColor.isValid()) {
564 oldDecorationColor = m_decorationColor;
565 m_decorationColor = decorationColor;
566 }
567
568 bool hasSelection = selectionEnd >= 0
569 && selectionStart <= selectionEnd;
570
571 QTextLine &line = m_currentLine;
572 int rangeEnd = rangeStart + rangeLength;
573 if (!hasSelection || (selectionStart > rangeEnd || selectionEnd < rangeStart)) {
574 const QList<QGlyphRun> glyphRuns = line.glyphRuns(rangeStart, rangeLength);
575 for (const QGlyphRun &glyphRun : glyphRuns)
576 addUnselectedGlyphs(glyphRun);
577 } else {
578 if (rangeStart < selectionStart) {
579 int length = qMin(selectionStart - rangeStart, rangeLength);
580 const QList<QGlyphRun> glyphRuns = line.glyphRuns(rangeStart, length);
581 for (const QGlyphRun &glyphRun : glyphRuns)
582 addUnselectedGlyphs(glyphRun);
583 }
584
585 if (rangeEnd > selectionStart) {
586 int start = qMax(selectionStart, rangeStart);
587 int length = qMin(selectionEnd - start + 1, rangeEnd - start);
588 const QList<QGlyphRun> glyphRuns = line.glyphRuns(start, length);
589 for (const QGlyphRun &glyphRun : glyphRuns)
590 addSelectedGlyphs(glyphRun);
591 }
592
593 if (selectionEnd >= rangeStart && selectionEnd < rangeEnd) {
594 int start = selectionEnd + 1;
595 int length = rangeEnd - selectionEnd - 1;
596 const QList<QGlyphRun> glyphRuns = line.glyphRuns(start, length);
597 for (const QGlyphRun &glyphRun : glyphRuns)
598 addUnselectedGlyphs(glyphRun);
599 }
600 }
601
602 if (decorationColor.isValid())
603 m_decorationColor = oldDecorationColor;
604
605 if (backgroundColor.isValid())
606 m_backgroundColor = oldBackgroundColor;
607
608 if (oldColor.isValid())
609 m_textColor = oldColor;
610}
611
612void QQuickTextNodeEngine::addBorder(const QRectF &rect, qreal border,
613 QTextFrameFormat::BorderStyle borderStyle,
614 const QBrush &borderBrush)
615{
616 const QColor &color = borderBrush.color();
617
618 // Currently we don't support other styles than solid
619 Q_UNUSED(borderStyle);
620
621 m_backgrounds.append(std::make_pair(QRectF(rect.left(), rect.top(), border, rect.height() + border), color));
622 m_backgrounds.append(std::make_pair(QRectF(rect.left() + border, rect.top(), rect.width(), border), color));
623 m_backgrounds.append(std::make_pair(QRectF(rect.right(), rect.top() + border, border, rect.height() - border), color));
624 m_backgrounds.append(std::make_pair(QRectF(rect.left() + border, rect.bottom(), rect.width(), border), color));
625}
626
627void QQuickTextNodeEngine::addFrameDecorations(QTextDocument *document, QTextFrame *frame)
628{
629 QTextDocumentLayout *documentLayout = qobject_cast<QTextDocumentLayout *>(document->documentLayout());
630 if (Q_UNLIKELY(!documentLayout))
631 return;
632
633 QTextFrameFormat frameFormat = frame->format().toFrameFormat();
634 QTextTable *table = qobject_cast<QTextTable *>(frame);
635
636 QRectF boundingRect = table == nullptr
637 ? documentLayout->frameBoundingRect(frame)
638 : documentLayout->tableBoundingRect(table);
639
640 QBrush bg = frame->frameFormat().background();
641 if (bg.style() != Qt::NoBrush)
642 m_backgrounds.append(std::make_pair(boundingRect, bg.color()));
643
644 if (!frameFormat.hasProperty(QTextFormat::FrameBorder))
645 return;
646
647 qreal borderWidth = frameFormat.border();
648 if (qFuzzyIsNull(borderWidth))
649 return;
650
651 QBrush borderBrush = frameFormat.borderBrush();
652 QTextFrameFormat::BorderStyle borderStyle = frameFormat.borderStyle();
653 if (borderStyle == QTextFrameFormat::BorderStyle_None)
654 return;
655
656 const auto collapsed = table->format().borderCollapse();
657
658 if (!collapsed) {
659 addBorder(boundingRect.adjusted(frameFormat.leftMargin(), frameFormat.topMargin(),
660 -frameFormat.rightMargin() - borderWidth,
661 -frameFormat.bottomMargin() - borderWidth),
662 borderWidth, borderStyle, borderBrush);
663 }
664 if (table != nullptr) {
665 int rows = table->rows();
666 int columns = table->columns();
667
668 for (int row=0; row<rows; ++row) {
669 for (int column=0; column<columns; ++column) {
670 QTextTableCell cell = table->cellAt(row, column);
671
672 QRectF cellRect = documentLayout->tableCellBoundingRect(table, cell);
673 addBorder(cellRect.adjusted(-borderWidth, -borderWidth, collapsed ? -borderWidth : 0, collapsed ? -borderWidth : 0), borderWidth,
674 borderStyle, borderBrush);
675 }
676 }
677 }
678}
679
681{
682 return qHashMulti(seed, key.fontEngine, key.clipNode, key.color, key.selectionState);
683}
684
685void QQuickTextNodeEngine::mergeProcessedNodes(QList<BinaryTreeNode *> *regularNodes,
686 QList<BinaryTreeNode *> *imageNodes)
687{
688 QHash<BinaryTreeNodeKey, QList<BinaryTreeNode *> > map;
689
690 for (int i = 0; i < m_processedNodes.size(); ++i) {
691 BinaryTreeNode *node = m_processedNodes.data() + i;
692
693 if (node->image.isNull()) {
694 if (node->glyphRun.isEmpty())
695 continue;
696
697 BinaryTreeNodeKey key(node);
698
699 QList<BinaryTreeNode *> &nodes = map[key];
700 if (nodes.isEmpty())
701 regularNodes->append(node);
702
703 nodes.append(node);
704 } else {
705 imageNodes->append(node);
706 }
707 }
708
709 for (int i = 0; i < regularNodes->size(); ++i) {
710 BinaryTreeNode *primaryNode = regularNodes->at(i);
711 BinaryTreeNodeKey key(primaryNode);
712
713 const QList<BinaryTreeNode *> &nodes = map.value(key);
714 Q_ASSERT(nodes.first() == primaryNode);
715
716 int count = 0;
717 for (int j = 0; j < nodes.size(); ++j)
718 count += nodes.at(j)->glyphRun.glyphIndexes().size();
719
720 if (count != primaryNode->glyphRun.glyphIndexes().size()) {
721 QGlyphRun &glyphRun = primaryNode->glyphRun;
722 QList<quint32> glyphIndexes = glyphRun.glyphIndexes();
723 glyphIndexes.reserve(count);
724
725 QList<QPointF> glyphPositions = glyphRun.positions();
726 glyphPositions.reserve(count);
727
728 QRectF glyphBoundingRect = glyphRun.boundingRect();
729
730 for (int j = 1; j < nodes.size(); ++j) {
731 BinaryTreeNode *otherNode = nodes.at(j);
732 glyphIndexes += otherNode->glyphRun.glyphIndexes();
733 primaryNode->ranges += otherNode->ranges;
734 glyphBoundingRect = glyphBoundingRect.united(otherNode->boundingRect);
735
736 QList<QPointF> otherPositions = otherNode->glyphRun.positions();
737 for (int k = 0; k < otherPositions.size(); ++k)
738 glyphPositions += otherPositions.at(k) + (otherNode->position - primaryNode->position);
739 }
740
741 Q_ASSERT(glyphPositions.size() == count);
742 Q_ASSERT(glyphIndexes.size() == count);
743
744 glyphRun.setGlyphIndexes(glyphIndexes);
745 glyphRun.setPositions(glyphPositions);
746 glyphRun.setBoundingRect(glyphBoundingRect);
747 }
748 }
749}
750
751void QQuickTextNodeEngine::addToSceneGraph(QSGInternalTextNode *parentNode,
752 QQuickText::TextStyle style,
753 const QColor &styleColor)
754{
755 if (m_currentLine.isValid())
756 processCurrentLine();
757
758 QList<BinaryTreeNode *> nodes;
759 QList<BinaryTreeNode *> imageNodes;
760 mergeProcessedNodes(&nodes, &imageNodes);
761
762 for (int i = 0; i < m_backgrounds.size(); ++i) {
763 const QRectF &rect = m_backgrounds.at(i).first;
764 const QColor &color = m_backgrounds.at(i).second;
765 if (color.alpha() != 0)
766 parentNode->addRectangleNode(rect, color);
767 }
768
769 // Add all text with unselected color first
770 for (int i = 0; i < nodes.size(); ++i) {
771 const BinaryTreeNode *node = nodes.at(i);
772 parentNode->addGlyphs(node->position, node->glyphRun, node->color, style, styleColor, nullptr);
773 }
774
775 for (int i = 0; i < imageNodes.size(); ++i) {
776 const BinaryTreeNode *node = imageNodes.at(i);
777 if (node->selectionState == Unselected)
778 parentNode->addImage(node->boundingRect, node->image);
779 }
780
781 // Then, prepend all selection rectangles to the tree
782 for (int i = 0; i < m_selectionRects.size(); ++i) {
783 const QRectF &rect = m_selectionRects.at(i);
784 if (m_selectionColor.alpha() != 0)
785 parentNode->addRectangleNode(rect, m_selectionColor);
786 }
787
788 // Add decorations for each node to the tree.
789 for (int i = 0; i < m_lines.size(); ++i) {
790 const TextDecoration &textDecoration = m_lines.at(i);
791
792 QColor color = textDecoration.selectionState == Selected
793 ? m_selectedTextColor
794 : textDecoration.color;
795
796 parentNode->addDecorationNode(textDecoration.rect, color);
797 }
798
799 // Finally add the selected text on top of everything
800 for (int i = 0; i < nodes.size(); ++i) {
801 const BinaryTreeNode *node = nodes.at(i);
802 QQuickDefaultClipNode *clipNode = node->clipNode;
803 if (clipNode != nullptr && clipNode->parent() == nullptr)
804 parentNode->appendChildNode(clipNode);
805
806 if (node->selectionState == Selected) {
807 QColor color = m_selectedTextColor;
808 int previousNodeIndex = i - 1;
809 int nextNodeIndex = i + 1;
810 const BinaryTreeNode *previousNode = previousNodeIndex < 0 ? 0 : nodes.at(previousNodeIndex);
811 while (previousNode != nullptr && qFuzzyCompare(previousNode->boundingRect.left(), node->boundingRect.left()))
812 previousNode = --previousNodeIndex < 0 ? 0 : nodes.at(previousNodeIndex);
813
814 const BinaryTreeNode *nextNode = nextNodeIndex == nodes.size() ? 0 : nodes.at(nextNodeIndex);
815
816 if (previousNode != nullptr && previousNode->selectionState == Unselected)
817 parentNode->addGlyphs(previousNode->position, previousNode->glyphRun, color, style, styleColor, clipNode);
818
819 if (nextNode != nullptr && nextNode->selectionState == Unselected)
820 parentNode->addGlyphs(nextNode->position, nextNode->glyphRun, color, style, styleColor, clipNode);
821
822 // If the previous or next node completely overlaps this one, then we have already drawn the glyphs of
823 // this node
824 bool drawCurrent = false;
825 if (previousNode != nullptr || nextNode != nullptr) {
826 for (int i = 0; i < node->ranges.size(); ++i) {
827 const std::pair<int, int> &range = node->ranges.at(i);
828
829 int rangeLength = range.second - range.first + 1;
830 if (previousNode != nullptr) {
831 for (int j = 0; j < previousNode->ranges.size(); ++j) {
832 const std::pair<int, int> &otherRange = previousNode->ranges.at(j);
833
834 if (range.first < otherRange.second && range.second > otherRange.first) {
835 int start = qMax(range.first, otherRange.first);
836 int end = qMin(range.second, otherRange.second);
837 rangeLength -= end - start + 1;
838 if (rangeLength == 0)
839 break;
840 }
841 }
842 }
843
844 if (nextNode != nullptr && rangeLength > 0) {
845 for (int j = 0; j < nextNode->ranges.size(); ++j) {
846 const std::pair<int, int> &otherRange = nextNode->ranges.at(j);
847
848 if (range.first < otherRange.second && range.second > otherRange.first) {
849 int start = qMax(range.first, otherRange.first);
850 int end = qMin(range.second, otherRange.second);
851 rangeLength -= end - start + 1;
852 if (rangeLength == 0)
853 break;
854 }
855 }
856 }
857
858 if (rangeLength > 0) {
859 drawCurrent = true;
860 break;
861 }
862 }
863 } else {
864 drawCurrent = true;
865 }
866
867 if (drawCurrent)
868 parentNode->addGlyphs(node->position, node->glyphRun, color, style, styleColor, clipNode);
869 }
870 }
871
872 for (int i = 0; i < imageNodes.size(); ++i) {
873 const BinaryTreeNode *node = imageNodes.at(i);
874 if (node->selectionState == Selected) {
875 parentNode->addImage(node->boundingRect, node->image);
876 if (node->selectionState == Selected) {
877 QColor color = m_selectionColor;
878 color.setAlpha(128);
879 parentNode->addRectangleNode(node->boundingRect, color);
880 }
881 }
882 }
883}
884
885void QQuickTextNodeEngine::mergeFormats(QTextLayout *textLayout, QVarLengthArray<QTextLayout::FormatRange> *mergedFormats)
886{
887 Q_ASSERT(mergedFormats != nullptr);
888 if (textLayout == nullptr)
889 return;
890
891 const QList<QTextLayout::FormatRange> additionalFormats = textLayout->formats();
892 for (QTextLayout::FormatRange additionalFormat : additionalFormats) {
893 if (additionalFormat.format.hasProperty(QTextFormat::ForegroundBrush)
894 || additionalFormat.format.hasProperty(QTextFormat::BackgroundBrush)
895 || additionalFormat.format.isAnchor()) {
896 // Merge overlapping formats
897 if (!mergedFormats->isEmpty()) {
898 QTextLayout::FormatRange *lastFormat = mergedFormats->data() + mergedFormats->size() - 1;
899
900 if (additionalFormat.start < lastFormat->start + lastFormat->length) {
901 QTextLayout::FormatRange *mergedRange = nullptr;
902
903 int length = additionalFormat.length;
904 if (additionalFormat.start > lastFormat->start) {
905 lastFormat->length = additionalFormat.start - lastFormat->start;
906 length -= lastFormat->length;
907
908 mergedFormats->append(QTextLayout::FormatRange());
909 mergedRange = mergedFormats->data() + mergedFormats->size() - 1;
910 lastFormat = mergedFormats->data() + mergedFormats->size() - 2;
911 } else {
912 mergedRange = lastFormat;
913 }
914
915 mergedRange->format = lastFormat->format;
916 mergedRange->format.merge(additionalFormat.format);
917 mergedRange->start = additionalFormat.start;
918
919 int end = qMin(additionalFormat.start + additionalFormat.length,
920 lastFormat->start + lastFormat->length);
921
922 mergedRange->length = end - mergedRange->start;
923 length -= mergedRange->length;
924
925 additionalFormat.start = end;
926 additionalFormat.length = length;
927 }
928 }
929
930 if (additionalFormat.length > 0)
931 mergedFormats->append(additionalFormat);
932 }
933 }
934}
935
936/*!
937 \internal
938 Adds the \a block from the \a textDocument at \a position if its
939 \l {QAbstractTextDocumentLayout::blockBoundingRect()}{bounding rect}
940 intersects the \a viewport, or if \c viewport is not valid
941 (i.e. use a default-constructed QRectF to skip the viewport check).
942
943 \sa QQuickItem::clipRect()
944 */
945void QQuickTextNodeEngine::addTextBlock(QTextDocument *textDocument, const QTextBlock &block, const QPointF &position,
946 const QColor &textColor, const QColor &anchorColor, int selectionStart, int selectionEnd, const QRectF &viewport)
947{
948 Q_ASSERT(textDocument);
949#if QT_CONFIG(im)
950 int preeditLength = block.isValid() ? block.layout()->preeditAreaText().size() : 0;
951 int preeditPosition = block.isValid() ? block.layout()->preeditAreaPosition() : -1;
952#endif
953
954 setCurrentTextDirection(block.textDirection());
955
956 QVarLengthArray<QTextLayout::FormatRange> colorChanges;
957 mergeFormats(block.layout(), &colorChanges);
958
959 const QTextCharFormat charFormat = block.charFormat();
960 const QRectF blockBoundingRect = textDocument->documentLayout()->blockBoundingRect(block).translated(position);
961 if (viewport.isValid()) {
962 if (!blockBoundingRect.intersects(viewport))
963 return;
964 qCDebug(lcSgText) << "adding block with length" << block.length() << ':' << blockBoundingRect << "in viewport" << viewport;
965 }
966
967 if (charFormat.background().style() != Qt::NoBrush)
968 m_backgrounds.append(std::make_pair(blockBoundingRect, charFormat.background().color()));
969
970 if (QTextList *textList = block.textList()) {
971 QPointF pos = blockBoundingRect.topLeft();
972 QTextLayout *layout = block.layout();
973 if (layout->lineCount() > 0) {
974 QTextLine firstLine = layout->lineAt(0);
975 Q_ASSERT(firstLine.isValid());
976
977 setCurrentLine(firstLine);
978
979 QRectF textRect = firstLine.naturalTextRect();
980 pos += textRect.topLeft();
981 if (block.textDirection() == Qt::RightToLeft)
982 pos.rx() += textRect.width();
983
984 QFont font(charFormat.font());
985 QFontMetricsF fontMetrics(font);
986 QTextListFormat listFormat = textList->format();
987
988 QString listItemBullet;
989 switch (listFormat.style()) {
990 case QTextListFormat::ListCircle:
991 listItemBullet = QChar(0x25E6); // White bullet
992 break;
993 case QTextListFormat::ListSquare:
994 listItemBullet = QChar(0x25AA); // Black small square
995 break;
996 case QTextListFormat::ListDecimal:
997 case QTextListFormat::ListLowerAlpha:
998 case QTextListFormat::ListUpperAlpha:
999 case QTextListFormat::ListLowerRoman:
1000 case QTextListFormat::ListUpperRoman:
1001 listItemBullet = textList->itemText(block);
1002 break;
1003 default:
1004 listItemBullet = QChar(0x2022); // Black bullet
1005 break;
1006 };
1007
1008 switch (block.blockFormat().marker()) {
1009 case QTextBlockFormat::MarkerType::Checked:
1010 listItemBullet = QChar(0x2612); // Checked checkbox
1011 break;
1012 case QTextBlockFormat::MarkerType::Unchecked:
1013 listItemBullet = QChar(0x2610); // Unchecked checkbox
1014 break;
1015 case QTextBlockFormat::MarkerType::NoMarker:
1016 break;
1017 }
1018
1019 QSizeF size(fontMetrics.horizontalAdvance(listItemBullet), fontMetrics.height());
1020 qreal xoff = fontMetrics.horizontalAdvance(QLatin1Char(' '));
1021 if (block.textDirection() == Qt::LeftToRight)
1022 xoff = -xoff - size.width();
1023 setPosition(pos + QPointF(xoff, 0));
1024
1025 QTextLayout layout;
1026 layout.setFont(font);
1027 layout.setText(listItemBullet); // Bullet
1028 layout.beginLayout();
1029 QTextLine line = layout.createLine();
1030 line.setPosition(QPointF(0, 0));
1031 layout.endLayout();
1032
1033 // set the color for the bullets, instead of using the previous QTextBlock's color.
1034 if (charFormat.foreground().style() == Qt::NoBrush)
1035 setTextColor(textColor);
1036 else
1037 setTextColor(charFormat.foreground().color());
1038
1039 const QList<QGlyphRun> glyphRuns = layout.glyphRuns();
1040 for (const auto &e : glyphRuns)
1041 addUnselectedGlyphs(e);
1042 }
1043 }
1044
1045 int textPos = block.position();
1046 QTextBlock::iterator blockIterator = block.begin();
1047
1048 while (!blockIterator.atEnd()) {
1049 QTextFragment fragment = blockIterator.fragment();
1050 QString text = fragment.text();
1051 if (text.isEmpty())
1052 continue;
1053
1054 QTextCharFormat charFormat = fragment.charFormat();
1055 QFont font(charFormat.font());
1056 QFontMetricsF fontMetrics(font);
1057
1058 int fontHeight = fontMetrics.descent() + fontMetrics.ascent();
1059 int valign = charFormat.verticalAlignment();
1060 if (valign == QTextCharFormat::AlignSuperScript)
1061 setPosition(QPointF(blockBoundingRect.x(), blockBoundingRect.y() - fontHeight / 2));
1062 else if (valign == QTextCharFormat::AlignSubScript)
1063 setPosition(QPointF(blockBoundingRect.x(), blockBoundingRect.y() + fontHeight / 6));
1064 else
1065 setPosition(blockBoundingRect.topLeft());
1066
1067 if (text.contains(QChar::ObjectReplacementCharacter) && charFormat.objectType() != QTextFormat::NoObject) {
1068 QTextFrame *frame = qobject_cast<QTextFrame *>(textDocument->objectForFormat(charFormat));
1069 if (!frame || frame->frameFormat().position() == QTextFrameFormat::InFlow) {
1070 int blockRelativePosition = textPos - block.position();
1071 QTextLine line = block.layout()->lineForTextPosition(blockRelativePosition);
1072 if (!currentLine().isValid()
1073 || line.lineNumber() != currentLine().lineNumber()) {
1074 setCurrentLine(line);
1075 }
1076
1077 QQuickTextNodeEngine::SelectionState selectionState =
1078 (selectionStart < textPos + text.size()
1079 && selectionEnd >= textPos)
1080 ? QQuickTextNodeEngine::Selected
1081 : QQuickTextNodeEngine::Unselected;
1082
1083 addTextObject(block, QPointF(), charFormat, selectionState, textDocument, textPos);
1084 }
1085 textPos += text.size();
1086 } else {
1087 if (charFormat.foreground().style() != Qt::NoBrush)
1088 setTextColor(charFormat.foreground().color());
1089 else if (charFormat.isAnchor())
1090 setTextColor(anchorColor);
1091 else
1092 setTextColor(textColor);
1093
1094 int fragmentEnd = textPos + fragment.length();
1095#if QT_CONFIG(im)
1096 if (preeditPosition >= 0
1097 && (preeditPosition + block.position()) >= textPos
1098 && (preeditPosition + block.position()) <= fragmentEnd) {
1099 fragmentEnd += preeditLength;
1100 }
1101#endif
1102 if (charFormat.background().style() != Qt::NoBrush || charFormat.hasProperty(QTextFormat::TextUnderlineColor)) {
1103 QTextLayout::FormatRange additionalFormat;
1104 additionalFormat.start = textPos - block.position();
1105 additionalFormat.length = fragmentEnd - textPos;
1106 additionalFormat.format = charFormat;
1107 colorChanges << additionalFormat;
1108 }
1109
1110 textPos = addText(block, charFormat, textColor, colorChanges, textPos, fragmentEnd,
1111 selectionStart, selectionEnd);
1112 }
1113
1114 ++blockIterator;
1115 }
1116
1117#if QT_CONFIG(im)
1118 if (preeditLength >= 0 && textPos <= block.position() + preeditPosition) {
1119 setPosition(blockBoundingRect.topLeft());
1120 textPos = block.position() + preeditPosition;
1121 QTextLine line = block.layout()->lineForTextPosition(preeditPosition);
1122 if (!currentLine().isValid()
1123 || line.lineNumber() != currentLine().lineNumber()) {
1124 setCurrentLine(line);
1125 }
1126 textPos = addText(block, block.charFormat(), textColor, colorChanges,
1127 textPos, textPos + preeditLength,
1128 selectionStart, selectionEnd);
1129 }
1130#endif
1131
1132 // Add block decorations (so far only horizontal rules)
1133 if (block.blockFormat().hasProperty(QTextFormat::BlockTrailingHorizontalRulerWidth)) {
1134 auto ruleLength = qvariant_cast<QTextLength>(block.blockFormat().property(QTextFormat::BlockTrailingHorizontalRulerWidth));
1135 QRectF ruleRect(0, 0, ruleLength.value(blockBoundingRect.width()), 1);
1136 ruleRect.moveCenter(blockBoundingRect.center());
1137 const QColor ruleColor = block.blockFormat().hasProperty(QTextFormat::BackgroundBrush)
1138 ? qvariant_cast<QBrush>(block.blockFormat().property(QTextFormat::BackgroundBrush)).color()
1139 : m_textColor;
1140 m_lines.append(TextDecoration(QQuickTextNodeEngine::Unselected, ruleRect, ruleColor));
1141 }
1142
1143 setCurrentLine(QTextLine()); // Reset current line because the text layout changed
1144 m_hasContents = true;
1145}
1146
1147
1148QT_END_NAMESPACE
void addSelectedGlyphs(const QGlyphRun &glyphRun)
void addUnselectedGlyphs(const QGlyphRun &glyphRun)
void addTextObject(const QTextBlock &block, const QPointF &position, const QTextCharFormat &format, SelectionState selectionState, QTextDocument *textDocument, int pos, QTextFrameFormat::Position layoutPosition=QTextFrameFormat::InFlow)
void mergeProcessedNodes(QList< BinaryTreeNode * > *regularNodes, QList< BinaryTreeNode * > *imageNodes)
void addTextBlock(QTextDocument *, const QTextBlock &, const QPointF &position, const QColor &textColor, const QColor &anchorColor, int selectionStart, int selectionEnd, const QRectF &viewport=QRectF())
void addGlyphsInRange(int rangeStart, int rangeEnd, const QColor &color, const QColor &backgroundColor, const QColor &underlineColor, int selectionStart, int selectionEnd)
void setTextColor(const QColor &textColor)
void setCurrentLine(const QTextLine &currentLine)
int addText(const QTextBlock &block, const QTextCharFormat &charFormat, const QColor &textColor, const QVarLengthArray< QTextLayout::FormatRange > &colorChanges, int textPos, int fragmentEnd, int selectionStart, int selectionEnd)
void addImage(const QRectF &rect, const QImage &image, qreal ascent, SelectionState selectionState, QTextFrameFormat::Position layoutPosition)
void addBorder(const QRectF &rect, qreal border, QTextFrameFormat::BorderStyle borderStyle, const QBrush &borderBrush)
void addFrameDecorations(QTextDocument *document, QTextFrame *frame)
void addGlyphsForRanges(const QVarLengthArray< QTextLayout::FormatRange > &ranges, int start, int end, int selectionStart, int selectionEnd)
Combined button and popup list for selecting options.
size_t qHash(const QQuickTextNodeEngine::BinaryTreeNodeKey &key, size_t seed=0)
BinaryTreeNode(const QGlyphRun &g, SelectionState selState, const QRectF &brect, const Decorations &decs, const QColor &c, const QColor &bc, const QColor &dc, const QPointF &pos, qreal a)