1 /****************************************************************************
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtGui module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** 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 "qtextdocument_p.h"
56 #include <qapplication.h>
63 // Helper class used in QTextEngine::itemize
64 // keep it out here to allow us to keep supporting various compilers.
67 Itemizer(const QString &string, const QScriptAnalysis *analysis, QScriptItemArray &items)
79 /// generate the script items
80 /// The caps parameter is used to choose the algoritm of splitting text and assiging roles to the textitems
81 void generate(int start, int length, QFont::Capitalization caps)
83 if ((int)caps == (int)QFont::SmallCaps)
84 generateScriptItemsSmallCaps(reinterpret_cast<const ushort *>(m_string.unicode()), start, length);
85 else if(caps == QFont::Capitalize)
86 generateScriptItemsCapitalize(start, length);
87 else if(caps != QFont::MixedCase) {
88 generateScriptItemsAndChangeCase(start, length,
89 caps == QFont::AllLowercase ? QScriptAnalysis::Lowercase : QScriptAnalysis::Uppercase);
92 generateScriptItems(start, length);
96 enum { MaxItemLength = 4096 };
98 void generateScriptItemsAndChangeCase(int start, int length, QScriptAnalysis::Flags flags)
100 generateScriptItems(start, length);
101 if (m_items.isEmpty()) // the next loop won't work in that case
103 QScriptItemArray::Iterator iter = m_items.end();
106 if (iter->analysis.flags < QScriptAnalysis::TabOrObject)
107 iter->analysis.flags = flags;
108 } while (iter->position > start);
111 void generateScriptItems(int start, int length)
115 const int end = start + length;
116 for (int i = start + 1; i < end; ++i) {
117 if ((m_analysis[i] == m_analysis[start])
118 && m_analysis[i].flags < QScriptAnalysis::SpaceTabOrObject
119 && i - start < MaxItemLength)
121 m_items.append(QScriptItem(start, m_analysis[start]));
124 m_items.append(QScriptItem(start, m_analysis[start]));
127 void generateScriptItemsCapitalize(int start, int length)
133 m_splitter = new QTextBoundaryFinder(QTextBoundaryFinder::Word,
134 m_string.constData(), m_string.length(),
135 /*buffer*/0, /*buffer size*/0);
137 m_splitter->setPosition(start);
138 QScriptAnalysis itemAnalysis = m_analysis[start];
140 if (m_splitter->boundaryReasons() & QTextBoundaryFinder::StartWord) {
141 itemAnalysis.flags = QScriptAnalysis::Uppercase;
142 m_splitter->toNextBoundary();
145 const int end = start + length;
146 for (int i = start + 1; i < end; ++i) {
148 bool atWordBoundary = false;
150 if (i == m_splitter->position()) {
151 if (m_splitter->boundaryReasons() & QTextBoundaryFinder::StartWord
152 && m_analysis[i].flags < QScriptAnalysis::TabOrObject)
153 atWordBoundary = true;
155 m_splitter->toNextBoundary();
158 if (m_analysis[i] == itemAnalysis
159 && m_analysis[i].flags < QScriptAnalysis::TabOrObject
161 && i - start < MaxItemLength)
164 m_items.append(QScriptItem(start, itemAnalysis));
166 itemAnalysis = m_analysis[start];
169 itemAnalysis.flags = QScriptAnalysis::Uppercase;
171 m_items.append(QScriptItem(start, itemAnalysis));
174 void generateScriptItemsSmallCaps(const ushort *uc, int start, int length)
178 bool lower = (QChar::category(uc[start]) == QChar::Letter_Lowercase);
179 const int end = start + length;
180 // split text into parts that are already uppercase and parts that are lowercase, and mark the latter to be uppercased later.
181 for (int i = start + 1; i < end; ++i) {
182 bool l = (QChar::category(uc[i]) == QChar::Letter_Lowercase);
183 if ((m_analysis[i] == m_analysis[start])
184 && m_analysis[i].flags < QScriptAnalysis::TabOrObject
186 && i - start < MaxItemLength)
188 m_items.append(QScriptItem(start, m_analysis[start]));
190 m_items.last().analysis.flags = QScriptAnalysis::SmallCaps;
195 m_items.append(QScriptItem(start, m_analysis[start]));
197 m_items.last().analysis.flags = QScriptAnalysis::SmallCaps;
200 const QString &m_string;
201 const QScriptAnalysis * const m_analysis;
202 QScriptItemArray &m_items;
203 QTextBoundaryFinder *m_splitter;
208 // ----------------------------------------------------------------------------
210 // The BiDi algorithm
212 // ----------------------------------------------------------------------------
215 #if (BIDI_DEBUG >= 1)
216 QT_BEGIN_INCLUDE_NAMESPACE
218 QT_END_INCLUDE_NAMESPACE
221 static const char *directions[] = {
222 "DirL", "DirR", "DirEN", "DirES", "DirET", "DirAN", "DirCS", "DirB", "DirS", "DirWS", "DirON",
223 "DirLRE", "DirLRO", "DirAL", "DirRLE", "DirRLO", "DirPDF", "DirNSM", "DirBN"
231 lastStrong = QChar::DirON;
232 last = QChar:: DirON;
235 QChar::Direction eor;
236 QChar::Direction lastStrong;
237 QChar::Direction last;
238 QChar::Direction dir;
241 enum { MaxBidiLevel = 61 };
243 struct QBidiControl {
244 inline QBidiControl(bool rtl)
245 : cCtx(0), base(rtl ? 1 : 0), level(rtl ? 1 : 0), override(false) {}
247 inline void embed(bool rtl, bool o = false) {
248 unsigned int toAdd = 1;
249 if((level%2 != 0) == rtl ) {
252 if (level + toAdd <= MaxBidiLevel) {
253 ctx[cCtx].level = level;
254 ctx[cCtx].override = override;
260 inline bool canPop() const { return cCtx != 0; }
264 level = ctx[cCtx].level;
265 override = ctx[cCtx].override;
268 inline QChar::Direction basicDirection() const {
269 return (base ? QChar::DirR : QChar:: DirL);
271 inline unsigned int baseLevel() const {
274 inline QChar::Direction direction() const {
275 return ((level%2) ? QChar::DirR : QChar:: DirL);
283 const unsigned int base;
289 static void appendItems(QScriptAnalysis *analysis, int &start, int &stop, const QBidiControl &control, QChar::Direction dir)
294 int level = control.level;
296 if(dir != QChar::DirON && !control.override) {
297 // add level of run (cases I1 & I2)
299 if(dir == QChar::DirL || dir == QChar::DirAN || dir == QChar::DirEN)
302 if(dir == QChar::DirR)
304 else if(dir == QChar::DirAN || dir == QChar::DirEN)
309 #if (BIDI_DEBUG >= 1)
310 qDebug("new run: dir=%s from %d, to %d level = %d override=%d", directions[dir], start, stop, level, control.override);
312 QScriptAnalysis *s = analysis + start;
313 const QScriptAnalysis *e = analysis + stop;
315 s->bidiLevel = level;
322 static QChar::Direction skipBoundryNeutrals(QScriptAnalysis *analysis,
323 const ushort *unicode, int length,
324 int &sor, int &eor, QBidiControl &control)
326 QChar::Direction dir = control.basicDirection();
327 int level = sor > 0 ? analysis[sor - 1].bidiLevel : control.level;
328 while (sor < length) {
329 dir = QChar::direction(unicode[sor]);
330 // Keep skipping DirBN as if it doesn't exist
331 if (dir != QChar::DirBN)
333 analysis[sor++].bidiLevel = level;
338 dir = control.basicDirection();
343 // creates the next QScript items.
344 static bool bidiItemize(QTextEngine *engine, QScriptAnalysis *analysis, QBidiControl &control)
346 bool rightToLeft = (control.basicDirection() == 1);
347 bool hasBidi = rightToLeft;
349 qDebug() << "bidiItemize: rightToLeft=" << rightToLeft << engine->layoutData->string;
356 int length = engine->layoutData->string.length();
358 const ushort *unicode = (const ushort *)engine->layoutData->string.unicode();
361 QChar::Direction dir = rightToLeft ? QChar::DirR : QChar::DirL;
364 QChar::Direction sdir = QChar::direction(*unicode);
365 if (sdir != QChar::DirL && sdir != QChar::DirR && sdir != QChar::DirEN && sdir != QChar::DirAN)
370 status.lastStrong = rightToLeft ? QChar::DirR : QChar::DirL;
371 status.last = status.lastStrong;
375 while (current <= length) {
377 QChar::Direction dirCurrent;
378 if (current == (int)length)
379 dirCurrent = control.basicDirection();
381 dirCurrent = QChar::direction(unicode[current]);
383 #if (BIDI_DEBUG >= 2)
384 // qDebug() << "pos=" << current << " dir=" << directions[dir]
385 // << " current=" << directions[dirCurrent] << " last=" << directions[status.last]
386 // << " eor=" << eor << '/' << directions[status.eor]
387 // << " sor=" << sor << " lastStrong="
388 // << directions[status.lastStrong]
389 // << " level=" << (int)control.level << " override=" << (bool)control.override;
394 // embedding and overrides (X1-X9 in the BiDi specs)
400 bool rtl = (dirCurrent == QChar::DirRLE || dirCurrent == QChar::DirRLO);
402 bool override = (dirCurrent == QChar::DirLRO || dirCurrent == QChar::DirRLO);
404 unsigned int level = control.level+1;
405 if ((level%2 != 0) == rtl) ++level;
406 if(level < MaxBidiLevel) {
408 appendItems(analysis, sor, eor, control, dir);
410 control.embed(rtl, override);
411 QChar::Direction edir = (rtl ? QChar::DirR : QChar::DirL);
412 dir = status.eor = edir;
413 status.lastStrong = edir;
419 if (control.canPop()) {
420 if (dir != control.direction()) {
422 appendItems(analysis, sor, eor, control, dir);
423 dir = control.direction();
426 appendItems(analysis, sor, eor, control, dir);
428 dir = QChar::DirON; status.eor = QChar::DirON;
429 status.last = control.direction();
430 if (control.override)
431 dir = control.direction();
434 status.lastStrong = control.direction();
441 if(dir == QChar::DirON)
446 eor = current; status.eor = QChar::DirL; break;
452 appendItems(analysis, sor, eor, control, dir);
453 status.eor = dir = skipBoundryNeutrals(analysis, unicode, length, sor, eor, control);
455 eor = current; status.eor = dir;
466 if(dir != QChar::DirL) {
467 //last stuff takes embedding dir
468 if(control.direction() == QChar::DirR) {
469 if(status.eor != QChar::DirR) {
471 appendItems(analysis, sor, eor, control, dir);
472 status.eor = QChar::DirON;
476 appendItems(analysis, sor, eor, control, dir);
477 status.eor = dir = skipBoundryNeutrals(analysis, unicode, length, sor, eor, control);
479 if(status.eor != QChar::DirL) {
480 appendItems(analysis, sor, eor, control, dir);
481 status.eor = QChar::DirON;
484 eor = current; status.eor = QChar::DirL; break;
488 eor = current; status.eor = QChar::DirL;
493 status.lastStrong = QChar::DirL;
498 if(dir == QChar::DirON) dir = QChar::DirR;
505 appendItems(analysis, sor, eor, control, dir);
509 dir = QChar::DirR; eor = current; status.eor = QChar::DirR; break;
518 if(status.eor != QChar::DirR && status.eor != QChar::DirAL) {
519 //last stuff takes embedding dir
520 if(control.direction() == QChar::DirR
521 || status.lastStrong == QChar::DirR || status.lastStrong == QChar::DirAL) {
522 appendItems(analysis, sor, eor, control, dir);
523 dir = QChar::DirR; status.eor = QChar::DirON;
527 appendItems(analysis, sor, eor, control, dir);
528 dir = QChar::DirR; status.eor = QChar::DirON;
531 eor = current; status.eor = QChar::DirR;
536 status.lastStrong = dirCurrent;
542 if (eor == current-1)
546 // if last strong was AL change EN to AN
547 if(status.lastStrong != QChar::DirAL) {
548 if(dir == QChar::DirON) {
549 if(status.lastStrong == QChar::DirL)
557 if (status.lastStrong == QChar::DirR || status.lastStrong == QChar::DirAL) {
558 appendItems(analysis, sor, eor, control, dir);
559 status.eor = QChar::DirON;
566 status.eor = dirCurrent;
572 appendItems(analysis, sor, eor, control, dir);
575 status.eor = QChar::DirEN;
576 dir = QChar::DirAN; break;
579 if(status.eor == QChar::DirEN || dir == QChar::DirAN) {
580 eor = current; break;
587 if(status.eor == QChar::DirR) {
590 appendItems(analysis, sor, eor, control, dir);
591 dir = QChar::DirON; status.eor = QChar::DirEN;
594 else if(status.eor == QChar::DirL ||
595 (status.eor == QChar::DirEN && status.lastStrong == QChar::DirL)) {
596 eor = current; status.eor = dirCurrent;
598 // numbers on both sides, neutrals get right to left direction
599 if(dir != QChar::DirL) {
600 appendItems(analysis, sor, eor, control, dir);
601 dir = QChar::DirON; status.eor = QChar::DirON;
604 appendItems(analysis, sor, eor, control, dir);
605 dir = QChar::DirON; status.eor = QChar::DirON;
608 eor = current; status.eor = dirCurrent;
618 dirCurrent = QChar::DirAN;
619 if(dir == QChar::DirON) dir = QChar::DirAN;
624 eor = current; status.eor = QChar::DirAN; break;
629 appendItems(analysis, sor, eor, control, dir);
633 dir = QChar::DirAN; status.eor = QChar::DirAN;
636 if(status.eor == QChar::DirAN) {
637 eor = current; break;
646 if(status.eor == QChar::DirR) {
649 appendItems(analysis, sor, eor, control, dir);
650 status.eor = QChar::DirAN;
652 } else if(status.eor == QChar::DirL ||
653 (status.eor == QChar::DirEN && status.lastStrong == QChar::DirL)) {
654 eor = current; status.eor = dirCurrent;
656 // numbers on both sides, neutrals get right to left direction
657 if(dir != QChar::DirL) {
658 appendItems(analysis, sor, eor, control, dir);
659 status.eor = QChar::DirON;
662 appendItems(analysis, sor, eor, control, dir);
663 status.eor = QChar::DirAN;
666 eor = current; status.eor = dirCurrent;
677 if(status.last == QChar::DirEN) {
678 dirCurrent = QChar::DirEN;
679 eor = current; status.eor = dirCurrent;
683 // boundary neutrals should be ignored
688 // ### what do we do with newline and paragraph separators that come to here?
691 // ### implement rule L1
700 //qDebug() << " after: dir=" << // dir << " current=" << dirCurrent << " last=" << status.last << " eor=" << status.eor << " lastStrong=" << status.lastStrong << " embedding=" << control.direction();
702 if(current >= (int)length) break;
704 // set status.last as needed.
719 status.last = dirCurrent;
722 status.last = QChar::DirON;
731 status.last = QChar::DirL;
735 status.last = QChar::DirR;
738 if (status.last == QChar::DirL) {
739 status.last = QChar::DirL;
744 status.last = dirCurrent;
750 #if (BIDI_DEBUG >= 1)
751 qDebug() << "reached end of line current=" << current << ", eor=" << eor;
753 eor = current - 1; // remove dummy char
756 appendItems(analysis, sor, eor, control, dir);
761 void QTextEngine::bidiReorder(int numItems, const quint8 *levels, int *visualOrder)
764 // first find highest and lowest levels
765 quint8 levelLow = 128;
766 quint8 levelHigh = 0;
768 while (i < numItems) {
769 //printf("level = %d\n", r->level);
770 if (levels[i] > levelHigh)
771 levelHigh = levels[i];
772 if (levels[i] < levelLow)
773 levelLow = levels[i];
777 // implements reordering of the line (L2 according to BiDi spec):
778 // L2. From the highest level found in the text to the lowest odd level on each line,
779 // reverse any contiguous sequence of characters that are at that level or higher.
781 // reversing is only done up to the lowest odd level
782 if(!(levelLow%2)) levelLow++;
784 #if (BIDI_DEBUG >= 1)
785 // qDebug() << "reorderLine: lineLow = " << (uint)levelLow << ", lineHigh = " << (uint)levelHigh;
788 int count = numItems - 1;
789 for (i = 0; i < numItems; i++)
792 while(levelHigh >= levelLow) {
795 while(i < count && levels[i] < levelHigh) i++;
797 while(i <= count && levels[i] >= levelHigh) i++;
801 //qDebug() << "reversing from " << start << " to " << end;
802 for(int j = 0; j < (end-start+1)/2; j++) {
803 int tmp = visualOrder[start+j];
804 visualOrder[start+j] = visualOrder[end-j];
805 visualOrder[end-j] = tmp;
813 #if (BIDI_DEBUG >= 1)
814 // qDebug() << "visual order is:";
815 // for (i = 0; i < numItems; i++)
816 // qDebug() << visualOrder[i];
820 QT_BEGIN_INCLUDE_NAMESPACE
822 #if defined(Q_WS_X11) || defined (Q_WS_QWS)
823 # include "qfontengine_ft_p.h"
824 #elif defined(Q_WS_MAC)
825 # include "qtextengine_mac.cpp"
828 #include <private/qharfbuzz_p.h>
830 QT_END_INCLUDE_NAMESPACE
832 // ask the font engine to find out which glyphs (as an index in the specific font) to use for the text in one item.
833 static bool stringToGlyphs(HB_ShaperItem *item, QGlyphLayout *glyphs, QFontEngine *fontEngine)
835 int nGlyphs = item->num_glyphs;
837 QTextEngine::ShaperFlags shaperFlags(QTextEngine::GlyphIndicesOnly);
838 if (item->item.bidiLevel % 2)
839 shaperFlags |= QTextEngine::RightToLeft;
841 bool result = fontEngine->stringToCMap(reinterpret_cast<const QChar *>(item->string + item->item.pos), item->item.length, glyphs, &nGlyphs, shaperFlags);
842 item->num_glyphs = nGlyphs;
843 glyphs->numGlyphs = nGlyphs;
847 // shape all the items that intersect with the line, taking tab widths into account to find out what text actually fits in the line.
848 void QTextEngine::shapeLine(const QScriptLine &line)
852 const int end = findItem(line.from + line.length - 1);
853 int item = findItem(line.from);
856 for (item = findItem(line.from); item <= end; ++item) {
857 QScriptItem &si = layoutData->items[item];
858 if (si.analysis.flags == QScriptAnalysis::Tab) {
860 si.width = calculateTabWidth(item, x);
864 if (first && si.position != line.from) { // that means our x position has to be offset
865 QGlyphLayout glyphs = shapedGlyphs(&si);
866 Q_ASSERT(line.from > si.position);
867 for (int i = line.from - si.position - 1; i >= 0; i--) {
868 x -= glyphs.effectiveAdvance(i);
877 #if !defined(QT_ENABLE_HARFBUZZ_FOR_MAC) && defined(Q_WS_MAC)
878 static bool enableHarfBuzz()
880 static enum { Yes, No, Unknown } status = Unknown;
882 if (status == Unknown) {
883 QByteArray v = qgetenv("QT_ENABLE_HARFBUZZ");
884 bool value = !v.isEmpty() && v != "0" && v != "false";
885 if (value) status = Yes;
888 return status == Yes;
892 void QTextEngine::shapeText(int item) const
894 Q_ASSERT(item < layoutData->items.size());
895 QScriptItem &si = layoutData->items[item];
900 #if defined(Q_WS_MAC)
901 #if !defined(QT_ENABLE_HARFBUZZ_FOR_MAC)
902 if (enableHarfBuzz()) {
904 QFontEngine *actualFontEngine = fontEngine(si, &si.ascent, &si.descent, &si.leading);
905 if (actualFontEngine->type() == QFontEngine::Multi)
906 actualFontEngine = static_cast<QFontEngineMulti *>(actualFontEngine)->engine(0);
908 HB_Face face = actualFontEngine->harfbuzzFace();
909 HB_Script script = (HB_Script) si.analysis.script;
910 if (face->supported_scripts[script])
911 shapeTextWithHarfbuzz(item);
914 #if !defined(QT_ENABLE_HARFBUZZ_FOR_MAC)
919 #elif defined(Q_WS_WINCE)
920 shapeTextWithCE(item);
922 shapeTextWithHarfbuzz(item);
929 QGlyphLayout glyphs = shapedGlyphs(&si);
931 QFont font = this->font(si);
932 bool letterSpacingIsAbsolute = font.d->letterSpacingIsAbsolute;
933 QFixed letterSpacing = font.d->letterSpacing;
934 QFixed wordSpacing = font.d->wordSpacing;
936 if (letterSpacingIsAbsolute && letterSpacing.value())
937 letterSpacing *= font.d->dpi / qt_defaultDpiY();
939 if (letterSpacing != 0) {
940 for (int i = 1; i < si.num_glyphs; ++i) {
941 if (glyphs.attributes[i].clusterStart) {
942 if (letterSpacingIsAbsolute)
943 glyphs.advances_x[i-1] += letterSpacing;
945 QFixed &advance = glyphs.advances_x[i-1];
946 advance += (letterSpacing - 100) * advance / 100;
950 if (letterSpacingIsAbsolute)
951 glyphs.advances_x[si.num_glyphs-1] += letterSpacing;
953 QFixed &advance = glyphs.advances_x[si.num_glyphs-1];
954 advance += (letterSpacing - 100) * advance / 100;
957 if (wordSpacing != 0) {
958 for (int i = 0; i < si.num_glyphs; ++i) {
959 if (glyphs.attributes[i].justification == HB_Space
960 || glyphs.attributes[i].justification == HB_Arabic_Space) {
961 // word spacing only gets added once to a consecutive run of spaces (see CSS spec)
962 if (i + 1 == si.num_glyphs
963 ||(glyphs.attributes[i+1].justification != HB_Space
964 && glyphs.attributes[i+1].justification != HB_Arabic_Space))
965 glyphs.advances_x[i] += wordSpacing;
970 for (int i = 0; i < si.num_glyphs; ++i)
971 si.width += glyphs.advances_x[i];
974 static inline bool hasCaseChange(const QScriptItem &si)
976 return si.analysis.flags == QScriptAnalysis::SmallCaps ||
977 si.analysis.flags == QScriptAnalysis::Uppercase ||
978 si.analysis.flags == QScriptAnalysis::Lowercase;
981 #if defined(Q_WS_WINCE) //TODO
982 // set the glyph attributes heuristically. Assumes a 1 to 1 relationship between chars and glyphs
983 // and no reordering.
984 // also computes logClusters heuristically
985 static void heuristicSetGlyphAttributes(const QChar *uc, int length, QGlyphLayout *glyphs, unsigned short *logClusters, int num_glyphs)
987 // ### zeroWidth and justification are missing here!!!!!
989 Q_UNUSED(num_glyphs);
990 Q_ASSERT(num_glyphs <= length);
992 // qDebug("QScriptEngine::heuristicSetGlyphAttributes, num_glyphs=%d", item->num_glyphs);
995 for (int i = 0; i < length; i++) {
996 if (uc[i].unicode() >= 0xd800 && uc[i].unicode() < 0xdc00 && i < length-1
997 && uc[i+1].unicode() >= 0xdc00 && uc[i+1].unicode() < 0xe000) {
998 logClusters[i] = glyph_pos;
999 logClusters[++i] = glyph_pos;
1001 logClusters[i] = glyph_pos;
1006 // first char in a run is never (treated as) a mark
1009 const bool symbolFont = false; // ####
1010 glyphs->attributes[0].mark = false;
1011 glyphs->attributes[0].clusterStart = true;
1012 glyphs->attributes[0].dontPrint = (!symbolFont && uc[0].unicode() == 0x00ad) || qIsControlChar(uc[0].unicode());
1015 int lastCat = QChar::category(uc[0].unicode());
1016 for (int i = 1; i < length; ++i) {
1017 if (logClusters[i] == pos)
1021 while (pos < logClusters[i]) {
1022 glyphs[pos].attributes = glyphs[pos-1].attributes;
1025 // hide soft-hyphens by default
1026 if ((!symbolFont && uc[i].unicode() == 0x00ad) || qIsControlChar(uc[i].unicode()))
1027 glyphs->attributes[pos].dontPrint = true;
1028 const QUnicodeTables::Properties *prop = QUnicodeTables::properties(uc[i].unicode());
1029 int cat = prop->category;
1030 if (cat != QChar::Mark_NonSpacing) {
1031 glyphs->attributes[pos].mark = false;
1032 glyphs->attributes[pos].clusterStart = true;
1033 glyphs->attributes[pos].combiningClass = 0;
1034 cStart = logClusters[i];
1036 int cmb = prop->combiningClass;
1039 // Fix 0 combining classes
1040 if ((uc[pos].unicode() & 0xff00) == 0x0e00) {
1042 unsigned char col = uc[pos].cell();
1052 cmb = QChar::Combining_AboveRight;
1053 } else if (col == 0xb1 ||
1061 cmb = QChar::Combining_Above;
1062 } else if (col == 0xbc) {
1063 cmb = QChar::Combining_Below;
1068 glyphs->attributes[pos].mark = true;
1069 glyphs->attributes[pos].clusterStart = false;
1070 glyphs->attributes[pos].combiningClass = cmb;
1071 logClusters[i] = cStart;
1072 glyphs->advances_x[pos] = 0;
1073 glyphs->advances_y[pos] = 0;
1076 // one gets an inter character justification point if the current char is not a non spacing mark.
1077 // as then the current char belongs to the last one and one gets a space justification point
1078 // after the space char.
1079 if (lastCat == QChar::Separator_Space)
1080 glyphs->attributes[pos-1].justification = HB_Space;
1081 else if (cat != QChar::Mark_NonSpacing)
1082 glyphs->attributes[pos-1].justification = HB_Character;
1084 glyphs->attributes[pos-1].justification = HB_NoJustification;
1088 pos = logClusters[length-1];
1089 if (lastCat == QChar::Separator_Space)
1090 glyphs->attributes[pos].justification = HB_Space;
1092 glyphs->attributes[pos].justification = HB_Character;
1095 void QTextEngine::shapeTextWithCE(int item) const
1097 QScriptItem &si = layoutData->items[item];
1098 si.glyph_data_offset = layoutData->used;
1100 QFontEngine *fe = fontEngine(si, &si.ascent, &si.descent, &si.leading);
1102 QTextEngine::ShaperFlags flags;
1103 if (si.analysis.bidiLevel % 2)
1104 flags |= RightToLeft;
1105 if (option.useDesignMetrics())
1106 flags |= DesignMetrics;
1108 // pre-initialize char attributes
1112 const int len = length(item);
1113 int num_glyphs = length(item);
1114 const QChar *str = layoutData->string.unicode() + si.position;
1115 ushort upperCased[256];
1116 if (hasCaseChange(si)) {
1117 ushort *uc = upperCased;
1119 uc = new ushort[len];
1120 for (int i = 0; i < len; ++i) {
1121 if(si.analysis.flags == QScriptAnalysis::Lowercase)
1122 uc[i] = str[i].toLower().unicode();
1124 uc[i] = str[i].toUpper().unicode();
1126 str = reinterpret_cast<const QChar *>(uc);
1130 if (! ensureSpace(num_glyphs)) {
1131 // If str is converted to uppercase/lowercase form with a new buffer,
1132 // we need to delete that buffer before return for error
1133 const ushort *uc = reinterpret_cast<const ushort *>(str);
1134 if (hasCaseChange(si) && uc != upperCased)
1138 num_glyphs = layoutData->glyphLayout.numGlyphs - layoutData->used;
1140 QGlyphLayout g = availableGlyphs(&si);
1141 unsigned short *log_clusters = logClusters(&si);
1143 if (fe->stringToCMap(str,
1148 heuristicSetGlyphAttributes(str, len, &g, log_clusters, num_glyphs);
1153 si.num_glyphs = num_glyphs;
1155 layoutData->used += si.num_glyphs;
1157 const ushort *uc = reinterpret_cast<const ushort *>(str);
1158 if (hasCaseChange(si) && uc != upperCased)
1163 static inline void moveGlyphData(const QGlyphLayout &destination, const QGlyphLayout &source, int num)
1165 if (num > 0 && destination.glyphs != source.glyphs) {
1166 memmove(destination.glyphs, source.glyphs, num * sizeof(HB_Glyph));
1167 memmove(destination.attributes, source.attributes, num * sizeof(HB_GlyphAttributes));
1168 memmove(destination.advances_x, source.advances_x, num * sizeof(HB_Fixed));
1169 memmove(destination.offsets, source.offsets, num * sizeof(HB_FixedPoint));
1173 /// take the item from layoutData->items and
1174 void QTextEngine::shapeTextWithHarfbuzz(int item) const
1176 Q_ASSERT(sizeof(HB_Fixed) == sizeof(QFixed));
1177 Q_ASSERT(sizeof(HB_FixedPoint) == sizeof(QFixedPoint));
1179 QScriptItem &si = layoutData->items[item];
1181 si.glyph_data_offset = layoutData->used;
1183 QFontEngine *font = fontEngine(si, &si.ascent, &si.descent, &si.leading);
1185 bool kerningEnabled = this->font(si).d->kerning;
1187 HB_ShaperItem entire_shaper_item;
1188 qMemSet(&entire_shaper_item, 0, sizeof(entire_shaper_item));
1189 entire_shaper_item.string = reinterpret_cast<const HB_UChar16 *>(layoutData->string.constData());
1190 entire_shaper_item.stringLength = layoutData->string.length();
1191 entire_shaper_item.item.script = (HB_Script)si.analysis.script;
1192 entire_shaper_item.item.pos = si.position;
1193 entire_shaper_item.item.length = length(item);
1194 entire_shaper_item.item.bidiLevel = si.analysis.bidiLevel;
1196 HB_UChar16 upperCased[256]; // XXX what about making this 4096, so we don't have to extend it ever.
1197 if (hasCaseChange(si)) {
1198 HB_UChar16 *uc = upperCased;
1199 if (entire_shaper_item.item.length > 256)
1200 uc = new HB_UChar16[entire_shaper_item.item.length];
1201 for (uint i = 0; i < entire_shaper_item.item.length; ++i) {
1202 if(si.analysis.flags == QScriptAnalysis::Lowercase)
1203 uc[i] = QChar::toLower(entire_shaper_item.string[si.position + i]);
1205 uc[i] = QChar::toUpper(entire_shaper_item.string[si.position + i]);
1207 entire_shaper_item.item.pos = 0;
1208 entire_shaper_item.string = uc;
1209 entire_shaper_item.stringLength = entire_shaper_item.item.length;
1212 entire_shaper_item.shaperFlags = 0;
1213 if (!kerningEnabled)
1214 entire_shaper_item.shaperFlags |= HB_ShaperFlag_NoKerning;
1215 if (option.useDesignMetrics())
1216 entire_shaper_item.shaperFlags |= HB_ShaperFlag_UseDesignMetrics;
1218 entire_shaper_item.num_glyphs = qMax(layoutData->glyphLayout.numGlyphs - layoutData->used, int(entire_shaper_item.item.length));
1219 if (! ensureSpace(entire_shaper_item.num_glyphs)) {
1220 if (hasCaseChange(si))
1221 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1224 QGlyphLayout initialGlyphs = availableGlyphs(&si).mid(0, entire_shaper_item.num_glyphs);
1226 if (!stringToGlyphs(&entire_shaper_item, &initialGlyphs, font)) {
1227 if (! ensureSpace(entire_shaper_item.num_glyphs)) {
1228 if (hasCaseChange(si))
1229 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1232 initialGlyphs = availableGlyphs(&si).mid(0, entire_shaper_item.num_glyphs);
1234 if (!stringToGlyphs(&entire_shaper_item, &initialGlyphs, font)) {
1235 // ############ if this happens there's a bug in the fontengine
1236 if (hasCaseChange(si) && entire_shaper_item.string != upperCased)
1237 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1242 // split up the item into parts that come from different font engines.
1243 QVarLengthArray<int> itemBoundaries(2);
1244 // k * 2 entries, array[k] == index in string, array[k + 1] == index in glyphs
1245 itemBoundaries[0] = entire_shaper_item.item.pos;
1246 itemBoundaries[1] = 0;
1248 if (font->type() == QFontEngine::Multi) {
1249 uint lastEngine = 0;
1250 int charIdx = entire_shaper_item.item.pos;
1251 const int stringEnd = charIdx + entire_shaper_item.item.length;
1252 for (quint32 i = 0; i < entire_shaper_item.num_glyphs; ++i, ++charIdx) {
1253 uint engineIdx = initialGlyphs.glyphs[i] >> 24;
1254 if (engineIdx != lastEngine && i > 0) {
1255 itemBoundaries.append(charIdx);
1256 itemBoundaries.append(i);
1258 lastEngine = engineIdx;
1259 if (HB_IsHighSurrogate(entire_shaper_item.string[charIdx])
1260 && charIdx < stringEnd - 1
1261 && HB_IsLowSurrogate(entire_shaper_item.string[charIdx + 1]))
1268 int remaining_glyphs = entire_shaper_item.num_glyphs;
1270 // for each item shape using harfbuzz and store the results in our layoutData's glyphs array.
1271 for (int k = 0; k < itemBoundaries.size(); k += 2) { // for the +2, see the comment at the definition of itemBoundaries
1273 HB_ShaperItem shaper_item = entire_shaper_item;
1275 shaper_item.item.pos = itemBoundaries[k];
1276 if (k < itemBoundaries.size() - 3) {
1277 shaper_item.item.length = itemBoundaries[k + 2] - shaper_item.item.pos;
1278 shaper_item.num_glyphs = itemBoundaries[k + 3] - itemBoundaries[k + 1];
1279 } else { // last combo in the list, avoid out of bounds access.
1280 shaper_item.item.length -= shaper_item.item.pos - entire_shaper_item.item.pos;
1281 shaper_item.num_glyphs -= itemBoundaries[k + 1];
1283 shaper_item.initialGlyphCount = shaper_item.num_glyphs;
1284 if (shaper_item.num_glyphs < shaper_item.item.length)
1285 shaper_item.num_glyphs = shaper_item.item.length;
1287 QFontEngine *actualFontEngine = font;
1289 if (font->type() == QFontEngine::Multi) {
1290 engineIdx = uint(availableGlyphs(&si).glyphs[glyph_pos] >> 24);
1292 actualFontEngine = static_cast<QFontEngineMulti *>(font)->engine(engineIdx);
1295 si.ascent = qMax(actualFontEngine->ascent(), si.ascent);
1296 si.descent = qMax(actualFontEngine->descent(), si.descent);
1297 si.leading = qMax(actualFontEngine->leading(), si.leading);
1299 shaper_item.font = actualFontEngine->harfbuzzFont();
1300 shaper_item.face = actualFontEngine->harfbuzzFace();
1302 shaper_item.glyphIndicesPresent = true;
1304 remaining_glyphs -= shaper_item.initialGlyphCount;
1307 if (! ensureSpace(glyph_pos + shaper_item.num_glyphs + remaining_glyphs)) {
1308 if (hasCaseChange(si))
1309 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1313 const QGlyphLayout g = availableGlyphs(&si).mid(glyph_pos);
1314 if (shaper_item.num_glyphs > shaper_item.item.length)
1315 moveGlyphData(g.mid(shaper_item.num_glyphs), g.mid(shaper_item.initialGlyphCount), remaining_glyphs);
1317 shaper_item.glyphs = g.glyphs;
1318 shaper_item.attributes = g.attributes;
1319 shaper_item.advances = reinterpret_cast<HB_Fixed *>(g.advances_x);
1320 shaper_item.offsets = reinterpret_cast<HB_FixedPoint *>(g.offsets);
1322 if (shaper_item.glyphIndicesPresent) {
1323 for (hb_uint32 i = 0; i < shaper_item.initialGlyphCount; ++i)
1324 shaper_item.glyphs[i] &= 0x00ffffff;
1327 shaper_item.log_clusters = logClusters(&si) + shaper_item.item.pos - entire_shaper_item.item.pos;
1329 // qDebug(" .. num_glyphs=%d, used=%d, item.num_glyphs=%d", num_glyphs, used, shaper_item.num_glyphs);
1330 } while (!qShapeItem(&shaper_item)); // this does the actual shaping via harfbuzz.
1332 QGlyphLayout g = availableGlyphs(&si).mid(glyph_pos, shaper_item.num_glyphs);
1333 moveGlyphData(g.mid(shaper_item.num_glyphs), g.mid(shaper_item.initialGlyphCount), remaining_glyphs);
1335 for (hb_uint32 i = 0; i < shaper_item.num_glyphs; ++i)
1336 g.glyphs[i] = g.glyphs[i] | (engineIdx << 24);
1338 for (hb_uint32 i = 0; i < shaper_item.item.length; ++i)
1339 shaper_item.log_clusters[i] += glyph_pos;
1341 if (kerningEnabled && !shaper_item.kerning_applied)
1342 font->doKerning(&g, option.useDesignMetrics() ? QFlag(QTextEngine::DesignMetrics) : QFlag(0));
1344 glyph_pos += shaper_item.num_glyphs;
1347 // qDebug(" -> item: script=%d num_glyphs=%d", shaper_item.script, shaper_item.num_glyphs);
1348 si.num_glyphs = glyph_pos;
1350 layoutData->used += si.num_glyphs;
1352 if (hasCaseChange(si) && entire_shaper_item.string != upperCased)
1353 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1356 static void init(QTextEngine *e)
1358 e->ignoreBidi = false;
1359 e->cacheGlyphs = false;
1360 e->forceJustification = false;
1361 e->visualMovement = false;
1368 e->underlinePositions = 0;
1370 e->stackEngine = false;
1373 QTextEngine::QTextEngine()
1378 QTextEngine::QTextEngine(const QString &str, const QFont &f)
1385 QTextEngine::~QTextEngine()
1392 const HB_CharAttributes *QTextEngine::attributes() const
1394 if (layoutData && layoutData->haveCharAttributes)
1395 return (HB_CharAttributes *) layoutData->memory;
1398 if (! ensureSpace(layoutData->string.length()))
1401 QVarLengthArray<HB_ScriptItem> hbScriptItems(layoutData->items.size());
1403 for (int i = 0; i < layoutData->items.size(); ++i) {
1404 const QScriptItem &si = layoutData->items[i];
1405 hbScriptItems[i].pos = si.position;
1406 hbScriptItems[i].length = length(i);
1407 hbScriptItems[i].bidiLevel = si.analysis.bidiLevel;
1408 hbScriptItems[i].script = (HB_Script)si.analysis.script;
1411 qGetCharAttributes(reinterpret_cast<const HB_UChar16 *>(layoutData->string.constData()),
1412 layoutData->string.length(),
1413 hbScriptItems.data(), hbScriptItems.size(),
1414 (HB_CharAttributes *)layoutData->memory);
1417 layoutData->haveCharAttributes = true;
1418 return (HB_CharAttributes *) layoutData->memory;
1421 void QTextEngine::shape(int item) const
1423 if (layoutData->items[item].analysis.flags == QScriptAnalysis::Object) {
1425 if (block.docHandle()) {
1426 QTextFormat format = formats()->format(formatIndex(&layoutData->items[item]));
1427 docLayout()->resizeInlineObject(QTextInlineObject(item, const_cast<QTextEngine *>(this)),
1428 layoutData->items[item].position + block.position(), format);
1430 } else if (layoutData->items[item].analysis.flags == QScriptAnalysis::Tab) {
1431 // set up at least the ascent/descent/leading of the script item for the tab
1432 fontEngine(layoutData->items[item],
1433 &layoutData->items[item].ascent,
1434 &layoutData->items[item].descent,
1435 &layoutData->items[item].leading);
1441 static inline void releaseCachedFontEngine(QFontEngine *fontEngine)
1444 fontEngine->ref.deref();
1445 if (fontEngine->cache_count == 0 && fontEngine->ref == 0)
1450 void QTextEngine::invalidate()
1456 specialData->resolvedFormatIndices.clear();
1458 releaseCachedFontEngine(feCache.prevFontEngine);
1459 releaseCachedFontEngine(feCache.prevScaledFontEngine);
1463 void QTextEngine::clearLineData()
1468 void QTextEngine::validate() const
1472 layoutData = new LayoutData();
1473 if (block.docHandle()) {
1474 layoutData->string = block.text();
1475 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators)
1476 layoutData->string += QLatin1Char(block.next().isValid() ? 0xb6 : 0x20);
1478 layoutData->string = text;
1480 if (specialData && specialData->preeditPosition != -1)
1481 layoutData->string.insert(specialData->preeditPosition, specialData->preeditText);
1484 void QTextEngine::itemize() const
1487 if (layoutData->items.size())
1490 int length = layoutData->string.length();
1493 #if defined(Q_WS_MAC) && !defined(QT_MAC_USE_COCOA)
1494 // ATSUI requires RTL flags to correctly identify the character stops.
1495 bool ignore = false;
1497 bool ignore = ignoreBidi;
1500 bool rtl = isRightToLeft();
1502 if (!ignore && !rtl) {
1504 const QChar *start = layoutData->string.unicode();
1505 const QChar * const end = start + length;
1506 while (start < end) {
1507 if (start->unicode() >= 0x590) {
1515 QVarLengthArray<QScriptAnalysis, 4096> scriptAnalysis(length);
1516 QScriptAnalysis *analysis = scriptAnalysis.data();
1518 QBidiControl control(rtl);
1521 memset(analysis, 0, length*sizeof(QScriptAnalysis));
1522 if (option.textDirection() == Qt::RightToLeft) {
1523 for (int i = 0; i < length; ++i)
1524 analysis[i].bidiLevel = 1;
1525 layoutData->hasBidi = true;
1528 layoutData->hasBidi = bidiItemize(const_cast<QTextEngine *>(this), analysis, control);
1531 const ushort *uc = reinterpret_cast<const ushort *>(layoutData->string.unicode());
1532 const ushort *e = uc + length;
1533 int lastScript = QUnicodeTables::Common;
1535 int script = QUnicodeTables::script(*uc);
1536 if (script == QUnicodeTables::Inherited)
1537 script = lastScript;
1538 analysis->flags = QScriptAnalysis::None;
1539 if (*uc == QChar::ObjectReplacementCharacter) {
1540 if (analysis->bidiLevel % 2)
1541 --analysis->bidiLevel;
1542 analysis->script = QUnicodeTables::Common;
1543 analysis->flags = QScriptAnalysis::Object;
1544 } else if (*uc == QChar::LineSeparator) {
1545 if (analysis->bidiLevel % 2)
1546 --analysis->bidiLevel;
1547 analysis->script = QUnicodeTables::Common;
1548 analysis->flags = QScriptAnalysis::LineOrParagraphSeparator;
1549 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators)
1550 *const_cast<ushort*>(uc) = 0x21B5; // visual line separator
1551 } else if (*uc == 9) {
1552 analysis->script = QUnicodeTables::Common;
1553 analysis->flags = QScriptAnalysis::Tab;
1554 analysis->bidiLevel = control.baseLevel();
1555 } else if ((*uc == 32 || *uc == QChar::Nbsp)
1556 && (option.flags() & QTextOption::ShowTabsAndSpaces)) {
1557 analysis->script = QUnicodeTables::Common;
1558 analysis->flags = QScriptAnalysis::Space;
1559 analysis->bidiLevel = control.baseLevel();
1561 analysis->script = script;
1563 lastScript = analysis->script;
1567 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators) {
1568 (analysis-1)->flags = QScriptAnalysis::LineOrParagraphSeparator; // to exclude it from width
1571 Itemizer itemizer(layoutData->string, scriptAnalysis.data(), layoutData->items);
1573 const QTextDocumentPrivate *p = block.docHandle();
1575 SpecialData *s = specialData;
1577 QTextDocumentPrivate::FragmentIterator it = p->find(block.position());
1578 QTextDocumentPrivate::FragmentIterator end = p->find(block.position() + block.length() - 1); // -1 to omit the block separator char
1579 int format = it.value()->format;
1581 int prevPosition = 0;
1582 int position = prevPosition;
1584 const QTextFragmentData * const frag = it.value();
1585 if (it == end || format != frag->format) {
1586 if (s && position >= s->preeditPosition) {
1587 position += s->preeditText.length();
1590 Q_ASSERT(position <= length);
1591 itemizer.generate(prevPosition, position - prevPosition,
1592 formats()->charFormat(format).fontCapitalization());
1594 if (position < length)
1595 itemizer.generate(position, length - position,
1596 formats()->charFormat(format).fontCapitalization());
1599 format = frag->format;
1600 prevPosition = position;
1602 position += frag->size_array[0];
1606 itemizer.generate(0, length, static_cast<QFont::Capitalization> (fnt.d->capital));
1609 addRequiredBoundaries();
1610 resolveAdditionalFormats();
1613 bool QTextEngine::isRightToLeft() const
1615 switch (option.textDirection()) {
1616 case Qt::LeftToRight:
1618 case Qt::RightToLeft:
1625 // this places the cursor in the right position depending on the keyboard layout
1626 if (layoutData->string.isEmpty())
1627 return QApplication::keyboardInputDirection() == Qt::RightToLeft;
1628 return layoutData->string.isRightToLeft();
1632 int QTextEngine::findItem(int strPos) const
1637 for (item = layoutData->items.size()-1; item > 0; --item) {
1638 if (layoutData->items[item].position <= strPos)
1644 QFixed QTextEngine::width(int from, int len) const
1650 // qDebug("QTextEngine::width(from = %d, len = %d), numItems=%d, strleng=%d", from, len, items.size(), string.length());
1651 for (int i = 0; i < layoutData->items.size(); i++) {
1652 const QScriptItem *si = layoutData->items.constData() + i;
1653 int pos = si->position;
1654 int ilen = length(i);
1655 // qDebug("item %d: from %d len %d", i, pos, ilen);
1656 if (pos >= from + len)
1658 if (pos + ilen > from) {
1659 if (!si->num_glyphs)
1662 if (si->analysis.flags == QScriptAnalysis::Object) {
1665 } else if (si->analysis.flags == QScriptAnalysis::Tab) {
1666 w += calculateTabWidth(i, w);
1671 QGlyphLayout glyphs = shapedGlyphs(si);
1672 unsigned short *logClusters = this->logClusters(si);
1674 // fprintf(stderr, " logclusters:");
1675 // for (int k = 0; k < ilen; k++)
1676 // fprintf(stderr, " %d", logClusters[k]);
1677 // fprintf(stderr, "\n");
1678 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1679 int charFrom = from - pos;
1682 int glyphStart = logClusters[charFrom];
1683 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1684 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1686 if (charFrom < ilen) {
1687 glyphStart = logClusters[charFrom];
1688 int charEnd = from + len - 1 - pos;
1689 if (charEnd >= ilen)
1691 int glyphEnd = logClusters[charEnd];
1692 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1694 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1696 // qDebug("char: start=%d end=%d / glyph: start = %d, end = %d", charFrom, charEnd, glyphStart, glyphEnd);
1697 for (int i = glyphStart; i < glyphEnd; i++)
1698 w += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
1702 // qDebug(" --> w= %d ", w);
1706 glyph_metrics_t QTextEngine::boundingBox(int from, int len) const
1712 for (int i = 0; i < layoutData->items.size(); i++) {
1713 const QScriptItem *si = layoutData->items.constData() + i;
1715 int pos = si->position;
1716 int ilen = length(i);
1717 if (pos > from + len)
1719 if (pos + ilen > from) {
1720 if (!si->num_glyphs)
1723 if (si->analysis.flags == QScriptAnalysis::Object) {
1724 gm.width += si->width;
1726 } else if (si->analysis.flags == QScriptAnalysis::Tab) {
1727 gm.width += calculateTabWidth(i, gm.width);
1731 unsigned short *logClusters = this->logClusters(si);
1732 QGlyphLayout glyphs = shapedGlyphs(si);
1734 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1735 int charFrom = from - pos;
1738 int glyphStart = logClusters[charFrom];
1739 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1740 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1742 if (charFrom < ilen) {
1743 QFontEngine *fe = fontEngine(*si);
1744 glyphStart = logClusters[charFrom];
1745 int charEnd = from + len - 1 - pos;
1746 if (charEnd >= ilen)
1748 int glyphEnd = logClusters[charEnd];
1749 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1751 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1752 if (glyphStart <= glyphEnd ) {
1753 glyph_metrics_t m = fe->boundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
1754 gm.x = qMin(gm.x, m.x + gm.xoff);
1755 gm.y = qMin(gm.y, m.y + gm.yoff);
1756 gm.width = qMax(gm.width, m.width+gm.xoff);
1757 gm.height = qMax(gm.height, m.height+gm.yoff);
1767 glyph_metrics_t QTextEngine::tightBoundingBox(int from, int len) const
1773 for (int i = 0; i < layoutData->items.size(); i++) {
1774 const QScriptItem *si = layoutData->items.constData() + i;
1775 int pos = si->position;
1776 int ilen = length(i);
1777 if (pos > from + len)
1779 if (pos + len > from) {
1780 if (!si->num_glyphs)
1782 unsigned short *logClusters = this->logClusters(si);
1783 QGlyphLayout glyphs = shapedGlyphs(si);
1785 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1786 int charFrom = from - pos;
1789 int glyphStart = logClusters[charFrom];
1790 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1791 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1793 if (charFrom < ilen) {
1794 glyphStart = logClusters[charFrom];
1795 int charEnd = from + len - 1 - pos;
1796 if (charEnd >= ilen)
1798 int glyphEnd = logClusters[charEnd];
1799 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1801 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1802 if (glyphStart <= glyphEnd ) {
1803 QFontEngine *fe = fontEngine(*si);
1804 glyph_metrics_t m = fe->tightBoundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
1805 gm.x = qMin(gm.x, m.x + gm.xoff);
1806 gm.y = qMin(gm.y, m.y + gm.yoff);
1807 gm.width = qMax(gm.width, m.width+gm.xoff);
1808 gm.height = qMax(gm.height, m.height+gm.yoff);
1818 QFont QTextEngine::font(const QScriptItem &si) const
1822 QTextCharFormat f = format(&si);
1825 if (block.docHandle() && block.docHandle()->layout()) {
1826 // Make sure we get the right dpi on printers
1827 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
1829 font = QFont(font, pdev);
1831 font = font.resolve(fnt);
1833 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
1834 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
1835 if (font.pointSize() != -1)
1836 font.setPointSize((font.pointSize() * 2) / 3);
1838 font.setPixelSize((font.pixelSize() * 2) / 3);
1842 if (si.analysis.flags == QScriptAnalysis::SmallCaps)
1843 font = font.d->smallCapsFont();
1848 QTextEngine::FontEngineCache::FontEngineCache()
1853 //we cache the previous results of this function, as calling it numerous times with the same effective
1854 //input is common (and hard to cache at a higher level)
1855 QFontEngine *QTextEngine::fontEngine(const QScriptItem &si, QFixed *ascent, QFixed *descent, QFixed *leading) const
1857 QFontEngine *engine = 0;
1858 QFontEngine *scaledEngine = 0;
1859 int script = si.analysis.script;
1863 if (feCache.prevFontEngine && feCache.prevPosition == si.position && feCache.prevLength == length(&si) && feCache.prevScript == script) {
1864 engine = feCache.prevFontEngine;
1865 scaledEngine = feCache.prevScaledFontEngine;
1867 QTextCharFormat f = format(&si);
1870 if (block.docHandle() && block.docHandle()->layout()) {
1871 // Make sure we get the right dpi on printers
1872 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
1874 font = QFont(font, pdev);
1876 font = font.resolve(fnt);
1878 engine = font.d->engineForScript(script);
1879 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
1880 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
1881 if (font.pointSize() != -1)
1882 font.setPointSize((font.pointSize() * 2) / 3);
1884 font.setPixelSize((font.pixelSize() * 2) / 3);
1885 scaledEngine = font.d->engineForScript(script);
1887 feCache.prevFontEngine = engine;
1890 feCache.prevScaledFontEngine = scaledEngine;
1892 scaledEngine->ref.ref();
1893 feCache.prevScript = script;
1894 feCache.prevPosition = si.position;
1895 feCache.prevLength = length(&si);
1898 if (feCache.prevFontEngine && feCache.prevScript == script && feCache.prevPosition == -1)
1899 engine = feCache.prevFontEngine;
1901 engine = font.d->engineForScript(script);
1902 feCache.prevFontEngine = engine;
1905 feCache.prevScript = script;
1906 feCache.prevPosition = -1;
1907 feCache.prevLength = -1;
1908 feCache.prevScaledFontEngine = 0;
1912 if (si.analysis.flags == QScriptAnalysis::SmallCaps) {
1913 QFontPrivate *p = font.d->smallCapsFontPrivate();
1914 scaledEngine = p->engineForScript(script);
1918 *ascent = engine->ascent();
1919 *descent = engine->descent();
1920 *leading = engine->leading();
1924 return scaledEngine;
1928 struct QJustificationPoint {
1930 QFixed kashidaWidth;
1932 QFontEngine *fontEngine;
1935 Q_DECLARE_TYPEINFO(QJustificationPoint, Q_PRIMITIVE_TYPE);
1937 static void set(QJustificationPoint *point, int type, const QGlyphLayout &glyph, QFontEngine *fe)
1940 point->glyph = glyph;
1941 point->fontEngine = fe;
1943 if (type >= HB_Arabic_Normal) {
1944 QChar ch(0x640); // Kashida character
1945 QGlyphLayoutArray<8> glyphs;
1947 fe->stringToCMap(&ch, 1, &glyphs, &nglyphs, 0);
1948 if (glyphs.glyphs[0] && glyphs.advances_x[0] != 0) {
1949 point->kashidaWidth = glyphs.advances_x[0];
1951 point->type = HB_NoJustification;
1952 point->kashidaWidth = 0;
1958 void QTextEngine::justify(const QScriptLine &line)
1960 // qDebug("justify: line.gridfitted = %d, line.justified=%d", line.gridfitted, line.justified);
1961 if (line.gridfitted && line.justified)
1964 if (!line.gridfitted) {
1965 // redo layout in device metrics, then adjust
1966 const_cast<QScriptLine &>(line).gridfitted = true;
1969 if ((option.alignment() & Qt::AlignHorizontal_Mask) != Qt::AlignJustify)
1974 if (!forceJustification) {
1975 int end = line.from + (int)line.length;
1976 if (end == layoutData->string.length())
1977 return; // no justification at end of paragraph
1978 if (end && layoutData->items[findItem(end-1)].analysis.flags == QScriptAnalysis::LineOrParagraphSeparator)
1979 return; // no justification at the end of an explicitly separated line
1985 // don't include trailing white spaces when doing justification
1986 int line_length = line.length;
1987 const HB_CharAttributes *a = attributes();
1991 while (line_length && a[line_length-1].whiteSpace)
1993 // subtract one char more, as we can't justfy after the last character
1999 int firstItem = findItem(line.from);
2000 int nItems = findItem(line.from + line_length - 1) - firstItem + 1;
2002 QVarLengthArray<QJustificationPoint> justificationPoints;
2004 // 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());
2005 QFixed minKashida = 0x100000;
2007 // we need to do all shaping before we go into the next loop, as we there
2008 // store pointers to the glyph data that could get reallocated by the shaping
2010 for (int i = 0; i < nItems; ++i) {
2011 QScriptItem &si = layoutData->items[firstItem + i];
2013 shape(firstItem + i);
2016 for (int i = 0; i < nItems; ++i) {
2017 QScriptItem &si = layoutData->items[firstItem + i];
2019 int kashida_type = HB_Arabic_Normal;
2020 int kashida_pos = -1;
2022 int start = qMax(line.from - si.position, 0);
2023 int end = qMin(line.from + line_length - (int)si.position, length(firstItem+i));
2025 unsigned short *log_clusters = logClusters(&si);
2027 int gs = log_clusters[start];
2028 int ge = (end == length(firstItem+i) ? si.num_glyphs : log_clusters[end]);
2030 const QGlyphLayout g = shapedGlyphs(&si);
2032 for (int i = gs; i < ge; ++i) {
2033 g.justifications[i].type = QGlyphJustification::JustifyNone;
2034 g.justifications[i].nKashidas = 0;
2035 g.justifications[i].space_18d6 = 0;
2037 justificationPoints.resize(nPoints+3);
2038 int justification = g.attributes[i].justification;
2040 switch(justification) {
2041 case HB_NoJustification:
2045 case HB_Arabic_Space :
2046 if (kashida_pos >= 0) {
2047 // qDebug("kashida position at %d in word", kashida_pos);
2048 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
2049 if (justificationPoints[nPoints].kashidaWidth > 0) {
2050 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
2051 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
2056 kashida_type = HB_Arabic_Normal;
2059 set(&justificationPoints[nPoints++], justification, g.mid(i), fontEngine(si));
2060 maxJustify = qMax(maxJustify, justification);
2062 case HB_Arabic_Normal :
2063 case HB_Arabic_Waw :
2064 case HB_Arabic_BaRa :
2065 case HB_Arabic_Alef :
2066 case HB_Arabic_HaaDal :
2067 case HB_Arabic_Seen :
2068 case HB_Arabic_Kashida :
2069 if (justification >= kashida_type) {
2071 kashida_type = justification;
2075 if (kashida_pos >= 0) {
2076 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
2077 if (justificationPoints[nPoints].kashidaWidth > 0) {
2078 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
2079 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
2085 QFixed need = line.width - line.textWidth;
2087 // line overflows already!
2088 const_cast<QScriptLine &>(line).justified = true;
2092 // qDebug("doing justification: textWidth=%x, requested=%x, maxJustify=%d", line.textWidth.value(), line.width.value(), maxJustify);
2093 // qDebug(" minKashida=%f, need=%f", minKashida.toReal(), need.toReal());
2095 // distribute in priority order
2096 if (maxJustify >= HB_Arabic_Normal) {
2097 while (need >= minKashida) {
2098 for (int type = maxJustify; need >= minKashida && type >= HB_Arabic_Normal; --type) {
2099 for (int i = 0; need >= minKashida && i < nPoints; ++i) {
2100 if (justificationPoints[i].type == type && justificationPoints[i].kashidaWidth <= need) {
2101 justificationPoints[i].glyph.justifications->nKashidas++;
2103 justificationPoints[i].glyph.justifications->space_18d6 += justificationPoints[i].kashidaWidth.value();
2104 need -= justificationPoints[i].kashidaWidth;
2105 // qDebug("adding kashida type %d with width %x, neednow %x", type, justificationPoints[i].kashidaWidth, need.value());
2111 Q_ASSERT(need >= 0);
2115 maxJustify = qMin(maxJustify, (int)HB_Space);
2116 for (int type = maxJustify; need != 0 && type > 0; --type) {
2118 for (int i = 0; i < nPoints; ++i) {
2119 if (justificationPoints[i].type == type)
2122 // qDebug("number of points for justification type %d: %d", type, n);
2128 for (int i = 0; i < nPoints; ++i) {
2129 if (justificationPoints[i].type == type) {
2130 QFixed add = need/n;
2131 // qDebug("adding %x to glyph %x", add.value(), justificationPoints[i].glyph->glyph);
2132 justificationPoints[i].glyph.justifications[0].space_18d6 = add.value();
2141 const_cast<QScriptLine &>(line).justified = true;
2144 void QScriptLine::setDefaultHeight(QTextEngine *eng)
2149 if (eng->block.docHandle() && eng->block.docHandle()->layout()) {
2150 f = eng->block.charFormat().font();
2151 // Make sure we get the right dpi on printers
2152 QPaintDevice *pdev = eng->block.docHandle()->layout()->paintDevice();
2155 e = f.d->engineForScript(QUnicodeTables::Common);
2157 e = eng->fnt.d->engineForScript(QUnicodeTables::Common);
2160 QFixed other_ascent = e->ascent();
2161 QFixed other_descent = e->descent();
2162 QFixed other_leading = e->leading();
2163 leading = qMax(leading + ascent, other_leading + other_ascent) - qMax(ascent, other_ascent);
2164 ascent = qMax(ascent, other_ascent);
2165 descent = qMax(descent, other_descent);
2168 QTextEngine::LayoutData::LayoutData()
2172 memory_on_stack = false;
2175 layoutState = LayoutEmpty;
2176 haveCharAttributes = false;
2178 available_glyphs = 0;
2181 QTextEngine::LayoutData::LayoutData(const QString &str, void **stack_memory, int _allocated)
2184 allocated = _allocated;
2186 int space_charAttributes = sizeof(HB_CharAttributes)*string.length()/sizeof(void*) + 1;
2187 int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2188 available_glyphs = ((int)allocated - space_charAttributes - space_logClusters)*(int)sizeof(void*)/(int)QGlyphLayout::spaceNeededForGlyphLayout(1);
2190 if (available_glyphs < str.length()) {
2191 // need to allocate on the heap
2194 memory_on_stack = false;
2198 memory_on_stack = true;
2199 memory = stack_memory;
2200 logClustersPtr = (unsigned short *)(memory + space_charAttributes);
2202 void *m = memory + space_charAttributes + space_logClusters;
2203 glyphLayout = QGlyphLayout(reinterpret_cast<char *>(m), str.length());
2204 glyphLayout.clear();
2205 memset(memory, 0, space_charAttributes*sizeof(void *));
2209 layoutState = LayoutEmpty;
2210 haveCharAttributes = false;
2213 QTextEngine::LayoutData::~LayoutData()
2215 if (!memory_on_stack)
2220 bool QTextEngine::LayoutData::reallocate(int totalGlyphs)
2222 Q_ASSERT(totalGlyphs >= glyphLayout.numGlyphs);
2223 if (memory_on_stack && available_glyphs >= totalGlyphs) {
2224 glyphLayout.grow(glyphLayout.data(), totalGlyphs);
2228 int space_charAttributes = sizeof(HB_CharAttributes)*string.length()/sizeof(void*) + 1;
2229 int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2230 int space_glyphs = QGlyphLayout::spaceNeededForGlyphLayout(totalGlyphs)/sizeof(void*) + 2;
2232 int newAllocated = space_charAttributes + space_glyphs + space_logClusters;
2233 // These values can be negative if the length of string/glyphs causes overflow,
2234 // we can't layout such a long string all at once, so return false here to
2235 // indicate there is a failure
2236 if (space_charAttributes < 0 || space_logClusters < 0 || space_glyphs < 0 || newAllocated < allocated) {
2237 layoutState = LayoutFailed;
2241 void **newMem = memory;
2242 newMem = (void **)::realloc(memory_on_stack ? 0 : memory, newAllocated*sizeof(void *));
2244 layoutState = LayoutFailed;
2247 if (memory_on_stack)
2248 memcpy(newMem, memory, allocated*sizeof(void *));
2250 memory_on_stack = false;
2253 m += space_charAttributes;
2254 logClustersPtr = (unsigned short *) m;
2255 m += space_logClusters;
2257 const int space_preGlyphLayout = space_charAttributes + space_logClusters;
2258 if (allocated < space_preGlyphLayout)
2259 memset(memory + allocated, 0, (space_preGlyphLayout - allocated)*sizeof(void *));
2261 glyphLayout.grow(reinterpret_cast<char *>(m), totalGlyphs);
2263 allocated = newAllocated;
2267 // grow to the new size, copying the existing data to the new layout
2268 void QGlyphLayout::grow(char *address, int totalGlyphs)
2270 QGlyphLayout oldLayout(address, numGlyphs);
2271 QGlyphLayout newLayout(address, totalGlyphs);
2274 // move the existing data
2275 memmove(newLayout.attributes, oldLayout.attributes, numGlyphs * sizeof(HB_GlyphAttributes));
2276 memmove(newLayout.justifications, oldLayout.justifications, numGlyphs * sizeof(QGlyphJustification));
2277 memmove(newLayout.advances_y, oldLayout.advances_y, numGlyphs * sizeof(QFixed));
2278 memmove(newLayout.advances_x, oldLayout.advances_x, numGlyphs * sizeof(QFixed));
2279 memmove(newLayout.glyphs, oldLayout.glyphs, numGlyphs * sizeof(HB_Glyph));
2282 // clear the new data
2283 newLayout.clear(numGlyphs);
2288 void QTextEngine::freeMemory()
2294 layoutData->used = 0;
2295 layoutData->hasBidi = false;
2296 layoutData->layoutState = LayoutEmpty;
2297 layoutData->haveCharAttributes = false;
2299 for (int i = 0; i < lines.size(); ++i) {
2300 lines[i].justified = 0;
2301 lines[i].gridfitted = 0;
2305 int QTextEngine::formatIndex(const QScriptItem *si) const
2307 if (specialData && !specialData->resolvedFormatIndices.isEmpty())
2308 return specialData->resolvedFormatIndices.at(si - &layoutData->items[0]);
2309 QTextDocumentPrivate *p = block.docHandle();
2312 int pos = si->position;
2313 if (specialData && si->position >= specialData->preeditPosition) {
2314 if (si->position < specialData->preeditPosition + specialData->preeditText.length())
2315 pos = qMax(specialData->preeditPosition - 1, 0);
2317 pos -= specialData->preeditText.length();
2319 QTextDocumentPrivate::FragmentIterator it = p->find(block.position() + pos);
2320 return it.value()->format;
2324 QTextCharFormat QTextEngine::format(const QScriptItem *si) const
2326 QTextCharFormat format;
2327 const QTextFormatCollection *formats = 0;
2328 if (block.docHandle()) {
2329 formats = this->formats();
2330 format = formats->charFormat(formatIndex(si));
2332 if (specialData && specialData->resolvedFormatIndices.isEmpty()) {
2333 int end = si->position + length(si);
2334 for (int i = 0; i < specialData->addFormats.size(); ++i) {
2335 const QTextLayout::FormatRange &r = specialData->addFormats.at(i);
2336 if (r.start <= si->position && r.start + r.length >= end) {
2337 if (!specialData->addFormatIndices.isEmpty())
2338 format.merge(formats->format(specialData->addFormatIndices.at(i)));
2340 format.merge(r.format);
2347 void QTextEngine::addRequiredBoundaries() const
2350 for (int i = 0; i < specialData->addFormats.size(); ++i) {
2351 const QTextLayout::FormatRange &r = specialData->addFormats.at(i);
2352 setBoundary(r.start);
2353 setBoundary(r.start + r.length);
2354 //qDebug("adding boundaries %d %d", r.start, r.start+r.length);
2359 bool QTextEngine::atWordSeparator(int position) const
2361 const QChar c = layoutData->string.at(position);
2362 switch (c.toLatin1()) {
2399 bool QTextEngine::atSpace(int position) const
2401 const QChar c = layoutData->string.at(position);
2403 return c == QLatin1Char(' ')
2405 || c == QChar::LineSeparator
2406 || c == QLatin1Char('\t')
2411 void QTextEngine::indexAdditionalFormats()
2413 if (!block.docHandle())
2416 specialData->addFormatIndices.resize(specialData->addFormats.count());
2417 QTextFormatCollection * const formats = this->formats();
2419 for (int i = 0; i < specialData->addFormats.count(); ++i) {
2420 specialData->addFormatIndices[i] = formats->indexForFormat(specialData->addFormats.at(i).format);
2421 specialData->addFormats[i].format = QTextCharFormat();
2425 /* These two helper functions are used to determine whether we need to insert a ZWJ character
2426 between the text that gets truncated and the ellipsis. This is important to get
2427 correctly shaped results for arabic text.
2429 static bool nextCharJoins(const QString &string, int pos)
2431 while (pos < string.length() && string.at(pos).category() == QChar::Mark_NonSpacing)
2433 if (pos == string.length())
2435 return string.at(pos).joining() != QChar::OtherJoining;
2438 static bool prevCharJoins(const QString &string, int pos)
2440 while (pos > 0 && string.at(pos - 1).category() == QChar::Mark_NonSpacing)
2444 return (string.at(pos - 1).joining() == QChar::Dual || string.at(pos - 1).joining() == QChar::Center);
2447 QString QTextEngine::elidedText(Qt::TextElideMode mode, const QFixed &width, int flags) const
2449 // qDebug() << "elidedText; available width" << width.toReal() << "text width:" << this->width(0, layoutData->string.length()).toReal();
2451 if (flags & Qt::TextShowMnemonic) {
2453 HB_CharAttributes *attributes = const_cast<HB_CharAttributes *>(this->attributes());
2456 for (int i = 0; i < layoutData->items.size(); ++i) {
2457 QScriptItem &si = layoutData->items[i];
2461 unsigned short *logClusters = this->logClusters(&si);
2462 QGlyphLayout glyphs = shapedGlyphs(&si);
2464 const int end = si.position + length(&si);
2465 for (int i = si.position; i < end - 1; ++i) {
2466 if (layoutData->string.at(i) == QLatin1Char('&')) {
2467 const int gp = logClusters[i - si.position];
2468 glyphs.attributes[gp].dontPrint = true;
2469 attributes[i + 1].charStop = false;
2470 attributes[i + 1].whiteSpace = false;
2471 attributes[i + 1].lineBreakType = HB_NoBreak;
2472 if (layoutData->string.at(i + 1) == QLatin1Char('&'))
2481 if (mode == Qt::ElideNone
2482 || this->width(0, layoutData->string.length()) <= width
2483 || layoutData->string.length() <= 1)
2484 return layoutData->string;
2486 QFixed ellipsisWidth;
2487 QString ellipsisText;
2489 QChar ellipsisChar(0x2026);
2491 QFontEngine *fe = fnt.d->engineForScript(QUnicodeTables::Common);
2493 QGlyphLayoutArray<1> ellipsisGlyph;
2495 QFontEngine *feForEllipsis = (fe->type() == QFontEngine::Multi)
2496 ? static_cast<QFontEngineMulti *>(fe)->engine(0)
2499 if (feForEllipsis->type() == QFontEngine::Mac)
2502 // the lookup can be really slow when we use XLFD fonts
2503 if (feForEllipsis->type() != QFontEngine::XLFD
2504 && feForEllipsis->canRender(&ellipsisChar, 1)) {
2506 feForEllipsis->stringToCMap(&ellipsisChar, 1, &ellipsisGlyph, &nGlyphs, 0);
2510 if (ellipsisGlyph.glyphs[0]) {
2511 ellipsisWidth = ellipsisGlyph.advances_x[0];
2512 ellipsisText = ellipsisChar;
2514 QString dotDotDot(QLatin1String("..."));
2516 QGlyphLayoutArray<3> glyphs;
2518 if (!fe->stringToCMap(dotDotDot.constData(), 3, &glyphs, &nGlyphs, 0))
2519 // should never happen...
2520 return layoutData->string;
2521 for (int i = 0; i < nGlyphs; ++i)
2522 ellipsisWidth += glyphs.advances_x[i];
2523 ellipsisText = dotDotDot;
2527 const QFixed availableWidth = width - ellipsisWidth;
2528 if (availableWidth < 0)
2531 const HB_CharAttributes *attributes = this->attributes();
2535 if (mode == Qt::ElideRight) {
2536 QFixed currentWidth;
2544 while (nextBreak < layoutData->string.length() && !attributes[nextBreak].charStop)
2547 currentWidth += this->width(pos, nextBreak - pos);
2548 } while (nextBreak < layoutData->string.length()
2549 && currentWidth < availableWidth);
2551 if (nextCharJoins(layoutData->string, pos))
2552 ellipsisText.prepend(QChar(0x200d) /* ZWJ */);
2554 return layoutData->string.left(pos) + ellipsisText;
2555 } else if (mode == Qt::ElideLeft) {
2556 QFixed currentWidth;
2558 int nextBreak = layoutData->string.length();
2564 while (nextBreak > 0 && !attributes[nextBreak].charStop)
2567 currentWidth += this->width(nextBreak, pos - nextBreak);
2568 } while (nextBreak > 0
2569 && currentWidth < availableWidth);
2571 if (prevCharJoins(layoutData->string, pos))
2572 ellipsisText.append(QChar(0x200d) /* ZWJ */);
2574 return ellipsisText + layoutData->string.mid(pos);
2575 } else if (mode == Qt::ElideMiddle) {
2580 int nextLeftBreak = 0;
2582 int rightPos = layoutData->string.length();
2583 int nextRightBreak = layoutData->string.length();
2586 leftPos = nextLeftBreak;
2587 rightPos = nextRightBreak;
2590 while (nextLeftBreak < layoutData->string.length() && !attributes[nextLeftBreak].charStop)
2594 while (nextRightBreak > 0 && !attributes[nextRightBreak].charStop)
2597 leftWidth += this->width(leftPos, nextLeftBreak - leftPos);
2598 rightWidth += this->width(nextRightBreak, rightPos - nextRightBreak);
2599 } while (nextLeftBreak < layoutData->string.length()
2600 && nextRightBreak > 0
2601 && leftWidth + rightWidth < availableWidth);
2603 if (nextCharJoins(layoutData->string, leftPos))
2604 ellipsisText.prepend(QChar(0x200d) /* ZWJ */);
2605 if (prevCharJoins(layoutData->string, rightPos))
2606 ellipsisText.append(QChar(0x200d) /* ZWJ */);
2608 return layoutData->string.left(leftPos) + ellipsisText + layoutData->string.mid(rightPos);
2611 return layoutData->string;
2614 void QTextEngine::setBoundary(int strPos) const
2616 if (strPos <= 0 || strPos >= layoutData->string.length())
2619 int itemToSplit = 0;
2620 while (itemToSplit < layoutData->items.size() && layoutData->items.at(itemToSplit).position <= strPos)
2623 if (layoutData->items.at(itemToSplit).position == strPos) {
2624 // already a split at the requested position
2627 splitItem(itemToSplit, strPos - layoutData->items.at(itemToSplit).position);
2630 void QTextEngine::splitItem(int item, int pos) const
2635 layoutData->items.insert(item + 1, layoutData->items[item]);
2636 QScriptItem &oldItem = layoutData->items[item];
2637 QScriptItem &newItem = layoutData->items[item+1];
2638 newItem.position += pos;
2640 if (oldItem.num_glyphs) {
2641 // already shaped, break glyphs aswell
2642 int breakGlyph = logClusters(&oldItem)[pos];
2644 newItem.num_glyphs = oldItem.num_glyphs - breakGlyph;
2645 oldItem.num_glyphs = breakGlyph;
2646 newItem.glyph_data_offset = oldItem.glyph_data_offset + breakGlyph;
2648 for (int i = 0; i < newItem.num_glyphs; i++)
2649 logClusters(&newItem)[i] -= breakGlyph;
2652 const QGlyphLayout g = shapedGlyphs(&oldItem);
2653 for(int j = 0; j < breakGlyph; ++j)
2654 w += g.advances_x[j];
2656 newItem.width = oldItem.width - w;
2660 // qDebug("split at position %d itempos=%d", pos, item);
2663 QFixed QTextEngine::calculateTabWidth(int item, QFixed x) const
2665 const QScriptItem &si = layoutData->items[item];
2667 QFixed dpiScale = 1;
2668 if (block.docHandle() && block.docHandle()->layout()) {
2669 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
2671 dpiScale = QFixed::fromReal(pdev->logicalDpiY() / qreal(qt_defaultDpiY()));
2673 dpiScale = QFixed::fromReal(fnt.d->dpi / qreal(qt_defaultDpiY()));
2676 QList<QTextOption::Tab> tabArray = option.tabs();
2677 if (!tabArray.isEmpty()) {
2678 if (isRightToLeft()) { // rebase the tabArray positions.
2679 QList<QTextOption::Tab> newTabs;
2680 QList<QTextOption::Tab>::Iterator iter = tabArray.begin();
2681 while(iter != tabArray.end()) {
2682 QTextOption::Tab tab = *iter;
2683 if (tab.type == QTextOption::LeftTab)
2684 tab.type = QTextOption::RightTab;
2685 else if (tab.type == QTextOption::RightTab)
2686 tab.type = QTextOption::LeftTab;
2692 for (int i = 0; i < tabArray.size(); ++i) {
2693 QFixed tab = QFixed::fromReal(tabArray[i].position) * dpiScale;
2694 if (tab > x) { // this is the tab we need.
2695 QTextOption::Tab tabSpec = tabArray[i];
2696 int tabSectionEnd = layoutData->string.count();
2697 if (tabSpec.type == QTextOption::RightTab || tabSpec.type == QTextOption::CenterTab) {
2698 // find next tab to calculate the width required.
2699 tab = QFixed::fromReal(tabSpec.position);
2700 for (int i=item + 1; i < layoutData->items.count(); i++) {
2701 const QScriptItem &item = layoutData->items[i];
2702 if (item.analysis.flags == QScriptAnalysis::TabOrObject) { // found it.
2703 tabSectionEnd = item.position;
2708 else if (tabSpec.type == QTextOption::DelimiterTab)
2709 // find delimitor character to calculate the width required
2710 tabSectionEnd = qMax(si.position, layoutData->string.indexOf(tabSpec.delimiter, si.position) + 1);
2712 if (tabSectionEnd > si.position) {
2714 // Calculate the length of text between this tab and the tabSectionEnd
2715 for (int i=item; i < layoutData->items.count(); i++) {
2716 QScriptItem &item = layoutData->items[i];
2717 if (item.position > tabSectionEnd || item.position <= si.position)
2719 shape(i); // first, lets make sure relevant text is already shaped
2720 QGlyphLayout glyphs = this->shapedGlyphs(&item);
2721 const int end = qMin(item.position + item.num_glyphs, tabSectionEnd) - item.position;
2722 for (int i=0; i < end; i++)
2723 length += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
2724 if (end + item.position == tabSectionEnd && tabSpec.type == QTextOption::DelimiterTab) // remove half of matching char
2725 length -= glyphs.advances_x[end] / 2 * !glyphs.attributes[end].dontPrint;
2728 switch (tabSpec.type) {
2729 case QTextOption::CenterTab:
2732 case QTextOption::DelimiterTab:
2734 case QTextOption::RightTab:
2735 tab = QFixed::fromReal(tabSpec.position) * dpiScale - length;
2736 if (tab < 0) // default to tab taking no space
2739 case QTextOption::LeftTab:
2747 QFixed tab = QFixed::fromReal(option.tabStop());
2749 tab = 80; // default
2751 QFixed nextTabPos = ((x / tab).truncate() + 1) * tab;
2752 QFixed tabWidth = nextTabPos - x;
2757 void QTextEngine::resolveAdditionalFormats() const
2759 if (!specialData || specialData->addFormats.isEmpty()
2760 || !block.docHandle()
2761 || !specialData->resolvedFormatIndices.isEmpty())
2764 QTextFormatCollection *collection = this->formats();
2766 specialData->resolvedFormatIndices.clear();
2767 QVector<int> indices(layoutData->items.count());
2768 for (int i = 0; i < layoutData->items.count(); ++i) {
2769 QTextCharFormat f = format(&layoutData->items.at(i));
2770 indices[i] = collection->indexForFormat(f);
2772 specialData->resolvedFormatIndices = indices;
2775 QFixed QTextEngine::leadingSpaceWidth(const QScriptLine &line)
2777 if (!line.hasTrailingSpaces
2778 || (option.flags() & QTextOption::IncludeTrailingSpaces)
2779 || !isRightToLeft())
2782 int pos = line.length;
2783 const HB_CharAttributes *attributes = this->attributes();
2786 while (pos > 0 && attributes[line.from + pos - 1].whiteSpace)
2788 return width(line.from + pos, line.length - pos);
2791 QFixed QTextEngine::alignLine(const QScriptLine &line)
2795 // if width is QFIXED_MAX that means we used setNumColumns() and that implicitly makes this line left aligned.
2796 if (!line.justified && line.width != QFIXED_MAX) {
2797 int align = option.alignment();
2798 if (align & Qt::AlignLeft)
2799 x -= leadingSpaceWidth(line);
2800 if (align & Qt::AlignJustify && isRightToLeft())
2801 align = Qt::AlignRight;
2802 if (align & Qt::AlignRight)
2803 x = line.width - (line.textAdvance + leadingSpaceWidth(line));
2804 else if (align & Qt::AlignHCenter)
2805 x = (line.width - line.textAdvance)/2 - leadingSpaceWidth(line);
2810 QFixed QTextEngine::offsetInLigature(const QScriptItem *si, int pos, int max, int glyph_pos)
2812 unsigned short *logClusters = this->logClusters(si);
2813 const QGlyphLayout &glyphs = shapedGlyphs(si);
2815 int offsetInCluster = 0;
2816 for (int i = pos - 1; i >= 0; i--) {
2817 if (logClusters[i] == glyph_pos)
2823 // in the case that the offset is inside a (multi-character) glyph,
2824 // interpolate the position.
2825 if (offsetInCluster > 0) {
2826 int clusterLength = 0;
2827 for (int i = pos - offsetInCluster; i < max; i++) {
2828 if (logClusters[i] == glyph_pos)
2834 return glyphs.advances_x[glyph_pos] * offsetInCluster / clusterLength;
2840 // Scan in logClusters[from..to-1] for glyph_pos
2841 int QTextEngine::getClusterLength(unsigned short *logClusters,
2842 const HB_CharAttributes *attributes,
2843 int from, int to, int glyph_pos, int *start)
2845 int clusterLength = 0;
2846 for (int i = from; i < to; i++) {
2847 if (logClusters[i] == glyph_pos && attributes[i].charStop) {
2852 else if (clusterLength)
2855 return clusterLength;
2858 int QTextEngine::positionInLigature(const QScriptItem *si, int end,
2859 QFixed x, QFixed edge, int glyph_pos,
2860 bool cursorOnCharacter)
2862 unsigned short *logClusters = this->logClusters(si);
2863 int clusterStart = -1;
2864 int clusterLength = 0;
2866 if (si->analysis.script != QUnicodeTables::Common &&
2867 si->analysis.script != QUnicodeTables::Greek) {
2868 if (glyph_pos == -1)
2869 return si->position + end;
2872 for (i = 0; i < end; i++)
2873 if (logClusters[i] == glyph_pos)
2875 return si->position + i;
2879 if (glyph_pos == -1 && end > 0)
2880 glyph_pos = logClusters[end - 1];
2886 const HB_CharAttributes *attrs = attributes();
2887 logClusters = this->logClusters(si);
2888 clusterLength = getClusterLength(logClusters, attrs, 0, end, glyph_pos, &clusterStart);
2890 if (clusterLength) {
2891 const QGlyphLayout &glyphs = shapedGlyphs(si);
2892 QFixed glyphWidth = glyphs.effectiveAdvance(glyph_pos);
2893 // the approximate width of each individual element of the ligature
2894 QFixed perItemWidth = glyphWidth / clusterLength;
2895 QFixed left = x > edge ? edge : edge - glyphWidth;
2896 int n = ((x - left) / perItemWidth).floor().toInt();
2897 QFixed dist = x - left - n * perItemWidth;
2898 int closestItem = dist > (perItemWidth / 2) ? n + 1 : n;
2899 if (cursorOnCharacter && closestItem > 0)
2901 int pos = si->position + clusterStart + closestItem;
2902 // Jump to the next charStop
2903 while (!attrs[pos].charStop && pos < end)
2907 return si->position + end;
2910 int QTextEngine::previousLogicalPosition(int oldPos) const
2912 const HB_CharAttributes *attrs = attributes();
2913 if (!attrs || oldPos < 0)
2919 while (oldPos && !attrs[oldPos].charStop)
2924 int QTextEngine::nextLogicalPosition(int oldPos) const
2926 const HB_CharAttributes *attrs = attributes();
2927 int len = block.isValid() ? block.length() - 1
2928 : layoutData->string.length();
2929 Q_ASSERT(len <= layoutData->string.length());
2930 if (!attrs || oldPos < 0 || oldPos >= len)
2934 while (oldPos < len && !attrs[oldPos].charStop)
2939 int QTextEngine::lineNumberForTextPosition(int pos)
2943 if (pos == layoutData->string.length() && lines.size())
2944 return lines.size() - 1;
2945 for (int i = 0; i < lines.size(); ++i) {
2946 const QScriptLine& line = lines[i];
2947 if (line.from + line.length > pos)
2953 void QTextEngine::insertionPointsForLine(int lineNum, QVector<int> &insertionPoints)
2955 QTextLineItemIterator iterator(this, lineNum);
2956 bool rtl = isRightToLeft();
2957 bool lastLine = lineNum >= lines.size() - 1;
2959 while (!iterator.atEnd()) {
2961 const QScriptItem *si = &layoutData->items[iterator.item];
2962 if (si->analysis.bidiLevel % 2) {
2963 int i = iterator.itemEnd - 1, min = iterator.itemStart;
2964 if (lastLine && (rtl ? iterator.atBeginning() : iterator.atEnd()))
2966 for (; i >= min; i--)
2967 insertionPoints.push_back(i);
2969 int i = iterator.itemStart, max = iterator.itemEnd;
2970 if (lastLine && (rtl ? iterator.atBeginning() : iterator.atEnd()))
2972 for (; i < max; i++)
2973 insertionPoints.push_back(i);
2978 int QTextEngine::endOfLine(int lineNum)
2980 QVector<int> insertionPoints;
2981 insertionPointsForLine(lineNum, insertionPoints);
2983 if (insertionPoints.size() > 0)
2984 return insertionPoints.last();
2988 int QTextEngine::beginningOfLine(int lineNum)
2990 QVector<int> insertionPoints;
2991 insertionPointsForLine(lineNum, insertionPoints);
2993 if (insertionPoints.size() > 0)
2994 return insertionPoints.first();
2998 int QTextEngine::positionAfterVisualMovement(int pos, QTextCursor::MoveOperation op)
3003 bool moveRight = (op == QTextCursor::Right);
3004 bool alignRight = isRightToLeft();
3005 if (!layoutData->hasBidi)
3006 return moveRight ^ alignRight ? nextLogicalPosition(pos) : previousLogicalPosition(pos);
3008 int lineNum = lineNumberForTextPosition(pos);
3009 Q_ASSERT(lineNum >= 0);
3011 QVector<int> insertionPoints;
3012 insertionPointsForLine(lineNum, insertionPoints);
3013 int i, max = insertionPoints.size();
3014 for (i = 0; i < max; i++)
3015 if (pos == insertionPoints[i]) {
3018 return insertionPoints[i + 1];
3021 return insertionPoints[i - 1];
3024 if (moveRight ^ alignRight) {
3025 if (lineNum + 1 < lines.size())
3026 return alignRight ? endOfLine(lineNum + 1) : beginningOfLine(lineNum + 1);
3030 return alignRight ? beginningOfLine(lineNum - 1) : endOfLine(lineNum - 1);
3037 QStackTextEngine::QStackTextEngine(const QString &string, const QFont &f)
3038 : QTextEngine(string, f),
3039 _layoutData(string, _memory, MemSize)
3042 layoutData = &_layoutData;
3045 QTextItemInt::QTextItemInt(const QScriptItem &si, QFont *font, const QTextCharFormat &format)
3046 : justified(false), underlineStyle(QTextCharFormat::NoUnderline), charFormat(format),
3047 num_chars(0), chars(0), logClusters(0), f(0), fontEngine(0)
3050 fontEngine = f->d->engineForScript(si.analysis.script);
3051 Q_ASSERT(fontEngine);
3053 initWithScriptItem(si);
3056 QTextItemInt::QTextItemInt(const QGlyphLayout &g, QFont *font, const QChar *chars_, int numChars, QFontEngine *fe, const QTextCharFormat &format)
3057 : flags(0), justified(false), underlineStyle(QTextCharFormat::NoUnderline), charFormat(format),
3058 num_chars(numChars), chars(chars_), logClusters(0), f(font), glyphs(g), fontEngine(fe)
3062 // Fix up flags and underlineStyle with given info
3063 void QTextItemInt::initWithScriptItem(const QScriptItem &si)
3065 // explicitly initialize flags so that initFontAttributes can be called
3066 // multiple times on the same TextItem
3068 if (si.analysis.bidiLevel %2)
3069 flags |= QTextItem::RightToLeft;
3071 descent = si.descent;
3073 if (charFormat.hasProperty(QTextFormat::TextUnderlineStyle)) {
3074 underlineStyle = charFormat.underlineStyle();
3075 } else if (charFormat.boolProperty(QTextFormat::FontUnderline)
3076 || f->d->underline) {
3077 underlineStyle = QTextCharFormat::SingleUnderline;
3081 if (underlineStyle == QTextCharFormat::SingleUnderline)
3082 flags |= QTextItem::Underline;
3084 if (f->d->overline || charFormat.fontOverline())
3085 flags |= QTextItem::Overline;
3086 if (f->d->strikeOut || charFormat.fontStrikeOut())
3087 flags |= QTextItem::StrikeOut;
3090 QTextItemInt QTextItemInt::midItem(QFontEngine *fontEngine, int firstGlyphIndex, int numGlyphs) const
3092 QTextItemInt ti = *this;
3093 const int end = firstGlyphIndex + numGlyphs;
3094 ti.glyphs = glyphs.mid(firstGlyphIndex, numGlyphs);
3095 ti.fontEngine = fontEngine;
3097 if (logClusters && chars) {
3098 const int logClusterOffset = logClusters[0];
3099 while (logClusters[ti.chars - chars] - logClusterOffset < firstGlyphIndex)
3102 ti.logClusters += (ti.chars - chars);
3105 int char_start = ti.chars - chars;
3106 while (char_start + ti.num_chars < num_chars && ti.logClusters[ti.num_chars] - logClusterOffset < end)
3113 QTransform qt_true_matrix(qreal w, qreal h, QTransform x)
3115 QRectF rect = x.mapRect(QRectF(0, 0, w, h));
3116 return x * QTransform::fromTranslate(-rect.x(), -rect.y());
3120 glyph_metrics_t glyph_metrics_t::transformed(const QTransform &matrix) const
3122 if (matrix.type() < QTransform::TxTranslate)
3125 glyph_metrics_t m = *this;
3127 qreal w = width.toReal();
3128 qreal h = height.toReal();
3129 QTransform xform = qt_true_matrix(w, h, matrix);
3131 QRectF rect(0, 0, w, h);
3132 rect = xform.mapRect(rect);
3133 m.width = QFixed::fromReal(rect.width());
3134 m.height = QFixed::fromReal(rect.height());
3136 QLineF l = xform.map(QLineF(x.toReal(), y.toReal(), xoff.toReal(), yoff.toReal()));
3138 m.x = QFixed::fromReal(l.x1());
3139 m.y = QFixed::fromReal(l.y1());
3141 // The offset is relative to the baseline which is why we use dx/dy of the line
3142 m.xoff = QFixed::fromReal(l.dx());
3143 m.yoff = QFixed::fromReal(l.dy());
3148 QTextLineItemIterator::QTextLineItemIterator(QTextEngine *_eng, int _lineNum, const QPointF &pos,
3149 const QTextLayout::FormatRange *_selection)
3151 line(eng->lines[_lineNum]),
3154 lineEnd(line.from + line.length),
3155 firstItem(eng->findItem(line.from)),
3156 lastItem(eng->findItem(lineEnd - 1)),
3157 nItems((firstItem >= 0 && lastItem >= firstItem)? (lastItem-firstItem+1) : 0),
3160 visualOrder(nItems),
3162 selection(_selection)
3164 pos_x = x = QFixed::fromReal(pos.x());
3168 x += eng->alignLine(line);
3170 for (int i = 0; i < nItems; ++i)
3171 levels[i] = eng->layoutData->items[i+firstItem].analysis.bidiLevel;
3172 QTextEngine::bidiReorder(nItems, levels.data(), visualOrder.data());
3174 eng->shapeLine(line);
3177 QScriptItem &QTextLineItemIterator::next()
3182 item = visualOrder[logicalItem] + firstItem;
3183 itemLength = eng->length(item);
3184 si = &eng->layoutData->items[item];
3185 if (!si->num_glyphs)
3188 if (si->analysis.flags >= QScriptAnalysis::TabOrObject) {
3189 itemWidth = si->width;
3193 unsigned short *logClusters = eng->logClusters(si);
3194 QGlyphLayout glyphs = eng->shapedGlyphs(si);
3196 itemStart = qMax(line.from, si->position);
3197 glyphsStart = logClusters[itemStart - si->position];
3198 if (lineEnd < si->position + itemLength) {
3200 glyphsEnd = logClusters[itemEnd-si->position];
3202 itemEnd = si->position + itemLength;
3203 glyphsEnd = si->num_glyphs;
3205 // show soft-hyphen at line-break
3206 if (si->position + itemLength >= lineEnd
3207 && eng->layoutData->string.at(lineEnd - 1) == 0x00ad)
3208 glyphs.attributes[glyphsEnd - 1].dontPrint = false;
3211 for (int g = glyphsStart; g < glyphsEnd; ++g)
3212 itemWidth += glyphs.effectiveAdvance(g);
3217 bool QTextLineItemIterator::getSelectionBounds(QFixed *selectionX, QFixed *selectionWidth) const
3219 *selectionX = *selectionWidth = 0;
3224 if (si->analysis.flags >= QScriptAnalysis::TabOrObject) {
3225 if (si->position >= selection->start + selection->length
3226 || si->position + itemLength <= selection->start)
3230 *selectionWidth = itemWidth;
3232 unsigned short *logClusters = eng->logClusters(si);
3233 QGlyphLayout glyphs = eng->shapedGlyphs(si);
3235 int from = qMax(itemStart, selection->start) - si->position;
3236 int to = qMin(itemEnd, selection->start + selection->length) - si->position;
3240 int start_glyph = logClusters[from];
3241 int end_glyph = (to == eng->length(item)) ? si->num_glyphs : logClusters[to];
3244 if (si->analysis.bidiLevel %2) {
3245 for (int g = glyphsEnd - 1; g >= end_glyph; --g)
3246 soff += glyphs.effectiveAdvance(g);
3247 for (int g = end_glyph - 1; g >= start_glyph; --g)
3248 swidth += glyphs.effectiveAdvance(g);
3250 for (int g = glyphsStart; g < start_glyph; ++g)
3251 soff += glyphs.effectiveAdvance(g);
3252 for (int g = start_glyph; g < end_glyph; ++g)
3253 swidth += glyphs.effectiveAdvance(g);
3256 // If the starting character is in the middle of a ligature,
3257 // selection should only contain the right part of that ligature
3258 // glyph, so we need to get the width of the left part here and
3259 // add it to *selectionX
3260 QFixed leftOffsetInLigature = eng->offsetInLigature(si, from, to, start_glyph);
3261 *selectionX = x + soff + leftOffsetInLigature;
3262 *selectionWidth = swidth - leftOffsetInLigature;
3263 // If the ending character is also part of a ligature, swidth does
3264 // not contain that part yet, we also need to find out the width of
3266 *selectionWidth += eng->offsetInLigature(si, to, eng->length(item), end_glyph);