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 hb_buffer_t *buffer = hb_buffer_create();
1619 hb_buffer_set_unicode_funcs(buffer, hb_qt_get_unicode_funcs());
1620 hb_buffer_pre_allocate(buffer, itemLength);
1621 if (Q_UNLIKELY(!hb_buffer_allocation_successful(buffer))) {
1622 hb_buffer_destroy(buffer);
1623 return 0;
1624 }
1625
1626 hb_segment_properties_t props = HB_SEGMENT_PROPERTIES_DEFAULT;
1627 props.direction = si.analysis.bidiLevel % 2 ? HB_DIRECTION_RTL : HB_DIRECTION_LTR;
1628 QChar::Script script = si.analysis.script < QChar::ScriptCount
1629 ? QChar::Script(si.analysis.script)
1630 : QChar::Script_Common;
1631 props.script = hb_qt_script_to_script(script);
1632
1633 // set harfbuzz language from QLocale
1634 const QByteArray localeBcp47 = QLocale().bcp47Name().toUtf8();
1635 const hb_language_t hb_language = hb_language_from_string(localeBcp47.constData(), localeBcp47.size());
1636 if (hb_language == HB_LANGUAGE_INVALID)
1637 props.language = hb_language_get_default();
1638 else
1639 props.language = hb_language;
1640
1641 for (qsizetype k = 0; k < itemBoundaries.size(); k += 3) {
1642 const uint item_pos = itemBoundaries[k];
1643 const uint item_length = (k + 4 < itemBoundaries.size() ? itemBoundaries[k + 3] : itemLength) - item_pos;
1644 const uint engineIdx = itemBoundaries[k + 2];
1645
1646 QFontEngine *actualFontEngine = fontEngine->type() != QFontEngine::Multi ? fontEngine
1647 : static_cast<QFontEngineMulti *>(fontEngine)->engine(engineIdx);
1648
1649
1650 // prepare buffer
1651 hb_buffer_clear_contents(buffer);
1652
1653 // Populate the buffer using the base string pointer and length, so HarfBuzz can grab an
1654 // enclosing context for proper shaping at item boundaries in certain languages (e.g.
1655 // Arabic).
1656 hb_buffer_add_utf16(buffer, reinterpret_cast<const uint16_t *>(string), stringLength,
1657 stringBaseIndex + item_pos, item_length);
1658
1659 hb_buffer_set_segment_properties(buffer, &props);
1660
1661 uint buffer_flags = HB_BUFFER_FLAG_DEFAULT;
1662 // Symbol encoding used to encode various crap in the 32..255 character code range,
1663 // and thus might override U+00AD [SHY]; avoid hiding default ignorables
1664 if (Q_UNLIKELY(actualFontEngine->symbol || (option.flags() & QTextOption::ShowDefaultIgnorables)))
1665 buffer_flags |= HB_BUFFER_FLAG_PRESERVE_DEFAULT_IGNORABLES;
1666 hb_buffer_set_flags(buffer, hb_buffer_flags_t(buffer_flags));
1667
1668
1669 // shape
1670 {
1671 hb_font_t *hb_font = hb_qt_font_get_for_engine(actualFontEngine);
1672 Q_ASSERT(hb_font);
1673 hb_qt_font_set_use_design_metrics(hb_font, option.useDesignMetrics() ? uint(QFontEngine::DesignMetrics) : 0); // ###
1674
1675 // Ligatures are incompatible with custom letter spacing, so when a letter spacing is set,
1676 // we disable them for writing systems where they are purely cosmetic.
1677 bool scriptRequiresOpenType = ((script >= QChar::Script_Syriac && script <= QChar::Script_Sinhala)
1678 || script == QChar::Script_Khmer || script == QChar::Script_Nko);
1679
1680 bool dontLigate = hasLetterSpacing && !scriptRequiresOpenType;
1681
1682 QVarLengthFlatMap<QFont::Tag, hb_feature_t, 16> features;
1683 auto insertFeature = [&features](QFont::Tag tag, quint32 value) {
1684 features.insert(tag, { tag.value(),
1685 value,
1686 HB_FEATURE_GLOBAL_START,
1687 HB_FEATURE_GLOBAL_END });
1688 };
1689 // fontFeatures have precedence
1690 for (const auto &[tag, value]: fontFeatures.asKeyValueRange())
1691 insertFeature(tag, value);
1692 insertFeature(QFont::Tag("kern"), !!kerningEnabled);
1693 if (dontLigate) {
1694 insertFeature(QFont::Tag("liga"), false);
1695 insertFeature(QFont::Tag("clig"), false);
1696 insertFeature(QFont::Tag("dlig"), false);
1697 insertFeature(QFont::Tag("hlig"), false);
1698 }
1699
1700 // whitelist cross-platforms shapers only
1701 constexpr const char *shaper_list[] = {
1702 "graphite2",
1703 "ot",
1704 "fallback",
1705 nullptr
1706 };
1707
1708 bool shapedOk = hb_shape_full(hb_font,
1709 buffer,
1710 features.values().constData(),
1711 features.values().size(),
1712 shaper_list);
1713 if (Q_UNLIKELY(!shapedOk)) {
1714 hb_buffer_destroy(buffer);
1715 return 0;
1716 }
1717
1718 if (Q_UNLIKELY(HB_DIRECTION_IS_BACKWARD(props.direction)))
1719 hb_buffer_reverse(buffer);
1720 }
1721
1722 uint num_glyphs = hb_buffer_get_length(buffer);
1723 const bool has_glyphs = num_glyphs > 0;
1724 // If Harfbuzz returns zero glyphs, we have to manually add a missing glyph
1725 if (Q_UNLIKELY(!has_glyphs))
1726 num_glyphs = 1;
1727
1728 // ensure we have enough space for shaped glyphs and metrics
1729 if (Q_UNLIKELY(!ensureSpace(glyphs_shaped + num_glyphs))) {
1730 hb_buffer_destroy(buffer);
1731 return 0;
1732 }
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 hb_buffer_destroy(buffer);
1793
1794 return glyphs_shaped;
1795}
1796
1797#endif // harfbuzz
1798
1799void QTextEngine::init(QTextEngine *e)
1800{
1801 e->ignoreBidi = false;
1802 e->cacheGlyphs = false;
1803 e->forceJustification = false;
1804 e->visualMovement = false;
1805 e->delayDecorations = false;
1806
1807 e->layoutData = nullptr;
1808
1809 e->minWidth = 0;
1810 e->maxWidth = 0;
1811
1812 e->specialData = nullptr;
1813 e->stackEngine = false;
1814#ifndef QT_NO_RAWFONT
1815 e->useRawFont = false;
1816#endif
1817}
1818
1819QTextEngine::QTextEngine()
1820{
1821 init(this);
1822}
1823
1824QTextEngine::QTextEngine(const QString &str, const QFont &f)
1825 : text(str),
1826 fnt(f)
1827{
1828 init(this);
1829}
1830
1831QTextEngine::~QTextEngine()
1832{
1833 if (!stackEngine)
1834 delete layoutData;
1835 delete specialData;
1836 resetFontEngineCache();
1837}
1838
1839const QCharAttributes *QTextEngine::attributes() const
1840{
1841 if (layoutData && layoutData->haveCharAttributes)
1842 return (QCharAttributes *) layoutData->memory;
1843
1844 itemize();
1845 if (! ensureSpace(layoutData->string.size()))
1846 return nullptr;
1847
1848 QVarLengthArray<QUnicodeTools::ScriptItem> scriptItems(layoutData->items.size());
1849 for (int i = 0; i < layoutData->items.size(); ++i) {
1850 const QScriptItem &si = layoutData->items.at(i);
1851 scriptItems[i].position = si.position;
1852 scriptItems[i].script = QChar::Script(si.analysis.script);
1853 }
1854
1855 QUnicodeTools::initCharAttributes(
1856 layoutData->string,
1857 scriptItems.data(), scriptItems.size(),
1858 reinterpret_cast<QCharAttributes *>(layoutData->memory),
1859 QUnicodeTools::CharAttributeOptions(QUnicodeTools::GraphemeBreaks
1860 | QUnicodeTools::LineBreaks
1861 | QUnicodeTools::WhiteSpaces
1862 | QUnicodeTools::HangulLineBreakTailoring));
1863
1864
1865 layoutData->haveCharAttributes = true;
1866 return (QCharAttributes *) layoutData->memory;
1867}
1868
1869void QTextEngine::shape(int item) const
1870{
1871 auto &li = layoutData->items[item];
1872 if (li.analysis.flags == QScriptAnalysis::Object) {
1873 ensureSpace(1);
1874 if (QTextDocumentPrivate::get(block) != nullptr) {
1875 docLayout()->resizeInlineObject(QTextInlineObject(item, const_cast<QTextEngine *>(this)),
1876 li.position + block.position(),
1877 format(&li));
1878 } else {
1879 // Standalone QTextLayout (no QTextDocument): read the
1880 // object size from a QTextImageFormat set via setFormats().
1881 QTextCharFormat fmt = format(&li);
1882 if (fmt.isImageFormat()) {
1883 QTextImageFormat imgFmt = fmt.toImageFormat();
1884 const qreal w = imgFmt.width();
1885 const qreal h = imgFmt.height();
1886 if (w > 0 && h > 0) {
1887 QTextInlineObject obj(item, const_cast<QTextEngine *>(this));
1888 obj.setWidth(w);
1889 // Mirror QTextDocumentLayout::resizeInlineObject()
1890 // vertical alignment logic.
1891 const QFontMetricsF fm(fnt);
1892 switch (fmt.verticalAlignment()) {
1893 case QTextCharFormat::AlignMiddle: {
1894 const qreal halfX = fm.xHeight() / 2.0;
1895 obj.setAscent((h + halfX) / 2.0);
1896 obj.setDescent((h - halfX) / 2.0);
1897 break;
1898 }
1899 case QTextCharFormat::AlignBaseline: {
1900 const qreal descent = fm.descent();
1901 obj.setDescent(descent);
1902 obj.setAscent(h - descent);
1903 break;
1904 }
1905 default:
1906 obj.setDescent(0);
1907 obj.setAscent(h);
1908 break;
1909 }
1910 }
1911 }
1912 }
1913 // fix log clusters to point to the previous glyph, as the object doesn't have a glyph of it's own.
1914 // This is required so that all entries in the array get initialized and are ordered correctly.
1915 if (layoutData->logClustersPtr) {
1916 ushort *lc = logClusters(&li);
1917 *lc = (lc != layoutData->logClustersPtr) ? lc[-1] : 0;
1918 }
1919 } else if (li.analysis.flags == QScriptAnalysis::Tab) {
1920 // set up at least the ascent/descent/leading of the script item for the tab
1921 fontEngine(li, &li.ascent, &li.descent, &li.leading);
1922 // see the comment above
1923 if (layoutData->logClustersPtr) {
1924 ushort *lc = logClusters(&li);
1925 *lc = (lc != layoutData->logClustersPtr) ? lc[-1] : 0;
1926 }
1927 } else {
1928 shapeText(item);
1929 }
1930}
1931
1932static inline void releaseCachedFontEngine(QFontEngine *fontEngine)
1933{
1934 if (fontEngine && !fontEngine->ref.deref())
1935 delete fontEngine;
1936}
1937
1938void QTextEngine::resetFontEngineCache()
1939{
1940 releaseCachedFontEngine(feCache.prevFontEngine);
1941 releaseCachedFontEngine(feCache.prevScaledFontEngine);
1942 feCache.reset();
1943}
1944
1945void QTextEngine::invalidate()
1946{
1947 freeMemory();
1948 minWidth = 0;
1949 maxWidth = 0;
1950
1951 resetFontEngineCache();
1952}
1953
1954void QTextEngine::clearLineData()
1955{
1956 lines.clear();
1957}
1958
1959void QTextEngine::validate() const
1960{
1961 if (layoutData)
1962 return;
1963 layoutData = new LayoutData();
1964 if (QTextDocumentPrivate::get(block) != nullptr) {
1965 layoutData->string = block.text();
1966 const bool nextBlockValid = block.next().isValid();
1967 if (!nextBlockValid && option.flags() & QTextOption::ShowDocumentTerminator) {
1968 layoutData->string += QLatin1Char('\xA7');
1969 } else if (option.flags() & QTextOption::ShowLineAndParagraphSeparators) {
1970 layoutData->string += QLatin1Char(nextBlockValid ? '\xB6' : '\x20');
1971 }
1972
1973 } else {
1974 layoutData->string = text;
1975 }
1976 if (specialData && specialData->preeditPosition != -1)
1977 layoutData->string.insert(specialData->preeditPosition, specialData->preeditText);
1978}
1979
1980#if !defined(QT_NO_EMOJISEGMENTER)
1981namespace {
1982
1983 enum CharacterCategory {
1984 EMOJI = 0,
1985 EMOJI_TEXT_PRESENTATION = 1,
1986 EMOJI_EMOJI_PRESENTATION = 2,
1987 EMOJI_MODIFIER_BASE = 3,
1988 EMOJI_MODIFIER = 4,
1989 EMOJI_VS_BASE = 5,
1990 REGIONAL_INDICATOR = 6,
1991 KEYCAP_BASE = 7,
1992 COMBINING_ENCLOSING_KEYCAP = 8,
1993 COMBINING_ENCLOSING_CIRCLE_BACKSLASH = 9,
1994 ZWJ = 10,
1995 VS15 = 11,
1996 VS16 = 12,
1997 TAG_BASE = 13,
1998 TAG_SEQUENCE = 14,
1999 TAG_TERM = 15,
2000 OTHER = 16
2001 };
2002
2003 typedef CharacterCategory *emoji_text_iter_t;
2004
2005 #include "../../3rdparty/emoji-segmenter/emoji_presentation_scanner.c"
2006}
2007#endif
2008
2009void QTextEngine::itemize() const
2010{
2011 validate();
2012 if (layoutData->items.size())
2013 return;
2014
2015 int length = layoutData->string.size();
2016 if (!length)
2017 return;
2018
2019 const ushort *string = reinterpret_cast<const ushort *>(layoutData->string.unicode());
2020
2021 bool rtl = isRightToLeft();
2022
2023 QVarLengthArray<QScriptAnalysis> scriptAnalysis(length);
2024 QScriptAnalysis *analysis = scriptAnalysis.data();
2025
2026 QBidiAlgorithm bidi(layoutData->string.constData(), analysis, length, rtl);
2027 layoutData->hasBidi = bidi.process();
2028
2029 {
2030 QUnicodeTools::ScriptItemArray scriptItems;
2031 QUnicodeTools::initScripts(layoutData->string, &scriptItems);
2032 for (int i = 0; i < scriptItems.size(); ++i) {
2033 const auto &item = scriptItems.at(i);
2034 int end = i < scriptItems.size() - 1 ? scriptItems.at(i + 1).position : length;
2035 for (int j = item.position; j < end; ++j)
2036 analysis[j].script = item.script;
2037 }
2038 }
2039
2040#if !defined(QT_NO_EMOJISEGMENTER)
2041 const bool disableEmojiSegmenter = QFontEngine::disableEmojiSegmenter() || option.flags().testFlag(QTextOption::DisableEmojiParsing);
2042
2043 qCDebug(lcEmojiSegmenter) << "Emoji segmenter disabled:" << disableEmojiSegmenter;
2044
2045 QVarLengthArray<CharacterCategory> categorizedString;
2046 if (!disableEmojiSegmenter) {
2047 // Parse emoji sequences
2048 for (int i = 0; i < length; ++i) {
2049 const QChar &c = string[i];
2050 const bool isSurrogate = c.isHighSurrogate()
2051 && i < length - 1
2052 && QChar::isLowSurrogate(string[i + 1]);
2053 const char32_t ucs4 = isSurrogate
2054 ? QChar::surrogateToUcs4(c, string[++i])
2055 : c.unicode();
2056 const QUnicodeTables::Properties *p = QUnicodeTables::properties(ucs4);
2057
2058 if (ucs4 == 0x20E3)
2059 categorizedString.append(CharacterCategory::COMBINING_ENCLOSING_KEYCAP);
2060 else if (ucs4 == 0x20E0)
2061 categorizedString.append(CharacterCategory::COMBINING_ENCLOSING_CIRCLE_BACKSLASH);
2062 else if (ucs4 == 0xFE0E)
2063 categorizedString.append(CharacterCategory::VS15);
2064 else if (ucs4 == 0xFE0F)
2065 categorizedString.append(CharacterCategory::VS16);
2066 else if (ucs4 == 0x200D)
2067 categorizedString.append(CharacterCategory::ZWJ);
2068 else if (ucs4 == 0x1F3F4)
2069 categorizedString.append(CharacterCategory::TAG_BASE);
2070 else if (ucs4 == 0xE007F)
2071 categorizedString.append(CharacterCategory::TAG_TERM);
2072 else if ((ucs4 >= 0xE0030 && ucs4 <= 0xE0039) || (ucs4 >= 0xE0061 && ucs4 <= 0xE007A))
2073 categorizedString.append(CharacterCategory::TAG_SEQUENCE);
2074 else if (ucs4 >= 0x1F1E6 && ucs4 <= 0x1F1FF)
2075 categorizedString.append(CharacterCategory::REGIONAL_INDICATOR);
2076 // emoji_keycap_sequence = [0-9#*] \x{FE0F 20E3}
2077 else if ((ucs4 >= 0x0030 && ucs4 <= 0x0039) || ucs4 == 0x0023 || ucs4 == 0x002A)
2078 categorizedString.append(CharacterCategory::KEYCAP_BASE);
2079 else if (p->emojiFlags & uchar(QUnicodeTables::EmojiFlags::Emoji_Modifier_Base))
2080 categorizedString.append(CharacterCategory::EMOJI_MODIFIER_BASE);
2081 else if (p->emojiFlags & uchar(QUnicodeTables::EmojiFlags::Emoji_Modifier))
2082 categorizedString.append(CharacterCategory::EMOJI_MODIFIER);
2083 else if (p->emojiFlags & uchar(QUnicodeTables::EmojiFlags::Emoji_Presentation))
2084 categorizedString.append(CharacterCategory::EMOJI_EMOJI_PRESENTATION);
2085 // If it's in the emoji list and doesn't have the emoji presentation, it is text
2086 // presentation.
2087 else if (p->emojiFlags & uchar(QUnicodeTables::EmojiFlags::Emoji))
2088 categorizedString.append(CharacterCategory::EMOJI_TEXT_PRESENTATION);
2089 else
2090 categorizedString.append(CharacterCategory::OTHER);
2091
2092 qCDebug(lcEmojiSegmenter) << "Checking character" << (isSurrogate ? (i - 1) : i)
2093 << ", ucs4 ==" << ucs4
2094 << ", category:" << categorizedString.last();
2095 }
2096 }
2097#endif
2098
2099 const ushort *uc = string;
2100 const ushort *e = uc + length;
2101
2102#if !defined(QT_NO_EMOJISEGMENTER)
2103 const emoji_text_iter_t categoriesStart = categorizedString.data();
2104 const emoji_text_iter_t categoriesEnd = categoriesStart + categorizedString.size();
2105
2106 emoji_text_iter_t categoryIt = categoriesStart;
2107
2108 bool isEmoji = false;
2109 bool hasVs = false;
2110 emoji_text_iter_t nextIt = categoryIt;
2111#endif
2112
2113 while (uc < e) {
2114#if !defined(QT_NO_EMOJISEGMENTER)
2115 // Find next emoji sequence
2116 if (!disableEmojiSegmenter && categoryIt == nextIt) {
2117 nextIt = scan_emoji_presentation(categoryIt, categoriesEnd, &isEmoji, &hasVs);
2118
2119 qCDebug(lcEmojiSegmenter) << "Checking character" << (categoryIt - categoriesStart)
2120 << ", sequence length:" << (nextIt - categoryIt)
2121 << ", is emoji sequence:" << isEmoji;
2122
2123 }
2124#endif
2125
2126 switch (*uc) {
2127 case QChar::ObjectReplacementCharacter:
2128 {
2129 const QTextDocumentPrivate *doc_p = QTextDocumentPrivate::get(block);
2130 if (doc_p != nullptr
2131 && doc_p->layout() != nullptr
2132 && QAbstractTextDocumentLayoutPrivate::get(doc_p->layout()) != nullptr
2133 && QAbstractTextDocumentLayoutPrivate::get(doc_p->layout())->hasHandlers()) {
2134 analysis->flags = QScriptAnalysis::Object;
2135 } else if (specialData) {
2136 // Standalone QTextLayout: check if a QTextImageFormat
2137 // was set for this position via setFormats().
2138 const int pos = uc - string;
2139 analysis->flags = QScriptAnalysis::None;
2140 for (const auto &range : std::as_const(specialData->formats)) {
2141 if (range.start <= pos && pos < range.start + range.length
2142 && range.format.isImageFormat()) {
2143 analysis->flags = QScriptAnalysis::Object;
2144 break;
2145 }
2146 }
2147 } else {
2148 analysis->flags = QScriptAnalysis::None;
2149 }
2150 }
2151 break;
2152 case QChar::LineSeparator:
2153 analysis->flags = QScriptAnalysis::LineOrParagraphSeparator;
2154 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators) {
2155 const int offset = uc - string;
2156 layoutData->string.detach();
2157 string = reinterpret_cast<const ushort *>(layoutData->string.unicode());
2158 uc = string + offset;
2159 e = string + length;
2160 *const_cast<ushort*>(uc) = 0x21B5; // visual line separator
2161 }
2162 break;
2163 case QChar::Tabulation:
2164 analysis->flags = QScriptAnalysis::Tab;
2165 analysis->bidiLevel = bidi.baseLevel;
2166 break;
2167 case QChar::Space:
2168 case QChar::Nbsp:
2169 if (option.flags() & QTextOption::ShowTabsAndSpaces) {
2170 analysis->flags = (*uc == QChar::Space) ? QScriptAnalysis::Space : QScriptAnalysis::Nbsp;
2171 break;
2172 }
2173 Q_FALLTHROUGH();
2174 default:
2175 analysis->flags = QScriptAnalysis::None;
2176 break;
2177 };
2178
2179#if !defined(QT_NO_EMOJISEGMENTER)
2180 if (!disableEmojiSegmenter) {
2181 if (isEmoji) {
2182 static_assert(QChar::ScriptCount < USHRT_MAX);
2183 analysis->script = QFontDatabasePrivate::Script_Emoji;
2184 }
2185
2186 if (QChar::isHighSurrogate(*uc) && (uc + 1) < e && QChar::isLowSurrogate(*(uc + 1))) {
2187 if (isEmoji)
2188 (analysis + 1)->script = QFontDatabasePrivate::Script_Emoji;
2189
2190 ++uc;
2191 ++analysis;
2192 }
2193
2194 ++categoryIt;
2195 }
2196#endif
2197
2198 ++uc;
2199 ++analysis;
2200 }
2201#if !defined(QT_NO_EMOJISEGMENTER)
2202 Q_ASSERT(disableEmojiSegmenter || categoryIt == categoriesEnd);
2203#endif
2204 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators) {
2205 (analysis-1)->flags = QScriptAnalysis::LineOrParagraphSeparator; // to exclude it from width
2206 }
2207
2208 Itemizer itemizer(layoutData->string, scriptAnalysis.data(), layoutData->items);
2209
2210 const QTextDocumentPrivate *p = QTextDocumentPrivate::get(block);
2211 if (p) {
2212 SpecialData *s = specialData;
2213
2214 QTextDocumentPrivate::FragmentIterator it = p->find(block.position());
2215 QTextDocumentPrivate::FragmentIterator end = p->find(block.position() + block.length() - 1); // -1 to omit the block separator char
2216 int format = it.value()->format;
2217
2218 int preeditPosition = s ? s->preeditPosition : INT_MAX;
2219 int prevPosition = 0;
2220 int position = prevPosition;
2221 while (1) {
2222 const QTextFragmentData * const frag = it.value();
2223 if (it == end || format != frag->format) {
2224 if (s && position >= preeditPosition) {
2225 position += s->preeditText.size();
2226 preeditPosition = INT_MAX;
2227 }
2228 Q_ASSERT(position <= length);
2229 QFont::Capitalization capitalization =
2230 formatCollection()->charFormat(format).hasProperty(QTextFormat::FontCapitalization)
2231 ? formatCollection()->charFormat(format).fontCapitalization()
2232 : formatCollection()->defaultFont().capitalization();
2233 if (s) {
2234 for (const auto &range : std::as_const(s->formats)) {
2235 if (range.start + range.length <= prevPosition || range.start >= position)
2236 continue;
2237 if (range.format.hasProperty(QTextFormat::FontCapitalization)) {
2238 if (range.start > prevPosition)
2239 itemizer.generate(prevPosition, range.start - prevPosition, capitalization);
2240 int newStart = std::max(prevPosition, range.start);
2241 int newEnd = std::min(position, range.start + range.length);
2242 itemizer.generate(newStart, newEnd - newStart, range.format.fontCapitalization());
2243 prevPosition = newEnd;
2244 }
2245 }
2246 }
2247 itemizer.generate(prevPosition, position - prevPosition, capitalization);
2248 if (it == end) {
2249 if (position < length)
2250 itemizer.generate(position, length - position, capitalization);
2251 break;
2252 }
2253 format = frag->format;
2254 prevPosition = position;
2255 }
2256 position += frag->size_array[0];
2257 ++it;
2258 }
2259 } else {
2260#ifndef QT_NO_RAWFONT
2261 if (useRawFont && specialData) {
2262 int lastIndex = 0;
2263 for (int i = 0; i < specialData->formats.size(); ++i) {
2264 const QTextLayout::FormatRange &range = specialData->formats.at(i);
2265 const QTextCharFormat &format = range.format;
2266 if (format.hasProperty(QTextFormat::FontCapitalization)) {
2267 itemizer.generate(lastIndex, range.start - lastIndex, QFont::MixedCase);
2268 itemizer.generate(range.start, range.length, format.fontCapitalization());
2269 lastIndex = range.start + range.length;
2270 }
2271 }
2272 itemizer.generate(lastIndex, length - lastIndex, QFont::MixedCase);
2273 } else
2274#endif
2275 itemizer.generate(0, length, static_cast<QFont::Capitalization> (fnt.d->capital));
2276 }
2277
2278 addRequiredBoundaries();
2279 resolveFormats();
2280}
2281
2282bool QTextEngine::isRightToLeft() const
2283{
2284 switch (option.textDirection()) {
2285 case Qt::LeftToRight:
2286 return false;
2287 case Qt::RightToLeft:
2288 return true;
2289 default:
2290 break;
2291 }
2292 if (!layoutData)
2293 itemize();
2294 // this places the cursor in the right position depending on the keyboard layout
2295 if (layoutData->string.isEmpty())
2296 return QGuiApplication::inputMethod()->inputDirection() == Qt::RightToLeft;
2297 return layoutData->string.isRightToLeft();
2298}
2299
2300
2301int QTextEngine::findItem(int strPos, int firstItem) const
2302{
2303 itemize();
2304 if (strPos < 0 || strPos >= layoutData->string.size() || firstItem < 0)
2305 return -1;
2306
2307 int left = firstItem + 1;
2308 int right = layoutData->items.size()-1;
2309 while(left <= right) {
2310 int middle = ((right-left)/2)+left;
2311 if (strPos > layoutData->items.at(middle).position)
2312 left = middle+1;
2313 else if (strPos < layoutData->items.at(middle).position)
2314 right = middle-1;
2315 else {
2316 return middle;
2317 }
2318 }
2319 return right;
2320}
2321
2322namespace {
2323template<typename InnerFunc>
2324void textIterator(const QTextEngine *textEngine, int from, int len, QFixed &width, InnerFunc &&innerFunc)
2325{
2326 for (int i = 0; i < textEngine->layoutData->items.size(); i++) {
2327 const QScriptItem *si = textEngine->layoutData->items.constData() + i;
2328 int pos = si->position;
2329 int ilen = textEngine->length(i);
2330// qDebug("item %d: from %d len %d", i, pos, ilen);
2331 if (pos >= from + len)
2332 break;
2333 if (pos + ilen > from) {
2334 if (!si->num_glyphs)
2335 textEngine->shape(i);
2336
2337 if (si->analysis.flags == QScriptAnalysis::Object) {
2338 width += si->width;
2339 continue;
2340 } else if (si->analysis.flags == QScriptAnalysis::Tab) {
2341 width += textEngine->calculateTabWidth(i, width);
2342 continue;
2343 }
2344
2345 unsigned short *logClusters = textEngine->logClusters(si);
2346
2347// fprintf(stderr, " logclusters:");
2348// for (int k = 0; k < ilen; k++)
2349// fprintf(stderr, " %d", logClusters[k]);
2350// fprintf(stderr, "\n");
2351 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
2352 int charFrom = from - pos;
2353 if (charFrom < 0)
2354 charFrom = 0;
2355 int glyphStart = logClusters[charFrom];
2356 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
2357 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
2358 charFrom++;
2359 if (charFrom < ilen) {
2360 glyphStart = logClusters[charFrom];
2361 int charEnd = from + len - 1 - pos;
2362 if (charEnd >= ilen)
2363 charEnd = ilen-1;
2364 int glyphEnd = logClusters[charEnd];
2365 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
2366 charEnd++;
2367 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
2368
2369// qDebug("char: start=%d end=%d / glyph: start = %d, end = %d", charFrom, charEnd, glyphStart, glyphEnd);
2370 innerFunc(glyphStart, glyphEnd, si);
2371 }
2372 }
2373 }
2374}
2375} // namespace
2376
2377QFixed QTextEngine::width(int from, int len) const
2378{
2379 itemize();
2380
2381 QFixed w = 0;
2382// qDebug("QTextEngine::width(from = %d, len = %d), numItems=%d, strleng=%d", from, len, items.size(), string.length());
2383 textIterator(this, from, len, w, [this, &w](int glyphStart, int glyphEnd, const QScriptItem *si) {
2384 QGlyphLayout glyphs = this->shapedGlyphs(si);
2385 for (int j = glyphStart; j < glyphEnd; j++)
2386 w += glyphs.advances[j] * !glyphs.attributes[j].dontPrint;
2387 });
2388// qDebug(" --> w= %d ", w);
2389 return w;
2390}
2391
2392glyph_metrics_t QTextEngine::boundingBox(int from, int len) const
2393{
2394 itemize();
2395
2396 glyph_metrics_t gm;
2397
2398 textIterator(this, from, len, gm.width, [this, &gm](int glyphStart, int glyphEnd, const QScriptItem *si) {
2399 if (glyphStart <= glyphEnd) {
2400 QGlyphLayout glyphs = this->shapedGlyphs(si);
2401 QFontEngine *fe = this->fontEngine(*si);
2402 glyph_metrics_t m = fe->boundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
2403 gm.x = qMin(gm.x, m.x + gm.xoff);
2404 gm.y = qMin(gm.y, m.y + gm.yoff);
2405 gm.width = qMax(gm.width, m.width + gm.xoff);
2406 gm.height = qMax(gm.height, m.height + gm.yoff);
2407 gm.xoff += m.xoff;
2408 gm.yoff += m.yoff;
2409 }
2410 });
2411
2412 return gm;
2413}
2414
2415glyph_metrics_t QTextEngine::tightBoundingBox(int from, int len) const
2416{
2417 itemize();
2418
2419 glyph_metrics_t gm;
2420
2421 textIterator(this, from, len, gm.width, [this, &gm](int glyphStart, int glyphEnd, const QScriptItem *si) {
2422 if (glyphStart <= glyphEnd) {
2423 QGlyphLayout glyphs = this->shapedGlyphs(si);
2424 QFontEngine *fe = fontEngine(*si);
2425
2426 QTextItem::RenderFlags flags = si->analysis.bidiLevel % 2
2427 ? QTextItem::RightToLeft
2428 : QTextItem::RenderFlags();
2429 glyph_metrics_t m = fe->tightBoundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart), flags);
2430
2431 gm.x = qMin(gm.x, m.x + gm.xoff);
2432 gm.y = qMin(gm.y, m.y + gm.yoff);
2433 gm.width = qMax(gm.width, m.width + gm.xoff);
2434 gm.height = qMax(gm.height, m.height + gm.yoff);
2435 gm.xoff += m.xoff;
2436 gm.yoff += m.yoff;
2437 }
2438 });
2439 return gm;
2440}
2441
2442QFont QTextEngine::font(const QScriptItem &si) const
2443{
2444 QFont font = fnt;
2445 if (hasFormats()) {
2446 QTextCharFormat f = format(&si);
2447 font = f.font();
2448
2449 const QTextDocumentPrivate *document_d = QTextDocumentPrivate::get(block);
2450 if (document_d != nullptr && document_d->layout() != nullptr) {
2451 // Make sure we get the right dpi on printers
2452 QPaintDevice *pdev = document_d->layout()->paintDevice();
2453 if (pdev)
2454 font = QFont(font, pdev);
2455 } else {
2456 font = font.resolve(fnt);
2457 }
2458 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
2459 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
2460 if (font.pointSize() != -1)
2461 font.setPointSize((font.pointSize() * 2) / 3);
2462 else
2463 font.setPixelSize((font.pixelSize() * 2) / 3);
2464 }
2465 }
2466
2467 if (si.analysis.flags == QScriptAnalysis::SmallCaps)
2468 font = font.d->smallCapsFont();
2469
2470 return font;
2471}
2472
2473QTextEngine::FontEngineCache::FontEngineCache()
2474{
2475 reset();
2476}
2477
2478//we cache the previous results of this function, as calling it numerous times with the same effective
2479//input is common (and hard to cache at a higher level)
2480QFontEngine *QTextEngine::fontEngine(const QScriptItem &si, QFixed *ascent, QFixed *descent, QFixed *leading) const
2481{
2482 QFontEngine *engine = nullptr;
2483 QFontEngine *scaledEngine = nullptr;
2484 int script = si.analysis.script;
2485
2486 QFont font = fnt;
2487#ifndef QT_NO_RAWFONT
2488 if (useRawFont && rawFont.isValid()) {
2489 if (feCache.prevFontEngine && feCache.prevFontEngine->type() == QFontEngine::Multi && feCache.prevScript == script) {
2490 engine = feCache.prevFontEngine;
2491 } else {
2492 engine = QFontEngineMulti::createMultiFontEngine(rawFont.d->fontEngine, script);
2493 engine->ref.ref();
2494 if (feCache.prevFontEngine)
2495 releaseCachedFontEngine(feCache.prevFontEngine);
2496 feCache.prevFontEngine = engine;
2497 feCache.prevScript = script;
2498 if (feCache.prevScaledFontEngine) {
2499 releaseCachedFontEngine(feCache.prevScaledFontEngine);
2500 feCache.prevScaledFontEngine = nullptr;
2501 }
2502 }
2503 if (si.analysis.flags == QScriptAnalysis::SmallCaps) {
2504 if (feCache.prevScaledFontEngine) {
2505 scaledEngine = feCache.prevScaledFontEngine;
2506 } else {
2507 // GCC 12 gets confused about QFontEngine::ref, for some non-obvious reason
2508 // warning: ‘unsigned int __atomic_or_fetch_4(volatile void*, unsigned int, int)’ writing 4 bytes
2509 // into a region of size 0 overflows the destination [-Wstringop-overflow=]
2510 QT_WARNING_PUSH
2511 QT_WARNING_DISABLE_GCC("-Wstringop-overflow")
2512
2513 QFontEngine *scEngine = rawFont.d->fontEngine->cloneWithSize(smallCapsFraction * rawFont.pixelSize());
2514 scEngine->ref.ref();
2515 scaledEngine = QFontEngineMulti::createMultiFontEngine(scEngine, script);
2516 scaledEngine->ref.ref();
2517 feCache.prevScaledFontEngine = scaledEngine;
2518 // If scEngine is not ref'ed by scaledEngine, make sure it is deallocated and not leaked.
2519 if (!scEngine->ref.deref())
2520 delete scEngine;
2521
2522 QT_WARNING_POP
2523 }
2524 }
2525 } else
2526#endif
2527 {
2528 if (hasFormats()) {
2529 if (feCache.prevFontEngine && feCache.prevPosition == si.position && feCache.prevLength == length(&si) && feCache.prevScript == script) {
2530 engine = feCache.prevFontEngine;
2531 scaledEngine = feCache.prevScaledFontEngine;
2532 } else {
2533 QTextCharFormat f = format(&si);
2534 font = f.font();
2535
2536 if (QTextDocumentPrivate::get(block) != nullptr && QTextDocumentPrivate::get(block)->layout() != nullptr) {
2537 // Make sure we get the right dpi on printers
2538 QPaintDevice *pdev = QTextDocumentPrivate::get(block)->layout()->paintDevice();
2539 if (pdev)
2540 font = QFont(font, pdev);
2541 } else {
2542 font = font.resolve(fnt);
2543 }
2544 engine = font.d->engineForScript(script);
2545 Q_ASSERT(engine);
2546 engine->ref.ref();
2547
2548 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
2549 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
2550 if (font.pointSize() != -1)
2551 font.setPointSize((font.pointSize() * 2) / 3);
2552 else
2553 font.setPixelSize((font.pixelSize() * 2) / 3);
2554 scaledEngine = font.d->engineForScript(script);
2555 if (scaledEngine)
2556 scaledEngine->ref.ref();
2557 }
2558
2559 if (feCache.prevFontEngine)
2560 releaseCachedFontEngine(feCache.prevFontEngine);
2561 feCache.prevFontEngine = engine;
2562
2563 if (feCache.prevScaledFontEngine)
2564 releaseCachedFontEngine(feCache.prevScaledFontEngine);
2565 feCache.prevScaledFontEngine = scaledEngine;
2566
2567 feCache.prevScript = script;
2568 feCache.prevPosition = si.position;
2569 feCache.prevLength = length(&si);
2570 }
2571 } else {
2572 if (feCache.prevFontEngine && feCache.prevScript == script && feCache.prevPosition == -1) {
2573 engine = feCache.prevFontEngine;
2574 } else {
2575 engine = font.d->engineForScript(script);
2576 Q_ASSERT(engine);
2577 engine->ref.ref();
2578 if (feCache.prevFontEngine)
2579 releaseCachedFontEngine(feCache.prevFontEngine);
2580 feCache.prevFontEngine = engine;
2581
2582 feCache.prevScript = script;
2583 feCache.prevPosition = -1;
2584 feCache.prevLength = -1;
2585 if (feCache.prevScaledFontEngine)
2586 releaseCachedFontEngine(feCache.prevScaledFontEngine);
2587 feCache.prevScaledFontEngine = nullptr;
2588 }
2589 }
2590
2591 if (si.analysis.flags == QScriptAnalysis::SmallCaps) {
2592 QFontPrivate *p = font.d->smallCapsFontPrivate();
2593 scaledEngine = p->engineForScript(script);
2594 }
2595 }
2596
2597 if (leading) {
2598 Q_ASSERT(engine);
2599 Q_ASSERT(ascent);
2600 Q_ASSERT(descent);
2601 *ascent = engine->ascent();
2602 *descent = engine->descent();
2603 *leading = engine->leading();
2604 }
2605
2606 if (scaledEngine)
2607 return scaledEngine;
2608 return engine;
2609}
2610
2616
2618
2619static void set(QJustificationPoint *point, int type, const QGlyphLayout &glyph, QFontEngine *fe)
2620{
2621 point->type = type;
2622 point->glyph = glyph;
2623
2624 if (type >= Justification_Arabic_Normal) {
2625 const char32_t ch = U'\x640'; // Kashida character
2626
2627 glyph_t kashidaGlyph = fe->glyphIndex(ch);
2628 if (kashidaGlyph != 0) {
2629 QGlyphLayout g;
2630 g.numGlyphs = 1;
2631 g.glyphs = &kashidaGlyph;
2632 g.advances = &point->kashidaWidth;
2633 fe->recalcAdvances(&g, { });
2634
2635 if (point->kashidaWidth == 0)
2637 } else {
2639 point->kashidaWidth = 0;
2640 }
2641 }
2642}
2643
2644
2645void QTextEngine::justify(const QScriptLine &line)
2646{
2647// qDebug("justify: line.gridfitted = %d, line.justified=%d", line.gridfitted, line.justified);
2648 if (line.gridfitted && line.justified)
2649 return;
2650
2651 if (!line.gridfitted) {
2652 // redo layout in device metrics, then adjust
2653 const_cast<QScriptLine &>(line).gridfitted = true;
2654 }
2655
2656 if ((option.alignment() & Qt::AlignHorizontal_Mask) != Qt::AlignJustify)
2657 return;
2658
2659 itemize();
2660
2661 if (!forceJustification) {
2662 int end = line.from + (int)line.length + line.trailingSpaces;
2663 if (end == layoutData->string.size())
2664 return; // no justification at end of paragraph
2665 if (end && layoutData->items.at(findItem(end - 1)).analysis.flags == QScriptAnalysis::LineOrParagraphSeparator)
2666 return; // no justification at the end of an explicitly separated line
2667 }
2668
2669 // justify line
2670 int maxJustify = 0;
2671
2672 // May shape the trailing spaces, so do it before taking the glyph views below
2673 const QFixed leading = leadingSpaceWidth(line);
2674
2675 // don't include trailing white spaces when doing justification
2676 int line_length = line.length;
2677 const QCharAttributes *a = attributes();
2678 if (! a)
2679 return;
2680 a += line.from;
2681 while (line_length && a[line_length-1].whiteSpace)
2682 --line_length;
2683 // subtract one char more, as we can't justfy after the last character
2684 --line_length;
2685
2686 if (line_length <= 0)
2687 return;
2688
2689 int firstItem = findItem(line.from);
2690 int lastItem = findItem(line.from + line_length - 1, firstItem);
2691 int nItems = (firstItem >= 0 && lastItem >= firstItem)? (lastItem-firstItem+1) : 0;
2692
2693 QVarLengthArray<QJustificationPoint> justificationPoints;
2694 int nPoints = 0;
2695// 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());
2696 QFixed minKashida = 0x100000;
2697
2698 // we need to do all shaping before we go into the next loop, as we there
2699 // store pointers to the glyph data that could get reallocated by the shaping
2700 // process.
2701 for (int i = 0; i < nItems; ++i) {
2702 const QScriptItem &si = layoutData->items.at(firstItem + i);
2703 if (!si.num_glyphs)
2704 shape(firstItem + i);
2705 }
2706
2707 for (int i = 0; i < nItems; ++i) {
2708 const QScriptItem &si = layoutData->items.at(firstItem + i);
2709
2710 int kashida_type = Justification_Arabic_Normal;
2711 int kashida_pos = -1;
2712
2713 int start = qMax(line.from - si.position, 0);
2714 int end = qMin(line.from + line_length - (int)si.position, length(firstItem+i));
2715
2716 unsigned short *log_clusters = logClusters(&si);
2717
2718 int gs = log_clusters[start];
2719 int ge = (end == length(firstItem+i) ? si.num_glyphs : log_clusters[end]);
2720
2721 Q_ASSERT(ge <= si.num_glyphs);
2722
2723 const QGlyphLayout g = shapedGlyphs(&si);
2724
2725 for (int i = gs; i < ge; ++i) {
2726 g.justifications[i].type = QGlyphJustification::JustifyNone;
2727 g.justifications[i].nKashidas = 0;
2728 g.justifications[i].space_18d6 = 0;
2729
2730 justificationPoints.resize(nPoints+3);
2731 int justification = g.attributes[i].justification;
2732
2733 switch(justification) {
2734 case Justification_Prohibited:
2735 break;
2736 case Justification_Space:
2737 case Justification_Arabic_Space:
2738 if (kashida_pos >= 0) {
2739// qDebug("kashida position at %d in word", kashida_pos);
2740 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
2741 if (justificationPoints[nPoints].kashidaWidth > 0) {
2742 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
2743 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
2744 ++nPoints;
2745 }
2746 }
2747 kashida_pos = -1;
2748 kashida_type = Justification_Arabic_Normal;
2749 Q_FALLTHROUGH();
2750 case Justification_Character:
2751 set(&justificationPoints[nPoints++], justification, g.mid(i), fontEngine(si));
2752 maxJustify = qMax(maxJustify, justification);
2753 break;
2754 case Justification_Arabic_Normal:
2755 case Justification_Arabic_Waw:
2756 case Justification_Arabic_BaRa:
2757 case Justification_Arabic_Alef:
2758 case Justification_Arabic_HahDal:
2759 case Justification_Arabic_Seen:
2760 case Justification_Arabic_Kashida:
2761 if (justification >= kashida_type) {
2762 kashida_pos = i;
2763 kashida_type = justification;
2764 }
2765 }
2766 }
2767 if (kashida_pos >= 0) {
2768 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
2769 if (justificationPoints[nPoints].kashidaWidth > 0) {
2770 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
2771 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
2772 ++nPoints;
2773 }
2774 }
2775 }
2776
2777 QFixed need = line.width - line.textWidth - leading;
2778 if (need < 0) {
2779 // line overflows already!
2780 const_cast<QScriptLine &>(line).justified = true;
2781 return;
2782 }
2783
2784// qDebug("doing justification: textWidth=%x, requested=%x, maxJustify=%d", line.textWidth.value(), line.width.value(), maxJustify);
2785// qDebug(" minKashida=%f, need=%f", minKashida.toReal(), need.toReal());
2786
2787 // distribute in priority order
2788 if (maxJustify >= Justification_Arabic_Normal) {
2789 while (need >= minKashida) {
2790 for (int type = maxJustify; need >= minKashida && type >= Justification_Arabic_Normal; --type) {
2791 for (int i = 0; need >= minKashida && i < nPoints; ++i) {
2792 if (justificationPoints[i].type == type && justificationPoints[i].kashidaWidth <= need) {
2793 justificationPoints[i].glyph.justifications->nKashidas++;
2794 // ############
2795 justificationPoints[i].glyph.justifications->space_18d6 += justificationPoints[i].kashidaWidth.value();
2796 need -= justificationPoints[i].kashidaWidth;
2797// qDebug("adding kashida type %d with width %x, neednow %x", type, justificationPoints[i].kashidaWidth, need.value());
2798 }
2799 }
2800 }
2801 }
2802 }
2803 Q_ASSERT(need >= 0);
2804 if (!need)
2805 goto end;
2806
2807 maxJustify = qMin(maxJustify, int(Justification_Space));
2808 for (int type = maxJustify; need != 0 && type > 0; --type) {
2809 int n = 0;
2810 for (int i = 0; i < nPoints; ++i) {
2811 if (justificationPoints[i].type == type)
2812 ++n;
2813 }
2814// qDebug("number of points for justification type %d: %d", type, n);
2815
2816
2817 if (!n)
2818 continue;
2819
2820 for (int i = 0; i < nPoints; ++i) {
2821 if (justificationPoints[i].type == type) {
2822 QFixed add = need/n;
2823// qDebug("adding %x to glyph %x", add.value(), justificationPoints[i].glyph->glyph);
2824 justificationPoints[i].glyph.justifications[0].space_18d6 = add.value();
2825 need -= add;
2826 --n;
2827 }
2828 }
2829
2830 Q_ASSERT(!need);
2831 }
2832 end:
2833 const_cast<QScriptLine &>(line).justified = true;
2834}
2835
2836void QScriptLine::setDefaultHeight(QTextEngine *eng)
2837{
2838 QFont f;
2839 QFontEngine *e;
2840
2841 if (QTextDocumentPrivate::get(eng->block) != nullptr && QTextDocumentPrivate::get(eng->block)->layout() != nullptr) {
2842 f = eng->block.charFormat().font();
2843 // Make sure we get the right dpi on printers
2844 QPaintDevice *pdev = QTextDocumentPrivate::get(eng->block)->layout()->paintDevice();
2845 if (pdev)
2846 f = QFont(f, pdev);
2847 e = f.d->engineForScript(QChar::Script_Common);
2848 } else {
2849 e = eng->fnt.d->engineForScript(QChar::Script_Common);
2850 }
2851
2852 QFixed other_ascent = e->ascent();
2853 QFixed other_descent = e->descent();
2854 QFixed other_leading = e->leading();
2855 leading = qMax(leading + ascent, other_leading + other_ascent) - qMax(ascent, other_ascent);
2856 ascent = qMax(ascent, other_ascent);
2857 descent = qMax(descent, other_descent);
2858}
2859
2860QTextEngine::LayoutData::LayoutData()
2861{
2862 memory = nullptr;
2863 allocated = 0;
2864 memory_on_stack = false;
2865 used = 0;
2866 hasBidi = false;
2867 layoutState = LayoutEmpty;
2868 haveCharAttributes = false;
2869 logClustersPtr = nullptr;
2870 available_glyphs = 0;
2871 currentMaxWidth = 0;
2872}
2873
2874QTextEngine::LayoutData::LayoutData(const QString &str, void **stack_memory, qsizetype _allocated)
2875 : string(str)
2876{
2877 allocated = _allocated;
2878
2879 constexpr qsizetype voidSize = sizeof(void*);
2880 qsizetype space_charAttributes = sizeof(QCharAttributes) * string.size() / voidSize + 1;
2881 qsizetype space_logClusters = sizeof(unsigned short) * string.size() / voidSize + 1;
2882 available_glyphs = (allocated - space_charAttributes - space_logClusters) * voidSize / QGlyphLayout::SpaceNeeded;
2883
2884 if (available_glyphs < str.size()) {
2885 // need to allocate on the heap
2886 allocated = 0;
2887
2888 memory_on_stack = false;
2889 memory = nullptr;
2890 logClustersPtr = nullptr;
2891 } else {
2892 memory_on_stack = true;
2893 memory = stack_memory;
2894 logClustersPtr = (unsigned short *)(memory + space_charAttributes);
2895
2896 void *m = memory + space_charAttributes + space_logClusters;
2897 glyphLayout = QGlyphLayout(reinterpret_cast<char *>(m), str.size());
2898 glyphLayout.clear();
2899 memset(memory, 0, space_charAttributes*sizeof(void *));
2900 }
2901 used = 0;
2902 hasBidi = false;
2903 layoutState = LayoutEmpty;
2904 haveCharAttributes = false;
2905 currentMaxWidth = 0;
2906}
2907
2908QTextEngine::LayoutData::~LayoutData()
2909{
2910 if (!memory_on_stack)
2911 free(memory);
2912 memory = nullptr;
2913}
2914
2915bool QTextEngine::LayoutData::reallocate(int totalGlyphs)
2916{
2917 Q_ASSERT(totalGlyphs >= glyphLayout.numGlyphs);
2918 if (memory_on_stack && available_glyphs >= totalGlyphs) {
2919 glyphLayout.grow(glyphLayout.data(), totalGlyphs);
2920 return true;
2921 }
2922
2923 const qsizetype space_charAttributes = (sizeof(QCharAttributes) * string.size() / sizeof(void*) + 1);
2924 const qsizetype space_logClusters = (sizeof(unsigned short) * string.size() / sizeof(void*) + 1);
2925 const qsizetype space_glyphs = qsizetype(totalGlyphs) * QGlyphLayout::SpaceNeeded / sizeof(void *) + 2;
2926
2927 const qsizetype newAllocated = space_charAttributes + space_glyphs + space_logClusters;
2928 // Check if the length of string/glyphs causes int overflow,
2929 // we can't layout such a long string all at once, so return false here to
2930 // indicate there is a failure
2931 if (size_t(space_charAttributes) > INT_MAX || size_t(space_logClusters) > INT_MAX || totalGlyphs < 0
2932 || size_t(space_glyphs) > INT_MAX || size_t(newAllocated) > INT_MAX || newAllocated < allocated) {
2933 layoutState = LayoutFailed;
2934 return false;
2935 }
2936
2937 void **newMem = (void **)::realloc(memory_on_stack ? nullptr : memory, newAllocated*sizeof(void *));
2938 if (!newMem) {
2939 layoutState = LayoutFailed;
2940 return false;
2941 }
2942 if (memory_on_stack)
2943 memcpy(newMem, memory, allocated*sizeof(void *));
2944 memory = newMem;
2945 memory_on_stack = false;
2946
2947 void **m = memory;
2948 m += space_charAttributes;
2949 logClustersPtr = (unsigned short *) m;
2950 m += space_logClusters;
2951
2952 const qsizetype space_preGlyphLayout = space_charAttributes + space_logClusters;
2953 if (allocated < space_preGlyphLayout)
2954 memset(memory + allocated, 0, (space_preGlyphLayout - allocated)*sizeof(void *));
2955
2956 glyphLayout.grow(reinterpret_cast<char *>(m), totalGlyphs);
2957
2958 allocated = newAllocated;
2959 return true;
2960}
2961
2963{
2964 Q_ASSERT(offsets != oldLayout->offsets);
2965
2966 int n = std::min(numGlyphs, oldLayout->numGlyphs);
2967
2968 memcpy(offsets, oldLayout->offsets, n * sizeof(QFixedPoint));
2969 memcpy(attributes, oldLayout->attributes, n * sizeof(QGlyphAttributes));
2970 memcpy(justifications, oldLayout->justifications, n * sizeof(QGlyphJustification));
2971 memcpy(advances, oldLayout->advances, n * sizeof(QFixed));
2972 memcpy(glyphs, oldLayout->glyphs, n * sizeof(glyph_t));
2973
2974 numGlyphs = n;
2975}
2976
2977// grow to the new size, copying the existing data to the new layout
2978void QGlyphLayout::grow(char *address, int totalGlyphs)
2979{
2980 QGlyphLayout oldLayout(address, numGlyphs);
2981 QGlyphLayout newLayout(address, totalGlyphs);
2982
2983 if (numGlyphs) {
2984 // move the existing data
2985 memmove(newLayout.attributes, oldLayout.attributes, numGlyphs * sizeof(QGlyphAttributes));
2986 memmove(newLayout.justifications, oldLayout.justifications, numGlyphs * sizeof(QGlyphJustification));
2987 memmove(newLayout.advances, oldLayout.advances, numGlyphs * sizeof(QFixed));
2988 memmove(newLayout.glyphs, oldLayout.glyphs, numGlyphs * sizeof(glyph_t));
2989 }
2990
2991 // clear the new data
2992 newLayout.clear(numGlyphs);
2993
2994 *this = newLayout;
2995}
2996
2997void QTextEngine::freeMemory()
2998{
2999 if (!stackEngine) {
3000 delete layoutData;
3001 layoutData = nullptr;
3002 } else {
3003 layoutData->used = 0;
3004 layoutData->hasBidi = false;
3005 layoutData->layoutState = LayoutEmpty;
3006 layoutData->haveCharAttributes = false;
3007 layoutData->currentMaxWidth = 0;
3008 layoutData->items.clear();
3009 }
3010 if (specialData)
3011 specialData->resolvedFormats.clear();
3012 for (int i = 0; i < lines.size(); ++i) {
3013 lines[i].justified = 0;
3014 lines[i].gridfitted = 0;
3015 }
3016}
3017
3018int QTextEngine::formatIndex(const QScriptItem *si) const
3019{
3020 if (specialData && !specialData->resolvedFormats.isEmpty()) {
3021 QTextFormatCollection *collection = formatCollection();
3022 Q_ASSERT(collection);
3023 return collection->indexForFormat(specialData->resolvedFormats.at(si - &layoutData->items.at(0)));
3024 }
3025
3026 const QTextDocumentPrivate *p = QTextDocumentPrivate::get(block);
3027 if (!p)
3028 return -1;
3029 int pos = si->position;
3030 if (specialData && si->position >= specialData->preeditPosition) {
3031 if (si->position < specialData->preeditPosition + specialData->preeditText.size())
3032 pos = qMax(qMin(block.length(), specialData->preeditPosition) - 1, 0);
3033 else
3034 pos -= specialData->preeditText.size();
3035 }
3036 QTextDocumentPrivate::FragmentIterator it = p->find(block.position() + pos);
3037 return it.value()->format;
3038}
3039
3040
3041QTextCharFormat QTextEngine::format(const QScriptItem *si) const
3042{
3043 if (const QTextFormatCollection *collection = formatCollection())
3044 return collection->charFormat(formatIndex(si));
3045 return QTextCharFormat();
3046}
3047
3048void QTextEngine::addRequiredBoundaries() const
3049{
3050 if (specialData) {
3051 for (int i = 0; i < specialData->formats.size(); ++i) {
3052 const QTextLayout::FormatRange &r = specialData->formats.at(i);
3053 setBoundary(r.start);
3054 setBoundary(r.start + r.length);
3055 //qDebug("adding boundaries %d %d", r.start, r.start+r.length);
3056 }
3057 }
3058}
3059
3060bool QTextEngine::atWordSeparator(int position) const
3061{
3062 const QChar c = layoutData->string.at(position);
3063 switch (c.unicode()) {
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 case '*':
3089 case '\'':
3090 case '"':
3091 case '`':
3092 case '~':
3093 case '|':
3094 case '\\':
3095 return true;
3096 default:
3097 break;
3098 }
3099 return false;
3100}
3101
3102void QTextEngine::setPreeditArea(int position, const QString &preeditText)
3103{
3104 if (preeditText.isEmpty()) {
3105 if (!specialData)
3106 return;
3107 if (specialData->formats.isEmpty()) {
3108 delete specialData;
3109 specialData = nullptr;
3110 } else {
3111 specialData->preeditText = QString();
3112 specialData->preeditPosition = -1;
3113 }
3114 } else {
3115 if (!specialData)
3116 specialData = new SpecialData;
3117 specialData->preeditPosition = position;
3118 specialData->preeditText = preeditText;
3119 }
3120 invalidate();
3121 clearLineData();
3122}
3123
3124void QTextEngine::setFormats(const QList<QTextLayout::FormatRange> &formats)
3125{
3126 if (formats.isEmpty()) {
3127 if (!specialData)
3128 return;
3129 if (specialData->preeditText.isEmpty()) {
3130 delete specialData;
3131 specialData = nullptr;
3132 } else {
3133 specialData->formats.clear();
3134 }
3135 } else {
3136 if (!specialData) {
3137 specialData = new SpecialData;
3138 specialData->preeditPosition = -1;
3139 }
3140 specialData->formats = formats;
3141 indexFormats();
3142 }
3143 invalidate();
3144 clearLineData();
3145}
3146
3147void QTextEngine::indexFormats()
3148{
3149 QTextFormatCollection *collection = formatCollection();
3150 if (!collection) {
3151 Q_ASSERT(QTextDocumentPrivate::get(block) == nullptr);
3152 specialData->formatCollection.reset(new QTextFormatCollection);
3153 collection = specialData->formatCollection.data();
3154 }
3155
3156 // replace with shared copies
3157 for (int i = 0; i < specialData->formats.size(); ++i) {
3158 QTextCharFormat &format = specialData->formats[i].format;
3159 format = collection->charFormat(collection->indexForFormat(format));
3160 }
3161}
3162
3163/* These two helper functions are used to determine whether we need to insert a ZWJ character
3164 between the text that gets truncated and the ellipsis. This is important to get
3165 correctly shaped results for arabic text.
3166*/
3167static inline bool nextCharJoins(const QString &string, int pos)
3168{
3169 while (pos < string.size() && string.at(pos).category() == QChar::Mark_NonSpacing)
3170 ++pos;
3171 if (pos == string.size())
3172 return false;
3173 QChar::JoiningType joining = string.at(pos).joiningType();
3174 return joining != QChar::Joining_None && joining != QChar::Joining_Transparent;
3175}
3176
3177static inline bool prevCharJoins(const QString &string, int pos)
3178{
3179 while (pos > 0 && string.at(pos - 1).category() == QChar::Mark_NonSpacing)
3180 --pos;
3181 if (pos == 0)
3182 return false;
3183 QChar::JoiningType joining = string.at(pos - 1).joiningType();
3184 return joining == QChar::Joining_Dual || joining == QChar::Joining_Causing;
3185}
3186
3187static constexpr bool isRetainableControlCode(char16_t c) noexcept
3188{
3189 return (c >= 0x202a && c <= 0x202e) // LRE, RLE, PDF, LRO, RLO
3190 || (c >= 0x200e && c <= 0x200f) // LRM, RLM
3191 || (c >= 0x2066 && c <= 0x2069); // LRI, RLI, FSI, PDI
3192}
3193
3194static QString stringMidRetainingBidiCC(const QString &string,
3195 const QString &ellidePrefix,
3196 const QString &ellideSuffix,
3197 int subStringFrom,
3198 int subStringTo,
3199 int midStart,
3200 int midLength)
3201{
3202 QString prefix;
3203 for (int i=subStringFrom; i<midStart; ++i) {
3204 char16_t c = string.at(i).unicode();
3206 prefix += c;
3207 }
3208
3209 QString suffix;
3210 for (int i=midStart + midLength; i<subStringTo; ++i) {
3211 char16_t c = string.at(i).unicode();
3213 suffix += c;
3214 }
3215
3216 return prefix + ellidePrefix + QStringView{string}.mid(midStart, midLength) + ellideSuffix + suffix;
3217}
3218
3219QString QTextEngine::elidedText(Qt::TextElideMode mode, QFixed width, int flags, int from, int count) const
3220{
3221// qDebug() << "elidedText; available width" << width.toReal() << "text width:" << this->width(0, layoutData->string.length()).toReal();
3222
3223 if (flags & Qt::TextShowMnemonic) {
3224 itemize();
3225 QCharAttributes *attributes = const_cast<QCharAttributes *>(this->attributes());
3226 if (!attributes)
3227 return QString();
3228 for (int i = 0; i < layoutData->items.size(); ++i) {
3229 const QScriptItem &si = layoutData->items.at(i);
3230 if (!si.num_glyphs)
3231 shape(i);
3232
3233 unsigned short *logClusters = this->logClusters(&si);
3234 QGlyphLayout glyphs = shapedGlyphs(&si);
3235
3236 const int end = si.position + length(&si);
3237 for (int i = si.position; i < end - 1; ++i) {
3238 if (layoutData->string.at(i) == u'&'
3239 && !attributes[i + 1].whiteSpace && attributes[i + 1].graphemeBoundary) {
3240 const int gp = logClusters[i - si.position];
3241 glyphs.attributes[gp].dontPrint = true;
3242 // emulate grapheme cluster
3243 attributes[i] = attributes[i + 1];
3244 memset(attributes + i + 1, 0, sizeof(QCharAttributes));
3245 if (layoutData->string.at(i + 1) == u'&')
3246 ++i;
3247 }
3248 }
3249 }
3250 }
3251
3252 validate();
3253
3254 const int to = count >= 0 && count <= layoutData->string.size() - from
3255 ? from + count
3256 : layoutData->string.size();
3257
3258 // The text after a hard line break cannot be appended to the requested range. If there is
3259 // such text, we need to elide, no matter how narrow the text is. Only ElideRight can express
3260 // that; for the other modes the ellipsis would not mark the missing lines below.
3261 const bool continuesAfterLineBreak = mode == Qt::ElideRight && to > from
3262 && to < layoutData->string.size()
3263 && layoutData->string.at(to - 1) == QChar::LineSeparator;
3264
3265 if (mode == Qt::ElideNone
3266 || (!continuesAfterLineBreak
3267 && (this->width(from, layoutData->string.size()) <= width || to - from <= 1))) {
3268 return layoutData->string.mid(from, from - to);
3269 }
3270
3271 QFixed ellipsisWidth;
3272 QString ellipsisText;
3273 {
3274 QFontEngine *engine = fnt.d->engineForScript(QChar::Script_Common);
3275
3276 constexpr char16_t ellipsisChar = u'\x2026';
3277
3278 // We only want to use the ellipsis character if it is from the main
3279 // font (not one of the fallbacks), since using a fallback font
3280 // will affect the metrics of the text, potentially causing it to shift
3281 // when it is being elided.
3282 if (engine->type() == QFontEngine::Multi) {
3283 QFontEngineMulti *multiEngine = static_cast<QFontEngineMulti *>(engine);
3284 multiEngine->ensureEngineAt(0);
3285 engine = multiEngine->engine(0);
3286 }
3287
3288 glyph_t glyph = engine->glyphIndex(ellipsisChar);
3289
3290 QGlyphLayout glyphs;
3291 glyphs.numGlyphs = 1;
3292 glyphs.glyphs = &glyph;
3293 glyphs.advances = &ellipsisWidth;
3294
3295 if (glyph != 0) {
3296 engine->recalcAdvances(&glyphs, { });
3297
3298 ellipsisText = ellipsisChar;
3299 } else {
3300 glyph = engine->glyphIndex('.');
3301 if (glyph != 0) {
3302 engine->recalcAdvances(&glyphs, { });
3303
3304 ellipsisWidth *= 3;
3305 ellipsisText = QStringLiteral("...");
3306 } else {
3307 engine = fnt.d->engineForScript(QChar::Script_Common);
3308 glyph = engine->glyphIndex(ellipsisChar);
3309 engine->recalcAdvances(&glyphs, { });
3310 ellipsisText = ellipsisChar;
3311 }
3312 }
3313 }
3314
3315 const QFixed availableWidth = width - ellipsisWidth;
3316 if (availableWidth < 0)
3317 return QString();
3318
3319 const QCharAttributes *attributes = this->attributes();
3320 if (!attributes)
3321 return QString();
3322
3323 constexpr char16_t ZWJ = u'\x200d'; // ZERO-WIDTH JOINER
3324
3325 if (mode == Qt::ElideRight) {
3326 QFixed currentWidth;
3327 int pos;
3328 int nextBreak = from;
3329
3330 do {
3331 pos = nextBreak;
3332
3333 ++nextBreak;
3334 while (nextBreak < layoutData->string.size() && !attributes[nextBreak].graphemeBoundary)
3335 ++nextBreak;
3336
3337 currentWidth += this->width(pos, nextBreak - pos);
3338 } while (nextBreak < to
3339 && currentWidth < availableWidth);
3340
3341 if (nextCharJoins(layoutData->string, pos))
3342 ellipsisText.prepend(ZWJ);
3343
3344 return stringMidRetainingBidiCC(layoutData->string,
3345 QString(), ellipsisText,
3346 from, to,
3347 from, pos - from);
3348 } else if (mode == Qt::ElideLeft) {
3349 QFixed currentWidth;
3350 int pos;
3351 int nextBreak = to;
3352
3353 do {
3354 pos = nextBreak;
3355
3356 --nextBreak;
3357 while (nextBreak > 0 && !attributes[nextBreak].graphemeBoundary)
3358 --nextBreak;
3359
3360 currentWidth += this->width(nextBreak, pos - nextBreak);
3361 } while (nextBreak > from
3362 && currentWidth < availableWidth);
3363
3364 if (prevCharJoins(layoutData->string, pos))
3365 ellipsisText.append(ZWJ);
3366
3367 return stringMidRetainingBidiCC(layoutData->string,
3368 ellipsisText, QString(),
3369 from, to,
3370 pos, to - pos);
3371 } else if (mode == Qt::ElideMiddle) {
3372 QFixed leftWidth;
3373 QFixed rightWidth;
3374
3375 int leftPos = from;
3376 int nextLeftBreak = from;
3377
3378 int rightPos = to;
3379 int nextRightBreak = to;
3380
3381 do {
3382 leftPos = nextLeftBreak;
3383 rightPos = nextRightBreak;
3384
3385 ++nextLeftBreak;
3386 while (nextLeftBreak < layoutData->string.size() && !attributes[nextLeftBreak].graphemeBoundary)
3387 ++nextLeftBreak;
3388
3389 --nextRightBreak;
3390 while (nextRightBreak > from && !attributes[nextRightBreak].graphemeBoundary)
3391 --nextRightBreak;
3392
3393 leftWidth += this->width(leftPos, nextLeftBreak - leftPos);
3394 rightWidth += this->width(nextRightBreak, rightPos - nextRightBreak);
3395 } while (nextLeftBreak < to
3396 && nextRightBreak > from
3397 && leftWidth + rightWidth < availableWidth);
3398
3399 if (nextCharJoins(layoutData->string, leftPos))
3400 ellipsisText.prepend(ZWJ);
3401 if (prevCharJoins(layoutData->string, rightPos))
3402 ellipsisText.append(ZWJ);
3403
3404 return QStringView{layoutData->string}.mid(from, leftPos - from) + ellipsisText + QStringView{layoutData->string}.mid(rightPos, to - rightPos);
3405 }
3406
3407 return layoutData->string.mid(from, to - from);
3408}
3409
3410void QTextEngine::setBoundary(int strPos) const
3411{
3412 const int item = findItem(strPos);
3413 if (item < 0)
3414 return;
3415
3416 QScriptItem newItem = layoutData->items.at(item);
3417 if (newItem.position != strPos) {
3418 newItem.position = strPos;
3419 layoutData->items.insert(item + 1, newItem);
3420 }
3421}
3422
3423QFixed QTextEngine::calculateTabWidth(int item, QFixed x) const
3424{
3425 const QScriptItem &si = layoutData->items.at(item);
3426
3427 QFixed dpiScale = 1;
3428 if (QTextDocumentPrivate::get(block) != nullptr && QTextDocumentPrivate::get(block)->layout() != nullptr) {
3429 QPaintDevice *pdev = QTextDocumentPrivate::get(block)->layout()->paintDevice();
3430 if (pdev)
3431 dpiScale = QFixed::fromReal(pdev->logicalDpiY() / qreal(qt_defaultDpiY()));
3432 } else {
3433 dpiScale = QFixed::fromReal(fnt.d->dpi / qreal(qt_defaultDpiY()));
3434 }
3435
3436 QList<QTextOption::Tab> tabArray = option.tabs();
3437 if (!tabArray.isEmpty()) {
3438 if (isRightToLeft()) { // rebase the tabArray positions.
3439 auto isLeftOrRightTab = [](const QTextOption::Tab &tab) {
3440 return tab.type == QTextOption::LeftTab || tab.type == QTextOption::RightTab;
3441 };
3442 const auto cbegin = tabArray.cbegin();
3443 const auto cend = tabArray.cend();
3444 const auto cit = std::find_if(cbegin, cend, isLeftOrRightTab);
3445 if (cit != cend) {
3446 const int index = std::distance(cbegin, cit);
3447 auto iter = tabArray.begin() + index;
3448 const auto end = tabArray.end();
3449 while (iter != end) {
3450 QTextOption::Tab &tab = *iter;
3451 if (tab.type == QTextOption::LeftTab)
3452 tab.type = QTextOption::RightTab;
3453 else if (tab.type == QTextOption::RightTab)
3454 tab.type = QTextOption::LeftTab;
3455 ++iter;
3456 }
3457 }
3458 }
3459 for (const QTextOption::Tab &tabSpec : std::as_const(tabArray)) {
3460 QFixed tab = QFixed::fromReal(tabSpec.position) * dpiScale;
3461 if (tab > x) { // this is the tab we need.
3462 int tabSectionEnd = layoutData->string.size();
3463 if (tabSpec.type == QTextOption::RightTab || tabSpec.type == QTextOption::CenterTab) {
3464 // find next tab to calculate the width required.
3465 tab = QFixed::fromReal(tabSpec.position);
3466 for (int i=item + 1; i < layoutData->items.size(); i++) {
3467 const QScriptItem &item = layoutData->items.at(i);
3468 if (item.analysis.flags == QScriptAnalysis::TabOrObject) { // found it.
3469 tabSectionEnd = item.position;
3470 break;
3471 }
3472 }
3473 }
3474 else if (tabSpec.type == QTextOption::DelimiterTab)
3475 // find delimiter character to calculate the width required
3476 tabSectionEnd = qMax(si.position, layoutData->string.indexOf(tabSpec.delimiter, si.position) + 1);
3477
3478 if (tabSectionEnd > si.position) {
3479 QFixed length;
3480 // Calculate the length of text between this tab and the tabSectionEnd
3481 for (int i=item; i < layoutData->items.size(); i++) {
3482 const QScriptItem &item = layoutData->items.at(i);
3483 if (item.position > tabSectionEnd || item.position <= si.position)
3484 continue;
3485 shape(i); // first, lets make sure relevant text is already shaped
3486 if (item.analysis.flags == QScriptAnalysis::Object) {
3487 length += item.width;
3488 continue;
3489 }
3490 QGlyphLayout glyphs = this->shapedGlyphs(&item);
3491 const int end = qMin(item.position + item.num_glyphs, tabSectionEnd) - item.position;
3492 for (int i=0; i < end; i++)
3493 length += glyphs.advances[i] * !glyphs.attributes[i].dontPrint;
3494 if (end + item.position == tabSectionEnd && tabSpec.type == QTextOption::DelimiterTab) // remove half of matching char
3495 length -= glyphs.advances[end] / 2 * !glyphs.attributes[end].dontPrint;
3496 }
3497
3498 switch (tabSpec.type) {
3499 case QTextOption::CenterTab:
3500 length /= 2;
3501 Q_FALLTHROUGH();
3502 case QTextOption::DelimiterTab:
3503 case QTextOption::RightTab:
3504 tab = QFixed::fromReal(tabSpec.position) * dpiScale - length;
3505 if (tab < x) // default to tab taking no space
3506 return QFixed();
3507 break;
3508 case QTextOption::LeftTab:
3509 break;
3510 }
3511 }
3512 return tab - x;
3513 }
3514 }
3515 }
3516 QFixed tab = QFixed::fromReal(option.tabStopDistance());
3517 if (tab <= 0)
3518 tab = 80; // default
3519 tab *= dpiScale;
3520 QFixed nextTabPos = ((x / tab).truncate() + 1) * tab;
3521 QFixed tabWidth = nextTabPos - x;
3522
3523 return tabWidth;
3524}
3525
3526namespace {
3527class FormatRangeComparatorByStart {
3528 const QList<QTextLayout::FormatRange> &list;
3529public:
3530 FormatRangeComparatorByStart(const QList<QTextLayout::FormatRange> &list) : list(list) { }
3531 bool operator()(int a, int b) {
3532 return list.at(a).start < list.at(b).start;
3533 }
3534};
3535class FormatRangeComparatorByEnd {
3536 const QList<QTextLayout::FormatRange> &list;
3537public:
3538 FormatRangeComparatorByEnd(const QList<QTextLayout::FormatRange> &list) : list(list) { }
3539 bool operator()(int a, int b) {
3540 return list.at(a).start + list.at(a).length < list.at(b).start + list.at(b).length;
3541 }
3542};
3543}
3544
3545void QTextEngine::resolveFormats() const
3546{
3547 if (!specialData || specialData->formats.isEmpty())
3548 return;
3549 Q_ASSERT(specialData->resolvedFormats.isEmpty());
3550
3551 QTextFormatCollection *collection = formatCollection();
3552
3553 QList<QTextCharFormat> resolvedFormats(layoutData->items.size());
3554
3555 QVarLengthArray<int, 64> formatsSortedByStart;
3556 formatsSortedByStart.reserve(specialData->formats.size());
3557 for (int i = 0; i < specialData->formats.size(); ++i) {
3558 if (specialData->formats.at(i).length >= 0)
3559 formatsSortedByStart.append(i);
3560 }
3561 QVarLengthArray<int, 64> formatsSortedByEnd = formatsSortedByStart;
3562 std::sort(formatsSortedByStart.begin(), formatsSortedByStart.end(),
3563 FormatRangeComparatorByStart(specialData->formats));
3564 std::sort(formatsSortedByEnd.begin(), formatsSortedByEnd.end(),
3565 FormatRangeComparatorByEnd(specialData->formats));
3566
3567 QVarLengthArray<int, 16> currentFormats;
3568 const int *startIt = formatsSortedByStart.constBegin();
3569 const int *endIt = formatsSortedByEnd.constBegin();
3570
3571 for (int i = 0; i < layoutData->items.size(); ++i) {
3572 const QScriptItem *si = &layoutData->items.at(i);
3573 int end = si->position + length(si);
3574
3575 while (startIt != formatsSortedByStart.constEnd() &&
3576 specialData->formats.at(*startIt).start <= si->position) {
3577 currentFormats.insert(std::upper_bound(currentFormats.begin(), currentFormats.end(), *startIt),
3578 *startIt);
3579 ++startIt;
3580 }
3581 while (endIt != formatsSortedByEnd.constEnd() &&
3582 specialData->formats.at(*endIt).start + specialData->formats.at(*endIt).length < end) {
3583 int *currentFormatIterator = std::lower_bound(currentFormats.begin(), currentFormats.end(), *endIt);
3584 if (*endIt < *currentFormatIterator)
3585 currentFormatIterator = currentFormats.end();
3586 currentFormats.remove(currentFormatIterator - currentFormats.begin());
3587 ++endIt;
3588 }
3589
3590 QTextCharFormat &format = resolvedFormats[i];
3591 if (QTextDocumentPrivate::get(block) != nullptr) {
3592 // when we have a QTextDocumentPrivate, formatIndex might still return a valid index based
3593 // on the preeditPosition. for all other cases, we cleared the resolved format indices
3594 format = collection->charFormat(formatIndex(si));
3595 }
3596 if (!currentFormats.isEmpty()) {
3597 for (int cur : currentFormats) {
3598 const QTextLayout::FormatRange &range = specialData->formats.at(cur);
3599 Q_ASSERT(range.start <= si->position && range.start + range.length >= end);
3600 format.merge(range.format);
3601 }
3602 format = collection->charFormat(collection->indexForFormat(format)); // get shared copy
3603 }
3604 }
3605
3606 specialData->resolvedFormats = resolvedFormats;
3607}
3608
3609QFixed QTextEngine::leadingSpaceWidth(const QScriptLine &line)
3610{
3611 if (!line.hasTrailingSpaces
3612 || (option.flags() & QTextOption::IncludeTrailingSpaces)
3613 || !isRightToLeft())
3614 return QFixed();
3615
3616 return width(line.from + line.length, line.trailingSpaces);
3617}
3618
3619QFixed QTextEngine::alignLine(const QScriptLine &line)
3620{
3621 QFixed x = 0;
3622 justify(line);
3623 // if width is QFIXED_MAX that means we used setNumColumns() and that implicitly makes this line left aligned.
3624 if (!line.justified && line.width != QFIXED_MAX) {
3625 int align = option.alignment();
3626 if (align & Qt::AlignJustify && isRightToLeft())
3627 align = Qt::AlignRight;
3628 if (align & Qt::AlignRight)
3629 x = line.width - (line.textAdvance);
3630 else if (align & Qt::AlignHCenter)
3631 x = (line.width - line.textAdvance)/2;
3632 }
3633 return x;
3634}
3635
3636QFixed QTextEngine::offsetInLigature(const QScriptItem *si, int pos, int max, int glyph_pos)
3637{
3638 unsigned short *logClusters = this->logClusters(si);
3639 const QGlyphLayout &glyphs = shapedGlyphs(si);
3640
3641 int offsetInCluster = 0;
3642 for (int i = pos - 1; i >= 0; i--) {
3643 if (logClusters[i] == glyph_pos)
3644 offsetInCluster++;
3645 else
3646 break;
3647 }
3648
3649 // in the case that the offset is inside a (multi-character) glyph,
3650 // interpolate the position.
3651 if (offsetInCluster > 0) {
3652 int clusterLength = 0;
3653 for (int i = pos - offsetInCluster; i < max; i++) {
3654 if (logClusters[i] == glyph_pos)
3655 clusterLength++;
3656 else
3657 break;
3658 }
3659 if (clusterLength)
3660 return glyphs.advances[glyph_pos] * offsetInCluster / clusterLength;
3661 }
3662
3663 return 0;
3664}
3665
3666// Scan in logClusters[from..to-1] for glyph_pos
3667int QTextEngine::getClusterLength(unsigned short *logClusters,
3668 const QCharAttributes *attributes,
3669 int from, int to, int glyph_pos, int *start)
3670{
3671 int clusterLength = 0;
3672 for (int i = from; i < to; i++) {
3673 if (logClusters[i] == glyph_pos && attributes[i].graphemeBoundary) {
3674 if (*start < 0)
3675 *start = i;
3676 clusterLength++;
3677 }
3678 else if (clusterLength)
3679 break;
3680 }
3681 return clusterLength;
3682}
3683
3684int QTextEngine::positionInLigature(const QScriptItem *si, int end,
3685 QFixed x, QFixed edge, int glyph_pos,
3686 bool cursorOnCharacter)
3687{
3688 unsigned short *logClusters = this->logClusters(si);
3689 int clusterStart = -1;
3690 int clusterLength = 0;
3691
3692 if (si->analysis.script != QChar::Script_Common &&
3693 si->analysis.script != QChar::Script_Greek &&
3694 si->analysis.script != QChar::Script_Latin &&
3695 si->analysis.script != QChar::Script_Hiragana &&
3696 si->analysis.script != QChar::Script_Katakana &&
3697 si->analysis.script != QChar::Script_Bopomofo &&
3698 si->analysis.script != QChar::Script_Han) {
3699 if (glyph_pos == -1)
3700 return si->position + end;
3701 else {
3702 int i;
3703 for (i = 0; i < end; i++)
3704 if (logClusters[i] == glyph_pos)
3705 break;
3706 return si->position + i;
3707 }
3708 }
3709
3710 const bool rightToLeft = si->analysis.bidiLevel % 2;
3711 if (glyph_pos == -1 && end > 0) {
3712 glyph_pos = logClusters[end - 1];
3713 } else {
3714 // If on border, snap to left-most glyph
3715 if (rightToLeft ? x > edge : x <= edge)
3716 glyph_pos--;
3717 }
3718
3719 const QCharAttributes *attrs = attributes() + si->position;
3720 logClusters = this->logClusters(si);
3721 clusterLength = getClusterLength(logClusters, attrs, 0, end, glyph_pos, &clusterStart);
3722
3723 if (clusterLength) {
3724 const QGlyphLayout &glyphs = shapedGlyphs(si);
3725 QFixed glyphWidth = glyphs.effectiveAdvance(glyph_pos);
3726 // the approximate width of each individual element of the ligature
3727 QFixed perItemWidth = glyphWidth / clusterLength;
3728 if (perItemWidth <= 0)
3729 return si->position + clusterStart;
3730 QFixed left = x > edge ? edge : edge - glyphWidth;
3731 int n = ((x - left) / perItemWidth).floor().toInt();
3732 QFixed dist = x - left - n * perItemWidth;
3733 int closestItem = dist > (perItemWidth / 2) ? n + 1 : n;
3734 // In right-to-left items, the first character of the cluster is on the right
3735 if (rightToLeft)
3736 closestItem = clusterLength - closestItem;
3737 // x should be within the glyph, but make sure we never go past the boundaries
3738 // of the cluster (0 is before its first character, clusterLength after its last)
3739 closestItem = std::clamp(closestItem, 0, clusterLength);
3740 if (cursorOnCharacter && closestItem > 0)
3741 closestItem--;
3742 int pos = clusterStart + closestItem;
3743 // Jump to the next grapheme boundary
3744 while (pos < end && !attrs[pos].graphemeBoundary)
3745 pos++;
3746 return si->position + pos;
3747 }
3748 return si->position + end;
3749}
3750
3751int QTextEngine::previousLogicalPosition(int oldPos) const
3752{
3753 const QCharAttributes *attrs = attributes();
3754 int len = block.isValid() ? block.length() - 1
3755 : layoutData->string.size();
3756 Q_ASSERT(len <= layoutData->string.size());
3757 if (!attrs || oldPos <= 0 || oldPos > len)
3758 return oldPos;
3759
3760 oldPos--;
3761 while (oldPos && !attrs[oldPos].graphemeBoundary)
3762 oldPos--;
3763 return oldPos;
3764}
3765
3766int QTextEngine::nextLogicalPosition(int oldPos) const
3767{
3768 const QCharAttributes *attrs = attributes();
3769 int len = block.isValid() ? block.length() - 1
3770 : layoutData->string.size();
3771 Q_ASSERT(len <= layoutData->string.size());
3772 if (!attrs || oldPos < 0 || oldPos >= len)
3773 return oldPos;
3774
3775 oldPos++;
3776 while (oldPos < len && !attrs[oldPos].graphemeBoundary)
3777 oldPos++;
3778 return oldPos;
3779}
3780
3781int QTextEngine::lineNumberForTextPosition(int pos)
3782{
3783 if (!layoutData)
3784 itemize();
3785 if (pos == layoutData->string.size() && lines.size())
3786 return lines.size() - 1;
3787 for (int i = 0; i < lines.size(); ++i) {
3788 const QScriptLine& line = lines[i];
3789 if (line.from + line.length + line.trailingSpaces > pos)
3790 return i;
3791 }
3792 return -1;
3793}
3794
3795std::vector<int> QTextEngine::insertionPointsForLine(int lineNum)
3796{
3797 QTextLineItemIterator iterator(this, lineNum);
3798
3799 std::vector<int> insertionPoints;
3800 insertionPoints.reserve(size_t(iterator.line.length));
3801
3802 bool lastLine = lineNum >= lines.size() - 1;
3803
3804 while (!iterator.atEnd()) {
3805 const QScriptItem &si = iterator.next();
3806
3807 int end = iterator.itemEnd;
3808 if (lastLine && iterator.item == iterator.lastItem)
3809 ++end; // the last item in the last line -> insert eol position
3810 if (si.analysis.bidiLevel % 2) {
3811 for (int i = end - 1; i >= iterator.itemStart; --i)
3812 insertionPoints.push_back(i);
3813 } else {
3814 for (int i = iterator.itemStart; i < end; ++i)
3815 insertionPoints.push_back(i);
3816 }
3817 }
3818 return insertionPoints;
3819}
3820
3821int QTextEngine::endOfLine(int lineNum)
3822{
3823 const auto insertionPoints = insertionPointsForLine(lineNum);
3824 if (insertionPoints.size() > 0)
3825 return insertionPoints.back();
3826 return 0;
3827}
3828
3829int QTextEngine::beginningOfLine(int lineNum)
3830{
3831 const auto insertionPoints = insertionPointsForLine(lineNum);
3832 if (insertionPoints.size() > 0)
3833 return insertionPoints.front();
3834 return 0;
3835}
3836
3837int QTextEngine::positionAfterVisualMovement(int pos, QTextCursor::MoveOperation op)
3838{
3839 itemize();
3840
3841 bool moveRight = (op == QTextCursor::Right);
3842 bool alignRight = isRightToLeft();
3843 if (!layoutData->hasBidi)
3844 return moveRight ^ alignRight ? nextLogicalPosition(pos) : previousLogicalPosition(pos);
3845
3846 int lineNum = lineNumberForTextPosition(pos);
3847 if (lineNum < 0)
3848 return pos;
3849
3850 const auto insertionPoints = insertionPointsForLine(lineNum);
3851 for (size_t i = 0, max = insertionPoints.size(); i < max; ++i)
3852 if (pos == insertionPoints[i]) {
3853 if (moveRight) {
3854 if (i + 1 < max)
3855 return insertionPoints[i + 1];
3856 } else {
3857 if (i > 0)
3858 return insertionPoints[i - 1];
3859 }
3860
3861 if (moveRight ^ alignRight) {
3862 if (lineNum + 1 < lines.size())
3863 return alignRight ? endOfLine(lineNum + 1) : beginningOfLine(lineNum + 1);
3864 }
3865 else {
3866 if (lineNum > 0)
3867 return alignRight ? beginningOfLine(lineNum - 1) : endOfLine(lineNum - 1);
3868 }
3869
3870 break;
3871 }
3872
3873 return pos;
3874}
3875
3876void QTextEngine::addItemDecoration(QPainter *painter, const QLineF &line, ItemDecorationList *decorationList)
3877{
3878 if (delayDecorations) {
3879 decorationList->append(ItemDecoration(line.x1(), line.x2(), line.y1(), painter->pen()));
3880 } else {
3881 painter->drawLine(line);
3882 }
3883}
3884
3885void QTextEngine::addUnderline(QPainter *painter, const QLineF &line)
3886{
3887 // qDebug() << "Adding underline:" << line;
3888 addItemDecoration(painter, line, &underlineList);
3889}
3890
3891void QTextEngine::addStrikeOut(QPainter *painter, const QLineF &line)
3892{
3893 addItemDecoration(painter, line, &strikeOutList);
3894}
3895
3896void QTextEngine::addOverline(QPainter *painter, const QLineF &line)
3897{
3898 addItemDecoration(painter, line, &overlineList);
3899}
3900
3901void QTextEngine::drawItemDecorationList(QPainter *painter, const ItemDecorationList &decorationList)
3902{
3903 // qDebug() << "Drawing" << decorationList.size() << "decorations";
3904 if (decorationList.isEmpty())
3905 return;
3906
3907 for (const ItemDecoration &decoration : decorationList) {
3908 painter->setPen(decoration.pen);
3909 painter->drawLine(QLineF(decoration.x1, decoration.y, decoration.x2, decoration.y));
3910 }
3911}
3912
3913void QTextEngine::drawDecorations(QPainter *painter)
3914{
3915 QPen oldPen = painter->pen();
3916
3917 adjustUnderlines();
3918 drawItemDecorationList(painter, underlineList);
3919 drawItemDecorationList(painter, strikeOutList);
3920 drawItemDecorationList(painter, overlineList);
3921
3922 clearDecorations();
3923
3924 painter->setPen(oldPen);
3925}
3926
3927void QTextEngine::clearDecorations()
3928{
3929 underlineList.clear();
3930 strikeOutList.clear();
3931 overlineList.clear();
3932}
3933
3934void QTextEngine::adjustUnderlines()
3935{
3936 // qDebug() << __PRETTY_FUNCTION__ << underlineList.count() << "underlines";
3937 if (underlineList.isEmpty())
3938 return;
3939
3940 ItemDecorationList::iterator start = underlineList.begin();
3941 ItemDecorationList::iterator end = underlineList.end();
3942 ItemDecorationList::iterator it = start;
3943 qreal underlinePos = start->y;
3944 qreal penWidth = start->pen.widthF();
3945 qreal lastLineEnd = start->x1;
3946
3947 while (it != end) {
3948 if (qFuzzyCompare(lastLineEnd, it->x1)) { // no gap between underlines
3949 underlinePos = qMax(underlinePos, it->y);
3950 penWidth = qMax(penWidth, it->pen.widthF());
3951 } else { // gap between this and the last underline
3952 adjustUnderlines(start, it, underlinePos, penWidth);
3953 start = it;
3954 underlinePos = start->y;
3955 penWidth = start->pen.widthF();
3956 }
3957 lastLineEnd = it->x2;
3958 ++it;
3959 }
3960
3961 adjustUnderlines(start, end, underlinePos, penWidth);
3962}
3963
3964void QTextEngine::adjustUnderlines(ItemDecorationList::iterator start,
3965 ItemDecorationList::iterator end,
3966 qreal underlinePos, qreal penWidth)
3967{
3968 for (ItemDecorationList::iterator it = start; it != end; ++it) {
3969 it->y = underlinePos;
3970 it->pen.setWidthF(penWidth);
3971 }
3972}
3973
3974QStackTextEngine::QStackTextEngine(const QString &string, const QFont &f)
3975 : QTextEngine(string, f),
3976 _layoutData(string, _memory, MemSize)
3977{
3978 stackEngine = true;
3979 layoutData = &_layoutData;
3980}
3981
3982QTextItemInt::QTextItemInt(const QScriptItem &si, QFont *font, const QTextCharFormat &format)
3983 : charFormat(format),
3984 f(font),
3985 fontEngine(font->d->engineForScript(si.analysis.script))
3986{
3987 Q_ASSERT(fontEngine);
3988
3990}
3991
3992QTextItemInt::QTextItemInt(const QGlyphLayout &g, QFont *font, const QChar *chars_, int numChars, QFontEngine *fe, const QTextCharFormat &format)
3993 : charFormat(format),
3994 num_chars(numChars),
3995 chars(chars_),
3996 f(font),
3997 glyphs(g),
3998 fontEngine(fe)
3999{
4000}
4001
4002// Fix up flags and underlineStyle with given info
4004{
4005 // explicitly initialize flags so that initFontAttributes can be called
4006 // multiple times on the same TextItem
4007 flags = { };
4008 if (si.analysis.bidiLevel %2)
4009 flags |= QTextItem::RightToLeft;
4010 ascent = si.ascent;
4011 descent = si.descent;
4012
4013 if (charFormat.hasProperty(QTextFormat::TextUnderlineStyle)) {
4014 underlineStyle = charFormat.underlineStyle();
4015 } else if (charFormat.boolProperty(QTextFormat::FontUnderline)
4016 || f->d->underline) {
4017 underlineStyle = QTextCharFormat::SingleUnderline;
4018 }
4019
4020 // compat
4021 if (underlineStyle == QTextCharFormat::SingleUnderline)
4022 flags |= QTextItem::Underline;
4023
4024 if (f->d->overline || charFormat.fontOverline())
4025 flags |= QTextItem::Overline;
4026 if (f->d->strikeOut || charFormat.fontStrikeOut())
4027 flags |= QTextItem::StrikeOut;
4028}
4029
4030QTextItemInt QTextItemInt::midItem(QFontEngine *fontEngine, int firstGlyphIndex, int numGlyphs) const
4031{
4032 QTextItemInt ti = *this;
4033 const int end = firstGlyphIndex + numGlyphs;
4034 ti.glyphs = glyphs.mid(firstGlyphIndex, numGlyphs);
4035 ti.fontEngine = fontEngine;
4036
4037 if (logClusters && chars) {
4038 const int logClusterOffset = logClusters[0];
4039 while (logClusters[ti.chars - chars] - logClusterOffset < firstGlyphIndex)
4040 ++ti.chars;
4041
4042 ti.logClusters += (ti.chars - chars);
4043
4044 ti.num_chars = 0;
4045 int char_start = ti.chars - chars;
4046 while (char_start + ti.num_chars < num_chars && ti.logClusters[ti.num_chars] - logClusterOffset < end)
4047 ++ti.num_chars;
4048 }
4049 return ti;
4050}
4051
4052
4053QTransform qt_true_matrix(qreal w, qreal h, const QTransform &x)
4054{
4055 QRectF rect = x.mapRect(QRectF(0, 0, w, h));
4056 return x * QTransform::fromTranslate(-rect.x(), -rect.y());
4057}
4058
4059
4060glyph_metrics_t glyph_metrics_t::transformed(const QTransform &matrix) const
4061{
4062 if (matrix.type() < QTransform::TxTranslate)
4063 return *this;
4064
4065 glyph_metrics_t m = *this;
4066
4067 qreal w = width.toReal();
4068 qreal h = height.toReal();
4069 QTransform xform = qt_true_matrix(w, h, matrix);
4070
4071 QRectF rect(0, 0, w, h);
4072 rect = xform.mapRect(rect);
4073 m.width = QFixed::fromReal(rect.width());
4074 m.height = QFixed::fromReal(rect.height());
4075
4076 QLineF l = xform.map(QLineF(x.toReal(), y.toReal(), xoff.toReal(), yoff.toReal()));
4077
4078 m.x = QFixed::fromReal(l.x1());
4079 m.y = QFixed::fromReal(l.y1());
4080
4081 // The offset is relative to the baseline which is why we use dx/dy of the line
4082 m.xoff = QFixed::fromReal(l.dx());
4083 m.yoff = QFixed::fromReal(l.dy());
4084
4085 return m;
4086}
4087
4088QTextLineItemIterator::QTextLineItemIterator(QTextEngine *_eng, int _lineNum, const QPointF &pos,
4089 const QTextLayout::FormatRange *_selection)
4090 : eng(_eng),
4091 line(eng->lines[_lineNum]),
4092 si(nullptr),
4093 lineNum(_lineNum),
4094 lineEnd(line.from + line.length),
4095 firstItem(eng->findItem(line.from)),
4096 lastItem(eng->findItem(lineEnd - 1, firstItem)),
4097 nItems((firstItem >= 0 && lastItem >= firstItem)? (lastItem-firstItem+1) : 0),
4098 logicalItem(-1),
4099 item(-1),
4100 visualOrder(nItems),
4101 selection(_selection)
4102{
4103 x = QFixed::fromReal(pos.x());
4104
4105 x += line.x;
4106
4107 x += eng->alignLine(line);
4108
4109 if (nItems > 0) {
4110 QVarLengthArray<uchar> levels(nItems);
4111 for (int i = 0; i < nItems; ++i)
4112 levels[i] = eng->layoutData->items.at(i + firstItem).analysis.bidiLevel;
4113 QTextEngine::bidiReorder(nItems, levels.data(), visualOrder.data());
4114 }
4115
4116 eng->shapeLine(line);
4117}
4118
4120{
4121 x += itemWidth;
4122
4123 ++logicalItem;
4124 item = visualOrder[logicalItem] + firstItem;
4125 itemLength = eng->length(item);
4126 si = &eng->layoutData->items[item];
4127 if (!si->num_glyphs)
4128 eng->shape(item);
4129
4130 itemStart = qMax(line.from, si->position);
4132
4133 if (si->analysis.flags >= QScriptAnalysis::TabOrObject) {
4134 glyphsStart = 0;
4135 glyphsEnd = 1;
4136 itemWidth = si->width;
4137 return *si;
4138 }
4139
4140 unsigned short *logClusters = eng->logClusters(si);
4141 QGlyphLayout glyphs = eng->shapedGlyphs(si);
4142
4143 glyphsStart = logClusters[itemStart - si->position];
4145
4146 // show soft-hyphen at line-break
4147 if (si->position + itemLength >= lineEnd
4148 && eng->layoutData->string.at(lineEnd - 1).unicode() == QChar::SoftHyphen)
4149 glyphs.attributes[glyphsEnd - 1].dontPrint = false;
4150
4151 itemWidth = 0;
4152 for (int g = glyphsStart; g < glyphsEnd; ++g)
4153 itemWidth += glyphs.effectiveAdvance(g);
4154
4155 return *si;
4156}
4157
4158bool QTextLineItemIterator::getSelectionBounds(QFixed *selectionX, QFixed *selectionWidth) const
4159{
4160 *selectionX = *selectionWidth = 0;
4161
4162 if (!selection)
4163 return false;
4164
4165 if (si->analysis.flags >= QScriptAnalysis::TabOrObject) {
4166 if (si->position >= selection->start + selection->length
4167 || si->position + itemLength <= selection->start)
4168 return false;
4169
4170 *selectionX = x;
4171 *selectionWidth = itemWidth;
4172 } else {
4173 unsigned short *logClusters = eng->logClusters(si);
4174 QGlyphLayout glyphs = eng->shapedGlyphs(si);
4175
4176 int from = qMax(itemStart, selection->start) - si->position;
4177 int to = qMin(itemEnd, selection->start + selection->length) - si->position;
4178 if (from >= to)
4179 return false;
4180
4181 int start_glyph = logClusters[from];
4182 int end_glyph = (to == itemLength) ? si->num_glyphs : logClusters[to];
4183 QFixed soff;
4184 QFixed swidth;
4185 if (si->analysis.bidiLevel %2) {
4186 for (int g = glyphsEnd - 1; g >= end_glyph; --g)
4187 soff += glyphs.effectiveAdvance(g);
4188 for (int g = end_glyph - 1; g >= start_glyph; --g)
4189 swidth += glyphs.effectiveAdvance(g);
4190 } else {
4191 for (int g = glyphsStart; g < start_glyph; ++g)
4192 soff += glyphs.effectiveAdvance(g);
4193 for (int g = start_glyph; g < end_glyph; ++g)
4194 swidth += glyphs.effectiveAdvance(g);
4195 }
4196
4197 // If the starting character is in the middle of a ligature,
4198 // selection should only contain the right part of that ligature
4199 // glyph, so we need to get the width of the left part here and
4200 // add it to *selectionX
4201 QFixed leftOffsetInLigature = eng->offsetInLigature(si, from, to, start_glyph);
4202 *selectionX = x + soff + leftOffsetInLigature;
4203 *selectionWidth = swidth - leftOffsetInLigature;
4204 // If the ending character is also part of a ligature, swidth does
4205 // not contain that part yet, we also need to find out the width of
4206 // that left part
4207 *selectionWidth += eng->offsetInLigature(si, to, itemLength, end_glyph);
4208 }
4209 return true;
4210}
4211
4212QT_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:1859
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