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