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