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