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 QHash<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 QHash<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 while (last_cluster++ < cluster && str_pos < item_length)
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 glyph_metrics_t m = fe->tightBoundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
2372 gm.x = qMin(gm.x, m.x + gm.xoff);
2373 gm.y = qMin(gm.y, m.y + gm.yoff);
2374 gm.width = qMax(gm.width, m.width + gm.xoff);
2375 gm.height = qMax(gm.height, m.height + gm.yoff);
2376 gm.xoff += m.xoff;
2377 gm.yoff += m.yoff;
2378 }
2379 });
2380 return gm;
2381}
2382
2383QFont QTextEngine::font(const QScriptItem &si) const
2384{
2385 QFont font = fnt;
2386 if (hasFormats()) {
2387 QTextCharFormat f = format(&si);
2388 font = f.font();
2389
2390 const QTextDocumentPrivate *document_d = QTextDocumentPrivate::get(block);
2391 if (document_d != nullptr && document_d->layout() != nullptr) {
2392 // Make sure we get the right dpi on printers
2393 QPaintDevice *pdev = document_d->layout()->paintDevice();
2394 if (pdev)
2395 font = QFont(font, pdev);
2396 } else {
2397 font = font.resolve(fnt);
2398 }
2399 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
2400 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
2401 if (font.pointSize() != -1)
2402 font.setPointSize((font.pointSize() * 2) / 3);
2403 else
2404 font.setPixelSize((font.pixelSize() * 2) / 3);
2405 }
2406 }
2407
2408 if (si.analysis.flags == QScriptAnalysis::SmallCaps)
2409 font = font.d->smallCapsFont();
2410
2411 return font;
2412}
2413
2414QTextEngine::FontEngineCache::FontEngineCache()
2415{
2416 reset();
2417}
2418
2419//we cache the previous results of this function, as calling it numerous times with the same effective
2420//input is common (and hard to cache at a higher level)
2421QFontEngine *QTextEngine::fontEngine(const QScriptItem &si, QFixed *ascent, QFixed *descent, QFixed *leading) const
2422{
2423 QFontEngine *engine = nullptr;
2424 QFontEngine *scaledEngine = nullptr;
2425 int script = si.analysis.script;
2426
2427 QFont font = fnt;
2428#ifndef QT_NO_RAWFONT
2429 if (useRawFont && rawFont.isValid()) {
2430 if (feCache.prevFontEngine && feCache.prevFontEngine->type() == QFontEngine::Multi && feCache.prevScript == script) {
2431 engine = feCache.prevFontEngine;
2432 } else {
2433 engine = QFontEngineMulti::createMultiFontEngine(rawFont.d->fontEngine, script);
2434 feCache.prevFontEngine = engine;
2435 feCache.prevScript = script;
2436 engine->ref.ref();
2437 if (feCache.prevScaledFontEngine) {
2438 releaseCachedFontEngine(feCache.prevScaledFontEngine);
2439 feCache.prevScaledFontEngine = nullptr;
2440 }
2441 }
2442 if (si.analysis.flags == QScriptAnalysis::SmallCaps) {
2443 if (feCache.prevScaledFontEngine) {
2444 scaledEngine = feCache.prevScaledFontEngine;
2445 } else {
2446 // GCC 12 gets confused about QFontEngine::ref, for some non-obvious reason
2447 // warning: ‘unsigned int __atomic_or_fetch_4(volatile void*, unsigned int, int)’ writing 4 bytes
2448 // into a region of size 0 overflows the destination [-Wstringop-overflow=]
2449 QT_WARNING_PUSH
2450 QT_WARNING_DISABLE_GCC("-Wstringop-overflow")
2451
2452 QFontEngine *scEngine = rawFont.d->fontEngine->cloneWithSize(smallCapsFraction * rawFont.pixelSize());
2453 scEngine->ref.ref();
2454 scaledEngine = QFontEngineMulti::createMultiFontEngine(scEngine, script);
2455 scaledEngine->ref.ref();
2456 feCache.prevScaledFontEngine = scaledEngine;
2457 // If scEngine is not ref'ed by scaledEngine, make sure it is deallocated and not leaked.
2458 if (!scEngine->ref.deref())
2459 delete scEngine;
2460
2461 QT_WARNING_POP
2462 }
2463 }
2464 } else
2465#endif
2466 {
2467 if (hasFormats()) {
2468 if (feCache.prevFontEngine && feCache.prevPosition == si.position && feCache.prevLength == length(&si) && feCache.prevScript == script) {
2469 engine = feCache.prevFontEngine;
2470 scaledEngine = feCache.prevScaledFontEngine;
2471 } else {
2472 QTextCharFormat f = format(&si);
2473 font = f.font();
2474
2475 if (QTextDocumentPrivate::get(block) != nullptr && QTextDocumentPrivate::get(block)->layout() != nullptr) {
2476 // Make sure we get the right dpi on printers
2477 QPaintDevice *pdev = QTextDocumentPrivate::get(block)->layout()->paintDevice();
2478 if (pdev)
2479 font = QFont(font, pdev);
2480 } else {
2481 font = font.resolve(fnt);
2482 }
2483 engine = font.d->engineForScript(script);
2484 Q_ASSERT(engine);
2485 engine->ref.ref();
2486
2487 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
2488 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
2489 if (font.pointSize() != -1)
2490 font.setPointSize((font.pointSize() * 2) / 3);
2491 else
2492 font.setPixelSize((font.pixelSize() * 2) / 3);
2493 scaledEngine = font.d->engineForScript(script);
2494 if (scaledEngine)
2495 scaledEngine->ref.ref();
2496 }
2497
2498 if (feCache.prevFontEngine)
2499 releaseCachedFontEngine(feCache.prevFontEngine);
2500 feCache.prevFontEngine = engine;
2501
2502 if (feCache.prevScaledFontEngine)
2503 releaseCachedFontEngine(feCache.prevScaledFontEngine);
2504 feCache.prevScaledFontEngine = scaledEngine;
2505
2506 feCache.prevScript = script;
2507 feCache.prevPosition = si.position;
2508 feCache.prevLength = length(&si);
2509 }
2510 } else {
2511 if (feCache.prevFontEngine && feCache.prevScript == script && feCache.prevPosition == -1) {
2512 engine = feCache.prevFontEngine;
2513 } else {
2514 engine = font.d->engineForScript(script);
2515 Q_ASSERT(engine);
2516 engine->ref.ref();
2517 if (feCache.prevFontEngine)
2518 releaseCachedFontEngine(feCache.prevFontEngine);
2519 feCache.prevFontEngine = engine;
2520
2521 feCache.prevScript = script;
2522 feCache.prevPosition = -1;
2523 feCache.prevLength = -1;
2524 feCache.prevScaledFontEngine = nullptr;
2525 }
2526 }
2527
2528 if (si.analysis.flags == QScriptAnalysis::SmallCaps) {
2529 QFontPrivate *p = font.d->smallCapsFontPrivate();
2530 scaledEngine = p->engineForScript(script);
2531 }
2532 }
2533
2534 if (leading) {
2535 Q_ASSERT(engine);
2536 Q_ASSERT(ascent);
2537 Q_ASSERT(descent);
2538 *ascent = engine->ascent();
2539 *descent = engine->descent();
2540 *leading = engine->leading();
2541 }
2542
2543 if (scaledEngine)
2544 return scaledEngine;
2545 return engine;
2546}
2547
2553
2555
2556static void set(QJustificationPoint *point, int type, const QGlyphLayout &glyph, QFontEngine *fe)
2557{
2558 point->type = type;
2559 point->glyph = glyph;
2560
2561 if (type >= Justification_Arabic_Normal) {
2562 const char32_t ch = U'\x640'; // Kashida character
2563
2564 glyph_t kashidaGlyph = fe->glyphIndex(ch);
2565 if (kashidaGlyph != 0) {
2566 QGlyphLayout g;
2567 g.numGlyphs = 1;
2568 g.glyphs = &kashidaGlyph;
2569 g.advances = &point->kashidaWidth;
2570 fe->recalcAdvances(&g, { });
2571
2572 if (point->kashidaWidth == 0)
2574 } else {
2576 point->kashidaWidth = 0;
2577 }
2578 }
2579}
2580
2581
2582void QTextEngine::justify(const QScriptLine &line)
2583{
2584// qDebug("justify: line.gridfitted = %d, line.justified=%d", line.gridfitted, line.justified);
2585 if (line.gridfitted && line.justified)
2586 return;
2587
2588 if (!line.gridfitted) {
2589 // redo layout in device metrics, then adjust
2590 const_cast<QScriptLine &>(line).gridfitted = true;
2591 }
2592
2593 if ((option.alignment() & Qt::AlignHorizontal_Mask) != Qt::AlignJustify)
2594 return;
2595
2596 itemize();
2597
2598 if (!forceJustification) {
2599 int end = line.from + (int)line.length + line.trailingSpaces;
2600 if (end == layoutData->string.size())
2601 return; // no justification at end of paragraph
2602 if (end && layoutData->items.at(findItem(end - 1)).analysis.flags == QScriptAnalysis::LineOrParagraphSeparator)
2603 return; // no justification at the end of an explicitly separated line
2604 }
2605
2606 // justify line
2607 int maxJustify = 0;
2608
2609 // don't include trailing white spaces when doing justification
2610 int line_length = line.length;
2611 const QCharAttributes *a = attributes();
2612 if (! a)
2613 return;
2614 a += line.from;
2615 while (line_length && a[line_length-1].whiteSpace)
2616 --line_length;
2617 // subtract one char more, as we can't justfy after the last character
2618 --line_length;
2619
2620 if (line_length <= 0)
2621 return;
2622
2623 int firstItem = findItem(line.from);
2624 int lastItem = findItem(line.from + line_length - 1, firstItem);
2625 int nItems = (firstItem >= 0 && lastItem >= firstItem)? (lastItem-firstItem+1) : 0;
2626
2627 QVarLengthArray<QJustificationPoint> justificationPoints;
2628 int nPoints = 0;
2629// 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());
2630 QFixed minKashida = 0x100000;
2631
2632 // we need to do all shaping before we go into the next loop, as we there
2633 // store pointers to the glyph data that could get reallocated by the shaping
2634 // process.
2635 for (int i = 0; i < nItems; ++i) {
2636 const QScriptItem &si = layoutData->items.at(firstItem + i);
2637 if (!si.num_glyphs)
2638 shape(firstItem + i);
2639 }
2640
2641 for (int i = 0; i < nItems; ++i) {
2642 const QScriptItem &si = layoutData->items.at(firstItem + i);
2643
2644 int kashida_type = Justification_Arabic_Normal;
2645 int kashida_pos = -1;
2646
2647 int start = qMax(line.from - si.position, 0);
2648 int end = qMin(line.from + line_length - (int)si.position, length(firstItem+i));
2649
2650 unsigned short *log_clusters = logClusters(&si);
2651
2652 int gs = log_clusters[start];
2653 int ge = (end == length(firstItem+i) ? si.num_glyphs : log_clusters[end]);
2654
2655 Q_ASSERT(ge <= si.num_glyphs);
2656
2657 const QGlyphLayout g = shapedGlyphs(&si);
2658
2659 for (int i = gs; i < ge; ++i) {
2660 g.justifications[i].type = QGlyphJustification::JustifyNone;
2661 g.justifications[i].nKashidas = 0;
2662 g.justifications[i].space_18d6 = 0;
2663
2664 justificationPoints.resize(nPoints+3);
2665 int justification = g.attributes[i].justification;
2666
2667 switch(justification) {
2668 case Justification_Prohibited:
2669 break;
2670 case Justification_Space:
2671 case Justification_Arabic_Space:
2672 if (kashida_pos >= 0) {
2673// qDebug("kashida position at %d in word", kashida_pos);
2674 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
2675 if (justificationPoints[nPoints].kashidaWidth > 0) {
2676 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
2677 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
2678 ++nPoints;
2679 }
2680 }
2681 kashida_pos = -1;
2682 kashida_type = Justification_Arabic_Normal;
2683 Q_FALLTHROUGH();
2684 case Justification_Character:
2685 set(&justificationPoints[nPoints++], justification, g.mid(i), fontEngine(si));
2686 maxJustify = qMax(maxJustify, justification);
2687 break;
2688 case Justification_Arabic_Normal:
2689 case Justification_Arabic_Waw:
2690 case Justification_Arabic_BaRa:
2691 case Justification_Arabic_Alef:
2692 case Justification_Arabic_HahDal:
2693 case Justification_Arabic_Seen:
2694 case Justification_Arabic_Kashida:
2695 if (justification >= kashida_type) {
2696 kashida_pos = i;
2697 kashida_type = justification;
2698 }
2699 }
2700 }
2701 if (kashida_pos >= 0) {
2702 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
2703 if (justificationPoints[nPoints].kashidaWidth > 0) {
2704 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
2705 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
2706 ++nPoints;
2707 }
2708 }
2709 }
2710
2711 QFixed leading = leadingSpaceWidth(line);
2712 QFixed need = line.width - line.textWidth - leading;
2713 if (need < 0) {
2714 // line overflows already!
2715 const_cast<QScriptLine &>(line).justified = true;
2716 return;
2717 }
2718
2719// qDebug("doing justification: textWidth=%x, requested=%x, maxJustify=%d", line.textWidth.value(), line.width.value(), maxJustify);
2720// qDebug(" minKashida=%f, need=%f", minKashida.toReal(), need.toReal());
2721
2722 // distribute in priority order
2723 if (maxJustify >= Justification_Arabic_Normal) {
2724 while (need >= minKashida) {
2725 for (int type = maxJustify; need >= minKashida && type >= Justification_Arabic_Normal; --type) {
2726 for (int i = 0; need >= minKashida && i < nPoints; ++i) {
2727 if (justificationPoints[i].type == type && justificationPoints[i].kashidaWidth <= need) {
2728 justificationPoints[i].glyph.justifications->nKashidas++;
2729 // ############
2730 justificationPoints[i].glyph.justifications->space_18d6 += justificationPoints[i].kashidaWidth.value();
2731 need -= justificationPoints[i].kashidaWidth;
2732// qDebug("adding kashida type %d with width %x, neednow %x", type, justificationPoints[i].kashidaWidth, need.value());
2733 }
2734 }
2735 }
2736 }
2737 }
2738 Q_ASSERT(need >= 0);
2739 if (!need)
2740 goto end;
2741
2742 maxJustify = qMin(maxJustify, int(Justification_Space));
2743 for (int type = maxJustify; need != 0 && type > 0; --type) {
2744 int n = 0;
2745 for (int i = 0; i < nPoints; ++i) {
2746 if (justificationPoints[i].type == type)
2747 ++n;
2748 }
2749// qDebug("number of points for justification type %d: %d", type, n);
2750
2751
2752 if (!n)
2753 continue;
2754
2755 for (int i = 0; i < nPoints; ++i) {
2756 if (justificationPoints[i].type == type) {
2757 QFixed add = need/n;
2758// qDebug("adding %x to glyph %x", add.value(), justificationPoints[i].glyph->glyph);
2759 justificationPoints[i].glyph.justifications[0].space_18d6 = add.value();
2760 need -= add;
2761 --n;
2762 }
2763 }
2764
2765 Q_ASSERT(!need);
2766 }
2767 end:
2768 const_cast<QScriptLine &>(line).justified = true;
2769}
2770
2771void QScriptLine::setDefaultHeight(QTextEngine *eng)
2772{
2773 QFont f;
2774 QFontEngine *e;
2775
2776 if (QTextDocumentPrivate::get(eng->block) != nullptr && QTextDocumentPrivate::get(eng->block)->layout() != nullptr) {
2777 f = eng->block.charFormat().font();
2778 // Make sure we get the right dpi on printers
2779 QPaintDevice *pdev = QTextDocumentPrivate::get(eng->block)->layout()->paintDevice();
2780 if (pdev)
2781 f = QFont(f, pdev);
2782 e = f.d->engineForScript(QChar::Script_Common);
2783 } else {
2784 e = eng->fnt.d->engineForScript(QChar::Script_Common);
2785 }
2786
2787 QFixed other_ascent = e->ascent();
2788 QFixed other_descent = e->descent();
2789 QFixed other_leading = e->leading();
2790 leading = qMax(leading + ascent, other_leading + other_ascent) - qMax(ascent, other_ascent);
2791 ascent = qMax(ascent, other_ascent);
2792 descent = qMax(descent, other_descent);
2793}
2794
2795QTextEngine::LayoutData::LayoutData()
2796{
2797 memory = nullptr;
2798 allocated = 0;
2799 memory_on_stack = false;
2800 used = 0;
2801 hasBidi = false;
2802 layoutState = LayoutEmpty;
2803 haveCharAttributes = false;
2804 logClustersPtr = nullptr;
2805 available_glyphs = 0;
2806 currentMaxWidth = 0;
2807}
2808
2809QTextEngine::LayoutData::LayoutData(const QString &str, void **stack_memory, qsizetype _allocated)
2810 : string(str)
2811{
2812 allocated = _allocated;
2813
2814 constexpr qsizetype voidSize = sizeof(void*);
2815 qsizetype space_charAttributes = sizeof(QCharAttributes) * string.size() / voidSize + 1;
2816 qsizetype space_logClusters = sizeof(unsigned short) * string.size() / voidSize + 1;
2817 available_glyphs = (allocated - space_charAttributes - space_logClusters) * voidSize / QGlyphLayout::SpaceNeeded;
2818
2819 if (available_glyphs < str.size()) {
2820 // need to allocate on the heap
2821 allocated = 0;
2822
2823 memory_on_stack = false;
2824 memory = nullptr;
2825 logClustersPtr = nullptr;
2826 } else {
2827 memory_on_stack = true;
2828 memory = stack_memory;
2829 logClustersPtr = (unsigned short *)(memory + space_charAttributes);
2830
2831 void *m = memory + space_charAttributes + space_logClusters;
2832 glyphLayout = QGlyphLayout(reinterpret_cast<char *>(m), str.size());
2833 glyphLayout.clear();
2834 memset(memory, 0, space_charAttributes*sizeof(void *));
2835 }
2836 used = 0;
2837 hasBidi = false;
2838 layoutState = LayoutEmpty;
2839 haveCharAttributes = false;
2840 currentMaxWidth = 0;
2841}
2842
2843QTextEngine::LayoutData::~LayoutData()
2844{
2845 if (!memory_on_stack)
2846 free(memory);
2847 memory = nullptr;
2848}
2849
2850bool QTextEngine::LayoutData::reallocate(int totalGlyphs)
2851{
2852 Q_ASSERT(totalGlyphs >= glyphLayout.numGlyphs);
2853 if (memory_on_stack && available_glyphs >= totalGlyphs) {
2854 glyphLayout.grow(glyphLayout.data(), totalGlyphs);
2855 return true;
2856 }
2857
2858 const qsizetype space_charAttributes = (sizeof(QCharAttributes) * string.size() / sizeof(void*) + 1);
2859 const qsizetype space_logClusters = (sizeof(unsigned short) * string.size() / sizeof(void*) + 1);
2860 const qsizetype space_glyphs = qsizetype(totalGlyphs) * QGlyphLayout::SpaceNeeded / sizeof(void *) + 2;
2861
2862 const qsizetype newAllocated = space_charAttributes + space_glyphs + space_logClusters;
2863 // Check if the length of string/glyphs causes int overflow,
2864 // we can't layout such a long string all at once, so return false here to
2865 // indicate there is a failure
2866 if (size_t(space_charAttributes) > INT_MAX || size_t(space_logClusters) > INT_MAX || totalGlyphs < 0
2867 || size_t(space_glyphs) > INT_MAX || size_t(newAllocated) > INT_MAX || newAllocated < allocated) {
2868 layoutState = LayoutFailed;
2869 return false;
2870 }
2871
2872 void **newMem = (void **)::realloc(memory_on_stack ? nullptr : memory, newAllocated*sizeof(void *));
2873 if (!newMem) {
2874 layoutState = LayoutFailed;
2875 return false;
2876 }
2877 if (memory_on_stack)
2878 memcpy(newMem, memory, allocated*sizeof(void *));
2879 memory = newMem;
2880 memory_on_stack = false;
2881
2882 void **m = memory;
2883 m += space_charAttributes;
2884 logClustersPtr = (unsigned short *) m;
2885 m += space_logClusters;
2886
2887 const qsizetype space_preGlyphLayout = space_charAttributes + space_logClusters;
2888 if (allocated < space_preGlyphLayout)
2889 memset(memory + allocated, 0, (space_preGlyphLayout - allocated)*sizeof(void *));
2890
2891 glyphLayout.grow(reinterpret_cast<char *>(m), totalGlyphs);
2892
2893 allocated = newAllocated;
2894 return true;
2895}
2896
2898{
2899 Q_ASSERT(offsets != oldLayout->offsets);
2900
2901 int n = std::min(numGlyphs, oldLayout->numGlyphs);
2902
2903 memcpy(offsets, oldLayout->offsets, n * sizeof(QFixedPoint));
2904 memcpy(attributes, oldLayout->attributes, n * sizeof(QGlyphAttributes));
2905 memcpy(justifications, oldLayout->justifications, n * sizeof(QGlyphJustification));
2906 memcpy(advances, oldLayout->advances, n * sizeof(QFixed));
2907 memcpy(glyphs, oldLayout->glyphs, n * sizeof(glyph_t));
2908
2909 numGlyphs = n;
2910}
2911
2912// grow to the new size, copying the existing data to the new layout
2913void QGlyphLayout::grow(char *address, int totalGlyphs)
2914{
2915 QGlyphLayout oldLayout(address, numGlyphs);
2916 QGlyphLayout newLayout(address, totalGlyphs);
2917
2918 if (numGlyphs) {
2919 // move the existing data
2920 memmove(newLayout.attributes, oldLayout.attributes, numGlyphs * sizeof(QGlyphAttributes));
2921 memmove(newLayout.justifications, oldLayout.justifications, numGlyphs * sizeof(QGlyphJustification));
2922 memmove(newLayout.advances, oldLayout.advances, numGlyphs * sizeof(QFixed));
2923 memmove(newLayout.glyphs, oldLayout.glyphs, numGlyphs * sizeof(glyph_t));
2924 }
2925
2926 // clear the new data
2927 newLayout.clear(numGlyphs);
2928
2929 *this = newLayout;
2930}
2931
2932void QTextEngine::freeMemory()
2933{
2934 if (!stackEngine) {
2935 delete layoutData;
2936 layoutData = nullptr;
2937 } else {
2938 layoutData->used = 0;
2939 layoutData->hasBidi = false;
2940 layoutData->layoutState = LayoutEmpty;
2941 layoutData->haveCharAttributes = false;
2942 layoutData->currentMaxWidth = 0;
2943 layoutData->items.clear();
2944 }
2945 if (specialData)
2946 specialData->resolvedFormats.clear();
2947 for (int i = 0; i < lines.size(); ++i) {
2948 lines[i].justified = 0;
2949 lines[i].gridfitted = 0;
2950 }
2951}
2952
2953int QTextEngine::formatIndex(const QScriptItem *si) const
2954{
2955 if (specialData && !specialData->resolvedFormats.isEmpty()) {
2956 QTextFormatCollection *collection = formatCollection();
2957 Q_ASSERT(collection);
2958 return collection->indexForFormat(specialData->resolvedFormats.at(si - &layoutData->items.at(0)));
2959 }
2960
2961 const QTextDocumentPrivate *p = QTextDocumentPrivate::get(block);
2962 if (!p)
2963 return -1;
2964 int pos = si->position;
2965 if (specialData && si->position >= specialData->preeditPosition) {
2966 if (si->position < specialData->preeditPosition + specialData->preeditText.size())
2967 pos = qMax(qMin(block.length(), specialData->preeditPosition) - 1, 0);
2968 else
2969 pos -= specialData->preeditText.size();
2970 }
2971 QTextDocumentPrivate::FragmentIterator it = p->find(block.position() + pos);
2972 return it.value()->format;
2973}
2974
2975
2976QTextCharFormat QTextEngine::format(const QScriptItem *si) const
2977{
2978 if (const QTextFormatCollection *collection = formatCollection())
2979 return collection->charFormat(formatIndex(si));
2980 return QTextCharFormat();
2981}
2982
2983void QTextEngine::addRequiredBoundaries() const
2984{
2985 if (specialData) {
2986 for (int i = 0; i < specialData->formats.size(); ++i) {
2987 const QTextLayout::FormatRange &r = specialData->formats.at(i);
2988 setBoundary(r.start);
2989 setBoundary(r.start + r.length);
2990 //qDebug("adding boundaries %d %d", r.start, r.start+r.length);
2991 }
2992 }
2993}
2994
2995bool QTextEngine::atWordSeparator(int position) const
2996{
2997 const QChar c = layoutData->string.at(position);
2998 switch (c.unicode()) {
2999 case '.':
3000 case ',':
3001 case '?':
3002 case '!':
3003 case '@':
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 return true;
3031 default:
3032 break;
3033 }
3034 return false;
3035}
3036
3037void QTextEngine::setPreeditArea(int position, const QString &preeditText)
3038{
3039 if (preeditText.isEmpty()) {
3040 if (!specialData)
3041 return;
3042 if (specialData->formats.isEmpty()) {
3043 delete specialData;
3044 specialData = nullptr;
3045 } else {
3046 specialData->preeditText = QString();
3047 specialData->preeditPosition = -1;
3048 }
3049 } else {
3050 if (!specialData)
3051 specialData = new SpecialData;
3052 specialData->preeditPosition = position;
3053 specialData->preeditText = preeditText;
3054 }
3055 invalidate();
3056 clearLineData();
3057}
3058
3059void QTextEngine::setFormats(const QList<QTextLayout::FormatRange> &formats)
3060{
3061 if (formats.isEmpty()) {
3062 if (!specialData)
3063 return;
3064 if (specialData->preeditText.isEmpty()) {
3065 delete specialData;
3066 specialData = nullptr;
3067 } else {
3068 specialData->formats.clear();
3069 }
3070 } else {
3071 if (!specialData) {
3072 specialData = new SpecialData;
3073 specialData->preeditPosition = -1;
3074 }
3075 specialData->formats = formats;
3076 indexFormats();
3077 }
3078 invalidate();
3079 clearLineData();
3080}
3081
3082void QTextEngine::indexFormats()
3083{
3084 QTextFormatCollection *collection = formatCollection();
3085 if (!collection) {
3086 Q_ASSERT(QTextDocumentPrivate::get(block) == nullptr);
3087 specialData->formatCollection.reset(new QTextFormatCollection);
3088 collection = specialData->formatCollection.data();
3089 }
3090
3091 // replace with shared copies
3092 for (int i = 0; i < specialData->formats.size(); ++i) {
3093 QTextCharFormat &format = specialData->formats[i].format;
3094 format = collection->charFormat(collection->indexForFormat(format));
3095 }
3096}
3097
3098/* These two helper functions are used to determine whether we need to insert a ZWJ character
3099 between the text that gets truncated and the ellipsis. This is important to get
3100 correctly shaped results for arabic text.
3101*/
3102static inline bool nextCharJoins(const QString &string, int pos)
3103{
3104 while (pos < string.size() && string.at(pos).category() == QChar::Mark_NonSpacing)
3105 ++pos;
3106 if (pos == string.size())
3107 return false;
3108 QChar::JoiningType joining = string.at(pos).joiningType();
3109 return joining != QChar::Joining_None && joining != QChar::Joining_Transparent;
3110}
3111
3112static inline bool prevCharJoins(const QString &string, int pos)
3113{
3114 while (pos > 0 && string.at(pos - 1).category() == QChar::Mark_NonSpacing)
3115 --pos;
3116 if (pos == 0)
3117 return false;
3118 QChar::JoiningType joining = string.at(pos - 1).joiningType();
3119 return joining == QChar::Joining_Dual || joining == QChar::Joining_Causing;
3120}
3121
3122static constexpr bool isRetainableControlCode(char16_t c) noexcept
3123{
3124 return (c >= 0x202a && c <= 0x202e) // LRE, RLE, PDF, LRO, RLO
3125 || (c >= 0x200e && c <= 0x200f) // LRM, RLM
3126 || (c >= 0x2066 && c <= 0x2069); // LRI, RLI, FSI, PDI
3127}
3128
3129static QString stringMidRetainingBidiCC(const QString &string,
3130 const QString &ellidePrefix,
3131 const QString &ellideSuffix,
3132 int subStringFrom,
3133 int subStringTo,
3134 int midStart,
3135 int midLength)
3136{
3137 QString prefix;
3138 for (int i=subStringFrom; i<midStart; ++i) {
3139 char16_t c = string.at(i).unicode();
3141 prefix += c;
3142 }
3143
3144 QString suffix;
3145 for (int i=midStart + midLength; i<subStringTo; ++i) {
3146 char16_t c = string.at(i).unicode();
3148 suffix += c;
3149 }
3150
3151 return prefix + ellidePrefix + QStringView{string}.mid(midStart, midLength) + ellideSuffix + suffix;
3152}
3153
3154QString QTextEngine::elidedText(Qt::TextElideMode mode, QFixed width, int flags, int from, int count) const
3155{
3156// qDebug() << "elidedText; available width" << width.toReal() << "text width:" << this->width(0, layoutData->string.length()).toReal();
3157
3158 if (flags & Qt::TextShowMnemonic) {
3159 itemize();
3160 QCharAttributes *attributes = const_cast<QCharAttributes *>(this->attributes());
3161 if (!attributes)
3162 return QString();
3163 for (int i = 0; i < layoutData->items.size(); ++i) {
3164 const QScriptItem &si = layoutData->items.at(i);
3165 if (!si.num_glyphs)
3166 shape(i);
3167
3168 unsigned short *logClusters = this->logClusters(&si);
3169 QGlyphLayout glyphs = shapedGlyphs(&si);
3170
3171 const int end = si.position + length(&si);
3172 for (int i = si.position; i < end - 1; ++i) {
3173 if (layoutData->string.at(i) == u'&'
3174 && !attributes[i + 1].whiteSpace && attributes[i + 1].graphemeBoundary) {
3175 const int gp = logClusters[i - si.position];
3176 glyphs.attributes[gp].dontPrint = true;
3177 // emulate grapheme cluster
3178 attributes[i] = attributes[i + 1];
3179 memset(attributes + i + 1, 0, sizeof(QCharAttributes));
3180 if (layoutData->string.at(i + 1) == u'&')
3181 ++i;
3182 }
3183 }
3184 }
3185 }
3186
3187 validate();
3188
3189 const int to = count >= 0 && count <= layoutData->string.size() - from
3190 ? from + count
3191 : layoutData->string.size();
3192
3193 if (mode == Qt::ElideNone
3194 || this->width(from, layoutData->string.size()) <= width
3195 || to - from <= 1)
3196 return layoutData->string.mid(from, from - to);
3197
3198 QFixed ellipsisWidth;
3199 QString ellipsisText;
3200 {
3201 QFontEngine *engine = fnt.d->engineForScript(QChar::Script_Common);
3202
3203 constexpr char16_t ellipsisChar = u'\x2026';
3204
3205 // We only want to use the ellipsis character if it is from the main
3206 // font (not one of the fallbacks), since using a fallback font
3207 // will affect the metrics of the text, potentially causing it to shift
3208 // when it is being elided.
3209 if (engine->type() == QFontEngine::Multi) {
3210 QFontEngineMulti *multiEngine = static_cast<QFontEngineMulti *>(engine);
3211 multiEngine->ensureEngineAt(0);
3212 engine = multiEngine->engine(0);
3213 }
3214
3215 glyph_t glyph = engine->glyphIndex(ellipsisChar);
3216
3217 QGlyphLayout glyphs;
3218 glyphs.numGlyphs = 1;
3219 glyphs.glyphs = &glyph;
3220 glyphs.advances = &ellipsisWidth;
3221
3222 if (glyph != 0) {
3223 engine->recalcAdvances(&glyphs, { });
3224
3225 ellipsisText = ellipsisChar;
3226 } else {
3227 glyph = engine->glyphIndex('.');
3228 if (glyph != 0) {
3229 engine->recalcAdvances(&glyphs, { });
3230
3231 ellipsisWidth *= 3;
3232 ellipsisText = QStringLiteral("...");
3233 } else {
3234 engine = fnt.d->engineForScript(QChar::Script_Common);
3235 glyph = engine->glyphIndex(ellipsisChar);
3236 engine->recalcAdvances(&glyphs, { });
3237 ellipsisText = ellipsisChar;
3238 }
3239 }
3240 }
3241
3242 const QFixed availableWidth = width - ellipsisWidth;
3243 if (availableWidth < 0)
3244 return QString();
3245
3246 const QCharAttributes *attributes = this->attributes();
3247 if (!attributes)
3248 return QString();
3249
3250 constexpr char16_t ZWJ = u'\x200d'; // ZERO-WIDTH JOINER
3251
3252 if (mode == Qt::ElideRight) {
3253 QFixed currentWidth;
3254 int pos;
3255 int nextBreak = from;
3256
3257 do {
3258 pos = nextBreak;
3259
3260 ++nextBreak;
3261 while (nextBreak < layoutData->string.size() && !attributes[nextBreak].graphemeBoundary)
3262 ++nextBreak;
3263
3264 currentWidth += this->width(pos, nextBreak - pos);
3265 } while (nextBreak < to
3266 && currentWidth < availableWidth);
3267
3268 if (nextCharJoins(layoutData->string, pos))
3269 ellipsisText.prepend(ZWJ);
3270
3271 return stringMidRetainingBidiCC(layoutData->string,
3272 QString(), ellipsisText,
3273 from, to,
3274 from, pos - from);
3275 } else if (mode == Qt::ElideLeft) {
3276 QFixed currentWidth;
3277 int pos;
3278 int nextBreak = to;
3279
3280 do {
3281 pos = nextBreak;
3282
3283 --nextBreak;
3284 while (nextBreak > 0 && !attributes[nextBreak].graphemeBoundary)
3285 --nextBreak;
3286
3287 currentWidth += this->width(nextBreak, pos - nextBreak);
3288 } while (nextBreak > from
3289 && currentWidth < availableWidth);
3290
3291 if (prevCharJoins(layoutData->string, pos))
3292 ellipsisText.append(ZWJ);
3293
3294 return stringMidRetainingBidiCC(layoutData->string,
3295 ellipsisText, QString(),
3296 from, to,
3297 pos, to - pos);
3298 } else if (mode == Qt::ElideMiddle) {
3299 QFixed leftWidth;
3300 QFixed rightWidth;
3301
3302 int leftPos = from;
3303 int nextLeftBreak = from;
3304
3305 int rightPos = to;
3306 int nextRightBreak = to;
3307
3308 do {
3309 leftPos = nextLeftBreak;
3310 rightPos = nextRightBreak;
3311
3312 ++nextLeftBreak;
3313 while (nextLeftBreak < layoutData->string.size() && !attributes[nextLeftBreak].graphemeBoundary)
3314 ++nextLeftBreak;
3315
3316 --nextRightBreak;
3317 while (nextRightBreak > from && !attributes[nextRightBreak].graphemeBoundary)
3318 --nextRightBreak;
3319
3320 leftWidth += this->width(leftPos, nextLeftBreak - leftPos);
3321 rightWidth += this->width(nextRightBreak, rightPos - nextRightBreak);
3322 } while (nextLeftBreak < to
3323 && nextRightBreak > from
3324 && leftWidth + rightWidth < availableWidth);
3325
3326 if (nextCharJoins(layoutData->string, leftPos))
3327 ellipsisText.prepend(ZWJ);
3328 if (prevCharJoins(layoutData->string, rightPos))
3329 ellipsisText.append(ZWJ);
3330
3331 return QStringView{layoutData->string}.mid(from, leftPos - from) + ellipsisText + QStringView{layoutData->string}.mid(rightPos, to - rightPos);
3332 }
3333
3334 return layoutData->string.mid(from, to - from);
3335}
3336
3337void QTextEngine::setBoundary(int strPos) const
3338{
3339 const int item = findItem(strPos);
3340 if (item < 0)
3341 return;
3342
3343 QScriptItem newItem = layoutData->items.at(item);
3344 if (newItem.position != strPos) {
3345 newItem.position = strPos;
3346 layoutData->items.insert(item + 1, newItem);
3347 }
3348}
3349
3350QFixed QTextEngine::calculateTabWidth(int item, QFixed x) const
3351{
3352 const QScriptItem &si = layoutData->items.at(item);
3353
3354 QFixed dpiScale = 1;
3355 if (QTextDocumentPrivate::get(block) != nullptr && QTextDocumentPrivate::get(block)->layout() != nullptr) {
3356 QPaintDevice *pdev = QTextDocumentPrivate::get(block)->layout()->paintDevice();
3357 if (pdev)
3358 dpiScale = QFixed::fromReal(pdev->logicalDpiY() / qreal(qt_defaultDpiY()));
3359 } else {
3360 dpiScale = QFixed::fromReal(fnt.d->dpi / qreal(qt_defaultDpiY()));
3361 }
3362
3363 QList<QTextOption::Tab> tabArray = option.tabs();
3364 if (!tabArray.isEmpty()) {
3365 if (isRightToLeft()) { // rebase the tabArray positions.
3366 auto isLeftOrRightTab = [](const QTextOption::Tab &tab) {
3367 return tab.type == QTextOption::LeftTab || tab.type == QTextOption::RightTab;
3368 };
3369 const auto cbegin = tabArray.cbegin();
3370 const auto cend = tabArray.cend();
3371 const auto cit = std::find_if(cbegin, cend, isLeftOrRightTab);
3372 if (cit != cend) {
3373 const int index = std::distance(cbegin, cit);
3374 auto iter = tabArray.begin() + index;
3375 const auto end = tabArray.end();
3376 while (iter != end) {
3377 QTextOption::Tab &tab = *iter;
3378 if (tab.type == QTextOption::LeftTab)
3379 tab.type = QTextOption::RightTab;
3380 else if (tab.type == QTextOption::RightTab)
3381 tab.type = QTextOption::LeftTab;
3382 ++iter;
3383 }
3384 }
3385 }
3386 for (const QTextOption::Tab &tabSpec : std::as_const(tabArray)) {
3387 QFixed tab = QFixed::fromReal(tabSpec.position) * dpiScale;
3388 if (tab > x) { // this is the tab we need.
3389 int tabSectionEnd = layoutData->string.size();
3390 if (tabSpec.type == QTextOption::RightTab || tabSpec.type == QTextOption::CenterTab) {
3391 // find next tab to calculate the width required.
3392 tab = QFixed::fromReal(tabSpec.position);
3393 for (int i=item + 1; i < layoutData->items.size(); i++) {
3394 const QScriptItem &item = layoutData->items.at(i);
3395 if (item.analysis.flags == QScriptAnalysis::TabOrObject) { // found it.
3396 tabSectionEnd = item.position;
3397 break;
3398 }
3399 }
3400 }
3401 else if (tabSpec.type == QTextOption::DelimiterTab)
3402 // find delimiter character to calculate the width required
3403 tabSectionEnd = qMax(si.position, layoutData->string.indexOf(tabSpec.delimiter, si.position) + 1);
3404
3405 if (tabSectionEnd > si.position) {
3406 QFixed length;
3407 // Calculate the length of text between this tab and the tabSectionEnd
3408 for (int i=item; i < layoutData->items.size(); i++) {
3409 const QScriptItem &item = layoutData->items.at(i);
3410 if (item.position > tabSectionEnd || item.position <= si.position)
3411 continue;
3412 shape(i); // first, lets make sure relevant text is already shaped
3413 if (item.analysis.flags == QScriptAnalysis::Object) {
3414 length += item.width;
3415 continue;
3416 }
3417 QGlyphLayout glyphs = this->shapedGlyphs(&item);
3418 const int end = qMin(item.position + item.num_glyphs, tabSectionEnd) - item.position;
3419 for (int i=0; i < end; i++)
3420 length += glyphs.advances[i] * !glyphs.attributes[i].dontPrint;
3421 if (end + item.position == tabSectionEnd && tabSpec.type == QTextOption::DelimiterTab) // remove half of matching char
3422 length -= glyphs.advances[end] / 2 * !glyphs.attributes[end].dontPrint;
3423 }
3424
3425 switch (tabSpec.type) {
3426 case QTextOption::CenterTab:
3427 length /= 2;
3428 Q_FALLTHROUGH();
3429 case QTextOption::DelimiterTab:
3430 case QTextOption::RightTab:
3431 tab = QFixed::fromReal(tabSpec.position) * dpiScale - length;
3432 if (tab < x) // default to tab taking no space
3433 return QFixed();
3434 break;
3435 case QTextOption::LeftTab:
3436 break;
3437 }
3438 }
3439 return tab - x;
3440 }
3441 }
3442 }
3443 QFixed tab = QFixed::fromReal(option.tabStopDistance());
3444 if (tab <= 0)
3445 tab = 80; // default
3446 tab *= dpiScale;
3447 QFixed nextTabPos = ((x / tab).truncate() + 1) * tab;
3448 QFixed tabWidth = nextTabPos - x;
3449
3450 return tabWidth;
3451}
3452
3453namespace {
3454class FormatRangeComparatorByStart {
3455 const QList<QTextLayout::FormatRange> &list;
3456public:
3457 FormatRangeComparatorByStart(const QList<QTextLayout::FormatRange> &list) : list(list) { }
3458 bool operator()(int a, int b) {
3459 return list.at(a).start < list.at(b).start;
3460 }
3461};
3462class FormatRangeComparatorByEnd {
3463 const QList<QTextLayout::FormatRange> &list;
3464public:
3465 FormatRangeComparatorByEnd(const QList<QTextLayout::FormatRange> &list) : list(list) { }
3466 bool operator()(int a, int b) {
3467 return list.at(a).start + list.at(a).length < list.at(b).start + list.at(b).length;
3468 }
3469};
3470}
3471
3472void QTextEngine::resolveFormats() const
3473{
3474 if (!specialData || specialData->formats.isEmpty())
3475 return;
3476 Q_ASSERT(specialData->resolvedFormats.isEmpty());
3477
3478 QTextFormatCollection *collection = formatCollection();
3479
3480 QList<QTextCharFormat> resolvedFormats(layoutData->items.size());
3481
3482 QVarLengthArray<int, 64> formatsSortedByStart;
3483 formatsSortedByStart.reserve(specialData->formats.size());
3484 for (int i = 0; i < specialData->formats.size(); ++i) {
3485 if (specialData->formats.at(i).length >= 0)
3486 formatsSortedByStart.append(i);
3487 }
3488 QVarLengthArray<int, 64> formatsSortedByEnd = formatsSortedByStart;
3489 std::sort(formatsSortedByStart.begin(), formatsSortedByStart.end(),
3490 FormatRangeComparatorByStart(specialData->formats));
3491 std::sort(formatsSortedByEnd.begin(), formatsSortedByEnd.end(),
3492 FormatRangeComparatorByEnd(specialData->formats));
3493
3494 QVarLengthArray<int, 16> currentFormats;
3495 const int *startIt = formatsSortedByStart.constBegin();
3496 const int *endIt = formatsSortedByEnd.constBegin();
3497
3498 for (int i = 0; i < layoutData->items.size(); ++i) {
3499 const QScriptItem *si = &layoutData->items.at(i);
3500 int end = si->position + length(si);
3501
3502 while (startIt != formatsSortedByStart.constEnd() &&
3503 specialData->formats.at(*startIt).start <= si->position) {
3504 currentFormats.insert(std::upper_bound(currentFormats.begin(), currentFormats.end(), *startIt),
3505 *startIt);
3506 ++startIt;
3507 }
3508 while (endIt != formatsSortedByEnd.constEnd() &&
3509 specialData->formats.at(*endIt).start + specialData->formats.at(*endIt).length < end) {
3510 int *currentFormatIterator = std::lower_bound(currentFormats.begin(), currentFormats.end(), *endIt);
3511 if (*endIt < *currentFormatIterator)
3512 currentFormatIterator = currentFormats.end();
3513 currentFormats.remove(currentFormatIterator - currentFormats.begin());
3514 ++endIt;
3515 }
3516
3517 QTextCharFormat &format = resolvedFormats[i];
3518 if (QTextDocumentPrivate::get(block) != nullptr) {
3519 // when we have a QTextDocumentPrivate, formatIndex might still return a valid index based
3520 // on the preeditPosition. for all other cases, we cleared the resolved format indices
3521 format = collection->charFormat(formatIndex(si));
3522 }
3523 if (!currentFormats.isEmpty()) {
3524 for (int cur : currentFormats) {
3525 const QTextLayout::FormatRange &range = specialData->formats.at(cur);
3526 Q_ASSERT(range.start <= si->position && range.start + range.length >= end);
3527 format.merge(range.format);
3528 }
3529 format = collection->charFormat(collection->indexForFormat(format)); // get shared copy
3530 }
3531 }
3532
3533 specialData->resolvedFormats = resolvedFormats;
3534}
3535
3536QFixed QTextEngine::leadingSpaceWidth(const QScriptLine &line)
3537{
3538 if (!line.hasTrailingSpaces
3539 || (option.flags() & QTextOption::IncludeTrailingSpaces)
3540 || !isRightToLeft())
3541 return QFixed();
3542
3543 return width(line.from + line.length, line.trailingSpaces);
3544}
3545
3546QFixed QTextEngine::alignLine(const QScriptLine &line)
3547{
3548 QFixed x = 0;
3549 justify(line);
3550 // if width is QFIXED_MAX that means we used setNumColumns() and that implicitly makes this line left aligned.
3551 if (!line.justified && line.width != QFIXED_MAX) {
3552 int align = option.alignment();
3553 if (align & Qt::AlignJustify && isRightToLeft())
3554 align = Qt::AlignRight;
3555 if (align & Qt::AlignRight)
3556 x = line.width - (line.textAdvance);
3557 else if (align & Qt::AlignHCenter)
3558 x = (line.width - line.textAdvance)/2;
3559 }
3560 return x;
3561}
3562
3563QFixed QTextEngine::offsetInLigature(const QScriptItem *si, int pos, int max, int glyph_pos)
3564{
3565 unsigned short *logClusters = this->logClusters(si);
3566 const QGlyphLayout &glyphs = shapedGlyphs(si);
3567
3568 int offsetInCluster = 0;
3569 for (int i = pos - 1; i >= 0; i--) {
3570 if (logClusters[i] == glyph_pos)
3571 offsetInCluster++;
3572 else
3573 break;
3574 }
3575
3576 // in the case that the offset is inside a (multi-character) glyph,
3577 // interpolate the position.
3578 if (offsetInCluster > 0) {
3579 int clusterLength = 0;
3580 for (int i = pos - offsetInCluster; i < max; i++) {
3581 if (logClusters[i] == glyph_pos)
3582 clusterLength++;
3583 else
3584 break;
3585 }
3586 if (clusterLength)
3587 return glyphs.advances[glyph_pos] * offsetInCluster / clusterLength;
3588 }
3589
3590 return 0;
3591}
3592
3593// Scan in logClusters[from..to-1] for glyph_pos
3594int QTextEngine::getClusterLength(unsigned short *logClusters,
3595 const QCharAttributes *attributes,
3596 int from, int to, int glyph_pos, int *start)
3597{
3598 int clusterLength = 0;
3599 for (int i = from; i < to; i++) {
3600 if (logClusters[i] == glyph_pos && attributes[i].graphemeBoundary) {
3601 if (*start < 0)
3602 *start = i;
3603 clusterLength++;
3604 }
3605 else if (clusterLength)
3606 break;
3607 }
3608 return clusterLength;
3609}
3610
3611int QTextEngine::positionInLigature(const QScriptItem *si, int end,
3612 QFixed x, QFixed edge, int glyph_pos,
3613 bool cursorOnCharacter)
3614{
3615 unsigned short *logClusters = this->logClusters(si);
3616 int clusterStart = -1;
3617 int clusterLength = 0;
3618
3619 if (si->analysis.script != QChar::Script_Common &&
3620 si->analysis.script != QChar::Script_Greek &&
3621 si->analysis.script != QChar::Script_Latin &&
3622 si->analysis.script != QChar::Script_Hiragana &&
3623 si->analysis.script != QChar::Script_Katakana &&
3624 si->analysis.script != QChar::Script_Bopomofo &&
3625 si->analysis.script != QChar::Script_Han) {
3626 if (glyph_pos == -1)
3627 return si->position + end;
3628 else {
3629 int i;
3630 for (i = 0; i < end; i++)
3631 if (logClusters[i] == glyph_pos)
3632 break;
3633 return si->position + i;
3634 }
3635 }
3636
3637 if (glyph_pos == -1 && end > 0)
3638 glyph_pos = logClusters[end - 1];
3639 else {
3640 if (x <= edge)
3641 glyph_pos--;
3642 }
3643
3644 const QCharAttributes *attrs = attributes() + si->position;
3645 logClusters = this->logClusters(si);
3646 clusterLength = getClusterLength(logClusters, attrs, 0, end, glyph_pos, &clusterStart);
3647
3648 if (clusterLength) {
3649 const QGlyphLayout &glyphs = shapedGlyphs(si);
3650 QFixed glyphWidth = glyphs.effectiveAdvance(glyph_pos);
3651 // the approximate width of each individual element of the ligature
3652 QFixed perItemWidth = glyphWidth / clusterLength;
3653 if (perItemWidth <= 0)
3654 return si->position + clusterStart;
3655 QFixed left = x > edge ? edge : edge - glyphWidth;
3656 int n = ((x - left) / perItemWidth).floor().toInt();
3657 QFixed dist = x - left - n * perItemWidth;
3658 int closestItem = dist > (perItemWidth / 2) ? n + 1 : n;
3659 if (cursorOnCharacter && closestItem > 0)
3660 closestItem--;
3661 int pos = clusterStart + closestItem;
3662 // Jump to the next grapheme boundary
3663 while (pos < end && !attrs[pos].graphemeBoundary)
3664 pos++;
3665 return si->position + pos;
3666 }
3667 return si->position + end;
3668}
3669
3670int QTextEngine::previousLogicalPosition(int oldPos) const
3671{
3672 const QCharAttributes *attrs = attributes();
3673 int len = block.isValid() ? block.length() - 1
3674 : layoutData->string.size();
3675 Q_ASSERT(len <= layoutData->string.size());
3676 if (!attrs || oldPos <= 0 || oldPos > len)
3677 return oldPos;
3678
3679 oldPos--;
3680 while (oldPos && !attrs[oldPos].graphemeBoundary)
3681 oldPos--;
3682 return oldPos;
3683}
3684
3685int QTextEngine::nextLogicalPosition(int oldPos) const
3686{
3687 const QCharAttributes *attrs = attributes();
3688 int len = block.isValid() ? block.length() - 1
3689 : layoutData->string.size();
3690 Q_ASSERT(len <= layoutData->string.size());
3691 if (!attrs || oldPos < 0 || oldPos >= len)
3692 return oldPos;
3693
3694 oldPos++;
3695 while (oldPos < len && !attrs[oldPos].graphemeBoundary)
3696 oldPos++;
3697 return oldPos;
3698}
3699
3700int QTextEngine::lineNumberForTextPosition(int pos)
3701{
3702 if (!layoutData)
3703 itemize();
3704 if (pos == layoutData->string.size() && lines.size())
3705 return lines.size() - 1;
3706 for (int i = 0; i < lines.size(); ++i) {
3707 const QScriptLine& line = lines[i];
3708 if (line.from + line.length + line.trailingSpaces > pos)
3709 return i;
3710 }
3711 return -1;
3712}
3713
3714std::vector<int> QTextEngine::insertionPointsForLine(int lineNum)
3715{
3716 QTextLineItemIterator iterator(this, lineNum);
3717
3718 std::vector<int> insertionPoints;
3719 insertionPoints.reserve(size_t(iterator.line.length));
3720
3721 bool lastLine = lineNum >= lines.size() - 1;
3722
3723 while (!iterator.atEnd()) {
3724 const QScriptItem &si = iterator.next();
3725
3726 int end = iterator.itemEnd;
3727 if (lastLine && iterator.item == iterator.lastItem)
3728 ++end; // the last item in the last line -> insert eol position
3729 if (si.analysis.bidiLevel % 2) {
3730 for (int i = end - 1; i >= iterator.itemStart; --i)
3731 insertionPoints.push_back(i);
3732 } else {
3733 for (int i = iterator.itemStart; i < end; ++i)
3734 insertionPoints.push_back(i);
3735 }
3736 }
3737 return insertionPoints;
3738}
3739
3740int QTextEngine::endOfLine(int lineNum)
3741{
3742 const auto insertionPoints = insertionPointsForLine(lineNum);
3743 if (insertionPoints.size() > 0)
3744 return insertionPoints.back();
3745 return 0;
3746}
3747
3748int QTextEngine::beginningOfLine(int lineNum)
3749{
3750 const auto insertionPoints = insertionPointsForLine(lineNum);
3751 if (insertionPoints.size() > 0)
3752 return insertionPoints.front();
3753 return 0;
3754}
3755
3756int QTextEngine::positionAfterVisualMovement(int pos, QTextCursor::MoveOperation op)
3757{
3758 itemize();
3759
3760 bool moveRight = (op == QTextCursor::Right);
3761 bool alignRight = isRightToLeft();
3762 if (!layoutData->hasBidi)
3763 return moveRight ^ alignRight ? nextLogicalPosition(pos) : previousLogicalPosition(pos);
3764
3765 int lineNum = lineNumberForTextPosition(pos);
3766 if (lineNum < 0)
3767 return pos;
3768
3769 const auto insertionPoints = insertionPointsForLine(lineNum);
3770 for (size_t i = 0, max = insertionPoints.size(); i < max; ++i)
3771 if (pos == insertionPoints[i]) {
3772 if (moveRight) {
3773 if (i + 1 < max)
3774 return insertionPoints[i + 1];
3775 } else {
3776 if (i > 0)
3777 return insertionPoints[i - 1];
3778 }
3779
3780 if (moveRight ^ alignRight) {
3781 if (lineNum + 1 < lines.size())
3782 return alignRight ? endOfLine(lineNum + 1) : beginningOfLine(lineNum + 1);
3783 }
3784 else {
3785 if (lineNum > 0)
3786 return alignRight ? beginningOfLine(lineNum - 1) : endOfLine(lineNum - 1);
3787 }
3788
3789 break;
3790 }
3791
3792 return pos;
3793}
3794
3795void QTextEngine::addItemDecoration(QPainter *painter, const QLineF &line, ItemDecorationList *decorationList)
3796{
3797 if (delayDecorations) {
3798 decorationList->append(ItemDecoration(line.x1(), line.x2(), line.y1(), painter->pen()));
3799 } else {
3800 painter->drawLine(line);
3801 }
3802}
3803
3804void QTextEngine::addUnderline(QPainter *painter, const QLineF &line)
3805{
3806 // qDebug() << "Adding underline:" << line;
3807 addItemDecoration(painter, line, &underlineList);
3808}
3809
3810void QTextEngine::addStrikeOut(QPainter *painter, const QLineF &line)
3811{
3812 addItemDecoration(painter, line, &strikeOutList);
3813}
3814
3815void QTextEngine::addOverline(QPainter *painter, const QLineF &line)
3816{
3817 addItemDecoration(painter, line, &overlineList);
3818}
3819
3820void QTextEngine::drawItemDecorationList(QPainter *painter, const ItemDecorationList &decorationList)
3821{
3822 // qDebug() << "Drawing" << decorationList.size() << "decorations";
3823 if (decorationList.isEmpty())
3824 return;
3825
3826 for (const ItemDecoration &decoration : decorationList) {
3827 painter->setPen(decoration.pen);
3828 painter->drawLine(QLineF(decoration.x1, decoration.y, decoration.x2, decoration.y));
3829 }
3830}
3831
3832void QTextEngine::drawDecorations(QPainter *painter)
3833{
3834 QPen oldPen = painter->pen();
3835
3836 adjustUnderlines();
3837 drawItemDecorationList(painter, underlineList);
3838 drawItemDecorationList(painter, strikeOutList);
3839 drawItemDecorationList(painter, overlineList);
3840
3841 clearDecorations();
3842
3843 painter->setPen(oldPen);
3844}
3845
3846void QTextEngine::clearDecorations()
3847{
3848 underlineList.clear();
3849 strikeOutList.clear();
3850 overlineList.clear();
3851}
3852
3853void QTextEngine::adjustUnderlines()
3854{
3855 // qDebug() << __PRETTY_FUNCTION__ << underlineList.count() << "underlines";
3856 if (underlineList.isEmpty())
3857 return;
3858
3859 ItemDecorationList::iterator start = underlineList.begin();
3860 ItemDecorationList::iterator end = underlineList.end();
3861 ItemDecorationList::iterator it = start;
3862 qreal underlinePos = start->y;
3863 qreal penWidth = start->pen.widthF();
3864 qreal lastLineEnd = start->x1;
3865
3866 while (it != end) {
3867 if (qFuzzyCompare(lastLineEnd, it->x1)) { // no gap between underlines
3868 underlinePos = qMax(underlinePos, it->y);
3869 penWidth = qMax(penWidth, it->pen.widthF());
3870 } else { // gap between this and the last underline
3871 adjustUnderlines(start, it, underlinePos, penWidth);
3872 start = it;
3873 underlinePos = start->y;
3874 penWidth = start->pen.widthF();
3875 }
3876 lastLineEnd = it->x2;
3877 ++it;
3878 }
3879
3880 adjustUnderlines(start, end, underlinePos, penWidth);
3881}
3882
3883void QTextEngine::adjustUnderlines(ItemDecorationList::iterator start,
3884 ItemDecorationList::iterator end,
3885 qreal underlinePos, qreal penWidth)
3886{
3887 for (ItemDecorationList::iterator it = start; it != end; ++it) {
3888 it->y = underlinePos;
3889 it->pen.setWidthF(penWidth);
3890 }
3891}
3892
3893QStackTextEngine::QStackTextEngine(const QString &string, const QFont &f)
3894 : QTextEngine(string, f),
3895 _layoutData(string, _memory, MemSize)
3896{
3897 stackEngine = true;
3898 layoutData = &_layoutData;
3899}
3900
3901QTextItemInt::QTextItemInt(const QScriptItem &si, QFont *font, const QTextCharFormat &format)
3902 : charFormat(format),
3903 f(font),
3904 fontEngine(font->d->engineForScript(si.analysis.script))
3905{
3906 Q_ASSERT(fontEngine);
3907
3909}
3910
3911QTextItemInt::QTextItemInt(const QGlyphLayout &g, QFont *font, const QChar *chars_, int numChars, QFontEngine *fe, const QTextCharFormat &format)
3912 : charFormat(format),
3913 num_chars(numChars),
3914 chars(chars_),
3915 f(font),
3916 glyphs(g),
3917 fontEngine(fe)
3918{
3919}
3920
3921// Fix up flags and underlineStyle with given info
3923{
3924 // explicitly initialize flags so that initFontAttributes can be called
3925 // multiple times on the same TextItem
3926 flags = { };
3927 if (si.analysis.bidiLevel %2)
3928 flags |= QTextItem::RightToLeft;
3929 ascent = si.ascent;
3930 descent = si.descent;
3931
3932 if (charFormat.hasProperty(QTextFormat::TextUnderlineStyle)) {
3933 underlineStyle = charFormat.underlineStyle();
3934 } else if (charFormat.boolProperty(QTextFormat::FontUnderline)
3935 || f->d->underline) {
3936 underlineStyle = QTextCharFormat::SingleUnderline;
3937 }
3938
3939 // compat
3940 if (underlineStyle == QTextCharFormat::SingleUnderline)
3941 flags |= QTextItem::Underline;
3942
3943 if (f->d->overline || charFormat.fontOverline())
3944 flags |= QTextItem::Overline;
3945 if (f->d->strikeOut || charFormat.fontStrikeOut())
3946 flags |= QTextItem::StrikeOut;
3947}
3948
3949QTextItemInt QTextItemInt::midItem(QFontEngine *fontEngine, int firstGlyphIndex, int numGlyphs) const
3950{
3951 QTextItemInt ti = *this;
3952 const int end = firstGlyphIndex + numGlyphs;
3953 ti.glyphs = glyphs.mid(firstGlyphIndex, numGlyphs);
3954 ti.fontEngine = fontEngine;
3955
3956 if (logClusters && chars) {
3957 const int logClusterOffset = logClusters[0];
3958 while (logClusters[ti.chars - chars] - logClusterOffset < firstGlyphIndex)
3959 ++ti.chars;
3960
3961 ti.logClusters += (ti.chars - chars);
3962
3963 ti.num_chars = 0;
3964 int char_start = ti.chars - chars;
3965 while (char_start + ti.num_chars < num_chars && ti.logClusters[ti.num_chars] - logClusterOffset < end)
3966 ++ti.num_chars;
3967 }
3968 return ti;
3969}
3970
3971
3972QTransform qt_true_matrix(qreal w, qreal h, const QTransform &x)
3973{
3974 QRectF rect = x.mapRect(QRectF(0, 0, w, h));
3975 return x * QTransform::fromTranslate(-rect.x(), -rect.y());
3976}
3977
3978
3979glyph_metrics_t glyph_metrics_t::transformed(const QTransform &matrix) const
3980{
3981 if (matrix.type() < QTransform::TxTranslate)
3982 return *this;
3983
3984 glyph_metrics_t m = *this;
3985
3986 qreal w = width.toReal();
3987 qreal h = height.toReal();
3988 QTransform xform = qt_true_matrix(w, h, matrix);
3989
3990 QRectF rect(0, 0, w, h);
3991 rect = xform.mapRect(rect);
3992 m.width = QFixed::fromReal(rect.width());
3993 m.height = QFixed::fromReal(rect.height());
3994
3995 QLineF l = xform.map(QLineF(x.toReal(), y.toReal(), xoff.toReal(), yoff.toReal()));
3996
3997 m.x = QFixed::fromReal(l.x1());
3998 m.y = QFixed::fromReal(l.y1());
3999
4000 // The offset is relative to the baseline which is why we use dx/dy of the line
4001 m.xoff = QFixed::fromReal(l.dx());
4002 m.yoff = QFixed::fromReal(l.dy());
4003
4004 return m;
4005}
4006
4007QTextLineItemIterator::QTextLineItemIterator(QTextEngine *_eng, int _lineNum, const QPointF &pos,
4008 const QTextLayout::FormatRange *_selection)
4009 : eng(_eng),
4010 line(eng->lines[_lineNum]),
4011 si(nullptr),
4012 lineNum(_lineNum),
4013 lineEnd(line.from + line.length),
4014 firstItem(eng->findItem(line.from)),
4015 lastItem(eng->findItem(lineEnd - 1, firstItem)),
4016 nItems((firstItem >= 0 && lastItem >= firstItem)? (lastItem-firstItem+1) : 0),
4017 logicalItem(-1),
4018 item(-1),
4019 visualOrder(nItems),
4020 selection(_selection)
4021{
4022 x = QFixed::fromReal(pos.x());
4023
4024 x += line.x;
4025
4026 x += eng->alignLine(line);
4027
4028 if (nItems > 0) {
4029 QVarLengthArray<uchar> levels(nItems);
4030 for (int i = 0; i < nItems; ++i)
4031 levels[i] = eng->layoutData->items.at(i + firstItem).analysis.bidiLevel;
4032 QTextEngine::bidiReorder(nItems, levels.data(), visualOrder.data());
4033 }
4034
4035 eng->shapeLine(line);
4036}
4037
4039{
4040 x += itemWidth;
4041
4042 ++logicalItem;
4043 item = visualOrder[logicalItem] + firstItem;
4044 itemLength = eng->length(item);
4045 si = &eng->layoutData->items[item];
4046 if (!si->num_glyphs)
4047 eng->shape(item);
4048
4049 itemStart = qMax(line.from, si->position);
4051
4052 if (si->analysis.flags >= QScriptAnalysis::TabOrObject) {
4053 glyphsStart = 0;
4054 glyphsEnd = 1;
4055 itemWidth = si->width;
4056 return *si;
4057 }
4058
4059 unsigned short *logClusters = eng->logClusters(si);
4060 QGlyphLayout glyphs = eng->shapedGlyphs(si);
4061
4062 glyphsStart = logClusters[itemStart - si->position];
4064
4065 // show soft-hyphen at line-break
4066 if (si->position + itemLength >= lineEnd
4067 && eng->layoutData->string.at(lineEnd - 1).unicode() == QChar::SoftHyphen)
4068 glyphs.attributes[glyphsEnd - 1].dontPrint = false;
4069
4070 itemWidth = 0;
4071 for (int g = glyphsStart; g < glyphsEnd; ++g)
4072 itemWidth += glyphs.effectiveAdvance(g);
4073
4074 return *si;
4075}
4076
4077bool QTextLineItemIterator::getSelectionBounds(QFixed *selectionX, QFixed *selectionWidth) const
4078{
4079 *selectionX = *selectionWidth = 0;
4080
4081 if (!selection)
4082 return false;
4083
4084 if (si->analysis.flags >= QScriptAnalysis::TabOrObject) {
4085 if (si->position >= selection->start + selection->length
4086 || si->position + itemLength <= selection->start)
4087 return false;
4088
4089 *selectionX = x;
4090 *selectionWidth = itemWidth;
4091 } else {
4092 unsigned short *logClusters = eng->logClusters(si);
4093 QGlyphLayout glyphs = eng->shapedGlyphs(si);
4094
4095 int from = qMax(itemStart, selection->start) - si->position;
4096 int to = qMin(itemEnd, selection->start + selection->length) - si->position;
4097 if (from >= to)
4098 return false;
4099
4100 int start_glyph = logClusters[from];
4101 int end_glyph = (to == itemLength) ? si->num_glyphs : logClusters[to];
4102 QFixed soff;
4103 QFixed swidth;
4104 if (si->analysis.bidiLevel %2) {
4105 for (int g = glyphsEnd - 1; g >= end_glyph; --g)
4106 soff += glyphs.effectiveAdvance(g);
4107 for (int g = end_glyph - 1; g >= start_glyph; --g)
4108 swidth += glyphs.effectiveAdvance(g);
4109 } else {
4110 for (int g = glyphsStart; g < start_glyph; ++g)
4111 soff += glyphs.effectiveAdvance(g);
4112 for (int g = start_glyph; g < end_glyph; ++g)
4113 swidth += glyphs.effectiveAdvance(g);
4114 }
4115
4116 // If the starting character is in the middle of a ligature,
4117 // selection should only contain the right part of that ligature
4118 // glyph, so we need to get the width of the left part here and
4119 // add it to *selectionX
4120 QFixed leftOffsetInLigature = eng->offsetInLigature(si, from, to, start_glyph);
4121 *selectionX = x + soff + leftOffsetInLigature;
4122 *selectionWidth = swidth - leftOffsetInLigature;
4123 // If the ending character is also part of a ligature, swidth does
4124 // not contain that part yet, we also need to find out the width of
4125 // that left part
4126 *selectionWidth += eng->offsetInLigature(si, to, itemLength, end_glyph);
4127 }
4128 return true;
4129}
4130
4131QT_END_NAMESPACE
friend class QFontEngine
Definition qpainter.h:432
friend class QTextEngine
Definition qpainter.h:445
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:1824
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