1 /****************************************************************************
2 **
3 ** Copyright (C) 2021 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 
62 QT_BEGIN_NAMESPACE
63 
64 static const float smallCapsFraction = 0.7f;
65 
66 namespace {
67 // Helper class used in QTextEngine::itemize
68 // keep it out here to allow us to keep supporting various compilers.
69 class Itemizer {
70 public:
Itemizer(const QString & string,const QScriptAnalysis * analysis,QScriptItemArray & items)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     }
~Itemizer()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
generate(int start,int length,QFont::Capitalization caps)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 
99 private:
100     enum { MaxItemLength = 4096 };
101 
generateScriptItemsAndChangeCase(int start,int length,QScriptAnalysis::Flags flags)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 
generateScriptItems(int start,int length)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 
generateScriptItemsCapitalize(int start,int length)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 
generateScriptItemsSmallCaps(const ushort * uc,int start,int length)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
221 enum { BidiDebugEnabled = false };
222 #define BIDI_DEBUG if (1) ; else qDebug
223 #else
224 enum { BidiDebugEnabled = true };
225 static 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
operator <<(QDebug d,QChar::Direction dir)231 QDebug operator<<(QDebug d, QChar::Direction dir) {
232     return (d << directions[dir]);
233 }
234 #endif
235 
236 struct QBidiAlgorithm {
237     template<typename T> using Vector = QVarLengthArray<T, 64>;
238 
QBidiAlgorithm__anonab4538b80111::QBidiAlgorithm239     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 
initScriptAnalysisAndIsolatePairs__anonab4538b80111::QBidiAlgorithm253     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             uint uc = text[i].unicode();
261             if (QChar::isHighSurrogate(uc) && i < length - 1 && text[i + 1].isLowSurrogate()) {
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 
generateDirectionalRuns__anonab4538b80111::QBidiAlgorithm329     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 
resolveExplicitLevels__anonab4538b80111::QBidiAlgorithm541     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;
Position__anonab4538b80111::QBidiAlgorithm::IsolatedRunSequenceIterator::Position555             Position(int current, int pos) : current(current), pos(pos) {}
556 
isValid__anonab4538b80111::QBidiAlgorithm::IsolatedRunSequenceIterator::Position557             bool isValid() const { return pos != -1; }
clear__anonab4538b80111::QBidiAlgorithm::IsolatedRunSequenceIterator::Position558             void clear() { pos = -1; }
559         };
IsolatedRunSequenceIterator__anonab4538b80111::QBidiAlgorithm::IsolatedRunSequenceIterator560         IsolatedRunSequenceIterator(const Vector<DirectionalRun> &runs, int i)
561             : runs(runs),
562               current(i)
563         {
564             pos = runs.at(current).start;
565         }
operator *__anonab4538b80111::QBidiAlgorithm::IsolatedRunSequenceIterator566         int operator *() const { return pos; }
atEnd__anonab4538b80111::QBidiAlgorithm::IsolatedRunSequenceIterator567         bool atEnd() const { return pos < 0; }
operator ++__anonab4538b80111::QBidiAlgorithm::IsolatedRunSequenceIterator568         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         }
setPosition__anonab4538b80111::QBidiAlgorithm::IsolatedRunSequenceIterator578         void setPosition(Position p) {
579             current = p.current;
580             pos = p.pos;
581         }
position__anonab4538b80111::QBidiAlgorithm::IsolatedRunSequenceIterator582         Position position() const {
583             return Position(current, pos);
584         }
operator !=__anonab4538b80111::QBidiAlgorithm::IsolatedRunSequenceIterator585         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 
resolveW1W2W3__anonab4538b80111::QBidiAlgorithm595     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 
resolveW4__anonab4538b80111::QBidiAlgorithm643     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 
resolveW5__anonab4538b80111::QBidiAlgorithm681     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 
resolveW6W7__anonab4538b80111::QBidiAlgorithm724     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 
isValid__anonab4538b80111::QBidiAlgorithm::BracketPair755         bool isValid() const { return second > 0; }
756 
containedDirection__anonab4538b80111::QBidiAlgorithm::BracketPair757         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;
Item__anonab4538b80111::QBidiAlgorithm::BracketStack::Item787             Item(uint pairedBracked, int position) : pairedBracked(pairedBracked), position(position) {}
788             uint pairedBracked = 0;
789             int position = 0;
790         };
791 
push__anonab4538b80111::QBidiAlgorithm::BracketStack792         void push(uint closingUnicode, int pos) {
793             if (position < MaxDepth)
794                 stack[position] = Item(closingUnicode, pos);
795             ++position;
796         }
match__anonab4538b80111::QBidiAlgorithm::BracketStack797         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 
overflowed__anonab4538b80111::QBidiAlgorithm::BracketStack817         bool overflowed() const { return position > MaxDepth; }
818     };
819 
resolveN0__anonab4538b80111::QBidiAlgorithm820     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(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 
resolveN1N2__anonab4538b80111::QBidiAlgorithm907     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 
resolveImplicitLevelsForIsolatedRun__anonab4538b80111::QBidiAlgorithm964     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 
resolveImplicitLevels__anonab4538b80111::QBidiAlgorithm1048     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 
checkForBidi__anonab4538b80111::QBidiAlgorithm1058     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 
process__anonab4538b80111::QBidiAlgorithm1078     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 
bidiReorder(int numItems,const quint8 * levels,int * visualOrder)1174 void 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 
1230 enum 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 */
qt_getDefaultJustificationOpportunities(const ushort * string,int length,const QGlyphLayout & g,ushort * log_clusters,int spaceAs)1250 static 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 
qt_getJustificationOpportunities(const ushort * string,int length,const QScriptItem & si,const QGlyphLayout & g,ushort * log_clusters)1284 static 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.
shapeLine(const QScriptLine & line)1327 void 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)
1358 extern bool qt_useHarfbuzzNG(); // defined in qfontengine.cpp
1359 #endif
1360 
applyVisibilityRules(ushort ucs,QGlyphLayout * glyphs,uint glyphPosition,QFontEngine * fontEngine)1361 static 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 
shapeText(int item) const1392 void 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     QVector<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 (Q_UNLIKELY(!shapingEnabled)) {
1514         ushort *log_clusters = logClusters(&si);
1515 
1516         int glyph_pos = 0;
1517         for (int i = 0; i < itemLength; ++i, ++glyph_pos) {
1518             log_clusters[i] = glyph_pos;
1519             initialGlyphs.attributes[glyph_pos].clusterStart = true;
1520             if (QChar::isHighSurrogate(string[i])
1521                     && i + 1 < itemLength
1522                     && QChar::isLowSurrogate(string[i + 1])) {
1523                 initialGlyphs.attributes[glyph_pos].dontPrint = !QChar::isPrint(QChar::surrogateToUcs4(string[i], string[i + 1]));
1524                 ++i;
1525                 log_clusters[i] = glyph_pos;
1526 
1527             } else {
1528                 initialGlyphs.attributes[glyph_pos].dontPrint = !QChar::isPrint(string[i]);
1529             }
1530 
1531             if (Q_UNLIKELY(!initialGlyphs.attributes[glyph_pos].dontPrint)) {
1532                 QFontEngine *actualFontEngine = fontEngine;
1533                 if (actualFontEngine->type() == QFontEngine::Multi) {
1534                     const uint engineIdx = initialGlyphs.glyphs[glyph_pos] >> 24;
1535                     actualFontEngine = static_cast<QFontEngineMulti *>(fontEngine)->engine(engineIdx);
1536                 }
1537 
1538                 applyVisibilityRules(string[i], &initialGlyphs, glyph_pos, actualFontEngine);
1539             }
1540         }
1541 
1542         si.num_glyphs = glyph_pos;
1543 #if QT_CONFIG(harfbuzz)
1544     } else if (Q_LIKELY(qt_useHarfbuzzNG())) {
1545         si.num_glyphs = shapeTextWithHarfbuzzNG(si, string, itemLength, fontEngine, itemBoundaries, kerningEnabled, letterSpacing != 0);
1546 #endif
1547     } else {
1548         si.num_glyphs = shapeTextWithHarfbuzz(si, string, itemLength, fontEngine, itemBoundaries, kerningEnabled);
1549     }
1550     if (Q_UNLIKELY(si.num_glyphs == 0)) {
1551         Q_UNREACHABLE(); // ### report shaping errors somehow
1552         return;
1553     }
1554 
1555 
1556     layoutData->used += si.num_glyphs;
1557 
1558     QGlyphLayout glyphs = shapedGlyphs(&si);
1559 
1560 #if QT_CONFIG(harfbuzz)
1561     if (Q_LIKELY(qt_useHarfbuzzNG()))
1562         qt_getJustificationOpportunities(string, itemLength, si, glyphs, logClusters(&si));
1563 #endif
1564 
1565     if (letterSpacing != 0) {
1566         for (int i = 1; i < si.num_glyphs; ++i) {
1567             if (glyphs.attributes[i].clusterStart) {
1568                 if (letterSpacingIsAbsolute)
1569                     glyphs.advances[i - 1] += letterSpacing;
1570                 else {
1571                     QFixed &advance = glyphs.advances[i - 1];
1572                     advance += (letterSpacing - 100) * advance / 100;
1573                 }
1574             }
1575         }
1576         if (letterSpacingIsAbsolute)
1577             glyphs.advances[si.num_glyphs - 1] += letterSpacing;
1578         else {
1579             QFixed &advance = glyphs.advances[si.num_glyphs - 1];
1580             advance += (letterSpacing - 100) * advance / 100;
1581         }
1582     }
1583     if (wordSpacing != 0) {
1584         for (int i = 0; i < si.num_glyphs; ++i) {
1585             if (glyphs.attributes[i].justification == Justification_Space
1586                 || glyphs.attributes[i].justification == Justification_Arabic_Space) {
1587                 // word spacing only gets added once to a consecutive run of spaces (see CSS spec)
1588                 if (i + 1 == si.num_glyphs
1589                     ||(glyphs.attributes[i+1].justification != Justification_Space
1590                        && glyphs.attributes[i+1].justification != Justification_Arabic_Space))
1591                     glyphs.advances[i] += wordSpacing;
1592             }
1593         }
1594     }
1595 
1596     for (int i = 0; i < si.num_glyphs; ++i)
1597         si.width += glyphs.advances[i] * !glyphs.attributes[i].dontPrint;
1598 }
1599 
1600 #if QT_CONFIG(harfbuzz)
1601 
1602 QT_BEGIN_INCLUDE_NAMESPACE
1603 
1604 #include "qharfbuzzng_p.h"
1605 
1606 QT_END_INCLUDE_NAMESPACE
1607 
shapeTextWithHarfbuzzNG(const QScriptItem & si,const ushort * string,int itemLength,QFontEngine * fontEngine,const QVector<uint> & itemBoundaries,bool kerningEnabled,bool hasLetterSpacing) const1608 int QTextEngine::shapeTextWithHarfbuzzNG(const QScriptItem &si,
1609                                          const ushort *string,
1610                                          int itemLength,
1611                                          QFontEngine *fontEngine,
1612                                          const QVector<uint> &itemBoundaries,
1613                                          bool kerningEnabled,
1614                                          bool hasLetterSpacing) const
1615 {
1616     uint glyphs_shaped = 0;
1617 
1618     hb_buffer_t *buffer = hb_buffer_create();
1619     hb_buffer_set_unicode_funcs(buffer, hb_qt_get_unicode_funcs());
1620     hb_buffer_pre_allocate(buffer, itemLength);
1621     if (Q_UNLIKELY(!hb_buffer_allocation_successful(buffer))) {
1622         hb_buffer_destroy(buffer);
1623         return 0;
1624     }
1625 
1626     hb_segment_properties_t props = HB_SEGMENT_PROPERTIES_DEFAULT;
1627     props.direction = si.analysis.bidiLevel % 2 ? HB_DIRECTION_RTL : HB_DIRECTION_LTR;
1628     QChar::Script script = QChar::Script(si.analysis.script);
1629     props.script = hb_qt_script_to_script(script);
1630     // ### props.language = hb_language_get_default_for_script(props.script);
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 #if defined(Q_OS_DARWIN)
1646         // ### temporary workaround for QTBUG-38113
1647         // CoreText throws away the PDF token, while the OpenType backend will replace it with
1648         // a zero-advance glyph. This becomes a real issue when PDF is the last character,
1649         // since it gets treated like if it were a grapheme extender, so we
1650         // temporarily replace it with some visible grapheme starter.
1651         bool endsWithPDF = actualFontEngine->type() == QFontEngine::Mac && string[item_pos + item_length - 1] == 0x202c;
1652         if (Q_UNLIKELY(endsWithPDF)) {
1653             uint num_glyphs;
1654             hb_glyph_info_t *infos = hb_buffer_get_glyph_infos(buffer, &num_glyphs);
1655             infos[num_glyphs - 1].codepoint = '.';
1656         }
1657 #endif
1658 
1659         hb_buffer_set_segment_properties(buffer, &props);
1660         hb_buffer_guess_segment_properties(buffer);
1661 
1662         uint buffer_flags = HB_BUFFER_FLAG_DEFAULT;
1663         // Symbol encoding used to encode various crap in the 32..255 character code range,
1664         // and thus might override U+00AD [SHY]; avoid hiding default ignorables
1665         if (Q_UNLIKELY(actualFontEngine->symbol))
1666             buffer_flags |= HB_BUFFER_FLAG_PRESERVE_DEFAULT_IGNORABLES;
1667         hb_buffer_set_flags(buffer, hb_buffer_flags_t(buffer_flags));
1668 
1669 
1670         // shape
1671         {
1672             hb_font_t *hb_font = hb_qt_font_get_for_engine(actualFontEngine);
1673             Q_ASSERT(hb_font);
1674             hb_qt_font_set_use_design_metrics(hb_font, option.useDesignMetrics() ? uint(QFontEngine::DesignMetrics) : 0); // ###
1675 
1676             // Ligatures are incompatible with custom letter spacing, so when a letter spacing is set,
1677             // we disable them for writing systems where they are purely cosmetic.
1678             bool scriptRequiresOpenType = ((script >= QChar::Script_Syriac && script <= QChar::Script_Sinhala)
1679                                          || script == QChar::Script_Khmer || script == QChar::Script_Nko);
1680 
1681             bool dontLigate = hasLetterSpacing && !scriptRequiresOpenType;
1682             const hb_feature_t features[5] = {
1683                 { HB_TAG('k','e','r','n'), !!kerningEnabled, 0, uint(-1) },
1684                 { HB_TAG('l','i','g','a'), !dontLigate, 0, uint(-1) },
1685                 { HB_TAG('c','l','i','g'), !dontLigate, 0, uint(-1) },
1686                 { HB_TAG('d','l','i','g'), !dontLigate, 0, uint(-1) },
1687                 { HB_TAG('h','l','i','g'), !dontLigate, 0, uint(-1) } };
1688             const int num_features = dontLigate ? 5 : 1;
1689 
1690             const char *const *shaper_list = nullptr;
1691 #if defined(Q_OS_DARWIN)
1692             // What's behind QFontEngine::FaceData::user_data isn't compatible between different font engines
1693             // - specifically functions in hb-coretext.cc would run into undefined behavior with data
1694             // from non-CoreText engine. The other shapers works with that engine just fine.
1695             if (actualFontEngine->type() != QFontEngine::Mac) {
1696                 static const char *s_shaper_list_without_coretext[] = {
1697                     "graphite2",
1698                     "ot",
1699                     "fallback",
1700                     nullptr
1701                 };
1702                 shaper_list = s_shaper_list_without_coretext;
1703             }
1704 #endif
1705 
1706             bool shapedOk = hb_shape_full(hb_font, buffer, features, num_features, shaper_list);
1707             if (Q_UNLIKELY(!shapedOk)) {
1708                 hb_buffer_destroy(buffer);
1709                 return 0;
1710             }
1711 
1712             if (Q_UNLIKELY(HB_DIRECTION_IS_BACKWARD(props.direction)))
1713                 hb_buffer_reverse(buffer);
1714         }
1715 
1716         const uint num_glyphs = hb_buffer_get_length(buffer);
1717         // ensure we have enough space for shaped glyphs and metrics
1718         if (Q_UNLIKELY(num_glyphs == 0 || !ensureSpace(glyphs_shaped + num_glyphs))) {
1719             hb_buffer_destroy(buffer);
1720             return 0;
1721         }
1722 
1723         // fetch the shaped glyphs and metrics
1724         QGlyphLayout g = availableGlyphs(&si).mid(glyphs_shaped, num_glyphs);
1725         ushort *log_clusters = logClusters(&si) + item_pos;
1726 
1727         hb_glyph_info_t *infos = hb_buffer_get_glyph_infos(buffer, nullptr);
1728         hb_glyph_position_t *positions = hb_buffer_get_glyph_positions(buffer, nullptr);
1729         uint str_pos = 0;
1730         uint last_cluster = ~0u;
1731         uint last_glyph_pos = glyphs_shaped;
1732         for (uint i = 0; i < num_glyphs; ++i, ++infos, ++positions) {
1733             g.glyphs[i] = infos->codepoint;
1734 
1735             g.advances[i] = QFixed::fromFixed(positions->x_advance);
1736             g.offsets[i].x = QFixed::fromFixed(positions->x_offset);
1737             g.offsets[i].y = QFixed::fromFixed(positions->y_offset);
1738 
1739             uint cluster = infos->cluster;
1740             if (Q_LIKELY(last_cluster != cluster)) {
1741                 g.attributes[i].clusterStart = true;
1742 
1743                 // fix up clusters so that the cluster indices will be monotonic
1744                 // and thus we never return out-of-order indices
1745                 while (last_cluster++ < cluster && str_pos < item_length)
1746                     log_clusters[str_pos++] = last_glyph_pos;
1747                 last_glyph_pos = i + glyphs_shaped;
1748                 last_cluster = cluster;
1749 
1750                 applyVisibilityRules(string[item_pos + str_pos], &g, i, actualFontEngine);
1751             }
1752         }
1753         while (str_pos < item_length)
1754             log_clusters[str_pos++] = last_glyph_pos;
1755 
1756 #if defined(Q_OS_DARWIN)
1757         if (Q_UNLIKELY(endsWithPDF)) {
1758             int last_glyph_idx = num_glyphs - 1;
1759             g.glyphs[last_glyph_idx] = 0xffff;
1760             g.advances[last_glyph_idx] = QFixed();
1761             g.offsets[last_glyph_idx].x = QFixed();
1762             g.offsets[last_glyph_idx].y = QFixed();
1763             g.attributes[last_glyph_idx].clusterStart = true;
1764             g.attributes[last_glyph_idx].dontPrint = true;
1765 
1766             log_clusters[item_length - 1] = glyphs_shaped + last_glyph_idx;
1767         }
1768 #endif
1769 
1770         if (Q_UNLIKELY(engineIdx != 0)) {
1771             for (quint32 i = 0; i < num_glyphs; ++i)
1772                 g.glyphs[i] |= (engineIdx << 24);
1773         }
1774 
1775 #ifdef Q_OS_DARWIN
1776         if (actualFontEngine->type() == QFontEngine::Mac) {
1777             if (actualFontEngine->fontDef.stretch != 100 && actualFontEngine->fontDef.stretch != QFont::AnyStretch) {
1778                 QFixed stretch = QFixed(int(actualFontEngine->fontDef.stretch)) / QFixed(100);
1779                 for (uint i = 0; i < num_glyphs; ++i)
1780                     g.advances[i] *= stretch;
1781             }
1782         }
1783 #endif
1784 
1785 QT_WARNING_PUSH
1786 QT_WARNING_DISABLE_DEPRECATED
1787         if (!actualFontEngine->supportsSubPixelPositions() || (actualFontEngine->fontDef.styleStrategy & QFont::ForceIntegerMetrics)) {
1788 QT_WARNING_POP
1789             for (uint i = 0; i < num_glyphs; ++i)
1790                 g.advances[i] = g.advances[i].round();
1791         }
1792 
1793         glyphs_shaped += num_glyphs;
1794     }
1795 
1796     hb_buffer_destroy(buffer);
1797 
1798     return glyphs_shaped;
1799 }
1800 
1801 #endif // harfbuzz
1802 
1803 
1804 QT_BEGIN_INCLUDE_NAMESPACE
1805 
1806 #include <private/qharfbuzz_p.h>
1807 
1808 QT_END_INCLUDE_NAMESPACE
1809 
1810 Q_STATIC_ASSERT(sizeof(HB_Glyph) == sizeof(glyph_t));
1811 Q_STATIC_ASSERT(sizeof(HB_Fixed) == sizeof(QFixed));
1812 Q_STATIC_ASSERT(sizeof(HB_FixedPoint) == sizeof(QFixedPoint));
1813 
moveGlyphData(const QGlyphLayout & destination,const QGlyphLayout & source,int num)1814 static inline void moveGlyphData(const QGlyphLayout &destination, const QGlyphLayout &source, int num)
1815 {
1816     if (num > 0 && destination.glyphs != source.glyphs)
1817         memmove(destination.glyphs, source.glyphs, num * sizeof(glyph_t));
1818 }
1819 
shapeTextWithHarfbuzz(const QScriptItem & si,const ushort * string,int itemLength,QFontEngine * fontEngine,const QVector<uint> & itemBoundaries,bool kerningEnabled) const1820 int QTextEngine::shapeTextWithHarfbuzz(const QScriptItem &si, const ushort *string, int itemLength, QFontEngine *fontEngine, const QVector<uint> &itemBoundaries, bool kerningEnabled) const
1821 {
1822     HB_ShaperItem entire_shaper_item;
1823     memset(&entire_shaper_item, 0, sizeof(entire_shaper_item));
1824     entire_shaper_item.string = reinterpret_cast<const HB_UChar16 *>(string);
1825     entire_shaper_item.stringLength = itemLength;
1826     entire_shaper_item.item.script = script_to_hbscript(si.analysis.script);
1827     entire_shaper_item.item.pos = 0;
1828     entire_shaper_item.item.length = itemLength;
1829     entire_shaper_item.item.bidiLevel = si.analysis.bidiLevel;
1830 
1831     entire_shaper_item.shaperFlags = 0;
1832     if (!kerningEnabled)
1833         entire_shaper_item.shaperFlags |= HB_ShaperFlag_NoKerning;
1834     if (option.useDesignMetrics())
1835         entire_shaper_item.shaperFlags |= HB_ShaperFlag_UseDesignMetrics;
1836 
1837     // ensure we are not asserting in HB_HeuristicSetGlyphAttributes()
1838     entire_shaper_item.num_glyphs = 0;
1839     for (int i = 0; i < itemLength; ++i, ++entire_shaper_item.num_glyphs) {
1840         if (QChar::isHighSurrogate(string[i]) && i + 1 < itemLength && QChar::isLowSurrogate(string[i + 1]))
1841             ++i;
1842     }
1843 
1844 
1845     int remaining_glyphs = entire_shaper_item.num_glyphs;
1846     int glyph_pos = 0;
1847     // for each item shape using harfbuzz and store the results in our layoutData's glyphs array.
1848     for (int k = 0; k < itemBoundaries.size(); k += 3) {
1849         HB_ShaperItem shaper_item = entire_shaper_item;
1850         shaper_item.item.pos = itemBoundaries[k];
1851         if (k + 4 < itemBoundaries.size()) {
1852             shaper_item.item.length = itemBoundaries[k + 3] - shaper_item.item.pos;
1853             shaper_item.num_glyphs = itemBoundaries[k + 4] - itemBoundaries[k + 1];
1854         } else { // last combo in the list, avoid out of bounds access.
1855             shaper_item.item.length -= shaper_item.item.pos - entire_shaper_item.item.pos;
1856             shaper_item.num_glyphs -= itemBoundaries[k + 1];
1857         }
1858         shaper_item.initialGlyphCount = shaper_item.num_glyphs;
1859         if (shaper_item.num_glyphs < shaper_item.item.length)
1860             shaper_item.num_glyphs = shaper_item.item.length;
1861 
1862         uint engineIdx = itemBoundaries[k + 2];
1863         QFontEngine *actualFontEngine = fontEngine;
1864         if (fontEngine->type() == QFontEngine::Multi) {
1865             actualFontEngine = static_cast<QFontEngineMulti *>(fontEngine)->engine(engineIdx);
1866 
1867             if ((si.analysis.bidiLevel % 2) == 0)
1868                 shaper_item.glyphIndicesPresent = true;
1869         }
1870 
1871         shaper_item.font = (HB_Font)actualFontEngine->harfbuzzFont();
1872         shaper_item.face = (HB_Face)actualFontEngine->harfbuzzFace();
1873 
1874         remaining_glyphs -= shaper_item.initialGlyphCount;
1875 
1876         QVarLengthArray<HB_GlyphAttributes, 128> hbGlyphAttributes;
1877         do {
1878             if (!ensureSpace(glyph_pos + shaper_item.num_glyphs + remaining_glyphs))
1879                 return 0;
1880             if (hbGlyphAttributes.size() < int(shaper_item.num_glyphs)) {
1881                 hbGlyphAttributes.resize(shaper_item.num_glyphs);
1882                 memset(hbGlyphAttributes.data(), 0, hbGlyphAttributes.size() * sizeof(HB_GlyphAttributes));
1883             }
1884 
1885             const QGlyphLayout g = availableGlyphs(&si).mid(glyph_pos);
1886             if (fontEngine->type() == QFontEngine::Multi && shaper_item.num_glyphs > shaper_item.item.length)
1887                 moveGlyphData(g.mid(shaper_item.num_glyphs), g.mid(shaper_item.initialGlyphCount), remaining_glyphs);
1888 
1889             shaper_item.glyphs = reinterpret_cast<HB_Glyph *>(g.glyphs);
1890             shaper_item.advances = reinterpret_cast<HB_Fixed *>(g.advances);
1891             shaper_item.offsets = reinterpret_cast<HB_FixedPoint *>(g.offsets);
1892             shaper_item.attributes = hbGlyphAttributes.data();
1893 
1894             if (engineIdx != 0 && shaper_item.glyphIndicesPresent) {
1895                 for (quint32 i = 0; i < shaper_item.initialGlyphCount; ++i)
1896                     shaper_item.glyphs[i] &= 0x00ffffff;
1897             }
1898 
1899             shaper_item.log_clusters = logClusters(&si) + shaper_item.item.pos - entire_shaper_item.item.pos;
1900         } while (!qShapeItem(&shaper_item)); // this does the actual shaping via harfbuzz.
1901 
1902         QGlyphLayout g = availableGlyphs(&si).mid(glyph_pos, shaper_item.num_glyphs);
1903         if (fontEngine->type() == QFontEngine::Multi)
1904             moveGlyphData(g.mid(shaper_item.num_glyphs), g.mid(shaper_item.initialGlyphCount), remaining_glyphs);
1905 
1906         for (quint32 i = 0; i < shaper_item.num_glyphs; ++i) {
1907             HB_GlyphAttributes hbAttrs = hbGlyphAttributes.at(i);
1908             QGlyphAttributes &attrs = g.attributes[i];
1909             attrs.clusterStart = hbAttrs.clusterStart;
1910             attrs.dontPrint = hbAttrs.dontPrint;
1911             attrs.justification = hbAttrs.justification;
1912         }
1913 
1914         for (quint32 i = 0; i < shaper_item.item.length; ++i) {
1915             // Workaround wrong log_clusters for surrogates (i.e. QTBUG-39875)
1916             if (shaper_item.log_clusters[i] >= shaper_item.num_glyphs)
1917                 shaper_item.log_clusters[i] = shaper_item.num_glyphs - 1;
1918             shaper_item.log_clusters[i] += glyph_pos;
1919         }
1920 
1921         if (kerningEnabled && !shaper_item.kerning_applied)
1922             actualFontEngine->doKerning(&g, option.useDesignMetrics() ? QFontEngine::DesignMetrics : QFontEngine::ShaperFlags{});
1923 
1924         if (engineIdx != 0) {
1925             for (quint32 i = 0; i < shaper_item.num_glyphs; ++i)
1926                 g.glyphs[i] |= (engineIdx << 24);
1927         }
1928 
1929         glyph_pos += shaper_item.num_glyphs;
1930     }
1931 
1932     return glyph_pos;
1933 }
1934 
init(QTextEngine * e)1935 void QTextEngine::init(QTextEngine *e)
1936 {
1937     e->ignoreBidi = false;
1938     e->cacheGlyphs = false;
1939     e->forceJustification = false;
1940     e->visualMovement = false;
1941     e->delayDecorations = false;
1942 
1943     e->layoutData = nullptr;
1944 
1945     e->minWidth = 0;
1946     e->maxWidth = 0;
1947 
1948     e->specialData = nullptr;
1949     e->stackEngine = false;
1950 #ifndef QT_NO_RAWFONT
1951     e->useRawFont = false;
1952 #endif
1953 }
1954 
QTextEngine()1955 QTextEngine::QTextEngine()
1956 {
1957     init(this);
1958 }
1959 
QTextEngine(const QString & str,const QFont & f)1960 QTextEngine::QTextEngine(const QString &str, const QFont &f)
1961     : text(str),
1962       fnt(f)
1963 {
1964     init(this);
1965 }
1966 
~QTextEngine()1967 QTextEngine::~QTextEngine()
1968 {
1969     if (!stackEngine)
1970         delete layoutData;
1971     delete specialData;
1972     resetFontEngineCache();
1973 }
1974 
attributes() const1975 const QCharAttributes *QTextEngine::attributes() const
1976 {
1977     if (layoutData && layoutData->haveCharAttributes)
1978         return (QCharAttributes *) layoutData->memory;
1979 
1980     itemize();
1981     if (! ensureSpace(layoutData->string.length()))
1982         return nullptr;
1983 
1984     QVarLengthArray<QUnicodeTools::ScriptItem> scriptItems(layoutData->items.size());
1985     for (int i = 0; i < layoutData->items.size(); ++i) {
1986         const QScriptItem &si = layoutData->items.at(i);
1987         scriptItems[i].position = si.position;
1988         scriptItems[i].script = si.analysis.script;
1989     }
1990 
1991     QUnicodeTools::initCharAttributes(reinterpret_cast<const ushort *>(layoutData->string.constData()),
1992                                       layoutData->string.length(),
1993                                       scriptItems.data(), scriptItems.size(),
1994                                       (QCharAttributes *)layoutData->memory,
1995                                       QUnicodeTools::CharAttributeOptions(QUnicodeTools::DefaultOptionsCompat
1996                                                                           | QUnicodeTools::HangulLineBreakTailoring));
1997 
1998 
1999     layoutData->haveCharAttributes = true;
2000     return (QCharAttributes *) layoutData->memory;
2001 }
2002 
shape(int item) const2003 void QTextEngine::shape(int item) const
2004 {
2005     auto &li = layoutData->items[item];
2006     if (li.analysis.flags == QScriptAnalysis::Object) {
2007         ensureSpace(1);
2008         if (block.docHandle()) {
2009             docLayout()->resizeInlineObject(QTextInlineObject(item, const_cast<QTextEngine *>(this)),
2010                                             li.position + block.position(),
2011                                             format(&li));
2012         }
2013         // fix log clusters to point to the previous glyph, as the object doesn't have a glyph of it's own.
2014         // This is required so that all entries in the array get initialized and are ordered correctly.
2015         if (layoutData->logClustersPtr) {
2016             ushort *lc = logClusters(&li);
2017             *lc = (lc != layoutData->logClustersPtr) ? lc[-1] : 0;
2018         }
2019     } else if (li.analysis.flags == QScriptAnalysis::Tab) {
2020         // set up at least the ascent/descent/leading of the script item for the tab
2021         fontEngine(li, &li.ascent, &li.descent, &li.leading);
2022         // see the comment above
2023         if (layoutData->logClustersPtr) {
2024             ushort *lc = logClusters(&li);
2025             *lc = (lc != layoutData->logClustersPtr) ? lc[-1] : 0;
2026         }
2027     } else {
2028         shapeText(item);
2029     }
2030 }
2031 
releaseCachedFontEngine(QFontEngine * fontEngine)2032 static inline void releaseCachedFontEngine(QFontEngine *fontEngine)
2033 {
2034     if (fontEngine && !fontEngine->ref.deref())
2035         delete fontEngine;
2036 }
2037 
resetFontEngineCache()2038 void QTextEngine::resetFontEngineCache()
2039 {
2040     releaseCachedFontEngine(feCache.prevFontEngine);
2041     releaseCachedFontEngine(feCache.prevScaledFontEngine);
2042     feCache.reset();
2043 }
2044 
invalidate()2045 void QTextEngine::invalidate()
2046 {
2047     freeMemory();
2048     minWidth = 0;
2049     maxWidth = 0;
2050 
2051     resetFontEngineCache();
2052 }
2053 
clearLineData()2054 void QTextEngine::clearLineData()
2055 {
2056     lines.clear();
2057 }
2058 
validate() const2059 void QTextEngine::validate() const
2060 {
2061     if (layoutData)
2062         return;
2063     layoutData = new LayoutData();
2064     if (block.docHandle()) {
2065         layoutData->string = block.text();
2066         const bool nextBlockValid = block.next().isValid();
2067         if (!nextBlockValid && option.flags() & QTextOption::ShowDocumentTerminator) {
2068             layoutData->string += QChar(0xA7);
2069         } else if (option.flags() & QTextOption::ShowLineAndParagraphSeparators) {
2070             layoutData->string += QLatin1Char(nextBlockValid ? 0xb6 : 0x20);
2071         }
2072 
2073     } else {
2074         layoutData->string = text;
2075     }
2076     if (specialData && specialData->preeditPosition != -1)
2077         layoutData->string.insert(specialData->preeditPosition, specialData->preeditText);
2078 }
2079 
itemize() const2080 void QTextEngine::itemize() const
2081 {
2082     validate();
2083     if (layoutData->items.size())
2084         return;
2085 
2086     int length = layoutData->string.length();
2087     if (!length)
2088         return;
2089 
2090     const ushort *string = reinterpret_cast<const ushort *>(layoutData->string.unicode());
2091 
2092     bool rtl = isRightToLeft();
2093 
2094     QVarLengthArray<QScriptAnalysis, 4096> scriptAnalysis(length);
2095     QScriptAnalysis *analysis = scriptAnalysis.data();
2096 
2097     QBidiAlgorithm bidi(layoutData->string.constData(), analysis, length, rtl);
2098     layoutData->hasBidi = bidi.process();
2099 
2100     {
2101         QVarLengthArray<uchar> scripts(length);
2102         QUnicodeTools::initScripts(string, length, scripts.data());
2103         for (int i = 0; i < length; ++i)
2104             analysis[i].script = scripts.at(i);
2105     }
2106 
2107     const ushort *uc = string;
2108     const ushort *e = uc + length;
2109     while (uc < e) {
2110         switch (*uc) {
2111         case QChar::ObjectReplacementCharacter:
2112             analysis->flags = QScriptAnalysis::Object;
2113             break;
2114         case QChar::LineSeparator:
2115             analysis->flags = QScriptAnalysis::LineOrParagraphSeparator;
2116             if (option.flags() & QTextOption::ShowLineAndParagraphSeparators) {
2117                 const int offset = uc - string;
2118                 layoutData->string.detach();
2119                 string = reinterpret_cast<const ushort *>(layoutData->string.unicode());
2120                 uc = string + offset;
2121                 e = string + length;
2122                 *const_cast<ushort*>(uc) = 0x21B5; // visual line separator
2123             }
2124             break;
2125         case QChar::Tabulation:
2126             analysis->flags = QScriptAnalysis::Tab;
2127             analysis->bidiLevel = bidi.baseLevel;
2128             break;
2129         case QChar::Space:
2130         case QChar::Nbsp:
2131             if (option.flags() & QTextOption::ShowTabsAndSpaces) {
2132                 analysis->flags = (*uc == QChar::Space) ? QScriptAnalysis::Space : QScriptAnalysis::Nbsp;
2133                 break;
2134             }
2135             Q_FALLTHROUGH();
2136         default:
2137             analysis->flags = QScriptAnalysis::None;
2138             break;
2139         }
2140 #if !QT_CONFIG(harfbuzz)
2141         analysis->script = hbscript_to_script(script_to_hbscript(analysis->script));
2142 #endif
2143         ++uc;
2144         ++analysis;
2145     }
2146     if (option.flags() & QTextOption::ShowLineAndParagraphSeparators) {
2147         (analysis-1)->flags = QScriptAnalysis::LineOrParagraphSeparator; // to exclude it from width
2148     }
2149 #if QT_CONFIG(harfbuzz)
2150     analysis = scriptAnalysis.data();
2151     if (!qt_useHarfbuzzNG()) {
2152         for (int i = 0; i < length; ++i)
2153             analysis[i].script = hbscript_to_script(script_to_hbscript(analysis[i].script));
2154     }
2155 #endif
2156 
2157     Itemizer itemizer(layoutData->string, scriptAnalysis.data(), layoutData->items);
2158 
2159     const QTextDocumentPrivate *p = block.docHandle();
2160     if (p) {
2161         SpecialData *s = specialData;
2162 
2163         QTextDocumentPrivate::FragmentIterator it = p->find(block.position());
2164         QTextDocumentPrivate::FragmentIterator end = p->find(block.position() + block.length() - 1); // -1 to omit the block separator char
2165         int format = it.value()->format;
2166 
2167         int prevPosition = 0;
2168         int position = prevPosition;
2169         while (1) {
2170             const QTextFragmentData * const frag = it.value();
2171             if (it == end || format != frag->format) {
2172                 if (s && position >= s->preeditPosition) {
2173                     position += s->preeditText.length();
2174                     s = nullptr;
2175                 }
2176                 Q_ASSERT(position <= length);
2177                 QFont::Capitalization capitalization =
2178                         formatCollection()->charFormat(format).hasProperty(QTextFormat::FontCapitalization)
2179                         ? formatCollection()->charFormat(format).fontCapitalization()
2180                         : formatCollection()->defaultFont().capitalization();
2181                 itemizer.generate(prevPosition, position - prevPosition, capitalization);
2182                 if (it == end) {
2183                     if (position < length)
2184                         itemizer.generate(position, length - position, capitalization);
2185                     break;
2186                 }
2187                 format = frag->format;
2188                 prevPosition = position;
2189             }
2190             position += frag->size_array[0];
2191             ++it;
2192         }
2193     } else {
2194 #ifndef QT_NO_RAWFONT
2195         if (useRawFont && specialData) {
2196             int lastIndex = 0;
2197             for (int i = 0; i < specialData->formats.size(); ++i) {
2198                 const QTextLayout::FormatRange &range = specialData->formats.at(i);
2199                 const QTextCharFormat &format = range.format;
2200                 if (format.hasProperty(QTextFormat::FontCapitalization)) {
2201                     itemizer.generate(lastIndex, range.start - lastIndex, QFont::MixedCase);
2202                     itemizer.generate(range.start, range.length, format.fontCapitalization());
2203                     lastIndex = range.start + range.length;
2204                 }
2205             }
2206             itemizer.generate(lastIndex, length - lastIndex, QFont::MixedCase);
2207         } else
2208 #endif
2209             itemizer.generate(0, length, static_cast<QFont::Capitalization> (fnt.d->capital));
2210     }
2211 
2212     addRequiredBoundaries();
2213     resolveFormats();
2214 }
2215 
isRightToLeft() const2216 bool QTextEngine::isRightToLeft() const
2217 {
2218     switch (option.textDirection()) {
2219     case Qt::LeftToRight:
2220         return false;
2221     case Qt::RightToLeft:
2222         return true;
2223     default:
2224         break;
2225     }
2226     if (!layoutData)
2227         itemize();
2228     // this places the cursor in the right position depending on the keyboard layout
2229     if (layoutData->string.isEmpty())
2230         return QGuiApplication::inputMethod()->inputDirection() == Qt::RightToLeft;
2231     return layoutData->string.isRightToLeft();
2232 }
2233 
2234 
findItem(int strPos,int firstItem) const2235 int QTextEngine::findItem(int strPos, int firstItem) const
2236 {
2237     itemize();
2238     if (strPos < 0 || strPos >= layoutData->string.size() || firstItem < 0)
2239         return -1;
2240 
2241     int left = firstItem + 1;
2242     int right = layoutData->items.size()-1;
2243     while(left <= right) {
2244         int middle = ((right-left)/2)+left;
2245         if (strPos > layoutData->items.at(middle).position)
2246             left = middle+1;
2247         else if (strPos < layoutData->items.at(middle).position)
2248             right = middle-1;
2249         else {
2250             return middle;
2251         }
2252     }
2253     return right;
2254 }
2255 
width(int from,int len) const2256 QFixed QTextEngine::width(int from, int len) const
2257 {
2258     itemize();
2259 
2260     QFixed w = 0;
2261 
2262 //     qDebug("QTextEngine::width(from = %d, len = %d), numItems=%d, strleng=%d", from,  len, items.size(), string.length());
2263     for (int i = 0; i < layoutData->items.size(); i++) {
2264         const QScriptItem *si = layoutData->items.constData() + i;
2265         int pos = si->position;
2266         int ilen = length(i);
2267 //          qDebug("item %d: from %d len %d", i, pos, ilen);
2268         if (pos >= from + len)
2269             break;
2270         if (pos + ilen > from) {
2271             if (!si->num_glyphs)
2272                 shape(i);
2273 
2274             if (si->analysis.flags == QScriptAnalysis::Object) {
2275                 w += si->width;
2276                 continue;
2277             } else if (si->analysis.flags == QScriptAnalysis::Tab) {
2278                 w += calculateTabWidth(i, w);
2279                 continue;
2280             }
2281 
2282 
2283             QGlyphLayout glyphs = shapedGlyphs(si);
2284             unsigned short *logClusters = this->logClusters(si);
2285 
2286 //             fprintf(stderr, "  logclusters:");
2287 //             for (int k = 0; k < ilen; k++)
2288 //                 fprintf(stderr, " %d", logClusters[k]);
2289 //             fprintf(stderr, "\n");
2290             // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
2291             int charFrom = from - pos;
2292             if (charFrom < 0)
2293                 charFrom = 0;
2294             int glyphStart = logClusters[charFrom];
2295             if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
2296                 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
2297                     charFrom++;
2298             if (charFrom < ilen) {
2299                 glyphStart = logClusters[charFrom];
2300                 int charEnd = from + len - 1 - pos;
2301                 if (charEnd >= ilen)
2302                     charEnd = ilen-1;
2303                 int glyphEnd = logClusters[charEnd];
2304                 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
2305                     charEnd++;
2306                 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
2307 
2308 //                 qDebug("char: start=%d end=%d / glyph: start = %d, end = %d", charFrom, charEnd, glyphStart, glyphEnd);
2309                 for (int i = glyphStart; i < glyphEnd; i++)
2310                     w += glyphs.advances[i] * !glyphs.attributes[i].dontPrint;
2311             }
2312         }
2313     }
2314 //     qDebug("   --> w= %d ", w);
2315     return w;
2316 }
2317 
boundingBox(int from,int len) const2318 glyph_metrics_t QTextEngine::boundingBox(int from,  int len) const
2319 {
2320     itemize();
2321 
2322     glyph_metrics_t gm;
2323 
2324     for (int i = 0; i < layoutData->items.size(); i++) {
2325         const QScriptItem *si = layoutData->items.constData() + i;
2326 
2327         int pos = si->position;
2328         int ilen = length(i);
2329         if (pos > from + len)
2330             break;
2331         if (pos + ilen > from) {
2332             if (!si->num_glyphs)
2333                 shape(i);
2334 
2335             if (si->analysis.flags == QScriptAnalysis::Object) {
2336                 gm.width += si->width;
2337                 continue;
2338             } else if (si->analysis.flags == QScriptAnalysis::Tab) {
2339                 gm.width += calculateTabWidth(i, gm.width);
2340                 continue;
2341             }
2342 
2343             unsigned short *logClusters = this->logClusters(si);
2344             QGlyphLayout glyphs = shapedGlyphs(si);
2345 
2346             // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
2347             int charFrom = from - pos;
2348             if (charFrom < 0)
2349                 charFrom = 0;
2350             int glyphStart = logClusters[charFrom];
2351             if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
2352                 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
2353                     charFrom++;
2354             if (charFrom < ilen) {
2355                 QFontEngine *fe = fontEngine(*si);
2356                 glyphStart = logClusters[charFrom];
2357                 int charEnd = from + len - 1 - pos;
2358                 if (charEnd >= ilen)
2359                     charEnd = ilen-1;
2360                 int glyphEnd = logClusters[charEnd];
2361                 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
2362                     charEnd++;
2363                 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
2364                 if (glyphStart <= glyphEnd ) {
2365                     glyph_metrics_t m = fe->boundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
2366                     gm.x = qMin(gm.x, m.x + gm.xoff);
2367                     gm.y = qMin(gm.y, m.y + gm.yoff);
2368                     gm.width = qMax(gm.width, m.width+gm.xoff);
2369                     gm.height = qMax(gm.height, m.height+gm.yoff);
2370                     gm.xoff += m.xoff;
2371                     gm.yoff += m.yoff;
2372                 }
2373             }
2374         }
2375     }
2376     return gm;
2377 }
2378 
tightBoundingBox(int from,int len) const2379 glyph_metrics_t QTextEngine::tightBoundingBox(int from,  int len) const
2380 {
2381     itemize();
2382 
2383     glyph_metrics_t gm;
2384 
2385     for (int i = 0; i < layoutData->items.size(); i++) {
2386         const QScriptItem *si = layoutData->items.constData() + i;
2387         int pos = si->position;
2388         int ilen = length(i);
2389         if (pos > from + len)
2390             break;
2391         if (pos + len > from) {
2392             if (!si->num_glyphs)
2393                 shape(i);
2394             unsigned short *logClusters = this->logClusters(si);
2395             QGlyphLayout glyphs = shapedGlyphs(si);
2396 
2397             // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
2398             int charFrom = from - pos;
2399             if (charFrom < 0)
2400                 charFrom = 0;
2401             int glyphStart = logClusters[charFrom];
2402             if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
2403                 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
2404                     charFrom++;
2405             if (charFrom < ilen) {
2406                 glyphStart = logClusters[charFrom];
2407                 int charEnd = from + len - 1 - pos;
2408                 if (charEnd >= ilen)
2409                     charEnd = ilen-1;
2410                 int glyphEnd = logClusters[charEnd];
2411                 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
2412                     charEnd++;
2413                 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
2414                 if (glyphStart <= glyphEnd ) {
2415                     QFontEngine *fe = fontEngine(*si);
2416                     glyph_metrics_t m = fe->tightBoundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
2417                     gm.x = qMin(gm.x, m.x + gm.xoff);
2418                     gm.y = qMin(gm.y, m.y + gm.yoff);
2419                     gm.width = qMax(gm.width, m.width+gm.xoff);
2420                     gm.height = qMax(gm.height, m.height+gm.yoff);
2421                     gm.xoff += m.xoff;
2422                     gm.yoff += m.yoff;
2423                 }
2424             }
2425         }
2426     }
2427     return gm;
2428 }
2429 
font(const QScriptItem & si) const2430 QFont QTextEngine::font(const QScriptItem &si) const
2431 {
2432     QFont font = fnt;
2433     if (hasFormats()) {
2434         QTextCharFormat f = format(&si);
2435         font = f.font();
2436 
2437         if (block.docHandle() && block.docHandle()->layout()) {
2438             // Make sure we get the right dpi on printers
2439             QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
2440             if (pdev)
2441                 font = QFont(font, pdev);
2442         } else {
2443             font = font.resolve(fnt);
2444         }
2445         QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
2446         if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
2447             if (font.pointSize() != -1)
2448                 font.setPointSize((font.pointSize() * 2) / 3);
2449             else
2450                 font.setPixelSize((font.pixelSize() * 2) / 3);
2451         }
2452     }
2453 
2454     if (si.analysis.flags == QScriptAnalysis::SmallCaps)
2455         font = font.d->smallCapsFont();
2456 
2457     return font;
2458 }
2459 
FontEngineCache()2460 QTextEngine::FontEngineCache::FontEngineCache()
2461 {
2462     reset();
2463 }
2464 
2465 //we cache the previous results of this function, as calling it numerous times with the same effective
2466 //input is common (and hard to cache at a higher level)
fontEngine(const QScriptItem & si,QFixed * ascent,QFixed * descent,QFixed * leading) const2467 QFontEngine *QTextEngine::fontEngine(const QScriptItem &si, QFixed *ascent, QFixed *descent, QFixed *leading) const
2468 {
2469     QFontEngine *engine = nullptr;
2470     QFontEngine *scaledEngine = nullptr;
2471     int script = si.analysis.script;
2472 
2473     QFont font = fnt;
2474 #ifndef QT_NO_RAWFONT
2475     if (useRawFont && rawFont.isValid()) {
2476         if (feCache.prevFontEngine && feCache.prevFontEngine->type() == QFontEngine::Multi && feCache.prevScript == script) {
2477             engine = feCache.prevFontEngine;
2478         } else {
2479             engine = QFontEngineMulti::createMultiFontEngine(rawFont.d->fontEngine, script);
2480             feCache.prevFontEngine = engine;
2481             feCache.prevScript = script;
2482             engine->ref.ref();
2483             if (feCache.prevScaledFontEngine) {
2484                 releaseCachedFontEngine(feCache.prevScaledFontEngine);
2485                 feCache.prevScaledFontEngine = nullptr;
2486             }
2487         }
2488         if (si.analysis.flags == QScriptAnalysis::SmallCaps) {
2489             if (feCache.prevScaledFontEngine) {
2490                 scaledEngine = feCache.prevScaledFontEngine;
2491             } else {
2492                 QFontEngine *scEngine = rawFont.d->fontEngine->cloneWithSize(smallCapsFraction * rawFont.pixelSize());
2493                 scEngine->ref.ref();
2494                 scaledEngine = QFontEngineMulti::createMultiFontEngine(scEngine, script);
2495                 scaledEngine->ref.ref();
2496                 feCache.prevScaledFontEngine = scaledEngine;
2497                 // If scEngine is not ref'ed by scaledEngine, make sure it is deallocated and not leaked.
2498                 if (!scEngine->ref.deref())
2499                     delete scEngine;
2500 
2501             }
2502         }
2503     } else
2504 #endif
2505     {
2506         if (hasFormats()) {
2507             if (feCache.prevFontEngine && feCache.prevPosition == si.position && feCache.prevLength == length(&si) && feCache.prevScript == script) {
2508                 engine = feCache.prevFontEngine;
2509                 scaledEngine = feCache.prevScaledFontEngine;
2510             } else {
2511                 QTextCharFormat f = format(&si);
2512                 font = f.font();
2513 
2514                 if (block.docHandle() && block.docHandle()->layout()) {
2515                     // Make sure we get the right dpi on printers
2516                     QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
2517                     if (pdev)
2518                         font = QFont(font, pdev);
2519                 } else {
2520                     font = font.resolve(fnt);
2521                 }
2522                 engine = font.d->engineForScript(script);
2523                 if (engine)
2524                     engine->ref.ref();
2525 
2526                 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
2527                 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
2528                     if (font.pointSize() != -1)
2529                         font.setPointSize((font.pointSize() * 2) / 3);
2530                     else
2531                         font.setPixelSize((font.pixelSize() * 2) / 3);
2532                     scaledEngine = font.d->engineForScript(script);
2533                     if (scaledEngine)
2534                         scaledEngine->ref.ref();
2535                 }
2536 
2537                 if (feCache.prevFontEngine)
2538                     releaseCachedFontEngine(feCache.prevFontEngine);
2539                 feCache.prevFontEngine = engine;
2540 
2541                 if (feCache.prevScaledFontEngine)
2542                     releaseCachedFontEngine(feCache.prevScaledFontEngine);
2543                 feCache.prevScaledFontEngine = scaledEngine;
2544 
2545                 feCache.prevScript = script;
2546                 feCache.prevPosition = si.position;
2547                 feCache.prevLength = length(&si);
2548             }
2549         } else {
2550             if (feCache.prevFontEngine && feCache.prevScript == script && feCache.prevPosition == -1)
2551                 engine = feCache.prevFontEngine;
2552             else {
2553                 engine = font.d->engineForScript(script);
2554 
2555                 if (engine)
2556                     engine->ref.ref();
2557                 if (feCache.prevFontEngine)
2558                     releaseCachedFontEngine(feCache.prevFontEngine);
2559                 feCache.prevFontEngine = engine;
2560 
2561                 feCache.prevScript = script;
2562                 feCache.prevPosition = -1;
2563                 feCache.prevLength = -1;
2564                 feCache.prevScaledFontEngine = nullptr;
2565             }
2566         }
2567 
2568         if (si.analysis.flags == QScriptAnalysis::SmallCaps) {
2569             QFontPrivate *p = font.d->smallCapsFontPrivate();
2570             scaledEngine = p->engineForScript(script);
2571         }
2572     }
2573 
2574     if (ascent) {
2575         *ascent = engine->ascent();
2576         *descent = engine->descent();
2577         *leading = engine->leading();
2578     }
2579 
2580     if (scaledEngine)
2581         return scaledEngine;
2582     return engine;
2583 }
2584 
2585 struct QJustificationPoint {
2586     int type;
2587     QFixed kashidaWidth;
2588     QGlyphLayout glyph;
2589 };
2590 
2591 Q_DECLARE_TYPEINFO(QJustificationPoint, Q_PRIMITIVE_TYPE);
2592 
set(QJustificationPoint * point,int type,const QGlyphLayout & glyph,QFontEngine * fe)2593 static void set(QJustificationPoint *point, int type, const QGlyphLayout &glyph, QFontEngine *fe)
2594 {
2595     point->type = type;
2596     point->glyph = glyph;
2597 
2598     if (type >= Justification_Arabic_Normal) {
2599         QChar ch(0x640); // Kashida character
2600 
2601         glyph_t kashidaGlyph = fe->glyphIndex(ch.unicode());
2602         if (kashidaGlyph != 0) {
2603             QGlyphLayout g;
2604             g.numGlyphs = 1;
2605             g.glyphs = &kashidaGlyph;
2606             g.advances = &point->kashidaWidth;
2607             fe->recalcAdvances(&g, { });
2608 
2609             if (point->kashidaWidth == 0)
2610                 point->type = Justification_Prohibited;
2611         } else {
2612             point->type = Justification_Prohibited;
2613             point->kashidaWidth = 0;
2614         }
2615     }
2616 }
2617 
2618 
justify(const QScriptLine & line)2619 void QTextEngine::justify(const QScriptLine &line)
2620 {
2621 //     qDebug("justify: line.gridfitted = %d, line.justified=%d", line.gridfitted, line.justified);
2622     if (line.gridfitted && line.justified)
2623         return;
2624 
2625     if (!line.gridfitted) {
2626         // redo layout in device metrics, then adjust
2627         const_cast<QScriptLine &>(line).gridfitted = true;
2628     }
2629 
2630     if ((option.alignment() & Qt::AlignHorizontal_Mask) != Qt::AlignJustify)
2631         return;
2632 
2633     itemize();
2634 
2635     if (!forceJustification) {
2636         int end = line.from + (int)line.length + line.trailingSpaces;
2637         if (end == layoutData->string.length())
2638             return; // no justification at end of paragraph
2639         if (end && layoutData->items.at(findItem(end - 1)).analysis.flags == QScriptAnalysis::LineOrParagraphSeparator)
2640             return; // no justification at the end of an explicitly separated line
2641     }
2642 
2643     // justify line
2644     int maxJustify = 0;
2645 
2646     // don't include trailing white spaces when doing justification
2647     int line_length = line.length;
2648     const QCharAttributes *a = attributes();
2649     if (! a)
2650         return;
2651     a += line.from;
2652     while (line_length && a[line_length-1].whiteSpace)
2653         --line_length;
2654     // subtract one char more, as we can't justfy after the last character
2655     --line_length;
2656 
2657     if (line_length <= 0)
2658         return;
2659 
2660     int firstItem = findItem(line.from);
2661     int lastItem = findItem(line.from + line_length - 1, firstItem);
2662     int nItems = (firstItem >= 0 && lastItem >= firstItem)? (lastItem-firstItem+1) : 0;
2663 
2664     QVarLengthArray<QJustificationPoint> justificationPoints;
2665     int nPoints = 0;
2666 //     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());
2667     QFixed minKashida = 0x100000;
2668 
2669     // we need to do all shaping before we go into the next loop, as we there
2670     // store pointers to the glyph data that could get reallocated by the shaping
2671     // process.
2672     for (int i = 0; i < nItems; ++i) {
2673         const QScriptItem &si = layoutData->items.at(firstItem + i);
2674         if (!si.num_glyphs)
2675             shape(firstItem + i);
2676     }
2677 
2678     for (int i = 0; i < nItems; ++i) {
2679         const QScriptItem &si = layoutData->items.at(firstItem + i);
2680 
2681         int kashida_type = Justification_Arabic_Normal;
2682         int kashida_pos = -1;
2683 
2684         int start = qMax(line.from - si.position, 0);
2685         int end = qMin(line.from + line_length - (int)si.position, length(firstItem+i));
2686 
2687         unsigned short *log_clusters = logClusters(&si);
2688 
2689         int gs = log_clusters[start];
2690         int ge = (end == length(firstItem+i) ? si.num_glyphs : log_clusters[end]);
2691 
2692         Q_ASSERT(ge <= si.num_glyphs);
2693 
2694         const QGlyphLayout g = shapedGlyphs(&si);
2695 
2696         for (int i = gs; i < ge; ++i) {
2697             g.justifications[i].type = QGlyphJustification::JustifyNone;
2698             g.justifications[i].nKashidas = 0;
2699             g.justifications[i].space_18d6 = 0;
2700 
2701             justificationPoints.resize(nPoints+3);
2702             int justification = g.attributes[i].justification;
2703 
2704             switch(justification) {
2705             case Justification_Prohibited:
2706                 break;
2707             case Justification_Space:
2708             case Justification_Arabic_Space:
2709                 if (kashida_pos >= 0) {
2710 //                     qDebug("kashida position at %d in word", kashida_pos);
2711                     set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
2712                     if (justificationPoints[nPoints].kashidaWidth > 0) {
2713                         minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
2714                         maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
2715                         ++nPoints;
2716                     }
2717                 }
2718                 kashida_pos = -1;
2719                 kashida_type = Justification_Arabic_Normal;
2720                 Q_FALLTHROUGH();
2721             case Justification_Character:
2722                 set(&justificationPoints[nPoints++], justification, g.mid(i), fontEngine(si));
2723                 maxJustify = qMax(maxJustify, justification);
2724                 break;
2725             case Justification_Arabic_Normal:
2726             case Justification_Arabic_Waw:
2727             case Justification_Arabic_BaRa:
2728             case Justification_Arabic_Alef:
2729             case Justification_Arabic_HahDal:
2730             case Justification_Arabic_Seen:
2731             case Justification_Arabic_Kashida:
2732                 if (justification >= kashida_type) {
2733                     kashida_pos = i;
2734                     kashida_type = justification;
2735                 }
2736             }
2737         }
2738         if (kashida_pos >= 0) {
2739             set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
2740             if (justificationPoints[nPoints].kashidaWidth > 0) {
2741                 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
2742                 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
2743                 ++nPoints;
2744             }
2745         }
2746     }
2747 
2748     QFixed leading = leadingSpaceWidth(line);
2749     QFixed need = line.width - line.textWidth - leading;
2750     if (need < 0) {
2751         // line overflows already!
2752         const_cast<QScriptLine &>(line).justified = true;
2753         return;
2754     }
2755 
2756 //     qDebug("doing justification: textWidth=%x, requested=%x, maxJustify=%d", line.textWidth.value(), line.width.value(), maxJustify);
2757 //     qDebug("     minKashida=%f, need=%f", minKashida.toReal(), need.toReal());
2758 
2759     // distribute in priority order
2760     if (maxJustify >= Justification_Arabic_Normal) {
2761         while (need >= minKashida) {
2762             for (int type = maxJustify; need >= minKashida && type >= Justification_Arabic_Normal; --type) {
2763                 for (int i = 0; need >= minKashida && i < nPoints; ++i) {
2764                     if (justificationPoints[i].type == type && justificationPoints[i].kashidaWidth <= need) {
2765                         justificationPoints[i].glyph.justifications->nKashidas++;
2766                         // ############
2767                         justificationPoints[i].glyph.justifications->space_18d6 += justificationPoints[i].kashidaWidth.value();
2768                         need -= justificationPoints[i].kashidaWidth;
2769 //                         qDebug("adding kashida type %d with width %x, neednow %x", type, justificationPoints[i].kashidaWidth, need.value());
2770                     }
2771                 }
2772             }
2773         }
2774     }
2775     Q_ASSERT(need >= 0);
2776     if (!need)
2777         goto end;
2778 
2779     maxJustify = qMin(maxJustify, int(Justification_Space));
2780     for (int type = maxJustify; need != 0 && type > 0; --type) {
2781         int n = 0;
2782         for (int i = 0; i < nPoints; ++i) {
2783             if (justificationPoints[i].type == type)
2784                 ++n;
2785         }
2786 //          qDebug("number of points for justification type %d: %d", type, n);
2787 
2788 
2789         if (!n)
2790             continue;
2791 
2792         for (int i = 0; i < nPoints; ++i) {
2793             if (justificationPoints[i].type == type) {
2794                 QFixed add = need/n;
2795 //                  qDebug("adding %x to glyph %x", add.value(), justificationPoints[i].glyph->glyph);
2796                 justificationPoints[i].glyph.justifications[0].space_18d6 = add.value();
2797                 need -= add;
2798                 --n;
2799             }
2800         }
2801 
2802         Q_ASSERT(!need);
2803     }
2804  end:
2805     const_cast<QScriptLine &>(line).justified = true;
2806 }
2807 
setDefaultHeight(QTextEngine * eng)2808 void QScriptLine::setDefaultHeight(QTextEngine *eng)
2809 {
2810     QFont f;
2811     QFontEngine *e;
2812 
2813     if (eng->block.docHandle() && eng->block.docHandle()->layout()) {
2814         f = eng->block.charFormat().font();
2815         // Make sure we get the right dpi on printers
2816         QPaintDevice *pdev = eng->block.docHandle()->layout()->paintDevice();
2817         if (pdev)
2818             f = QFont(f, pdev);
2819         e = f.d->engineForScript(QChar::Script_Common);
2820     } else {
2821         e = eng->fnt.d->engineForScript(QChar::Script_Common);
2822     }
2823 
2824     QFixed other_ascent = e->ascent();
2825     QFixed other_descent = e->descent();
2826     QFixed other_leading = e->leading();
2827     leading = qMax(leading + ascent, other_leading + other_ascent) - qMax(ascent, other_ascent);
2828     ascent = qMax(ascent, other_ascent);
2829     descent = qMax(descent, other_descent);
2830 }
2831 
LayoutData()2832 QTextEngine::LayoutData::LayoutData()
2833 {
2834     memory = nullptr;
2835     allocated = 0;
2836     memory_on_stack = false;
2837     used = 0;
2838     hasBidi = false;
2839     layoutState = LayoutEmpty;
2840     haveCharAttributes = false;
2841     logClustersPtr = nullptr;
2842     available_glyphs = 0;
2843 }
2844 
LayoutData(const QString & str,void ** stack_memory,int _allocated)2845 QTextEngine::LayoutData::LayoutData(const QString &str, void **stack_memory, int _allocated)
2846     : string(str)
2847 {
2848     allocated = _allocated;
2849 
2850     int space_charAttributes = sizeof(QCharAttributes)*string.length()/sizeof(void*) + 1;
2851     int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2852     available_glyphs = ((int)allocated - space_charAttributes - space_logClusters)*(int)sizeof(void*)/(int)QGlyphLayout::SpaceNeeded;
2853 
2854     if (available_glyphs < str.length()) {
2855         // need to allocate on the heap
2856         allocated = 0;
2857 
2858         memory_on_stack = false;
2859         memory = nullptr;
2860         logClustersPtr = nullptr;
2861     } else {
2862         memory_on_stack = true;
2863         memory = stack_memory;
2864         logClustersPtr = (unsigned short *)(memory + space_charAttributes);
2865 
2866         void *m = memory + space_charAttributes + space_logClusters;
2867         glyphLayout = QGlyphLayout(reinterpret_cast<char *>(m), str.length());
2868         glyphLayout.clear();
2869         memset(memory, 0, space_charAttributes*sizeof(void *));
2870     }
2871     used = 0;
2872     hasBidi = false;
2873     layoutState = LayoutEmpty;
2874     haveCharAttributes = false;
2875 }
2876 
~LayoutData()2877 QTextEngine::LayoutData::~LayoutData()
2878 {
2879     if (!memory_on_stack)
2880         free(memory);
2881     memory = nullptr;
2882 }
2883 
reallocate(int totalGlyphs)2884 bool QTextEngine::LayoutData::reallocate(int totalGlyphs)
2885 {
2886     Q_ASSERT(totalGlyphs >= glyphLayout.numGlyphs);
2887     if (memory_on_stack && available_glyphs >= totalGlyphs) {
2888         glyphLayout.grow(glyphLayout.data(), totalGlyphs);
2889         return true;
2890     }
2891 
2892     int space_charAttributes = sizeof(QCharAttributes)*string.length()/sizeof(void*) + 1;
2893     int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2894     int space_glyphs = (totalGlyphs * QGlyphLayout::SpaceNeeded) / sizeof(void *) + 2;
2895 
2896     int newAllocated = space_charAttributes + space_glyphs + space_logClusters;
2897     // These values can be negative if the length of string/glyphs causes overflow,
2898     // we can't layout such a long string all at once, so return false here to
2899     // indicate there is a failure
2900     if (space_charAttributes < 0 || space_logClusters < 0 || space_glyphs < 0 || newAllocated < allocated) {
2901         layoutState = LayoutFailed;
2902         return false;
2903     }
2904 
2905     void **newMem = (void **)::realloc(memory_on_stack ? nullptr : memory, newAllocated*sizeof(void *));
2906     if (!newMem) {
2907         layoutState = LayoutFailed;
2908         return false;
2909     }
2910     if (memory_on_stack)
2911         memcpy(newMem, memory, allocated*sizeof(void *));
2912     memory = newMem;
2913     memory_on_stack = false;
2914 
2915     void **m = memory;
2916     m += space_charAttributes;
2917     logClustersPtr = (unsigned short *) m;
2918     m += space_logClusters;
2919 
2920     const int space_preGlyphLayout = space_charAttributes + space_logClusters;
2921     if (allocated < space_preGlyphLayout)
2922         memset(memory + allocated, 0, (space_preGlyphLayout - allocated)*sizeof(void *));
2923 
2924     glyphLayout.grow(reinterpret_cast<char *>(m), totalGlyphs);
2925 
2926     allocated = newAllocated;
2927     return true;
2928 }
2929 
2930 // grow to the new size, copying the existing data to the new layout
grow(char * address,int totalGlyphs)2931 void QGlyphLayout::grow(char *address, int totalGlyphs)
2932 {
2933     QGlyphLayout oldLayout(address, numGlyphs);
2934     QGlyphLayout newLayout(address, totalGlyphs);
2935 
2936     if (numGlyphs) {
2937         // move the existing data
2938         memmove(newLayout.attributes, oldLayout.attributes, numGlyphs * sizeof(QGlyphAttributes));
2939         memmove(newLayout.justifications, oldLayout.justifications, numGlyphs * sizeof(QGlyphJustification));
2940         memmove(newLayout.advances, oldLayout.advances, numGlyphs * sizeof(QFixed));
2941         memmove(newLayout.glyphs, oldLayout.glyphs, numGlyphs * sizeof(glyph_t));
2942     }
2943 
2944     // clear the new data
2945     newLayout.clear(numGlyphs);
2946 
2947     *this = newLayout;
2948 }
2949 
freeMemory()2950 void QTextEngine::freeMemory()
2951 {
2952     if (!stackEngine) {
2953         delete layoutData;
2954         layoutData = nullptr;
2955     } else {
2956         layoutData->used = 0;
2957         layoutData->hasBidi = false;
2958         layoutData->layoutState = LayoutEmpty;
2959         layoutData->haveCharAttributes = false;
2960         layoutData->items.clear();
2961     }
2962     if (specialData)
2963         specialData->resolvedFormats.clear();
2964     for (int i = 0; i < lines.size(); ++i) {
2965         lines[i].justified = 0;
2966         lines[i].gridfitted = 0;
2967     }
2968 }
2969 
formatIndex(const QScriptItem * si) const2970 int QTextEngine::formatIndex(const QScriptItem *si) const
2971 {
2972     if (specialData && !specialData->resolvedFormats.isEmpty()) {
2973         QTextFormatCollection *collection = formatCollection();
2974         Q_ASSERT(collection);
2975         return collection->indexForFormat(specialData->resolvedFormats.at(si - &layoutData->items.at(0)));
2976     }
2977 
2978     QTextDocumentPrivate *p = block.docHandle();
2979     if (!p)
2980         return -1;
2981     int pos = si->position;
2982     if (specialData && si->position >= specialData->preeditPosition) {
2983         if (si->position < specialData->preeditPosition + specialData->preeditText.length())
2984             pos = qMax(qMin(block.length(), specialData->preeditPosition) - 1, 0);
2985         else
2986             pos -= specialData->preeditText.length();
2987     }
2988     QTextDocumentPrivate::FragmentIterator it = p->find(block.position() + pos);
2989     return it.value()->format;
2990 }
2991 
2992 
format(const QScriptItem * si) const2993 QTextCharFormat QTextEngine::format(const QScriptItem *si) const
2994 {
2995     if (const QTextFormatCollection *collection = formatCollection())
2996         return collection->charFormat(formatIndex(si));
2997     return QTextCharFormat();
2998 }
2999 
addRequiredBoundaries() const3000 void QTextEngine::addRequiredBoundaries() const
3001 {
3002     if (specialData) {
3003         for (int i = 0; i < specialData->formats.size(); ++i) {
3004             const QTextLayout::FormatRange &r = specialData->formats.at(i);
3005             setBoundary(r.start);
3006             setBoundary(r.start + r.length);
3007             //qDebug("adding boundaries %d %d", r.start, r.start+r.length);
3008         }
3009     }
3010 }
3011 
atWordSeparator(int position) const3012 bool QTextEngine::atWordSeparator(int position) const
3013 {
3014     const QChar c = layoutData->string.at(position);
3015     switch (c.unicode()) {
3016     case '.':
3017     case ',':
3018     case '?':
3019     case '!':
3020     case '@':
3021     case '#':
3022     case '$':
3023     case ':':
3024     case ';':
3025     case '-':
3026     case '<':
3027     case '>':
3028     case '[':
3029     case ']':
3030     case '(':
3031     case ')':
3032     case '{':
3033     case '}':
3034     case '=':
3035     case '/':
3036     case '+':
3037     case '%':
3038     case '&':
3039     case '^':
3040     case '*':
3041     case '\'':
3042     case '"':
3043     case '`':
3044     case '~':
3045     case '|':
3046     case '\\':
3047         return true;
3048     default:
3049         break;
3050     }
3051     return false;
3052 }
3053 
setPreeditArea(int position,const QString & preeditText)3054 void QTextEngine::setPreeditArea(int position, const QString &preeditText)
3055 {
3056     if (preeditText.isEmpty()) {
3057         if (!specialData)
3058             return;
3059         if (specialData->formats.isEmpty()) {
3060             delete specialData;
3061             specialData = nullptr;
3062         } else {
3063             specialData->preeditText = QString();
3064             specialData->preeditPosition = -1;
3065         }
3066     } else {
3067         if (!specialData)
3068             specialData = new SpecialData;
3069         specialData->preeditPosition = position;
3070         specialData->preeditText = preeditText;
3071     }
3072     invalidate();
3073     clearLineData();
3074 }
3075 
setFormats(const QVector<QTextLayout::FormatRange> & formats)3076 void QTextEngine::setFormats(const QVector<QTextLayout::FormatRange> &formats)
3077 {
3078     if (formats.isEmpty()) {
3079         if (!specialData)
3080             return;
3081         if (specialData->preeditText.isEmpty()) {
3082             delete specialData;
3083             specialData = nullptr;
3084         } else {
3085             specialData->formats.clear();
3086         }
3087     } else {
3088         if (!specialData) {
3089             specialData = new SpecialData;
3090             specialData->preeditPosition = -1;
3091         }
3092         specialData->formats = formats;
3093         indexFormats();
3094     }
3095     invalidate();
3096     clearLineData();
3097 }
3098 
indexFormats()3099 void QTextEngine::indexFormats()
3100 {
3101     QTextFormatCollection *collection = formatCollection();
3102     if (!collection) {
3103         Q_ASSERT(!block.docHandle());
3104         specialData->formatCollection.reset(new QTextFormatCollection);
3105         collection = specialData->formatCollection.data();
3106     }
3107 
3108     // replace with shared copies
3109     for (int i = 0; i < specialData->formats.size(); ++i) {
3110         QTextCharFormat &format = specialData->formats[i].format;
3111         format = collection->charFormat(collection->indexForFormat(format));
3112     }
3113 }
3114 
3115 /* These two helper functions are used to determine whether we need to insert a ZWJ character
3116    between the text that gets truncated and the ellipsis. This is important to get
3117    correctly shaped results for arabic text.
3118 */
nextCharJoins(const QString & string,int pos)3119 static inline bool nextCharJoins(const QString &string, int pos)
3120 {
3121     while (pos < string.length() && string.at(pos).category() == QChar::Mark_NonSpacing)
3122         ++pos;
3123     if (pos == string.length())
3124         return false;
3125     QChar::JoiningType joining = string.at(pos).joiningType();
3126     return joining != QChar::Joining_None && joining != QChar::Joining_Transparent;
3127 }
3128 
prevCharJoins(const QString & string,int pos)3129 static inline bool prevCharJoins(const QString &string, int pos)
3130 {
3131     while (pos > 0 && string.at(pos - 1).category() == QChar::Mark_NonSpacing)
3132         --pos;
3133     if (pos == 0)
3134         return false;
3135     QChar::JoiningType joining = string.at(pos - 1).joiningType();
3136     return joining == QChar::Joining_Dual || joining == QChar::Joining_Causing;
3137 }
3138 
isRetainableControlCode(QChar c)3139 static inline bool isRetainableControlCode(QChar c)
3140 {
3141     return (c.unicode() >= 0x202a && c.unicode() <= 0x202e) // LRE, RLE, PDF, LRO, RLO
3142             || (c.unicode() >= 0x200e && c.unicode() <= 0x200f) // LRM, RLM
3143             || (c.unicode() >= 0x2066 && c.unicode() <= 0x2069); // LRI, RLI, FSI, PDI
3144 }
3145 
stringMidRetainingBidiCC(const QString & string,const QString & ellidePrefix,const QString & ellideSuffix,int subStringFrom,int subStringTo,int midStart,int midLength)3146 static QString stringMidRetainingBidiCC(const QString &string,
3147                                         const QString &ellidePrefix,
3148                                         const QString &ellideSuffix,
3149                                         int subStringFrom,
3150                                         int subStringTo,
3151                                         int midStart,
3152                                         int midLength)
3153 {
3154     QString prefix;
3155     for (int i=subStringFrom; i<midStart; ++i) {
3156         QChar c = string.at(i);
3157         if (isRetainableControlCode(c))
3158             prefix += c;
3159     }
3160 
3161     QString suffix;
3162     for (int i=midStart + midLength; i<subStringTo; ++i) {
3163         QChar c = string.at(i);
3164         if (isRetainableControlCode(c))
3165             suffix += c;
3166     }
3167 
3168     return prefix + ellidePrefix + string.midRef(midStart, midLength) + ellideSuffix + suffix;
3169 }
3170 
elidedText(Qt::TextElideMode mode,const QFixed & width,int flags,int from,int count) const3171 QString QTextEngine::elidedText(Qt::TextElideMode mode, const QFixed &width, int flags, int from, int count) const
3172 {
3173 //    qDebug() << "elidedText; available width" << width.toReal() << "text width:" << this->width(0, layoutData->string.length()).toReal();
3174 
3175     if (flags & Qt::TextShowMnemonic) {
3176         itemize();
3177         QCharAttributes *attributes = const_cast<QCharAttributes *>(this->attributes());
3178         if (!attributes)
3179             return QString();
3180         for (int i = 0; i < layoutData->items.size(); ++i) {
3181             const QScriptItem &si = layoutData->items.at(i);
3182             if (!si.num_glyphs)
3183                 shape(i);
3184 
3185             unsigned short *logClusters = this->logClusters(&si);
3186             QGlyphLayout glyphs = shapedGlyphs(&si);
3187 
3188             const int end = si.position + length(&si);
3189             for (int i = si.position; i < end - 1; ++i) {
3190                 if (layoutData->string.at(i) == QLatin1Char('&')
3191                     && !attributes[i + 1].whiteSpace && attributes[i + 1].graphemeBoundary) {
3192                     const int gp = logClusters[i - si.position];
3193                     glyphs.attributes[gp].dontPrint = true;
3194                     // emulate grapheme cluster
3195                     attributes[i] = attributes[i + 1];
3196                     memset(attributes + i + 1, 0, sizeof(QCharAttributes));
3197                     if (layoutData->string.at(i + 1) == QLatin1Char('&'))
3198                         ++i;
3199                 }
3200             }
3201         }
3202     }
3203 
3204     validate();
3205 
3206     const int to = count >= 0 && count <= layoutData->string.length() - from
3207             ? from + count
3208             : layoutData->string.length();
3209 
3210     if (mode == Qt::ElideNone
3211         || this->width(from, layoutData->string.length()) <= width
3212         || to - from <= 1)
3213         return layoutData->string.mid(from, from - to);
3214 
3215     QFixed ellipsisWidth;
3216     QString ellipsisText;
3217     {
3218         QFontEngine *engine = fnt.d->engineForScript(QChar::Script_Common);
3219 
3220         QChar ellipsisChar(0x2026);
3221 
3222         // We only want to use the ellipsis character if it is from the main
3223         // font (not one of the fallbacks), since using a fallback font
3224         // will affect the metrics of the text, potentially causing it to shift
3225         // when it is being elided.
3226         if (engine->type() == QFontEngine::Multi) {
3227             QFontEngineMulti *multiEngine = static_cast<QFontEngineMulti *>(engine);
3228             multiEngine->ensureEngineAt(0);
3229             engine = multiEngine->engine(0);
3230         }
3231 
3232         glyph_t glyph = engine->glyphIndex(ellipsisChar.unicode());
3233 
3234         QGlyphLayout glyphs;
3235         glyphs.numGlyphs = 1;
3236         glyphs.glyphs = &glyph;
3237         glyphs.advances = &ellipsisWidth;
3238 
3239         if (glyph != 0) {
3240             engine->recalcAdvances(&glyphs, { });
3241 
3242             ellipsisText = ellipsisChar;
3243         } else {
3244             glyph = engine->glyphIndex('.');
3245             if (glyph != 0) {
3246                 engine->recalcAdvances(&glyphs, { });
3247 
3248                 ellipsisWidth *= 3;
3249                 ellipsisText = QStringLiteral("...");
3250             }
3251         }
3252     }
3253 
3254     const QFixed availableWidth = width - ellipsisWidth;
3255     if (availableWidth < 0)
3256         return QString();
3257 
3258     const QCharAttributes *attributes = this->attributes();
3259     if (!attributes)
3260         return QString();
3261 
3262     if (mode == Qt::ElideRight) {
3263         QFixed currentWidth;
3264         int pos;
3265         int nextBreak = from;
3266 
3267         do {
3268             pos = nextBreak;
3269 
3270             ++nextBreak;
3271             while (nextBreak < layoutData->string.length() && !attributes[nextBreak].graphemeBoundary)
3272                 ++nextBreak;
3273 
3274             currentWidth += this->width(pos, nextBreak - pos);
3275         } while (nextBreak < to
3276                  && currentWidth < availableWidth);
3277 
3278         if (nextCharJoins(layoutData->string, pos))
3279             ellipsisText.prepend(QChar(0x200d) /* ZWJ */);
3280 
3281         return stringMidRetainingBidiCC(layoutData->string,
3282                                         QString(), ellipsisText,
3283                                         from, to,
3284                                         from, pos - from);
3285     } else if (mode == Qt::ElideLeft) {
3286         QFixed currentWidth;
3287         int pos;
3288         int nextBreak = to;
3289 
3290         do {
3291             pos = nextBreak;
3292 
3293             --nextBreak;
3294             while (nextBreak > 0 && !attributes[nextBreak].graphemeBoundary)
3295                 --nextBreak;
3296 
3297             currentWidth += this->width(nextBreak, pos - nextBreak);
3298         } while (nextBreak > from
3299                  && currentWidth < availableWidth);
3300 
3301         if (prevCharJoins(layoutData->string, pos))
3302             ellipsisText.append(QChar(0x200d) /* ZWJ */);
3303 
3304         return stringMidRetainingBidiCC(layoutData->string,
3305                                         ellipsisText, QString(),
3306                                         from, to,
3307                                         pos, to - pos);
3308     } else if (mode == Qt::ElideMiddle) {
3309         QFixed leftWidth;
3310         QFixed rightWidth;
3311 
3312         int leftPos = from;
3313         int nextLeftBreak = from;
3314 
3315         int rightPos = to;
3316         int nextRightBreak = to;
3317 
3318         do {
3319             leftPos = nextLeftBreak;
3320             rightPos = nextRightBreak;
3321 
3322             ++nextLeftBreak;
3323             while (nextLeftBreak < layoutData->string.length() && !attributes[nextLeftBreak].graphemeBoundary)
3324                 ++nextLeftBreak;
3325 
3326             --nextRightBreak;
3327             while (nextRightBreak > from && !attributes[nextRightBreak].graphemeBoundary)
3328                 --nextRightBreak;
3329 
3330             leftWidth += this->width(leftPos, nextLeftBreak - leftPos);
3331             rightWidth += this->width(nextRightBreak, rightPos - nextRightBreak);
3332         } while (nextLeftBreak < to
3333                  && nextRightBreak > from
3334                  && leftWidth + rightWidth < availableWidth);
3335 
3336         if (nextCharJoins(layoutData->string, leftPos))
3337             ellipsisText.prepend(QChar(0x200d) /* ZWJ */);
3338         if (prevCharJoins(layoutData->string, rightPos))
3339             ellipsisText.append(QChar(0x200d) /* ZWJ */);
3340 
3341         return layoutData->string.midRef(from, leftPos - from) + ellipsisText + layoutData->string.midRef(rightPos, to - rightPos);
3342     }
3343 
3344     return layoutData->string.mid(from, to - from);
3345 }
3346 
setBoundary(int strPos) const3347 void QTextEngine::setBoundary(int strPos) const
3348 {
3349     const int item = findItem(strPos);
3350     if (item < 0)
3351         return;
3352 
3353     QScriptItem newItem = layoutData->items.at(item);
3354     if (newItem.position != strPos) {
3355         newItem.position = strPos;
3356         layoutData->items.insert(item + 1, newItem);
3357     }
3358 }
3359 
calculateTabWidth(int item,QFixed x) const3360 QFixed QTextEngine::calculateTabWidth(int item, QFixed x) const
3361 {
3362     const QScriptItem &si = layoutData->items[item];
3363 
3364     QFixed dpiScale = 1;
3365     if (block.docHandle() && block.docHandle()->layout()) {
3366         QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
3367         if (pdev)
3368             dpiScale = QFixed::fromReal(pdev->logicalDpiY() / qreal(qt_defaultDpiY()));
3369     } else {
3370         dpiScale = QFixed::fromReal(fnt.d->dpi / qreal(qt_defaultDpiY()));
3371     }
3372 
3373     QList<QTextOption::Tab> tabArray = option.tabs();
3374     if (!tabArray.isEmpty()) {
3375         if (isRightToLeft()) { // rebase the tabArray positions.
3376             auto isLeftOrRightTab = [](const QTextOption::Tab &tab) {
3377                 return tab.type == QTextOption::LeftTab || tab.type == QTextOption::RightTab;
3378             };
3379             const auto cbegin = tabArray.cbegin();
3380             const auto cend = tabArray.cend();
3381             const auto cit = std::find_if(cbegin, cend, isLeftOrRightTab);
3382             if (cit != cend) {
3383                 const int index = std::distance(cbegin, cit);
3384                 auto iter = tabArray.begin() + index;
3385                 const auto end = tabArray.end();
3386                 while (iter != end) {
3387                     QTextOption::Tab &tab = *iter;
3388                     if (tab.type == QTextOption::LeftTab)
3389                         tab.type = QTextOption::RightTab;
3390                     else if (tab.type == QTextOption::RightTab)
3391                         tab.type = QTextOption::LeftTab;
3392                     ++iter;
3393                 }
3394             }
3395         }
3396         for (const QTextOption::Tab &tabSpec : qAsConst(tabArray)) {
3397             QFixed tab = QFixed::fromReal(tabSpec.position) * dpiScale;
3398             if (tab > x) {  // this is the tab we need.
3399                 int tabSectionEnd = layoutData->string.count();
3400                 if (tabSpec.type == QTextOption::RightTab || tabSpec.type == QTextOption::CenterTab) {
3401                     // find next tab to calculate the width required.
3402                     tab = QFixed::fromReal(tabSpec.position);
3403                     for (int i=item + 1; i < layoutData->items.count(); i++) {
3404                         const QScriptItem &item = layoutData->items[i];
3405                         if (item.analysis.flags == QScriptAnalysis::TabOrObject) { // found it.
3406                             tabSectionEnd = item.position;
3407                             break;
3408                         }
3409                     }
3410                 }
3411                 else if (tabSpec.type == QTextOption::DelimiterTab)
3412                     // find delimitor character to calculate the width required
3413                     tabSectionEnd = qMax(si.position, layoutData->string.indexOf(tabSpec.delimiter, si.position) + 1);
3414 
3415                 if (tabSectionEnd > si.position) {
3416                     QFixed length;
3417                     // Calculate the length of text between this tab and the tabSectionEnd
3418                     for (int i=item; i < layoutData->items.count(); i++) {
3419                         const QScriptItem &item = layoutData->items.at(i);
3420                         if (item.position > tabSectionEnd || item.position <= si.position)
3421                             continue;
3422                         shape(i); // first, lets make sure relevant text is already shaped
3423                         if (item.analysis.flags == QScriptAnalysis::Object) {
3424                             length += item.width;
3425                             continue;
3426                         }
3427                         QGlyphLayout glyphs = this->shapedGlyphs(&item);
3428                         const int end = qMin(item.position + item.num_glyphs, tabSectionEnd) - item.position;
3429                         for (int i=0; i < end; i++)
3430                             length += glyphs.advances[i] * !glyphs.attributes[i].dontPrint;
3431                         if (end + item.position == tabSectionEnd && tabSpec.type == QTextOption::DelimiterTab) // remove half of matching char
3432                             length -= glyphs.advances[end] / 2 * !glyphs.attributes[end].dontPrint;
3433                     }
3434 
3435                     switch (tabSpec.type) {
3436                     case QTextOption::CenterTab:
3437                         length /= 2;
3438                         Q_FALLTHROUGH();
3439                     case QTextOption::DelimiterTab:
3440                     case QTextOption::RightTab:
3441                         tab = QFixed::fromReal(tabSpec.position) * dpiScale - length;
3442                         if (tab < x) // default to tab taking no space
3443                             return QFixed();
3444                         break;
3445                     case QTextOption::LeftTab:
3446                         break;
3447                     }
3448                 }
3449                 return tab - x;
3450             }
3451         }
3452     }
3453     QFixed tab = QFixed::fromReal(option.tabStopDistance());
3454     if (tab <= 0)
3455         tab = 80; // default
3456     tab *= dpiScale;
3457     QFixed nextTabPos = ((x / tab).truncate() + 1) * tab;
3458     QFixed tabWidth = nextTabPos - x;
3459 
3460     return tabWidth;
3461 }
3462 
3463 namespace {
3464 class FormatRangeComparatorByStart {
3465     const QVector<QTextLayout::FormatRange> &list;
3466 public:
FormatRangeComparatorByStart(const QVector<QTextLayout::FormatRange> & list)3467     FormatRangeComparatorByStart(const QVector<QTextLayout::FormatRange> &list) : list(list) { }
operator ()(int a,int b)3468     bool operator()(int a, int b) {
3469         return list.at(a).start < list.at(b).start;
3470     }
3471 };
3472 class FormatRangeComparatorByEnd {
3473     const QVector<QTextLayout::FormatRange> &list;
3474 public:
FormatRangeComparatorByEnd(const QVector<QTextLayout::FormatRange> & list)3475     FormatRangeComparatorByEnd(const QVector<QTextLayout::FormatRange> &list) : list(list) { }
operator ()(int a,int b)3476     bool operator()(int a, int b) {
3477         return list.at(a).start + list.at(a).length < list.at(b).start + list.at(b).length;
3478     }
3479 };
3480 }
3481 
resolveFormats() const3482 void QTextEngine::resolveFormats() const
3483 {
3484     if (!specialData || specialData->formats.isEmpty())
3485         return;
3486     Q_ASSERT(specialData->resolvedFormats.isEmpty());
3487 
3488     QTextFormatCollection *collection = formatCollection();
3489 
3490     QVector<QTextCharFormat> resolvedFormats(layoutData->items.count());
3491 
3492     QVarLengthArray<int, 64> formatsSortedByStart;
3493     formatsSortedByStart.reserve(specialData->formats.size());
3494     for (int i = 0; i < specialData->formats.size(); ++i) {
3495         if (specialData->formats.at(i).length >= 0)
3496             formatsSortedByStart.append(i);
3497     }
3498     QVarLengthArray<int, 64> formatsSortedByEnd = formatsSortedByStart;
3499     std::sort(formatsSortedByStart.begin(), formatsSortedByStart.end(),
3500               FormatRangeComparatorByStart(specialData->formats));
3501     std::sort(formatsSortedByEnd.begin(), formatsSortedByEnd.end(),
3502               FormatRangeComparatorByEnd(specialData->formats));
3503 
3504     QVarLengthArray<int, 16>  currentFormats;
3505     const int *startIt = formatsSortedByStart.constBegin();
3506     const int *endIt = formatsSortedByEnd.constBegin();
3507 
3508     for (int i = 0; i < layoutData->items.count(); ++i) {
3509         const QScriptItem *si = &layoutData->items.at(i);
3510         int end = si->position + length(si);
3511 
3512         while (startIt != formatsSortedByStart.constEnd() &&
3513             specialData->formats.at(*startIt).start <= si->position) {
3514             currentFormats.insert(std::upper_bound(currentFormats.begin(), currentFormats.end(), *startIt),
3515                                   *startIt);
3516             ++startIt;
3517         }
3518         while (endIt != formatsSortedByEnd.constEnd() &&
3519             specialData->formats.at(*endIt).start + specialData->formats.at(*endIt).length < end) {
3520             int *currentFormatIterator = std::lower_bound(currentFormats.begin(), currentFormats.end(), *endIt);
3521             if (*endIt < *currentFormatIterator)
3522                 currentFormatIterator = currentFormats.end();
3523             currentFormats.remove(currentFormatIterator - currentFormats.begin());
3524             ++endIt;
3525         }
3526 
3527         QTextCharFormat &format = resolvedFormats[i];
3528         if (block.docHandle()) {
3529             // when we have a docHandle, formatIndex might still return a valid index based
3530             // on the preeditPosition. for all other cases, we cleared the resolved format indices
3531             format = collection->charFormat(formatIndex(si));
3532         }
3533         if (!currentFormats.isEmpty()) {
3534             for (int cur : currentFormats) {
3535                 const QTextLayout::FormatRange &range = specialData->formats.at(cur);
3536                 Q_ASSERT(range.start <= si->position && range.start + range.length >= end);
3537                 format.merge(range.format);
3538             }
3539             format = collection->charFormat(collection->indexForFormat(format)); // get shared copy
3540         }
3541     }
3542 
3543     specialData->resolvedFormats = resolvedFormats;
3544 }
3545 
leadingSpaceWidth(const QScriptLine & line)3546 QFixed QTextEngine::leadingSpaceWidth(const QScriptLine &line)
3547 {
3548     if (!line.hasTrailingSpaces
3549         || (option.flags() & QTextOption::IncludeTrailingSpaces)
3550         || !isRightToLeft())
3551         return QFixed();
3552 
3553     return width(line.from + line.length, line.trailingSpaces);
3554 }
3555 
alignLine(const QScriptLine & line)3556 QFixed QTextEngine::alignLine(const QScriptLine &line)
3557 {
3558     QFixed x = 0;
3559     justify(line);
3560     // if width is QFIXED_MAX that means we used setNumColumns() and that implicitly makes this line left aligned.
3561     if (!line.justified && line.width != QFIXED_MAX) {
3562         int align = option.alignment();
3563         if (align & Qt::AlignJustify && isRightToLeft())
3564             align = Qt::AlignRight;
3565         if (align & Qt::AlignRight)
3566             x = line.width - (line.textAdvance);
3567         else if (align & Qt::AlignHCenter)
3568             x = (line.width - line.textAdvance)/2;
3569     }
3570     return x;
3571 }
3572 
offsetInLigature(const QScriptItem * si,int pos,int max,int glyph_pos)3573 QFixed QTextEngine::offsetInLigature(const QScriptItem *si, int pos, int max, int glyph_pos)
3574 {
3575     unsigned short *logClusters = this->logClusters(si);
3576     const QGlyphLayout &glyphs = shapedGlyphs(si);
3577 
3578     int offsetInCluster = 0;
3579     for (int i = pos - 1; i >= 0; i--) {
3580         if (logClusters[i] == glyph_pos)
3581             offsetInCluster++;
3582         else
3583             break;
3584     }
3585 
3586     // in the case that the offset is inside a (multi-character) glyph,
3587     // interpolate the position.
3588     if (offsetInCluster > 0) {
3589         int clusterLength = 0;
3590         for (int i = pos - offsetInCluster; i < max; i++) {
3591             if (logClusters[i] == glyph_pos)
3592                 clusterLength++;
3593             else
3594                 break;
3595         }
3596         if (clusterLength)
3597             return glyphs.advances[glyph_pos] * offsetInCluster / clusterLength;
3598     }
3599 
3600     return 0;
3601 }
3602 
3603 // Scan in logClusters[from..to-1] for glyph_pos
getClusterLength(unsigned short * logClusters,const QCharAttributes * attributes,int from,int to,int glyph_pos,int * start)3604 int QTextEngine::getClusterLength(unsigned short *logClusters,
3605                                   const QCharAttributes *attributes,
3606                                   int from, int to, int glyph_pos, int *start)
3607 {
3608     int clusterLength = 0;
3609     for (int i = from; i < to; i++) {
3610         if (logClusters[i] == glyph_pos && attributes[i].graphemeBoundary) {
3611             if (*start < 0)
3612                 *start = i;
3613             clusterLength++;
3614         }
3615         else if (clusterLength)
3616             break;
3617     }
3618     return clusterLength;
3619 }
3620 
positionInLigature(const QScriptItem * si,int end,QFixed x,QFixed edge,int glyph_pos,bool cursorOnCharacter)3621 int QTextEngine::positionInLigature(const QScriptItem *si, int end,
3622                                     QFixed x, QFixed edge, int glyph_pos,
3623                                     bool cursorOnCharacter)
3624 {
3625     unsigned short *logClusters = this->logClusters(si);
3626     int clusterStart = -1;
3627     int clusterLength = 0;
3628 
3629     if (si->analysis.script != QChar::Script_Common &&
3630         si->analysis.script != QChar::Script_Greek &&
3631         si->analysis.script != QChar::Script_Latin &&
3632         si->analysis.script != QChar::Script_Hiragana &&
3633         si->analysis.script != QChar::Script_Katakana &&
3634         si->analysis.script != QChar::Script_Bopomofo &&
3635         si->analysis.script != QChar::Script_Han) {
3636         if (glyph_pos == -1)
3637             return si->position + end;
3638         else {
3639             int i;
3640             for (i = 0; i < end; i++)
3641                 if (logClusters[i] == glyph_pos)
3642                     break;
3643             return si->position + i;
3644         }
3645     }
3646 
3647     if (glyph_pos == -1 && end > 0)
3648         glyph_pos = logClusters[end - 1];
3649     else {
3650         if (x <= edge)
3651             glyph_pos--;
3652     }
3653 
3654     const QCharAttributes *attrs = attributes() + si->position;
3655     logClusters = this->logClusters(si);
3656     clusterLength = getClusterLength(logClusters, attrs, 0, end, glyph_pos, &clusterStart);
3657 
3658     if (clusterLength) {
3659         const QGlyphLayout &glyphs = shapedGlyphs(si);
3660         QFixed glyphWidth = glyphs.effectiveAdvance(glyph_pos);
3661         // the approximate width of each individual element of the ligature
3662         QFixed perItemWidth = glyphWidth / clusterLength;
3663         if (perItemWidth <= 0)
3664             return si->position + clusterStart;
3665         QFixed left = x > edge ? edge : edge - glyphWidth;
3666         int n = ((x - left) / perItemWidth).floor().toInt();
3667         QFixed dist = x - left - n * perItemWidth;
3668         int closestItem = dist > (perItemWidth / 2) ? n + 1 : n;
3669         if (cursorOnCharacter && closestItem > 0)
3670             closestItem--;
3671         int pos = clusterStart + closestItem;
3672         // Jump to the next grapheme boundary
3673         while (pos < end && !attrs[pos].graphemeBoundary)
3674             pos++;
3675         return si->position + pos;
3676     }
3677     return si->position + end;
3678 }
3679 
previousLogicalPosition(int oldPos) const3680 int QTextEngine::previousLogicalPosition(int oldPos) const
3681 {
3682     const QCharAttributes *attrs = attributes();
3683     int len = block.isValid() ? block.length() - 1
3684                               : layoutData->string.length();
3685     Q_ASSERT(len <= layoutData->string.length());
3686     if (!attrs || oldPos <= 0 || oldPos > len)
3687         return oldPos;
3688 
3689     oldPos--;
3690     while (oldPos && !attrs[oldPos].graphemeBoundary)
3691         oldPos--;
3692     return oldPos;
3693 }
3694 
nextLogicalPosition(int oldPos) const3695 int QTextEngine::nextLogicalPosition(int oldPos) const
3696 {
3697     const QCharAttributes *attrs = attributes();
3698     int len = block.isValid() ? block.length() - 1
3699                               : layoutData->string.length();
3700     Q_ASSERT(len <= layoutData->string.length());
3701     if (!attrs || oldPos < 0 || oldPos >= len)
3702         return oldPos;
3703 
3704     oldPos++;
3705     while (oldPos < len && !attrs[oldPos].graphemeBoundary)
3706         oldPos++;
3707     return oldPos;
3708 }
3709 
lineNumberForTextPosition(int pos)3710 int QTextEngine::lineNumberForTextPosition(int pos)
3711 {
3712     if (!layoutData)
3713         itemize();
3714     if (pos == layoutData->string.length() && lines.size())
3715         return lines.size() - 1;
3716     for (int i = 0; i < lines.size(); ++i) {
3717         const QScriptLine& line = lines[i];
3718         if (line.from + line.length + line.trailingSpaces > pos)
3719             return i;
3720     }
3721     return -1;
3722 }
3723 
insertionPointsForLine(int lineNum)3724 std::vector<int> QTextEngine::insertionPointsForLine(int lineNum)
3725 {
3726     QTextLineItemIterator iterator(this, lineNum);
3727 
3728     std::vector<int> insertionPoints;
3729     insertionPoints.reserve(size_t(iterator.line.length));
3730 
3731     bool lastLine = lineNum >= lines.size() - 1;
3732 
3733     while (!iterator.atEnd()) {
3734         const QScriptItem &si = iterator.next();
3735 
3736         int end = iterator.itemEnd;
3737         if (lastLine && iterator.item == iterator.lastItem)
3738             ++end; // the last item in the last line -> insert eol position
3739         if (si.analysis.bidiLevel % 2) {
3740             for (int i = end - 1; i >= iterator.itemStart; --i)
3741                 insertionPoints.push_back(i);
3742         } else {
3743             for (int i = iterator.itemStart; i < end; ++i)
3744                 insertionPoints.push_back(i);
3745         }
3746     }
3747     return insertionPoints;
3748 }
3749 
endOfLine(int lineNum)3750 int QTextEngine::endOfLine(int lineNum)
3751 {
3752     const auto insertionPoints = insertionPointsForLine(lineNum);
3753     if (insertionPoints.size() > 0)
3754         return insertionPoints.back();
3755     return 0;
3756 }
3757 
beginningOfLine(int lineNum)3758 int QTextEngine::beginningOfLine(int lineNum)
3759 {
3760     const auto insertionPoints = insertionPointsForLine(lineNum);
3761     if (insertionPoints.size() > 0)
3762         return insertionPoints.front();
3763     return 0;
3764 }
3765 
positionAfterVisualMovement(int pos,QTextCursor::MoveOperation op)3766 int QTextEngine::positionAfterVisualMovement(int pos, QTextCursor::MoveOperation op)
3767 {
3768     itemize();
3769 
3770     bool moveRight = (op == QTextCursor::Right);
3771     bool alignRight = isRightToLeft();
3772     if (!layoutData->hasBidi)
3773         return moveRight ^ alignRight ? nextLogicalPosition(pos) : previousLogicalPosition(pos);
3774 
3775     int lineNum = lineNumberForTextPosition(pos);
3776     if (lineNum < 0)
3777         return pos;
3778 
3779     const auto insertionPoints = insertionPointsForLine(lineNum);
3780     for (size_t i = 0, max = insertionPoints.size(); i < max; ++i)
3781         if (pos == insertionPoints[i]) {
3782             if (moveRight) {
3783                 if (i + 1 < max)
3784                     return insertionPoints[i + 1];
3785             } else {
3786                 if (i > 0)
3787                     return insertionPoints[i - 1];
3788             }
3789 
3790             if (moveRight ^ alignRight) {
3791                 if (lineNum + 1 < lines.size())
3792                     return alignRight ? endOfLine(lineNum + 1) : beginningOfLine(lineNum + 1);
3793             }
3794             else {
3795                 if (lineNum > 0)
3796                     return alignRight ? beginningOfLine(lineNum - 1) : endOfLine(lineNum - 1);
3797             }
3798 
3799             break;
3800         }
3801 
3802     return pos;
3803 }
3804 
addItemDecoration(QPainter * painter,const QLineF & line,ItemDecorationList * decorationList)3805 void QTextEngine::addItemDecoration(QPainter *painter, const QLineF &line, ItemDecorationList *decorationList)
3806 {
3807     if (delayDecorations) {
3808         decorationList->append(ItemDecoration(line.x1(), line.x2(), line.y1(), painter->pen()));
3809     } else {
3810         painter->drawLine(line);
3811     }
3812 }
3813 
addUnderline(QPainter * painter,const QLineF & line)3814 void QTextEngine::addUnderline(QPainter *painter, const QLineF &line)
3815 {
3816     // qDebug() << "Adding underline:" << line;
3817     addItemDecoration(painter, line, &underlineList);
3818 }
3819 
addStrikeOut(QPainter * painter,const QLineF & line)3820 void QTextEngine::addStrikeOut(QPainter *painter, const QLineF &line)
3821 {
3822     addItemDecoration(painter, line, &strikeOutList);
3823 }
3824 
addOverline(QPainter * painter,const QLineF & line)3825 void QTextEngine::addOverline(QPainter *painter, const QLineF &line)
3826 {
3827     addItemDecoration(painter, line, &overlineList);
3828 }
3829 
drawItemDecorationList(QPainter * painter,const ItemDecorationList & decorationList)3830 void QTextEngine::drawItemDecorationList(QPainter *painter, const ItemDecorationList &decorationList)
3831 {
3832     // qDebug() << "Drawing" << decorationList.size() << "decorations";
3833     if (decorationList.isEmpty())
3834         return;
3835 
3836     for (const ItemDecoration &decoration : decorationList) {
3837         painter->setPen(decoration.pen);
3838         painter->drawLine(QLineF(decoration.x1, decoration.y, decoration.x2, decoration.y));
3839     }
3840 }
3841 
drawDecorations(QPainter * painter)3842 void QTextEngine::drawDecorations(QPainter *painter)
3843 {
3844     QPen oldPen = painter->pen();
3845 
3846     bool wasCompatiblePainting = painter->renderHints()
3847             & QPainter::Qt4CompatiblePainting;
3848 
3849     if (wasCompatiblePainting)
3850         painter->setRenderHint(QPainter::Qt4CompatiblePainting, false);
3851 
3852     adjustUnderlines();
3853     drawItemDecorationList(painter, underlineList);
3854     drawItemDecorationList(painter, strikeOutList);
3855     drawItemDecorationList(painter, overlineList);
3856 
3857     clearDecorations();
3858 
3859     if (wasCompatiblePainting)
3860         painter->setRenderHint(QPainter::Qt4CompatiblePainting);
3861 
3862     painter->setPen(oldPen);
3863 }
3864 
clearDecorations()3865 void QTextEngine::clearDecorations()
3866 {
3867     underlineList.clear();
3868     strikeOutList.clear();
3869     overlineList.clear();
3870 }
3871 
adjustUnderlines()3872 void QTextEngine::adjustUnderlines()
3873 {
3874     // qDebug() << __PRETTY_FUNCTION__ << underlineList.count() << "underlines";
3875     if (underlineList.isEmpty())
3876         return;
3877 
3878     ItemDecorationList::iterator start = underlineList.begin();
3879     ItemDecorationList::iterator end   = underlineList.end();
3880     ItemDecorationList::iterator it = start;
3881     qreal underlinePos = start->y;
3882     qreal penWidth = start->pen.widthF();
3883     qreal lastLineEnd = start->x1;
3884 
3885     while (it != end) {
3886         if (qFuzzyCompare(lastLineEnd, it->x1)) { // no gap between underlines
3887             underlinePos = qMax(underlinePos, it->y);
3888             penWidth = qMax(penWidth, it->pen.widthF());
3889         } else { // gap between this and the last underline
3890             adjustUnderlines(start, it, underlinePos, penWidth);
3891             start = it;
3892             underlinePos = start->y;
3893             penWidth = start->pen.widthF();
3894         }
3895         lastLineEnd = it->x2;
3896         ++it;
3897     }
3898 
3899     adjustUnderlines(start, end, underlinePos, penWidth);
3900 }
3901 
adjustUnderlines(ItemDecorationList::iterator start,ItemDecorationList::iterator end,qreal underlinePos,qreal penWidth)3902 void QTextEngine::adjustUnderlines(ItemDecorationList::iterator start,
3903                                    ItemDecorationList::iterator end,
3904                                    qreal underlinePos, qreal penWidth)
3905 {
3906     for (ItemDecorationList::iterator it = start; it != end; ++it) {
3907         it->y = underlinePos;
3908         it->pen.setWidthF(penWidth);
3909     }
3910 }
3911 
QStackTextEngine(const QString & string,const QFont & f)3912 QStackTextEngine::QStackTextEngine(const QString &string, const QFont &f)
3913     : QTextEngine(string, f),
3914       _layoutData(string, _memory, MemSize)
3915 {
3916     stackEngine = true;
3917     layoutData = &_layoutData;
3918 }
3919 
QTextItemInt(const QScriptItem & si,QFont * font,const QTextCharFormat & format)3920 QTextItemInt::QTextItemInt(const QScriptItem &si, QFont *font, const QTextCharFormat &format)
3921     : charFormat(format),
3922       f(font),
3923       fontEngine(font->d->engineForScript(si.analysis.script))
3924 {
3925     Q_ASSERT(fontEngine);
3926 
3927     initWithScriptItem(si);
3928 }
3929 
QTextItemInt(const QGlyphLayout & g,QFont * font,const QChar * chars_,int numChars,QFontEngine * fe,const QTextCharFormat & format)3930 QTextItemInt::QTextItemInt(const QGlyphLayout &g, QFont *font, const QChar *chars_, int numChars, QFontEngine *fe, const QTextCharFormat &format)
3931     : charFormat(format),
3932       num_chars(numChars),
3933       chars(chars_),
3934       f(font),
3935       glyphs(g),
3936       fontEngine(fe)
3937 {
3938 }
3939 
3940 // Fix up flags and underlineStyle with given info
initWithScriptItem(const QScriptItem & si)3941 void QTextItemInt::initWithScriptItem(const QScriptItem &si)
3942 {
3943     // explicitly initialize flags so that initFontAttributes can be called
3944     // multiple times on the same TextItem
3945     flags = { };
3946     if (si.analysis.bidiLevel %2)
3947         flags |= QTextItem::RightToLeft;
3948     ascent = si.ascent;
3949     descent = si.descent;
3950 
3951     if (charFormat.hasProperty(QTextFormat::TextUnderlineStyle)) {
3952         underlineStyle = charFormat.underlineStyle();
3953     } else if (charFormat.boolProperty(QTextFormat::FontUnderline)
3954                || f->d->underline) {
3955         underlineStyle = QTextCharFormat::SingleUnderline;
3956     }
3957 
3958     // compat
3959     if (underlineStyle == QTextCharFormat::SingleUnderline)
3960         flags |= QTextItem::Underline;
3961 
3962     if (f->d->overline || charFormat.fontOverline())
3963         flags |= QTextItem::Overline;
3964     if (f->d->strikeOut || charFormat.fontStrikeOut())
3965         flags |= QTextItem::StrikeOut;
3966 }
3967 
midItem(QFontEngine * fontEngine,int firstGlyphIndex,int numGlyphs) const3968 QTextItemInt QTextItemInt::midItem(QFontEngine *fontEngine, int firstGlyphIndex, int numGlyphs) const
3969 {
3970     QTextItemInt ti = *this;
3971     const int end = firstGlyphIndex + numGlyphs;
3972     ti.glyphs = glyphs.mid(firstGlyphIndex, numGlyphs);
3973     ti.fontEngine = fontEngine;
3974 
3975     if (logClusters && chars) {
3976         const int logClusterOffset = logClusters[0];
3977         while (logClusters[ti.chars - chars] - logClusterOffset < firstGlyphIndex)
3978             ++ti.chars;
3979 
3980         ti.logClusters += (ti.chars - chars);
3981 
3982         ti.num_chars = 0;
3983         int char_start = ti.chars - chars;
3984         while (char_start + ti.num_chars < num_chars && ti.logClusters[ti.num_chars] - logClusterOffset < end)
3985             ++ti.num_chars;
3986     }
3987     return ti;
3988 }
3989 
3990 
qt_true_matrix(qreal w,qreal h,const QTransform & x)3991 QTransform qt_true_matrix(qreal w, qreal h, const QTransform &x)
3992 {
3993     QRectF rect = x.mapRect(QRectF(0, 0, w, h));
3994     return x * QTransform::fromTranslate(-rect.x(), -rect.y());
3995 }
3996 
3997 
transformed(const QTransform & matrix) const3998 glyph_metrics_t glyph_metrics_t::transformed(const QTransform &matrix) const
3999 {
4000     if (matrix.type() < QTransform::TxTranslate)
4001         return *this;
4002 
4003     glyph_metrics_t m = *this;
4004 
4005     qreal w = width.toReal();
4006     qreal h = height.toReal();
4007     QTransform xform = qt_true_matrix(w, h, matrix);
4008 
4009     QRectF rect(0, 0, w, h);
4010     rect = xform.mapRect(rect);
4011     m.width = QFixed::fromReal(rect.width());
4012     m.height = QFixed::fromReal(rect.height());
4013 
4014     QLineF l = xform.map(QLineF(x.toReal(), y.toReal(), xoff.toReal(), yoff.toReal()));
4015 
4016     m.x = QFixed::fromReal(l.x1());
4017     m.y = QFixed::fromReal(l.y1());
4018 
4019     // The offset is relative to the baseline which is why we use dx/dy of the line
4020     m.xoff = QFixed::fromReal(l.dx());
4021     m.yoff = QFixed::fromReal(l.dy());
4022 
4023     return m;
4024 }
4025 
QTextLineItemIterator(QTextEngine * _eng,int _lineNum,const QPointF & pos,const QTextLayout::FormatRange * _selection)4026 QTextLineItemIterator::QTextLineItemIterator(QTextEngine *_eng, int _lineNum, const QPointF &pos,
4027                                              const QTextLayout::FormatRange *_selection)
4028     : eng(_eng),
4029       line(eng->lines[_lineNum]),
4030       si(nullptr),
4031       lineNum(_lineNum),
4032       lineEnd(line.from + line.length),
4033       firstItem(eng->findItem(line.from)),
4034       lastItem(eng->findItem(lineEnd - 1, firstItem)),
4035       nItems((firstItem >= 0 && lastItem >= firstItem)? (lastItem-firstItem+1) : 0),
4036       logicalItem(-1),
4037       item(-1),
4038       visualOrder(nItems),
4039       selection(_selection)
4040 {
4041     x = QFixed::fromReal(pos.x());
4042 
4043     x += line.x;
4044 
4045     x += eng->alignLine(line);
4046 
4047     QVarLengthArray<uchar> levels(nItems);
4048     for (int i = 0; i < nItems; ++i)
4049         levels[i] = eng->layoutData->items.at(i + firstItem).analysis.bidiLevel;
4050     QTextEngine::bidiReorder(nItems, levels.data(), visualOrder.data());
4051 
4052     eng->shapeLine(line);
4053 }
4054 
next()4055 QScriptItem &QTextLineItemIterator::next()
4056 {
4057     x += itemWidth;
4058 
4059     ++logicalItem;
4060     item = visualOrder[logicalItem] + firstItem;
4061     itemLength = eng->length(item);
4062     si = &eng->layoutData->items[item];
4063     if (!si->num_glyphs)
4064         eng->shape(item);
4065 
4066     itemStart = qMax(line.from, si->position);
4067     itemEnd = qMin(lineEnd, si->position + itemLength);
4068 
4069     if (si->analysis.flags >= QScriptAnalysis::TabOrObject) {
4070         glyphsStart = 0;
4071         glyphsEnd = 1;
4072         itemWidth = si->width;
4073         return *si;
4074     }
4075 
4076     unsigned short *logClusters = eng->logClusters(si);
4077     QGlyphLayout glyphs = eng->shapedGlyphs(si);
4078 
4079     glyphsStart = logClusters[itemStart - si->position];
4080     glyphsEnd = (itemEnd == si->position + itemLength) ? si->num_glyphs : logClusters[itemEnd - si->position];
4081 
4082     // show soft-hyphen at line-break
4083     if (si->position + itemLength >= lineEnd
4084         && eng->layoutData->string.at(lineEnd - 1).unicode() == QChar::SoftHyphen)
4085         glyphs.attributes[glyphsEnd - 1].dontPrint = false;
4086 
4087     itemWidth = 0;
4088     for (int g = glyphsStart; g < glyphsEnd; ++g)
4089         itemWidth += glyphs.effectiveAdvance(g);
4090 
4091     return *si;
4092 }
4093 
getSelectionBounds(QFixed * selectionX,QFixed * selectionWidth) const4094 bool QTextLineItemIterator::getSelectionBounds(QFixed *selectionX, QFixed *selectionWidth) const
4095 {
4096     *selectionX = *selectionWidth = 0;
4097 
4098     if (!selection)
4099         return false;
4100 
4101     if (si->analysis.flags >= QScriptAnalysis::TabOrObject) {
4102         if (si->position >= selection->start + selection->length
4103             || si->position + itemLength <= selection->start)
4104             return false;
4105 
4106         *selectionX = x;
4107         *selectionWidth = itemWidth;
4108     } else {
4109         unsigned short *logClusters = eng->logClusters(si);
4110         QGlyphLayout glyphs = eng->shapedGlyphs(si);
4111 
4112         int from = qMax(itemStart, selection->start) - si->position;
4113         int to = qMin(itemEnd, selection->start + selection->length) - si->position;
4114         if (from >= to)
4115             return false;
4116 
4117         int start_glyph = logClusters[from];
4118         int end_glyph = (to == itemLength) ? si->num_glyphs : logClusters[to];
4119         QFixed soff;
4120         QFixed swidth;
4121         if (si->analysis.bidiLevel %2) {
4122             for (int g = glyphsEnd - 1; g >= end_glyph; --g)
4123                 soff += glyphs.effectiveAdvance(g);
4124             for (int g = end_glyph - 1; g >= start_glyph; --g)
4125                 swidth += glyphs.effectiveAdvance(g);
4126         } else {
4127             for (int g = glyphsStart; g < start_glyph; ++g)
4128                 soff += glyphs.effectiveAdvance(g);
4129             for (int g = start_glyph; g < end_glyph; ++g)
4130                 swidth += glyphs.effectiveAdvance(g);
4131         }
4132 
4133         // If the starting character is in the middle of a ligature,
4134         // selection should only contain the right part of that ligature
4135         // glyph, so we need to get the width of the left part here and
4136         // add it to *selectionX
4137         QFixed leftOffsetInLigature = eng->offsetInLigature(si, from, to, start_glyph);
4138         *selectionX = x + soff + leftOffsetInLigature;
4139         *selectionWidth = swidth - leftOffsetInLigature;
4140         // If the ending character is also part of a ligature, swidth does
4141         // not contain that part yet, we also need to find out the width of
4142         // that left part
4143         *selectionWidth += eng->offsetInLigature(si, to, itemLength, end_glyph);
4144     }
4145     return true;
4146 }
4147 
4148 QT_END_NAMESPACE
4149