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 ** No Commercial Usage
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
16 ** GNU Lesser General Public License Usage
17 ** Alternatively, this file may be used under the terms of the GNU Lesser
18 ** General Public License version 2.1 as published by the Free Software
19 ** Foundation and appearing in the file LICENSE.LGPL included in the
20 ** packaging of this file. Please review the following information to
21 ** ensure the GNU Lesser General Public License version 2.1 requirements
22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 ** In addition, as a special exception, Nokia gives you certain additional
25 ** rights. These rights are described in the Nokia Qt LGPL Exception
26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at qt-info@nokia.com.
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;
323 // creates the next QScript items.
324 static bool bidiItemize(QTextEngine *engine, QScriptAnalysis *analysis, QBidiControl &control)
326 bool rightToLeft = (control.basicDirection() == 1);
327 bool hasBidi = rightToLeft;
329 qDebug() << "bidiItemize: rightToLeft=" << rightToLeft << engine->layoutData->string;
336 int length = engine->layoutData->string.length();
338 const ushort *unicode = (const ushort *)engine->layoutData->string.unicode();
341 QChar::Direction dir = rightToLeft ? QChar::DirR : QChar::DirL;
344 QChar::Direction sdir = QChar::direction(*unicode);
345 if (sdir != QChar::DirL && sdir != QChar::DirR && sdir != QChar::DirEN && sdir != QChar::DirAN)
350 status.lastStrong = rightToLeft ? QChar::DirR : QChar::DirL;
351 status.last = status.lastStrong;
355 while (current <= length) {
357 QChar::Direction dirCurrent;
358 if (current == (int)length)
359 dirCurrent = control.basicDirection();
361 dirCurrent = QChar::direction(unicode[current]);
363 #if (BIDI_DEBUG >= 2)
364 // qDebug() << "pos=" << current << " dir=" << directions[dir]
365 // << " current=" << directions[dirCurrent] << " last=" << directions[status.last]
366 // << " eor=" << eor << '/' << directions[status.eor]
367 // << " sor=" << sor << " lastStrong="
368 // << directions[status.lastStrong]
369 // << " level=" << (int)control.level << " override=" << (bool)control.override;
374 // embedding and overrides (X1-X9 in the BiDi specs)
380 bool rtl = (dirCurrent == QChar::DirRLE || dirCurrent == QChar::DirRLO);
382 bool override = (dirCurrent == QChar::DirLRO || dirCurrent == QChar::DirRLO);
384 unsigned int level = control.level+1;
385 if ((level%2 != 0) == rtl) ++level;
386 if(level < MaxBidiLevel) {
388 appendItems(analysis, sor, eor, control, dir);
390 control.embed(rtl, override);
391 QChar::Direction edir = (rtl ? QChar::DirR : QChar::DirL);
392 dir = status.eor = edir;
393 status.lastStrong = edir;
399 if (control.canPop()) {
400 if (dir != control.direction()) {
402 appendItems(analysis, sor, eor, control, dir);
403 dir = control.direction();
406 appendItems(analysis, sor, eor, control, dir);
408 dir = QChar::DirON; status.eor = QChar::DirON;
409 status.last = control.direction();
410 if (control.override)
411 dir = control.direction();
414 status.lastStrong = control.direction();
421 if(dir == QChar::DirON)
426 eor = current; status.eor = QChar::DirL; break;
432 appendItems(analysis, sor, eor, control, dir);
433 dir = eor < length ? QChar::direction(unicode[eor]) : control.basicDirection();
436 eor = current; status.eor = dir;
447 if(dir != QChar::DirL) {
448 //last stuff takes embedding dir
449 if(control.direction() == QChar::DirR) {
450 if(status.eor != QChar::DirR) {
452 appendItems(analysis, sor, eor, control, dir);
453 status.eor = QChar::DirON;
457 appendItems(analysis, sor, eor, control, dir);
458 dir = eor < length ? QChar::direction(unicode[eor]) : control.basicDirection();
461 if(status.eor != QChar::DirL) {
462 appendItems(analysis, sor, eor, control, dir);
463 status.eor = QChar::DirON;
466 eor = current; status.eor = QChar::DirL; break;
470 eor = current; status.eor = QChar::DirL;
475 status.lastStrong = QChar::DirL;
480 if(dir == QChar::DirON) dir = QChar::DirR;
487 appendItems(analysis, sor, eor, control, dir);
491 dir = QChar::DirR; eor = current; status.eor = QChar::DirR; break;
500 if(status.eor != QChar::DirR && status.eor != QChar::DirAL) {
501 //last stuff takes embedding dir
502 if(control.direction() == QChar::DirR
503 || status.lastStrong == QChar::DirR || status.lastStrong == QChar::DirAL) {
504 appendItems(analysis, sor, eor, control, dir);
505 dir = QChar::DirR; status.eor = QChar::DirON;
509 appendItems(analysis, sor, eor, control, dir);
510 dir = QChar::DirR; status.eor = QChar::DirON;
513 eor = current; status.eor = QChar::DirR;
518 status.lastStrong = dirCurrent;
524 if (eor == current-1)
528 // if last strong was AL change EN to AN
529 if(status.lastStrong != QChar::DirAL) {
530 if(dir == QChar::DirON) {
531 if(status.lastStrong == QChar::DirL)
539 if (status.lastStrong == QChar::DirR || status.lastStrong == QChar::DirAL) {
540 appendItems(analysis, sor, eor, control, dir);
541 status.eor = QChar::DirON;
548 status.eor = dirCurrent;
554 appendItems(analysis, sor, eor, control, dir);
557 status.eor = QChar::DirEN;
558 dir = QChar::DirAN; break;
561 if(status.eor == QChar::DirEN || dir == QChar::DirAN) {
562 eor = current; break;
569 if(status.eor == QChar::DirR) {
572 appendItems(analysis, sor, eor, control, dir);
573 dir = QChar::DirON; status.eor = QChar::DirEN;
576 else if(status.eor == QChar::DirL ||
577 (status.eor == QChar::DirEN && status.lastStrong == QChar::DirL)) {
578 eor = current; status.eor = dirCurrent;
580 // numbers on both sides, neutrals get right to left direction
581 if(dir != QChar::DirL) {
582 appendItems(analysis, sor, eor, control, dir);
583 dir = QChar::DirON; status.eor = QChar::DirON;
586 appendItems(analysis, sor, eor, control, dir);
587 dir = QChar::DirON; status.eor = QChar::DirON;
590 eor = current; status.eor = dirCurrent;
600 dirCurrent = QChar::DirAN;
601 if(dir == QChar::DirON) dir = QChar::DirAN;
606 eor = current; status.eor = QChar::DirAN; break;
611 appendItems(analysis, sor, eor, control, dir);
615 dir = QChar::DirAN; status.eor = QChar::DirAN;
618 if(status.eor == QChar::DirAN) {
619 eor = current; break;
628 if(status.eor == QChar::DirR) {
631 appendItems(analysis, sor, eor, control, dir);
632 status.eor = QChar::DirAN;
634 } else if(status.eor == QChar::DirL ||
635 (status.eor == QChar::DirEN && status.lastStrong == QChar::DirL)) {
636 eor = current; status.eor = dirCurrent;
638 // numbers on both sides, neutrals get right to left direction
639 if(dir != QChar::DirL) {
640 appendItems(analysis, sor, eor, control, dir);
641 status.eor = QChar::DirON;
644 appendItems(analysis, sor, eor, control, dir);
645 status.eor = QChar::DirAN;
648 eor = current; status.eor = dirCurrent;
659 if(status.last == QChar::DirEN) {
660 dirCurrent = QChar::DirEN;
661 eor = current; status.eor = dirCurrent;
665 // boundary neutrals should be ignored
670 // ### what do we do with newline and paragraph separators that come to here?
673 // ### implement rule L1
682 //qDebug() << " after: dir=" << // dir << " current=" << dirCurrent << " last=" << status.last << " eor=" << status.eor << " lastStrong=" << status.lastStrong << " embedding=" << control.direction();
684 if(current >= (int)length) break;
686 // set status.last as needed.
701 status.last = dirCurrent;
704 status.last = QChar::DirON;
713 status.last = QChar::DirL;
717 status.last = QChar::DirR;
720 if (status.last == QChar::DirL) {
721 status.last = QChar::DirL;
726 status.last = dirCurrent;
732 #if (BIDI_DEBUG >= 1)
733 qDebug() << "reached end of line current=" << current << ", eor=" << eor;
735 eor = current - 1; // remove dummy char
738 appendItems(analysis, sor, eor, control, dir);
743 void QTextEngine::bidiReorder(int numItems, const quint8 *levels, int *visualOrder)
746 // first find highest and lowest levels
747 quint8 levelLow = 128;
748 quint8 levelHigh = 0;
750 while (i < numItems) {
751 //printf("level = %d\n", r->level);
752 if (levels[i] > levelHigh)
753 levelHigh = levels[i];
754 if (levels[i] < levelLow)
755 levelLow = levels[i];
759 // implements reordering of the line (L2 according to BiDi spec):
760 // L2. From the highest level found in the text to the lowest odd level on each line,
761 // reverse any contiguous sequence of characters that are at that level or higher.
763 // reversing is only done up to the lowest odd level
764 if(!(levelLow%2)) levelLow++;
766 #if (BIDI_DEBUG >= 1)
767 // qDebug() << "reorderLine: lineLow = " << (uint)levelLow << ", lineHigh = " << (uint)levelHigh;
770 int count = numItems - 1;
771 for (i = 0; i < numItems; i++)
774 while(levelHigh >= levelLow) {
777 while(i < count && levels[i] < levelHigh) i++;
779 while(i <= count && levels[i] >= levelHigh) i++;
783 //qDebug() << "reversing from " << start << " to " << end;
784 for(int j = 0; j < (end-start+1)/2; j++) {
785 int tmp = visualOrder[start+j];
786 visualOrder[start+j] = visualOrder[end-j];
787 visualOrder[end-j] = tmp;
795 #if (BIDI_DEBUG >= 1)
796 // qDebug() << "visual order is:";
797 // for (i = 0; i < numItems; i++)
798 // qDebug() << visualOrder[i];
802 QT_BEGIN_INCLUDE_NAMESPACE
804 #if defined(Q_WS_X11) || defined (Q_WS_QWS)
805 # include "qfontengine_ft_p.h"
806 #elif defined(Q_WS_MAC)
807 # include "qtextengine_mac.cpp"
810 #include <private/qharfbuzz_p.h>
812 QT_END_INCLUDE_NAMESPACE
814 // ask the font engine to find out which glyphs (as an index in the specific font) to use for the text in one item.
815 static bool stringToGlyphs(HB_ShaperItem *item, QGlyphLayout *glyphs, QFontEngine *fontEngine)
817 int nGlyphs = item->num_glyphs;
819 QTextEngine::ShaperFlags shaperFlags(QTextEngine::GlyphIndicesOnly);
820 if (item->item.bidiLevel % 2)
821 shaperFlags |= QTextEngine::RightToLeft;
823 bool result = fontEngine->stringToCMap(reinterpret_cast<const QChar *>(item->string + item->item.pos), item->item.length, glyphs, &nGlyphs, shaperFlags);
824 item->num_glyphs = nGlyphs;
825 glyphs->numGlyphs = nGlyphs;
829 // shape all the items that intersect with the line, taking tab widths into account to find out what text actually fits in the line.
830 void QTextEngine::shapeLine(const QScriptLine &line)
834 const int end = findItem(line.from + line.length - 1);
835 int item = findItem(line.from);
838 for (item = findItem(line.from); item <= end; ++item) {
839 QScriptItem &si = layoutData->items[item];
840 if (si.analysis.flags == QScriptAnalysis::Tab) {
842 si.width = calculateTabWidth(item, x);
846 if (first && si.position != line.from) { // that means our x position has to be offset
847 QGlyphLayout glyphs = shapedGlyphs(&si);
848 Q_ASSERT(line.from > si.position);
849 for (int i = line.from - si.position - 1; i >= 0; i--) {
850 x -= glyphs.effectiveAdvance(i);
859 #if !defined(QT_ENABLE_HARFBUZZ_FOR_MAC)
860 static bool enableHarfBuzz()
862 static enum { Yes, No, Unknown } status = Unknown;
864 if (status == Unknown) {
865 QByteArray v = qgetenv("QT_ENABLE_HARFBUZZ");
866 bool value = !v.isEmpty() && v != "0" && v != "false";
867 if (value) status = Yes;
870 return status == Yes;
874 void QTextEngine::shapeText(int item) const
876 Q_ASSERT(item < layoutData->items.size());
877 QScriptItem &si = layoutData->items[item];
882 #if defined(Q_WS_MAC)
883 #if !defined(QT_ENABLE_HARFBUZZ_FOR_MAC)
884 if (enableHarfBuzz()) {
886 QFontEngine *actualFontEngine = fontEngine(si, &si.ascent, &si.descent, &si.leading);
887 if (actualFontEngine->type() == QFontEngine::Multi)
888 actualFontEngine = static_cast<QFontEngineMulti *>(actualFontEngine)->engine(0);
890 HB_Face face = actualFontEngine->harfbuzzFace();
891 HB_Script script = (HB_Script) si.analysis.script;
892 if (face->supported_scripts[script])
893 shapeTextWithHarfbuzz(item);
896 #if !defined(QT_ENABLE_HARFBUZZ_FOR_MAC)
901 #elif defined(Q_WS_WINCE)
902 shapeTextWithCE(item);
904 shapeTextWithHarfbuzz(item);
911 QGlyphLayout glyphs = shapedGlyphs(&si);
913 QFont font = this->font(si);
914 bool letterSpacingIsAbsolute = font.d->letterSpacingIsAbsolute;
915 QFixed letterSpacing = font.d->letterSpacing;
916 QFixed wordSpacing = font.d->wordSpacing;
918 if (letterSpacingIsAbsolute && letterSpacing.value())
919 letterSpacing *= font.d->dpi / qt_defaultDpiY();
921 if (letterSpacing != 0) {
922 for (int i = 1; i < si.num_glyphs; ++i) {
923 if (glyphs.attributes[i].clusterStart) {
924 if (letterSpacingIsAbsolute)
925 glyphs.advances_x[i-1] += letterSpacing;
927 QFixed &advance = glyphs.advances_x[i-1];
928 advance += (letterSpacing - 100) * advance / 100;
932 if (letterSpacingIsAbsolute)
933 glyphs.advances_x[si.num_glyphs-1] += letterSpacing;
935 QFixed &advance = glyphs.advances_x[si.num_glyphs-1];
936 advance += (letterSpacing - 100) * advance / 100;
939 if (wordSpacing != 0) {
940 for (int i = 0; i < si.num_glyphs; ++i) {
941 if (glyphs.attributes[i].justification == HB_Space
942 || glyphs.attributes[i].justification == HB_Arabic_Space) {
943 // word spacing only gets added once to a consecutive run of spaces (see CSS spec)
944 if (i + 1 == si.num_glyphs
945 ||(glyphs.attributes[i+1].justification != HB_Space
946 && glyphs.attributes[i+1].justification != HB_Arabic_Space))
947 glyphs.advances_x[i] += wordSpacing;
952 for (int i = 0; i < si.num_glyphs; ++i)
953 si.width += glyphs.advances_x[i];
956 static inline bool hasCaseChange(const QScriptItem &si)
958 return si.analysis.flags == QScriptAnalysis::SmallCaps ||
959 si.analysis.flags == QScriptAnalysis::Uppercase ||
960 si.analysis.flags == QScriptAnalysis::Lowercase;
963 #if defined(Q_WS_WINCE) //TODO
964 // set the glyph attributes heuristically. Assumes a 1 to 1 relationship between chars and glyphs
965 // and no reordering.
966 // also computes logClusters heuristically
967 static void heuristicSetGlyphAttributes(const QChar *uc, int length, QGlyphLayout *glyphs, unsigned short *logClusters, int num_glyphs)
969 // ### zeroWidth and justification are missing here!!!!!
971 Q_UNUSED(num_glyphs);
972 Q_ASSERT(num_glyphs <= length);
974 // qDebug("QScriptEngine::heuristicSetGlyphAttributes, num_glyphs=%d", item->num_glyphs);
977 for (int i = 0; i < length; i++) {
978 if (uc[i].unicode() >= 0xd800 && uc[i].unicode() < 0xdc00 && i < length-1
979 && uc[i+1].unicode() >= 0xdc00 && uc[i+1].unicode() < 0xe000) {
980 logClusters[i] = glyph_pos;
981 logClusters[++i] = glyph_pos;
983 logClusters[i] = glyph_pos;
988 // first char in a run is never (treated as) a mark
991 const bool symbolFont = false; // ####
992 glyphs->attributes[0].mark = false;
993 glyphs->attributes[0].clusterStart = true;
994 glyphs->attributes[0].dontPrint = (!symbolFont && uc[0].unicode() == 0x00ad) || qIsControlChar(uc[0].unicode());
997 int lastCat = QChar::category(uc[0].unicode());
998 for (int i = 1; i < length; ++i) {
999 if (logClusters[i] == pos)
1003 while (pos < logClusters[i]) {
1004 glyphs[pos].attributes = glyphs[pos-1].attributes;
1007 // hide soft-hyphens by default
1008 if ((!symbolFont && uc[i].unicode() == 0x00ad) || qIsControlChar(uc[i].unicode()))
1009 glyphs->attributes[pos].dontPrint = true;
1010 const QUnicodeTables::Properties *prop = QUnicodeTables::properties(uc[i].unicode());
1011 int cat = prop->category;
1012 if (cat != QChar::Mark_NonSpacing) {
1013 glyphs->attributes[pos].mark = false;
1014 glyphs->attributes[pos].clusterStart = true;
1015 glyphs->attributes[pos].combiningClass = 0;
1016 cStart = logClusters[i];
1018 int cmb = prop->combiningClass;
1021 // Fix 0 combining classes
1022 if ((uc[pos].unicode() & 0xff00) == 0x0e00) {
1024 unsigned char col = uc[pos].cell();
1034 cmb = QChar::Combining_AboveRight;
1035 } else if (col == 0xb1 ||
1043 cmb = QChar::Combining_Above;
1044 } else if (col == 0xbc) {
1045 cmb = QChar::Combining_Below;
1050 glyphs->attributes[pos].mark = true;
1051 glyphs->attributes[pos].clusterStart = false;
1052 glyphs->attributes[pos].combiningClass = cmb;
1053 logClusters[i] = cStart;
1054 glyphs->advances_x[pos] = 0;
1055 glyphs->advances_y[pos] = 0;
1058 // one gets an inter character justification point if the current char is not a non spacing mark.
1059 // as then the current char belongs to the last one and one gets a space justification point
1060 // after the space char.
1061 if (lastCat == QChar::Separator_Space)
1062 glyphs->attributes[pos-1].justification = HB_Space;
1063 else if (cat != QChar::Mark_NonSpacing)
1064 glyphs->attributes[pos-1].justification = HB_Character;
1066 glyphs->attributes[pos-1].justification = HB_NoJustification;
1070 pos = logClusters[length-1];
1071 if (lastCat == QChar::Separator_Space)
1072 glyphs->attributes[pos].justification = HB_Space;
1074 glyphs->attributes[pos].justification = HB_Character;
1077 void QTextEngine::shapeTextWithCE(int item) const
1079 QScriptItem &si = layoutData->items[item];
1080 si.glyph_data_offset = layoutData->used;
1082 QFontEngine *fe = fontEngine(si, &si.ascent, &si.descent, &si.leading);
1084 QTextEngine::ShaperFlags flags;
1085 if (si.analysis.bidiLevel % 2)
1086 flags |= RightToLeft;
1087 if (option.useDesignMetrics())
1088 flags |= DesignMetrics;
1090 // pre-initialize char attributes
1094 const int len = length(item);
1095 int num_glyphs = length(item);
1096 const QChar *str = layoutData->string.unicode() + si.position;
1097 ushort upperCased[256];
1098 if (hasCaseChange(si)) {
1099 ushort *uc = upperCased;
1101 uc = new ushort[len];
1102 for (int i = 0; i < len; ++i) {
1103 if(si.analysis.flags == QScriptAnalysis::Lowercase)
1104 uc[i] = str[i].toLower().unicode();
1106 uc[i] = str[i].toUpper().unicode();
1108 str = reinterpret_cast<const QChar *>(uc);
1112 if (! ensureSpace(num_glyphs)) {
1113 // If str is converted to uppercase/lowercase form with a new buffer,
1114 // we need to delete that buffer before return for error
1115 const ushort *uc = reinterpret_cast<const ushort *>(str);
1116 if (hasCaseChange(si) && uc != upperCased)
1120 num_glyphs = layoutData->glyphLayout.numGlyphs - layoutData->used;
1122 QGlyphLayout g = availableGlyphs(&si);
1123 unsigned short *log_clusters = logClusters(&si);
1125 if (fe->stringToCMap(str,
1130 heuristicSetGlyphAttributes(str, len, &g, log_clusters, num_glyphs);
1135 si.num_glyphs = num_glyphs;
1137 layoutData->used += si.num_glyphs;
1139 const ushort *uc = reinterpret_cast<const ushort *>(str);
1140 if (hasCaseChange(si) && uc != upperCased)
1145 static inline void moveGlyphData(const QGlyphLayout &destination, const QGlyphLayout &source, int num)
1147 if (num > 0 && destination.glyphs != source.glyphs) {
1148 memmove(destination.glyphs, source.glyphs, num * sizeof(HB_Glyph));
1149 memmove(destination.attributes, source.attributes, num * sizeof(HB_GlyphAttributes));
1150 memmove(destination.advances_x, source.advances_x, num * sizeof(HB_Fixed));
1151 memmove(destination.offsets, source.offsets, num * sizeof(HB_FixedPoint));
1155 /// take the item from layoutData->items and
1156 void QTextEngine::shapeTextWithHarfbuzz(int item) const
1158 Q_ASSERT(sizeof(HB_Fixed) == sizeof(QFixed));
1159 Q_ASSERT(sizeof(HB_FixedPoint) == sizeof(QFixedPoint));
1161 QScriptItem &si = layoutData->items[item];
1163 si.glyph_data_offset = layoutData->used;
1165 QFontEngine *font = fontEngine(si, &si.ascent, &si.descent, &si.leading);
1167 bool kerningEnabled = this->font(si).d->kerning;
1169 HB_ShaperItem entire_shaper_item;
1170 qMemSet(&entire_shaper_item, 0, sizeof(entire_shaper_item));
1171 entire_shaper_item.string = reinterpret_cast<const HB_UChar16 *>(layoutData->string.constData());
1172 entire_shaper_item.stringLength = layoutData->string.length();
1173 entire_shaper_item.item.script = (HB_Script)si.analysis.script;
1174 entire_shaper_item.item.pos = si.position;
1175 entire_shaper_item.item.length = length(item);
1176 entire_shaper_item.item.bidiLevel = si.analysis.bidiLevel;
1178 HB_UChar16 upperCased[256]; // XXX what about making this 4096, so we don't have to extend it ever.
1179 if (hasCaseChange(si)) {
1180 HB_UChar16 *uc = upperCased;
1181 if (entire_shaper_item.item.length > 256)
1182 uc = new HB_UChar16[entire_shaper_item.item.length];
1183 for (uint i = 0; i < entire_shaper_item.item.length; ++i) {
1184 if(si.analysis.flags == QScriptAnalysis::Lowercase)
1185 uc[i] = QChar::toLower(entire_shaper_item.string[si.position + i]);
1187 uc[i] = QChar::toUpper(entire_shaper_item.string[si.position + i]);
1189 entire_shaper_item.item.pos = 0;
1190 entire_shaper_item.string = uc;
1191 entire_shaper_item.stringLength = entire_shaper_item.item.length;
1194 entire_shaper_item.shaperFlags = 0;
1195 if (!kerningEnabled)
1196 entire_shaper_item.shaperFlags |= HB_ShaperFlag_NoKerning;
1197 if (option.useDesignMetrics())
1198 entire_shaper_item.shaperFlags |= HB_ShaperFlag_UseDesignMetrics;
1200 entire_shaper_item.num_glyphs = qMax(layoutData->glyphLayout.numGlyphs - layoutData->used, int(entire_shaper_item.item.length));
1201 if (! ensureSpace(entire_shaper_item.num_glyphs)) {
1202 if (hasCaseChange(si))
1203 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1206 QGlyphLayout initialGlyphs = availableGlyphs(&si).mid(0, entire_shaper_item.num_glyphs);
1208 if (!stringToGlyphs(&entire_shaper_item, &initialGlyphs, font)) {
1209 if (! ensureSpace(entire_shaper_item.num_glyphs)) {
1210 if (hasCaseChange(si))
1211 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1214 initialGlyphs = availableGlyphs(&si).mid(0, entire_shaper_item.num_glyphs);
1216 if (!stringToGlyphs(&entire_shaper_item, &initialGlyphs, font)) {
1217 // ############ if this happens there's a bug in the fontengine
1218 if (hasCaseChange(si) && entire_shaper_item.string != upperCased)
1219 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1224 // split up the item into parts that come from different font engines.
1225 QVarLengthArray<int> itemBoundaries(2);
1226 // k * 2 entries, array[k] == index in string, array[k + 1] == index in glyphs
1227 itemBoundaries[0] = entire_shaper_item.item.pos;
1228 itemBoundaries[1] = 0;
1230 if (font->type() == QFontEngine::Multi) {
1231 uint lastEngine = 0;
1232 int charIdx = entire_shaper_item.item.pos;
1233 const int stringEnd = charIdx + entire_shaper_item.item.length;
1234 for (quint32 i = 0; i < entire_shaper_item.num_glyphs; ++i, ++charIdx) {
1235 uint engineIdx = initialGlyphs.glyphs[i] >> 24;
1236 if (engineIdx != lastEngine && i > 0) {
1237 itemBoundaries.append(charIdx);
1238 itemBoundaries.append(i);
1240 lastEngine = engineIdx;
1241 if (HB_IsHighSurrogate(entire_shaper_item.string[charIdx])
1242 && charIdx < stringEnd - 1
1243 && HB_IsLowSurrogate(entire_shaper_item.string[charIdx + 1]))
1250 int remaining_glyphs = entire_shaper_item.num_glyphs;
1252 // for each item shape using harfbuzz and store the results in our layoutData's glyphs array.
1253 for (int k = 0; k < itemBoundaries.size(); k += 2) { // for the +2, see the comment at the definition of itemBoundaries
1255 HB_ShaperItem shaper_item = entire_shaper_item;
1257 shaper_item.item.pos = itemBoundaries[k];
1258 if (k < itemBoundaries.size() - 3) {
1259 shaper_item.item.length = itemBoundaries[k + 2] - shaper_item.item.pos;
1260 shaper_item.num_glyphs = itemBoundaries[k + 3] - itemBoundaries[k + 1];
1261 } else { // last combo in the list, avoid out of bounds access.
1262 shaper_item.item.length -= shaper_item.item.pos - entire_shaper_item.item.pos;
1263 shaper_item.num_glyphs -= itemBoundaries[k + 1];
1265 shaper_item.initialGlyphCount = shaper_item.num_glyphs;
1266 if (shaper_item.num_glyphs < shaper_item.item.length)
1267 shaper_item.num_glyphs = shaper_item.item.length;
1269 QFontEngine *actualFontEngine = font;
1271 if (font->type() == QFontEngine::Multi) {
1272 engineIdx = uint(availableGlyphs(&si).glyphs[glyph_pos] >> 24);
1274 actualFontEngine = static_cast<QFontEngineMulti *>(font)->engine(engineIdx);
1277 shaper_item.font = actualFontEngine->harfbuzzFont();
1278 shaper_item.face = actualFontEngine->harfbuzzFace();
1280 shaper_item.glyphIndicesPresent = true;
1282 remaining_glyphs -= shaper_item.initialGlyphCount;
1285 if (! ensureSpace(glyph_pos + shaper_item.num_glyphs + remaining_glyphs)) {
1286 if (hasCaseChange(si))
1287 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1291 const QGlyphLayout g = availableGlyphs(&si).mid(glyph_pos);
1292 if (shaper_item.num_glyphs > shaper_item.item.length)
1293 moveGlyphData(g.mid(shaper_item.num_glyphs), g.mid(shaper_item.initialGlyphCount), remaining_glyphs);
1295 shaper_item.glyphs = g.glyphs;
1296 shaper_item.attributes = g.attributes;
1297 shaper_item.advances = reinterpret_cast<HB_Fixed *>(g.advances_x);
1298 shaper_item.offsets = reinterpret_cast<HB_FixedPoint *>(g.offsets);
1300 if (shaper_item.glyphIndicesPresent) {
1301 for (hb_uint32 i = 0; i < shaper_item.initialGlyphCount; ++i)
1302 shaper_item.glyphs[i] &= 0x00ffffff;
1305 shaper_item.log_clusters = logClusters(&si) + shaper_item.item.pos - entire_shaper_item.item.pos;
1307 // qDebug(" .. num_glyphs=%d, used=%d, item.num_glyphs=%d", num_glyphs, used, shaper_item.num_glyphs);
1308 } while (!qShapeItem(&shaper_item)); // this does the actual shaping via harfbuzz.
1310 QGlyphLayout g = availableGlyphs(&si).mid(glyph_pos, shaper_item.num_glyphs);
1311 moveGlyphData(g.mid(shaper_item.num_glyphs), g.mid(shaper_item.initialGlyphCount), remaining_glyphs);
1313 for (hb_uint32 i = 0; i < shaper_item.num_glyphs; ++i)
1314 g.glyphs[i] = g.glyphs[i] | (engineIdx << 24);
1316 for (hb_uint32 i = 0; i < shaper_item.item.length; ++i)
1317 shaper_item.log_clusters[i] += glyph_pos;
1319 if (kerningEnabled && !shaper_item.kerning_applied)
1320 font->doKerning(&g, option.useDesignMetrics() ? QFlag(QTextEngine::DesignMetrics) : QFlag(0));
1322 glyph_pos += shaper_item.num_glyphs;
1325 // qDebug(" -> item: script=%d num_glyphs=%d", shaper_item.script, shaper_item.num_glyphs);
1326 si.num_glyphs = glyph_pos;
1328 layoutData->used += si.num_glyphs;
1330 if (hasCaseChange(si) && entire_shaper_item.string != upperCased)
1331 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1334 static void init(QTextEngine *e)
1336 e->ignoreBidi = false;
1337 e->cacheGlyphs = false;
1338 e->forceJustification = false;
1339 e->visualMovement = false;
1346 e->underlinePositions = 0;
1348 e->stackEngine = false;
1351 QTextEngine::QTextEngine()
1356 QTextEngine::QTextEngine(const QString &str, const QFont &f)
1363 QTextEngine::~QTextEngine()
1370 const HB_CharAttributes *QTextEngine::attributes() const
1372 if (layoutData && layoutData->haveCharAttributes)
1373 return (HB_CharAttributes *) layoutData->memory;
1376 if (! ensureSpace(layoutData->string.length()))
1379 QVarLengthArray<HB_ScriptItem> hbScriptItems(layoutData->items.size());
1381 for (int i = 0; i < layoutData->items.size(); ++i) {
1382 const QScriptItem &si = layoutData->items[i];
1383 hbScriptItems[i].pos = si.position;
1384 hbScriptItems[i].length = length(i);
1385 hbScriptItems[i].bidiLevel = si.analysis.bidiLevel;
1386 hbScriptItems[i].script = (HB_Script)si.analysis.script;
1389 qGetCharAttributes(reinterpret_cast<const HB_UChar16 *>(layoutData->string.constData()),
1390 layoutData->string.length(),
1391 hbScriptItems.data(), hbScriptItems.size(),
1392 (HB_CharAttributes *)layoutData->memory);
1395 layoutData->haveCharAttributes = true;
1396 return (HB_CharAttributes *) layoutData->memory;
1399 void QTextEngine::shape(int item) const
1401 if (layoutData->items[item].analysis.flags == QScriptAnalysis::Object) {
1403 if (block.docHandle()) {
1404 QTextFormat format = formats()->format(formatIndex(&layoutData->items[item]));
1405 docLayout()->resizeInlineObject(QTextInlineObject(item, const_cast<QTextEngine *>(this)),
1406 layoutData->items[item].position + block.position(), format);
1408 } else if (layoutData->items[item].analysis.flags == QScriptAnalysis::Tab) {
1409 // set up at least the ascent/descent/leading of the script item for the tab
1410 fontEngine(layoutData->items[item],
1411 &layoutData->items[item].ascent,
1412 &layoutData->items[item].descent,
1413 &layoutData->items[item].leading);
1419 static inline void releaseCachedFontEngine(QFontEngine *fontEngine)
1422 fontEngine->ref.deref();
1423 if (fontEngine->cache_count == 0 && fontEngine->ref == 0)
1428 void QTextEngine::invalidate()
1434 specialData->resolvedFormatIndices.clear();
1436 releaseCachedFontEngine(feCache.prevFontEngine);
1437 releaseCachedFontEngine(feCache.prevScaledFontEngine);
1441 void QTextEngine::clearLineData()
1446 void QTextEngine::validate() const
1450 layoutData = new LayoutData();
1451 if (block.docHandle()) {
1452 layoutData->string = block.text();
1453 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators)
1454 layoutData->string += QLatin1Char(block.next().isValid() ? 0xb6 : 0x20);
1456 layoutData->string = text;
1458 if (specialData && specialData->preeditPosition != -1)
1459 layoutData->string.insert(specialData->preeditPosition, specialData->preeditText);
1462 void QTextEngine::itemize() const
1465 if (layoutData->items.size())
1468 int length = layoutData->string.length();
1471 #if defined(Q_WS_MAC) && !defined(QT_MAC_USE_COCOA)
1472 // ATSUI requires RTL flags to correctly identify the character stops.
1473 bool ignore = false;
1475 bool ignore = ignoreBidi;
1478 bool rtl = isRightToLeft();
1480 if (!ignore && !rtl) {
1482 const QChar *start = layoutData->string.unicode();
1483 const QChar * const end = start + length;
1484 while (start < end) {
1485 if (start->unicode() >= 0x590) {
1493 QVarLengthArray<QScriptAnalysis, 4096> scriptAnalysis(length);
1494 QScriptAnalysis *analysis = scriptAnalysis.data();
1496 QBidiControl control(rtl);
1499 memset(analysis, 0, length*sizeof(QScriptAnalysis));
1500 if (option.textDirection() == Qt::RightToLeft) {
1501 for (int i = 0; i < length; ++i)
1502 analysis[i].bidiLevel = 1;
1503 layoutData->hasBidi = true;
1506 layoutData->hasBidi = bidiItemize(const_cast<QTextEngine *>(this), analysis, control);
1509 const ushort *uc = reinterpret_cast<const ushort *>(layoutData->string.unicode());
1510 const ushort *e = uc + length;
1511 int lastScript = QUnicodeTables::Common;
1513 int script = QUnicodeTables::script(*uc);
1514 if (script == QUnicodeTables::Inherited)
1515 script = lastScript;
1516 analysis->flags = QScriptAnalysis::None;
1517 if (*uc == QChar::ObjectReplacementCharacter) {
1518 if (analysis->bidiLevel % 2)
1519 --analysis->bidiLevel;
1520 analysis->script = QUnicodeTables::Common;
1521 analysis->flags = QScriptAnalysis::Object;
1522 } else if (*uc == QChar::LineSeparator) {
1523 if (analysis->bidiLevel % 2)
1524 --analysis->bidiLevel;
1525 analysis->script = QUnicodeTables::Common;
1526 analysis->flags = QScriptAnalysis::LineOrParagraphSeparator;
1527 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators)
1528 *const_cast<ushort*>(uc) = 0x21B5; // visual line separator
1529 } else if (*uc == 9) {
1530 analysis->script = QUnicodeTables::Common;
1531 analysis->flags = QScriptAnalysis::Tab;
1532 analysis->bidiLevel = control.baseLevel();
1533 } else if ((*uc == 32 || *uc == QChar::Nbsp)
1534 && (option.flags() & QTextOption::ShowTabsAndSpaces)) {
1535 analysis->script = QUnicodeTables::Common;
1536 analysis->flags = QScriptAnalysis::Space;
1537 analysis->bidiLevel = control.baseLevel();
1539 analysis->script = script;
1541 lastScript = analysis->script;
1545 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators) {
1546 (analysis-1)->flags = QScriptAnalysis::LineOrParagraphSeparator; // to exclude it from width
1549 Itemizer itemizer(layoutData->string, scriptAnalysis.data(), layoutData->items);
1551 const QTextDocumentPrivate *p = block.docHandle();
1553 SpecialData *s = specialData;
1555 QTextDocumentPrivate::FragmentIterator it = p->find(block.position());
1556 QTextDocumentPrivate::FragmentIterator end = p->find(block.position() + block.length() - 1); // -1 to omit the block separator char
1557 int format = it.value()->format;
1559 int prevPosition = 0;
1560 int position = prevPosition;
1562 const QTextFragmentData * const frag = it.value();
1563 if (it == end || format != frag->format) {
1564 if (s && position >= s->preeditPosition) {
1565 position += s->preeditText.length();
1568 Q_ASSERT(position <= length);
1569 itemizer.generate(prevPosition, position - prevPosition,
1570 formats()->charFormat(format).fontCapitalization());
1572 if (position < length)
1573 itemizer.generate(position, length - position,
1574 formats()->charFormat(format).fontCapitalization());
1577 format = frag->format;
1578 prevPosition = position;
1580 position += frag->size_array[0];
1584 itemizer.generate(0, length, static_cast<QFont::Capitalization> (fnt.d->capital));
1587 addRequiredBoundaries();
1588 resolveAdditionalFormats();
1591 bool QTextEngine::isRightToLeft() const
1593 switch (option.textDirection()) {
1594 case Qt::LeftToRight:
1596 case Qt::RightToLeft:
1601 // this places the cursor in the right position depending on the keyboard layout
1602 if (layoutData->string.isEmpty())
1603 return QApplication::keyboardInputDirection() == Qt::RightToLeft;
1604 return layoutData->string.isRightToLeft();
1608 int QTextEngine::findItem(int strPos) const
1612 int right = layoutData->items.size()-1;
1613 while(left <= right) {
1614 int middle = ((right-left)/2)+left;
1615 if (strPos > layoutData->items[middle].position)
1617 else if(strPos < layoutData->items[middle].position)
1626 QFixed QTextEngine::width(int from, int len) const
1632 // qDebug("QTextEngine::width(from = %d, len = %d), numItems=%d, strleng=%d", from, len, items.size(), string.length());
1633 for (int i = 0; i < layoutData->items.size(); i++) {
1634 const QScriptItem *si = layoutData->items.constData() + i;
1635 int pos = si->position;
1636 int ilen = length(i);
1637 // qDebug("item %d: from %d len %d", i, pos, ilen);
1638 if (pos >= from + len)
1640 if (pos + ilen > from) {
1641 if (!si->num_glyphs)
1644 if (si->analysis.flags == QScriptAnalysis::Object) {
1647 } else if (si->analysis.flags == QScriptAnalysis::Tab) {
1648 w += calculateTabWidth(i, w);
1653 QGlyphLayout glyphs = shapedGlyphs(si);
1654 unsigned short *logClusters = this->logClusters(si);
1656 // fprintf(stderr, " logclusters:");
1657 // for (int k = 0; k < ilen; k++)
1658 // fprintf(stderr, " %d", logClusters[k]);
1659 // fprintf(stderr, "\n");
1660 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1661 int charFrom = from - pos;
1664 int glyphStart = logClusters[charFrom];
1665 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1666 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1668 if (charFrom < ilen) {
1669 glyphStart = logClusters[charFrom];
1670 int charEnd = from + len - 1 - pos;
1671 if (charEnd >= ilen)
1673 int glyphEnd = logClusters[charEnd];
1674 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1676 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1678 // qDebug("char: start=%d end=%d / glyph: start = %d, end = %d", charFrom, charEnd, glyphStart, glyphEnd);
1679 for (int i = glyphStart; i < glyphEnd; i++)
1680 w += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
1684 // qDebug(" --> w= %d ", w);
1688 glyph_metrics_t QTextEngine::boundingBox(int from, int len) const
1694 for (int i = 0; i < layoutData->items.size(); i++) {
1695 const QScriptItem *si = layoutData->items.constData() + i;
1697 int pos = si->position;
1698 int ilen = length(i);
1699 if (pos > from + len)
1701 if (pos + ilen > from) {
1702 if (!si->num_glyphs)
1705 if (si->analysis.flags == QScriptAnalysis::Object) {
1706 gm.width += si->width;
1708 } else if (si->analysis.flags == QScriptAnalysis::Tab) {
1709 gm.width += calculateTabWidth(i, gm.width);
1713 unsigned short *logClusters = this->logClusters(si);
1714 QGlyphLayout glyphs = shapedGlyphs(si);
1716 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1717 int charFrom = from - pos;
1720 int glyphStart = logClusters[charFrom];
1721 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1722 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1724 if (charFrom < ilen) {
1725 QFontEngine *fe = fontEngine(*si);
1726 glyphStart = logClusters[charFrom];
1727 int charEnd = from + len - 1 - pos;
1728 if (charEnd >= ilen)
1730 int glyphEnd = logClusters[charEnd];
1731 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1733 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1734 if (glyphStart <= glyphEnd ) {
1735 glyph_metrics_t m = fe->boundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
1736 gm.x = qMin(gm.x, m.x + gm.xoff);
1737 gm.y = qMin(gm.y, m.y + gm.yoff);
1738 gm.width = qMax(gm.width, m.width+gm.xoff);
1739 gm.height = qMax(gm.height, m.height+gm.yoff);
1749 glyph_metrics_t QTextEngine::tightBoundingBox(int from, int len) const
1755 for (int i = 0; i < layoutData->items.size(); i++) {
1756 const QScriptItem *si = layoutData->items.constData() + i;
1757 int pos = si->position;
1758 int ilen = length(i);
1759 if (pos > from + len)
1761 if (pos + len > from) {
1762 if (!si->num_glyphs)
1764 unsigned short *logClusters = this->logClusters(si);
1765 QGlyphLayout glyphs = shapedGlyphs(si);
1767 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1768 int charFrom = from - pos;
1771 int glyphStart = logClusters[charFrom];
1772 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1773 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1775 if (charFrom < ilen) {
1776 glyphStart = logClusters[charFrom];
1777 int charEnd = from + len - 1 - pos;
1778 if (charEnd >= ilen)
1780 int glyphEnd = logClusters[charEnd];
1781 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1783 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1784 if (glyphStart <= glyphEnd ) {
1785 QFontEngine *fe = fontEngine(*si);
1786 glyph_metrics_t m = fe->tightBoundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
1787 gm.x = qMin(gm.x, m.x + gm.xoff);
1788 gm.y = qMin(gm.y, m.y + gm.yoff);
1789 gm.width = qMax(gm.width, m.width+gm.xoff);
1790 gm.height = qMax(gm.height, m.height+gm.yoff);
1800 QFont QTextEngine::font(const QScriptItem &si) const
1804 QTextCharFormat f = format(&si);
1807 if (block.docHandle() && block.docHandle()->layout()) {
1808 // Make sure we get the right dpi on printers
1809 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
1811 font = QFont(font, pdev);
1813 font = font.resolve(fnt);
1815 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
1816 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
1817 if (font.pointSize() != -1)
1818 font.setPointSize((font.pointSize() * 2) / 3);
1820 font.setPixelSize((font.pixelSize() * 2) / 3);
1824 if (si.analysis.flags == QScriptAnalysis::SmallCaps)
1825 font = font.d->smallCapsFont();
1830 QTextEngine::FontEngineCache::FontEngineCache()
1835 //we cache the previous results of this function, as calling it numerous times with the same effective
1836 //input is common (and hard to cache at a higher level)
1837 QFontEngine *QTextEngine::fontEngine(const QScriptItem &si, QFixed *ascent, QFixed *descent, QFixed *leading) const
1839 QFontEngine *engine = 0;
1840 QFontEngine *scaledEngine = 0;
1841 int script = si.analysis.script;
1845 if (feCache.prevFontEngine && feCache.prevPosition == si.position && feCache.prevLength == length(&si) && feCache.prevScript == script) {
1846 engine = feCache.prevFontEngine;
1847 scaledEngine = feCache.prevScaledFontEngine;
1849 QTextCharFormat f = format(&si);
1852 if (block.docHandle() && block.docHandle()->layout()) {
1853 // Make sure we get the right dpi on printers
1854 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
1856 font = QFont(font, pdev);
1858 font = font.resolve(fnt);
1860 engine = font.d->engineForScript(script);
1861 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
1862 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
1863 if (font.pointSize() != -1)
1864 font.setPointSize((font.pointSize() * 2) / 3);
1866 font.setPixelSize((font.pixelSize() * 2) / 3);
1867 scaledEngine = font.d->engineForScript(script);
1869 feCache.prevFontEngine = engine;
1872 feCache.prevScaledFontEngine = scaledEngine;
1874 scaledEngine->ref.ref();
1875 feCache.prevScript = script;
1876 feCache.prevPosition = si.position;
1877 feCache.prevLength = length(&si);
1880 if (feCache.prevFontEngine && feCache.prevScript == script && feCache.prevPosition == -1)
1881 engine = feCache.prevFontEngine;
1883 engine = font.d->engineForScript(script);
1884 feCache.prevFontEngine = engine;
1887 feCache.prevScript = script;
1888 feCache.prevPosition = -1;
1889 feCache.prevLength = -1;
1890 feCache.prevScaledFontEngine = 0;
1894 if (si.analysis.flags == QScriptAnalysis::SmallCaps) {
1895 QFontPrivate *p = font.d->smallCapsFontPrivate();
1896 scaledEngine = p->engineForScript(script);
1900 *ascent = engine->ascent();
1901 *descent = engine->descent();
1902 *leading = engine->leading();
1906 return scaledEngine;
1910 struct QJustificationPoint {
1912 QFixed kashidaWidth;
1914 QFontEngine *fontEngine;
1917 Q_DECLARE_TYPEINFO(QJustificationPoint, Q_PRIMITIVE_TYPE);
1919 static void set(QJustificationPoint *point, int type, const QGlyphLayout &glyph, QFontEngine *fe)
1922 point->glyph = glyph;
1923 point->fontEngine = fe;
1925 if (type >= HB_Arabic_Normal) {
1926 QChar ch(0x640); // Kashida character
1927 QGlyphLayoutArray<8> glyphs;
1929 fe->stringToCMap(&ch, 1, &glyphs, &nglyphs, 0);
1930 if (glyphs.glyphs[0] && glyphs.advances_x[0] != 0) {
1931 point->kashidaWidth = glyphs.advances_x[0];
1933 point->type = HB_NoJustification;
1934 point->kashidaWidth = 0;
1940 void QTextEngine::justify(const QScriptLine &line)
1942 // qDebug("justify: line.gridfitted = %d, line.justified=%d", line.gridfitted, line.justified);
1943 if (line.gridfitted && line.justified)
1946 if (!line.gridfitted) {
1947 // redo layout in device metrics, then adjust
1948 const_cast<QScriptLine &>(line).gridfitted = true;
1951 if ((option.alignment() & Qt::AlignHorizontal_Mask) != Qt::AlignJustify)
1956 if (!forceJustification) {
1957 int end = line.from + (int)line.length;
1958 if (end == layoutData->string.length())
1959 return; // no justification at end of paragraph
1960 if (end && layoutData->items[findItem(end-1)].analysis.flags == QScriptAnalysis::LineOrParagraphSeparator)
1961 return; // no justification at the end of an explicitly separated line
1967 // don't include trailing white spaces when doing justification
1968 int line_length = line.length;
1969 const HB_CharAttributes *a = attributes();
1973 while (line_length && a[line_length-1].whiteSpace)
1975 // subtract one char more, as we can't justfy after the last character
1981 int firstItem = findItem(line.from);
1982 int nItems = findItem(line.from + line_length - 1) - firstItem + 1;
1984 QVarLengthArray<QJustificationPoint> justificationPoints;
1986 // 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());
1987 QFixed minKashida = 0x100000;
1989 // we need to do all shaping before we go into the next loop, as we there
1990 // store pointers to the glyph data that could get reallocated by the shaping
1992 for (int i = 0; i < nItems; ++i) {
1993 QScriptItem &si = layoutData->items[firstItem + i];
1995 shape(firstItem + i);
1998 for (int i = 0; i < nItems; ++i) {
1999 QScriptItem &si = layoutData->items[firstItem + i];
2001 int kashida_type = HB_Arabic_Normal;
2002 int kashida_pos = -1;
2004 int start = qMax(line.from - si.position, 0);
2005 int end = qMin(line.from + line_length - (int)si.position, length(firstItem+i));
2007 unsigned short *log_clusters = logClusters(&si);
2009 int gs = log_clusters[start];
2010 int ge = (end == length(firstItem+i) ? si.num_glyphs : log_clusters[end]);
2012 const QGlyphLayout g = shapedGlyphs(&si);
2014 for (int i = gs; i < ge; ++i) {
2015 g.justifications[i].type = QGlyphJustification::JustifyNone;
2016 g.justifications[i].nKashidas = 0;
2017 g.justifications[i].space_18d6 = 0;
2019 justificationPoints.resize(nPoints+3);
2020 int justification = g.attributes[i].justification;
2022 switch(justification) {
2023 case HB_NoJustification:
2027 case HB_Arabic_Space :
2028 if (kashida_pos >= 0) {
2029 // qDebug("kashida position at %d in word", kashida_pos);
2030 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
2031 if (justificationPoints[nPoints].kashidaWidth > 0) {
2032 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
2033 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
2038 kashida_type = HB_Arabic_Normal;
2041 set(&justificationPoints[nPoints++], justification, g.mid(i), fontEngine(si));
2042 maxJustify = qMax(maxJustify, justification);
2044 case HB_Arabic_Normal :
2045 case HB_Arabic_Waw :
2046 case HB_Arabic_BaRa :
2047 case HB_Arabic_Alef :
2048 case HB_Arabic_HaaDal :
2049 case HB_Arabic_Seen :
2050 case HB_Arabic_Kashida :
2051 if (justification >= kashida_type) {
2053 kashida_type = justification;
2057 if (kashida_pos >= 0) {
2058 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
2059 if (justificationPoints[nPoints].kashidaWidth > 0) {
2060 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
2061 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
2067 QFixed need = line.width - line.textWidth;
2069 // line overflows already!
2070 const_cast<QScriptLine &>(line).justified = true;
2074 // qDebug("doing justification: textWidth=%x, requested=%x, maxJustify=%d", line.textWidth.value(), line.width.value(), maxJustify);
2075 // qDebug(" minKashida=%f, need=%f", minKashida.toReal(), need.toReal());
2077 // distribute in priority order
2078 if (maxJustify >= HB_Arabic_Normal) {
2079 while (need >= minKashida) {
2080 for (int type = maxJustify; need >= minKashida && type >= HB_Arabic_Normal; --type) {
2081 for (int i = 0; need >= minKashida && i < nPoints; ++i) {
2082 if (justificationPoints[i].type == type && justificationPoints[i].kashidaWidth <= need) {
2083 justificationPoints[i].glyph.justifications->nKashidas++;
2085 justificationPoints[i].glyph.justifications->space_18d6 += justificationPoints[i].kashidaWidth.value();
2086 need -= justificationPoints[i].kashidaWidth;
2087 // qDebug("adding kashida type %d with width %x, neednow %x", type, justificationPoints[i].kashidaWidth, need.value());
2093 Q_ASSERT(need >= 0);
2097 maxJustify = qMin(maxJustify, (int)HB_Space);
2098 for (int type = maxJustify; need != 0 && type > 0; --type) {
2100 for (int i = 0; i < nPoints; ++i) {
2101 if (justificationPoints[i].type == type)
2104 // qDebug("number of points for justification type %d: %d", type, n);
2110 for (int i = 0; i < nPoints; ++i) {
2111 if (justificationPoints[i].type == type) {
2112 QFixed add = need/n;
2113 // qDebug("adding %x to glyph %x", add.value(), justificationPoints[i].glyph->glyph);
2114 justificationPoints[i].glyph.justifications[0].space_18d6 = add.value();
2123 const_cast<QScriptLine &>(line).justified = true;
2126 void QScriptLine::setDefaultHeight(QTextEngine *eng)
2131 if (eng->block.docHandle() && eng->block.docHandle()->layout()) {
2132 f = eng->block.charFormat().font();
2133 // Make sure we get the right dpi on printers
2134 QPaintDevice *pdev = eng->block.docHandle()->layout()->paintDevice();
2137 e = f.d->engineForScript(QUnicodeTables::Common);
2139 e = eng->fnt.d->engineForScript(QUnicodeTables::Common);
2142 QFixed other_ascent = e->ascent();
2143 QFixed other_descent = e->descent();
2144 QFixed other_leading = e->leading();
2145 leading = qMax(leading + ascent, other_leading + other_ascent) - qMax(ascent, other_ascent);
2146 ascent = qMax(ascent, other_ascent);
2147 descent = qMax(descent, other_descent);
2150 QTextEngine::LayoutData::LayoutData()
2154 memory_on_stack = false;
2157 layoutState = LayoutEmpty;
2158 haveCharAttributes = false;
2160 available_glyphs = 0;
2163 QTextEngine::LayoutData::LayoutData(const QString &str, void **stack_memory, int _allocated)
2166 allocated = _allocated;
2168 int space_charAttributes = sizeof(HB_CharAttributes)*string.length()/sizeof(void*) + 1;
2169 int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2170 available_glyphs = ((int)allocated - space_charAttributes - space_logClusters)*(int)sizeof(void*)/(int)QGlyphLayout::spaceNeededForGlyphLayout(1);
2172 if (available_glyphs < str.length()) {
2173 // need to allocate on the heap
2176 memory_on_stack = false;
2180 memory_on_stack = true;
2181 memory = stack_memory;
2182 logClustersPtr = (unsigned short *)(memory + space_charAttributes);
2184 void *m = memory + space_charAttributes + space_logClusters;
2185 glyphLayout = QGlyphLayout(reinterpret_cast<char *>(m), str.length());
2186 glyphLayout.clear();
2187 memset(memory, 0, space_charAttributes*sizeof(void *));
2191 layoutState = LayoutEmpty;
2192 haveCharAttributes = false;
2195 QTextEngine::LayoutData::~LayoutData()
2197 if (!memory_on_stack)
2202 bool QTextEngine::LayoutData::reallocate(int totalGlyphs)
2204 Q_ASSERT(totalGlyphs >= glyphLayout.numGlyphs);
2205 if (memory_on_stack && available_glyphs >= totalGlyphs) {
2206 glyphLayout.grow(glyphLayout.data(), totalGlyphs);
2210 int space_charAttributes = sizeof(HB_CharAttributes)*string.length()/sizeof(void*) + 1;
2211 int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2212 int space_glyphs = QGlyphLayout::spaceNeededForGlyphLayout(totalGlyphs)/sizeof(void*) + 2;
2214 int newAllocated = space_charAttributes + space_glyphs + space_logClusters;
2215 // These values can be negative if the length of string/glyphs causes overflow,
2216 // we can't layout such a long string all at once, so return false here to
2217 // indicate there is a failure
2218 if (space_charAttributes < 0 || space_logClusters < 0 || space_glyphs < 0 || newAllocated < allocated) {
2219 layoutState = LayoutFailed;
2223 void **newMem = memory;
2224 newMem = (void **)::realloc(memory_on_stack ? 0 : memory, newAllocated*sizeof(void *));
2226 layoutState = LayoutFailed;
2229 if (memory_on_stack)
2230 memcpy(newMem, memory, allocated*sizeof(void *));
2232 memory_on_stack = false;
2235 m += space_charAttributes;
2236 logClustersPtr = (unsigned short *) m;
2237 m += space_logClusters;
2239 const int space_preGlyphLayout = space_charAttributes + space_logClusters;
2240 if (allocated < space_preGlyphLayout)
2241 memset(memory + allocated, 0, (space_preGlyphLayout - allocated)*sizeof(void *));
2243 glyphLayout.grow(reinterpret_cast<char *>(m), totalGlyphs);
2245 allocated = newAllocated;
2249 // grow to the new size, copying the existing data to the new layout
2250 void QGlyphLayout::grow(char *address, int totalGlyphs)
2252 QGlyphLayout oldLayout(address, numGlyphs);
2253 QGlyphLayout newLayout(address, totalGlyphs);
2256 // move the existing data
2257 memmove(newLayout.attributes, oldLayout.attributes, numGlyphs * sizeof(HB_GlyphAttributes));
2258 memmove(newLayout.justifications, oldLayout.justifications, numGlyphs * sizeof(QGlyphJustification));
2259 memmove(newLayout.advances_y, oldLayout.advances_y, numGlyphs * sizeof(QFixed));
2260 memmove(newLayout.advances_x, oldLayout.advances_x, numGlyphs * sizeof(QFixed));
2261 memmove(newLayout.glyphs, oldLayout.glyphs, numGlyphs * sizeof(HB_Glyph));
2264 // clear the new data
2265 newLayout.clear(numGlyphs);
2270 void QTextEngine::freeMemory()
2276 layoutData->used = 0;
2277 layoutData->hasBidi = false;
2278 layoutData->layoutState = LayoutEmpty;
2279 layoutData->haveCharAttributes = false;
2281 for (int i = 0; i < lines.size(); ++i) {
2282 lines[i].justified = 0;
2283 lines[i].gridfitted = 0;
2287 int QTextEngine::formatIndex(const QScriptItem *si) const
2289 if (specialData && !specialData->resolvedFormatIndices.isEmpty())
2290 return specialData->resolvedFormatIndices.at(si - &layoutData->items[0]);
2291 QTextDocumentPrivate *p = block.docHandle();
2294 int pos = si->position;
2295 if (specialData && si->position >= specialData->preeditPosition) {
2296 if (si->position < specialData->preeditPosition + specialData->preeditText.length())
2297 pos = qMax(specialData->preeditPosition - 1, 0);
2299 pos -= specialData->preeditText.length();
2301 QTextDocumentPrivate::FragmentIterator it = p->find(block.position() + pos);
2302 return it.value()->format;
2306 QTextCharFormat QTextEngine::format(const QScriptItem *si) const
2308 QTextCharFormat format;
2309 const QTextFormatCollection *formats = 0;
2310 if (block.docHandle()) {
2311 formats = this->formats();
2312 format = formats->charFormat(formatIndex(si));
2314 if (specialData && specialData->resolvedFormatIndices.isEmpty()) {
2315 int end = si->position + length(si);
2316 for (int i = 0; i < specialData->addFormats.size(); ++i) {
2317 const QTextLayout::FormatRange &r = specialData->addFormats.at(i);
2318 if (r.start <= si->position && r.start + r.length >= end) {
2319 if (!specialData->addFormatIndices.isEmpty())
2320 format.merge(formats->format(specialData->addFormatIndices.at(i)));
2322 format.merge(r.format);
2329 void QTextEngine::addRequiredBoundaries() const
2332 for (int i = 0; i < specialData->addFormats.size(); ++i) {
2333 const QTextLayout::FormatRange &r = specialData->addFormats.at(i);
2334 setBoundary(r.start);
2335 setBoundary(r.start + r.length);
2336 //qDebug("adding boundaries %d %d", r.start, r.start+r.length);
2341 bool QTextEngine::atWordSeparator(int position) const
2343 const QChar c = layoutData->string.at(position);
2344 switch (c.toLatin1()) {
2381 bool QTextEngine::atSpace(int position) const
2383 const QChar c = layoutData->string.at(position);
2385 return c == QLatin1Char(' ')
2387 || c == QChar::LineSeparator
2388 || c == QLatin1Char('\t')
2393 void QTextEngine::indexAdditionalFormats()
2395 if (!block.docHandle())
2398 specialData->addFormatIndices.resize(specialData->addFormats.count());
2399 QTextFormatCollection * const formats = this->formats();
2401 for (int i = 0; i < specialData->addFormats.count(); ++i) {
2402 specialData->addFormatIndices[i] = formats->indexForFormat(specialData->addFormats.at(i).format);
2403 specialData->addFormats[i].format = QTextCharFormat();
2407 /* These two helper functions are used to determine whether we need to insert a ZWJ character
2408 between the text that gets truncated and the ellipsis. This is important to get
2409 correctly shaped results for arabic text.
2411 static bool nextCharJoins(const QString &string, int pos)
2413 while (pos < string.length() && string.at(pos).category() == QChar::Mark_NonSpacing)
2415 if (pos == string.length())
2417 return string.at(pos).joining() != QChar::OtherJoining;
2420 static bool prevCharJoins(const QString &string, int pos)
2422 while (pos > 0 && string.at(pos - 1).category() == QChar::Mark_NonSpacing)
2426 return (string.at(pos - 1).joining() == QChar::Dual || string.at(pos - 1).joining() == QChar::Center);
2429 QString QTextEngine::elidedText(Qt::TextElideMode mode, const QFixed &width, int flags) const
2431 // qDebug() << "elidedText; available width" << width.toReal() << "text width:" << this->width(0, layoutData->string.length()).toReal();
2433 if (flags & Qt::TextShowMnemonic) {
2435 HB_CharAttributes *attributes = const_cast<HB_CharAttributes *>(this->attributes());
2438 for (int i = 0; i < layoutData->items.size(); ++i) {
2439 QScriptItem &si = layoutData->items[i];
2443 unsigned short *logClusters = this->logClusters(&si);
2444 QGlyphLayout glyphs = shapedGlyphs(&si);
2446 const int end = si.position + length(&si);
2447 for (int i = si.position; i < end - 1; ++i) {
2448 if (layoutData->string.at(i) == QLatin1Char('&')) {
2449 const int gp = logClusters[i - si.position];
2450 glyphs.attributes[gp].dontPrint = true;
2451 attributes[i + 1].charStop = false;
2452 attributes[i + 1].whiteSpace = false;
2453 attributes[i + 1].lineBreakType = HB_NoBreak;
2454 if (layoutData->string.at(i + 1) == QLatin1Char('&'))
2463 if (mode == Qt::ElideNone
2464 || this->width(0, layoutData->string.length()) <= width
2465 || layoutData->string.length() <= 1)
2466 return layoutData->string;
2468 QFixed ellipsisWidth;
2469 QString ellipsisText;
2471 QChar ellipsisChar(0x2026);
2473 QFontEngine *fe = fnt.d->engineForScript(QUnicodeTables::Common);
2475 QGlyphLayoutArray<1> ellipsisGlyph;
2477 QFontEngine *feForEllipsis = (fe->type() == QFontEngine::Multi)
2478 ? static_cast<QFontEngineMulti *>(fe)->engine(0)
2481 if (feForEllipsis->type() == QFontEngine::Mac)
2484 // the lookup can be really slow when we use XLFD fonts
2485 if (feForEllipsis->type() != QFontEngine::XLFD
2486 && feForEllipsis->canRender(&ellipsisChar, 1)) {
2488 feForEllipsis->stringToCMap(&ellipsisChar, 1, &ellipsisGlyph, &nGlyphs, 0);
2492 if (ellipsisGlyph.glyphs[0]) {
2493 ellipsisWidth = ellipsisGlyph.advances_x[0];
2494 ellipsisText = ellipsisChar;
2496 QString dotDotDot(QLatin1String("..."));
2498 QGlyphLayoutArray<3> glyphs;
2500 if (!fe->stringToCMap(dotDotDot.constData(), 3, &glyphs, &nGlyphs, 0))
2501 // should never happen...
2502 return layoutData->string;
2503 for (int i = 0; i < nGlyphs; ++i)
2504 ellipsisWidth += glyphs.advances_x[i];
2505 ellipsisText = dotDotDot;
2509 const QFixed availableWidth = width - ellipsisWidth;
2510 if (availableWidth < 0)
2513 const HB_CharAttributes *attributes = this->attributes();
2517 if (mode == Qt::ElideRight) {
2518 QFixed currentWidth;
2526 while (nextBreak < layoutData->string.length() && !attributes[nextBreak].charStop)
2529 currentWidth += this->width(pos, nextBreak - pos);
2530 } while (nextBreak < layoutData->string.length()
2531 && currentWidth < availableWidth);
2533 if (nextCharJoins(layoutData->string, pos))
2534 ellipsisText.prepend(QChar(0x200d) /* ZWJ */);
2536 return layoutData->string.left(pos) + ellipsisText;
2537 } else if (mode == Qt::ElideLeft) {
2538 QFixed currentWidth;
2540 int nextBreak = layoutData->string.length();
2546 while (nextBreak > 0 && !attributes[nextBreak].charStop)
2549 currentWidth += this->width(nextBreak, pos - nextBreak);
2550 } while (nextBreak > 0
2551 && currentWidth < availableWidth);
2553 if (prevCharJoins(layoutData->string, pos))
2554 ellipsisText.append(QChar(0x200d) /* ZWJ */);
2556 return ellipsisText + layoutData->string.mid(pos);
2557 } else if (mode == Qt::ElideMiddle) {
2562 int nextLeftBreak = 0;
2564 int rightPos = layoutData->string.length();
2565 int nextRightBreak = layoutData->string.length();
2568 leftPos = nextLeftBreak;
2569 rightPos = nextRightBreak;
2572 while (nextLeftBreak < layoutData->string.length() && !attributes[nextLeftBreak].charStop)
2576 while (nextRightBreak > 0 && !attributes[nextRightBreak].charStop)
2579 leftWidth += this->width(leftPos, nextLeftBreak - leftPos);
2580 rightWidth += this->width(nextRightBreak, rightPos - nextRightBreak);
2581 } while (nextLeftBreak < layoutData->string.length()
2582 && nextRightBreak > 0
2583 && leftWidth + rightWidth < availableWidth);
2585 if (nextCharJoins(layoutData->string, leftPos))
2586 ellipsisText.prepend(QChar(0x200d) /* ZWJ */);
2587 if (prevCharJoins(layoutData->string, rightPos))
2588 ellipsisText.append(QChar(0x200d) /* ZWJ */);
2590 return layoutData->string.left(leftPos) + ellipsisText + layoutData->string.mid(rightPos);
2593 return layoutData->string;
2596 void QTextEngine::setBoundary(int strPos) const
2598 if (strPos <= 0 || strPos >= layoutData->string.length())
2601 int itemToSplit = 0;
2602 while (itemToSplit < layoutData->items.size() && layoutData->items.at(itemToSplit).position <= strPos)
2605 if (layoutData->items.at(itemToSplit).position == strPos) {
2606 // already a split at the requested position
2609 splitItem(itemToSplit, strPos - layoutData->items.at(itemToSplit).position);
2612 void QTextEngine::splitItem(int item, int pos) const
2617 layoutData->items.insert(item + 1, layoutData->items[item]);
2618 QScriptItem &oldItem = layoutData->items[item];
2619 QScriptItem &newItem = layoutData->items[item+1];
2620 newItem.position += pos;
2622 if (oldItem.num_glyphs) {
2623 // already shaped, break glyphs aswell
2624 int breakGlyph = logClusters(&oldItem)[pos];
2626 newItem.num_glyphs = oldItem.num_glyphs - breakGlyph;
2627 oldItem.num_glyphs = breakGlyph;
2628 newItem.glyph_data_offset = oldItem.glyph_data_offset + breakGlyph;
2630 for (int i = 0; i < newItem.num_glyphs; i++)
2631 logClusters(&newItem)[i] -= breakGlyph;
2634 const QGlyphLayout g = shapedGlyphs(&oldItem);
2635 for(int j = 0; j < breakGlyph; ++j)
2636 w += g.advances_x[j];
2638 newItem.width = oldItem.width - w;
2642 // qDebug("split at position %d itempos=%d", pos, item);
2645 QFixed QTextEngine::calculateTabWidth(int item, QFixed x) const
2647 const QScriptItem &si = layoutData->items[item];
2649 QFixed dpiScale = 1;
2650 if (block.docHandle() && block.docHandle()->layout()) {
2651 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
2653 dpiScale = QFixed::fromReal(pdev->logicalDpiY() / qreal(qt_defaultDpiY()));
2655 dpiScale = QFixed::fromReal(fnt.d->dpi / qreal(qt_defaultDpiY()));
2658 QList<QTextOption::Tab> tabArray = option.tabs();
2659 if (!tabArray.isEmpty()) {
2660 if (isRightToLeft()) { // rebase the tabArray positions.
2661 QList<QTextOption::Tab> newTabs;
2662 QList<QTextOption::Tab>::Iterator iter = tabArray.begin();
2663 while(iter != tabArray.end()) {
2664 QTextOption::Tab tab = *iter;
2665 if (tab.type == QTextOption::LeftTab)
2666 tab.type = QTextOption::RightTab;
2667 else if (tab.type == QTextOption::RightTab)
2668 tab.type = QTextOption::LeftTab;
2674 for (int i = 0; i < tabArray.size(); ++i) {
2675 QFixed tab = QFixed::fromReal(tabArray[i].position) * dpiScale;
2676 if (tab > x) { // this is the tab we need.
2677 QTextOption::Tab tabSpec = tabArray[i];
2678 int tabSectionEnd = layoutData->string.count();
2679 if (tabSpec.type == QTextOption::RightTab || tabSpec.type == QTextOption::CenterTab) {
2680 // find next tab to calculate the width required.
2681 tab = QFixed::fromReal(tabSpec.position);
2682 for (int i=item + 1; i < layoutData->items.count(); i++) {
2683 const QScriptItem &item = layoutData->items[i];
2684 if (item.analysis.flags == QScriptAnalysis::TabOrObject) { // found it.
2685 tabSectionEnd = item.position;
2690 else if (tabSpec.type == QTextOption::DelimiterTab)
2691 // find delimitor character to calculate the width required
2692 tabSectionEnd = qMax(si.position, layoutData->string.indexOf(tabSpec.delimiter, si.position) + 1);
2694 if (tabSectionEnd > si.position) {
2696 // Calculate the length of text between this tab and the tabSectionEnd
2697 for (int i=item; i < layoutData->items.count(); i++) {
2698 QScriptItem &item = layoutData->items[i];
2699 if (item.position > tabSectionEnd || item.position <= si.position)
2701 shape(i); // first, lets make sure relevant text is already shaped
2702 QGlyphLayout glyphs = this->shapedGlyphs(&item);
2703 const int end = qMin(item.position + item.num_glyphs, tabSectionEnd) - item.position;
2704 for (int i=0; i < end; i++)
2705 length += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
2706 if (end + item.position == tabSectionEnd && tabSpec.type == QTextOption::DelimiterTab) // remove half of matching char
2707 length -= glyphs.advances_x[end] / 2 * !glyphs.attributes[end].dontPrint;
2710 switch (tabSpec.type) {
2711 case QTextOption::CenterTab:
2714 case QTextOption::DelimiterTab:
2716 case QTextOption::RightTab:
2717 tab = QFixed::fromReal(tabSpec.position) * dpiScale - length;
2718 if (tab < 0) // default to tab taking no space
2721 case QTextOption::LeftTab:
2729 QFixed tab = QFixed::fromReal(option.tabStop());
2731 tab = 80; // default
2733 QFixed nextTabPos = ((x / tab).truncate() + 1) * tab;
2734 QFixed tabWidth = nextTabPos - x;
2739 void QTextEngine::resolveAdditionalFormats() const
2741 if (!specialData || specialData->addFormats.isEmpty()
2742 || !block.docHandle()
2743 || !specialData->resolvedFormatIndices.isEmpty())
2746 QTextFormatCollection *collection = this->formats();
2748 specialData->resolvedFormatIndices.clear();
2749 QVector<int> indices(layoutData->items.count());
2750 for (int i = 0; i < layoutData->items.count(); ++i) {
2751 QTextCharFormat f = format(&layoutData->items.at(i));
2752 indices[i] = collection->indexForFormat(f);
2754 specialData->resolvedFormatIndices = indices;
2757 QFixed QTextEngine::leadingSpaceWidth(const QScriptLine &line)
2759 if (!line.hasTrailingSpaces
2760 || (option.flags() & QTextOption::IncludeTrailingSpaces)
2761 || !isRightToLeft())
2764 int pos = line.length;
2765 const HB_CharAttributes *attributes = this->attributes();
2768 while (pos > 0 && attributes[line.from + pos - 1].whiteSpace)
2770 return width(line.from + pos, line.length - pos);
2773 QFixed QTextEngine::alignLine(const QScriptLine &line)
2777 // if width is QFIXED_MAX that means we used setNumColumns() and that implicitly makes this line left aligned.
2778 if (!line.justified && line.width != QFIXED_MAX) {
2779 int align = option.alignment();
2780 if (align & Qt::AlignLeft)
2781 x -= leadingSpaceWidth(line);
2782 if (align & Qt::AlignJustify && isRightToLeft())
2783 align = Qt::AlignRight;
2784 if (align & Qt::AlignRight)
2785 x = line.width - (line.textAdvance + leadingSpaceWidth(line));
2786 else if (align & Qt::AlignHCenter)
2787 x = (line.width - (line.textAdvance + leadingSpaceWidth(line)))/2;
2792 QFixed QTextEngine::offsetInLigature(const QScriptItem *si, int pos, int max, int glyph_pos)
2794 unsigned short *logClusters = this->logClusters(si);
2795 const QGlyphLayout &glyphs = shapedGlyphs(si);
2797 int offsetInCluster = 0;
2798 for (int i = pos - 1; i >= 0; i--) {
2799 if (logClusters[i] == glyph_pos)
2805 // in the case that the offset is inside a (multi-character) glyph,
2806 // interpolate the position.
2807 if (offsetInCluster > 0) {
2808 int clusterLength = 0;
2809 for (int i = pos - offsetInCluster; i < max; i++) {
2810 if (logClusters[i] == glyph_pos)
2816 return glyphs.advances_x[glyph_pos] * offsetInCluster / clusterLength;
2822 int QTextEngine::previousLogicalPosition(int oldPos) const
2824 const HB_CharAttributes *attrs = attributes();
2825 if (!attrs || oldPos < 0)
2831 while (oldPos && !attrs[oldPos].charStop)
2836 int QTextEngine::nextLogicalPosition(int oldPos) const
2838 const HB_CharAttributes *attrs = attributes();
2839 int len = block.isValid() ? block.length() - 1
2840 : layoutData->string.length();
2841 Q_ASSERT(len <= layoutData->string.length());
2842 if (!attrs || oldPos < 0 || oldPos >= len)
2846 while (oldPos < len && !attrs[oldPos].charStop)
2851 int QTextEngine::lineNumberForTextPosition(int pos)
2855 if (pos == layoutData->string.length() && lines.size())
2856 return lines.size() - 1;
2857 for (int i = 0; i < lines.size(); ++i) {
2858 const QScriptLine& line = lines[i];
2859 if (line.from + line.length > pos)
2865 void QTextEngine::insertionPointsForLine(int lineNum, QVector<int> &insertionPoints)
2867 QTextLineItemIterator iterator(this, lineNum);
2868 bool rtl = isRightToLeft();
2869 bool lastLine = lineNum >= lines.size() - 1;
2871 while (!iterator.atEnd()) {
2873 const QScriptItem *si = &layoutData->items[iterator.item];
2874 if (si->analysis.bidiLevel % 2) {
2875 int i = iterator.itemEnd - 1, min = iterator.itemStart;
2876 if (lastLine && (rtl ? iterator.atBeginning() : iterator.atEnd()))
2878 for (; i >= min; i--)
2879 insertionPoints.push_back(i);
2881 int i = iterator.itemStart, max = iterator.itemEnd;
2882 if (lastLine && (rtl ? iterator.atBeginning() : iterator.atEnd()))
2884 for (; i < max; i++)
2885 insertionPoints.push_back(i);
2890 int QTextEngine::endOfLine(int lineNum)
2892 QVector<int> insertionPoints;
2893 insertionPointsForLine(lineNum, insertionPoints);
2895 if (insertionPoints.size() > 0)
2896 return insertionPoints.last();
2900 int QTextEngine::beginningOfLine(int lineNum)
2902 QVector<int> insertionPoints;
2903 insertionPointsForLine(lineNum, insertionPoints);
2905 if (insertionPoints.size() > 0)
2906 return insertionPoints.first();
2910 int QTextEngine::positionAfterVisualMovement(int pos, QTextCursor::MoveOperation op)
2915 bool moveRight = (op == QTextCursor::Right);
2916 bool alignRight = isRightToLeft();
2917 if (!layoutData->hasBidi)
2918 return moveRight ^ alignRight ? nextLogicalPosition(pos) : previousLogicalPosition(pos);
2920 int lineNum = lineNumberForTextPosition(pos);
2921 Q_ASSERT(lineNum >= 0);
2923 QVector<int> insertionPoints;
2924 insertionPointsForLine(lineNum, insertionPoints);
2925 int i, max = insertionPoints.size();
2926 for (i = 0; i < max; i++)
2927 if (pos == insertionPoints[i]) {
2930 return insertionPoints[i + 1];
2933 return insertionPoints[i - 1];
2936 if (moveRight ^ alignRight) {
2937 if (lineNum + 1 < lines.size())
2938 return alignRight ? endOfLine(lineNum + 1) : beginningOfLine(lineNum + 1);
2942 return alignRight ? beginningOfLine(lineNum - 1) : endOfLine(lineNum - 1);
2949 QStackTextEngine::QStackTextEngine(const QString &string, const QFont &f)
2950 : QTextEngine(string, f),
2951 _layoutData(string, _memory, MemSize)
2954 layoutData = &_layoutData;
2957 QTextItemInt::QTextItemInt(const QScriptItem &si, QFont *font, const QTextCharFormat &format)
2958 : justified(false), underlineStyle(QTextCharFormat::NoUnderline), charFormat(format),
2959 num_chars(0), chars(0), logClusters(0), f(0), fontEngine(0)
2961 // explicitly initialize flags so that initFontAttributes can be called
2962 // multiple times on the same TextItem
2964 if (si.analysis.bidiLevel %2)
2965 flags |= QTextItem::RightToLeft;
2967 descent = si.descent;
2969 fontEngine = f->d->engineForScript(si.analysis.script);
2970 Q_ASSERT(fontEngine);
2972 if (format.hasProperty(QTextFormat::TextUnderlineStyle)) {
2973 underlineStyle = format.underlineStyle();
2974 } else if (format.boolProperty(QTextFormat::FontUnderline)
2975 || f->d->underline) {
2976 underlineStyle = QTextCharFormat::SingleUnderline;
2980 if (underlineStyle == QTextCharFormat::SingleUnderline)
2981 flags |= QTextItem::Underline;
2983 if (f->d->overline || format.fontOverline())
2984 flags |= QTextItem::Overline;
2985 if (f->d->strikeOut || format.fontStrikeOut())
2986 flags |= QTextItem::StrikeOut;
2989 QTextItemInt::QTextItemInt(const QGlyphLayout &g, QFont *font, const QChar *chars_, int numChars, QFontEngine *fe)
2990 : flags(0), justified(false), underlineStyle(QTextCharFormat::NoUnderline),
2991 num_chars(numChars), chars(chars_), logClusters(0), f(font), glyphs(g), fontEngine(fe)
2995 QTextItemInt QTextItemInt::midItem(QFontEngine *fontEngine, int firstGlyphIndex, int numGlyphs) const
2997 QTextItemInt ti = *this;
2998 const int end = firstGlyphIndex + numGlyphs;
2999 ti.glyphs = glyphs.mid(firstGlyphIndex, numGlyphs);
3000 ti.fontEngine = fontEngine;
3002 if (logClusters && chars) {
3003 const int logClusterOffset = logClusters[0];
3004 while (logClusters[ti.chars - chars] - logClusterOffset < firstGlyphIndex)
3007 ti.logClusters += (ti.chars - chars);
3010 int char_start = ti.chars - chars;
3011 while (char_start + ti.num_chars < num_chars && ti.logClusters[ti.num_chars] - logClusterOffset < end)
3018 QTransform qt_true_matrix(qreal w, qreal h, QTransform x)
3020 QRectF rect = x.mapRect(QRectF(0, 0, w, h));
3021 return x * QTransform::fromTranslate(-rect.x(), -rect.y());
3025 glyph_metrics_t glyph_metrics_t::transformed(const QTransform &matrix) const
3027 if (matrix.type() < QTransform::TxTranslate)
3030 glyph_metrics_t m = *this;
3032 qreal w = width.toReal();
3033 qreal h = height.toReal();
3034 QTransform xform = qt_true_matrix(w, h, matrix);
3036 QRectF rect(0, 0, w, h);
3037 rect = xform.mapRect(rect);
3038 m.width = QFixed::fromReal(rect.width());
3039 m.height = QFixed::fromReal(rect.height());
3041 QLineF l = xform.map(QLineF(x.toReal(), y.toReal(), xoff.toReal(), yoff.toReal()));
3043 m.x = QFixed::fromReal(l.x1());
3044 m.y = QFixed::fromReal(l.y1());
3046 // The offset is relative to the baseline which is why we use dx/dy of the line
3047 m.xoff = QFixed::fromReal(l.dx());
3048 m.yoff = QFixed::fromReal(l.dy());
3053 QTextLineItemIterator::QTextLineItemIterator(QTextEngine *_eng, int _lineNum, const QPointF &pos,
3054 const QTextLayout::FormatRange *_selection)
3056 line(eng->lines[_lineNum]),
3059 lineEnd(line.from + line.length),
3060 firstItem(eng->findItem(line.from)),
3061 lastItem(eng->findItem(lineEnd - 1)),
3062 nItems((firstItem >= 0 && lastItem >= firstItem)? (lastItem-firstItem+1) : 0),
3065 visualOrder(nItems),
3067 selection(_selection)
3069 pos_x = x = QFixed::fromReal(pos.x());
3073 x += eng->alignLine(line);
3075 for (int i = 0; i < nItems; ++i)
3076 levels[i] = eng->layoutData->items[i+firstItem].analysis.bidiLevel;
3077 QTextEngine::bidiReorder(nItems, levels.data(), visualOrder.data());
3079 eng->shapeLine(line);
3082 QScriptItem &QTextLineItemIterator::next()
3087 item = visualOrder[logicalItem] + firstItem;
3088 itemLength = eng->length(item);
3089 si = &eng->layoutData->items[item];
3090 if (!si->num_glyphs)
3093 if (si->analysis.flags >= QScriptAnalysis::TabOrObject) {
3094 itemWidth = si->width;
3098 unsigned short *logClusters = eng->logClusters(si);
3099 QGlyphLayout glyphs = eng->shapedGlyphs(si);
3101 itemStart = qMax(line.from, si->position);
3102 glyphsStart = logClusters[itemStart - si->position];
3103 if (lineEnd < si->position + itemLength) {
3105 glyphsEnd = logClusters[itemEnd-si->position];
3107 itemEnd = si->position + itemLength;
3108 glyphsEnd = si->num_glyphs;
3110 // show soft-hyphen at line-break
3111 if (si->position + itemLength >= lineEnd
3112 && eng->layoutData->string.at(lineEnd - 1) == 0x00ad)
3113 glyphs.attributes[glyphsEnd - 1].dontPrint = false;
3116 for (int g = glyphsStart; g < glyphsEnd; ++g)
3117 itemWidth += glyphs.effectiveAdvance(g);
3122 bool QTextLineItemIterator::getSelectionBounds(QFixed *selectionX, QFixed *selectionWidth) const
3124 *selectionX = *selectionWidth = 0;
3129 if (si->analysis.flags >= QScriptAnalysis::TabOrObject) {
3130 if (si->position >= selection->start + selection->length
3131 || si->position + itemLength <= selection->start)
3135 *selectionWidth = itemWidth;
3137 unsigned short *logClusters = eng->logClusters(si);
3138 QGlyphLayout glyphs = eng->shapedGlyphs(si);
3140 int from = qMax(itemStart, selection->start) - si->position;
3141 int to = qMin(itemEnd, selection->start + selection->length) - si->position;
3145 int start_glyph = logClusters[from];
3146 int end_glyph = (to == eng->length(item)) ? si->num_glyphs : logClusters[to];
3149 if (si->analysis.bidiLevel %2) {
3150 for (int g = glyphsEnd - 1; g >= end_glyph; --g)
3151 soff += glyphs.effectiveAdvance(g);
3152 for (int g = end_glyph - 1; g >= start_glyph; --g)
3153 swidth += glyphs.effectiveAdvance(g);
3155 for (int g = glyphsStart; g < start_glyph; ++g)
3156 soff += glyphs.effectiveAdvance(g);
3157 for (int g = start_glyph; g < end_glyph; ++g)
3158 swidth += glyphs.effectiveAdvance(g);
3161 // If the starting character is in the middle of a ligature,
3162 // selection should only contain the right part of that ligature
3163 // glyph, so we need to get the width of the left part here and
3164 // add it to *selectionX
3165 QFixed leftOffsetInLigature = eng->offsetInLigature(si, from, to, start_glyph);
3166 *selectionX = x + soff + leftOffsetInLigature;
3167 *selectionWidth = swidth - leftOffsetInLigature;
3168 // If the ending character is also part of a ligature, swidth does
3169 // not contain that part yet, we also need to find out the width of
3171 *selectionWidth += eng->offsetInLigature(si, to, eng->length(item), end_glyph);