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