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