1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtGui module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
43 #include "qtextformat.h"
44 #include "qtextformat_p.h"
45 #include "qtextengine_p.h"
46 #include "qabstracttextdocumentlayout.h"
47 #include "qtextlayout.h"
48 #include "qtextboundaryfinder.h"
49 #include "qvarlengtharray.h"
52 #include "qfontengine_p.h"
54 #include <private/qunicodetables_p.h>
55 #include <private/qunicodetools_p.h>
56 #include "qtextdocument_p.h"
58 #include "qrawfont_p.h"
59 #include <qguiapplication.h>
60 #include <qinputmethod.h>
63 #include "qfontengine_qpa_p.h"
67 static const float smallCapsFraction = 0.7f;
70 // Helper class used in QTextEngine::itemize
71 // keep it out here to allow us to keep supporting various compilers.
74 Itemizer(const QString &string, const QScriptAnalysis *analysis, QScriptItemArray &items)
86 /// generate the script items
87 /// The caps parameter is used to choose the algoritm of splitting text and assiging roles to the textitems
88 void generate(int start, int length, QFont::Capitalization caps)
90 if ((int)caps == (int)QFont::SmallCaps)
91 generateScriptItemsSmallCaps(reinterpret_cast<const ushort *>(m_string.unicode()), start, length);
92 else if(caps == QFont::Capitalize)
93 generateScriptItemsCapitalize(start, length);
94 else if(caps != QFont::MixedCase) {
95 generateScriptItemsAndChangeCase(start, length,
96 caps == QFont::AllLowercase ? QScriptAnalysis::Lowercase : QScriptAnalysis::Uppercase);
99 generateScriptItems(start, length);
103 enum { MaxItemLength = 4096 };
105 void generateScriptItemsAndChangeCase(int start, int length, QScriptAnalysis::Flags flags)
107 generateScriptItems(start, length);
108 if (m_items.isEmpty()) // the next loop won't work in that case
110 QScriptItemArray::Iterator iter = m_items.end();
113 if (iter->analysis.flags < QScriptAnalysis::TabOrObject)
114 iter->analysis.flags = flags;
115 } while (iter->position > start);
118 void generateScriptItems(int start, int length)
122 const int end = start + length;
123 for (int i = start + 1; i < end; ++i) {
124 // According to the unicode spec we should be treating characters in the Common script
125 // (punctuation, spaces, etc) as being the same script as the surrounding text for the
126 // purpose of splitting up text. This is important because, for example, a fullstop
127 // (0x2E) can be used to indicate an abbreviation and so must be treated as part of a
128 // word. Thus it must be passed along with the word in languages that have to calculate
129 // word breaks. For example the thai word "ครม." has no word breaks but the word "ครม"
131 // Unfortuntely because we split up the strings for both wordwrapping and for setting
132 // the font and because Japanese and Chinese are also aliases of the script "Common",
133 // doing this would break too many things. So instead we only pass the full stop
134 // along, and nothing else.
135 if (m_analysis[i].bidiLevel == m_analysis[start].bidiLevel
136 && m_analysis[i].flags == m_analysis[start].flags
137 && (m_analysis[i].script == m_analysis[start].script || m_string[i] == QLatin1Char('.'))
138 && m_analysis[i].flags < QScriptAnalysis::SpaceTabOrObject
139 && i - start < MaxItemLength)
141 m_items.append(QScriptItem(start, m_analysis[start]));
144 m_items.append(QScriptItem(start, m_analysis[start]));
147 void generateScriptItemsCapitalize(int start, int length)
153 m_splitter = new QTextBoundaryFinder(QTextBoundaryFinder::Word,
154 m_string.constData(), m_string.length(),
155 /*buffer*/0, /*buffer size*/0);
157 m_splitter->setPosition(start);
158 QScriptAnalysis itemAnalysis = m_analysis[start];
160 if (m_splitter->boundaryReasons() & QTextBoundaryFinder::StartWord) {
161 itemAnalysis.flags = QScriptAnalysis::Uppercase;
162 m_splitter->toNextBoundary();
165 const int end = start + length;
166 for (int i = start + 1; i < end; ++i) {
168 bool atWordBoundary = false;
170 if (i == m_splitter->position()) {
171 if (m_splitter->boundaryReasons() & QTextBoundaryFinder::StartWord
172 && m_analysis[i].flags < QScriptAnalysis::TabOrObject)
173 atWordBoundary = true;
175 m_splitter->toNextBoundary();
178 if (m_analysis[i] == itemAnalysis
179 && m_analysis[i].flags < QScriptAnalysis::TabOrObject
181 && i - start < MaxItemLength)
184 m_items.append(QScriptItem(start, itemAnalysis));
186 itemAnalysis = m_analysis[start];
189 itemAnalysis.flags = QScriptAnalysis::Uppercase;
191 m_items.append(QScriptItem(start, itemAnalysis));
194 void generateScriptItemsSmallCaps(const ushort *uc, int start, int length)
198 bool lower = (QChar::category(uc[start]) == QChar::Letter_Lowercase);
199 const int end = start + length;
200 // split text into parts that are already uppercase and parts that are lowercase, and mark the latter to be uppercased later.
201 for (int i = start + 1; i < end; ++i) {
202 bool l = (QChar::category(uc[i]) == QChar::Letter_Lowercase);
203 if ((m_analysis[i] == m_analysis[start])
204 && m_analysis[i].flags < QScriptAnalysis::TabOrObject
206 && i - start < MaxItemLength)
208 m_items.append(QScriptItem(start, m_analysis[start]));
210 m_items.last().analysis.flags = QScriptAnalysis::SmallCaps;
215 m_items.append(QScriptItem(start, m_analysis[start]));
217 m_items.last().analysis.flags = QScriptAnalysis::SmallCaps;
220 const QString &m_string;
221 const QScriptAnalysis * const m_analysis;
222 QScriptItemArray &m_items;
223 QTextBoundaryFinder *m_splitter;
228 // ----------------------------------------------------------------------------
230 // The BiDi algorithm
232 // ----------------------------------------------------------------------------
235 #if (BIDI_DEBUG >= 1)
236 QT_BEGIN_INCLUDE_NAMESPACE
238 QT_END_INCLUDE_NAMESPACE
241 static const char *directions[] = {
242 "DirL", "DirR", "DirEN", "DirES", "DirET", "DirAN", "DirCS", "DirB", "DirS", "DirWS", "DirON",
243 "DirLRE", "DirLRO", "DirAL", "DirRLE", "DirRLO", "DirPDF", "DirNSM", "DirBN"
251 lastStrong = QChar::DirON;
252 last = QChar:: DirON;
255 QChar::Direction eor;
256 QChar::Direction lastStrong;
257 QChar::Direction last;
258 QChar::Direction dir;
261 enum { MaxBidiLevel = 61 };
263 struct QBidiControl {
264 inline QBidiControl(bool rtl)
265 : cCtx(0), base(rtl ? 1 : 0), level(rtl ? 1 : 0), override(false) {}
267 inline void embed(bool rtl, bool o = false) {
268 unsigned int toAdd = 1;
269 if((level%2 != 0) == rtl ) {
272 if (level + toAdd <= MaxBidiLevel) {
273 ctx[cCtx].level = level;
274 ctx[cCtx].override = override;
280 inline bool canPop() const { return cCtx != 0; }
284 level = ctx[cCtx].level;
285 override = ctx[cCtx].override;
288 inline QChar::Direction basicDirection() const {
289 return (base ? QChar::DirR : QChar:: DirL);
291 inline unsigned int baseLevel() const {
294 inline QChar::Direction direction() const {
295 return ((level%2) ? QChar::DirR : QChar:: DirL);
303 const unsigned int base;
309 static void appendItems(QScriptAnalysis *analysis, int &start, int &stop, const QBidiControl &control, QChar::Direction dir)
314 int level = control.level;
316 if(dir != QChar::DirON && !control.override) {
317 // add level of run (cases I1 & I2)
319 if(dir == QChar::DirL || dir == QChar::DirAN || dir == QChar::DirEN)
322 if(dir == QChar::DirR)
324 else if(dir == QChar::DirAN || dir == QChar::DirEN)
329 #if (BIDI_DEBUG >= 1)
330 qDebug("new run: dir=%s from %d, to %d level = %d override=%d", directions[dir], start, stop, level, control.override);
332 QScriptAnalysis *s = analysis + start;
333 const QScriptAnalysis *e = analysis + stop;
335 s->bidiLevel = level;
342 static QChar::Direction skipBoundryNeutrals(QScriptAnalysis *analysis,
343 const ushort *unicode, int length,
344 int &sor, int &eor, QBidiControl &control)
346 QChar::Direction dir = control.basicDirection();
347 int level = sor > 0 ? analysis[sor - 1].bidiLevel : control.level;
348 while (sor < length) {
349 dir = QChar::direction(unicode[sor]);
350 // Keep skipping DirBN as if it doesn't exist
351 if (dir != QChar::DirBN)
353 analysis[sor++].bidiLevel = level;
358 dir = control.basicDirection();
363 // creates the next QScript items.
364 static bool bidiItemize(QTextEngine *engine, QScriptAnalysis *analysis, QBidiControl &control)
366 bool rightToLeft = (control.basicDirection() == 1);
367 bool hasBidi = rightToLeft;
369 qDebug() << "bidiItemize: rightToLeft=" << rightToLeft << engine->layoutData->string;
376 int length = engine->layoutData->string.length();
378 const ushort *unicode = (const ushort *)engine->layoutData->string.unicode();
381 QChar::Direction dir = rightToLeft ? QChar::DirR : QChar::DirL;
384 QChar::Direction sdir = QChar::direction(*unicode);
385 if (sdir != QChar::DirL && sdir != QChar::DirR && sdir != QChar::DirEN && sdir != QChar::DirAN)
390 status.lastStrong = rightToLeft ? QChar::DirR : QChar::DirL;
391 status.last = status.lastStrong;
395 while (current <= length) {
397 QChar::Direction dirCurrent;
398 if (current == (int)length)
399 dirCurrent = control.basicDirection();
401 dirCurrent = QChar::direction(unicode[current]);
403 #if (BIDI_DEBUG >= 2)
404 // qDebug() << "pos=" << current << " dir=" << directions[dir]
405 // << " current=" << directions[dirCurrent] << " last=" << directions[status.last]
406 // << " eor=" << eor << '/' << directions[status.eor]
407 // << " sor=" << sor << " lastStrong="
408 // << directions[status.lastStrong]
409 // << " level=" << (int)control.level << " override=" << (bool)control.override;
414 // embedding and overrides (X1-X9 in the BiDi specs)
420 bool rtl = (dirCurrent == QChar::DirRLE || dirCurrent == QChar::DirRLO);
422 bool override = (dirCurrent == QChar::DirLRO || dirCurrent == QChar::DirRLO);
424 unsigned int level = control.level+1;
425 if ((level%2 != 0) == rtl) ++level;
426 if(level < MaxBidiLevel) {
428 appendItems(analysis, sor, eor, control, dir);
430 control.embed(rtl, override);
431 QChar::Direction edir = (rtl ? QChar::DirR : QChar::DirL);
432 dir = status.eor = edir;
433 status.lastStrong = edir;
439 if (control.canPop()) {
440 if (dir != control.direction()) {
442 appendItems(analysis, sor, eor, control, dir);
443 dir = control.direction();
446 appendItems(analysis, sor, eor, control, dir);
448 dir = QChar::DirON; status.eor = QChar::DirON;
449 status.last = control.direction();
450 if (control.override)
451 dir = control.direction();
454 status.lastStrong = control.direction();
461 if(dir == QChar::DirON)
466 eor = current; status.eor = QChar::DirL; break;
472 appendItems(analysis, sor, eor, control, dir);
473 status.eor = dir = skipBoundryNeutrals(analysis, unicode, length, sor, eor, control);
475 eor = current; status.eor = dir;
486 if(dir != QChar::DirL) {
487 //last stuff takes embedding dir
488 if(control.direction() == QChar::DirR) {
489 if(status.eor != QChar::DirR) {
491 appendItems(analysis, sor, eor, control, dir);
492 status.eor = QChar::DirON;
496 appendItems(analysis, sor, eor, control, dir);
497 status.eor = dir = skipBoundryNeutrals(analysis, unicode, length, sor, eor, control);
499 if(status.eor != QChar::DirL) {
500 appendItems(analysis, sor, eor, control, dir);
501 status.eor = QChar::DirON;
504 eor = current; status.eor = QChar::DirL; break;
508 eor = current; status.eor = QChar::DirL;
513 status.lastStrong = QChar::DirL;
518 if(dir == QChar::DirON) dir = QChar::DirR;
525 appendItems(analysis, sor, eor, control, dir);
529 dir = QChar::DirR; eor = current; status.eor = QChar::DirR; break;
538 if(status.eor != QChar::DirR && status.eor != QChar::DirAL) {
539 //last stuff takes embedding dir
540 if(control.direction() == QChar::DirR
541 || status.lastStrong == QChar::DirR || status.lastStrong == QChar::DirAL) {
542 appendItems(analysis, sor, eor, control, dir);
543 dir = QChar::DirR; status.eor = QChar::DirON;
547 appendItems(analysis, sor, eor, control, dir);
548 dir = QChar::DirR; status.eor = QChar::DirON;
551 eor = current; status.eor = QChar::DirR;
556 status.lastStrong = dirCurrent;
562 if (eor == current-1)
566 // if last strong was AL change EN to AN
567 if(status.lastStrong != QChar::DirAL) {
568 if(dir == QChar::DirON) {
569 if(status.lastStrong == QChar::DirL)
577 if (status.lastStrong == QChar::DirR || status.lastStrong == QChar::DirAL) {
578 appendItems(analysis, sor, eor, control, dir);
579 status.eor = QChar::DirON;
586 status.eor = dirCurrent;
592 appendItems(analysis, sor, eor, control, dir);
595 status.eor = QChar::DirEN;
596 dir = QChar::DirAN; break;
599 if(status.eor == QChar::DirEN || dir == QChar::DirAN) {
600 eor = current; break;
607 if(status.eor == QChar::DirR) {
610 appendItems(analysis, sor, eor, control, dir);
611 dir = QChar::DirON; status.eor = QChar::DirEN;
614 else if(status.eor == QChar::DirL ||
615 (status.eor == QChar::DirEN && status.lastStrong == QChar::DirL)) {
616 eor = current; status.eor = dirCurrent;
618 // numbers on both sides, neutrals get right to left direction
619 if(dir != QChar::DirL) {
620 appendItems(analysis, sor, eor, control, dir);
621 dir = QChar::DirON; status.eor = QChar::DirON;
624 appendItems(analysis, sor, eor, control, dir);
625 dir = QChar::DirON; status.eor = QChar::DirON;
628 eor = current; status.eor = dirCurrent;
638 dirCurrent = QChar::DirAN;
639 if(dir == QChar::DirON) dir = QChar::DirAN;
644 eor = current; status.eor = QChar::DirAN; break;
649 appendItems(analysis, sor, eor, control, dir);
653 dir = QChar::DirAN; status.eor = QChar::DirAN;
656 if(status.eor == QChar::DirAN) {
657 eor = current; break;
666 if(status.eor == QChar::DirR) {
669 appendItems(analysis, sor, eor, control, dir);
670 status.eor = QChar::DirAN;
672 } else if(status.eor == QChar::DirL ||
673 (status.eor == QChar::DirEN && status.lastStrong == QChar::DirL)) {
674 eor = current; status.eor = dirCurrent;
676 // numbers on both sides, neutrals get right to left direction
677 if(dir != QChar::DirL) {
678 appendItems(analysis, sor, eor, control, dir);
679 status.eor = QChar::DirON;
682 appendItems(analysis, sor, eor, control, dir);
683 status.eor = QChar::DirAN;
686 eor = current; status.eor = dirCurrent;
697 if(status.last == QChar::DirEN) {
698 dirCurrent = QChar::DirEN;
699 eor = current; status.eor = dirCurrent;
703 // boundary neutrals should be ignored
708 // ### what do we do with newline and paragraph separators that come to here?
711 // ### implement rule L1
720 //qDebug() << " after: dir=" << // dir << " current=" << dirCurrent << " last=" << status.last << " eor=" << status.eor << " lastStrong=" << status.lastStrong << " embedding=" << control.direction();
722 if(current >= (int)length) break;
724 // set status.last as needed.
739 status.last = dirCurrent;
742 status.last = QChar::DirON;
751 status.last = QChar::DirL;
755 status.last = QChar::DirR;
758 if (status.last == QChar::DirL) {
759 status.last = QChar::DirL;
764 status.last = dirCurrent;
770 #if (BIDI_DEBUG >= 1)
771 qDebug() << "reached end of line current=" << current << ", eor=" << eor;
773 eor = current - 1; // remove dummy char
776 appendItems(analysis, sor, eor, control, dir);
781 void QTextEngine::bidiReorder(int numItems, const quint8 *levels, int *visualOrder)
784 // first find highest and lowest levels
785 quint8 levelLow = 128;
786 quint8 levelHigh = 0;
788 while (i < numItems) {
789 //printf("level = %d\n", r->level);
790 if (levels[i] > levelHigh)
791 levelHigh = levels[i];
792 if (levels[i] < levelLow)
793 levelLow = levels[i];
797 // implements reordering of the line (L2 according to BiDi spec):
798 // L2. From the highest level found in the text to the lowest odd level on each line,
799 // reverse any contiguous sequence of characters that are at that level or higher.
801 // reversing is only done up to the lowest odd level
802 if(!(levelLow%2)) levelLow++;
804 #if (BIDI_DEBUG >= 1)
805 // qDebug() << "reorderLine: lineLow = " << (uint)levelLow << ", lineHigh = " << (uint)levelHigh;
808 int count = numItems - 1;
809 for (i = 0; i < numItems; i++)
812 while(levelHigh >= levelLow) {
815 while(i < count && levels[i] < levelHigh) i++;
817 while(i <= count && levels[i] >= levelHigh) i++;
821 //qDebug() << "reversing from " << start << " to " << end;
822 for(int j = 0; j < (end-start+1)/2; j++) {
823 int tmp = visualOrder[start+j];
824 visualOrder[start+j] = visualOrder[end-j];
825 visualOrder[end-j] = tmp;
833 #if (BIDI_DEBUG >= 1)
834 // qDebug() << "visual order is:";
835 // for (i = 0; i < numItems; i++)
836 // qDebug() << visualOrder[i];
840 QT_BEGIN_INCLUDE_NAMESPACE
843 #include <private/qharfbuzz_p.h>
845 QT_END_INCLUDE_NAMESPACE
847 // ask the font engine to find out which glyphs (as an index in the specific font) to use for the text in one item.
848 static bool stringToGlyphs(HB_ShaperItem *item, QGlyphLayout *glyphs, QFontEngine *fontEngine)
850 int nGlyphs = item->num_glyphs;
852 QTextEngine::ShaperFlags shaperFlags(QTextEngine::GlyphIndicesOnly);
853 if (item->item.bidiLevel % 2)
854 shaperFlags |= QTextEngine::RightToLeft;
856 bool result = fontEngine->stringToCMap(reinterpret_cast<const QChar *>(item->string + item->item.pos), item->item.length, glyphs, &nGlyphs, shaperFlags);
857 item->num_glyphs = nGlyphs;
858 glyphs->numGlyphs = nGlyphs;
862 // shape all the items that intersect with the line, taking tab widths into account to find out what text actually fits in the line.
863 void QTextEngine::shapeLine(const QScriptLine &line)
867 const int end = findItem(line.from + line.length - 1);
868 int item = findItem(line.from);
871 for (item = findItem(line.from); item <= end; ++item) {
872 QScriptItem &si = layoutData->items[item];
873 if (si.analysis.flags == QScriptAnalysis::Tab) {
875 si.width = calculateTabWidth(item, x);
879 if (first && si.position != line.from) { // that means our x position has to be offset
880 QGlyphLayout glyphs = shapedGlyphs(&si);
881 Q_ASSERT(line.from > si.position);
882 for (int i = line.from - si.position - 1; i >= 0; i--) {
883 x -= glyphs.effectiveAdvance(i);
893 void QTextEngine::shapeText(int item) const
895 Q_ASSERT(item < layoutData->items.size());
896 QScriptItem &si = layoutData->items[item];
901 shapeTextWithHarfbuzz(item);
907 QGlyphLayout glyphs = shapedGlyphs(&si);
909 bool letterSpacingIsAbsolute;
910 QFixed letterSpacing, wordSpacing;
911 #ifndef QT_NO_RAWFONT
913 QTextCharFormat f = format(&si);
914 wordSpacing = QFixed::fromReal(f.fontWordSpacing());
915 letterSpacing = QFixed::fromReal(f.fontLetterSpacing());
916 letterSpacingIsAbsolute = true;
920 QFont font = this->font(si);
921 letterSpacingIsAbsolute = font.d->letterSpacingIsAbsolute;
922 letterSpacing = font.d->letterSpacing;
923 wordSpacing = font.d->wordSpacing;
925 if (letterSpacingIsAbsolute && letterSpacing.value())
926 letterSpacing *= font.d->dpi / qt_defaultDpiY();
929 if (letterSpacing != 0) {
930 for (int i = 1; i < si.num_glyphs; ++i) {
931 if (glyphs.attributes[i].clusterStart) {
932 if (letterSpacingIsAbsolute)
933 glyphs.advances_x[i-1] += letterSpacing;
935 QFixed &advance = glyphs.advances_x[i-1];
936 advance += (letterSpacing - 100) * advance / 100;
940 if (letterSpacingIsAbsolute)
941 glyphs.advances_x[si.num_glyphs-1] += letterSpacing;
943 QFixed &advance = glyphs.advances_x[si.num_glyphs-1];
944 advance += (letterSpacing - 100) * advance / 100;
947 if (wordSpacing != 0) {
948 for (int i = 0; i < si.num_glyphs; ++i) {
949 if (glyphs.attributes[i].justification == HB_Space
950 || glyphs.attributes[i].justification == HB_Arabic_Space) {
951 // word spacing only gets added once to a consecutive run of spaces (see CSS spec)
952 if (i + 1 == si.num_glyphs
953 ||(glyphs.attributes[i+1].justification != HB_Space
954 && glyphs.attributes[i+1].justification != HB_Arabic_Space))
955 glyphs.advances_x[i] += wordSpacing;
960 for (int i = 0; i < si.num_glyphs; ++i)
961 si.width += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
964 static inline bool hasCaseChange(const QScriptItem &si)
966 return si.analysis.flags == QScriptAnalysis::SmallCaps ||
967 si.analysis.flags == QScriptAnalysis::Uppercase ||
968 si.analysis.flags == QScriptAnalysis::Lowercase;
972 static inline void moveGlyphData(const QGlyphLayout &destination, const QGlyphLayout &source, int num)
974 if (num > 0 && destination.glyphs != source.glyphs) {
975 memmove(destination.glyphs, source.glyphs, num * sizeof(HB_Glyph));
976 memmove(destination.attributes, source.attributes, num * sizeof(HB_GlyphAttributes));
977 memmove(destination.advances_x, source.advances_x, num * sizeof(HB_Fixed));
978 memmove(destination.offsets, source.offsets, num * sizeof(HB_FixedPoint));
982 /// take the item from layoutData->items and
983 void QTextEngine::shapeTextWithHarfbuzz(int item) const
985 Q_ASSERT(sizeof(HB_Fixed) == sizeof(QFixed));
986 Q_ASSERT(sizeof(HB_FixedPoint) == sizeof(QFixedPoint));
988 QScriptItem &si = layoutData->items[item];
990 si.glyph_data_offset = layoutData->used;
992 QFontEngine *font = fontEngine(si, &si.ascent, &si.descent, &si.leading);
995 #ifndef QT_NO_RAWFONT
997 QTextCharFormat f = format(&si);
998 kerningEnabled = f.fontKerning();
1001 kerningEnabled = this->font(si).d->kerning;
1003 HB_ShaperItem entire_shaper_item;
1004 memset(&entire_shaper_item, 0, sizeof(entire_shaper_item));
1005 entire_shaper_item.string = reinterpret_cast<const HB_UChar16 *>(layoutData->string.constData());
1006 entire_shaper_item.stringLength = layoutData->string.length();
1007 entire_shaper_item.item.script = (HB_Script)si.analysis.script;
1008 entire_shaper_item.item.pos = si.position;
1009 entire_shaper_item.item.length = length(item);
1010 entire_shaper_item.item.bidiLevel = si.analysis.bidiLevel;
1012 QVarLengthArray<HB_UChar16, 256> casedString;
1013 if (hasCaseChange(si)) {
1014 if (casedString.size() < static_cast<int>(entire_shaper_item.item.length))
1015 casedString.resize(entire_shaper_item.item.length);
1016 HB_UChar16 *uc = casedString.data();
1017 for (uint i = 0; i < entire_shaper_item.item.length; ++i) {
1018 if(si.analysis.flags == QScriptAnalysis::Lowercase)
1019 uc[i] = QChar::toLower(entire_shaper_item.string[si.position + i]);
1021 uc[i] = QChar::toUpper(entire_shaper_item.string[si.position + i]);
1023 entire_shaper_item.item.pos = 0;
1024 entire_shaper_item.string = uc;
1025 entire_shaper_item.stringLength = entire_shaper_item.item.length;
1028 entire_shaper_item.shaperFlags = 0;
1029 if (!kerningEnabled)
1030 entire_shaper_item.shaperFlags |= HB_ShaperFlag_NoKerning;
1031 if (option.useDesignMetrics())
1032 entire_shaper_item.shaperFlags |= HB_ShaperFlag_UseDesignMetrics;
1034 entire_shaper_item.num_glyphs = qMax(layoutData->glyphLayout.numGlyphs - layoutData->used, int(entire_shaper_item.item.length));
1035 if (!ensureSpace(entire_shaper_item.num_glyphs))
1037 QGlyphLayout initialGlyphs = availableGlyphs(&si).mid(0, entire_shaper_item.num_glyphs);
1039 if (!stringToGlyphs(&entire_shaper_item, &initialGlyphs, font)) {
1040 if (!ensureSpace(entire_shaper_item.num_glyphs))
1042 initialGlyphs = availableGlyphs(&si).mid(0, entire_shaper_item.num_glyphs);
1043 if (!stringToGlyphs(&entire_shaper_item, &initialGlyphs, font)) {
1044 // ############ if this happens there's a bug in the fontengine
1049 // split up the item into parts that come from different font engines.
1050 QVarLengthArray<int> itemBoundaries(2);
1051 // k * 2 entries, array[k] == index in string, array[k + 1] == index in glyphs
1052 itemBoundaries[0] = entire_shaper_item.item.pos;
1053 itemBoundaries[1] = 0;
1055 if (font->type() == QFontEngine::Multi) {
1056 uint lastEngine = 0;
1057 int charIdx = entire_shaper_item.item.pos;
1058 const int stringEnd = charIdx + entire_shaper_item.item.length;
1059 for (quint32 i = 0; i < entire_shaper_item.num_glyphs; ++i, ++charIdx) {
1060 uint engineIdx = initialGlyphs.glyphs[i] >> 24;
1061 if (engineIdx != lastEngine && i > 0) {
1062 itemBoundaries.append(charIdx);
1063 itemBoundaries.append(i);
1065 lastEngine = engineIdx;
1066 if (HB_IsHighSurrogate(entire_shaper_item.string[charIdx])
1067 && charIdx < stringEnd - 1
1068 && HB_IsLowSurrogate(entire_shaper_item.string[charIdx + 1]))
1075 int remaining_glyphs = entire_shaper_item.num_glyphs;
1077 // for each item shape using harfbuzz and store the results in our layoutData's glyphs array.
1078 for (int k = 0; k < itemBoundaries.size(); k += 2) { // for the +2, see the comment at the definition of itemBoundaries
1080 HB_ShaperItem shaper_item = entire_shaper_item;
1082 shaper_item.item.pos = itemBoundaries[k];
1083 if (k < itemBoundaries.size() - 3) {
1084 shaper_item.item.length = itemBoundaries[k + 2] - shaper_item.item.pos;
1085 shaper_item.num_glyphs = itemBoundaries[k + 3] - itemBoundaries[k + 1];
1086 } else { // last combo in the list, avoid out of bounds access.
1087 shaper_item.item.length -= shaper_item.item.pos - entire_shaper_item.item.pos;
1088 shaper_item.num_glyphs -= itemBoundaries[k + 1];
1090 shaper_item.initialGlyphCount = shaper_item.num_glyphs;
1091 if (shaper_item.num_glyphs < shaper_item.item.length)
1092 shaper_item.num_glyphs = shaper_item.item.length;
1094 QFontEngine *actualFontEngine = font;
1096 if (font->type() == QFontEngine::Multi) {
1097 engineIdx = uint(availableGlyphs(&si).glyphs[glyph_pos] >> 24);
1099 actualFontEngine = static_cast<QFontEngineMulti *>(font)->engine(engineIdx);
1102 si.ascent = qMax(actualFontEngine->ascent(), si.ascent);
1103 si.descent = qMax(actualFontEngine->descent(), si.descent);
1104 si.leading = qMax(actualFontEngine->leading(), si.leading);
1106 shaper_item.font = actualFontEngine->harfbuzzFont();
1107 shaper_item.face = actualFontEngine->initializedHarfbuzzFace();
1109 shaper_item.glyphIndicesPresent = true;
1111 remaining_glyphs -= shaper_item.initialGlyphCount;
1114 if (!ensureSpace(glyph_pos + shaper_item.num_glyphs + remaining_glyphs))
1117 const QGlyphLayout g = availableGlyphs(&si).mid(glyph_pos);
1118 if (shaper_item.num_glyphs > shaper_item.item.length)
1119 moveGlyphData(g.mid(shaper_item.num_glyphs), g.mid(shaper_item.initialGlyphCount), remaining_glyphs);
1121 shaper_item.glyphs = g.glyphs;
1122 shaper_item.attributes = g.attributes;
1123 shaper_item.advances = reinterpret_cast<HB_Fixed *>(g.advances_x);
1124 shaper_item.offsets = reinterpret_cast<HB_FixedPoint *>(g.offsets);
1126 if (shaper_item.glyphIndicesPresent) {
1127 for (hb_uint32 i = 0; i < shaper_item.initialGlyphCount; ++i)
1128 shaper_item.glyphs[i] &= 0x00ffffff;
1131 shaper_item.log_clusters = logClusters(&si) + shaper_item.item.pos - entire_shaper_item.item.pos;
1133 // qDebug(" .. num_glyphs=%d, used=%d, item.num_glyphs=%d", num_glyphs, used, shaper_item.num_glyphs);
1134 } while (!qShapeItem(&shaper_item)); // this does the actual shaping via harfbuzz.
1136 QGlyphLayout g = availableGlyphs(&si).mid(glyph_pos, shaper_item.num_glyphs);
1137 moveGlyphData(g.mid(shaper_item.num_glyphs), g.mid(shaper_item.initialGlyphCount), remaining_glyphs);
1139 for (hb_uint32 i = 0; i < shaper_item.num_glyphs; ++i)
1140 g.glyphs[i] = g.glyphs[i] | (engineIdx << 24);
1142 for (hb_uint32 i = 0; i < shaper_item.item.length; ++i)
1143 shaper_item.log_clusters[i] += glyph_pos;
1145 if (kerningEnabled && !shaper_item.kerning_applied)
1146 font->doKerning(&g, option.useDesignMetrics() ? QFlag(QTextEngine::DesignMetrics) : QFlag(0));
1148 glyph_pos += shaper_item.num_glyphs;
1151 // qDebug(" -> item: script=%d num_glyphs=%d", shaper_item.script, shaper_item.num_glyphs);
1152 si.num_glyphs = glyph_pos;
1154 layoutData->used += si.num_glyphs;
1157 static void init(QTextEngine *e)
1159 e->ignoreBidi = false;
1160 e->cacheGlyphs = false;
1161 e->forceJustification = false;
1162 e->visualMovement = false;
1163 e->delayDecorations = false;
1170 e->underlinePositions = 0;
1172 e->stackEngine = false;
1173 #ifndef QT_NO_RAWFONT
1174 e->useRawFont = false;
1178 QTextEngine::QTextEngine()
1183 QTextEngine::QTextEngine(const QString &str, const QFont &f)
1190 QTextEngine::~QTextEngine()
1195 resetFontEngineCache();
1198 const HB_CharAttributes *QTextEngine::attributes() const
1200 if (layoutData && layoutData->haveCharAttributes)
1201 return (HB_CharAttributes *) layoutData->memory;
1204 if (! ensureSpace(layoutData->string.length()))
1207 QVarLengthArray<HB_ScriptItem> hbScriptItems(layoutData->items.size());
1209 for (int i = 0; i < layoutData->items.size(); ++i) {
1210 const QScriptItem &si = layoutData->items[i];
1211 hbScriptItems[i].pos = si.position;
1212 hbScriptItems[i].length = length(i);
1213 hbScriptItems[i].bidiLevel = si.analysis.bidiLevel;
1214 hbScriptItems[i].script = (HB_Script)si.analysis.script;
1217 QUnicodeTools::initCharAttributes(reinterpret_cast<const HB_UChar16 *>(layoutData->string.constData()),
1218 layoutData->string.length(),
1219 hbScriptItems.data(), hbScriptItems.size(),
1220 (HB_CharAttributes *)layoutData->memory);
1223 layoutData->haveCharAttributes = true;
1224 return (HB_CharAttributes *) layoutData->memory;
1227 void QTextEngine::shape(int item) const
1229 if (layoutData->items[item].analysis.flags == QScriptAnalysis::Object) {
1231 if (block.docHandle()) {
1232 QTextFormat format = formats()->format(formatIndex(&layoutData->items[item]));
1233 docLayout()->resizeInlineObject(QTextInlineObject(item, const_cast<QTextEngine *>(this)),
1234 layoutData->items[item].position + block.position(), format);
1236 } else if (layoutData->items[item].analysis.flags == QScriptAnalysis::Tab) {
1237 // set up at least the ascent/descent/leading of the script item for the tab
1238 fontEngine(layoutData->items[item],
1239 &layoutData->items[item].ascent,
1240 &layoutData->items[item].descent,
1241 &layoutData->items[item].leading);
1247 static inline void releaseCachedFontEngine(QFontEngine *fontEngine)
1250 fontEngine->ref.deref();
1251 if (fontEngine->cache_count == 0 && fontEngine->ref.load() == 0)
1256 void QTextEngine::resetFontEngineCache()
1258 releaseCachedFontEngine(feCache.prevFontEngine);
1259 releaseCachedFontEngine(feCache.prevScaledFontEngine);
1263 void QTextEngine::invalidate()
1269 specialData->resolvedFormatIndices.clear();
1271 resetFontEngineCache();
1274 void QTextEngine::clearLineData()
1279 void QTextEngine::validate() const
1283 layoutData = new LayoutData();
1284 if (block.docHandle()) {
1285 layoutData->string = block.text();
1286 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators)
1287 layoutData->string += QLatin1Char(block.next().isValid() ? 0xb6 : 0x20);
1289 layoutData->string = text;
1291 if (specialData && specialData->preeditPosition != -1)
1292 layoutData->string.insert(specialData->preeditPosition, specialData->preeditText);
1295 void QTextEngine::itemize() const
1298 if (layoutData->items.size())
1301 int length = layoutData->string.length();
1305 bool ignore = ignoreBidi;
1307 bool rtl = isRightToLeft();
1309 if (!ignore && !rtl) {
1311 const QChar *start = layoutData->string.unicode();
1312 const QChar * const end = start + length;
1313 while (start < end) {
1314 if (start->unicode() >= 0x590) {
1322 QVarLengthArray<QScriptAnalysis, 4096> scriptAnalysis(length);
1323 QScriptAnalysis *analysis = scriptAnalysis.data();
1325 QBidiControl control(rtl);
1328 memset(analysis, 0, length*sizeof(QScriptAnalysis));
1329 if (option.textDirection() == Qt::RightToLeft) {
1330 for (int i = 0; i < length; ++i)
1331 analysis[i].bidiLevel = 1;
1332 layoutData->hasBidi = true;
1335 layoutData->hasBidi = bidiItemize(const_cast<QTextEngine *>(this), analysis, control);
1338 const ushort *uc = reinterpret_cast<const ushort *>(layoutData->string.unicode());
1339 const ushort *e = uc + length;
1340 int lastScript = QUnicodeTables::Common;
1343 case QChar::ObjectReplacementCharacter:
1344 analysis->script = QUnicodeTables::Common;
1345 analysis->flags = QScriptAnalysis::Object;
1347 case QChar::LineSeparator:
1348 if (analysis->bidiLevel % 2)
1349 --analysis->bidiLevel;
1350 analysis->script = QUnicodeTables::Common;
1351 analysis->flags = QScriptAnalysis::LineOrParagraphSeparator;
1352 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators)
1353 *const_cast<ushort*>(uc) = 0x21B5; // visual line separator
1355 case QChar::Tabulation:
1356 analysis->script = QUnicodeTables::Common;
1357 analysis->flags = QScriptAnalysis::Tab;
1358 analysis->bidiLevel = control.baseLevel();
1362 if (option.flags() & QTextOption::ShowTabsAndSpaces) {
1363 analysis->script = QUnicodeTables::Common;
1364 analysis->flags = QScriptAnalysis::Space;
1365 analysis->bidiLevel = control.baseLevel();
1370 int script = QUnicodeTables::script(*uc);
1371 analysis->script = script == QUnicodeTables::Inherited ? lastScript : script;
1372 analysis->flags = QScriptAnalysis::None;
1375 lastScript = analysis->script;
1379 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators) {
1380 (analysis-1)->flags = QScriptAnalysis::LineOrParagraphSeparator; // to exclude it from width
1383 Itemizer itemizer(layoutData->string, scriptAnalysis.data(), layoutData->items);
1385 const QTextDocumentPrivate *p = block.docHandle();
1387 SpecialData *s = specialData;
1389 QTextDocumentPrivate::FragmentIterator it = p->find(block.position());
1390 QTextDocumentPrivate::FragmentIterator end = p->find(block.position() + block.length() - 1); // -1 to omit the block separator char
1391 int format = it.value()->format;
1393 int prevPosition = 0;
1394 int position = prevPosition;
1396 const QTextFragmentData * const frag = it.value();
1397 if (it == end || format != frag->format) {
1398 if (s && position >= s->preeditPosition) {
1399 position += s->preeditText.length();
1402 Q_ASSERT(position <= length);
1403 QFont::Capitalization capitalization =
1404 formats()->charFormat(format).hasProperty(QTextFormat::FontCapitalization)
1405 ? formats()->charFormat(format).fontCapitalization()
1406 : formats()->defaultFont().capitalization();
1407 itemizer.generate(prevPosition, position - prevPosition, capitalization);
1409 if (position < length)
1410 itemizer.generate(position, length - position, capitalization);
1413 format = frag->format;
1414 prevPosition = position;
1416 position += frag->size_array[0];
1420 #ifndef QT_NO_RAWFONT
1421 if (useRawFont && specialData) {
1423 for (int i = 0; i < specialData->addFormats.size(); ++i) {
1424 const QTextLayout::FormatRange &range = specialData->addFormats.at(i);
1425 if (range.format.fontCapitalization()) {
1426 itemizer.generate(lastIndex, range.start - lastIndex, QFont::MixedCase);
1427 itemizer.generate(range.start, range.length, range.format.fontCapitalization());
1428 lastIndex = range.start + range.length;
1431 itemizer.generate(lastIndex, length - lastIndex, QFont::MixedCase);
1434 itemizer.generate(0, length, static_cast<QFont::Capitalization> (fnt.d->capital));
1437 addRequiredBoundaries();
1438 resolveAdditionalFormats();
1441 bool QTextEngine::isRightToLeft() const
1443 switch (option.textDirection()) {
1444 case Qt::LeftToRight:
1446 case Qt::RightToLeft:
1453 // this places the cursor in the right position depending on the keyboard layout
1454 if (layoutData->string.isEmpty())
1455 return qApp ? qApp->inputMethod()->inputDirection() == Qt::RightToLeft : false;
1456 return layoutData->string.isRightToLeft();
1460 int QTextEngine::findItem(int strPos) const
1464 int right = layoutData->items.size()-1;
1465 while(left <= right) {
1466 int middle = ((right-left)/2)+left;
1467 if (strPos > layoutData->items[middle].position)
1469 else if(strPos < layoutData->items[middle].position)
1478 QFixed QTextEngine::width(int from, int len) const
1484 // qDebug("QTextEngine::width(from = %d, len = %d), numItems=%d, strleng=%d", from, len, items.size(), string.length());
1485 for (int i = 0; i < layoutData->items.size(); i++) {
1486 const QScriptItem *si = layoutData->items.constData() + i;
1487 int pos = si->position;
1488 int ilen = length(i);
1489 // qDebug("item %d: from %d len %d", i, pos, ilen);
1490 if (pos >= from + len)
1492 if (pos + ilen > from) {
1493 if (!si->num_glyphs)
1496 if (si->analysis.flags == QScriptAnalysis::Object) {
1499 } else if (si->analysis.flags == QScriptAnalysis::Tab) {
1500 w += calculateTabWidth(i, w);
1505 QGlyphLayout glyphs = shapedGlyphs(si);
1506 unsigned short *logClusters = this->logClusters(si);
1508 // fprintf(stderr, " logclusters:");
1509 // for (int k = 0; k < ilen; k++)
1510 // fprintf(stderr, " %d", logClusters[k]);
1511 // fprintf(stderr, "\n");
1512 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1513 int charFrom = from - pos;
1516 int glyphStart = logClusters[charFrom];
1517 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1518 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1520 if (charFrom < ilen) {
1521 glyphStart = logClusters[charFrom];
1522 int charEnd = from + len - 1 - pos;
1523 if (charEnd >= ilen)
1525 int glyphEnd = logClusters[charEnd];
1526 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1528 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1530 // qDebug("char: start=%d end=%d / glyph: start = %d, end = %d", charFrom, charEnd, glyphStart, glyphEnd);
1531 for (int i = glyphStart; i < glyphEnd; i++)
1532 w += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
1536 // qDebug(" --> w= %d ", w);
1540 glyph_metrics_t QTextEngine::boundingBox(int from, int len) const
1546 for (int i = 0; i < layoutData->items.size(); i++) {
1547 const QScriptItem *si = layoutData->items.constData() + i;
1549 int pos = si->position;
1550 int ilen = length(i);
1551 if (pos > from + len)
1553 if (pos + ilen > from) {
1554 if (!si->num_glyphs)
1557 if (si->analysis.flags == QScriptAnalysis::Object) {
1558 gm.width += si->width;
1560 } else if (si->analysis.flags == QScriptAnalysis::Tab) {
1561 gm.width += calculateTabWidth(i, gm.width);
1565 unsigned short *logClusters = this->logClusters(si);
1566 QGlyphLayout glyphs = shapedGlyphs(si);
1568 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1569 int charFrom = from - pos;
1572 int glyphStart = logClusters[charFrom];
1573 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1574 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1576 if (charFrom < ilen) {
1577 QFontEngine *fe = fontEngine(*si);
1578 glyphStart = logClusters[charFrom];
1579 int charEnd = from + len - 1 - pos;
1580 if (charEnd >= ilen)
1582 int glyphEnd = logClusters[charEnd];
1583 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1585 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1586 if (glyphStart <= glyphEnd ) {
1587 glyph_metrics_t m = fe->boundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
1588 gm.x = qMin(gm.x, m.x + gm.xoff);
1589 gm.y = qMin(gm.y, m.y + gm.yoff);
1590 gm.width = qMax(gm.width, m.width+gm.xoff);
1591 gm.height = qMax(gm.height, m.height+gm.yoff);
1601 glyph_metrics_t QTextEngine::tightBoundingBox(int from, int len) const
1607 for (int i = 0; i < layoutData->items.size(); i++) {
1608 const QScriptItem *si = layoutData->items.constData() + i;
1609 int pos = si->position;
1610 int ilen = length(i);
1611 if (pos > from + len)
1613 if (pos + len > from) {
1614 if (!si->num_glyphs)
1616 unsigned short *logClusters = this->logClusters(si);
1617 QGlyphLayout glyphs = shapedGlyphs(si);
1619 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1620 int charFrom = from - pos;
1623 int glyphStart = logClusters[charFrom];
1624 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1625 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1627 if (charFrom < ilen) {
1628 glyphStart = logClusters[charFrom];
1629 int charEnd = from + len - 1 - pos;
1630 if (charEnd >= ilen)
1632 int glyphEnd = logClusters[charEnd];
1633 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1635 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1636 if (glyphStart <= glyphEnd ) {
1637 QFontEngine *fe = fontEngine(*si);
1638 glyph_metrics_t m = fe->tightBoundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
1639 gm.x = qMin(gm.x, m.x + gm.xoff);
1640 gm.y = qMin(gm.y, m.y + gm.yoff);
1641 gm.width = qMax(gm.width, m.width+gm.xoff);
1642 gm.height = qMax(gm.height, m.height+gm.yoff);
1652 QFont QTextEngine::font(const QScriptItem &si) const
1656 QTextCharFormat f = format(&si);
1659 if (block.docHandle() && block.docHandle()->layout()) {
1660 // Make sure we get the right dpi on printers
1661 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
1663 font = QFont(font, pdev);
1665 font = font.resolve(fnt);
1667 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
1668 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
1669 if (font.pointSize() != -1)
1670 font.setPointSize((font.pointSize() * 2) / 3);
1672 font.setPixelSize((font.pixelSize() * 2) / 3);
1676 if (si.analysis.flags == QScriptAnalysis::SmallCaps)
1677 font = font.d->smallCapsFont();
1682 QTextEngine::FontEngineCache::FontEngineCache()
1687 //we cache the previous results of this function, as calling it numerous times with the same effective
1688 //input is common (and hard to cache at a higher level)
1689 QFontEngine *QTextEngine::fontEngine(const QScriptItem &si, QFixed *ascent, QFixed *descent, QFixed *leading) const
1691 QFontEngine *engine = 0;
1692 QFontEngine *scaledEngine = 0;
1693 int script = si.analysis.script;
1696 #ifndef QT_NO_RAWFONT
1697 if (useRawFont && rawFont.isValid()) {
1698 if (feCache.prevFontEngine && feCache.prevFontEngine->type() == QFontEngine::Multi && feCache.prevScript == script) {
1699 engine = feCache.prevFontEngine;
1701 engine = QFontEngineMultiQPA::createMultiFontEngine(rawFont.d->fontEngine, script);
1702 feCache.prevFontEngine = engine;
1703 feCache.prevScript = script;
1705 if (feCache.prevScaledFontEngine)
1706 releaseCachedFontEngine(feCache.prevScaledFontEngine);
1708 if (si.analysis.flags & QFont::SmallCaps) {
1709 if (feCache.prevScaledFontEngine) {
1710 scaledEngine = feCache.prevScaledFontEngine;
1712 QFontEngine *scEngine = rawFont.d->fontEngine->cloneWithSize(smallCapsFraction * rawFont.pixelSize());
1713 scaledEngine = QFontEngineMultiQPA::createMultiFontEngine(scEngine, script);
1714 scaledEngine->ref.ref();
1715 feCache.prevScaledFontEngine = scaledEngine;
1722 if (feCache.prevFontEngine && feCache.prevPosition == si.position && feCache.prevLength == length(&si) && feCache.prevScript == script) {
1723 engine = feCache.prevFontEngine;
1724 scaledEngine = feCache.prevScaledFontEngine;
1726 QTextCharFormat f = format(&si);
1729 if (block.docHandle() && block.docHandle()->layout()) {
1730 // Make sure we get the right dpi on printers
1731 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
1733 font = QFont(font, pdev);
1735 font = font.resolve(fnt);
1737 engine = font.d->engineForScript(script);
1738 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
1739 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
1740 if (font.pointSize() != -1)
1741 font.setPointSize((font.pointSize() * 2) / 3);
1743 font.setPixelSize((font.pixelSize() * 2) / 3);
1744 scaledEngine = font.d->engineForScript(script);
1749 if (feCache.prevFontEngine)
1750 releaseCachedFontEngine(feCache.prevFontEngine);
1751 feCache.prevFontEngine = engine;
1754 scaledEngine->ref.ref();
1755 if (feCache.prevScaledFontEngine)
1756 releaseCachedFontEngine(feCache.prevScaledFontEngine);
1757 feCache.prevScaledFontEngine = scaledEngine;
1759 feCache.prevScript = script;
1760 feCache.prevPosition = si.position;
1761 feCache.prevLength = length(&si);
1764 if (feCache.prevFontEngine && feCache.prevScript == script && feCache.prevPosition == -1)
1765 engine = feCache.prevFontEngine;
1767 engine = font.d->engineForScript(script);
1771 if (feCache.prevFontEngine)
1772 releaseCachedFontEngine(feCache.prevFontEngine);
1773 feCache.prevFontEngine = engine;
1775 feCache.prevScript = script;
1776 feCache.prevPosition = -1;
1777 feCache.prevLength = -1;
1778 feCache.prevScaledFontEngine = 0;
1782 if (si.analysis.flags == QScriptAnalysis::SmallCaps) {
1783 QFontPrivate *p = font.d->smallCapsFontPrivate();
1784 scaledEngine = p->engineForScript(script);
1789 *ascent = engine->ascent();
1790 *descent = engine->descent();
1791 *leading = engine->leading();
1795 return scaledEngine;
1799 struct QJustificationPoint {
1801 QFixed kashidaWidth;
1803 QFontEngine *fontEngine;
1806 Q_DECLARE_TYPEINFO(QJustificationPoint, Q_PRIMITIVE_TYPE);
1808 static void set(QJustificationPoint *point, int type, const QGlyphLayout &glyph, QFontEngine *fe)
1811 point->glyph = glyph;
1812 point->fontEngine = fe;
1814 if (type >= HB_Arabic_Normal) {
1815 QChar ch(0x640); // Kashida character
1816 QGlyphLayoutArray<8> glyphs;
1818 fe->stringToCMap(&ch, 1, &glyphs, &nglyphs, 0);
1819 if (glyphs.glyphs[0] && glyphs.advances_x[0] != 0) {
1820 point->kashidaWidth = glyphs.advances_x[0];
1822 point->type = HB_NoJustification;
1823 point->kashidaWidth = 0;
1829 void QTextEngine::justify(const QScriptLine &line)
1831 // qDebug("justify: line.gridfitted = %d, line.justified=%d", line.gridfitted, line.justified);
1832 if (line.gridfitted && line.justified)
1835 if (!line.gridfitted) {
1836 // redo layout in device metrics, then adjust
1837 const_cast<QScriptLine &>(line).gridfitted = true;
1840 if ((option.alignment() & Qt::AlignHorizontal_Mask) != Qt::AlignJustify)
1845 if (!forceJustification) {
1846 int end = line.from + (int)line.length;
1847 if (end == layoutData->string.length())
1848 return; // no justification at end of paragraph
1849 if (end && layoutData->items[findItem(end-1)].analysis.flags == QScriptAnalysis::LineOrParagraphSeparator)
1850 return; // no justification at the end of an explicitly separated line
1856 // don't include trailing white spaces when doing justification
1857 int line_length = line.length;
1858 const HB_CharAttributes *a = attributes();
1862 while (line_length && a[line_length-1].whiteSpace)
1864 // subtract one char more, as we can't justfy after the last character
1870 int firstItem = findItem(line.from);
1871 int nItems = findItem(line.from + line_length - 1) - firstItem + 1;
1873 QVarLengthArray<QJustificationPoint> justificationPoints;
1875 // 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());
1876 QFixed minKashida = 0x100000;
1878 // we need to do all shaping before we go into the next loop, as we there
1879 // store pointers to the glyph data that could get reallocated by the shaping
1881 for (int i = 0; i < nItems; ++i) {
1882 QScriptItem &si = layoutData->items[firstItem + i];
1884 shape(firstItem + i);
1887 for (int i = 0; i < nItems; ++i) {
1888 QScriptItem &si = layoutData->items[firstItem + i];
1890 int kashida_type = HB_Arabic_Normal;
1891 int kashida_pos = -1;
1893 int start = qMax(line.from - si.position, 0);
1894 int end = qMin(line.from + line_length - (int)si.position, length(firstItem+i));
1896 unsigned short *log_clusters = logClusters(&si);
1898 int gs = log_clusters[start];
1899 int ge = (end == length(firstItem+i) ? si.num_glyphs : log_clusters[end]);
1901 const QGlyphLayout g = shapedGlyphs(&si);
1903 for (int i = gs; i < ge; ++i) {
1904 g.justifications[i].type = QGlyphJustification::JustifyNone;
1905 g.justifications[i].nKashidas = 0;
1906 g.justifications[i].space_18d6 = 0;
1908 justificationPoints.resize(nPoints+3);
1909 int justification = g.attributes[i].justification;
1911 switch(justification) {
1912 case HB_NoJustification:
1916 case HB_Arabic_Space :
1917 if (kashida_pos >= 0) {
1918 // qDebug("kashida position at %d in word", kashida_pos);
1919 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
1920 if (justificationPoints[nPoints].kashidaWidth > 0) {
1921 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
1922 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
1927 kashida_type = HB_Arabic_Normal;
1930 set(&justificationPoints[nPoints++], justification, g.mid(i), fontEngine(si));
1931 maxJustify = qMax(maxJustify, justification);
1933 case HB_Arabic_Normal :
1934 case HB_Arabic_Waw :
1935 case HB_Arabic_BaRa :
1936 case HB_Arabic_Alef :
1937 case HB_Arabic_HaaDal :
1938 case HB_Arabic_Seen :
1939 case HB_Arabic_Kashida :
1940 if (justification >= kashida_type) {
1942 kashida_type = justification;
1946 if (kashida_pos >= 0) {
1947 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
1948 if (justificationPoints[nPoints].kashidaWidth > 0) {
1949 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
1950 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
1956 QFixed leading = leadingSpaceWidth(line);
1957 QFixed need = line.width - line.textWidth - leading;
1959 // line overflows already!
1960 const_cast<QScriptLine &>(line).justified = true;
1964 // qDebug("doing justification: textWidth=%x, requested=%x, maxJustify=%d", line.textWidth.value(), line.width.value(), maxJustify);
1965 // qDebug(" minKashida=%f, need=%f", minKashida.toReal(), need.toReal());
1967 // distribute in priority order
1968 if (maxJustify >= HB_Arabic_Normal) {
1969 while (need >= minKashida) {
1970 for (int type = maxJustify; need >= minKashida && type >= HB_Arabic_Normal; --type) {
1971 for (int i = 0; need >= minKashida && i < nPoints; ++i) {
1972 if (justificationPoints[i].type == type && justificationPoints[i].kashidaWidth <= need) {
1973 justificationPoints[i].glyph.justifications->nKashidas++;
1975 justificationPoints[i].glyph.justifications->space_18d6 += justificationPoints[i].kashidaWidth.value();
1976 need -= justificationPoints[i].kashidaWidth;
1977 // qDebug("adding kashida type %d with width %x, neednow %x", type, justificationPoints[i].kashidaWidth, need.value());
1983 Q_ASSERT(need >= 0);
1987 maxJustify = qMin(maxJustify, (int)HB_Space);
1988 for (int type = maxJustify; need != 0 && type > 0; --type) {
1990 for (int i = 0; i < nPoints; ++i) {
1991 if (justificationPoints[i].type == type)
1994 // qDebug("number of points for justification type %d: %d", type, n);
2000 for (int i = 0; i < nPoints; ++i) {
2001 if (justificationPoints[i].type == type) {
2002 QFixed add = need/n;
2003 // qDebug("adding %x to glyph %x", add.value(), justificationPoints[i].glyph->glyph);
2004 justificationPoints[i].glyph.justifications[0].space_18d6 = add.value();
2013 const_cast<QScriptLine &>(line).justified = true;
2016 void QScriptLine::setDefaultHeight(QTextEngine *eng)
2021 if (eng->block.docHandle() && eng->block.docHandle()->layout()) {
2022 f = eng->block.charFormat().font();
2023 // Make sure we get the right dpi on printers
2024 QPaintDevice *pdev = eng->block.docHandle()->layout()->paintDevice();
2027 e = f.d->engineForScript(QUnicodeTables::Common);
2029 e = eng->fnt.d->engineForScript(QUnicodeTables::Common);
2032 QFixed other_ascent = e->ascent();
2033 QFixed other_descent = e->descent();
2034 QFixed other_leading = e->leading();
2035 leading = qMax(leading + ascent, other_leading + other_ascent) - qMax(ascent, other_ascent);
2036 ascent = qMax(ascent, other_ascent);
2037 descent = qMax(descent, other_descent);
2040 QTextEngine::LayoutData::LayoutData()
2044 memory_on_stack = false;
2047 layoutState = LayoutEmpty;
2048 haveCharAttributes = false;
2050 available_glyphs = 0;
2053 QTextEngine::LayoutData::LayoutData(const QString &str, void **stack_memory, int _allocated)
2056 allocated = _allocated;
2058 int space_charAttributes = sizeof(HB_CharAttributes)*string.length()/sizeof(void*) + 1;
2059 int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2060 available_glyphs = ((int)allocated - space_charAttributes - space_logClusters)*(int)sizeof(void*)/(int)QGlyphLayout::spaceNeededForGlyphLayout(1);
2062 if (available_glyphs < str.length()) {
2063 // need to allocate on the heap
2066 memory_on_stack = false;
2070 memory_on_stack = true;
2071 memory = stack_memory;
2072 logClustersPtr = (unsigned short *)(memory + space_charAttributes);
2074 void *m = memory + space_charAttributes + space_logClusters;
2075 glyphLayout = QGlyphLayout(reinterpret_cast<char *>(m), str.length());
2076 glyphLayout.clear();
2077 memset(memory, 0, space_charAttributes*sizeof(void *));
2081 layoutState = LayoutEmpty;
2082 haveCharAttributes = false;
2085 QTextEngine::LayoutData::~LayoutData()
2087 if (!memory_on_stack)
2092 bool QTextEngine::LayoutData::reallocate(int totalGlyphs)
2094 Q_ASSERT(totalGlyphs >= glyphLayout.numGlyphs);
2095 if (memory_on_stack && available_glyphs >= totalGlyphs) {
2096 glyphLayout.grow(glyphLayout.data(), totalGlyphs);
2100 int space_charAttributes = sizeof(HB_CharAttributes)*string.length()/sizeof(void*) + 1;
2101 int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2102 int space_glyphs = QGlyphLayout::spaceNeededForGlyphLayout(totalGlyphs)/sizeof(void*) + 2;
2104 int newAllocated = space_charAttributes + space_glyphs + space_logClusters;
2105 // These values can be negative if the length of string/glyphs causes overflow,
2106 // we can't layout such a long string all at once, so return false here to
2107 // indicate there is a failure
2108 if (space_charAttributes < 0 || space_logClusters < 0 || space_glyphs < 0 || newAllocated < allocated) {
2109 layoutState = LayoutFailed;
2113 void **newMem = memory;
2114 newMem = (void **)::realloc(memory_on_stack ? 0 : memory, newAllocated*sizeof(void *));
2116 layoutState = LayoutFailed;
2119 if (memory_on_stack)
2120 memcpy(newMem, memory, allocated*sizeof(void *));
2122 memory_on_stack = false;
2125 m += space_charAttributes;
2126 logClustersPtr = (unsigned short *) m;
2127 m += space_logClusters;
2129 const int space_preGlyphLayout = space_charAttributes + space_logClusters;
2130 if (allocated < space_preGlyphLayout)
2131 memset(memory + allocated, 0, (space_preGlyphLayout - allocated)*sizeof(void *));
2133 glyphLayout.grow(reinterpret_cast<char *>(m), totalGlyphs);
2135 allocated = newAllocated;
2139 // grow to the new size, copying the existing data to the new layout
2140 void QGlyphLayout::grow(char *address, int totalGlyphs)
2142 QGlyphLayout oldLayout(address, numGlyphs);
2143 QGlyphLayout newLayout(address, totalGlyphs);
2146 // move the existing data
2147 memmove(newLayout.attributes, oldLayout.attributes, numGlyphs * sizeof(HB_GlyphAttributes));
2148 memmove(newLayout.justifications, oldLayout.justifications, numGlyphs * sizeof(QGlyphJustification));
2149 memmove(newLayout.advances_y, oldLayout.advances_y, numGlyphs * sizeof(QFixed));
2150 memmove(newLayout.advances_x, oldLayout.advances_x, numGlyphs * sizeof(QFixed));
2151 memmove(newLayout.glyphs, oldLayout.glyphs, numGlyphs * sizeof(HB_Glyph));
2154 // clear the new data
2155 newLayout.clear(numGlyphs);
2160 void QTextEngine::freeMemory()
2166 layoutData->used = 0;
2167 layoutData->hasBidi = false;
2168 layoutData->layoutState = LayoutEmpty;
2169 layoutData->haveCharAttributes = false;
2171 for (int i = 0; i < lines.size(); ++i) {
2172 lines[i].justified = 0;
2173 lines[i].gridfitted = 0;
2177 int QTextEngine::formatIndex(const QScriptItem *si) const
2179 if (specialData && !specialData->resolvedFormatIndices.isEmpty())
2180 return specialData->resolvedFormatIndices.at(si - &layoutData->items[0]);
2181 QTextDocumentPrivate *p = block.docHandle();
2184 int pos = si->position;
2185 if (specialData && si->position >= specialData->preeditPosition) {
2186 if (si->position < specialData->preeditPosition + specialData->preeditText.length())
2187 pos = qMax(qMin(block.length(), specialData->preeditPosition) - 1, 0);
2189 pos -= specialData->preeditText.length();
2191 QTextDocumentPrivate::FragmentIterator it = p->find(block.position() + pos);
2192 return it.value()->format;
2196 QTextCharFormat QTextEngine::format(const QScriptItem *si) const
2198 QTextCharFormat format;
2199 const QTextFormatCollection *formats = 0;
2200 if (block.docHandle()) {
2201 formats = this->formats();
2202 format = formats->charFormat(formatIndex(si));
2204 if (specialData && specialData->resolvedFormatIndices.isEmpty()) {
2205 int end = si->position + length(si);
2206 for (int i = 0; i < specialData->addFormats.size(); ++i) {
2207 const QTextLayout::FormatRange &r = specialData->addFormats.at(i);
2208 if (r.start <= si->position && r.start + r.length >= end) {
2209 if (!specialData->addFormatIndices.isEmpty())
2210 format.merge(formats->format(specialData->addFormatIndices.at(i)));
2212 format.merge(r.format);
2219 void QTextEngine::addRequiredBoundaries() const
2222 for (int i = 0; i < specialData->addFormats.size(); ++i) {
2223 const QTextLayout::FormatRange &r = specialData->addFormats.at(i);
2224 setBoundary(r.start);
2225 setBoundary(r.start + r.length);
2226 //qDebug("adding boundaries %d %d", r.start, r.start+r.length);
2231 bool QTextEngine::atWordSeparator(int position) const
2233 const QChar c = layoutData->string.at(position);
2234 switch (c.unicode()) {
2272 bool QTextEngine::atSpace(int position) const
2274 const QChar c = layoutData->string.at(position);
2275 switch (c.unicode()) {
2276 case QChar::Tabulation:
2279 case QChar::LineSeparator:
2288 void QTextEngine::indexAdditionalFormats()
2290 if (!block.docHandle())
2293 specialData->addFormatIndices.resize(specialData->addFormats.count());
2294 QTextFormatCollection * const formats = this->formats();
2296 for (int i = 0; i < specialData->addFormats.count(); ++i) {
2297 specialData->addFormatIndices[i] = formats->indexForFormat(specialData->addFormats.at(i).format);
2298 specialData->addFormats[i].format = QTextCharFormat();
2302 /* These two helper functions are used to determine whether we need to insert a ZWJ character
2303 between the text that gets truncated and the ellipsis. This is important to get
2304 correctly shaped results for arabic text.
2306 static inline bool nextCharJoins(const QString &string, int pos)
2308 while (pos < string.length() && string.at(pos).category() == QChar::Mark_NonSpacing)
2310 if (pos == string.length())
2312 return string.at(pos).joining() != QChar::OtherJoining;
2315 static inline bool prevCharJoins(const QString &string, int pos)
2317 while (pos > 0 && string.at(pos - 1).category() == QChar::Mark_NonSpacing)
2321 QChar::Joining joining = string.at(pos - 1).joining();
2322 return (joining == QChar::Dual || joining == QChar::Center);
2325 static inline bool isRetainableControlCode(QChar c)
2327 return (c.unicode() == 0x202a // LRE
2328 || c.unicode() == 0x202b // LRE
2329 || c.unicode() == 0x202c // PDF
2330 || c.unicode() == 0x202d // LRO
2331 || c.unicode() == 0x202e // RLO
2332 || c.unicode() == 0x200e // LRM
2333 || c.unicode() == 0x200f); // RLM
2336 static QString stringMidRetainingBidiCC(const QString &string,
2337 const QString &ellidePrefix,
2338 const QString &ellideSuffix,
2345 for (int i=subStringFrom; i<midStart; ++i) {
2346 QChar c = string.at(i);
2347 if (isRetainableControlCode(c))
2352 for (int i=midStart + midLength; i<subStringTo; ++i) {
2353 QChar c = string.at(i);
2354 if (isRetainableControlCode(c))
2358 return prefix + ellidePrefix + string.mid(midStart, midLength) + ellideSuffix + suffix;
2361 QString QTextEngine::elidedText(Qt::TextElideMode mode, const QFixed &width, int flags, int from, int count) const
2363 // qDebug() << "elidedText; available width" << width.toReal() << "text width:" << this->width(0, layoutData->string.length()).toReal();
2365 if (flags & Qt::TextShowMnemonic) {
2367 HB_CharAttributes *attributes = const_cast<HB_CharAttributes *>(this->attributes());
2370 for (int i = 0; i < layoutData->items.size(); ++i) {
2371 QScriptItem &si = layoutData->items[i];
2375 unsigned short *logClusters = this->logClusters(&si);
2376 QGlyphLayout glyphs = shapedGlyphs(&si);
2378 const int end = si.position + length(&si);
2379 for (int i = si.position; i < end - 1; ++i) {
2380 if (layoutData->string.at(i) == QLatin1Char('&')) {
2381 const int gp = logClusters[i - si.position];
2382 glyphs.attributes[gp].dontPrint = true;
2383 attributes[i + 1].charStop = false;
2384 attributes[i + 1].whiteSpace = false;
2385 attributes[i + 1].lineBreakType = HB_NoBreak;
2386 if (layoutData->string.at(i + 1) == QLatin1Char('&'))
2395 const int to = count >= 0 && count <= layoutData->string.length() - from
2397 : layoutData->string.length();
2399 if (mode == Qt::ElideNone
2400 || this->width(from, layoutData->string.length()) <= width
2402 return layoutData->string.mid(from, from - to);
2404 QFixed ellipsisWidth;
2405 QString ellipsisText;
2407 QChar ellipsisChar(0x2026);
2409 QFontEngine *fe = fnt.d->engineForScript(QUnicodeTables::Common);
2411 QGlyphLayoutArray<1> ellipsisGlyph;
2413 QFontEngine *feForEllipsis = (fe->type() == QFontEngine::Multi)
2414 ? static_cast<QFontEngineMulti *>(fe)->engine(0)
2417 if (feForEllipsis->type() == QFontEngine::Mac)
2420 if (feForEllipsis->canRender(&ellipsisChar, 1)) {
2422 feForEllipsis->stringToCMap(&ellipsisChar, 1, &ellipsisGlyph, &nGlyphs, 0);
2426 if (ellipsisGlyph.glyphs[0]) {
2427 ellipsisWidth = ellipsisGlyph.advances_x[0];
2428 ellipsisText = ellipsisChar;
2430 QString dotDotDot(QLatin1String("..."));
2432 QGlyphLayoutArray<3> glyphs;
2434 if (!fe->stringToCMap(dotDotDot.constData(), 3, &glyphs, &nGlyphs, 0))
2435 // should never happen...
2436 return layoutData->string;
2437 for (int i = 0; i < nGlyphs; ++i)
2438 ellipsisWidth += glyphs.advances_x[i];
2439 ellipsisText = dotDotDot;
2443 const QFixed availableWidth = width - ellipsisWidth;
2444 if (availableWidth < 0)
2447 const HB_CharAttributes *attributes = this->attributes();
2451 if (mode == Qt::ElideRight) {
2452 QFixed currentWidth;
2454 int nextBreak = from;
2460 while (nextBreak < layoutData->string.length() && !attributes[nextBreak].charStop)
2463 currentWidth += this->width(pos, nextBreak - pos);
2464 } while (nextBreak < to
2465 && currentWidth < availableWidth);
2467 if (nextCharJoins(layoutData->string, pos))
2468 ellipsisText.prepend(QChar(0x200d) /* ZWJ */);
2470 return stringMidRetainingBidiCC(layoutData->string,
2471 QString(), ellipsisText,
2474 } else if (mode == Qt::ElideLeft) {
2475 QFixed currentWidth;
2483 while (nextBreak > 0 && !attributes[nextBreak].charStop)
2486 currentWidth += this->width(nextBreak, pos - nextBreak);
2487 } while (nextBreak > from
2488 && currentWidth < availableWidth);
2490 if (prevCharJoins(layoutData->string, pos))
2491 ellipsisText.append(QChar(0x200d) /* ZWJ */);
2493 return stringMidRetainingBidiCC(layoutData->string,
2494 ellipsisText, QString(),
2497 } else if (mode == Qt::ElideMiddle) {
2502 int nextLeftBreak = from;
2505 int nextRightBreak = to;
2508 leftPos = nextLeftBreak;
2509 rightPos = nextRightBreak;
2512 while (nextLeftBreak < layoutData->string.length() && !attributes[nextLeftBreak].charStop)
2516 while (nextRightBreak > from && !attributes[nextRightBreak].charStop)
2519 leftWidth += this->width(leftPos, nextLeftBreak - leftPos);
2520 rightWidth += this->width(nextRightBreak, rightPos - nextRightBreak);
2521 } while (nextLeftBreak < to
2522 && nextRightBreak > from
2523 && leftWidth + rightWidth < availableWidth);
2525 if (nextCharJoins(layoutData->string, leftPos))
2526 ellipsisText.prepend(QChar(0x200d) /* ZWJ */);
2527 if (prevCharJoins(layoutData->string, rightPos))
2528 ellipsisText.append(QChar(0x200d) /* ZWJ */);
2530 return layoutData->string.mid(from, leftPos - from) + ellipsisText + layoutData->string.mid(rightPos, to - rightPos);
2533 return layoutData->string.mid(from, to - from);
2536 void QTextEngine::setBoundary(int strPos) const
2538 if (strPos <= 0 || strPos >= layoutData->string.length())
2541 int itemToSplit = 0;
2542 while (itemToSplit < layoutData->items.size() && layoutData->items.at(itemToSplit).position <= strPos)
2545 if (layoutData->items.at(itemToSplit).position == strPos) {
2546 // already a split at the requested position
2549 splitItem(itemToSplit, strPos - layoutData->items.at(itemToSplit).position);
2552 void QTextEngine::splitItem(int item, int pos) const
2557 layoutData->items.insert(item + 1, layoutData->items[item]);
2558 QScriptItem &oldItem = layoutData->items[item];
2559 QScriptItem &newItem = layoutData->items[item+1];
2560 newItem.position += pos;
2562 if (oldItem.num_glyphs) {
2563 // already shaped, break glyphs aswell
2564 int breakGlyph = logClusters(&oldItem)[pos];
2566 newItem.num_glyphs = oldItem.num_glyphs - breakGlyph;
2567 oldItem.num_glyphs = breakGlyph;
2568 newItem.glyph_data_offset = oldItem.glyph_data_offset + breakGlyph;
2570 for (int i = 0; i < newItem.num_glyphs; i++)
2571 logClusters(&newItem)[i] -= breakGlyph;
2574 const QGlyphLayout g = shapedGlyphs(&oldItem);
2575 for(int j = 0; j < breakGlyph; ++j)
2576 w += g.advances_x[j] * !g.attributes[j].dontPrint;
2578 newItem.width = oldItem.width - w;
2582 // qDebug("split at position %d itempos=%d", pos, item);
2585 QFixed QTextEngine::calculateTabWidth(int item, QFixed x) const
2587 const QScriptItem &si = layoutData->items[item];
2589 QFixed dpiScale = 1;
2590 if (block.docHandle() && block.docHandle()->layout()) {
2591 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
2593 dpiScale = QFixed::fromReal(pdev->logicalDpiY() / qreal(qt_defaultDpiY()));
2595 dpiScale = QFixed::fromReal(fnt.d->dpi / qreal(qt_defaultDpiY()));
2598 QList<QTextOption::Tab> tabArray = option.tabs();
2599 if (!tabArray.isEmpty()) {
2600 if (isRightToLeft()) { // rebase the tabArray positions.
2601 QList<QTextOption::Tab> newTabs;
2602 QList<QTextOption::Tab>::Iterator iter = tabArray.begin();
2603 while(iter != tabArray.end()) {
2604 QTextOption::Tab tab = *iter;
2605 if (tab.type == QTextOption::LeftTab)
2606 tab.type = QTextOption::RightTab;
2607 else if (tab.type == QTextOption::RightTab)
2608 tab.type = QTextOption::LeftTab;
2614 for (int i = 0; i < tabArray.size(); ++i) {
2615 QFixed tab = QFixed::fromReal(tabArray[i].position) * dpiScale;
2616 if (tab > x) { // this is the tab we need.
2617 QTextOption::Tab tabSpec = tabArray[i];
2618 int tabSectionEnd = layoutData->string.count();
2619 if (tabSpec.type == QTextOption::RightTab || tabSpec.type == QTextOption::CenterTab) {
2620 // find next tab to calculate the width required.
2621 tab = QFixed::fromReal(tabSpec.position);
2622 for (int i=item + 1; i < layoutData->items.count(); i++) {
2623 const QScriptItem &item = layoutData->items[i];
2624 if (item.analysis.flags == QScriptAnalysis::TabOrObject) { // found it.
2625 tabSectionEnd = item.position;
2630 else if (tabSpec.type == QTextOption::DelimiterTab)
2631 // find delimitor character to calculate the width required
2632 tabSectionEnd = qMax(si.position, layoutData->string.indexOf(tabSpec.delimiter, si.position) + 1);
2634 if (tabSectionEnd > si.position) {
2636 // Calculate the length of text between this tab and the tabSectionEnd
2637 for (int i=item; i < layoutData->items.count(); i++) {
2638 QScriptItem &item = layoutData->items[i];
2639 if (item.position > tabSectionEnd || item.position <= si.position)
2641 shape(i); // first, lets make sure relevant text is already shaped
2642 QGlyphLayout glyphs = this->shapedGlyphs(&item);
2643 const int end = qMin(item.position + item.num_glyphs, tabSectionEnd) - item.position;
2644 for (int i=0; i < end; i++)
2645 length += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
2646 if (end + item.position == tabSectionEnd && tabSpec.type == QTextOption::DelimiterTab) // remove half of matching char
2647 length -= glyphs.advances_x[end] / 2 * !glyphs.attributes[end].dontPrint;
2650 switch (tabSpec.type) {
2651 case QTextOption::CenterTab:
2654 case QTextOption::DelimiterTab:
2656 case QTextOption::RightTab:
2657 tab = QFixed::fromReal(tabSpec.position) * dpiScale - length;
2658 if (tab < x) // default to tab taking no space
2661 case QTextOption::LeftTab:
2669 QFixed tab = QFixed::fromReal(option.tabStop());
2671 tab = 80; // default
2673 QFixed nextTabPos = ((x / tab).truncate() + 1) * tab;
2674 QFixed tabWidth = nextTabPos - x;
2679 void QTextEngine::resolveAdditionalFormats() const
2681 if (!specialData || specialData->addFormats.isEmpty()
2682 || !block.docHandle()
2683 || !specialData->resolvedFormatIndices.isEmpty())
2686 QTextFormatCollection *collection = this->formats();
2688 specialData->resolvedFormatIndices.clear();
2689 QVector<int> indices(layoutData->items.count());
2690 for (int i = 0; i < layoutData->items.count(); ++i) {
2691 QTextCharFormat f = format(&layoutData->items.at(i));
2692 indices[i] = collection->indexForFormat(f);
2694 specialData->resolvedFormatIndices = indices;
2697 QFixed QTextEngine::leadingSpaceWidth(const QScriptLine &line)
2699 if (!line.hasTrailingSpaces
2700 || (option.flags() & QTextOption::IncludeTrailingSpaces)
2701 || !isRightToLeft())
2704 return width(line.from + line.length, line.trailingSpaces);
2707 QFixed QTextEngine::alignLine(const QScriptLine &line)
2711 // if width is QFIXED_MAX that means we used setNumColumns() and that implicitly makes this line left aligned.
2712 if (!line.justified && line.width != QFIXED_MAX) {
2713 int align = option.alignment();
2714 if (align & Qt::AlignJustify && isRightToLeft())
2715 align = Qt::AlignRight;
2716 if (align & Qt::AlignRight)
2717 x = line.width - (line.textAdvance);
2718 else if (align & Qt::AlignHCenter)
2719 x = (line.width - line.textAdvance)/2;
2724 QFixed QTextEngine::offsetInLigature(const QScriptItem *si, int pos, int max, int glyph_pos)
2726 unsigned short *logClusters = this->logClusters(si);
2727 const QGlyphLayout &glyphs = shapedGlyphs(si);
2729 int offsetInCluster = 0;
2730 for (int i = pos - 1; i >= 0; i--) {
2731 if (logClusters[i] == glyph_pos)
2737 // in the case that the offset is inside a (multi-character) glyph,
2738 // interpolate the position.
2739 if (offsetInCluster > 0) {
2740 int clusterLength = 0;
2741 for (int i = pos - offsetInCluster; i < max; i++) {
2742 if (logClusters[i] == glyph_pos)
2748 return glyphs.advances_x[glyph_pos] * offsetInCluster / clusterLength;
2754 // Scan in logClusters[from..to-1] for glyph_pos
2755 int QTextEngine::getClusterLength(unsigned short *logClusters,
2756 const HB_CharAttributes *attributes,
2757 int from, int to, int glyph_pos, int *start)
2759 int clusterLength = 0;
2760 for (int i = from; i < to; i++) {
2761 if (logClusters[i] == glyph_pos && attributes[i].charStop) {
2766 else if (clusterLength)
2769 return clusterLength;
2772 int QTextEngine::positionInLigature(const QScriptItem *si, int end,
2773 QFixed x, QFixed edge, int glyph_pos,
2774 bool cursorOnCharacter)
2776 unsigned short *logClusters = this->logClusters(si);
2777 int clusterStart = -1;
2778 int clusterLength = 0;
2780 if (si->analysis.script != QUnicodeTables::Common &&
2781 si->analysis.script != QUnicodeTables::Greek) {
2782 if (glyph_pos == -1)
2783 return si->position + end;
2786 for (i = 0; i < end; i++)
2787 if (logClusters[i] == glyph_pos)
2789 return si->position + i;
2793 if (glyph_pos == -1 && end > 0)
2794 glyph_pos = logClusters[end - 1];
2800 const HB_CharAttributes *attrs = attributes();
2801 logClusters = this->logClusters(si);
2802 clusterLength = getClusterLength(logClusters, attrs, 0, end, glyph_pos, &clusterStart);
2804 if (clusterLength) {
2805 const QGlyphLayout &glyphs = shapedGlyphs(si);
2806 QFixed glyphWidth = glyphs.effectiveAdvance(glyph_pos);
2807 // the approximate width of each individual element of the ligature
2808 QFixed perItemWidth = glyphWidth / clusterLength;
2809 if (perItemWidth <= 0)
2810 return si->position + clusterStart;
2811 QFixed left = x > edge ? edge : edge - glyphWidth;
2812 int n = ((x - left) / perItemWidth).floor().toInt();
2813 QFixed dist = x - left - n * perItemWidth;
2814 int closestItem = dist > (perItemWidth / 2) ? n + 1 : n;
2815 if (cursorOnCharacter && closestItem > 0)
2817 int pos = si->position + clusterStart + closestItem;
2818 // Jump to the next charStop
2819 while (pos < end && !attrs[pos].charStop)
2823 return si->position + end;
2826 int QTextEngine::previousLogicalPosition(int oldPos) const
2828 const HB_CharAttributes *attrs = attributes();
2829 if (!attrs || oldPos < 0)
2835 while (oldPos && !attrs[oldPos].charStop)
2840 int QTextEngine::nextLogicalPosition(int oldPos) const
2842 const HB_CharAttributes *attrs = attributes();
2843 int len = block.isValid() ? block.length() - 1
2844 : layoutData->string.length();
2845 Q_ASSERT(len <= layoutData->string.length());
2846 if (!attrs || oldPos < 0 || oldPos >= len)
2850 while (oldPos < len && !attrs[oldPos].charStop)
2855 int QTextEngine::lineNumberForTextPosition(int pos)
2859 if (pos == layoutData->string.length() && lines.size())
2860 return lines.size() - 1;
2861 for (int i = 0; i < lines.size(); ++i) {
2862 const QScriptLine& line = lines[i];
2863 if (line.from + line.length + line.trailingSpaces > pos)
2869 void QTextEngine::insertionPointsForLine(int lineNum, QVector<int> &insertionPoints)
2871 QTextLineItemIterator iterator(this, lineNum);
2872 bool rtl = isRightToLeft();
2873 bool lastLine = lineNum >= lines.size() - 1;
2875 while (!iterator.atEnd()) {
2877 const QScriptItem *si = &layoutData->items[iterator.item];
2878 if (si->analysis.bidiLevel % 2) {
2879 int i = iterator.itemEnd - 1, min = iterator.itemStart;
2880 if (lastLine && (rtl ? iterator.atBeginning() : iterator.atEnd()))
2882 for (; i >= min; i--)
2883 insertionPoints.push_back(i);
2885 int i = iterator.itemStart, max = iterator.itemEnd;
2886 if (lastLine && (rtl ? iterator.atBeginning() : iterator.atEnd()))
2888 for (; i < max; i++)
2889 insertionPoints.push_back(i);
2894 int QTextEngine::endOfLine(int lineNum)
2896 QVector<int> insertionPoints;
2897 insertionPointsForLine(lineNum, insertionPoints);
2899 if (insertionPoints.size() > 0)
2900 return insertionPoints.last();
2904 int QTextEngine::beginningOfLine(int lineNum)
2906 QVector<int> insertionPoints;
2907 insertionPointsForLine(lineNum, insertionPoints);
2909 if (insertionPoints.size() > 0)
2910 return insertionPoints.first();
2914 int QTextEngine::positionAfterVisualMovement(int pos, QTextCursor::MoveOperation op)
2919 bool moveRight = (op == QTextCursor::Right);
2920 bool alignRight = isRightToLeft();
2921 if (!layoutData->hasBidi)
2922 return moveRight ^ alignRight ? nextLogicalPosition(pos) : previousLogicalPosition(pos);
2924 int lineNum = lineNumberForTextPosition(pos);
2925 Q_ASSERT(lineNum >= 0);
2927 QVector<int> insertionPoints;
2928 insertionPointsForLine(lineNum, insertionPoints);
2929 int i, max = insertionPoints.size();
2930 for (i = 0; i < max; i++)
2931 if (pos == insertionPoints[i]) {
2934 return insertionPoints[i + 1];
2937 return insertionPoints[i - 1];
2940 if (moveRight ^ alignRight) {
2941 if (lineNum + 1 < lines.size())
2942 return alignRight ? endOfLine(lineNum + 1) : beginningOfLine(lineNum + 1);
2946 return alignRight ? beginningOfLine(lineNum - 1) : endOfLine(lineNum - 1);
2953 void QTextEngine::addItemDecoration(QPainter *painter, const QLineF &line, ItemDecorationList *decorationList)
2955 if (delayDecorations) {
2956 decorationList->append(ItemDecoration(line.x1(), line.x2(), line.y1(), painter->pen()));
2958 painter->drawLine(line);
2962 void QTextEngine::addUnderline(QPainter *painter, const QLineF &line)
2964 // qDebug() << "Adding underline:" << line;
2965 addItemDecoration(painter, line, &underlineList);
2968 void QTextEngine::addStrikeOut(QPainter *painter, const QLineF &line)
2970 addItemDecoration(painter, line, &strikeOutList);
2973 void QTextEngine::addOverline(QPainter *painter, const QLineF &line)
2975 addItemDecoration(painter, line, &overlineList);
2978 void QTextEngine::drawItemDecorationList(QPainter *painter, const ItemDecorationList &decorationList)
2980 // qDebug() << "Drawing" << decorationList.size() << "decorations";
2981 if (decorationList.isEmpty())
2984 foreach (const ItemDecoration &decoration, decorationList) {
2985 painter->setPen(decoration.pen);
2986 QLineF line(decoration.x1, decoration.y, decoration.x2, decoration.y);
2987 painter->drawLine(line);
2991 void QTextEngine::drawDecorations(QPainter *painter)
2993 QPen oldPen = painter->pen();
2996 drawItemDecorationList(painter, underlineList);
2997 drawItemDecorationList(painter, strikeOutList);
2998 drawItemDecorationList(painter, overlineList);
3000 painter->setPen(oldPen);
3004 void QTextEngine::clearDecorations()
3006 underlineList.clear();
3007 strikeOutList.clear();
3008 overlineList.clear();
3011 void QTextEngine::adjustUnderlines()
3013 // qDebug() << __PRETTY_FUNCTION__ << underlineList.count() << "underlines";
3014 if (underlineList.isEmpty())
3017 ItemDecorationList::iterator start = underlineList.begin();
3018 ItemDecorationList::iterator end = underlineList.end();
3019 ItemDecorationList::iterator it = start;
3020 qreal underlinePos = start->y;
3021 qreal penWidth = start->pen.widthF();
3022 qreal lastLineEnd = start->x1;
3025 if (qFuzzyCompare(lastLineEnd, it->x1)) { // no gap between underlines
3026 underlinePos = qMax(underlinePos, it->y);
3027 penWidth = qMax(penWidth, it->pen.widthF());
3028 } else { // gap between this and the last underline
3029 adjustUnderlines(start, it, underlinePos, penWidth);
3031 underlinePos = start->y;
3032 penWidth = start->pen.widthF();
3034 lastLineEnd = it->x2;
3038 adjustUnderlines(start, end, underlinePos, penWidth);
3041 void QTextEngine::adjustUnderlines(ItemDecorationList::iterator start,
3042 ItemDecorationList::iterator end,
3043 qreal underlinePos, qreal penWidth)
3045 for (ItemDecorationList::iterator it = start; it != end; ++it) {
3046 it->y = underlinePos;
3047 it->pen.setWidthF(penWidth);
3051 QStackTextEngine::QStackTextEngine(const QString &string, const QFont &f)
3052 : QTextEngine(string, f),
3053 _layoutData(string, _memory, MemSize)
3056 layoutData = &_layoutData;
3059 QTextItemInt::QTextItemInt(const QScriptItem &si, QFont *font, const QTextCharFormat &format)
3060 : justified(false), underlineStyle(QTextCharFormat::NoUnderline), charFormat(format),
3061 num_chars(0), chars(0), logClusters(0), f(0), fontEngine(0)
3064 fontEngine = f->d->engineForScript(si.analysis.script);
3065 Q_ASSERT(fontEngine);
3067 initWithScriptItem(si);
3070 QTextItemInt::QTextItemInt(const QGlyphLayout &g, QFont *font, const QChar *chars_, int numChars, QFontEngine *fe, const QTextCharFormat &format)
3071 : flags(0), justified(false), underlineStyle(QTextCharFormat::NoUnderline), charFormat(format),
3072 num_chars(numChars), chars(chars_), logClusters(0), f(font), glyphs(g), fontEngine(fe)
3076 // Fix up flags and underlineStyle with given info
3077 void QTextItemInt::initWithScriptItem(const QScriptItem &si)
3079 // explicitly initialize flags so that initFontAttributes can be called
3080 // multiple times on the same TextItem
3082 if (si.analysis.bidiLevel %2)
3083 flags |= QTextItem::RightToLeft;
3085 descent = si.descent;
3087 if (charFormat.hasProperty(QTextFormat::TextUnderlineStyle)) {
3088 underlineStyle = charFormat.underlineStyle();
3089 } else if (charFormat.boolProperty(QTextFormat::FontUnderline)
3090 || f->d->underline) {
3091 underlineStyle = QTextCharFormat::SingleUnderline;
3095 if (underlineStyle == QTextCharFormat::SingleUnderline)
3096 flags |= QTextItem::Underline;
3098 if (f->d->overline || charFormat.fontOverline())
3099 flags |= QTextItem::Overline;
3100 if (f->d->strikeOut || charFormat.fontStrikeOut())
3101 flags |= QTextItem::StrikeOut;
3104 QTextItemInt QTextItemInt::midItem(QFontEngine *fontEngine, int firstGlyphIndex, int numGlyphs) const
3106 QTextItemInt ti = *this;
3107 const int end = firstGlyphIndex + numGlyphs;
3108 ti.glyphs = glyphs.mid(firstGlyphIndex, numGlyphs);
3109 ti.fontEngine = fontEngine;
3111 if (logClusters && chars) {
3112 const int logClusterOffset = logClusters[0];
3113 while (logClusters[ti.chars - chars] - logClusterOffset < firstGlyphIndex)
3116 ti.logClusters += (ti.chars - chars);
3119 int char_start = ti.chars - chars;
3120 while (char_start + ti.num_chars < num_chars && ti.logClusters[ti.num_chars] - logClusterOffset < end)
3127 QTransform qt_true_matrix(qreal w, qreal h, QTransform x)
3129 QRectF rect = x.mapRect(QRectF(0, 0, w, h));
3130 return x * QTransform::fromTranslate(-rect.x(), -rect.y());
3134 glyph_metrics_t glyph_metrics_t::transformed(const QTransform &matrix) const
3136 if (matrix.type() < QTransform::TxTranslate)
3139 glyph_metrics_t m = *this;
3141 qreal w = width.toReal();
3142 qreal h = height.toReal();
3143 QTransform xform = qt_true_matrix(w, h, matrix);
3145 QRectF rect(0, 0, w, h);
3146 rect = xform.mapRect(rect);
3147 m.width = QFixed::fromReal(rect.width());
3148 m.height = QFixed::fromReal(rect.height());
3150 QLineF l = xform.map(QLineF(x.toReal(), y.toReal(), xoff.toReal(), yoff.toReal()));
3152 m.x = QFixed::fromReal(l.x1());
3153 m.y = QFixed::fromReal(l.y1());
3155 // The offset is relative to the baseline which is why we use dx/dy of the line
3156 m.xoff = QFixed::fromReal(l.dx());
3157 m.yoff = QFixed::fromReal(l.dy());
3162 QTextLineItemIterator::QTextLineItemIterator(QTextEngine *_eng, int _lineNum, const QPointF &pos,
3163 const QTextLayout::FormatRange *_selection)
3165 line(eng->lines[_lineNum]),
3168 lineEnd(line.from + line.length),
3169 firstItem(eng->findItem(line.from)),
3170 lastItem(eng->findItem(lineEnd - 1)),
3171 nItems((firstItem >= 0 && lastItem >= firstItem)? (lastItem-firstItem+1) : 0),
3174 visualOrder(nItems),
3176 selection(_selection)
3178 pos_x = x = QFixed::fromReal(pos.x());
3182 x += eng->alignLine(line);
3184 for (int i = 0; i < nItems; ++i)
3185 levels[i] = eng->layoutData->items[i+firstItem].analysis.bidiLevel;
3186 QTextEngine::bidiReorder(nItems, levels.data(), visualOrder.data());
3188 eng->shapeLine(line);
3191 QScriptItem &QTextLineItemIterator::next()
3196 item = visualOrder[logicalItem] + firstItem;
3197 itemLength = eng->length(item);
3198 si = &eng->layoutData->items[item];
3199 if (!si->num_glyphs)
3202 if (si->analysis.flags >= QScriptAnalysis::TabOrObject) {
3203 itemWidth = si->width;
3207 unsigned short *logClusters = eng->logClusters(si);
3208 QGlyphLayout glyphs = eng->shapedGlyphs(si);
3210 itemStart = qMax(line.from, si->position);
3211 glyphsStart = logClusters[itemStart - si->position];
3212 if (lineEnd < si->position + itemLength) {
3214 glyphsEnd = logClusters[itemEnd-si->position];
3216 itemEnd = si->position + itemLength;
3217 glyphsEnd = si->num_glyphs;
3219 // show soft-hyphen at line-break
3220 if (si->position + itemLength >= lineEnd
3221 && eng->layoutData->string.at(lineEnd - 1) == 0x00ad)
3222 glyphs.attributes[glyphsEnd - 1].dontPrint = false;
3225 for (int g = glyphsStart; g < glyphsEnd; ++g)
3226 itemWidth += glyphs.effectiveAdvance(g);
3231 bool QTextLineItemIterator::getSelectionBounds(QFixed *selectionX, QFixed *selectionWidth) const
3233 *selectionX = *selectionWidth = 0;
3238 if (si->analysis.flags >= QScriptAnalysis::TabOrObject) {
3239 if (si->position >= selection->start + selection->length
3240 || si->position + itemLength <= selection->start)
3244 *selectionWidth = itemWidth;
3246 unsigned short *logClusters = eng->logClusters(si);
3247 QGlyphLayout glyphs = eng->shapedGlyphs(si);
3249 int from = qMax(itemStart, selection->start) - si->position;
3250 int to = qMin(itemEnd, selection->start + selection->length) - si->position;
3254 int start_glyph = logClusters[from];
3255 int end_glyph = (to == eng->length(item)) ? si->num_glyphs : logClusters[to];
3258 if (si->analysis.bidiLevel %2) {
3259 for (int g = glyphsEnd - 1; g >= end_glyph; --g)
3260 soff += glyphs.effectiveAdvance(g);
3261 for (int g = end_glyph - 1; g >= start_glyph; --g)
3262 swidth += glyphs.effectiveAdvance(g);
3264 for (int g = glyphsStart; g < start_glyph; ++g)
3265 soff += glyphs.effectiveAdvance(g);
3266 for (int g = start_glyph; g < end_glyph; ++g)
3267 swidth += glyphs.effectiveAdvance(g);
3270 // If the starting character is in the middle of a ligature,
3271 // selection should only contain the right part of that ligature
3272 // glyph, so we need to get the width of the left part here and
3273 // add it to *selectionX
3274 QFixed leftOffsetInLigature = eng->offsetInLigature(si, from, to, start_glyph);
3275 *selectionX = x + soff + leftOffsetInLigature;
3276 *selectionWidth = swidth - leftOffsetInLigature;
3277 // If the ending character is also part of a ligature, swidth does
3278 // not contain that part yet, we also need to find out the width of
3280 *selectionWidth += eng->offsetInLigature(si, to, eng->length(item), end_glyph);