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
qtextengine.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 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:critical reason:data-parser
4
5#include <QtCore/private/qflatmap_p.h>
6#include <QtGui/private/qtguiglobal_p.h>
7#include "qdebug.h"
8#include "qtextformat.h"
10#include "qtextengine_p.h"
13#include "qtextlayout.h"
15#include <QtCore/private/qunicodetables_p.h>
17#include "qfont.h"
18#include "qfont_p.h"
19#include "qfontengine_p.h"
20#include "qstring.h"
23#include "qrawfont_p.h"
24#include <qguiapplication.h>
25#include <qinputmethod.h>
26#include <qlocale.h>
27#include <algorithm>
28#include <stdlib.h>
29
31
32#if !defined(QT_NO_EMOJISEGMENTER)
33Q_STATIC_LOGGING_CATEGORY(lcEmojiSegmenter, "qt.text.emojisegmenter")
34#endif
35
36static const float smallCapsFraction = 0.7f;
37
38namespace {
39// Helper class used in QTextEngine::itemize
40// keep it out here to allow us to keep supporting various compilers.
41class Itemizer {
42public:
43 Itemizer(const QString &string, const QScriptAnalysis *analysis, QScriptItemArray &items)
44 : m_string(string),
45 m_analysis(analysis),
46 m_items(items)
47 {
48 }
49 ~Itemizer() = default;
50 /// generate the script items
51 /// The caps parameter is used to choose the algorithm of splitting text and assigning roles to the textitems
52 void generate(int start, int length, QFont::Capitalization caps)
53 {
54 if (caps == QFont::SmallCaps)
55 generateScriptItemsSmallCaps(reinterpret_cast<const ushort *>(m_string.unicode()), start, length);
56 else if (caps == QFont::Capitalize)
57 generateScriptItemsCapitalize(start, length);
58 else if (caps != QFont::MixedCase) {
59 generateScriptItemsAndChangeCase(start, length,
60 caps == QFont::AllLowercase ? QScriptAnalysis::Lowercase : QScriptAnalysis::Uppercase);
61 }
62 else
63 generateScriptItems(start, length);
64 }
65
66private:
67 enum { MaxItemLength = 4096 };
68
69 void generateScriptItemsAndChangeCase(int start, int length, QScriptAnalysis::Flags flags)
70 {
71 generateScriptItems(start, length);
72 if (m_items.isEmpty()) // the next loop won't work in that case
73 return;
74 QScriptItemArray::Iterator iter = m_items.end();
75 do {
76 iter--;
77 if (iter->analysis.flags < QScriptAnalysis::LineOrParagraphSeparator)
78 iter->analysis.flags = flags;
79 } while (iter->position > start);
80 }
81
82 void generateScriptItems(int start, int length)
83 {
84 if (!length)
85 return;
86 const int end = start + length;
87 for (int i = start + 1; i < end; ++i) {
88 if (m_analysis[i].bidiLevel == m_analysis[start].bidiLevel
89 && m_analysis[i].flags == m_analysis[start].flags
90 && (m_analysis[i].script == m_analysis[start].script || m_string[i] == u'.')
91 && m_analysis[i].flags < QScriptAnalysis::SpaceTabOrObject
92 && i - start < MaxItemLength)
93 continue;
94 m_items.append(QScriptItem(start, m_analysis[start]));
95 start = i;
96 }
97 m_items.append(QScriptItem(start, m_analysis[start]));
98 }
99
100 void generateScriptItemsCapitalize(int start, int length)
101 {
102 if (!length)
103 return;
104
105 if (!m_splitter)
106 m_splitter = std::make_unique<QTextBoundaryFinder>(QTextBoundaryFinder::Word,
107 m_string.constData(), m_string.size(),
108 /*buffer*/nullptr, /*buffer size*/0);
109
110 m_splitter->setPosition(start);
111 QScriptAnalysis itemAnalysis = m_analysis[start];
112
113 if (m_splitter->boundaryReasons() & QTextBoundaryFinder::StartOfItem)
114 itemAnalysis.flags = QScriptAnalysis::Uppercase;
115
116 m_splitter->toNextBoundary();
117
118 const int end = start + length;
119 for (int i = start + 1; i < end; ++i) {
120 bool atWordStart = false;
121
122 if (i == m_splitter->position()) {
123 if (m_splitter->boundaryReasons() & QTextBoundaryFinder::StartOfItem) {
124 Q_ASSERT(m_analysis[i].flags < QScriptAnalysis::TabOrObject);
125 atWordStart = true;
126 }
127
128 m_splitter->toNextBoundary();
129 }
130
131 if (m_analysis[i] == itemAnalysis
132 && m_analysis[i].flags < QScriptAnalysis::TabOrObject
133 && !atWordStart
134 && i - start < MaxItemLength)
135 continue;
136
137 m_items.append(QScriptItem(start, itemAnalysis));
138 start = i;
139 itemAnalysis = m_analysis[start];
140
141 if (atWordStart)
142 itemAnalysis.flags = QScriptAnalysis::Uppercase;
143 }
144 m_items.append(QScriptItem(start, itemAnalysis));
145 }
146
147 void generateScriptItemsSmallCaps(const ushort *uc, int start, int length)
148 {
149 if (!length)
150 return;
151 bool lower = (QChar::category(uc[start]) == QChar::Letter_Lowercase);
152 const int end = start + length;
153 // split text into parts that are already uppercase and parts that are lowercase, and mark the latter to be uppercased later.
154 for (int i = start + 1; i < end; ++i) {
155 bool l = (QChar::category(uc[i]) == QChar::Letter_Lowercase);
156 if ((m_analysis[i] == m_analysis[start])
157 && m_analysis[i].flags < QScriptAnalysis::TabOrObject
158 && l == lower
159 && i - start < MaxItemLength)
160 continue;
161 m_items.append(QScriptItem(start, m_analysis[start]));
162 if (lower)
163 m_items.last().analysis.flags = QScriptAnalysis::SmallCaps;
164
165 start = i;
166 lower = l;
167 }
168 m_items.append(QScriptItem(start, m_analysis[start]));
169 if (lower)
170 m_items.last().analysis.flags = QScriptAnalysis::SmallCaps;
171 }
172
173 const QString &m_string;
174 const QScriptAnalysis * const m_analysis;
175 QScriptItemArray &m_items;
176 std::unique_ptr<QTextBoundaryFinder> m_splitter;
177};
178
179// -----------------------------------------------------------------------------------------------------
180//
181// The Unicode Bidi algorithm.
182// See http://www.unicode.org/reports/tr9/tr9-37.html
183//
184// -----------------------------------------------------------------------------------------------------
185
186// #define DEBUG_BIDI
187#ifndef DEBUG_BIDI
188enum { BidiDebugEnabled = false };
189#define BIDI_DEBUG if (1) ; else qDebug
190#else
191enum { BidiDebugEnabled = true };
192static const char *directions[] = {
193 "DirL", "DirR", "DirEN", "DirES", "DirET", "DirAN", "DirCS", "DirB", "DirS", "DirWS", "DirON",
194 "DirLRE", "DirLRO", "DirAL", "DirRLE", "DirRLO", "DirPDF", "DirNSM", "DirBN",
195 "DirLRI", "DirRLI", "DirFSI", "DirPDI"
196};
197#define BIDI_DEBUG qDebug
198QDebug operator<<(QDebug d, QChar::Direction dir) {
199 return (d << directions[dir]);
200}
201#endif
202
203struct QBidiAlgorithm {
204 template<typename T> using Vector = QVarLengthArray<T, 64>;
205
206 QBidiAlgorithm(const QChar *text, QScriptAnalysis *analysis, int length, bool baseDirectionIsRtl)
207 : text(text),
208 analysis(analysis),
209 length(length),
210 baseLevel(baseDirectionIsRtl ? 1 : 0)
211 {
212
213 }
214
215 struct IsolatePair {
216 int start;
217 int end;
218 };
219
220 void initScriptAnalysisAndIsolatePairs(Vector<IsolatePair> &isolatePairs)
221 {
222 int isolateStack[128];
223 int isolateLevel = 0;
224 // load directions of string, and determine isolate pairs
225 for (int i = 0; i < length; ++i) {
226 int pos = i;
227 char32_t uc = text[i].unicode();
228 if (QChar::isHighSurrogate(uc) && i < length - 1 && text[i + 1].isLowSurrogate()) {
229 ++i;
230 analysis[i].bidiDirection = QChar::DirNSM;
231 uc = QChar::surrogateToUcs4(ushort(uc), text[i].unicode());
232 }
233 const QUnicodeTables::Properties *p = QUnicodeTables::properties(uc);
234 analysis[pos].bidiDirection = QChar::Direction(p->direction);
235 switch (QChar::Direction(p->direction)) {
236 case QChar::DirON:
237 // all mirrored chars are DirON
238 if (p->mirrorDiff)
239 analysis[pos].bidiFlags = QScriptAnalysis::BidiMirrored;
240 break;
241 case QChar::DirLRE:
242 case QChar::DirRLE:
243 case QChar::DirLRO:
244 case QChar::DirRLO:
245 case QChar::DirPDF:
246 case QChar::DirBN:
247 analysis[pos].bidiFlags = QScriptAnalysis::BidiMaybeResetToParagraphLevel|QScriptAnalysis::BidiBN;
248 break;
249 case QChar::DirLRI:
250 case QChar::DirRLI:
251 case QChar::DirFSI:
252 if (isolateLevel < 128) {
253 isolateStack[isolateLevel] = isolatePairs.size();
254 isolatePairs.append({ pos, length });
255 }
256 ++isolateLevel;
257 analysis[pos].bidiFlags = QScriptAnalysis::BidiMaybeResetToParagraphLevel;
258 break;
259 case QChar::DirPDI:
260 if (isolateLevel > 0) {
261 --isolateLevel;
262 if (isolateLevel < 128)
263 isolatePairs[isolateStack[isolateLevel]].end = pos;
264 }
265 Q_FALLTHROUGH();
266 case QChar::DirWS:
267 analysis[pos].bidiFlags = QScriptAnalysis::BidiMaybeResetToParagraphLevel;
268 break;
269 case QChar::DirS:
270 case QChar::DirB:
271 analysis[pos].bidiFlags = QScriptAnalysis::BidiResetToParagraphLevel;
272 if (uc == QChar::ParagraphSeparator) {
273 // close all open isolates as we start a new paragraph
274 while (isolateLevel > 0) {
275 --isolateLevel;
276 if (isolateLevel < 128)
277 isolatePairs[isolateStack[isolateLevel]].end = pos;
278 }
279 }
280 break;
281 default:
282 break;
283 }
284 }
285 }
286
287 struct DirectionalRun {
288 int start;
289 int end;
290 int continuation;
291 ushort level;
292 bool isContinuation;
293 bool hasContent;
294 };
295
296 void generateDirectionalRuns(const Vector<IsolatePair> &isolatePairs, Vector<DirectionalRun> &runs)
297 {
298 struct DirectionalStack {
299 enum { MaxDepth = 125 };
300 struct Item {
301 ushort level;
302 bool isOverride;
303 bool isIsolate;
304 int runBeforeIsolate;
305 };
306 Item items[128];
307 int counter = 0;
308
309 void push(Item i) {
310 items[counter] = i;
311 ++counter;
312 }
313 void pop() {
314 --counter;
315 }
316 int depth() const {
317 return counter;
318 }
319 const Item &top() const {
320 return items[counter - 1];
321 }
322 } stack;
323 int overflowIsolateCount = 0;
324 int overflowEmbeddingCount = 0;
325 int validIsolateCount = 0;
326
327 ushort level = baseLevel;
328 bool override = false;
329 stack.push({ level, false, false, -1 });
330
331 BIDI_DEBUG() << "resolving explicit levels";
332 int runStart = 0;
333 int continuationFrom = -1;
334 int lastRunWithContent = -1;
335 bool runHasContent = false;
336
337 auto appendRun = [&](int runEnd) {
338 if (runEnd < runStart)
339 return;
340 bool isContinuation = false;
341 if (continuationFrom != -1) {
342 runs[continuationFrom].continuation = runs.size();
343 isContinuation = true;
344 } else if (lastRunWithContent != -1 && level == runs.at(lastRunWithContent).level) {
345 runs[lastRunWithContent].continuation = runs.size();
346 isContinuation = true;
347 }
348 if (runHasContent)
349 lastRunWithContent = runs.size();
350 BIDI_DEBUG() << " appending run start/end" << runStart << runEnd << "level" << level;
351 runs.append({ runStart, runEnd, -1, level, isContinuation, runHasContent });
352 runHasContent = false;
353 runStart = runEnd + 1;
354 continuationFrom = -1;
355 };
356
357 int isolatePairPosition = 0;
358
359 for (int i = 0; i < length; ++i) {
360 QChar::Direction dir = analysis[i].bidiDirection;
361
362
363 auto doEmbed = [&](bool isRtl, bool isOverride, bool isIsolate) {
364 if (isIsolate) {
365 if (override)
366 analysis[i].bidiDirection = (level & 1) ? QChar::DirR : QChar::DirL;
367 runHasContent = true;
368 lastRunWithContent = -1;
369 ++isolatePairPosition;
370 }
371 int runBeforeIsolate = runs.size();
372 ushort newLevel = isRtl ? ((stack.top().level + 1) | 1) : ((stack.top().level + 2) & ~1);
373 if (newLevel <= DirectionalStack::MaxDepth && !overflowEmbeddingCount && !overflowIsolateCount) {
374 if (isIsolate)
375 ++validIsolateCount;
376 else
377 runBeforeIsolate = -1;
378 appendRun(isIsolate ? i : i - 1);
379 BIDI_DEBUG() << "pushing new item on stack: level" << (int)newLevel << "isOverride" << isOverride << "isIsolate" << isIsolate << runBeforeIsolate;
380 stack.push({ newLevel, isOverride, isIsolate, runBeforeIsolate });
381 override = isOverride;
382 level = newLevel;
383 } else {
384 if (isIsolate)
385 ++overflowIsolateCount;
386 else if (!overflowIsolateCount)
387 ++overflowEmbeddingCount;
388 }
389 if (!isIsolate) {
390 if (override)
391 analysis[i].bidiDirection = (level & 1) ? QChar::DirR : QChar::DirL;
392 else
393 analysis[i].bidiDirection = QChar::DirBN;
394 }
395 };
396
397 switch (dir) {
398 case QChar::DirLRE:
399 doEmbed(false, false, false);
400 break;
401 case QChar::DirRLE:
402 doEmbed(true, false, false);
403 break;
404 case QChar::DirLRO:
405 doEmbed(false, true, false);
406 break;
407 case QChar::DirRLO:
408 doEmbed(true, true, false);
409 break;
410 case QChar::DirLRI:
411 doEmbed(false, false, true);
412 break;
413 case QChar::DirRLI:
414 doEmbed(true, false, true);
415 break;
416 case QChar::DirFSI: {
417 bool isRtl = false;
418 if (isolatePairPosition < isolatePairs.size()) {
419 const auto &pair = isolatePairs.at(isolatePairPosition);
420 Q_ASSERT(pair.start == i);
421 isRtl = QStringView(text + pair.start + 1, pair.end - pair.start - 1).isRightToLeft();
422 }
423 doEmbed(isRtl, false, true);
424 break;
425 }
426
427 case QChar::DirPDF:
428 if (override)
429 analysis[i].bidiDirection = (level & 1) ? QChar::DirR : QChar::DirL;
430 else
431 analysis[i].bidiDirection = QChar::DirBN;
432 if (overflowIsolateCount) {
433 ; // do nothing
434 } else if (overflowEmbeddingCount) {
435 --overflowEmbeddingCount;
436 } else if (!stack.top().isIsolate && stack.depth() >= 2) {
437 appendRun(i);
438 stack.pop();
439 override = stack.top().isOverride;
440 level = stack.top().level;
441 BIDI_DEBUG() << "popped PDF from stack, level now" << (int)stack.top().level;
442 }
443 break;
444 case QChar::DirPDI:
445 runHasContent = true;
446 if (overflowIsolateCount) {
447 --overflowIsolateCount;
448 } else if (validIsolateCount == 0) {
449 ; // do nothing
450 } else {
451 appendRun(i - 1);
452 overflowEmbeddingCount = 0;
453 while (!stack.top().isIsolate)
454 stack.pop();
455 continuationFrom = stack.top().runBeforeIsolate;
456 BIDI_DEBUG() << "popped PDI from stack, level now" << (int)stack.top().level << "continuation from" << continuationFrom;
457 stack.pop();
458 override = stack.top().isOverride;
459 level = stack.top().level;
460 lastRunWithContent = -1;
461 --validIsolateCount;
462 }
463 if (override)
464 analysis[i].bidiDirection = (level & 1) ? QChar::DirR : QChar::DirL;
465 break;
466 case QChar::DirB:
467 // paragraph separator, go down to base direction, reset all state
468 if (text[i].unicode() == QChar::ParagraphSeparator) {
469 appendRun(i - 1);
470 while (stack.counter > 1) {
471 // there might be remaining isolates on the stack that are missing a PDI. Those need to get
472 // a continuation indicating to take the eos from the end of the string (ie. the paragraph level)
473 const auto &t = stack.top();
474 if (t.isIsolate) {
475 runs[t.runBeforeIsolate].continuation = -2;
476 }
477 --stack.counter;
478 }
479 continuationFrom = -1;
480 lastRunWithContent = -1;
481 validIsolateCount = 0;
482 overflowIsolateCount = 0;
483 overflowEmbeddingCount = 0;
484 level = baseLevel;
485 }
486 break;
487 default:
488 runHasContent = true;
489 Q_FALLTHROUGH();
490 case QChar::DirBN:
491 if (override)
492 analysis[i].bidiDirection = (level & 1) ? QChar::DirR : QChar::DirL;
493 break;
494 }
495 }
496 appendRun(length - 1);
497 while (stack.counter > 1) {
498 // there might be remaining isolates on the stack that are missing a PDI. Those need to get
499 // a continuation indicating to take the eos from the end of the string (ie. the paragraph level)
500 const auto &t = stack.top();
501 if (t.isIsolate) {
502 runs[t.runBeforeIsolate].continuation = -2;
503 }
504 --stack.counter;
505 }
506 }
507
508 void resolveExplicitLevels(Vector<DirectionalRun> &runs)
509 {
510 Vector<IsolatePair> isolatePairs;
511
512 initScriptAnalysisAndIsolatePairs(isolatePairs);
513 generateDirectionalRuns(isolatePairs, runs);
514 }
515
516 struct IsolatedRunSequenceIterator {
517 struct Position {
518 int current = -1;
519 int pos = -1;
520
521 Position() = default;
522 Position(int current, int pos) : current(current), pos(pos) {}
523
524 bool isValid() const { return pos != -1; }
525 void clear() { pos = -1; }
526 };
527 IsolatedRunSequenceIterator(const Vector<DirectionalRun> &runs, int i)
528 : runs(runs),
529 current(i)
530 {
531 pos = runs.at(current).start;
532 }
533 int operator *() const { return pos; }
534 bool atEnd() const { return pos < 0; }
535 void operator++() {
536 ++pos;
537 if (pos > runs.at(current).end) {
538 current = runs.at(current).continuation;
539 if (current > -1)
540 pos = runs.at(current).start;
541 else
542 pos = -1;
543 }
544 }
545 void setPosition(Position p) {
546 current = p.current;
547 pos = p.pos;
548 }
549 Position position() const {
550 return Position(current, pos);
551 }
552 bool operator !=(int position) const {
553 return pos != position;
554 }
555
556 const Vector<DirectionalRun> &runs;
557 int current;
558 int pos;
559 };
560
561
562 void resolveW1W2W3(const Vector<DirectionalRun> &runs, int i, QChar::Direction sos)
563 {
564 QChar::Direction last = sos;
565 QChar::Direction lastStrong = sos;
566 IsolatedRunSequenceIterator it(runs, i);
567 while (!it.atEnd()) {
568 int pos = *it;
569
570 // Rule W1: Resolve NSM
571 QChar::Direction current = analysis[pos].bidiDirection;
572 if (current == QChar::DirNSM) {
573 current = last;
574 analysis[pos].bidiDirection = current;
575 } else if (current >= QChar::DirLRI) {
576 last = QChar::DirON;
577 } else if (current == QChar::DirBN) {
578 current = last;
579 } else {
580 // there shouldn't be any explicit embedding marks here
581 Q_ASSERT(current != QChar::DirLRE);
582 Q_ASSERT(current != QChar::DirRLE);
583 Q_ASSERT(current != QChar::DirLRO);
584 Q_ASSERT(current != QChar::DirRLO);
585 Q_ASSERT(current != QChar::DirPDF);
586
587 last = current;
588 }
589
590 // Rule W2
591 if (current == QChar::DirEN && lastStrong == QChar::DirAL) {
592 current = QChar::DirAN;
593 analysis[pos].bidiDirection = current;
594 }
595
596 // remember last strong char for rule W2
597 if (current == QChar::DirL || current == QChar::DirR) {
598 lastStrong = current;
599 } else if (current == QChar::DirAL) {
600 // Rule W3
601 lastStrong = current;
602 analysis[pos].bidiDirection = QChar::DirR;
603 }
604 last = current;
605 ++it;
606 }
607 }
608
609
610 void resolveW4(const Vector<DirectionalRun> &runs, int i, QChar::Direction sos)
611 {
612 // Rule W4
613 QChar::Direction secondLast = sos;
614
615 IsolatedRunSequenceIterator it(runs, i);
616 int lastPos = *it;
617 QChar::Direction last = analysis[lastPos].bidiDirection;
618
619// BIDI_DEBUG() << "Applying rule W4/W5";
620 ++it;
621 while (!it.atEnd()) {
622 int pos = *it;
623 QChar::Direction current = analysis[pos].bidiDirection;
624 if (current == QChar::DirBN) {
625 ++it;
626 continue;
627 }
628// BIDI_DEBUG() << pos << secondLast << last << current;
629 if (last == QChar::DirES && current == QChar::DirEN && secondLast == QChar::DirEN) {
630 last = QChar::DirEN;
631 analysis[lastPos].bidiDirection = last;
632 } else if (last == QChar::DirCS) {
633 if (current == QChar::DirEN && secondLast == QChar::DirEN) {
634 last = QChar::DirEN;
635 analysis[lastPos].bidiDirection = last;
636 } else if (current == QChar::DirAN && secondLast == QChar::DirAN) {
637 last = QChar::DirAN;
638 analysis[lastPos].bidiDirection = last;
639 }
640 }
641 secondLast = last;
642 last = current;
643 lastPos = pos;
644 ++it;
645 }
646 }
647
648 void resolveW5(const Vector<DirectionalRun> &runs, int i)
649 {
650 // Rule W5
651 IsolatedRunSequenceIterator::Position lastETPosition;
652
653 IsolatedRunSequenceIterator it(runs, i);
654 int lastPos = *it;
655 QChar::Direction last = analysis[lastPos].bidiDirection;
656 if (last == QChar::DirET || last == QChar::DirBN)
657 lastETPosition = it.position();
658
659 ++it;
660 while (!it.atEnd()) {
661 int pos = *it;
662 QChar::Direction current = analysis[pos].bidiDirection;
663 if (current == QChar::DirBN) {
664 ++it;
665 continue;
666 }
667 if (current == QChar::DirET) {
668 if (last == QChar::DirEN) {
669 current = QChar::DirEN;
670 analysis[pos].bidiDirection = current;
671 } else if (!lastETPosition.isValid()) {
672 lastETPosition = it.position();
673 }
674 } else if (lastETPosition.isValid()) {
675 if (current == QChar::DirEN) {
676 it.setPosition(lastETPosition);
677 while (it != pos) {
678 int pos = *it;
679 analysis[pos].bidiDirection = QChar::DirEN;
680 ++it;
681 }
682 }
683 lastETPosition.clear();
684 }
685 last = current;
686 lastPos = pos;
687 ++it;
688 }
689 }
690
691 void resolveW6W7(const Vector<DirectionalRun> &runs, int i, QChar::Direction sos)
692 {
693 QChar::Direction lastStrong = sos;
694 IsolatedRunSequenceIterator it(runs, i);
695 while (!it.atEnd()) {
696 int pos = *it;
697
698 // Rule W6
699 QChar::Direction current = analysis[pos].bidiDirection;
700 if (current == QChar::DirBN) {
701 ++it;
702 continue;
703 }
704 if (current == QChar::DirET || current == QChar::DirES || current == QChar::DirCS) {
705 analysis[pos].bidiDirection = QChar::DirON;
706 }
707
708 // Rule W7
709 else if (current == QChar::DirL || current == QChar::DirR) {
710 lastStrong = current;
711 } else if (current == QChar::DirEN && lastStrong == QChar::DirL) {
712 analysis[pos].bidiDirection = lastStrong;
713 }
714 ++it;
715 }
716 }
717
718 struct BracketPair {
719 int first;
720 int second;
721
722 bool isValid() const { return second > 0; }
723
724 QChar::Direction containedDirection(const QScriptAnalysis *analysis, QChar::Direction embeddingDir) const {
725 int isolateCounter = 0;
726 QChar::Direction containedDir = QChar::DirON;
727 for (int i = first + 1; i < second; ++i) {
728 QChar::Direction dir = analysis[i].bidiDirection;
729 if (isolateCounter) {
730 if (dir == QChar::DirPDI)
731 --isolateCounter;
732 continue;
733 }
734 if (dir == QChar::DirL) {
735 containedDir = dir;
736 if (embeddingDir == dir)
737 break;
738 } else if (dir == QChar::DirR || dir == QChar::DirAN || dir == QChar::DirEN) {
739 containedDir = QChar::DirR;
740 if (embeddingDir == QChar::DirR)
741 break;
742 } else if (dir == QChar::DirLRI || dir == QChar::DirRLI || dir == QChar::DirFSI)
743 ++isolateCounter;
744 }
745 BIDI_DEBUG() << " contained dir for backet pair" << first << "/" << second << "is" << containedDir;
746 return containedDir;
747 }
748 };
749
750
751 struct BracketStack {
752 struct Item {
753 Item() = default;
754 Item(uint pairedBracked, int position) : pairedBracked(pairedBracked), position(position) {}
755 uint pairedBracked = 0;
756 int position = 0;
757 };
758
759 void push(uint closingUnicode, int pos) {
760 if (position < MaxDepth)
761 stack[position] = Item(closingUnicode, pos);
762 ++position;
763 }
764 int match(uint unicode) {
765 Q_ASSERT(!overflowed());
766 int p = position;
767 while (--p >= 0) {
768 if (stack[p].pairedBracked == unicode ||
769 // U+3009 and U+2329 are canonical equivalents of each other. Fortunately it's the only pair in Unicode 10
770 (stack[p].pairedBracked == 0x3009 && unicode == 0x232a) ||
771 (stack[p].pairedBracked == 0x232a && unicode == 0x3009)) {
772 position = p;
773 return stack[p].position;
774 }
775
776 }
777 return -1;
778 }
779
780 enum { MaxDepth = 63 };
781 Item stack[MaxDepth];
782 int position = 0;
783
784 bool overflowed() const { return position > MaxDepth; }
785 };
786
787 void resolveN0(const Vector<DirectionalRun> &runs, int i, QChar::Direction sos)
788 {
789 ushort level = runs.at(i).level;
790
791 Vector<BracketPair> bracketPairs;
792 {
793 BracketStack bracketStack;
794 IsolatedRunSequenceIterator it(runs, i);
795 while (!it.atEnd()) {
796 int pos = *it;
797 QChar::Direction dir = analysis[pos].bidiDirection;
798 if (dir == QChar::DirON) {
799 // assumes no mirrored pirs outside BMP (util/unicode guarantees this):
800 const QUnicodeTables::Properties *p = QUnicodeTables::properties(char16_t{text[pos].unicode()});
801 if (p->mirrorDiff) {
802 // either opening or closing bracket
803 if (p->category == QChar::Punctuation_Open) {
804 // opening bracked
805 uint closingBracked = text[pos].unicode() + p->mirrorDiff;
806 bracketStack.push(closingBracked, bracketPairs.size());
807 if (bracketStack.overflowed()) {
808 bracketPairs.clear();
809 break;
810 }
811 bracketPairs.append({ pos, -1 });
812 } else if (p->category == QChar::Punctuation_Close) {
813 int pairPos = bracketStack.match(text[pos].unicode());
814 if (pairPos != -1)
815 bracketPairs[pairPos].second = pos;
816 }
817 }
818 }
819 ++it;
820 }
821 }
822
823 if (BidiDebugEnabled && bracketPairs.size()) {
824 BIDI_DEBUG() << "matched bracket pairs:";
825 for (int i = 0; i < bracketPairs.size(); ++i)
826 BIDI_DEBUG() << " " << bracketPairs.at(i).first << bracketPairs.at(i).second;
827 }
828
829 QChar::Direction lastStrong = sos;
830 IsolatedRunSequenceIterator it(runs, i);
831 QChar::Direction embeddingDir = (level & 1) ? QChar::DirR : QChar::DirL;
832 for (int i = 0; i < bracketPairs.size(); ++i) {
833 const auto &pair = bracketPairs.at(i);
834 if (!pair.isValid())
835 continue;
836 QChar::Direction containedDir = pair.containedDirection(analysis, embeddingDir);
837 if (containedDir == QChar::DirON) {
838 BIDI_DEBUG() << " 3: resolve bracket pair" << i << "to DirON";
839 continue;
840 } else if (containedDir == embeddingDir) {
841 analysis[pair.first].bidiDirection = embeddingDir;
842 analysis[pair.second].bidiDirection = embeddingDir;
843 BIDI_DEBUG() << " 1: resolve bracket pair" << i << "to" << embeddingDir;
844 } else {
845 // case c.
846 while (it.pos < pair.first) {
847 int pos = *it;
848 switch (analysis[pos].bidiDirection) {
849 case QChar::DirR:
850 case QChar::DirEN:
851 case QChar::DirAN:
852 lastStrong = QChar::DirR;
853 break;
854 case QChar::DirL:
855 lastStrong = QChar::DirL;
856 break;
857 default:
858 break;
859 }
860 ++it;
861 }
862 analysis[pair.first].bidiDirection = lastStrong;
863 analysis[pair.second].bidiDirection = lastStrong;
864 BIDI_DEBUG() << " 2: resolve bracket pair" << i << "to" << lastStrong;
865 }
866 for (int i = pair.second + 1; i < length; ++i) {
867 if (text[i].direction() == QChar::DirNSM)
868 analysis[i].bidiDirection = analysis[pair.second].bidiDirection;
869 else
870 break;
871 }
872 }
873 }
874
875 void resolveN1N2(const Vector<DirectionalRun> &runs, int i, QChar::Direction sos, QChar::Direction eos)
876 {
877 // Rule N1 & N2
878 QChar::Direction lastStrong = sos;
879 IsolatedRunSequenceIterator::Position niPos;
880 IsolatedRunSequenceIterator it(runs, i);
881// QChar::Direction last = QChar::DirON;
882 while (1) {
883 int pos = *it;
884
885 QChar::Direction current = pos >= 0 ? analysis[pos].bidiDirection : eos;
886 QChar::Direction currentStrong = current;
887 switch (current) {
888 case QChar::DirEN:
889 case QChar::DirAN:
890 currentStrong = QChar::DirR;
891 Q_FALLTHROUGH();
892 case QChar::DirL:
893 case QChar::DirR:
894 if (niPos.isValid()) {
895 QChar::Direction dir = currentStrong;
896 if (lastStrong != currentStrong)
897 dir = (runs.at(i).level) & 1 ? QChar::DirR : QChar::DirL;
898 it.setPosition(niPos);
899 while (*it != pos) {
900 if (analysis[*it].bidiDirection != QChar::DirBN)
901 analysis[*it].bidiDirection = dir;
902 ++it;
903 }
904 niPos.clear();
905 }
906 lastStrong = currentStrong;
907 break;
908
909 case QChar::DirBN:
910 case QChar::DirS:
911 case QChar::DirWS:
912 case QChar::DirON:
913 case QChar::DirFSI:
914 case QChar::DirLRI:
915 case QChar::DirRLI:
916 case QChar::DirPDI:
917 case QChar::DirB:
918 if (!niPos.isValid())
919 niPos = it.position();
920 break;
921
922 default:
923 Q_UNREACHABLE();
924 }
925 if (it.atEnd())
926 break;
927// last = current;
928 ++it;
929 }
930 }
931
932 void resolveImplicitLevelsForIsolatedRun(const Vector<DirectionalRun> &runs, int i)
933 {
934 // Rule X10
935 int level = runs.at(i).level;
936 int before = i - 1;
937 while (before >= 0 && !runs.at(before).hasContent)
938 --before;
939 int level_before = (before >= 0) ? runs.at(before).level : baseLevel;
940 int after = i;
941 while (runs.at(after).continuation >= 0)
942 after = runs.at(after).continuation;
943 if (runs.at(after).continuation == -2) {
944 after = runs.size();
945 } else {
946 ++after;
947 while (after < runs.size() && !runs.at(after).hasContent)
948 ++after;
949 }
950 int level_after = (after == runs.size()) ? baseLevel : runs.at(after).level;
951 QChar::Direction sos = (qMax(level_before, level) & 1) ? QChar::DirR : QChar::DirL;
952 QChar::Direction eos = (qMax(level_after, level) & 1) ? QChar::DirR : QChar::DirL;
953
954 if (BidiDebugEnabled) {
955 BIDI_DEBUG() << "Isolated run starting at" << i << "sos/eos" << sos << eos;
956 BIDI_DEBUG() << "before implicit level processing:";
957 IsolatedRunSequenceIterator it(runs, i);
958 while (!it.atEnd()) {
959 BIDI_DEBUG() << " " << *it << Qt::hex << text[*it].unicode() << analysis[*it].bidiDirection;
960 ++it;
961 }
962 }
963
964 resolveW1W2W3(runs, i, sos);
965 resolveW4(runs, i, sos);
966 resolveW5(runs, i);
967
968 if (BidiDebugEnabled) {
969 BIDI_DEBUG() << "after W4/W5";
970 IsolatedRunSequenceIterator it(runs, i);
971 while (!it.atEnd()) {
972 BIDI_DEBUG() << " " << *it << Qt::hex << text[*it].unicode() << analysis[*it].bidiDirection;
973 ++it;
974 }
975 }
976
977 resolveW6W7(runs, i, sos);
978
979 // Resolve neutral types
980
981 // Rule N0
982 resolveN0(runs, i, sos);
983 resolveN1N2(runs, i, sos, eos);
984
985 BIDI_DEBUG() << "setting levels (run at" << level << ")";
986 // Rules I1 & I2: set correct levels
987 {
988 ushort level = runs.at(i).level;
989 IsolatedRunSequenceIterator it(runs, i);
990 while (!it.atEnd()) {
991 int pos = *it;
992
993 QChar::Direction current = analysis[pos].bidiDirection;
994 switch (current) {
995 case QChar::DirBN:
996 break;
997 case QChar::DirL:
998 analysis[pos].bidiLevel = (level + 1) & ~1;
999 break;
1000 case QChar::DirR:
1001 analysis[pos].bidiLevel = level | 1;
1002 break;
1003 case QChar::DirAN:
1004 case QChar::DirEN:
1005 analysis[pos].bidiLevel = (level + 2) & ~1;
1006 break;
1007 default:
1008 Q_UNREACHABLE();
1009 }
1010 BIDI_DEBUG() << " " << pos << current << analysis[pos].bidiLevel;
1011 ++it;
1012 }
1013 }
1014 }
1015
1016 void resolveImplicitLevels(const Vector<DirectionalRun> &runs)
1017 {
1018 for (int i = 0; i < runs.size(); ++i) {
1019 if (runs.at(i).isContinuation)
1020 continue;
1021
1022 resolveImplicitLevelsForIsolatedRun(runs, i);
1023 }
1024 }
1025
1026 bool checkForBidi() const
1027 {
1028 if (baseLevel != 0)
1029 return true;
1030 for (int i = 0; i < length; ++i) {
1031 if (text[i].unicode() >= 0x590) {
1032 switch (text[i].direction()) {
1033 case QChar::DirR: case QChar::DirAN:
1034 case QChar::DirLRE: case QChar::DirLRO: case QChar::DirAL:
1035 case QChar::DirRLE: case QChar::DirRLO: case QChar::DirPDF:
1036 case QChar::DirLRI: case QChar::DirRLI: case QChar::DirFSI: case QChar::DirPDI:
1037 return true;
1038 default:
1039 break;
1040 }
1041 }
1042 }
1043 return false;
1044 }
1045
1046 bool process()
1047 {
1048 memset(analysis, 0, length * sizeof(QScriptAnalysis));
1049
1050 bool hasBidi = checkForBidi();
1051
1052 if (!hasBidi)
1053 return false;
1054
1055 if (BidiDebugEnabled) {
1056 BIDI_DEBUG() << ">>>> start bidi, text length" << length;
1057 for (int i = 0; i < length; ++i)
1058 BIDI_DEBUG() << Qt::hex << " (" << i << ")" << text[i].unicode() << text[i].direction();
1059 }
1060
1061 {
1062 Vector<DirectionalRun> runs;
1063 resolveExplicitLevels(runs);
1064
1065 if (BidiDebugEnabled) {
1066 BIDI_DEBUG() << "resolved explicit levels, nruns" << runs.size();
1067 for (int i = 0; i < runs.size(); ++i)
1068 BIDI_DEBUG() << " " << i << "start/end" << runs.at(i).start << runs.at(i).end << "level" << (int)runs.at(i).level << "continuation" << runs.at(i).continuation;
1069 }
1070
1071 // now we have a list of isolated run sequences inside the vector of runs, that can be fed
1072 // through the implicit level resolving
1073
1074 resolveImplicitLevels(runs);
1075 }
1076
1077 BIDI_DEBUG() << "Rule L1:";
1078 // Rule L1:
1079 bool resetLevel = true;
1080 for (int i = length - 1; i >= 0; --i) {
1081 if (analysis[i].bidiFlags & QScriptAnalysis::BidiResetToParagraphLevel) {
1082 BIDI_DEBUG() << "resetting pos" << i << "to baselevel";
1083 analysis[i].bidiLevel = baseLevel;
1084 resetLevel = true;
1085 } else if (resetLevel && analysis[i].bidiFlags & QScriptAnalysis::BidiMaybeResetToParagraphLevel) {
1086 BIDI_DEBUG() << "resetting pos" << i << "to baselevel (maybereset flag)";
1087 analysis[i].bidiLevel = baseLevel;
1088 } else {
1089 resetLevel = false;
1090 }
1091 }
1092
1093 // set directions for BN to the minimum of adjacent chars
1094 // This makes is possible to be conformant with the Bidi algorithm even though we don't
1095 // remove BN and explicit embedding chars from the stream of characters to reorder
1096 int lastLevel = baseLevel;
1097 int lastBNPos = -1;
1098 for (int i = 0; i < length; ++i) {
1099 if (analysis[i].bidiFlags & QScriptAnalysis::BidiBN) {
1100 if (lastBNPos < 0)
1101 lastBNPos = i;
1102 analysis[i].bidiLevel = lastLevel;
1103 } else {
1104 int l = analysis[i].bidiLevel;
1105 if (lastBNPos >= 0) {
1106 if (l < lastLevel) {
1107 while (lastBNPos < i) {
1108 analysis[lastBNPos].bidiLevel = l;
1109 ++lastBNPos;
1110 }
1111 }
1112 lastBNPos = -1;
1113 }
1114 lastLevel = l;
1115 }
1116 }
1117 if (lastBNPos >= 0 && baseLevel < lastLevel) {
1118 while (lastBNPos < length) {
1119 analysis[lastBNPos].bidiLevel = baseLevel;
1120 ++lastBNPos;
1121 }
1122 }
1123
1124 if (BidiDebugEnabled) {
1125 BIDI_DEBUG() << "final resolved levels:";
1126 for (int i = 0; i < length; ++i)
1127 BIDI_DEBUG() << " " << i << Qt::hex << text[i].unicode() << Qt::dec << (int)analysis[i].bidiLevel;
1128 }
1129
1130 return true;
1131 }
1132
1133
1134 const QChar *text;
1135 QScriptAnalysis *analysis;
1136 int length;
1137 char baseLevel;
1138};
1139
1140} // namespace
1141
1142void QTextEngine::bidiReorder(int numItems, const quint8 *levels, int *visualOrder)
1143{
1144
1145 // first find highest and lowest levels
1146 quint8 levelLow = 128;
1147 quint8 levelHigh = 0;
1148 int i = 0;
1149 while (i < numItems) {
1150 //printf("level = %d\n", r->level);
1151 if (levels[i] > levelHigh)
1152 levelHigh = levels[i];
1153 if (levels[i] < levelLow)
1154 levelLow = levels[i];
1155 i++;
1156 }
1157
1158 // implements reordering of the line (L2 according to BiDi spec):
1159 // L2. From the highest level found in the text to the lowest odd level on each line,
1160 // reverse any contiguous sequence of characters that are at that level or higher.
1161
1162 // reversing is only done up to the lowest odd level
1163 if (!(levelLow%2)) levelLow++;
1164
1165 BIDI_DEBUG() << "reorderLine: lineLow = " << (uint)levelLow << ", lineHigh = " << (uint)levelHigh;
1166
1167 int count = numItems - 1;
1168 for (i = 0; i < numItems; i++)
1169 visualOrder[i] = i;
1170
1171 while(levelHigh >= levelLow) {
1172 int i = 0;
1173 while (i < count) {
1174 while(i < count && levels[i] < levelHigh) i++;
1175 int start = i;
1176 while(i <= count && levels[i] >= levelHigh) i++;
1177 int end = i-1;
1178
1179 if (start != end) {
1180 //qDebug() << "reversing from " << start << " to " << end;
1181 for(int j = 0; j < (end-start+1)/2; j++) {
1182 int tmp = visualOrder[start+j];
1183 visualOrder[start+j] = visualOrder[end-j];
1184 visualOrder[end-j] = tmp;
1185 }
1186 }
1187 i++;
1188 }
1189 levelHigh--;
1190 }
1191
1192// BIDI_DEBUG("visual order is:");
1193// for (i = 0; i < numItems; i++)
1194// BIDI_DEBUG() << visualOrder[i];
1195}
1196
1197
1199 Justification_Prohibited = 0, // Justification can not be applied after this glyph
1200 Justification_Arabic_Space = 1, // This glyph represents a space inside arabic text
1201 Justification_Character = 2, // Inter-character justification point follows this glyph
1202 Justification_Space = 4, // This glyph represents a blank outside an Arabic run
1203 Justification_Arabic_Normal = 7, // Normal Middle-Of-Word glyph that connects to the right (begin)
1204 Justification_Arabic_Waw = 8, // Next character is final form of Waw/Ain/Qaf/Feh
1205 Justification_Arabic_BaRa = 9, // Next two characters are Ba + Ra/Ya/AlefMaksura
1206 Justification_Arabic_Alef = 10, // Next character is final form of Alef/Tah/Lam/Kaf/Gaf
1207 Justification_Arabic_HahDal = 11, // Next character is final form of Hah/Dal/Teh Marbuta
1208 Justification_Arabic_Seen = 12, // Initial or medial form of Seen/Sad
1209 Justification_Arabic_Kashida = 13 // User-inserted Kashida(U+0640)
1210};
1211
1212#if QT_CONFIG(harfbuzz)
1213
1214/*
1215 Adds an inter character justification opportunity after the number or letter
1216 character and a space justification opportunity after the space character.
1217*/
1218static inline void qt_getDefaultJustificationOpportunities(const ushort *string, qsizetype length, const QGlyphLayout &g, ushort *log_clusters, int spaceAs)
1219{
1220 qsizetype str_pos = 0;
1221 while (str_pos < length) {
1222 int glyph_pos = log_clusters[str_pos];
1223
1224 Q_ASSERT(glyph_pos < g.numGlyphs && g.attributes[glyph_pos].clusterStart);
1225
1226 uint ucs4 = string[str_pos];
1227 if (QChar::isHighSurrogate(ucs4) && str_pos + 1 < length) {
1228 ushort low = string[str_pos + 1];
1229 if (QChar::isLowSurrogate(low)) {
1230 ++str_pos;
1231 ucs4 = QChar::surrogateToUcs4(ucs4, low);
1232 }
1233 }
1234
1235 // skip whole cluster
1236 do {
1237 ++str_pos;
1238 } while (str_pos < length && log_clusters[str_pos] == glyph_pos);
1239 do {
1240 ++glyph_pos;
1241 } while (glyph_pos < g.numGlyphs && !g.attributes[glyph_pos].clusterStart);
1242 --glyph_pos;
1243
1244 // justification opportunity at the end of cluster
1245 if (Q_LIKELY(QChar::isLetterOrNumber(ucs4)))
1246 g.attributes[glyph_pos].justification = Justification_Character;
1247 else if (Q_LIKELY(QChar::isSpace(ucs4)))
1248 g.attributes[glyph_pos].justification = spaceAs;
1249 }
1250}
1251
1252static inline void qt_getJustificationOpportunities(const ushort *string, qsizetype length, const QScriptItem &si, const QGlyphLayout &g, ushort *log_clusters)
1253{
1254 Q_ASSERT(length > 0 && g.numGlyphs > 0);
1255
1256 for (int glyph_pos = 0; glyph_pos < g.numGlyphs; ++glyph_pos)
1257 g.attributes[glyph_pos].justification = Justification_Prohibited;
1258
1259 int spaceAs;
1260
1261 switch (si.analysis.script) {
1262 case QChar::Script_Arabic:
1263 case QChar::Script_Syriac:
1264 case QChar::Script_Nko:
1265 case QChar::Script_Mandaic:
1266 case QChar::Script_Mongolian:
1267 case QChar::Script_PhagsPa:
1268 case QChar::Script_Manichaean:
1269 case QChar::Script_PsalterPahlavi:
1270 // same as default but inter character justification takes precedence
1271 spaceAs = Justification_Arabic_Space;
1272 break;
1273
1274 case QChar::Script_Tibetan:
1275 case QChar::Script_Hiragana:
1276 case QChar::Script_Katakana:
1277 case QChar::Script_Bopomofo:
1278 case QChar::Script_Han:
1279 // same as default but inter character justification is the only option
1280 spaceAs = Justification_Character;
1281 break;
1282
1283 default:
1284 spaceAs = Justification_Space;
1285 break;
1286 }
1287
1288 qt_getDefaultJustificationOpportunities(string, length, g, log_clusters, spaceAs);
1289}
1290
1291#endif // harfbuzz
1292
1293
1294// shape all the items that intersect with the line, taking tab widths into account to find out what text actually fits in the line.
1295void QTextEngine::shapeLine(const QScriptLine &line)
1296{
1297 QFixed x;
1298 bool first = true;
1299 int item = findItem(line.from);
1300 if (item == -1)
1301 return;
1302
1303 const int end = findItem(line.from + line.length + line.trailingSpaces - 1, item);
1304 for ( ; item <= end; ++item) {
1305 QScriptItem &si = layoutData->items[item];
1306 if (si.analysis.flags == QScriptAnalysis::Tab) {
1307 ensureSpace(1);
1308 si.width = calculateTabWidth(item, x);
1309 } else {
1310 shape(item);
1311 }
1312 if (first && si.position != line.from) { // that means our x position has to be offset
1313 QGlyphLayout glyphs = shapedGlyphs(&si);
1314 Q_ASSERT(line.from > si.position);
1315 for (int i = line.from - si.position - 1; i >= 0; i--) {
1316 x -= glyphs.effectiveAdvance(i);
1317 }
1318 }
1319 first = false;
1320
1321 x += si.width;
1322 }
1323}
1324
1325static void applyVisibilityRules(ushort ucs, QGlyphLayout *glyphs, uint glyphPosition, QFontEngine *fontEngine)
1326{
1327 // hide characters that should normally be invisible
1328 switch (ucs) {
1329 case QChar::LineFeed:
1330 case 0x000c: // FormFeed
1331 case QChar::CarriageReturn:
1332 case QChar::LineSeparator:
1333 case QChar::ParagraphSeparator:
1334 glyphs->attributes[glyphPosition].dontPrint = true;
1335 break;
1336 case QChar::SoftHyphen:
1337 if (!fontEngine->symbol) {
1338 // U+00AD [SOFT HYPHEN] is a default ignorable codepoint,
1339 // so we replace its glyph and metrics with ones for
1340 // U+002D [HYPHEN-MINUS] or U+2010 [HYPHEN] and make
1341 // it visible if it appears at line-break
1342 const uint engineIndex = glyphs->glyphs[glyphPosition] & 0xff000000;
1343 glyph_t glyph = fontEngine->glyphIndex(0x002d);
1344 if (glyph == 0)
1345 glyph = fontEngine->glyphIndex(0x2010);
1346 if (glyph == 0)
1347 glyph = fontEngine->glyphIndex(0x00ad);
1348 glyphs->glyphs[glyphPosition] = glyph;
1349 if (Q_LIKELY(glyphs->glyphs[glyphPosition] != 0)) {
1350 glyphs->glyphs[glyphPosition] |= engineIndex;
1351 QGlyphLayout tmp = glyphs->mid(glyphPosition, 1);
1352 fontEngine->recalcAdvances(&tmp, { });
1353 }
1354 glyphs->attributes[glyphPosition].dontPrint = true;
1355 }
1356 break;
1357 default:
1358 break;
1359 }
1360}
1361
1362void QTextEngine::shapeText(int item) const
1363{
1364 Q_ASSERT(item < layoutData->items.size());
1365 QScriptItem &si = layoutData->items[item];
1366
1367 if (si.num_glyphs)
1368 return;
1369
1370 si.width = 0;
1371 si.glyph_data_offset = layoutData->used;
1372
1373 const ushort *string = reinterpret_cast<const ushort *>(layoutData->string.constData()) + si.position;
1374 const ushort *baseString = reinterpret_cast<const ushort *>(layoutData->string.constData());
1375 int baseStringStart = si.position;
1376 int baseStringLength = layoutData->string.length();
1377 const int itemLength = length(item);
1378
1379 QString casedString;
1380 if (si.analysis.flags && si.analysis.flags <= QScriptAnalysis::SmallCaps) {
1381 casedString.resize(itemLength);
1382 ushort *uc = reinterpret_cast<ushort *>(casedString.data());
1383 for (int i = 0; i < itemLength; ++i) {
1384 uint ucs4 = string[i];
1385 if (QChar::isHighSurrogate(ucs4) && i + 1 < itemLength) {
1386 uint low = string[i + 1];
1387 if (QChar::isLowSurrogate(low)) {
1388 // high part never changes in simple casing
1389 uc[i] = ucs4;
1390 ++i;
1391 ucs4 = QChar::surrogateToUcs4(ucs4, low);
1392 ucs4 = si.analysis.flags == QScriptAnalysis::Lowercase ? QChar::toLower(ucs4)
1393 : QChar::toUpper(ucs4);
1394 uc[i] = QChar::lowSurrogate(ucs4);
1395 }
1396 } else {
1397 uc[i] = si.analysis.flags == QScriptAnalysis::Lowercase ? QChar::toLower(ucs4)
1398 : QChar::toUpper(ucs4);
1399 }
1400 }
1401 string = reinterpret_cast<const ushort *>(casedString.constData());
1402 baseString = string;
1403 baseStringStart = 0;
1404 baseStringLength = casedString.length();
1405 }
1406
1407 if (Q_UNLIKELY(!ensureSpace(itemLength))) {
1408 Q_UNREACHABLE_RETURN(); // ### report OOM error somehow
1409 }
1410
1411 QFontEngine *fontEngine = this->fontEngine(si, &si.ascent, &si.descent, &si.leading);
1412
1413#if QT_CONFIG(harfbuzz)
1414 bool kerningEnabled;
1415#endif
1416 bool letterSpacingIsAbsolute;
1417 bool shapingEnabled = false;
1418 QMap<QFont::Tag, quint32> features;
1419 QFixed letterSpacing, wordSpacing;
1420#ifndef QT_NO_RAWFONT
1421 if (useRawFont) {
1422 QTextCharFormat f = format(&si);
1423 QFont font = f.font();
1424# if QT_CONFIG(harfbuzz)
1425 kerningEnabled = font.kerning();
1426 shapingEnabled = (si.analysis.script < QChar::ScriptCount && QFontEngine::scriptRequiresOpenType(QChar::Script(si.analysis.script)))
1427 || (font.styleStrategy() & QFont::PreferNoShaping) == 0;
1428# endif
1429 wordSpacing = QFixed::fromReal(font.wordSpacing());
1430 letterSpacing = QFixed::fromReal(font.letterSpacing());
1431 letterSpacingIsAbsolute = true;
1432 features = font.d->features;
1433 } else
1434#endif
1435 {
1436 QFont font = this->font(si);
1437#if QT_CONFIG(harfbuzz)
1438 kerningEnabled = font.d->kerning;
1439 shapingEnabled = (si.analysis.script < QChar::ScriptCount && QFontEngine::scriptRequiresOpenType(QChar::Script(si.analysis.script)))
1440 || (font.d->request.styleStrategy & QFont::PreferNoShaping) == 0;
1441#endif
1442 letterSpacingIsAbsolute = font.d->letterSpacingIsAbsolute;
1443 letterSpacing = font.d->letterSpacing;
1444 wordSpacing = font.d->wordSpacing;
1445 features = font.d->features;
1446
1447 if (letterSpacingIsAbsolute && letterSpacing.value())
1448 letterSpacing *= font.d->dpi / qt_defaultDpiY();
1449 }
1450
1451 // split up the item into parts that come from different font engines
1452 // k * 3 entries, array[k] == index in string, array[k + 1] == index in glyphs, array[k + 2] == engine index
1453 QVarLengthArray<uint, 24> itemBoundaries;
1454
1455 QGlyphLayout initialGlyphs = availableGlyphs(&si);
1456 int nGlyphs = initialGlyphs.numGlyphs;
1457 if (fontEngine->type() == QFontEngine::Multi || !shapingEnabled) {
1458 // ask the font engine to find out which glyphs (as an index in the specific font)
1459 // to use for the text in one item.
1460 QFontEngine::ShaperFlags shaperFlags =
1461 shapingEnabled
1462 ? QFontEngine::GlyphIndicesOnly
1463 : QFontEngine::ShaperFlag(0);
1464 if (fontEngine->stringToCMap(reinterpret_cast<const QChar *>(string), itemLength, &initialGlyphs, &nGlyphs, shaperFlags) < 0)
1465 Q_UNREACHABLE();
1466 }
1467
1468 if (fontEngine->type() == QFontEngine::Multi) {
1469 uint lastEngine = ~0u;
1470 for (int i = 0, glyph_pos = 0; i < itemLength; ++i, ++glyph_pos) {
1471 const uint engineIdx = initialGlyphs.glyphs[glyph_pos] >> 24;
1472 if (lastEngine != engineIdx) {
1473 itemBoundaries.push_back(i);
1474 itemBoundaries.push_back(glyph_pos);
1475 itemBoundaries.push_back(engineIdx);
1476
1477 if (engineIdx != 0) {
1478 QFontEngine *actualFontEngine = static_cast<QFontEngineMulti *>(fontEngine)->engine(engineIdx);
1479 si.ascent = qMax(actualFontEngine->ascent(), si.ascent);
1480 si.descent = qMax(actualFontEngine->descent(), si.descent);
1481 si.leading = qMax(actualFontEngine->leading(), si.leading);
1482 }
1483
1484 lastEngine = engineIdx;
1485 }
1486
1487 if (QChar::isHighSurrogate(string[i]) && i + 1 < itemLength && QChar::isLowSurrogate(string[i + 1]))
1488 ++i;
1489 }
1490 } else {
1491 itemBoundaries.push_back(0);
1492 itemBoundaries.push_back(0);
1493 itemBoundaries.push_back(0);
1494 }
1495
1496#if QT_CONFIG(harfbuzz)
1497 if (Q_LIKELY(shapingEnabled)) {
1498 si.num_glyphs = shapeTextWithHarfbuzzNG(si, baseString, baseStringStart, baseStringLength,
1499 itemLength, fontEngine, itemBoundaries,
1500 kerningEnabled, letterSpacing != 0, features);
1501 } else
1502#endif
1503 {
1504 ushort *log_clusters = logClusters(&si);
1505
1506 int glyph_pos = 0;
1507 for (int i = 0; i < itemLength; ++i, ++glyph_pos) {
1508 log_clusters[i] = glyph_pos;
1509 initialGlyphs.attributes[glyph_pos].clusterStart = true;
1510
1511 bool is_print_char;
1512 if (QChar::isHighSurrogate(string[i])
1513 && i + 1 < itemLength
1514 && QChar::isLowSurrogate(string[i + 1])) {
1515 is_print_char = QChar::isPrint(QChar::surrogateToUcs4(string[i], string[i + 1]));
1516 ++i;
1517 log_clusters[i] = glyph_pos;
1518
1519 } else {
1520 is_print_char = QChar::isPrint(string[i]);
1521 }
1522 initialGlyphs.attributes[glyph_pos].dontPrint =
1523 !is_print_char && !(option.flags() & QTextOption::ShowDefaultIgnorables);
1524
1525 if (Q_UNLIKELY(!initialGlyphs.attributes[glyph_pos].dontPrint)) {
1526 QFontEngine *actualFontEngine = fontEngine;
1527 if (actualFontEngine->type() == QFontEngine::Multi) {
1528 const uint engineIdx = initialGlyphs.glyphs[glyph_pos] >> 24;
1529 actualFontEngine = static_cast<QFontEngineMulti *>(fontEngine)->engine(engineIdx);
1530 }
1531
1532 applyVisibilityRules(string[i], &initialGlyphs, glyph_pos, actualFontEngine);
1533 }
1534 }
1535
1536 si.num_glyphs = glyph_pos;
1537 }
1538
1539 if (Q_UNLIKELY(si.num_glyphs == 0)) {
1540 if (Q_UNLIKELY(!ensureSpace(si.glyph_data_offset + 1))) {
1541 qWarning() << "Unable to allocate space for place-holder glyph";
1542 return;
1543 }
1544
1545 si.num_glyphs = 1;
1546
1547 // Overwrite with 0 token to indicate failure
1548 QGlyphLayout g = availableGlyphs(&si);
1549 g.glyphs[0] = 0;
1550 g.attributes[0].clusterStart = true;
1551
1552 ushort *log_clusters = logClusters(&si);
1553 for (int i = 0; i < itemLength; ++i)
1554 log_clusters[i] = 0;
1555
1556 return;
1557 }
1558
1559 layoutData->used += si.num_glyphs;
1560
1561 QGlyphLayout glyphs = shapedGlyphs(&si);
1562
1563#if QT_CONFIG(harfbuzz)
1564 qt_getJustificationOpportunities(string, itemLength, si, glyphs, logClusters(&si));
1565#endif
1566
1567 if (letterSpacing != 0) {
1568 for (int i = 1; i < si.num_glyphs; ++i) {
1569 if (glyphs.attributes[i].clusterStart) {
1570 if (letterSpacingIsAbsolute)
1571 glyphs.advances[i - 1] += letterSpacing;
1572 else {
1573 QFixed &advance = glyphs.advances[i - 1];
1574 advance += (letterSpacing - 100) * advance / 100;
1575 }
1576 }
1577 }
1578 if (letterSpacingIsAbsolute)
1579 glyphs.advances[si.num_glyphs - 1] += letterSpacing;
1580 else {
1581 QFixed &advance = glyphs.advances[si.num_glyphs - 1];
1582 advance += (letterSpacing - 100) * advance / 100;
1583 }
1584 }
1585 if (wordSpacing != 0) {
1586 for (int i = 0; i < si.num_glyphs; ++i) {
1587 if (glyphs.attributes[i].justification == Justification_Space
1588 || glyphs.attributes[i].justification == Justification_Arabic_Space) {
1589 // word spacing only gets added once to a consecutive run of spaces (see CSS spec)
1590 if (i + 1 == si.num_glyphs
1591 ||(glyphs.attributes[i+1].justification != Justification_Space
1592 && glyphs.attributes[i+1].justification != Justification_Arabic_Space))
1593 glyphs.advances[i] += wordSpacing;
1594 }
1595 }
1596 }
1597
1598 for (int i = 0; i < si.num_glyphs; ++i)
1599 si.width += glyphs.advances[i] * !glyphs.attributes[i].dontPrint;
1600}
1601
1602#if QT_CONFIG(harfbuzz)
1603
1604QT_BEGIN_INCLUDE_NAMESPACE
1605
1606#include "qharfbuzzng_p.h"
1607
1608QT_END_INCLUDE_NAMESPACE
1609
1610int QTextEngine::shapeTextWithHarfbuzzNG(const QScriptItem &si, const ushort *string,
1611 int stringBaseIndex, int stringLength, int itemLength,
1612 QFontEngine *fontEngine, QSpan<uint> itemBoundaries,
1613 bool kerningEnabled, bool hasLetterSpacing,
1614 const QMap<QFont::Tag, quint32> &fontFeatures) const
1615{
1616 uint glyphs_shaped = 0;
1617
1618 if (!buffer) {
1619 buffer = hb_buffer_create();
1620 hb_buffer_set_unicode_funcs(buffer, hb_qt_get_unicode_funcs());
1621 }
1622
1623 hb_buffer_pre_allocate(buffer, itemLength);
1624 if (Q_UNLIKELY(!hb_buffer_allocation_successful(buffer))) {
1625 hb_buffer_destroy(buffer);
1626 buffer = nullptr;
1627 return 0;
1628 }
1629
1630 hb_segment_properties_t props = HB_SEGMENT_PROPERTIES_DEFAULT;
1631 props.direction = si.analysis.bidiLevel % 2 ? HB_DIRECTION_RTL : HB_DIRECTION_LTR;
1632 QChar::Script script = si.analysis.script < QChar::ScriptCount
1633 ? QChar::Script(si.analysis.script)
1634 : QChar::Script_Common;
1635 props.script = hb_qt_script_to_script(script);
1636
1637 // set harfbuzz language from QLocale
1638 const QByteArray localeBcp47 = QLocale().bcp47Name().toUtf8();
1639 const hb_language_t hb_language = hb_language_from_string(localeBcp47.constData(), localeBcp47.size());
1640 if (hb_language == HB_LANGUAGE_INVALID)
1641 props.language = hb_language_get_default();
1642 else
1643 props.language = hb_language;
1644
1645 for (qsizetype k = 0; k < itemBoundaries.size(); k += 3) {
1646 const uint item_pos = itemBoundaries[k];
1647 const uint item_length = (k + 4 < itemBoundaries.size() ? itemBoundaries[k + 3] : itemLength) - item_pos;
1648 const uint engineIdx = itemBoundaries[k + 2];
1649
1650 QFontEngine *actualFontEngine = fontEngine->type() != QFontEngine::Multi ? fontEngine
1651 : static_cast<QFontEngineMulti *>(fontEngine)->engine(engineIdx);
1652
1653
1654 // prepare buffer
1655 hb_buffer_clear_contents(buffer);
1656
1657 // Populate the buffer using the base string pointer and length, so HarfBuzz can grab an
1658 // enclosing context for proper shaping at item boundaries in certain languages (e.g.
1659 // Arabic).
1660 hb_buffer_add_utf16(buffer, reinterpret_cast<const uint16_t *>(string), stringLength,
1661 stringBaseIndex + item_pos, item_length);
1662
1663 hb_buffer_set_segment_properties(buffer, &props);
1664
1665 uint buffer_flags = HB_BUFFER_FLAG_DEFAULT;
1666 // Symbol encoding used to encode various crap in the 32..255 character code range,
1667 // and thus might override U+00AD [SHY]; avoid hiding default ignorables
1668 if (Q_UNLIKELY(actualFontEngine->symbol || (option.flags() & QTextOption::ShowDefaultIgnorables)))
1669 buffer_flags |= HB_BUFFER_FLAG_PRESERVE_DEFAULT_IGNORABLES;
1670 hb_buffer_set_flags(buffer, hb_buffer_flags_t(buffer_flags));
1671
1672
1673 // shape
1674 {
1675 hb_font_t *hb_font = hb_qt_font_get_for_engine(actualFontEngine);
1676 Q_ASSERT(hb_font);
1677 hb_qt_font_set_use_design_metrics(hb_font, option.useDesignMetrics() ? uint(QFontEngine::DesignMetrics) : 0); // ###
1678
1679 // Ligatures are incompatible with custom letter spacing, so when a letter spacing is set,
1680 // we disable them for writing systems where they are purely cosmetic.
1681 bool scriptRequiresOpenType = ((script >= QChar::Script_Syriac && script <= QChar::Script_Sinhala)
1682 || script == QChar::Script_Khmer || script == QChar::Script_Nko);
1683
1684 bool dontLigate = hasLetterSpacing && !scriptRequiresOpenType;
1685
1686 QVarLengthFlatMap<QFont::Tag, hb_feature_t, 16> features;
1687 auto insertFeature = [&features](QFont::Tag tag, quint32 value) {
1688 features.insert(tag, { tag.value(),
1689 value,
1690 HB_FEATURE_GLOBAL_START,
1691 HB_FEATURE_GLOBAL_END });
1692 };
1693 // fontFeatures have precedence
1694 for (const auto &[tag, value]: fontFeatures.asKeyValueRange())
1695 insertFeature(tag, value);
1696 insertFeature(QFont::Tag("kern"), !!kerningEnabled);
1697 if (dontLigate) {
1698 insertFeature(QFont::Tag("liga"), false);
1699 insertFeature(QFont::Tag("clig"), false);
1700 insertFeature(QFont::Tag("dlig"), false);
1701 insertFeature(QFont::Tag("hlig"), false);
1702 }
1703
1704 // whitelist cross-platforms shapers only
1705 constexpr const char *shaper_list[] = {
1706 "graphite2",
1707 "ot",
1708 "fallback",
1709 nullptr
1710 };
1711
1712 bool shapedOk = hb_shape_full(hb_font,
1713 buffer,
1714 features.values().constData(),
1715 features.values().size(),
1716 shaper_list);
1717 if (Q_UNLIKELY(!shapedOk))
1718 return 0;
1719
1720 if (Q_UNLIKELY(HB_DIRECTION_IS_BACKWARD(props.direction)))
1721 hb_buffer_reverse(buffer);
1722 }
1723
1724 uint num_glyphs = hb_buffer_get_length(buffer);
1725 const bool has_glyphs = num_glyphs > 0;
1726 // If Harfbuzz returns zero glyphs, we have to manually add a missing glyph
1727 if (Q_UNLIKELY(!has_glyphs))
1728 num_glyphs = 1;
1729
1730 // ensure we have enough space for shaped glyphs and metrics
1731 if (Q_UNLIKELY(!ensureSpace(glyphs_shaped + num_glyphs)))
1732 return 0;
1733
1734 // fetch the shaped glyphs and metrics
1735 QGlyphLayout g = availableGlyphs(&si).mid(glyphs_shaped, num_glyphs);
1736 ushort *log_clusters = logClusters(&si) + item_pos;
1737 if (Q_LIKELY(has_glyphs)) {
1738 hb_glyph_info_t *infos = hb_buffer_get_glyph_infos(buffer, nullptr);
1739 hb_glyph_position_t *positions = hb_buffer_get_glyph_positions(buffer, nullptr);
1740 uint str_pos = 0;
1741 uint last_cluster = ~0u;
1742 uint last_glyph_pos = glyphs_shaped;
1743 for (uint i = 0; i < num_glyphs; ++i, ++infos, ++positions) {
1744 g.glyphs[i] = infos->codepoint;
1745
1746 g.advances[i] = QFixed::fromFixed(positions->x_advance);
1747 g.offsets[i].x = QFixed::fromFixed(positions->x_offset);
1748 g.offsets[i].y = QFixed::fromFixed(positions->y_offset);
1749
1750 uint cluster = infos->cluster;
1751 if (Q_LIKELY(last_cluster != cluster)) {
1752 g.attributes[i].clusterStart = true;
1753
1754 // fix up clusters so that the cluster indices will be monotonic
1755 // and thus we never return out-of-order indices
1756 for (uint j = last_cluster; j < cluster && str_pos < item_length; ++j)
1757 log_clusters[str_pos++] = last_glyph_pos;
1758 last_glyph_pos = i + glyphs_shaped;
1759 last_cluster = cluster;
1760
1761 applyVisibilityRules(string[stringBaseIndex + item_pos + str_pos], &g, i, actualFontEngine);
1762 }
1763 }
1764 while (str_pos < item_length)
1765 log_clusters[str_pos++] = last_glyph_pos;
1766 } else { // Harfbuzz did not return a glyph for the character, so we add a placeholder
1767 g.glyphs[0] = 0;
1768 g.advances[0] = QFixed{};
1769 g.offsets[0].x = QFixed{};
1770 g.offsets[0].y = QFixed{};
1771 g.attributes[0].clusterStart = true;
1772 g.attributes[0].dontPrint = true;
1773 for (uint str_pos = 0; str_pos < item_length; ++str_pos)
1774 log_clusters[str_pos] = glyphs_shaped;
1775 }
1776
1777 if (Q_UNLIKELY(engineIdx != 0)) {
1778 for (quint32 i = 0; i < num_glyphs; ++i)
1779 g.glyphs[i] |= (engineIdx << 24);
1780 }
1781
1782 if (!actualFontEngine->supportsHorizontalSubPixelPositions()) {
1783 for (uint i = 0; i < num_glyphs; ++i) {
1784 g.advances[i] = g.advances[i].round();
1785 g.offsets[i].x = g.offsets[i].x.round();
1786 }
1787 }
1788
1789 glyphs_shaped += num_glyphs;
1790 }
1791
1792 return glyphs_shaped;
1793}
1794
1795#endif // harfbuzz
1796
1797void QTextEngine::init(QTextEngine *e)
1798{
1799 e->ignoreBidi = false;
1800 e->cacheGlyphs = false;
1801 e->forceJustification = false;
1802 e->visualMovement = false;
1803 e->delayDecorations = false;
1804
1805 e->layoutData = nullptr;
1806
1807 e->minWidth = 0;
1808 e->maxWidth = 0;
1809
1810 e->specialData = nullptr;
1811 e->stackEngine = false;
1812#ifndef QT_NO_RAWFONT
1813 e->useRawFont = false;
1814#endif
1815}
1816
1817QTextEngine::QTextEngine()
1818{
1819 init(this);
1820}
1821
1822QTextEngine::QTextEngine(const QString &str, const QFont &f)
1823 : text(str),
1824 fnt(f)
1825{
1826 init(this);
1827}
1828
1829QTextEngine::~QTextEngine()
1830{
1831 if (!stackEngine)
1832 delete layoutData;
1833 delete specialData;
1834 resetFontEngineCache();
1835#if QT_CONFIG(harfbuzz)
1836 if (buffer) {
1837 hb_buffer_destroy(buffer);
1838 buffer = nullptr;
1839 }
1840#endif
1841}
1842
1843const QCharAttributes *QTextEngine::attributes() const
1844{
1845 if (layoutData && layoutData->haveCharAttributes)
1846 return (QCharAttributes *) layoutData->memory;
1847
1848 itemize();
1849 if (! ensureSpace(layoutData->string.size()))
1850 return nullptr;
1851
1852 QVarLengthArray<QUnicodeTools::ScriptItem> scriptItems(layoutData->items.size());
1853 for (int i = 0; i < layoutData->items.size(); ++i) {
1854 const QScriptItem &si = layoutData->items.at(i);
1855 scriptItems[i].position = si.position;
1856 scriptItems[i].script = QChar::Script(si.analysis.script);
1857 }
1858
1859 QUnicodeTools::initCharAttributes(
1860 layoutData->string,
1861 scriptItems.data(), scriptItems.size(),
1862 reinterpret_cast<QCharAttributes *>(layoutData->memory),
1863 QUnicodeTools::CharAttributeOptions(QUnicodeTools::GraphemeBreaks
1864 | QUnicodeTools::LineBreaks
1865 | QUnicodeTools::WhiteSpaces
1866 | QUnicodeTools::HangulLineBreakTailoring));
1867
1868
1869 layoutData->haveCharAttributes = true;
1870 return (QCharAttributes *) layoutData->memory;
1871}
1872
1873void QTextEngine::shape(int item) const
1874{
1875 auto &li = layoutData->items[item];
1876 if (li.analysis.flags == QScriptAnalysis::Object) {
1877 ensureSpace(1);
1878 if (QTextDocumentPrivate::get(block) != nullptr) {
1879 docLayout()->resizeInlineObject(QTextInlineObject(item, const_cast<QTextEngine *>(this)),
1880 li.position + block.position(),
1881 format(&li));
1882 } else {
1883 // Standalone QTextLayout (no QTextDocument): read the
1884 // object size from a QTextImageFormat set via setFormats().
1885 QTextCharFormat fmt = format(&li);
1886 if (fmt.isImageFormat()) {
1887 QTextImageFormat imgFmt = fmt.toImageFormat();
1888 const qreal w = imgFmt.width();
1889 const qreal h = imgFmt.height();
1890 if (w > 0 && h > 0) {
1891 QTextInlineObject obj(item, const_cast<QTextEngine *>(this));
1892 obj.setWidth(w);
1893 // Mirror QTextDocumentLayout::resizeInlineObject()
1894 // vertical alignment logic.
1895 const QFontMetricsF fm(fnt);
1896 switch (fmt.verticalAlignment()) {
1897 case QTextCharFormat::AlignMiddle: {
1898 const qreal halfX = fm.xHeight() / 2.0;
1899 obj.setAscent((h + halfX) / 2.0);
1900 obj.setDescent((h - halfX) / 2.0);
1901 break;
1902 }
1903 case QTextCharFormat::AlignBaseline: {
1904 const qreal descent = fm.descent();
1905 obj.setDescent(descent);
1906 obj.setAscent(h - descent);
1907 break;
1908 }
1909 default:
1910 obj.setDescent(0);
1911 obj.setAscent(h);
1912 break;
1913 }
1914 }
1915 }
1916 }
1917 // fix log clusters to point to the previous glyph, as the object doesn't have a glyph of it's own.
1918 // This is required so that all entries in the array get initialized and are ordered correctly.
1919 if (layoutData->logClustersPtr) {
1920 ushort *lc = logClusters(&li);
1921 *lc = (lc != layoutData->logClustersPtr) ? lc[-1] : 0;
1922 }
1923 } else if (li.analysis.flags == QScriptAnalysis::Tab) {
1924 // set up at least the ascent/descent/leading of the script item for the tab
1925 fontEngine(li, &li.ascent, &li.descent, &li.leading);
1926 // see the comment above
1927 if (layoutData->logClustersPtr) {
1928 ushort *lc = logClusters(&li);
1929 *lc = (lc != layoutData->logClustersPtr) ? lc[-1] : 0;
1930 }
1931 } else {
1932 shapeText(item);
1933 }
1934}
1935
1936static inline void releaseCachedFontEngine(QFontEngine *fontEngine)
1937{
1938 if (fontEngine && !fontEngine->ref.deref())
1939 delete fontEngine;
1940}
1941
1942void QTextEngine::resetFontEngineCache()
1943{
1944 releaseCachedFontEngine(feCache.prevFontEngine);
1945 releaseCachedFontEngine(feCache.prevScaledFontEngine);
1946 feCache.reset();
1947}
1948
1949void QTextEngine::invalidate()
1950{
1951 freeMemory();
1952 minWidth = 0;
1953 maxWidth = 0;
1954
1955 resetFontEngineCache();
1956}
1957
1958void QTextEngine::clearLineData()
1959{
1960 lines.clear();
1961}
1962
1963void QTextEngine::validate() const
1964{
1965 if (layoutData)
1966 return;
1967 layoutData = new LayoutData();
1968 if (QTextDocumentPrivate::get(block) != nullptr) {
1969 layoutData->string = block.text();
1970 const bool nextBlockValid = block.next().isValid();
1971 if (!nextBlockValid && option.flags() & QTextOption::ShowDocumentTerminator) {
1972 layoutData->string += QLatin1Char('\xA7');
1973 } else if (option.flags() & QTextOption::ShowLineAndParagraphSeparators) {
1974 layoutData->string += QLatin1Char(nextBlockValid ? '\xB6' : '\x20');
1975 }
1976
1977 } else {
1978 layoutData->string = text;
1979 }
1980 if (specialData && specialData->preeditPosition != -1)
1981 layoutData->string.insert(specialData->preeditPosition, specialData->preeditText);
1982}
1983
1984#if !defined(QT_NO_EMOJISEGMENTER)
1985namespace {
1986
1987 enum CharacterCategory {
1988 EMOJI = 0,
1989 EMOJI_TEXT_PRESENTATION = 1,
1990 EMOJI_EMOJI_PRESENTATION = 2,
1991 EMOJI_MODIFIER_BASE = 3,
1992 EMOJI_MODIFIER = 4,
1993 EMOJI_VS_BASE = 5,
1994 REGIONAL_INDICATOR = 6,
1995 KEYCAP_BASE = 7,
1996 COMBINING_ENCLOSING_KEYCAP = 8,
1997 COMBINING_ENCLOSING_CIRCLE_BACKSLASH = 9,
1998 ZWJ = 10,
1999 VS15 = 11,
2000 VS16 = 12,
2001 TAG_BASE = 13,
2002 TAG_SEQUENCE = 14,
2003 TAG_TERM = 15,
2004 OTHER = 16
2005 };
2006
2007 typedef CharacterCategory *emoji_text_iter_t;
2008
2009 #include "../../3rdparty/emoji-segmenter/emoji_presentation_scanner.c"
2010}
2011#endif
2012
2013void QTextEngine::itemize() const
2014{
2015 validate();
2016 if (layoutData->items.size())
2017 return;
2018
2019 int length = layoutData->string.size();
2020 if (!length)
2021 return;
2022
2023 const ushort *string = reinterpret_cast<const ushort *>(layoutData->string.unicode());
2024
2025 bool rtl = isRightToLeft();
2026
2027 QVarLengthArray<QScriptAnalysis, 4096> scriptAnalysis(length);
2028 QScriptAnalysis *analysis = scriptAnalysis.data();
2029
2030 QBidiAlgorithm bidi(layoutData->string.constData(), analysis, length, rtl);
2031 layoutData->hasBidi = bidi.process();
2032
2033 {
2034 QUnicodeTools::ScriptItemArray scriptItems;
2035 QUnicodeTools::initScripts(layoutData->string, &scriptItems);
2036 for (int i = 0; i < scriptItems.size(); ++i) {
2037 const auto &item = scriptItems.at(i);
2038 int end = i < scriptItems.size() - 1 ? scriptItems.at(i + 1).position : length;
2039 for (int j = item.position; j < end; ++j)
2040 analysis[j].script = item.script;
2041 }
2042 }
2043
2044#if !defined(QT_NO_EMOJISEGMENTER)
2045 const bool disableEmojiSegmenter = QFontEngine::disableEmojiSegmenter() || option.flags().testFlag(QTextOption::DisableEmojiParsing);
2046
2047 qCDebug(lcEmojiSegmenter) << "Emoji segmenter disabled:" << disableEmojiSegmenter;
2048
2049 QVarLengthArray<CharacterCategory> categorizedString;
2050 if (!disableEmojiSegmenter) {
2051 // Parse emoji sequences
2052 for (int i = 0; i < length; ++i) {
2053 const QChar &c = string[i];
2054 const bool isSurrogate = c.isHighSurrogate() && i < length - 1;
2055 const char32_t ucs4 = isSurrogate
2056 ? QChar::surrogateToUcs4(c, string[++i])
2057 : c.unicode();
2058 const QUnicodeTables::Properties *p = QUnicodeTables::properties(ucs4);
2059
2060 if (ucs4 == 0x20E3)
2061 categorizedString.append(CharacterCategory::COMBINING_ENCLOSING_KEYCAP);
2062 else if (ucs4 == 0x20E0)
2063 categorizedString.append(CharacterCategory::COMBINING_ENCLOSING_CIRCLE_BACKSLASH);
2064 else if (ucs4 == 0xFE0E)
2065 categorizedString.append(CharacterCategory::VS15);
2066 else if (ucs4 == 0xFE0F)
2067 categorizedString.append(CharacterCategory::VS16);
2068 else if (ucs4 == 0x200D)
2069 categorizedString.append(CharacterCategory::ZWJ);
2070 else if (ucs4 == 0x1F3F4)
2071 categorizedString.append(CharacterCategory::TAG_BASE);
2072 else if (ucs4 == 0xE007F)
2073 categorizedString.append(CharacterCategory::TAG_TERM);
2074 else if ((ucs4 >= 0xE0030 && ucs4 <= 0xE0039) || (ucs4 >= 0xE0061 && ucs4 <= 0xE007A))
2075 categorizedString.append(CharacterCategory::TAG_SEQUENCE);
2076 else if (ucs4 >= 0x1F1E6 && ucs4 <= 0x1F1FF)
2077 categorizedString.append(CharacterCategory::REGIONAL_INDICATOR);
2078 // emoji_keycap_sequence = [0-9#*] \x{FE0F 20E3}
2079 else if ((ucs4 >= 0x0030 && ucs4 <= 0x0039) || ucs4 == 0x0023 || ucs4 == 0x002A)
2080 categorizedString.append(CharacterCategory::KEYCAP_BASE);
2081 else if (p->emojiFlags & uchar(QUnicodeTables::EmojiFlags::Emoji_Modifier_Base))
2082 categorizedString.append(CharacterCategory::EMOJI_MODIFIER_BASE);
2083 else if (p->emojiFlags & uchar(QUnicodeTables::EmojiFlags::Emoji_Modifier))
2084 categorizedString.append(CharacterCategory::EMOJI_MODIFIER);
2085 else if (p->emojiFlags & uchar(QUnicodeTables::EmojiFlags::Emoji_Presentation))
2086 categorizedString.append(CharacterCategory::EMOJI_EMOJI_PRESENTATION);
2087 // If it's in the emoji list and doesn't have the emoji presentation, it is text
2088 // presentation.
2089 else if (p->emojiFlags & uchar(QUnicodeTables::EmojiFlags::Emoji))
2090 categorizedString.append(CharacterCategory::EMOJI_TEXT_PRESENTATION);
2091 else
2092 categorizedString.append(CharacterCategory::OTHER);
2093
2094 qCDebug(lcEmojiSegmenter) << "Checking character" << (isSurrogate ? (i - 1) : i)
2095 << ", ucs4 ==" << ucs4
2096 << ", category:" << categorizedString.last();
2097 }
2098 }
2099#endif
2100
2101 const ushort *uc = string;
2102 const ushort *e = uc + length;
2103
2104#if !defined(QT_NO_EMOJISEGMENTER)
2105 const emoji_text_iter_t categoriesStart = categorizedString.data();
2106 const emoji_text_iter_t categoriesEnd = categoriesStart + categorizedString.size();
2107
2108 emoji_text_iter_t categoryIt = categoriesStart;
2109
2110 bool isEmoji = false;
2111 bool hasVs = false;
2112 emoji_text_iter_t nextIt = categoryIt;
2113#endif
2114
2115 while (uc < e) {
2116#if !defined(QT_NO_EMOJISEGMENTER)
2117 // Find next emoji sequence
2118 if (!disableEmojiSegmenter && categoryIt == nextIt) {
2119 nextIt = scan_emoji_presentation(categoryIt, categoriesEnd, &isEmoji, &hasVs);
2120
2121 qCDebug(lcEmojiSegmenter) << "Checking character" << (categoryIt - categoriesStart)
2122 << ", sequence length:" << (nextIt - categoryIt)
2123 << ", is emoji sequence:" << isEmoji;
2124
2125 }
2126#endif
2127
2128 switch (*uc) {
2129 case QChar::ObjectReplacementCharacter:
2130 {
2131 const QTextDocumentPrivate *doc_p = QTextDocumentPrivate::get(block);
2132 if (doc_p != nullptr
2133 && doc_p->layout() != nullptr
2134 && QAbstractTextDocumentLayoutPrivate::get(doc_p->layout()) != nullptr
2135 && QAbstractTextDocumentLayoutPrivate::get(doc_p->layout())->hasHandlers()) {
2136 analysis->flags = QScriptAnalysis::Object;
2137 } else if (specialData) {
2138 // Standalone QTextLayout: check if a QTextImageFormat
2139 // was set for this position via setFormats().
2140 const int pos = uc - string;
2141 analysis->flags = QScriptAnalysis::None;
2142 for (const auto &range : std::as_const(specialData->formats)) {
2143 if (range.start <= pos && pos < range.start + range.length
2144 && range.format.isImageFormat()) {
2145 analysis->flags = QScriptAnalysis::Object;
2146 break;
2147 }
2148 }
2149 } else {
2150 analysis->flags = QScriptAnalysis::None;
2151 }
2152 }
2153 break;
2154 case QChar::LineSeparator:
2155 analysis->flags = QScriptAnalysis::LineOrParagraphSeparator;
2156 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators) {
2157 const int offset = uc - string;
2158 layoutData->string.detach();
2159 string = reinterpret_cast<const ushort *>(layoutData->string.unicode());
2160 uc = string + offset;
2161 e = string + length;
2162 *const_cast<ushort*>(uc) = 0x21B5; // visual line separator
2163 }
2164 break;
2165 case QChar::Tabulation:
2166 analysis->flags = QScriptAnalysis::Tab;
2167 analysis->bidiLevel = bidi.baseLevel;
2168 break;
2169 case QChar::Space:
2170 case QChar::Nbsp:
2171 if (option.flags() & QTextOption::ShowTabsAndSpaces) {
2172 analysis->flags = (*uc == QChar::Space) ? QScriptAnalysis::Space : QScriptAnalysis::Nbsp;
2173 break;
2174 }
2175 Q_FALLTHROUGH();
2176 default:
2177 analysis->flags = QScriptAnalysis::None;
2178 break;
2179 };
2180
2181#if !defined(QT_NO_EMOJISEGMENTER)
2182 if (!disableEmojiSegmenter) {
2183 if (isEmoji) {
2184 static_assert(QChar::ScriptCount < USHRT_MAX);
2185 analysis->script = QFontDatabasePrivate::Script_Emoji;
2186 }
2187
2188 if (QChar::isHighSurrogate(*uc) && (uc + 1) < e && QChar::isLowSurrogate(*(uc + 1))) {
2189 if (isEmoji)
2190 (analysis + 1)->script = QFontDatabasePrivate::Script_Emoji;
2191
2192 ++uc;
2193 ++analysis;
2194 }
2195
2196 ++categoryIt;
2197 }
2198#endif
2199
2200 ++uc;
2201 ++analysis;
2202 }
2203 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators) {
2204 (analysis-1)->flags = QScriptAnalysis::LineOrParagraphSeparator; // to exclude it from width
2205 }
2206
2207 Itemizer itemizer(layoutData->string, scriptAnalysis.data(), layoutData->items);
2208
2209 const QTextDocumentPrivate *p = QTextDocumentPrivate::get(block);
2210 if (p) {
2211 SpecialData *s = specialData;
2212
2213 QTextDocumentPrivate::FragmentIterator it = p->find(block.position());
2214 QTextDocumentPrivate::FragmentIterator end = p->find(block.position() + block.length() - 1); // -1 to omit the block separator char
2215 int format = it.value()->format;
2216
2217 int preeditPosition = s ? s->preeditPosition : INT_MAX;
2218 int prevPosition = 0;
2219 int position = prevPosition;
2220 while (1) {
2221 const QTextFragmentData * const frag = it.value();
2222 if (it == end || format != frag->format) {
2223 if (s && position >= preeditPosition) {
2224 position += s->preeditText.size();
2225 preeditPosition = INT_MAX;
2226 }
2227 Q_ASSERT(position <= length);
2228 QFont::Capitalization capitalization =
2229 formatCollection()->charFormat(format).hasProperty(QTextFormat::FontCapitalization)
2230 ? formatCollection()->charFormat(format).fontCapitalization()
2231 : formatCollection()->defaultFont().capitalization();
2232 if (s) {
2233 for (const auto &range : std::as_const(s->formats)) {
2234 if (range.start + range.length <= prevPosition || range.start >= position)
2235 continue;
2236 if (range.format.hasProperty(QTextFormat::FontCapitalization)) {
2237 if (range.start > prevPosition)
2238 itemizer.generate(prevPosition, range.start - prevPosition, capitalization);
2239 int newStart = std::max(prevPosition, range.start);
2240 int newEnd = std::min(position, range.start + range.length);
2241 itemizer.generate(newStart, newEnd - newStart, range.format.fontCapitalization());
2242 prevPosition = newEnd;
2243 }
2244 }
2245 }
2246 itemizer.generate(prevPosition, position - prevPosition, capitalization);
2247 if (it == end) {
2248 if (position < length)
2249 itemizer.generate(position, length - position, capitalization);
2250 break;
2251 }
2252 format = frag->format;
2253 prevPosition = position;
2254 }
2255 position += frag->size_array[0];
2256 ++it;
2257 }
2258 } else {
2259#ifndef QT_NO_RAWFONT
2260 if (useRawFont && specialData) {
2261 int lastIndex = 0;
2262 for (int i = 0; i < specialData->formats.size(); ++i) {
2263 const QTextLayout::FormatRange &range = specialData->formats.at(i);
2264 const QTextCharFormat &format = range.format;
2265 if (format.hasProperty(QTextFormat::FontCapitalization)) {
2266 itemizer.generate(lastIndex, range.start - lastIndex, QFont::MixedCase);
2267 itemizer.generate(range.start, range.length, format.fontCapitalization());
2268 lastIndex = range.start + range.length;
2269 }
2270 }
2271 itemizer.generate(lastIndex, length - lastIndex, QFont::MixedCase);
2272 } else
2273#endif
2274 itemizer.generate(0, length, static_cast<QFont::Capitalization> (fnt.d->capital));
2275 }
2276
2277 addRequiredBoundaries();
2278 resolveFormats();
2279}
2280
2281bool QTextEngine::isRightToLeft() const
2282{
2283 switch (option.textDirection()) {
2284 case Qt::LeftToRight:
2285 return false;
2286 case Qt::RightToLeft:
2287 return true;
2288 default:
2289 break;
2290 }
2291 if (!layoutData)
2292 itemize();
2293 // this places the cursor in the right position depending on the keyboard layout
2294 if (layoutData->string.isEmpty())
2295 return QGuiApplication::inputMethod()->inputDirection() == Qt::RightToLeft;
2296 return layoutData->string.isRightToLeft();
2297}
2298
2299
2300int QTextEngine::findItem(int strPos, int firstItem) const
2301{
2302 itemize();
2303 if (strPos < 0 || strPos >= layoutData->string.size() || firstItem < 0)
2304 return -1;
2305
2306 int left = firstItem + 1;
2307 int right = layoutData->items.size()-1;
2308 while(left <= right) {
2309 int middle = ((right-left)/2)+left;
2310 if (strPos > layoutData->items.at(middle).position)
2311 left = middle+1;
2312 else if (strPos < layoutData->items.at(middle).position)
2313 right = middle-1;
2314 else {
2315 return middle;
2316 }
2317 }
2318 return right;
2319}
2320
2321namespace {
2322template<typename InnerFunc>
2323void textIterator(const QTextEngine *textEngine, int from, int len, QFixed &width, InnerFunc &&innerFunc)
2324{
2325 for (int i = 0; i < textEngine->layoutData->items.size(); i++) {
2326 const QScriptItem *si = textEngine->layoutData->items.constData() + i;
2327 int pos = si->position;
2328 int ilen = textEngine->length(i);
2329// qDebug("item %d: from %d len %d", i, pos, ilen);
2330 if (pos >= from + len)
2331 break;
2332 if (pos + ilen > from) {
2333 if (!si->num_glyphs)
2334 textEngine->shape(i);
2335
2336 if (si->analysis.flags == QScriptAnalysis::Object) {
2337 width += si->width;
2338 continue;
2339 } else if (si->analysis.flags == QScriptAnalysis::Tab) {
2340 width += textEngine->calculateTabWidth(i, width);
2341 continue;
2342 }
2343
2344 unsigned short *logClusters = textEngine->logClusters(si);
2345
2346// fprintf(stderr, " logclusters:");
2347// for (int k = 0; k < ilen; k++)
2348// fprintf(stderr, " %d", logClusters[k]);
2349// fprintf(stderr, "\n");
2350 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
2351 int charFrom = from - pos;
2352 if (charFrom < 0)
2353 charFrom = 0;
2354 int glyphStart = logClusters[charFrom];
2355 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
2356 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
2357 charFrom++;
2358 if (charFrom < ilen) {
2359 glyphStart = logClusters[charFrom];
2360 int charEnd = from + len - 1 - pos;
2361 if (charEnd >= ilen)
2362 charEnd = ilen-1;
2363 int glyphEnd = logClusters[charEnd];
2364 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
2365 charEnd++;
2366 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
2367
2368// qDebug("char: start=%d end=%d / glyph: start = %d, end = %d", charFrom, charEnd, glyphStart, glyphEnd);
2369 innerFunc(glyphStart, glyphEnd, si);
2370 }
2371 }
2372 }
2373}
2374} // namespace
2375
2376QFixed QTextEngine::width(int from, int len) const
2377{
2378 itemize();
2379
2380 QFixed w = 0;
2381// qDebug("QTextEngine::width(from = %d, len = %d), numItems=%d, strleng=%d", from, len, items.size(), string.length());
2382 textIterator(this, from, len, w, [this, &w](int glyphStart, int glyphEnd, const QScriptItem *si) {
2383 QGlyphLayout glyphs = this->shapedGlyphs(si);
2384 for (int j = glyphStart; j < glyphEnd; j++)
2385 w += glyphs.advances[j] * !glyphs.attributes[j].dontPrint;
2386 });
2387// qDebug(" --> w= %d ", w);
2388 return w;
2389}
2390
2391glyph_metrics_t QTextEngine::boundingBox(int from, int len) const
2392{
2393 itemize();
2394
2395 glyph_metrics_t gm;
2396
2397 textIterator(this, from, len, gm.width, [this, &gm](int glyphStart, int glyphEnd, const QScriptItem *si) {
2398 if (glyphStart <= glyphEnd) {
2399 QGlyphLayout glyphs = this->shapedGlyphs(si);
2400 QFontEngine *fe = this->fontEngine(*si);
2401 glyph_metrics_t m = fe->boundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
2402 gm.x = qMin(gm.x, m.x + gm.xoff);
2403 gm.y = qMin(gm.y, m.y + gm.yoff);
2404 gm.width = qMax(gm.width, m.width + gm.xoff);
2405 gm.height = qMax(gm.height, m.height + gm.yoff);
2406 gm.xoff += m.xoff;
2407 gm.yoff += m.yoff;
2408 }
2409 });
2410
2411 return gm;
2412}
2413
2414glyph_metrics_t QTextEngine::tightBoundingBox(int from, int len) const
2415{
2416 itemize();
2417
2418 glyph_metrics_t gm;
2419
2420 textIterator(this, from, len, gm.width, [this, &gm](int glyphStart, int glyphEnd, const QScriptItem *si) {
2421 if (glyphStart <= glyphEnd) {
2422 QGlyphLayout glyphs = this->shapedGlyphs(si);
2423 QFontEngine *fe = fontEngine(*si);
2424
2425 QTextItem::RenderFlags flags = si->analysis.bidiLevel % 2
2426 ? QTextItem::RightToLeft
2427 : QTextItem::RenderFlags();
2428 glyph_metrics_t m = fe->tightBoundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart), flags);
2429
2430 gm.x = qMin(gm.x, m.x + gm.xoff);
2431 gm.y = qMin(gm.y, m.y + gm.yoff);
2432 gm.width = qMax(gm.width, m.width + gm.xoff);
2433 gm.height = qMax(gm.height, m.height + gm.yoff);
2434 gm.xoff += m.xoff;
2435 gm.yoff += m.yoff;
2436 }
2437 });
2438 return gm;
2439}
2440
2441QFont QTextEngine::font(const QScriptItem &si) const
2442{
2443 QFont font = fnt;
2444 if (hasFormats()) {
2445 QTextCharFormat f = format(&si);
2446 font = f.font();
2447
2448 const QTextDocumentPrivate *document_d = QTextDocumentPrivate::get(block);
2449 if (document_d != nullptr && document_d->layout() != nullptr) {
2450 // Make sure we get the right dpi on printers
2451 QPaintDevice *pdev = document_d->layout()->paintDevice();
2452 if (pdev)
2453 font = QFont(font, pdev);
2454 } else {
2455 font = font.resolve(fnt);
2456 }
2457 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
2458 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
2459 if (font.pointSize() != -1)
2460 font.setPointSize((font.pointSize() * 2) / 3);
2461 else
2462 font.setPixelSize((font.pixelSize() * 2) / 3);
2463 }
2464 }
2465
2466 if (si.analysis.flags == QScriptAnalysis::SmallCaps)
2467 font = font.d->smallCapsFont();
2468
2469 return font;
2470}
2471
2472QTextEngine::FontEngineCache::FontEngineCache()
2473{
2474 reset();
2475}
2476
2477//we cache the previous results of this function, as calling it numerous times with the same effective
2478//input is common (and hard to cache at a higher level)
2479QFontEngine *QTextEngine::fontEngine(const QScriptItem &si, QFixed *ascent, QFixed *descent, QFixed *leading) const
2480{
2481 QFontEngine *engine = nullptr;
2482 QFontEngine *scaledEngine = nullptr;
2483 int script = si.analysis.script;
2484
2485 QFont font = fnt;
2486#ifndef QT_NO_RAWFONT
2487 if (useRawFont && rawFont.isValid()) {
2488 if (feCache.prevFontEngine && feCache.prevFontEngine->type() == QFontEngine::Multi && feCache.prevScript == script) {
2489 engine = feCache.prevFontEngine;
2490 } else {
2491 engine = QFontEngineMulti::createMultiFontEngine(rawFont.d->fontEngine, script);
2492 feCache.prevFontEngine = engine;
2493 feCache.prevScript = script;
2494 engine->ref.ref();
2495 if (feCache.prevScaledFontEngine) {
2496 releaseCachedFontEngine(feCache.prevScaledFontEngine);
2497 feCache.prevScaledFontEngine = nullptr;
2498 }
2499 }
2500 if (si.analysis.flags == QScriptAnalysis::SmallCaps) {
2501 if (feCache.prevScaledFontEngine) {
2502 scaledEngine = feCache.prevScaledFontEngine;
2503 } else {
2504 // GCC 12 gets confused about QFontEngine::ref, for some non-obvious reason
2505 // warning: ‘unsigned int __atomic_or_fetch_4(volatile void*, unsigned int, int)’ writing 4 bytes
2506 // into a region of size 0 overflows the destination [-Wstringop-overflow=]
2507 QT_WARNING_PUSH
2508 QT_WARNING_DISABLE_GCC("-Wstringop-overflow")
2509
2510 QFontEngine *scEngine = rawFont.d->fontEngine->cloneWithSize(smallCapsFraction * rawFont.pixelSize());
2511 scEngine->ref.ref();
2512 scaledEngine = QFontEngineMulti::createMultiFontEngine(scEngine, script);
2513 scaledEngine->ref.ref();
2514 feCache.prevScaledFontEngine = scaledEngine;
2515 // If scEngine is not ref'ed by scaledEngine, make sure it is deallocated and not leaked.
2516 if (!scEngine->ref.deref())
2517 delete scEngine;
2518
2519 QT_WARNING_POP
2520 }
2521 }
2522 } else
2523#endif
2524 {
2525 if (hasFormats()) {
2526 if (feCache.prevFontEngine && feCache.prevPosition == si.position && feCache.prevLength == length(&si) && feCache.prevScript == script) {
2527 engine = feCache.prevFontEngine;
2528 scaledEngine = feCache.prevScaledFontEngine;
2529 } else {
2530 QTextCharFormat f = format(&si);
2531 font = f.font();
2532
2533 if (QTextDocumentPrivate::get(block) != nullptr && QTextDocumentPrivate::get(block)->layout() != nullptr) {
2534 // Make sure we get the right dpi on printers
2535 QPaintDevice *pdev = QTextDocumentPrivate::get(block)->layout()->paintDevice();
2536 if (pdev)
2537 font = QFont(font, pdev);
2538 } else {
2539 font = font.resolve(fnt);
2540 }
2541 engine = font.d->engineForScript(script);
2542 Q_ASSERT(engine);
2543 engine->ref.ref();
2544
2545 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
2546 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
2547 if (font.pointSize() != -1)
2548 font.setPointSize((font.pointSize() * 2) / 3);
2549 else
2550 font.setPixelSize((font.pixelSize() * 2) / 3);
2551 scaledEngine = font.d->engineForScript(script);
2552 if (scaledEngine)
2553 scaledEngine->ref.ref();
2554 }
2555
2556 if (feCache.prevFontEngine)
2557 releaseCachedFontEngine(feCache.prevFontEngine);
2558 feCache.prevFontEngine = engine;
2559
2560 if (feCache.prevScaledFontEngine)
2561 releaseCachedFontEngine(feCache.prevScaledFontEngine);
2562 feCache.prevScaledFontEngine = scaledEngine;
2563
2564 feCache.prevScript = script;
2565 feCache.prevPosition = si.position;
2566 feCache.prevLength = length(&si);
2567 }
2568 } else {
2569 if (feCache.prevFontEngine && feCache.prevScript == script && feCache.prevPosition == -1) {
2570 engine = feCache.prevFontEngine;
2571 } else {
2572 engine = font.d->engineForScript(script);
2573 Q_ASSERT(engine);
2574 engine->ref.ref();
2575 if (feCache.prevFontEngine)
2576 releaseCachedFontEngine(feCache.prevFontEngine);
2577 feCache.prevFontEngine = engine;
2578
2579 feCache.prevScript = script;
2580 feCache.prevPosition = -1;
2581 feCache.prevLength = -1;
2582 feCache.prevScaledFontEngine = nullptr;
2583 }
2584 }
2585
2586 if (si.analysis.flags == QScriptAnalysis::SmallCaps) {
2587 QFontPrivate *p = font.d->smallCapsFontPrivate();
2588 scaledEngine = p->engineForScript(script);
2589 }
2590 }
2591
2592 if (leading) {
2593 Q_ASSERT(engine);
2594 Q_ASSERT(ascent);
2595 Q_ASSERT(descent);
2596 *ascent = engine->ascent();
2597 *descent = engine->descent();
2598 *leading = engine->leading();
2599 }
2600
2601 if (scaledEngine)
2602 return scaledEngine;
2603 return engine;
2604}
2605
2611
2613
2614static void set(QJustificationPoint *point, int type, const QGlyphLayout &glyph, QFontEngine *fe)
2615{
2616 point->type = type;
2617 point->glyph = glyph;
2618
2619 if (type >= Justification_Arabic_Normal) {
2620 const char32_t ch = U'\x640'; // Kashida character
2621
2622 glyph_t kashidaGlyph = fe->glyphIndex(ch);
2623 if (kashidaGlyph != 0) {
2624 QGlyphLayout g;
2625 g.numGlyphs = 1;
2626 g.glyphs = &kashidaGlyph;
2627 g.advances = &point->kashidaWidth;
2628 fe->recalcAdvances(&g, { });
2629
2630 if (point->kashidaWidth == 0)
2632 } else {
2634 point->kashidaWidth = 0;
2635 }
2636 }
2637}
2638
2639
2640void QTextEngine::justify(const QScriptLine &line)
2641{
2642// qDebug("justify: line.gridfitted = %d, line.justified=%d", line.gridfitted, line.justified);
2643 if (line.gridfitted && line.justified)
2644 return;
2645
2646 if (!line.gridfitted) {
2647 // redo layout in device metrics, then adjust
2648 const_cast<QScriptLine &>(line).gridfitted = true;
2649 }
2650
2651 if ((option.alignment() & Qt::AlignHorizontal_Mask) != Qt::AlignJustify)
2652 return;
2653
2654 itemize();
2655
2656 if (!forceJustification) {
2657 int end = line.from + (int)line.length + line.trailingSpaces;
2658 if (end == layoutData->string.size())
2659 return; // no justification at end of paragraph
2660 if (end && layoutData->items.at(findItem(end - 1)).analysis.flags == QScriptAnalysis::LineOrParagraphSeparator)
2661 return; // no justification at the end of an explicitly separated line
2662 }
2663
2664 // justify line
2665 int maxJustify = 0;
2666
2667 // don't include trailing white spaces when doing justification
2668 int line_length = line.length;
2669 const QCharAttributes *a = attributes();
2670 if (! a)
2671 return;
2672 a += line.from;
2673 while (line_length && a[line_length-1].whiteSpace)
2674 --line_length;
2675 // subtract one char more, as we can't justfy after the last character
2676 --line_length;
2677
2678 if (line_length <= 0)
2679 return;
2680
2681 int firstItem = findItem(line.from);
2682 int lastItem = findItem(line.from + line_length - 1, firstItem);
2683 int nItems = (firstItem >= 0 && lastItem >= firstItem)? (lastItem-firstItem+1) : 0;
2684
2685 QVarLengthArray<QJustificationPoint> justificationPoints;
2686 int nPoints = 0;
2687// qDebug("justifying from %d len %d, firstItem=%d, nItems=%d (%s)", line.from, line_length, firstItem, nItems, layoutData->string.mid(line.from, line_length).toUtf8().constData());
2688 QFixed minKashida = 0x100000;
2689
2690 // we need to do all shaping before we go into the next loop, as we there
2691 // store pointers to the glyph data that could get reallocated by the shaping
2692 // process.
2693 for (int i = 0; i < nItems; ++i) {
2694 const QScriptItem &si = layoutData->items.at(firstItem + i);
2695 if (!si.num_glyphs)
2696 shape(firstItem + i);
2697 }
2698
2699 for (int i = 0; i < nItems; ++i) {
2700 const QScriptItem &si = layoutData->items.at(firstItem + i);
2701
2702 int kashida_type = Justification_Arabic_Normal;
2703 int kashida_pos = -1;
2704
2705 int start = qMax(line.from - si.position, 0);
2706 int end = qMin(line.from + line_length - (int)si.position, length(firstItem+i));
2707
2708 unsigned short *log_clusters = logClusters(&si);
2709
2710 int gs = log_clusters[start];
2711 int ge = (end == length(firstItem+i) ? si.num_glyphs : log_clusters[end]);
2712
2713 Q_ASSERT(ge <= si.num_glyphs);
2714
2715 const QGlyphLayout g = shapedGlyphs(&si);
2716
2717 for (int i = gs; i < ge; ++i) {
2718 g.justifications[i].type = QGlyphJustification::JustifyNone;
2719 g.justifications[i].nKashidas = 0;
2720 g.justifications[i].space_18d6 = 0;
2721
2722 justificationPoints.resize(nPoints+3);
2723 int justification = g.attributes[i].justification;
2724
2725 switch(justification) {
2726 case Justification_Prohibited:
2727 break;
2728 case Justification_Space:
2729 case Justification_Arabic_Space:
2730 if (kashida_pos >= 0) {
2731// qDebug("kashida position at %d in word", kashida_pos);
2732 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
2733 if (justificationPoints[nPoints].kashidaWidth > 0) {
2734 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
2735 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
2736 ++nPoints;
2737 }
2738 }
2739 kashida_pos = -1;
2740 kashida_type = Justification_Arabic_Normal;
2741 Q_FALLTHROUGH();
2742 case Justification_Character:
2743 set(&justificationPoints[nPoints++], justification, g.mid(i), fontEngine(si));
2744 maxJustify = qMax(maxJustify, justification);
2745 break;
2746 case Justification_Arabic_Normal:
2747 case Justification_Arabic_Waw:
2748 case Justification_Arabic_BaRa:
2749 case Justification_Arabic_Alef:
2750 case Justification_Arabic_HahDal:
2751 case Justification_Arabic_Seen:
2752 case Justification_Arabic_Kashida:
2753 if (justification >= kashida_type) {
2754 kashida_pos = i;
2755 kashida_type = justification;
2756 }
2757 }
2758 }
2759 if (kashida_pos >= 0) {
2760 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
2761 if (justificationPoints[nPoints].kashidaWidth > 0) {
2762 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
2763 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
2764 ++nPoints;
2765 }
2766 }
2767 }
2768
2769 QFixed leading = leadingSpaceWidth(line);
2770 QFixed need = line.width - line.textWidth - leading;
2771 if (need < 0) {
2772 // line overflows already!
2773 const_cast<QScriptLine &>(line).justified = true;
2774 return;
2775 }
2776
2777// qDebug("doing justification: textWidth=%x, requested=%x, maxJustify=%d", line.textWidth.value(), line.width.value(), maxJustify);
2778// qDebug(" minKashida=%f, need=%f", minKashida.toReal(), need.toReal());
2779
2780 // distribute in priority order
2781 if (maxJustify >= Justification_Arabic_Normal) {
2782 while (need >= minKashida) {
2783 for (int type = maxJustify; need >= minKashida && type >= Justification_Arabic_Normal; --type) {
2784 for (int i = 0; need >= minKashida && i < nPoints; ++i) {
2785 if (justificationPoints[i].type == type && justificationPoints[i].kashidaWidth <= need) {
2786 justificationPoints[i].glyph.justifications->nKashidas++;
2787 // ############
2788 justificationPoints[i].glyph.justifications->space_18d6 += justificationPoints[i].kashidaWidth.value();
2789 need -= justificationPoints[i].kashidaWidth;
2790// qDebug("adding kashida type %d with width %x, neednow %x", type, justificationPoints[i].kashidaWidth, need.value());
2791 }
2792 }
2793 }
2794 }
2795 }
2796 Q_ASSERT(need >= 0);
2797 if (!need)
2798 goto end;
2799
2800 maxJustify = qMin(maxJustify, int(Justification_Space));
2801 for (int type = maxJustify; need != 0 && type > 0; --type) {
2802 int n = 0;
2803 for (int i = 0; i < nPoints; ++i) {
2804 if (justificationPoints[i].type == type)
2805 ++n;
2806 }
2807// qDebug("number of points for justification type %d: %d", type, n);
2808
2809
2810 if (!n)
2811 continue;
2812
2813 for (int i = 0; i < nPoints; ++i) {
2814 if (justificationPoints[i].type == type) {
2815 QFixed add = need/n;
2816// qDebug("adding %x to glyph %x", add.value(), justificationPoints[i].glyph->glyph);
2817 justificationPoints[i].glyph.justifications[0].space_18d6 = add.value();
2818 need -= add;
2819 --n;
2820 }
2821 }
2822
2823 Q_ASSERT(!need);
2824 }
2825 end:
2826 const_cast<QScriptLine &>(line).justified = true;
2827}
2828
2829void QScriptLine::setDefaultHeight(QTextEngine *eng)
2830{
2831 QFont f;
2832 QFontEngine *e;
2833
2834 if (QTextDocumentPrivate::get(eng->block) != nullptr && QTextDocumentPrivate::get(eng->block)->layout() != nullptr) {
2835 f = eng->block.charFormat().font();
2836 // Make sure we get the right dpi on printers
2837 QPaintDevice *pdev = QTextDocumentPrivate::get(eng->block)->layout()->paintDevice();
2838 if (pdev)
2839 f = QFont(f, pdev);
2840 e = f.d->engineForScript(QChar::Script_Common);
2841 } else {
2842 e = eng->fnt.d->engineForScript(QChar::Script_Common);
2843 }
2844
2845 QFixed other_ascent = e->ascent();
2846 QFixed other_descent = e->descent();
2847 QFixed other_leading = e->leading();
2848 leading = qMax(leading + ascent, other_leading + other_ascent) - qMax(ascent, other_ascent);
2849 ascent = qMax(ascent, other_ascent);
2850 descent = qMax(descent, other_descent);
2851}
2852
2853QTextEngine::LayoutData::LayoutData()
2854{
2855 memory = nullptr;
2856 allocated = 0;
2857 memory_on_stack = false;
2858 used = 0;
2859 hasBidi = false;
2860 layoutState = LayoutEmpty;
2861 haveCharAttributes = false;
2862 logClustersPtr = nullptr;
2863 available_glyphs = 0;
2864 currentMaxWidth = 0;
2865}
2866
2867QTextEngine::LayoutData::LayoutData(const QString &str, void **stack_memory, qsizetype _allocated)
2868 : string(str)
2869{
2870 allocated = _allocated;
2871
2872 constexpr qsizetype voidSize = sizeof(void*);
2873 qsizetype space_charAttributes = sizeof(QCharAttributes) * string.size() / voidSize + 1;
2874 qsizetype space_logClusters = sizeof(unsigned short) * string.size() / voidSize + 1;
2875 available_glyphs = (allocated - space_charAttributes - space_logClusters) * voidSize / QGlyphLayout::SpaceNeeded;
2876
2877 if (available_glyphs < str.size()) {
2878 // need to allocate on the heap
2879 allocated = 0;
2880
2881 memory_on_stack = false;
2882 memory = nullptr;
2883 logClustersPtr = nullptr;
2884 } else {
2885 memory_on_stack = true;
2886 memory = stack_memory;
2887 logClustersPtr = (unsigned short *)(memory + space_charAttributes);
2888
2889 void *m = memory + space_charAttributes + space_logClusters;
2890 glyphLayout = QGlyphLayout(reinterpret_cast<char *>(m), str.size());
2891 glyphLayout.clear();
2892 memset(memory, 0, space_charAttributes*sizeof(void *));
2893 }
2894 used = 0;
2895 hasBidi = false;
2896 layoutState = LayoutEmpty;
2897 haveCharAttributes = false;
2898 currentMaxWidth = 0;
2899}
2900
2901QTextEngine::LayoutData::~LayoutData()
2902{
2903 if (!memory_on_stack)
2904 free(memory);
2905 memory = nullptr;
2906}
2907
2908bool QTextEngine::LayoutData::reallocate(int totalGlyphs)
2909{
2910 Q_ASSERT(totalGlyphs >= glyphLayout.numGlyphs);
2911 if (memory_on_stack && available_glyphs >= totalGlyphs) {
2912 glyphLayout.grow(glyphLayout.data(), totalGlyphs);
2913 return true;
2914 }
2915
2916 const qsizetype space_charAttributes = (sizeof(QCharAttributes) * string.size() / sizeof(void*) + 1);
2917 const qsizetype space_logClusters = (sizeof(unsigned short) * string.size() / sizeof(void*) + 1);
2918 const qsizetype space_glyphs = qsizetype(totalGlyphs) * QGlyphLayout::SpaceNeeded / sizeof(void *) + 2;
2919
2920 const qsizetype newAllocated = space_charAttributes + space_glyphs + space_logClusters;
2921 // Check if the length of string/glyphs causes int overflow,
2922 // we can't layout such a long string all at once, so return false here to
2923 // indicate there is a failure
2924 if (size_t(space_charAttributes) > INT_MAX || size_t(space_logClusters) > INT_MAX || totalGlyphs < 0
2925 || size_t(space_glyphs) > INT_MAX || size_t(newAllocated) > INT_MAX || newAllocated < allocated) {
2926 layoutState = LayoutFailed;
2927 return false;
2928 }
2929
2930 void **newMem = (void **)::realloc(memory_on_stack ? nullptr : memory, newAllocated*sizeof(void *));
2931 if (!newMem) {
2932 layoutState = LayoutFailed;
2933 return false;
2934 }
2935 if (memory_on_stack)
2936 memcpy(newMem, memory, allocated*sizeof(void *));
2937 memory = newMem;
2938 memory_on_stack = false;
2939
2940 void **m = memory;
2941 m += space_charAttributes;
2942 logClustersPtr = (unsigned short *) m;
2943 m += space_logClusters;
2944
2945 const qsizetype space_preGlyphLayout = space_charAttributes + space_logClusters;
2946 if (allocated < space_preGlyphLayout)
2947 memset(memory + allocated, 0, (space_preGlyphLayout - allocated)*sizeof(void *));
2948
2949 glyphLayout.grow(reinterpret_cast<char *>(m), totalGlyphs);
2950
2951 allocated = newAllocated;
2952 return true;
2953}
2954
2956{
2957 Q_ASSERT(offsets != oldLayout->offsets);
2958
2959 int n = std::min(numGlyphs, oldLayout->numGlyphs);
2960
2961 memcpy(offsets, oldLayout->offsets, n * sizeof(QFixedPoint));
2962 memcpy(attributes, oldLayout->attributes, n * sizeof(QGlyphAttributes));
2963 memcpy(justifications, oldLayout->justifications, n * sizeof(QGlyphJustification));
2964 memcpy(advances, oldLayout->advances, n * sizeof(QFixed));
2965 memcpy(glyphs, oldLayout->glyphs, n * sizeof(glyph_t));
2966
2967 numGlyphs = n;
2968}
2969
2970// grow to the new size, copying the existing data to the new layout
2971void QGlyphLayout::grow(char *address, int totalGlyphs)
2972{
2973 QGlyphLayout oldLayout(address, numGlyphs);
2974 QGlyphLayout newLayout(address, totalGlyphs);
2975
2976 if (numGlyphs) {
2977 // move the existing data
2978 memmove(newLayout.attributes, oldLayout.attributes, numGlyphs * sizeof(QGlyphAttributes));
2979 memmove(newLayout.justifications, oldLayout.justifications, numGlyphs * sizeof(QGlyphJustification));
2980 memmove(newLayout.advances, oldLayout.advances, numGlyphs * sizeof(QFixed));
2981 memmove(newLayout.glyphs, oldLayout.glyphs, numGlyphs * sizeof(glyph_t));
2982 }
2983
2984 // clear the new data
2985 newLayout.clear(numGlyphs);
2986
2987 *this = newLayout;
2988}
2989
2990void QTextEngine::freeMemory()
2991{
2992 if (!stackEngine) {
2993 delete layoutData;
2994 layoutData = nullptr;
2995 } else {
2996 layoutData->used = 0;
2997 layoutData->hasBidi = false;
2998 layoutData->layoutState = LayoutEmpty;
2999 layoutData->haveCharAttributes = false;
3000 layoutData->currentMaxWidth = 0;
3001 layoutData->items.clear();
3002 }
3003 if (specialData)
3004 specialData->resolvedFormats.clear();
3005 for (int i = 0; i < lines.size(); ++i) {
3006 lines[i].justified = 0;
3007 lines[i].gridfitted = 0;
3008 }
3009}
3010
3011int QTextEngine::formatIndex(const QScriptItem *si) const
3012{
3013 if (specialData && !specialData->resolvedFormats.isEmpty()) {
3014 QTextFormatCollection *collection = formatCollection();
3015 Q_ASSERT(collection);
3016 return collection->indexForFormat(specialData->resolvedFormats.at(si - &layoutData->items.at(0)));
3017 }
3018
3019 const QTextDocumentPrivate *p = QTextDocumentPrivate::get(block);
3020 if (!p)
3021 return -1;
3022 int pos = si->position;
3023 if (specialData && si->position >= specialData->preeditPosition) {
3024 if (si->position < specialData->preeditPosition + specialData->preeditText.size())
3025 pos = qMax(qMin(block.length(), specialData->preeditPosition) - 1, 0);
3026 else
3027 pos -= specialData->preeditText.size();
3028 }
3029 QTextDocumentPrivate::FragmentIterator it = p->find(block.position() + pos);
3030 return it.value()->format;
3031}
3032
3033
3034QTextCharFormat QTextEngine::format(const QScriptItem *si) const
3035{
3036 if (const QTextFormatCollection *collection = formatCollection())
3037 return collection->charFormat(formatIndex(si));
3038 return QTextCharFormat();
3039}
3040
3041void QTextEngine::addRequiredBoundaries() const
3042{
3043 if (specialData) {
3044 for (int i = 0; i < specialData->formats.size(); ++i) {
3045 const QTextLayout::FormatRange &r = specialData->formats.at(i);
3046 setBoundary(r.start);
3047 setBoundary(r.start + r.length);
3048 //qDebug("adding boundaries %d %d", r.start, r.start+r.length);
3049 }
3050 }
3051}
3052
3053bool QTextEngine::atWordSeparator(int position) const
3054{
3055 const QChar c = layoutData->string.at(position);
3056 switch (c.unicode()) {
3057 case '.':
3058 case ',':
3059 case '?':
3060 case '!':
3061 case '@':
3062 case '#':
3063 case '$':
3064 case ':':
3065 case ';':
3066 case '-':
3067 case '<':
3068 case '>':
3069 case '[':
3070 case ']':
3071 case '(':
3072 case ')':
3073 case '{':
3074 case '}':
3075 case '=':
3076 case '/':
3077 case '+':
3078 case '%':
3079 case '&':
3080 case '^':
3081 case '*':
3082 case '\'':
3083 case '"':
3084 case '`':
3085 case '~':
3086 case '|':
3087 case '\\':
3088 return true;
3089 default:
3090 break;
3091 }
3092 return false;
3093}
3094
3095void QTextEngine::setPreeditArea(int position, const QString &preeditText)
3096{
3097 if (preeditText.isEmpty()) {
3098 if (!specialData)
3099 return;
3100 if (specialData->formats.isEmpty()) {
3101 delete specialData;
3102 specialData = nullptr;
3103 } else {
3104 specialData->preeditText = QString();
3105 specialData->preeditPosition = -1;
3106 }
3107 } else {
3108 if (!specialData)
3109 specialData = new SpecialData;
3110 specialData->preeditPosition = position;
3111 specialData->preeditText = preeditText;
3112 }
3113 invalidate();
3114 clearLineData();
3115}
3116
3117void QTextEngine::setFormats(const QList<QTextLayout::FormatRange> &formats)
3118{
3119 if (formats.isEmpty()) {
3120 if (!specialData)
3121 return;
3122 if (specialData->preeditText.isEmpty()) {
3123 delete specialData;
3124 specialData = nullptr;
3125 } else {
3126 specialData->formats.clear();
3127 }
3128 } else {
3129 if (!specialData) {
3130 specialData = new SpecialData;
3131 specialData->preeditPosition = -1;
3132 }
3133 specialData->formats = formats;
3134 indexFormats();
3135 }
3136 invalidate();
3137 clearLineData();
3138}
3139
3140void QTextEngine::indexFormats()
3141{
3142 QTextFormatCollection *collection = formatCollection();
3143 if (!collection) {
3144 Q_ASSERT(QTextDocumentPrivate::get(block) == nullptr);
3145 specialData->formatCollection.reset(new QTextFormatCollection);
3146 collection = specialData->formatCollection.data();
3147 }
3148
3149 // replace with shared copies
3150 for (int i = 0; i < specialData->formats.size(); ++i) {
3151 QTextCharFormat &format = specialData->formats[i].format;
3152 format = collection->charFormat(collection->indexForFormat(format));
3153 }
3154}
3155
3156/* These two helper functions are used to determine whether we need to insert a ZWJ character
3157 between the text that gets truncated and the ellipsis. This is important to get
3158 correctly shaped results for arabic text.
3159*/
3160static inline bool nextCharJoins(const QString &string, int pos)
3161{
3162 while (pos < string.size() && string.at(pos).category() == QChar::Mark_NonSpacing)
3163 ++pos;
3164 if (pos == string.size())
3165 return false;
3166 QChar::JoiningType joining = string.at(pos).joiningType();
3167 return joining != QChar::Joining_None && joining != QChar::Joining_Transparent;
3168}
3169
3170static inline bool prevCharJoins(const QString &string, int pos)
3171{
3172 while (pos > 0 && string.at(pos - 1).category() == QChar::Mark_NonSpacing)
3173 --pos;
3174 if (pos == 0)
3175 return false;
3176 QChar::JoiningType joining = string.at(pos - 1).joiningType();
3177 return joining == QChar::Joining_Dual || joining == QChar::Joining_Causing;
3178}
3179
3180static constexpr bool isRetainableControlCode(char16_t c) noexcept
3181{
3182 return (c >= 0x202a && c <= 0x202e) // LRE, RLE, PDF, LRO, RLO
3183 || (c >= 0x200e && c <= 0x200f) // LRM, RLM
3184 || (c >= 0x2066 && c <= 0x2069); // LRI, RLI, FSI, PDI
3185}
3186
3187static QString stringMidRetainingBidiCC(const QString &string,
3188 const QString &ellidePrefix,
3189 const QString &ellideSuffix,
3190 int subStringFrom,
3191 int subStringTo,
3192 int midStart,
3193 int midLength)
3194{
3195 QString prefix;
3196 for (int i=subStringFrom; i<midStart; ++i) {
3197 char16_t c = string.at(i).unicode();
3199 prefix += c;
3200 }
3201
3202 QString suffix;
3203 for (int i=midStart + midLength; i<subStringTo; ++i) {
3204 char16_t c = string.at(i).unicode();
3206 suffix += c;
3207 }
3208
3209 return prefix + ellidePrefix + QStringView{string}.mid(midStart, midLength) + ellideSuffix + suffix;
3210}
3211
3212QString QTextEngine::elidedText(Qt::TextElideMode mode, QFixed width, int flags, int from, int count) const
3213{
3214// qDebug() << "elidedText; available width" << width.toReal() << "text width:" << this->width(0, layoutData->string.length()).toReal();
3215
3216 if (flags & Qt::TextShowMnemonic) {
3217 itemize();
3218 QCharAttributes *attributes = const_cast<QCharAttributes *>(this->attributes());
3219 if (!attributes)
3220 return QString();
3221 for (int i = 0; i < layoutData->items.size(); ++i) {
3222 const QScriptItem &si = layoutData->items.at(i);
3223 if (!si.num_glyphs)
3224 shape(i);
3225
3226 unsigned short *logClusters = this->logClusters(&si);
3227 QGlyphLayout glyphs = shapedGlyphs(&si);
3228
3229 const int end = si.position + length(&si);
3230 for (int i = si.position; i < end - 1; ++i) {
3231 if (layoutData->string.at(i) == u'&'
3232 && !attributes[i + 1].whiteSpace && attributes[i + 1].graphemeBoundary) {
3233 const int gp = logClusters[i - si.position];
3234 glyphs.attributes[gp].dontPrint = true;
3235 // emulate grapheme cluster
3236 attributes[i] = attributes[i + 1];
3237 memset(attributes + i + 1, 0, sizeof(QCharAttributes));
3238 if (layoutData->string.at(i + 1) == u'&')
3239 ++i;
3240 }
3241 }
3242 }
3243 }
3244
3245 validate();
3246
3247 const int to = count >= 0 && count <= layoutData->string.size() - from
3248 ? from + count
3249 : layoutData->string.size();
3250
3251 if (mode == Qt::ElideNone
3252 || this->width(from, layoutData->string.size()) <= width
3253 || to - from <= 1)
3254 return layoutData->string.mid(from, from - to);
3255
3256 QFixed ellipsisWidth;
3257 QString ellipsisText;
3258 {
3259 QFontEngine *engine = fnt.d->engineForScript(QChar::Script_Common);
3260
3261 constexpr char16_t ellipsisChar = u'\x2026';
3262
3263 // We only want to use the ellipsis character if it is from the main
3264 // font (not one of the fallbacks), since using a fallback font
3265 // will affect the metrics of the text, potentially causing it to shift
3266 // when it is being elided.
3267 if (engine->type() == QFontEngine::Multi) {
3268 QFontEngineMulti *multiEngine = static_cast<QFontEngineMulti *>(engine);
3269 multiEngine->ensureEngineAt(0);
3270 engine = multiEngine->engine(0);
3271 }
3272
3273 glyph_t glyph = engine->glyphIndex(ellipsisChar);
3274
3275 QGlyphLayout glyphs;
3276 glyphs.numGlyphs = 1;
3277 glyphs.glyphs = &glyph;
3278 glyphs.advances = &ellipsisWidth;
3279
3280 if (glyph != 0) {
3281 engine->recalcAdvances(&glyphs, { });
3282
3283 ellipsisText = ellipsisChar;
3284 } else {
3285 glyph = engine->glyphIndex('.');
3286 if (glyph != 0) {
3287 engine->recalcAdvances(&glyphs, { });
3288
3289 ellipsisWidth *= 3;
3290 ellipsisText = QStringLiteral("...");
3291 } else {
3292 engine = fnt.d->engineForScript(QChar::Script_Common);
3293 glyph = engine->glyphIndex(ellipsisChar);
3294 engine->recalcAdvances(&glyphs, { });
3295 ellipsisText = ellipsisChar;
3296 }
3297 }
3298 }
3299
3300 const QFixed availableWidth = width - ellipsisWidth;
3301 if (availableWidth < 0)
3302 return QString();
3303
3304 const QCharAttributes *attributes = this->attributes();
3305 if (!attributes)
3306 return QString();
3307
3308 constexpr char16_t ZWJ = u'\x200d'; // ZERO-WIDTH JOINER
3309
3310 if (mode == Qt::ElideRight) {
3311 QFixed currentWidth;
3312 int pos;
3313 int nextBreak = from;
3314
3315 do {
3316 pos = nextBreak;
3317
3318 ++nextBreak;
3319 while (nextBreak < layoutData->string.size() && !attributes[nextBreak].graphemeBoundary)
3320 ++nextBreak;
3321
3322 currentWidth += this->width(pos, nextBreak - pos);
3323 } while (nextBreak < to
3324 && currentWidth < availableWidth);
3325
3326 if (nextCharJoins(layoutData->string, pos))
3327 ellipsisText.prepend(ZWJ);
3328
3329 return stringMidRetainingBidiCC(layoutData->string,
3330 QString(), ellipsisText,
3331 from, to,
3332 from, pos - from);
3333 } else if (mode == Qt::ElideLeft) {
3334 QFixed currentWidth;
3335 int pos;
3336 int nextBreak = to;
3337
3338 do {
3339 pos = nextBreak;
3340
3341 --nextBreak;
3342 while (nextBreak > 0 && !attributes[nextBreak].graphemeBoundary)
3343 --nextBreak;
3344
3345 currentWidth += this->width(nextBreak, pos - nextBreak);
3346 } while (nextBreak > from
3347 && currentWidth < availableWidth);
3348
3349 if (prevCharJoins(layoutData->string, pos))
3350 ellipsisText.append(ZWJ);
3351
3352 return stringMidRetainingBidiCC(layoutData->string,
3353 ellipsisText, QString(),
3354 from, to,
3355 pos, to - pos);
3356 } else if (mode == Qt::ElideMiddle) {
3357 QFixed leftWidth;
3358 QFixed rightWidth;
3359
3360 int leftPos = from;
3361 int nextLeftBreak = from;
3362
3363 int rightPos = to;
3364 int nextRightBreak = to;
3365
3366 do {
3367 leftPos = nextLeftBreak;
3368 rightPos = nextRightBreak;
3369
3370 ++nextLeftBreak;
3371 while (nextLeftBreak < layoutData->string.size() && !attributes[nextLeftBreak].graphemeBoundary)
3372 ++nextLeftBreak;
3373
3374 --nextRightBreak;
3375 while (nextRightBreak > from && !attributes[nextRightBreak].graphemeBoundary)
3376 --nextRightBreak;
3377
3378 leftWidth += this->width(leftPos, nextLeftBreak - leftPos);
3379 rightWidth += this->width(nextRightBreak, rightPos - nextRightBreak);
3380 } while (nextLeftBreak < to
3381 && nextRightBreak > from
3382 && leftWidth + rightWidth < availableWidth);
3383
3384 if (nextCharJoins(layoutData->string, leftPos))
3385 ellipsisText.prepend(ZWJ);
3386 if (prevCharJoins(layoutData->string, rightPos))
3387 ellipsisText.append(ZWJ);
3388
3389 return QStringView{layoutData->string}.mid(from, leftPos - from) + ellipsisText + QStringView{layoutData->string}.mid(rightPos, to - rightPos);
3390 }
3391
3392 return layoutData->string.mid(from, to - from);
3393}
3394
3395void QTextEngine::setBoundary(int strPos) const
3396{
3397 const int item = findItem(strPos);
3398 if (item < 0)
3399 return;
3400
3401 QScriptItem newItem = layoutData->items.at(item);
3402 if (newItem.position != strPos) {
3403 newItem.position = strPos;
3404 layoutData->items.insert(item + 1, newItem);
3405 }
3406}
3407
3408QFixed QTextEngine::calculateTabWidth(int item, QFixed x) const
3409{
3410 const QScriptItem &si = layoutData->items.at(item);
3411
3412 QFixed dpiScale = 1;
3413 if (QTextDocumentPrivate::get(block) != nullptr && QTextDocumentPrivate::get(block)->layout() != nullptr) {
3414 QPaintDevice *pdev = QTextDocumentPrivate::get(block)->layout()->paintDevice();
3415 if (pdev)
3416 dpiScale = QFixed::fromReal(pdev->logicalDpiY() / qreal(qt_defaultDpiY()));
3417 } else {
3418 dpiScale = QFixed::fromReal(fnt.d->dpi / qreal(qt_defaultDpiY()));
3419 }
3420
3421 QList<QTextOption::Tab> tabArray = option.tabs();
3422 if (!tabArray.isEmpty()) {
3423 if (isRightToLeft()) { // rebase the tabArray positions.
3424 auto isLeftOrRightTab = [](const QTextOption::Tab &tab) {
3425 return tab.type == QTextOption::LeftTab || tab.type == QTextOption::RightTab;
3426 };
3427 const auto cbegin = tabArray.cbegin();
3428 const auto cend = tabArray.cend();
3429 const auto cit = std::find_if(cbegin, cend, isLeftOrRightTab);
3430 if (cit != cend) {
3431 const int index = std::distance(cbegin, cit);
3432 auto iter = tabArray.begin() + index;
3433 const auto end = tabArray.end();
3434 while (iter != end) {
3435 QTextOption::Tab &tab = *iter;
3436 if (tab.type == QTextOption::LeftTab)
3437 tab.type = QTextOption::RightTab;
3438 else if (tab.type == QTextOption::RightTab)
3439 tab.type = QTextOption::LeftTab;
3440 ++iter;
3441 }
3442 }
3443 }
3444 for (const QTextOption::Tab &tabSpec : std::as_const(tabArray)) {
3445 QFixed tab = QFixed::fromReal(tabSpec.position) * dpiScale;
3446 if (tab > x) { // this is the tab we need.
3447 int tabSectionEnd = layoutData->string.size();
3448 if (tabSpec.type == QTextOption::RightTab || tabSpec.type == QTextOption::CenterTab) {
3449 // find next tab to calculate the width required.
3450 tab = QFixed::fromReal(tabSpec.position);
3451 for (int i=item + 1; i < layoutData->items.size(); i++) {
3452 const QScriptItem &item = layoutData->items.at(i);
3453 if (item.analysis.flags == QScriptAnalysis::TabOrObject) { // found it.
3454 tabSectionEnd = item.position;
3455 break;
3456 }
3457 }
3458 }
3459 else if (tabSpec.type == QTextOption::DelimiterTab)
3460 // find delimiter character to calculate the width required
3461 tabSectionEnd = qMax(si.position, layoutData->string.indexOf(tabSpec.delimiter, si.position) + 1);
3462
3463 if (tabSectionEnd > si.position) {
3464 QFixed length;
3465 // Calculate the length of text between this tab and the tabSectionEnd
3466 for (int i=item; i < layoutData->items.size(); i++) {
3467 const QScriptItem &item = layoutData->items.at(i);
3468 if (item.position > tabSectionEnd || item.position <= si.position)
3469 continue;
3470 shape(i); // first, lets make sure relevant text is already shaped
3471 if (item.analysis.flags == QScriptAnalysis::Object) {
3472 length += item.width;
3473 continue;
3474 }
3475 QGlyphLayout glyphs = this->shapedGlyphs(&item);
3476 const int end = qMin(item.position + item.num_glyphs, tabSectionEnd) - item.position;
3477 for (int i=0; i < end; i++)
3478 length += glyphs.advances[i] * !glyphs.attributes[i].dontPrint;
3479 if (end + item.position == tabSectionEnd && tabSpec.type == QTextOption::DelimiterTab) // remove half of matching char
3480 length -= glyphs.advances[end] / 2 * !glyphs.attributes[end].dontPrint;
3481 }
3482
3483 switch (tabSpec.type) {
3484 case QTextOption::CenterTab:
3485 length /= 2;
3486 Q_FALLTHROUGH();
3487 case QTextOption::DelimiterTab:
3488 case QTextOption::RightTab:
3489 tab = QFixed::fromReal(tabSpec.position) * dpiScale - length;
3490 if (tab < x) // default to tab taking no space
3491 return QFixed();
3492 break;
3493 case QTextOption::LeftTab:
3494 break;
3495 }
3496 }
3497 return tab - x;
3498 }
3499 }
3500 }
3501 QFixed tab = QFixed::fromReal(option.tabStopDistance());
3502 if (tab <= 0)
3503 tab = 80; // default
3504 tab *= dpiScale;
3505 QFixed nextTabPos = ((x / tab).truncate() + 1) * tab;
3506 QFixed tabWidth = nextTabPos - x;
3507
3508 return tabWidth;
3509}
3510
3511namespace {
3512class FormatRangeComparatorByStart {
3513 const QList<QTextLayout::FormatRange> &list;
3514public:
3515 FormatRangeComparatorByStart(const QList<QTextLayout::FormatRange> &list) : list(list) { }
3516 bool operator()(int a, int b) {
3517 return list.at(a).start < list.at(b).start;
3518 }
3519};
3520class FormatRangeComparatorByEnd {
3521 const QList<QTextLayout::FormatRange> &list;
3522public:
3523 FormatRangeComparatorByEnd(const QList<QTextLayout::FormatRange> &list) : list(list) { }
3524 bool operator()(int a, int b) {
3525 return list.at(a).start + list.at(a).length < list.at(b).start + list.at(b).length;
3526 }
3527};
3528}
3529
3530void QTextEngine::resolveFormats() const
3531{
3532 if (!specialData || specialData->formats.isEmpty())
3533 return;
3534 Q_ASSERT(specialData->resolvedFormats.isEmpty());
3535
3536 QTextFormatCollection *collection = formatCollection();
3537
3538 QList<QTextCharFormat> resolvedFormats(layoutData->items.size());
3539
3540 QVarLengthArray<int, 64> formatsSortedByStart;
3541 formatsSortedByStart.reserve(specialData->formats.size());
3542 for (int i = 0; i < specialData->formats.size(); ++i) {
3543 if (specialData->formats.at(i).length >= 0)
3544 formatsSortedByStart.append(i);
3545 }
3546 QVarLengthArray<int, 64> formatsSortedByEnd = formatsSortedByStart;
3547 std::sort(formatsSortedByStart.begin(), formatsSortedByStart.end(),
3548 FormatRangeComparatorByStart(specialData->formats));
3549 std::sort(formatsSortedByEnd.begin(), formatsSortedByEnd.end(),
3550 FormatRangeComparatorByEnd(specialData->formats));
3551
3552 QVarLengthArray<int, 16> currentFormats;
3553 const int *startIt = formatsSortedByStart.constBegin();
3554 const int *endIt = formatsSortedByEnd.constBegin();
3555
3556 for (int i = 0; i < layoutData->items.size(); ++i) {
3557 const QScriptItem *si = &layoutData->items.at(i);
3558 int end = si->position + length(si);
3559
3560 while (startIt != formatsSortedByStart.constEnd() &&
3561 specialData->formats.at(*startIt).start <= si->position) {
3562 currentFormats.insert(std::upper_bound(currentFormats.begin(), currentFormats.end(), *startIt),
3563 *startIt);
3564 ++startIt;
3565 }
3566 while (endIt != formatsSortedByEnd.constEnd() &&
3567 specialData->formats.at(*endIt).start + specialData->formats.at(*endIt).length < end) {
3568 int *currentFormatIterator = std::lower_bound(currentFormats.begin(), currentFormats.end(), *endIt);
3569 if (*endIt < *currentFormatIterator)
3570 currentFormatIterator = currentFormats.end();
3571 currentFormats.remove(currentFormatIterator - currentFormats.begin());
3572 ++endIt;
3573 }
3574
3575 QTextCharFormat &format = resolvedFormats[i];
3576 if (QTextDocumentPrivate::get(block) != nullptr) {
3577 // when we have a QTextDocumentPrivate, formatIndex might still return a valid index based
3578 // on the preeditPosition. for all other cases, we cleared the resolved format indices
3579 format = collection->charFormat(formatIndex(si));
3580 }
3581 if (!currentFormats.isEmpty()) {
3582 for (int cur : currentFormats) {
3583 const QTextLayout::FormatRange &range = specialData->formats.at(cur);
3584 Q_ASSERT(range.start <= si->position && range.start + range.length >= end);
3585 format.merge(range.format);
3586 }
3587 format = collection->charFormat(collection->indexForFormat(format)); // get shared copy
3588 }
3589 }
3590
3591 specialData->resolvedFormats = resolvedFormats;
3592}
3593
3594QFixed QTextEngine::leadingSpaceWidth(const QScriptLine &line)
3595{
3596 if (!line.hasTrailingSpaces
3597 || (option.flags() & QTextOption::IncludeTrailingSpaces)
3598 || !isRightToLeft())
3599 return QFixed();
3600
3601 return width(line.from + line.length, line.trailingSpaces);
3602}
3603
3604QFixed QTextEngine::alignLine(const QScriptLine &line)
3605{
3606 QFixed x = 0;
3607 justify(line);
3608 // if width is QFIXED_MAX that means we used setNumColumns() and that implicitly makes this line left aligned.
3609 if (!line.justified && line.width != QFIXED_MAX) {
3610 int align = option.alignment();
3611 if (align & Qt::AlignJustify && isRightToLeft())
3612 align = Qt::AlignRight;
3613 if (align & Qt::AlignRight)
3614 x = line.width - (line.textAdvance);
3615 else if (align & Qt::AlignHCenter)
3616 x = (line.width - line.textAdvance)/2;
3617 }
3618 return x;
3619}
3620
3621QFixed QTextEngine::offsetInLigature(const QScriptItem *si, int pos, int max, int glyph_pos)
3622{
3623 unsigned short *logClusters = this->logClusters(si);
3624 const QGlyphLayout &glyphs = shapedGlyphs(si);
3625
3626 int offsetInCluster = 0;
3627 for (int i = pos - 1; i >= 0; i--) {
3628 if (logClusters[i] == glyph_pos)
3629 offsetInCluster++;
3630 else
3631 break;
3632 }
3633
3634 // in the case that the offset is inside a (multi-character) glyph,
3635 // interpolate the position.
3636 if (offsetInCluster > 0) {
3637 int clusterLength = 0;
3638 for (int i = pos - offsetInCluster; i < max; i++) {
3639 if (logClusters[i] == glyph_pos)
3640 clusterLength++;
3641 else
3642 break;
3643 }
3644 if (clusterLength)
3645 return glyphs.advances[glyph_pos] * offsetInCluster / clusterLength;
3646 }
3647
3648 return 0;
3649}
3650
3651// Scan in logClusters[from..to-1] for glyph_pos
3652int QTextEngine::getClusterLength(unsigned short *logClusters,
3653 const QCharAttributes *attributes,
3654 int from, int to, int glyph_pos, int *start)
3655{
3656 int clusterLength = 0;
3657 for (int i = from; i < to; i++) {
3658 if (logClusters[i] == glyph_pos && attributes[i].graphemeBoundary) {
3659 if (*start < 0)
3660 *start = i;
3661 clusterLength++;
3662 }
3663 else if (clusterLength)
3664 break;
3665 }
3666 return clusterLength;
3667}
3668
3669int QTextEngine::positionInLigature(const QScriptItem *si, int end,
3670 QFixed x, QFixed edge, int glyph_pos,
3671 bool cursorOnCharacter)
3672{
3673 unsigned short *logClusters = this->logClusters(si);
3674 int clusterStart = -1;
3675 int clusterLength = 0;
3676
3677 if (si->analysis.script != QChar::Script_Common &&
3678 si->analysis.script != QChar::Script_Greek &&
3679 si->analysis.script != QChar::Script_Latin &&
3680 si->analysis.script != QChar::Script_Hiragana &&
3681 si->analysis.script != QChar::Script_Katakana &&
3682 si->analysis.script != QChar::Script_Bopomofo &&
3683 si->analysis.script != QChar::Script_Han) {
3684 if (glyph_pos == -1)
3685 return si->position + end;
3686 else {
3687 int i;
3688 for (i = 0; i < end; i++)
3689 if (logClusters[i] == glyph_pos)
3690 break;
3691 return si->position + i;
3692 }
3693 }
3694
3695 if (glyph_pos == -1 && end > 0)
3696 glyph_pos = logClusters[end - 1];
3697 else {
3698 if (x <= edge)
3699 glyph_pos--;
3700 }
3701
3702 const QCharAttributes *attrs = attributes() + si->position;
3703 logClusters = this->logClusters(si);
3704 clusterLength = getClusterLength(logClusters, attrs, 0, end, glyph_pos, &clusterStart);
3705
3706 if (clusterLength) {
3707 const QGlyphLayout &glyphs = shapedGlyphs(si);
3708 QFixed glyphWidth = glyphs.effectiveAdvance(glyph_pos);
3709 // the approximate width of each individual element of the ligature
3710 QFixed perItemWidth = glyphWidth / clusterLength;
3711 if (perItemWidth <= 0)
3712 return si->position + clusterStart;
3713 QFixed left = x > edge ? edge : edge - glyphWidth;
3714 int n = ((x - left) / perItemWidth).floor().toInt();
3715 QFixed dist = x - left - n * perItemWidth;
3716 int closestItem = dist > (perItemWidth / 2) ? n + 1 : n;
3717 if (cursorOnCharacter && closestItem > 0)
3718 closestItem--;
3719 int pos = clusterStart + closestItem;
3720 // Jump to the next grapheme boundary
3721 while (pos < end && !attrs[pos].graphemeBoundary)
3722 pos++;
3723 return si->position + pos;
3724 }
3725 return si->position + end;
3726}
3727
3728int QTextEngine::previousLogicalPosition(int oldPos) const
3729{
3730 const QCharAttributes *attrs = attributes();
3731 int len = block.isValid() ? block.length() - 1
3732 : layoutData->string.size();
3733 Q_ASSERT(len <= layoutData->string.size());
3734 if (!attrs || oldPos <= 0 || oldPos > len)
3735 return oldPos;
3736
3737 oldPos--;
3738 while (oldPos && !attrs[oldPos].graphemeBoundary)
3739 oldPos--;
3740 return oldPos;
3741}
3742
3743int QTextEngine::nextLogicalPosition(int oldPos) const
3744{
3745 const QCharAttributes *attrs = attributes();
3746 int len = block.isValid() ? block.length() - 1
3747 : layoutData->string.size();
3748 Q_ASSERT(len <= layoutData->string.size());
3749 if (!attrs || oldPos < 0 || oldPos >= len)
3750 return oldPos;
3751
3752 oldPos++;
3753 while (oldPos < len && !attrs[oldPos].graphemeBoundary)
3754 oldPos++;
3755 return oldPos;
3756}
3757
3758int QTextEngine::lineNumberForTextPosition(int pos)
3759{
3760 if (!layoutData)
3761 itemize();
3762 if (pos == layoutData->string.size() && lines.size())
3763 return lines.size() - 1;
3764 for (int i = 0; i < lines.size(); ++i) {
3765 const QScriptLine& line = lines[i];
3766 if (line.from + line.length + line.trailingSpaces > pos)
3767 return i;
3768 }
3769 return -1;
3770}
3771
3772std::vector<int> QTextEngine::insertionPointsForLine(int lineNum)
3773{
3774 QTextLineItemIterator iterator(this, lineNum);
3775
3776 std::vector<int> insertionPoints;
3777 insertionPoints.reserve(size_t(iterator.line.length));
3778
3779 bool lastLine = lineNum >= lines.size() - 1;
3780
3781 while (!iterator.atEnd()) {
3782 const QScriptItem &si = iterator.next();
3783
3784 int end = iterator.itemEnd;
3785 if (lastLine && iterator.item == iterator.lastItem)
3786 ++end; // the last item in the last line -> insert eol position
3787 if (si.analysis.bidiLevel % 2) {
3788 for (int i = end - 1; i >= iterator.itemStart; --i)
3789 insertionPoints.push_back(i);
3790 } else {
3791 for (int i = iterator.itemStart; i < end; ++i)
3792 insertionPoints.push_back(i);
3793 }
3794 }
3795 return insertionPoints;
3796}
3797
3798int QTextEngine::endOfLine(int lineNum)
3799{
3800 const auto insertionPoints = insertionPointsForLine(lineNum);
3801 if (insertionPoints.size() > 0)
3802 return insertionPoints.back();
3803 return 0;
3804}
3805
3806int QTextEngine::beginningOfLine(int lineNum)
3807{
3808 const auto insertionPoints = insertionPointsForLine(lineNum);
3809 if (insertionPoints.size() > 0)
3810 return insertionPoints.front();
3811 return 0;
3812}
3813
3814int QTextEngine::positionAfterVisualMovement(int pos, QTextCursor::MoveOperation op)
3815{
3816 itemize();
3817
3818 bool moveRight = (op == QTextCursor::Right);
3819 bool alignRight = isRightToLeft();
3820 if (!layoutData->hasBidi)
3821 return moveRight ^ alignRight ? nextLogicalPosition(pos) : previousLogicalPosition(pos);
3822
3823 int lineNum = lineNumberForTextPosition(pos);
3824 if (lineNum < 0)
3825 return pos;
3826
3827 const auto insertionPoints = insertionPointsForLine(lineNum);
3828 for (size_t i = 0, max = insertionPoints.size(); i < max; ++i)
3829 if (pos == insertionPoints[i]) {
3830 if (moveRight) {
3831 if (i + 1 < max)
3832 return insertionPoints[i + 1];
3833 } else {
3834 if (i > 0)
3835 return insertionPoints[i - 1];
3836 }
3837
3838 if (moveRight ^ alignRight) {
3839 if (lineNum + 1 < lines.size())
3840 return alignRight ? endOfLine(lineNum + 1) : beginningOfLine(lineNum + 1);
3841 }
3842 else {
3843 if (lineNum > 0)
3844 return alignRight ? beginningOfLine(lineNum - 1) : endOfLine(lineNum - 1);
3845 }
3846
3847 break;
3848 }
3849
3850 return pos;
3851}
3852
3853void QTextEngine::addItemDecoration(QPainter *painter, const QLineF &line, ItemDecorationList *decorationList)
3854{
3855 if (delayDecorations) {
3856 decorationList->append(ItemDecoration(line.x1(), line.x2(), line.y1(), painter->pen()));
3857 } else {
3858 painter->drawLine(line);
3859 }
3860}
3861
3862void QTextEngine::addUnderline(QPainter *painter, const QLineF &line)
3863{
3864 // qDebug() << "Adding underline:" << line;
3865 addItemDecoration(painter, line, &underlineList);
3866}
3867
3868void QTextEngine::addStrikeOut(QPainter *painter, const QLineF &line)
3869{
3870 addItemDecoration(painter, line, &strikeOutList);
3871}
3872
3873void QTextEngine::addOverline(QPainter *painter, const QLineF &line)
3874{
3875 addItemDecoration(painter, line, &overlineList);
3876}
3877
3878void QTextEngine::drawItemDecorationList(QPainter *painter, const ItemDecorationList &decorationList)
3879{
3880 // qDebug() << "Drawing" << decorationList.size() << "decorations";
3881 if (decorationList.isEmpty())
3882 return;
3883
3884 for (const ItemDecoration &decoration : decorationList) {
3885 painter->setPen(decoration.pen);
3886 painter->drawLine(QLineF(decoration.x1, decoration.y, decoration.x2, decoration.y));
3887 }
3888}
3889
3890void QTextEngine::drawDecorations(QPainter *painter)
3891{
3892 QPen oldPen = painter->pen();
3893
3894 adjustUnderlines();
3895 drawItemDecorationList(painter, underlineList);
3896 drawItemDecorationList(painter, strikeOutList);
3897 drawItemDecorationList(painter, overlineList);
3898
3899 clearDecorations();
3900
3901 painter->setPen(oldPen);
3902}
3903
3904void QTextEngine::clearDecorations()
3905{
3906 underlineList.clear();
3907 strikeOutList.clear();
3908 overlineList.clear();
3909}
3910
3911void QTextEngine::adjustUnderlines()
3912{
3913 // qDebug() << __PRETTY_FUNCTION__ << underlineList.count() << "underlines";
3914 if (underlineList.isEmpty())
3915 return;
3916
3917 ItemDecorationList::iterator start = underlineList.begin();
3918 ItemDecorationList::iterator end = underlineList.end();
3919 ItemDecorationList::iterator it = start;
3920 qreal underlinePos = start->y;
3921 qreal penWidth = start->pen.widthF();
3922 qreal lastLineEnd = start->x1;
3923
3924 while (it != end) {
3925 if (qFuzzyCompare(lastLineEnd, it->x1)) { // no gap between underlines
3926 underlinePos = qMax(underlinePos, it->y);
3927 penWidth = qMax(penWidth, it->pen.widthF());
3928 } else { // gap between this and the last underline
3929 adjustUnderlines(start, it, underlinePos, penWidth);
3930 start = it;
3931 underlinePos = start->y;
3932 penWidth = start->pen.widthF();
3933 }
3934 lastLineEnd = it->x2;
3935 ++it;
3936 }
3937
3938 adjustUnderlines(start, end, underlinePos, penWidth);
3939}
3940
3941void QTextEngine::adjustUnderlines(ItemDecorationList::iterator start,
3942 ItemDecorationList::iterator end,
3943 qreal underlinePos, qreal penWidth)
3944{
3945 for (ItemDecorationList::iterator it = start; it != end; ++it) {
3946 it->y = underlinePos;
3947 it->pen.setWidthF(penWidth);
3948 }
3949}
3950
3951QStackTextEngine::QStackTextEngine(const QString &string, const QFont &f)
3952 : QTextEngine(string, f),
3953 _layoutData(string, _memory, MemSize)
3954{
3955 stackEngine = true;
3956 layoutData = &_layoutData;
3957}
3958
3959QTextItemInt::QTextItemInt(const QScriptItem &si, QFont *font, const QTextCharFormat &format)
3960 : charFormat(format),
3961 f(font),
3962 fontEngine(font->d->engineForScript(si.analysis.script))
3963{
3964 Q_ASSERT(fontEngine);
3965
3967}
3968
3969QTextItemInt::QTextItemInt(const QGlyphLayout &g, QFont *font, const QChar *chars_, int numChars, QFontEngine *fe, const QTextCharFormat &format)
3970 : charFormat(format),
3971 num_chars(numChars),
3972 chars(chars_),
3973 f(font),
3974 glyphs(g),
3975 fontEngine(fe)
3976{
3977}
3978
3979// Fix up flags and underlineStyle with given info
3981{
3982 // explicitly initialize flags so that initFontAttributes can be called
3983 // multiple times on the same TextItem
3984 flags = { };
3985 if (si.analysis.bidiLevel %2)
3986 flags |= QTextItem::RightToLeft;
3987 ascent = si.ascent;
3988 descent = si.descent;
3989
3990 if (charFormat.hasProperty(QTextFormat::TextUnderlineStyle)) {
3991 underlineStyle = charFormat.underlineStyle();
3992 } else if (charFormat.boolProperty(QTextFormat::FontUnderline)
3993 || f->d->underline) {
3994 underlineStyle = QTextCharFormat::SingleUnderline;
3995 }
3996
3997 // compat
3998 if (underlineStyle == QTextCharFormat::SingleUnderline)
3999 flags |= QTextItem::Underline;
4000
4001 if (f->d->overline || charFormat.fontOverline())
4002 flags |= QTextItem::Overline;
4003 if (f->d->strikeOut || charFormat.fontStrikeOut())
4004 flags |= QTextItem::StrikeOut;
4005}
4006
4007QTextItemInt QTextItemInt::midItem(QFontEngine *fontEngine, int firstGlyphIndex, int numGlyphs) const
4008{
4009 QTextItemInt ti = *this;
4010 const int end = firstGlyphIndex + numGlyphs;
4011 ti.glyphs = glyphs.mid(firstGlyphIndex, numGlyphs);
4012 ti.fontEngine = fontEngine;
4013
4014 if (logClusters && chars) {
4015 const int logClusterOffset = logClusters[0];
4016 while (logClusters[ti.chars - chars] - logClusterOffset < firstGlyphIndex)
4017 ++ti.chars;
4018
4019 ti.logClusters += (ti.chars - chars);
4020
4021 ti.num_chars = 0;
4022 int char_start = ti.chars - chars;
4023 while (char_start + ti.num_chars < num_chars && ti.logClusters[ti.num_chars] - logClusterOffset < end)
4024 ++ti.num_chars;
4025 }
4026 return ti;
4027}
4028
4029
4030QTransform qt_true_matrix(qreal w, qreal h, const QTransform &x)
4031{
4032 QRectF rect = x.mapRect(QRectF(0, 0, w, h));
4033 return x * QTransform::fromTranslate(-rect.x(), -rect.y());
4034}
4035
4036
4037glyph_metrics_t glyph_metrics_t::transformed(const QTransform &matrix) const
4038{
4039 if (matrix.type() < QTransform::TxTranslate)
4040 return *this;
4041
4042 glyph_metrics_t m = *this;
4043
4044 qreal w = width.toReal();
4045 qreal h = height.toReal();
4046 QTransform xform = qt_true_matrix(w, h, matrix);
4047
4048 QRectF rect(0, 0, w, h);
4049 rect = xform.mapRect(rect);
4050 m.width = QFixed::fromReal(rect.width());
4051 m.height = QFixed::fromReal(rect.height());
4052
4053 QLineF l = xform.map(QLineF(x.toReal(), y.toReal(), xoff.toReal(), yoff.toReal()));
4054
4055 m.x = QFixed::fromReal(l.x1());
4056 m.y = QFixed::fromReal(l.y1());
4057
4058 // The offset is relative to the baseline which is why we use dx/dy of the line
4059 m.xoff = QFixed::fromReal(l.dx());
4060 m.yoff = QFixed::fromReal(l.dy());
4061
4062 return m;
4063}
4064
4065QTextLineItemIterator::QTextLineItemIterator(QTextEngine *_eng, int _lineNum, const QPointF &pos,
4066 const QTextLayout::FormatRange *_selection)
4067 : eng(_eng),
4068 line(eng->lines[_lineNum]),
4069 si(nullptr),
4070 lineNum(_lineNum),
4071 lineEnd(line.from + line.length),
4072 firstItem(eng->findItem(line.from)),
4073 lastItem(eng->findItem(lineEnd - 1, firstItem)),
4074 nItems((firstItem >= 0 && lastItem >= firstItem)? (lastItem-firstItem+1) : 0),
4075 logicalItem(-1),
4076 item(-1),
4077 visualOrder(nItems),
4078 selection(_selection)
4079{
4080 x = QFixed::fromReal(pos.x());
4081
4082 x += line.x;
4083
4084 x += eng->alignLine(line);
4085
4086 if (nItems > 0) {
4087 QVarLengthArray<uchar> levels(nItems);
4088 for (int i = 0; i < nItems; ++i)
4089 levels[i] = eng->layoutData->items.at(i + firstItem).analysis.bidiLevel;
4090 QTextEngine::bidiReorder(nItems, levels.data(), visualOrder.data());
4091 }
4092
4093 eng->shapeLine(line);
4094}
4095
4097{
4098 x += itemWidth;
4099
4100 ++logicalItem;
4101 item = visualOrder[logicalItem] + firstItem;
4102 itemLength = eng->length(item);
4103 si = &eng->layoutData->items[item];
4104 if (!si->num_glyphs)
4105 eng->shape(item);
4106
4107 itemStart = qMax(line.from, si->position);
4109
4110 if (si->analysis.flags >= QScriptAnalysis::TabOrObject) {
4111 glyphsStart = 0;
4112 glyphsEnd = 1;
4113 itemWidth = si->width;
4114 return *si;
4115 }
4116
4117 unsigned short *logClusters = eng->logClusters(si);
4118 QGlyphLayout glyphs = eng->shapedGlyphs(si);
4119
4120 glyphsStart = logClusters[itemStart - si->position];
4122
4123 // show soft-hyphen at line-break
4124 if (si->position + itemLength >= lineEnd
4125 && eng->layoutData->string.at(lineEnd - 1).unicode() == QChar::SoftHyphen)
4126 glyphs.attributes[glyphsEnd - 1].dontPrint = false;
4127
4128 itemWidth = 0;
4129 for (int g = glyphsStart; g < glyphsEnd; ++g)
4130 itemWidth += glyphs.effectiveAdvance(g);
4131
4132 return *si;
4133}
4134
4135bool QTextLineItemIterator::getSelectionBounds(QFixed *selectionX, QFixed *selectionWidth) const
4136{
4137 *selectionX = *selectionWidth = 0;
4138
4139 if (!selection)
4140 return false;
4141
4142 if (si->analysis.flags >= QScriptAnalysis::TabOrObject) {
4143 if (si->position >= selection->start + selection->length
4144 || si->position + itemLength <= selection->start)
4145 return false;
4146
4147 *selectionX = x;
4148 *selectionWidth = itemWidth;
4149 } else {
4150 unsigned short *logClusters = eng->logClusters(si);
4151 QGlyphLayout glyphs = eng->shapedGlyphs(si);
4152
4153 int from = qMax(itemStart, selection->start) - si->position;
4154 int to = qMin(itemEnd, selection->start + selection->length) - si->position;
4155 if (from >= to)
4156 return false;
4157
4158 int start_glyph = logClusters[from];
4159 int end_glyph = (to == itemLength) ? si->num_glyphs : logClusters[to];
4160 QFixed soff;
4161 QFixed swidth;
4162 if (si->analysis.bidiLevel %2) {
4163 for (int g = glyphsEnd - 1; g >= end_glyph; --g)
4164 soff += glyphs.effectiveAdvance(g);
4165 for (int g = end_glyph - 1; g >= start_glyph; --g)
4166 swidth += glyphs.effectiveAdvance(g);
4167 } else {
4168 for (int g = glyphsStart; g < start_glyph; ++g)
4169 soff += glyphs.effectiveAdvance(g);
4170 for (int g = start_glyph; g < end_glyph; ++g)
4171 swidth += glyphs.effectiveAdvance(g);
4172 }
4173
4174 // If the starting character is in the middle of a ligature,
4175 // selection should only contain the right part of that ligature
4176 // glyph, so we need to get the width of the left part here and
4177 // add it to *selectionX
4178 QFixed leftOffsetInLigature = eng->offsetInLigature(si, from, to, start_glyph);
4179 *selectionX = x + soff + leftOffsetInLigature;
4180 *selectionWidth = swidth - leftOffsetInLigature;
4181 // If the ending character is also part of a ligature, swidth does
4182 // not contain that part yet, we also need to find out the width of
4183 // that left part
4184 *selectionWidth += eng->offsetInLigature(si, to, itemLength, end_glyph);
4185 }
4186 return true;
4187}
4188
4189QT_END_NAMESPACE
friend class QFontEngine
Definition qpainter.h:433
friend class QTextEngine
Definition qpainter.h:446
Internal QTextItem.
void initWithScriptItem(const QScriptItem &si)
QTextItemInt midItem(QFontEngine *fontEngine, int firstGlyphIndex, int numGlyphs) const
const QFont * f
const unsigned short * logClusters
QTextItemInt(const QGlyphLayout &g, QFont *font, const QChar *chars, int numChars, QFontEngine *fe, const QTextCharFormat &format=QTextCharFormat())
QFontEngine * fontEngine
QTextItemInt(const QScriptItem &si, QFont *font, const QTextCharFormat &format=QTextCharFormat())
Combined button and popup list for selecting options.
#define QStringLiteral(str)
Definition qstring.h:1825
QTransform qt_true_matrix(qreal w, qreal h, const QTransform &x)
Q_DECLARE_TYPEINFO(QJustificationPoint, Q_PRIMITIVE_TYPE)
JustificationClass
@ Justification_Arabic_Alef
@ Justification_Arabic_Waw
@ Justification_Arabic_Kashida
@ Justification_Space
@ Justification_Prohibited
@ Justification_Arabic_BaRa
@ Justification_Character
@ Justification_Arabic_Space
@ Justification_Arabic_HahDal
@ Justification_Arabic_Seen
@ Justification_Arabic_Normal
static bool prevCharJoins(const QString &string, int pos)
static QString stringMidRetainingBidiCC(const QString &string, const QString &ellidePrefix, const QString &ellideSuffix, int subStringFrom, int subStringTo, int midStart, int midLength)
static void applyVisibilityRules(ushort ucs, QGlyphLayout *glyphs, uint glyphPosition, QFontEngine *fontEngine)
static void set(QJustificationPoint *point, int type, const QGlyphLayout &glyph, QFontEngine *fe)
static bool nextCharJoins(const QString &string, int pos)
static constexpr bool isRetainableControlCode(char16_t c) noexcept
#define BIDI_DEBUG
static void releaseCachedFontEngine(QFontEngine *fontEngine)
QList< QScriptItem > QScriptItemArray
QGlyphJustification * justifications
void grow(char *address, int totalGlyphs)
void copy(QGlyphLayout *other)
QGlyphLayout(char *address, int totalGlyphs)
void clear(int first=0, int last=-1)
QGlyphAttributes * attributes
glyph_t * glyphs
QGlyphLayout mid(int position, int n=-1) const
unsigned short num_glyphs
bool getSelectionBounds(QFixed *selectionX, QFixed *selectionWidth) const