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;
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) && defined(Q_WS_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 si.ascent = qMax(actualFontEngine->ascent(), si.ascent);
1278 si.descent = qMax(actualFontEngine->descent(), si.descent);
1279 si.leading = qMax(actualFontEngine->leading(), si.leading);
1281 shaper_item.font = actualFontEngine->harfbuzzFont();
1282 shaper_item.face = actualFontEngine->harfbuzzFace();
1284 shaper_item.glyphIndicesPresent = true;
1286 remaining_glyphs -= shaper_item.initialGlyphCount;
1289 if (! ensureSpace(glyph_pos + shaper_item.num_glyphs + remaining_glyphs)) {
1290 if (hasCaseChange(si))
1291 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1295 const QGlyphLayout g = availableGlyphs(&si).mid(glyph_pos);
1296 if (shaper_item.num_glyphs > shaper_item.item.length)
1297 moveGlyphData(g.mid(shaper_item.num_glyphs), g.mid(shaper_item.initialGlyphCount), remaining_glyphs);
1299 shaper_item.glyphs = g.glyphs;
1300 shaper_item.attributes = g.attributes;
1301 shaper_item.advances = reinterpret_cast<HB_Fixed *>(g.advances_x);
1302 shaper_item.offsets = reinterpret_cast<HB_FixedPoint *>(g.offsets);
1304 if (shaper_item.glyphIndicesPresent) {
1305 for (hb_uint32 i = 0; i < shaper_item.initialGlyphCount; ++i)
1306 shaper_item.glyphs[i] &= 0x00ffffff;
1309 shaper_item.log_clusters = logClusters(&si) + shaper_item.item.pos - entire_shaper_item.item.pos;
1311 // qDebug(" .. num_glyphs=%d, used=%d, item.num_glyphs=%d", num_glyphs, used, shaper_item.num_glyphs);
1312 } while (!qShapeItem(&shaper_item)); // this does the actual shaping via harfbuzz.
1314 QGlyphLayout g = availableGlyphs(&si).mid(glyph_pos, shaper_item.num_glyphs);
1315 moveGlyphData(g.mid(shaper_item.num_glyphs), g.mid(shaper_item.initialGlyphCount), remaining_glyphs);
1317 for (hb_uint32 i = 0; i < shaper_item.num_glyphs; ++i)
1318 g.glyphs[i] = g.glyphs[i] | (engineIdx << 24);
1320 for (hb_uint32 i = 0; i < shaper_item.item.length; ++i)
1321 shaper_item.log_clusters[i] += glyph_pos;
1323 if (kerningEnabled && !shaper_item.kerning_applied)
1324 font->doKerning(&g, option.useDesignMetrics() ? QFlag(QTextEngine::DesignMetrics) : QFlag(0));
1326 glyph_pos += shaper_item.num_glyphs;
1329 // qDebug(" -> item: script=%d num_glyphs=%d", shaper_item.script, shaper_item.num_glyphs);
1330 si.num_glyphs = glyph_pos;
1332 layoutData->used += si.num_glyphs;
1334 if (hasCaseChange(si) && entire_shaper_item.string != upperCased)
1335 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1338 static void init(QTextEngine *e)
1340 e->ignoreBidi = false;
1341 e->cacheGlyphs = false;
1342 e->forceJustification = false;
1343 e->visualMovement = false;
1350 e->underlinePositions = 0;
1352 e->stackEngine = false;
1355 QTextEngine::QTextEngine()
1360 QTextEngine::QTextEngine(const QString &str, const QFont &f)
1367 QTextEngine::~QTextEngine()
1374 const HB_CharAttributes *QTextEngine::attributes() const
1376 if (layoutData && layoutData->haveCharAttributes)
1377 return (HB_CharAttributes *) layoutData->memory;
1380 if (! ensureSpace(layoutData->string.length()))
1383 QVarLengthArray<HB_ScriptItem> hbScriptItems(layoutData->items.size());
1385 for (int i = 0; i < layoutData->items.size(); ++i) {
1386 const QScriptItem &si = layoutData->items[i];
1387 hbScriptItems[i].pos = si.position;
1388 hbScriptItems[i].length = length(i);
1389 hbScriptItems[i].bidiLevel = si.analysis.bidiLevel;
1390 hbScriptItems[i].script = (HB_Script)si.analysis.script;
1393 qGetCharAttributes(reinterpret_cast<const HB_UChar16 *>(layoutData->string.constData()),
1394 layoutData->string.length(),
1395 hbScriptItems.data(), hbScriptItems.size(),
1396 (HB_CharAttributes *)layoutData->memory);
1399 layoutData->haveCharAttributes = true;
1400 return (HB_CharAttributes *) layoutData->memory;
1403 void QTextEngine::shape(int item) const
1405 if (layoutData->items[item].analysis.flags == QScriptAnalysis::Object) {
1407 if (block.docHandle()) {
1408 QTextFormat format = formats()->format(formatIndex(&layoutData->items[item]));
1409 docLayout()->resizeInlineObject(QTextInlineObject(item, const_cast<QTextEngine *>(this)),
1410 layoutData->items[item].position + block.position(), format);
1412 } else if (layoutData->items[item].analysis.flags == QScriptAnalysis::Tab) {
1413 // set up at least the ascent/descent/leading of the script item for the tab
1414 fontEngine(layoutData->items[item],
1415 &layoutData->items[item].ascent,
1416 &layoutData->items[item].descent,
1417 &layoutData->items[item].leading);
1423 static inline void releaseCachedFontEngine(QFontEngine *fontEngine)
1426 fontEngine->ref.deref();
1427 if (fontEngine->cache_count == 0 && fontEngine->ref == 0)
1432 void QTextEngine::invalidate()
1438 specialData->resolvedFormatIndices.clear();
1440 releaseCachedFontEngine(feCache.prevFontEngine);
1441 releaseCachedFontEngine(feCache.prevScaledFontEngine);
1445 void QTextEngine::clearLineData()
1450 void QTextEngine::validate() const
1454 layoutData = new LayoutData();
1455 if (block.docHandle()) {
1456 layoutData->string = block.text();
1457 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators)
1458 layoutData->string += QLatin1Char(block.next().isValid() ? 0xb6 : 0x20);
1460 layoutData->string = text;
1462 if (specialData && specialData->preeditPosition != -1)
1463 layoutData->string.insert(specialData->preeditPosition, specialData->preeditText);
1466 void QTextEngine::itemize() const
1469 if (layoutData->items.size())
1472 int length = layoutData->string.length();
1475 #if defined(Q_WS_MAC) && !defined(QT_MAC_USE_COCOA)
1476 // ATSUI requires RTL flags to correctly identify the character stops.
1477 bool ignore = false;
1479 bool ignore = ignoreBidi;
1482 bool rtl = isRightToLeft();
1484 if (!ignore && !rtl) {
1486 const QChar *start = layoutData->string.unicode();
1487 const QChar * const end = start + length;
1488 while (start < end) {
1489 if (start->unicode() >= 0x590) {
1497 QVarLengthArray<QScriptAnalysis, 4096> scriptAnalysis(length);
1498 QScriptAnalysis *analysis = scriptAnalysis.data();
1500 QBidiControl control(rtl);
1503 memset(analysis, 0, length*sizeof(QScriptAnalysis));
1504 if (option.textDirection() == Qt::RightToLeft) {
1505 for (int i = 0; i < length; ++i)
1506 analysis[i].bidiLevel = 1;
1507 layoutData->hasBidi = true;
1510 layoutData->hasBidi = bidiItemize(const_cast<QTextEngine *>(this), analysis, control);
1513 const ushort *uc = reinterpret_cast<const ushort *>(layoutData->string.unicode());
1514 const ushort *e = uc + length;
1515 int lastScript = QUnicodeTables::Common;
1517 int script = QUnicodeTables::script(*uc);
1518 if (script == QUnicodeTables::Inherited)
1519 script = lastScript;
1520 analysis->flags = QScriptAnalysis::None;
1521 if (*uc == QChar::ObjectReplacementCharacter) {
1522 if (analysis->bidiLevel % 2)
1523 --analysis->bidiLevel;
1524 analysis->script = QUnicodeTables::Common;
1525 analysis->flags = QScriptAnalysis::Object;
1526 } else if (*uc == QChar::LineSeparator) {
1527 if (analysis->bidiLevel % 2)
1528 --analysis->bidiLevel;
1529 analysis->script = QUnicodeTables::Common;
1530 analysis->flags = QScriptAnalysis::LineOrParagraphSeparator;
1531 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators)
1532 *const_cast<ushort*>(uc) = 0x21B5; // visual line separator
1533 } else if (*uc == 9) {
1534 analysis->script = QUnicodeTables::Common;
1535 analysis->flags = QScriptAnalysis::Tab;
1536 analysis->bidiLevel = control.baseLevel();
1537 } else if ((*uc == 32 || *uc == QChar::Nbsp)
1538 && (option.flags() & QTextOption::ShowTabsAndSpaces)) {
1539 analysis->script = QUnicodeTables::Common;
1540 analysis->flags = QScriptAnalysis::Space;
1541 analysis->bidiLevel = control.baseLevel();
1543 analysis->script = script;
1545 lastScript = analysis->script;
1549 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators) {
1550 (analysis-1)->flags = QScriptAnalysis::LineOrParagraphSeparator; // to exclude it from width
1553 Itemizer itemizer(layoutData->string, scriptAnalysis.data(), layoutData->items);
1555 const QTextDocumentPrivate *p = block.docHandle();
1557 SpecialData *s = specialData;
1559 QTextDocumentPrivate::FragmentIterator it = p->find(block.position());
1560 QTextDocumentPrivate::FragmentIterator end = p->find(block.position() + block.length() - 1); // -1 to omit the block separator char
1561 int format = it.value()->format;
1563 int prevPosition = 0;
1564 int position = prevPosition;
1566 const QTextFragmentData * const frag = it.value();
1567 if (it == end || format != frag->format) {
1568 if (s && position >= s->preeditPosition) {
1569 position += s->preeditText.length();
1572 Q_ASSERT(position <= length);
1573 itemizer.generate(prevPosition, position - prevPosition,
1574 formats()->charFormat(format).fontCapitalization());
1576 if (position < length)
1577 itemizer.generate(position, length - position,
1578 formats()->charFormat(format).fontCapitalization());
1581 format = frag->format;
1582 prevPosition = position;
1584 position += frag->size_array[0];
1588 itemizer.generate(0, length, static_cast<QFont::Capitalization> (fnt.d->capital));
1591 addRequiredBoundaries();
1592 resolveAdditionalFormats();
1595 bool QTextEngine::isRightToLeft() const
1597 switch (option.textDirection()) {
1598 case Qt::LeftToRight:
1600 case Qt::RightToLeft:
1607 // this places the cursor in the right position depending on the keyboard layout
1608 if (layoutData->string.isEmpty())
1609 return QApplication::keyboardInputDirection() == Qt::RightToLeft;
1610 return layoutData->string.isRightToLeft();
1614 int QTextEngine::findItem(int strPos) const
1618 int right = layoutData->items.size()-1;
1619 while(left <= right) {
1620 int middle = ((right-left)/2)+left;
1621 if (strPos > layoutData->items[middle].position)
1623 else if(strPos < layoutData->items[middle].position)
1632 QFixed QTextEngine::width(int from, int len) const
1638 // qDebug("QTextEngine::width(from = %d, len = %d), numItems=%d, strleng=%d", from, len, items.size(), string.length());
1639 for (int i = 0; i < layoutData->items.size(); i++) {
1640 const QScriptItem *si = layoutData->items.constData() + i;
1641 int pos = si->position;
1642 int ilen = length(i);
1643 // qDebug("item %d: from %d len %d", i, pos, ilen);
1644 if (pos >= from + len)
1646 if (pos + ilen > from) {
1647 if (!si->num_glyphs)
1650 if (si->analysis.flags == QScriptAnalysis::Object) {
1653 } else if (si->analysis.flags == QScriptAnalysis::Tab) {
1654 w += calculateTabWidth(i, w);
1659 QGlyphLayout glyphs = shapedGlyphs(si);
1660 unsigned short *logClusters = this->logClusters(si);
1662 // fprintf(stderr, " logclusters:");
1663 // for (int k = 0; k < ilen; k++)
1664 // fprintf(stderr, " %d", logClusters[k]);
1665 // fprintf(stderr, "\n");
1666 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1667 int charFrom = from - pos;
1670 int glyphStart = logClusters[charFrom];
1671 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1672 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1674 if (charFrom < ilen) {
1675 glyphStart = logClusters[charFrom];
1676 int charEnd = from + len - 1 - pos;
1677 if (charEnd >= ilen)
1679 int glyphEnd = logClusters[charEnd];
1680 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1682 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1684 // qDebug("char: start=%d end=%d / glyph: start = %d, end = %d", charFrom, charEnd, glyphStart, glyphEnd);
1685 for (int i = glyphStart; i < glyphEnd; i++)
1686 w += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
1690 // qDebug(" --> w= %d ", w);
1694 glyph_metrics_t QTextEngine::boundingBox(int from, int len) const
1700 for (int i = 0; i < layoutData->items.size(); i++) {
1701 const QScriptItem *si = layoutData->items.constData() + i;
1703 int pos = si->position;
1704 int ilen = length(i);
1705 if (pos > from + len)
1707 if (pos + ilen > from) {
1708 if (!si->num_glyphs)
1711 if (si->analysis.flags == QScriptAnalysis::Object) {
1712 gm.width += si->width;
1714 } else if (si->analysis.flags == QScriptAnalysis::Tab) {
1715 gm.width += calculateTabWidth(i, gm.width);
1719 unsigned short *logClusters = this->logClusters(si);
1720 QGlyphLayout glyphs = shapedGlyphs(si);
1722 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1723 int charFrom = from - pos;
1726 int glyphStart = logClusters[charFrom];
1727 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1728 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1730 if (charFrom < ilen) {
1731 QFontEngine *fe = fontEngine(*si);
1732 glyphStart = logClusters[charFrom];
1733 int charEnd = from + len - 1 - pos;
1734 if (charEnd >= ilen)
1736 int glyphEnd = logClusters[charEnd];
1737 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1739 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1740 if (glyphStart <= glyphEnd ) {
1741 glyph_metrics_t m = fe->boundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
1742 gm.x = qMin(gm.x, m.x + gm.xoff);
1743 gm.y = qMin(gm.y, m.y + gm.yoff);
1744 gm.width = qMax(gm.width, m.width+gm.xoff);
1745 gm.height = qMax(gm.height, m.height+gm.yoff);
1755 glyph_metrics_t QTextEngine::tightBoundingBox(int from, int len) const
1761 for (int i = 0; i < layoutData->items.size(); i++) {
1762 const QScriptItem *si = layoutData->items.constData() + i;
1763 int pos = si->position;
1764 int ilen = length(i);
1765 if (pos > from + len)
1767 if (pos + len > from) {
1768 if (!si->num_glyphs)
1770 unsigned short *logClusters = this->logClusters(si);
1771 QGlyphLayout glyphs = shapedGlyphs(si);
1773 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1774 int charFrom = from - pos;
1777 int glyphStart = logClusters[charFrom];
1778 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1779 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1781 if (charFrom < ilen) {
1782 glyphStart = logClusters[charFrom];
1783 int charEnd = from + len - 1 - pos;
1784 if (charEnd >= ilen)
1786 int glyphEnd = logClusters[charEnd];
1787 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1789 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1790 if (glyphStart <= glyphEnd ) {
1791 QFontEngine *fe = fontEngine(*si);
1792 glyph_metrics_t m = fe->tightBoundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
1793 gm.x = qMin(gm.x, m.x + gm.xoff);
1794 gm.y = qMin(gm.y, m.y + gm.yoff);
1795 gm.width = qMax(gm.width, m.width+gm.xoff);
1796 gm.height = qMax(gm.height, m.height+gm.yoff);
1806 QFont QTextEngine::font(const QScriptItem &si) const
1810 QTextCharFormat f = format(&si);
1813 if (block.docHandle() && block.docHandle()->layout()) {
1814 // Make sure we get the right dpi on printers
1815 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
1817 font = QFont(font, pdev);
1819 font = font.resolve(fnt);
1821 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
1822 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
1823 if (font.pointSize() != -1)
1824 font.setPointSize((font.pointSize() * 2) / 3);
1826 font.setPixelSize((font.pixelSize() * 2) / 3);
1830 if (si.analysis.flags == QScriptAnalysis::SmallCaps)
1831 font = font.d->smallCapsFont();
1836 QTextEngine::FontEngineCache::FontEngineCache()
1841 //we cache the previous results of this function, as calling it numerous times with the same effective
1842 //input is common (and hard to cache at a higher level)
1843 QFontEngine *QTextEngine::fontEngine(const QScriptItem &si, QFixed *ascent, QFixed *descent, QFixed *leading) const
1845 QFontEngine *engine = 0;
1846 QFontEngine *scaledEngine = 0;
1847 int script = si.analysis.script;
1851 if (feCache.prevFontEngine && feCache.prevPosition == si.position && feCache.prevLength == length(&si) && feCache.prevScript == script) {
1852 engine = feCache.prevFontEngine;
1853 scaledEngine = feCache.prevScaledFontEngine;
1855 QTextCharFormat f = format(&si);
1858 if (block.docHandle() && block.docHandle()->layout()) {
1859 // Make sure we get the right dpi on printers
1860 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
1862 font = QFont(font, pdev);
1864 font = font.resolve(fnt);
1866 engine = font.d->engineForScript(script);
1867 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
1868 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
1869 if (font.pointSize() != -1)
1870 font.setPointSize((font.pointSize() * 2) / 3);
1872 font.setPixelSize((font.pixelSize() * 2) / 3);
1873 scaledEngine = font.d->engineForScript(script);
1875 feCache.prevFontEngine = engine;
1878 feCache.prevScaledFontEngine = scaledEngine;
1880 scaledEngine->ref.ref();
1881 feCache.prevScript = script;
1882 feCache.prevPosition = si.position;
1883 feCache.prevLength = length(&si);
1886 if (feCache.prevFontEngine && feCache.prevScript == script && feCache.prevPosition == -1)
1887 engine = feCache.prevFontEngine;
1889 engine = font.d->engineForScript(script);
1890 feCache.prevFontEngine = engine;
1893 feCache.prevScript = script;
1894 feCache.prevPosition = -1;
1895 feCache.prevLength = -1;
1896 feCache.prevScaledFontEngine = 0;
1900 if (si.analysis.flags == QScriptAnalysis::SmallCaps) {
1901 QFontPrivate *p = font.d->smallCapsFontPrivate();
1902 scaledEngine = p->engineForScript(script);
1906 *ascent = engine->ascent();
1907 *descent = engine->descent();
1908 *leading = engine->leading();
1912 return scaledEngine;
1916 struct QJustificationPoint {
1918 QFixed kashidaWidth;
1920 QFontEngine *fontEngine;
1923 Q_DECLARE_TYPEINFO(QJustificationPoint, Q_PRIMITIVE_TYPE);
1925 static void set(QJustificationPoint *point, int type, const QGlyphLayout &glyph, QFontEngine *fe)
1928 point->glyph = glyph;
1929 point->fontEngine = fe;
1931 if (type >= HB_Arabic_Normal) {
1932 QChar ch(0x640); // Kashida character
1933 QGlyphLayoutArray<8> glyphs;
1935 fe->stringToCMap(&ch, 1, &glyphs, &nglyphs, 0);
1936 if (glyphs.glyphs[0] && glyphs.advances_x[0] != 0) {
1937 point->kashidaWidth = glyphs.advances_x[0];
1939 point->type = HB_NoJustification;
1940 point->kashidaWidth = 0;
1946 void QTextEngine::justify(const QScriptLine &line)
1948 // qDebug("justify: line.gridfitted = %d, line.justified=%d", line.gridfitted, line.justified);
1949 if (line.gridfitted && line.justified)
1952 if (!line.gridfitted) {
1953 // redo layout in device metrics, then adjust
1954 const_cast<QScriptLine &>(line).gridfitted = true;
1957 if ((option.alignment() & Qt::AlignHorizontal_Mask) != Qt::AlignJustify)
1962 if (!forceJustification) {
1963 int end = line.from + (int)line.length;
1964 if (end == layoutData->string.length())
1965 return; // no justification at end of paragraph
1966 if (end && layoutData->items[findItem(end-1)].analysis.flags == QScriptAnalysis::LineOrParagraphSeparator)
1967 return; // no justification at the end of an explicitly separated line
1973 // don't include trailing white spaces when doing justification
1974 int line_length = line.length;
1975 const HB_CharAttributes *a = attributes();
1979 while (line_length && a[line_length-1].whiteSpace)
1981 // subtract one char more, as we can't justfy after the last character
1987 int firstItem = findItem(line.from);
1988 int nItems = findItem(line.from + line_length - 1) - firstItem + 1;
1990 QVarLengthArray<QJustificationPoint> justificationPoints;
1992 // 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());
1993 QFixed minKashida = 0x100000;
1995 // we need to do all shaping before we go into the next loop, as we there
1996 // store pointers to the glyph data that could get reallocated by the shaping
1998 for (int i = 0; i < nItems; ++i) {
1999 QScriptItem &si = layoutData->items[firstItem + i];
2001 shape(firstItem + i);
2004 for (int i = 0; i < nItems; ++i) {
2005 QScriptItem &si = layoutData->items[firstItem + i];
2007 int kashida_type = HB_Arabic_Normal;
2008 int kashida_pos = -1;
2010 int start = qMax(line.from - si.position, 0);
2011 int end = qMin(line.from + line_length - (int)si.position, length(firstItem+i));
2013 unsigned short *log_clusters = logClusters(&si);
2015 int gs = log_clusters[start];
2016 int ge = (end == length(firstItem+i) ? si.num_glyphs : log_clusters[end]);
2018 const QGlyphLayout g = shapedGlyphs(&si);
2020 for (int i = gs; i < ge; ++i) {
2021 g.justifications[i].type = QGlyphJustification::JustifyNone;
2022 g.justifications[i].nKashidas = 0;
2023 g.justifications[i].space_18d6 = 0;
2025 justificationPoints.resize(nPoints+3);
2026 int justification = g.attributes[i].justification;
2028 switch(justification) {
2029 case HB_NoJustification:
2033 case HB_Arabic_Space :
2034 if (kashida_pos >= 0) {
2035 // qDebug("kashida position at %d in word", kashida_pos);
2036 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
2037 if (justificationPoints[nPoints].kashidaWidth > 0) {
2038 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
2039 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
2044 kashida_type = HB_Arabic_Normal;
2047 set(&justificationPoints[nPoints++], justification, g.mid(i), fontEngine(si));
2048 maxJustify = qMax(maxJustify, justification);
2050 case HB_Arabic_Normal :
2051 case HB_Arabic_Waw :
2052 case HB_Arabic_BaRa :
2053 case HB_Arabic_Alef :
2054 case HB_Arabic_HaaDal :
2055 case HB_Arabic_Seen :
2056 case HB_Arabic_Kashida :
2057 if (justification >= kashida_type) {
2059 kashida_type = justification;
2063 if (kashida_pos >= 0) {
2064 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
2065 if (justificationPoints[nPoints].kashidaWidth > 0) {
2066 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
2067 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
2073 QFixed need = line.width - line.textWidth;
2075 // line overflows already!
2076 const_cast<QScriptLine &>(line).justified = true;
2080 // qDebug("doing justification: textWidth=%x, requested=%x, maxJustify=%d", line.textWidth.value(), line.width.value(), maxJustify);
2081 // qDebug(" minKashida=%f, need=%f", minKashida.toReal(), need.toReal());
2083 // distribute in priority order
2084 if (maxJustify >= HB_Arabic_Normal) {
2085 while (need >= minKashida) {
2086 for (int type = maxJustify; need >= minKashida && type >= HB_Arabic_Normal; --type) {
2087 for (int i = 0; need >= minKashida && i < nPoints; ++i) {
2088 if (justificationPoints[i].type == type && justificationPoints[i].kashidaWidth <= need) {
2089 justificationPoints[i].glyph.justifications->nKashidas++;
2091 justificationPoints[i].glyph.justifications->space_18d6 += justificationPoints[i].kashidaWidth.value();
2092 need -= justificationPoints[i].kashidaWidth;
2093 // qDebug("adding kashida type %d with width %x, neednow %x", type, justificationPoints[i].kashidaWidth, need.value());
2099 Q_ASSERT(need >= 0);
2103 maxJustify = qMin(maxJustify, (int)HB_Space);
2104 for (int type = maxJustify; need != 0 && type > 0; --type) {
2106 for (int i = 0; i < nPoints; ++i) {
2107 if (justificationPoints[i].type == type)
2110 // qDebug("number of points for justification type %d: %d", type, n);
2116 for (int i = 0; i < nPoints; ++i) {
2117 if (justificationPoints[i].type == type) {
2118 QFixed add = need/n;
2119 // qDebug("adding %x to glyph %x", add.value(), justificationPoints[i].glyph->glyph);
2120 justificationPoints[i].glyph.justifications[0].space_18d6 = add.value();
2129 const_cast<QScriptLine &>(line).justified = true;
2132 void QScriptLine::setDefaultHeight(QTextEngine *eng)
2137 if (eng->block.docHandle() && eng->block.docHandle()->layout()) {
2138 f = eng->block.charFormat().font();
2139 // Make sure we get the right dpi on printers
2140 QPaintDevice *pdev = eng->block.docHandle()->layout()->paintDevice();
2143 e = f.d->engineForScript(QUnicodeTables::Common);
2145 e = eng->fnt.d->engineForScript(QUnicodeTables::Common);
2148 QFixed other_ascent = e->ascent();
2149 QFixed other_descent = e->descent();
2150 QFixed other_leading = e->leading();
2151 leading = qMax(leading + ascent, other_leading + other_ascent) - qMax(ascent, other_ascent);
2152 ascent = qMax(ascent, other_ascent);
2153 descent = qMax(descent, other_descent);
2156 QTextEngine::LayoutData::LayoutData()
2160 memory_on_stack = false;
2163 layoutState = LayoutEmpty;
2164 haveCharAttributes = false;
2166 available_glyphs = 0;
2169 QTextEngine::LayoutData::LayoutData(const QString &str, void **stack_memory, int _allocated)
2172 allocated = _allocated;
2174 int space_charAttributes = sizeof(HB_CharAttributes)*string.length()/sizeof(void*) + 1;
2175 int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2176 available_glyphs = ((int)allocated - space_charAttributes - space_logClusters)*(int)sizeof(void*)/(int)QGlyphLayout::spaceNeededForGlyphLayout(1);
2178 if (available_glyphs < str.length()) {
2179 // need to allocate on the heap
2182 memory_on_stack = false;
2186 memory_on_stack = true;
2187 memory = stack_memory;
2188 logClustersPtr = (unsigned short *)(memory + space_charAttributes);
2190 void *m = memory + space_charAttributes + space_logClusters;
2191 glyphLayout = QGlyphLayout(reinterpret_cast<char *>(m), str.length());
2192 glyphLayout.clear();
2193 memset(memory, 0, space_charAttributes*sizeof(void *));
2197 layoutState = LayoutEmpty;
2198 haveCharAttributes = false;
2201 QTextEngine::LayoutData::~LayoutData()
2203 if (!memory_on_stack)
2208 bool QTextEngine::LayoutData::reallocate(int totalGlyphs)
2210 Q_ASSERT(totalGlyphs >= glyphLayout.numGlyphs);
2211 if (memory_on_stack && available_glyphs >= totalGlyphs) {
2212 glyphLayout.grow(glyphLayout.data(), totalGlyphs);
2216 int space_charAttributes = sizeof(HB_CharAttributes)*string.length()/sizeof(void*) + 1;
2217 int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2218 int space_glyphs = QGlyphLayout::spaceNeededForGlyphLayout(totalGlyphs)/sizeof(void*) + 2;
2220 int newAllocated = space_charAttributes + space_glyphs + space_logClusters;
2221 // These values can be negative if the length of string/glyphs causes overflow,
2222 // we can't layout such a long string all at once, so return false here to
2223 // indicate there is a failure
2224 if (space_charAttributes < 0 || space_logClusters < 0 || space_glyphs < 0 || newAllocated < allocated) {
2225 layoutState = LayoutFailed;
2229 void **newMem = memory;
2230 newMem = (void **)::realloc(memory_on_stack ? 0 : memory, newAllocated*sizeof(void *));
2232 layoutState = LayoutFailed;
2235 if (memory_on_stack)
2236 memcpy(newMem, memory, allocated*sizeof(void *));
2238 memory_on_stack = false;
2241 m += space_charAttributes;
2242 logClustersPtr = (unsigned short *) m;
2243 m += space_logClusters;
2245 const int space_preGlyphLayout = space_charAttributes + space_logClusters;
2246 if (allocated < space_preGlyphLayout)
2247 memset(memory + allocated, 0, (space_preGlyphLayout - allocated)*sizeof(void *));
2249 glyphLayout.grow(reinterpret_cast<char *>(m), totalGlyphs);
2251 allocated = newAllocated;
2255 // grow to the new size, copying the existing data to the new layout
2256 void QGlyphLayout::grow(char *address, int totalGlyphs)
2258 QGlyphLayout oldLayout(address, numGlyphs);
2259 QGlyphLayout newLayout(address, totalGlyphs);
2262 // move the existing data
2263 memmove(newLayout.attributes, oldLayout.attributes, numGlyphs * sizeof(HB_GlyphAttributes));
2264 memmove(newLayout.justifications, oldLayout.justifications, numGlyphs * sizeof(QGlyphJustification));
2265 memmove(newLayout.advances_y, oldLayout.advances_y, numGlyphs * sizeof(QFixed));
2266 memmove(newLayout.advances_x, oldLayout.advances_x, numGlyphs * sizeof(QFixed));
2267 memmove(newLayout.glyphs, oldLayout.glyphs, numGlyphs * sizeof(HB_Glyph));
2270 // clear the new data
2271 newLayout.clear(numGlyphs);
2276 void QTextEngine::freeMemory()
2282 layoutData->used = 0;
2283 layoutData->hasBidi = false;
2284 layoutData->layoutState = LayoutEmpty;
2285 layoutData->haveCharAttributes = false;
2287 for (int i = 0; i < lines.size(); ++i) {
2288 lines[i].justified = 0;
2289 lines[i].gridfitted = 0;
2293 int QTextEngine::formatIndex(const QScriptItem *si) const
2295 if (specialData && !specialData->resolvedFormatIndices.isEmpty())
2296 return specialData->resolvedFormatIndices.at(si - &layoutData->items[0]);
2297 QTextDocumentPrivate *p = block.docHandle();
2300 int pos = si->position;
2301 if (specialData && si->position >= specialData->preeditPosition) {
2302 if (si->position < specialData->preeditPosition + specialData->preeditText.length())
2303 pos = qMax(specialData->preeditPosition - 1, 0);
2305 pos -= specialData->preeditText.length();
2307 QTextDocumentPrivate::FragmentIterator it = p->find(block.position() + pos);
2308 return it.value()->format;
2312 QTextCharFormat QTextEngine::format(const QScriptItem *si) const
2314 QTextCharFormat format;
2315 const QTextFormatCollection *formats = 0;
2316 if (block.docHandle()) {
2317 formats = this->formats();
2318 format = formats->charFormat(formatIndex(si));
2320 if (specialData && specialData->resolvedFormatIndices.isEmpty()) {
2321 int end = si->position + length(si);
2322 for (int i = 0; i < specialData->addFormats.size(); ++i) {
2323 const QTextLayout::FormatRange &r = specialData->addFormats.at(i);
2324 if (r.start <= si->position && r.start + r.length >= end) {
2325 if (!specialData->addFormatIndices.isEmpty())
2326 format.merge(formats->format(specialData->addFormatIndices.at(i)));
2328 format.merge(r.format);
2335 void QTextEngine::addRequiredBoundaries() const
2338 for (int i = 0; i < specialData->addFormats.size(); ++i) {
2339 const QTextLayout::FormatRange &r = specialData->addFormats.at(i);
2340 setBoundary(r.start);
2341 setBoundary(r.start + r.length);
2342 //qDebug("adding boundaries %d %d", r.start, r.start+r.length);
2347 bool QTextEngine::atWordSeparator(int position) const
2349 const QChar c = layoutData->string.at(position);
2350 switch (c.toLatin1()) {
2387 bool QTextEngine::atSpace(int position) const
2389 const QChar c = layoutData->string.at(position);
2391 return c == QLatin1Char(' ')
2393 || c == QChar::LineSeparator
2394 || c == QLatin1Char('\t')
2399 void QTextEngine::indexAdditionalFormats()
2401 if (!block.docHandle())
2404 specialData->addFormatIndices.resize(specialData->addFormats.count());
2405 QTextFormatCollection * const formats = this->formats();
2407 for (int i = 0; i < specialData->addFormats.count(); ++i) {
2408 specialData->addFormatIndices[i] = formats->indexForFormat(specialData->addFormats.at(i).format);
2409 specialData->addFormats[i].format = QTextCharFormat();
2413 /* These two helper functions are used to determine whether we need to insert a ZWJ character
2414 between the text that gets truncated and the ellipsis. This is important to get
2415 correctly shaped results for arabic text.
2417 static bool nextCharJoins(const QString &string, int pos)
2419 while (pos < string.length() && string.at(pos).category() == QChar::Mark_NonSpacing)
2421 if (pos == string.length())
2423 return string.at(pos).joining() != QChar::OtherJoining;
2426 static bool prevCharJoins(const QString &string, int pos)
2428 while (pos > 0 && string.at(pos - 1).category() == QChar::Mark_NonSpacing)
2432 return (string.at(pos - 1).joining() == QChar::Dual || string.at(pos - 1).joining() == QChar::Center);
2435 QString QTextEngine::elidedText(Qt::TextElideMode mode, const QFixed &width, int flags) const
2437 // qDebug() << "elidedText; available width" << width.toReal() << "text width:" << this->width(0, layoutData->string.length()).toReal();
2439 if (flags & Qt::TextShowMnemonic) {
2441 HB_CharAttributes *attributes = const_cast<HB_CharAttributes *>(this->attributes());
2444 for (int i = 0; i < layoutData->items.size(); ++i) {
2445 QScriptItem &si = layoutData->items[i];
2449 unsigned short *logClusters = this->logClusters(&si);
2450 QGlyphLayout glyphs = shapedGlyphs(&si);
2452 const int end = si.position + length(&si);
2453 for (int i = si.position; i < end - 1; ++i) {
2454 if (layoutData->string.at(i) == QLatin1Char('&')) {
2455 const int gp = logClusters[i - si.position];
2456 glyphs.attributes[gp].dontPrint = true;
2457 attributes[i + 1].charStop = false;
2458 attributes[i + 1].whiteSpace = false;
2459 attributes[i + 1].lineBreakType = HB_NoBreak;
2460 if (layoutData->string.at(i + 1) == QLatin1Char('&'))
2469 if (mode == Qt::ElideNone
2470 || this->width(0, layoutData->string.length()) <= width
2471 || layoutData->string.length() <= 1)
2472 return layoutData->string;
2474 QFixed ellipsisWidth;
2475 QString ellipsisText;
2477 QChar ellipsisChar(0x2026);
2479 QFontEngine *fe = fnt.d->engineForScript(QUnicodeTables::Common);
2481 QGlyphLayoutArray<1> ellipsisGlyph;
2483 QFontEngine *feForEllipsis = (fe->type() == QFontEngine::Multi)
2484 ? static_cast<QFontEngineMulti *>(fe)->engine(0)
2487 if (feForEllipsis->type() == QFontEngine::Mac)
2490 // the lookup can be really slow when we use XLFD fonts
2491 if (feForEllipsis->type() != QFontEngine::XLFD
2492 && feForEllipsis->canRender(&ellipsisChar, 1)) {
2494 feForEllipsis->stringToCMap(&ellipsisChar, 1, &ellipsisGlyph, &nGlyphs, 0);
2498 if (ellipsisGlyph.glyphs[0]) {
2499 ellipsisWidth = ellipsisGlyph.advances_x[0];
2500 ellipsisText = ellipsisChar;
2502 QString dotDotDot(QLatin1String("..."));
2504 QGlyphLayoutArray<3> glyphs;
2506 if (!fe->stringToCMap(dotDotDot.constData(), 3, &glyphs, &nGlyphs, 0))
2507 // should never happen...
2508 return layoutData->string;
2509 for (int i = 0; i < nGlyphs; ++i)
2510 ellipsisWidth += glyphs.advances_x[i];
2511 ellipsisText = dotDotDot;
2515 const QFixed availableWidth = width - ellipsisWidth;
2516 if (availableWidth < 0)
2519 const HB_CharAttributes *attributes = this->attributes();
2523 if (mode == Qt::ElideRight) {
2524 QFixed currentWidth;
2532 while (nextBreak < layoutData->string.length() && !attributes[nextBreak].charStop)
2535 currentWidth += this->width(pos, nextBreak - pos);
2536 } while (nextBreak < layoutData->string.length()
2537 && currentWidth < availableWidth);
2539 if (nextCharJoins(layoutData->string, pos))
2540 ellipsisText.prepend(QChar(0x200d) /* ZWJ */);
2542 return layoutData->string.left(pos) + ellipsisText;
2543 } else if (mode == Qt::ElideLeft) {
2544 QFixed currentWidth;
2546 int nextBreak = layoutData->string.length();
2552 while (nextBreak > 0 && !attributes[nextBreak].charStop)
2555 currentWidth += this->width(nextBreak, pos - nextBreak);
2556 } while (nextBreak > 0
2557 && currentWidth < availableWidth);
2559 if (prevCharJoins(layoutData->string, pos))
2560 ellipsisText.append(QChar(0x200d) /* ZWJ */);
2562 return ellipsisText + layoutData->string.mid(pos);
2563 } else if (mode == Qt::ElideMiddle) {
2568 int nextLeftBreak = 0;
2570 int rightPos = layoutData->string.length();
2571 int nextRightBreak = layoutData->string.length();
2574 leftPos = nextLeftBreak;
2575 rightPos = nextRightBreak;
2578 while (nextLeftBreak < layoutData->string.length() && !attributes[nextLeftBreak].charStop)
2582 while (nextRightBreak > 0 && !attributes[nextRightBreak].charStop)
2585 leftWidth += this->width(leftPos, nextLeftBreak - leftPos);
2586 rightWidth += this->width(nextRightBreak, rightPos - nextRightBreak);
2587 } while (nextLeftBreak < layoutData->string.length()
2588 && nextRightBreak > 0
2589 && leftWidth + rightWidth < availableWidth);
2591 if (nextCharJoins(layoutData->string, leftPos))
2592 ellipsisText.prepend(QChar(0x200d) /* ZWJ */);
2593 if (prevCharJoins(layoutData->string, rightPos))
2594 ellipsisText.append(QChar(0x200d) /* ZWJ */);
2596 return layoutData->string.left(leftPos) + ellipsisText + layoutData->string.mid(rightPos);
2599 return layoutData->string;
2602 void QTextEngine::setBoundary(int strPos) const
2604 if (strPos <= 0 || strPos >= layoutData->string.length())
2607 int itemToSplit = 0;
2608 while (itemToSplit < layoutData->items.size() && layoutData->items.at(itemToSplit).position <= strPos)
2611 if (layoutData->items.at(itemToSplit).position == strPos) {
2612 // already a split at the requested position
2615 splitItem(itemToSplit, strPos - layoutData->items.at(itemToSplit).position);
2618 void QTextEngine::splitItem(int item, int pos) const
2623 layoutData->items.insert(item + 1, layoutData->items[item]);
2624 QScriptItem &oldItem = layoutData->items[item];
2625 QScriptItem &newItem = layoutData->items[item+1];
2626 newItem.position += pos;
2628 if (oldItem.num_glyphs) {
2629 // already shaped, break glyphs aswell
2630 int breakGlyph = logClusters(&oldItem)[pos];
2632 newItem.num_glyphs = oldItem.num_glyphs - breakGlyph;
2633 oldItem.num_glyphs = breakGlyph;
2634 newItem.glyph_data_offset = oldItem.glyph_data_offset + breakGlyph;
2636 for (int i = 0; i < newItem.num_glyphs; i++)
2637 logClusters(&newItem)[i] -= breakGlyph;
2640 const QGlyphLayout g = shapedGlyphs(&oldItem);
2641 for(int j = 0; j < breakGlyph; ++j)
2642 w += g.advances_x[j];
2644 newItem.width = oldItem.width - w;
2648 // qDebug("split at position %d itempos=%d", pos, item);
2651 QFixed QTextEngine::calculateTabWidth(int item, QFixed x) const
2653 const QScriptItem &si = layoutData->items[item];
2655 QFixed dpiScale = 1;
2656 if (block.docHandle() && block.docHandle()->layout()) {
2657 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
2659 dpiScale = QFixed::fromReal(pdev->logicalDpiY() / qreal(qt_defaultDpiY()));
2661 dpiScale = QFixed::fromReal(fnt.d->dpi / qreal(qt_defaultDpiY()));
2664 QList<QTextOption::Tab> tabArray = option.tabs();
2665 if (!tabArray.isEmpty()) {
2666 if (isRightToLeft()) { // rebase the tabArray positions.
2667 QList<QTextOption::Tab> newTabs;
2668 QList<QTextOption::Tab>::Iterator iter = tabArray.begin();
2669 while(iter != tabArray.end()) {
2670 QTextOption::Tab tab = *iter;
2671 if (tab.type == QTextOption::LeftTab)
2672 tab.type = QTextOption::RightTab;
2673 else if (tab.type == QTextOption::RightTab)
2674 tab.type = QTextOption::LeftTab;
2680 for (int i = 0; i < tabArray.size(); ++i) {
2681 QFixed tab = QFixed::fromReal(tabArray[i].position) * dpiScale;
2682 if (tab > x) { // this is the tab we need.
2683 QTextOption::Tab tabSpec = tabArray[i];
2684 int tabSectionEnd = layoutData->string.count();
2685 if (tabSpec.type == QTextOption::RightTab || tabSpec.type == QTextOption::CenterTab) {
2686 // find next tab to calculate the width required.
2687 tab = QFixed::fromReal(tabSpec.position);
2688 for (int i=item + 1; i < layoutData->items.count(); i++) {
2689 const QScriptItem &item = layoutData->items[i];
2690 if (item.analysis.flags == QScriptAnalysis::TabOrObject) { // found it.
2691 tabSectionEnd = item.position;
2696 else if (tabSpec.type == QTextOption::DelimiterTab)
2697 // find delimitor character to calculate the width required
2698 tabSectionEnd = qMax(si.position, layoutData->string.indexOf(tabSpec.delimiter, si.position) + 1);
2700 if (tabSectionEnd > si.position) {
2702 // Calculate the length of text between this tab and the tabSectionEnd
2703 for (int i=item; i < layoutData->items.count(); i++) {
2704 QScriptItem &item = layoutData->items[i];
2705 if (item.position > tabSectionEnd || item.position <= si.position)
2707 shape(i); // first, lets make sure relevant text is already shaped
2708 QGlyphLayout glyphs = this->shapedGlyphs(&item);
2709 const int end = qMin(item.position + item.num_glyphs, tabSectionEnd) - item.position;
2710 for (int i=0; i < end; i++)
2711 length += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
2712 if (end + item.position == tabSectionEnd && tabSpec.type == QTextOption::DelimiterTab) // remove half of matching char
2713 length -= glyphs.advances_x[end] / 2 * !glyphs.attributes[end].dontPrint;
2716 switch (tabSpec.type) {
2717 case QTextOption::CenterTab:
2720 case QTextOption::DelimiterTab:
2722 case QTextOption::RightTab:
2723 tab = QFixed::fromReal(tabSpec.position) * dpiScale - length;
2724 if (tab < 0) // default to tab taking no space
2727 case QTextOption::LeftTab:
2735 QFixed tab = QFixed::fromReal(option.tabStop());
2737 tab = 80; // default
2739 QFixed nextTabPos = ((x / tab).truncate() + 1) * tab;
2740 QFixed tabWidth = nextTabPos - x;
2745 void QTextEngine::resolveAdditionalFormats() const
2747 if (!specialData || specialData->addFormats.isEmpty()
2748 || !block.docHandle()
2749 || !specialData->resolvedFormatIndices.isEmpty())
2752 QTextFormatCollection *collection = this->formats();
2754 specialData->resolvedFormatIndices.clear();
2755 QVector<int> indices(layoutData->items.count());
2756 for (int i = 0; i < layoutData->items.count(); ++i) {
2757 QTextCharFormat f = format(&layoutData->items.at(i));
2758 indices[i] = collection->indexForFormat(f);
2760 specialData->resolvedFormatIndices = indices;
2763 QFixed QTextEngine::leadingSpaceWidth(const QScriptLine &line)
2765 if (!line.hasTrailingSpaces
2766 || (option.flags() & QTextOption::IncludeTrailingSpaces)
2767 || !isRightToLeft())
2770 int pos = line.length;
2771 const HB_CharAttributes *attributes = this->attributes();
2774 while (pos > 0 && attributes[line.from + pos - 1].whiteSpace)
2776 return width(line.from + pos, line.length - pos);
2779 QFixed QTextEngine::alignLine(const QScriptLine &line)
2783 // if width is QFIXED_MAX that means we used setNumColumns() and that implicitly makes this line left aligned.
2784 if (!line.justified && line.width != QFIXED_MAX) {
2785 int align = option.alignment();
2786 if (align & Qt::AlignLeft)
2787 x -= leadingSpaceWidth(line);
2788 if (align & Qt::AlignJustify && isRightToLeft())
2789 align = Qt::AlignRight;
2790 if (align & Qt::AlignRight)
2791 x = line.width - (line.textAdvance + leadingSpaceWidth(line));
2792 else if (align & Qt::AlignHCenter)
2793 x = (line.width - line.textAdvance)/2 - leadingSpaceWidth(line);
2798 QFixed QTextEngine::offsetInLigature(const QScriptItem *si, int pos, int max, int glyph_pos)
2800 unsigned short *logClusters = this->logClusters(si);
2801 const QGlyphLayout &glyphs = shapedGlyphs(si);
2803 int offsetInCluster = 0;
2804 for (int i = pos - 1; i >= 0; i--) {
2805 if (logClusters[i] == glyph_pos)
2811 // in the case that the offset is inside a (multi-character) glyph,
2812 // interpolate the position.
2813 if (offsetInCluster > 0) {
2814 int clusterLength = 0;
2815 for (int i = pos - offsetInCluster; i < max; i++) {
2816 if (logClusters[i] == glyph_pos)
2822 return glyphs.advances_x[glyph_pos] * offsetInCluster / clusterLength;
2828 // Scan in logClusters[from..to-1] for glyph_pos
2829 int QTextEngine::getClusterLength(unsigned short *logClusters,
2830 const HB_CharAttributes *attributes,
2831 int from, int to, int glyph_pos, int *start)
2833 int clusterLength = 0;
2834 for (int i = from; i < to; i++) {
2835 if (logClusters[i] == glyph_pos && attributes[i].charStop) {
2840 else if (clusterLength)
2843 return clusterLength;
2846 int QTextEngine::positionInLigature(const QScriptItem *si, int end,
2847 QFixed x, QFixed edge, int glyph_pos,
2848 bool cursorOnCharacter)
2850 unsigned short *logClusters = this->logClusters(si);
2851 int clusterStart = -1;
2852 int clusterLength = 0;
2854 if (si->analysis.script != QUnicodeTables::Common &&
2855 si->analysis.script != QUnicodeTables::Greek) {
2856 if (glyph_pos == -1)
2857 return si->position + end;
2860 for (i = 0; i < end; i++)
2861 if (logClusters[i] == glyph_pos)
2863 return si->position + i;
2867 if (glyph_pos == -1 && end > 0)
2868 glyph_pos = logClusters[end - 1];
2874 const HB_CharAttributes *attrs = attributes();
2875 logClusters = this->logClusters(si);
2876 clusterLength = getClusterLength(logClusters, attrs, 0, end, glyph_pos, &clusterStart);
2878 if (clusterLength) {
2879 const QGlyphLayout &glyphs = shapedGlyphs(si);
2880 QFixed glyphWidth = glyphs.effectiveAdvance(glyph_pos);
2881 // the approximate width of each individual element of the ligature
2882 QFixed perItemWidth = glyphWidth / clusterLength;
2883 QFixed left = x > edge ? edge : edge - glyphWidth;
2884 int n = ((x - left) / perItemWidth).floor().toInt();
2885 QFixed dist = x - left - n * perItemWidth;
2886 int closestItem = dist > (perItemWidth / 2) ? n + 1 : n;
2887 if (cursorOnCharacter && closestItem > 0)
2889 int pos = si->position + clusterStart + closestItem;
2890 // Jump to the next charStop
2891 while (!attrs[pos].charStop && pos < end)
2895 return si->position + end;
2898 int QTextEngine::previousLogicalPosition(int oldPos) const
2900 const HB_CharAttributes *attrs = attributes();
2901 if (!attrs || oldPos < 0)
2907 while (oldPos && !attrs[oldPos].charStop)
2912 int QTextEngine::nextLogicalPosition(int oldPos) const
2914 const HB_CharAttributes *attrs = attributes();
2915 int len = block.isValid() ? block.length() - 1
2916 : layoutData->string.length();
2917 Q_ASSERT(len <= layoutData->string.length());
2918 if (!attrs || oldPos < 0 || oldPos >= len)
2922 while (oldPos < len && !attrs[oldPos].charStop)
2927 int QTextEngine::lineNumberForTextPosition(int pos)
2931 if (pos == layoutData->string.length() && lines.size())
2932 return lines.size() - 1;
2933 for (int i = 0; i < lines.size(); ++i) {
2934 const QScriptLine& line = lines[i];
2935 if (line.from + line.length > pos)
2941 void QTextEngine::insertionPointsForLine(int lineNum, QVector<int> &insertionPoints)
2943 QTextLineItemIterator iterator(this, lineNum);
2944 bool rtl = isRightToLeft();
2945 bool lastLine = lineNum >= lines.size() - 1;
2947 while (!iterator.atEnd()) {
2949 const QScriptItem *si = &layoutData->items[iterator.item];
2950 if (si->analysis.bidiLevel % 2) {
2951 int i = iterator.itemEnd - 1, min = iterator.itemStart;
2952 if (lastLine && (rtl ? iterator.atBeginning() : iterator.atEnd()))
2954 for (; i >= min; i--)
2955 insertionPoints.push_back(i);
2957 int i = iterator.itemStart, max = iterator.itemEnd;
2958 if (lastLine && (rtl ? iterator.atBeginning() : iterator.atEnd()))
2960 for (; i < max; i++)
2961 insertionPoints.push_back(i);
2966 int QTextEngine::endOfLine(int lineNum)
2968 QVector<int> insertionPoints;
2969 insertionPointsForLine(lineNum, insertionPoints);
2971 if (insertionPoints.size() > 0)
2972 return insertionPoints.last();
2976 int QTextEngine::beginningOfLine(int lineNum)
2978 QVector<int> insertionPoints;
2979 insertionPointsForLine(lineNum, insertionPoints);
2981 if (insertionPoints.size() > 0)
2982 return insertionPoints.first();
2986 int QTextEngine::positionAfterVisualMovement(int pos, QTextCursor::MoveOperation op)
2991 bool moveRight = (op == QTextCursor::Right);
2992 bool alignRight = isRightToLeft();
2993 if (!layoutData->hasBidi)
2994 return moveRight ^ alignRight ? nextLogicalPosition(pos) : previousLogicalPosition(pos);
2996 int lineNum = lineNumberForTextPosition(pos);
2997 Q_ASSERT(lineNum >= 0);
2999 QVector<int> insertionPoints;
3000 insertionPointsForLine(lineNum, insertionPoints);
3001 int i, max = insertionPoints.size();
3002 for (i = 0; i < max; i++)
3003 if (pos == insertionPoints[i]) {
3006 return insertionPoints[i + 1];
3009 return insertionPoints[i - 1];
3012 if (moveRight ^ alignRight) {
3013 if (lineNum + 1 < lines.size())
3014 return alignRight ? endOfLine(lineNum + 1) : beginningOfLine(lineNum + 1);
3018 return alignRight ? beginningOfLine(lineNum - 1) : endOfLine(lineNum - 1);
3025 QStackTextEngine::QStackTextEngine(const QString &string, const QFont &f)
3026 : QTextEngine(string, f),
3027 _layoutData(string, _memory, MemSize)
3030 layoutData = &_layoutData;
3033 QTextItemInt::QTextItemInt(const QScriptItem &si, QFont *font, const QTextCharFormat &format)
3034 : justified(false), underlineStyle(QTextCharFormat::NoUnderline), charFormat(format),
3035 num_chars(0), chars(0), logClusters(0), f(0), fontEngine(0)
3037 // explicitly initialize flags so that initFontAttributes can be called
3038 // multiple times on the same TextItem
3040 if (si.analysis.bidiLevel %2)
3041 flags |= QTextItem::RightToLeft;
3043 descent = si.descent;
3045 fontEngine = f->d->engineForScript(si.analysis.script);
3046 Q_ASSERT(fontEngine);
3048 if (format.hasProperty(QTextFormat::TextUnderlineStyle)) {
3049 underlineStyle = format.underlineStyle();
3050 } else if (format.boolProperty(QTextFormat::FontUnderline)
3051 || f->d->underline) {
3052 underlineStyle = QTextCharFormat::SingleUnderline;
3056 if (underlineStyle == QTextCharFormat::SingleUnderline)
3057 flags |= QTextItem::Underline;
3059 if (f->d->overline || format.fontOverline())
3060 flags |= QTextItem::Overline;
3061 if (f->d->strikeOut || format.fontStrikeOut())
3062 flags |= QTextItem::StrikeOut;
3065 QTextItemInt::QTextItemInt(const QGlyphLayout &g, QFont *font, const QChar *chars_, int numChars, QFontEngine *fe)
3066 : flags(0), justified(false), underlineStyle(QTextCharFormat::NoUnderline),
3067 num_chars(numChars), chars(chars_), logClusters(0), f(font), glyphs(g), fontEngine(fe)
3071 QTextItemInt QTextItemInt::midItem(QFontEngine *fontEngine, int firstGlyphIndex, int numGlyphs) const
3073 QTextItemInt ti = *this;
3074 const int end = firstGlyphIndex + numGlyphs;
3075 ti.glyphs = glyphs.mid(firstGlyphIndex, numGlyphs);
3076 ti.fontEngine = fontEngine;
3078 if (logClusters && chars) {
3079 const int logClusterOffset = logClusters[0];
3080 while (logClusters[ti.chars - chars] - logClusterOffset < firstGlyphIndex)
3083 ti.logClusters += (ti.chars - chars);
3086 int char_start = ti.chars - chars;
3087 while (char_start + ti.num_chars < num_chars && ti.logClusters[ti.num_chars] - logClusterOffset < end)
3094 QTransform qt_true_matrix(qreal w, qreal h, QTransform x)
3096 QRectF rect = x.mapRect(QRectF(0, 0, w, h));
3097 return x * QTransform::fromTranslate(-rect.x(), -rect.y());
3101 glyph_metrics_t glyph_metrics_t::transformed(const QTransform &matrix) const
3103 if (matrix.type() < QTransform::TxTranslate)
3106 glyph_metrics_t m = *this;
3108 qreal w = width.toReal();
3109 qreal h = height.toReal();
3110 QTransform xform = qt_true_matrix(w, h, matrix);
3112 QRectF rect(0, 0, w, h);
3113 rect = xform.mapRect(rect);
3114 m.width = QFixed::fromReal(rect.width());
3115 m.height = QFixed::fromReal(rect.height());
3117 QLineF l = xform.map(QLineF(x.toReal(), y.toReal(), xoff.toReal(), yoff.toReal()));
3119 m.x = QFixed::fromReal(l.x1());
3120 m.y = QFixed::fromReal(l.y1());
3122 // The offset is relative to the baseline which is why we use dx/dy of the line
3123 m.xoff = QFixed::fromReal(l.dx());
3124 m.yoff = QFixed::fromReal(l.dy());
3129 QTextLineItemIterator::QTextLineItemIterator(QTextEngine *_eng, int _lineNum, const QPointF &pos,
3130 const QTextLayout::FormatRange *_selection)
3132 line(eng->lines[_lineNum]),
3135 lineEnd(line.from + line.length),
3136 firstItem(eng->findItem(line.from)),
3137 lastItem(eng->findItem(lineEnd - 1)),
3138 nItems((firstItem >= 0 && lastItem >= firstItem)? (lastItem-firstItem+1) : 0),
3141 visualOrder(nItems),
3143 selection(_selection)
3145 pos_x = x = QFixed::fromReal(pos.x());
3149 x += eng->alignLine(line);
3151 for (int i = 0; i < nItems; ++i)
3152 levels[i] = eng->layoutData->items[i+firstItem].analysis.bidiLevel;
3153 QTextEngine::bidiReorder(nItems, levels.data(), visualOrder.data());
3155 eng->shapeLine(line);
3158 QScriptItem &QTextLineItemIterator::next()
3163 item = visualOrder[logicalItem] + firstItem;
3164 itemLength = eng->length(item);
3165 si = &eng->layoutData->items[item];
3166 if (!si->num_glyphs)
3169 if (si->analysis.flags >= QScriptAnalysis::TabOrObject) {
3170 itemWidth = si->width;
3174 unsigned short *logClusters = eng->logClusters(si);
3175 QGlyphLayout glyphs = eng->shapedGlyphs(si);
3177 itemStart = qMax(line.from, si->position);
3178 glyphsStart = logClusters[itemStart - si->position];
3179 if (lineEnd < si->position + itemLength) {
3181 glyphsEnd = logClusters[itemEnd-si->position];
3183 itemEnd = si->position + itemLength;
3184 glyphsEnd = si->num_glyphs;
3186 // show soft-hyphen at line-break
3187 if (si->position + itemLength >= lineEnd
3188 && eng->layoutData->string.at(lineEnd - 1) == 0x00ad)
3189 glyphs.attributes[glyphsEnd - 1].dontPrint = false;
3192 for (int g = glyphsStart; g < glyphsEnd; ++g)
3193 itemWidth += glyphs.effectiveAdvance(g);
3198 bool QTextLineItemIterator::getSelectionBounds(QFixed *selectionX, QFixed *selectionWidth) const
3200 *selectionX = *selectionWidth = 0;
3205 if (si->analysis.flags >= QScriptAnalysis::TabOrObject) {
3206 if (si->position >= selection->start + selection->length
3207 || si->position + itemLength <= selection->start)
3211 *selectionWidth = itemWidth;
3213 unsigned short *logClusters = eng->logClusters(si);
3214 QGlyphLayout glyphs = eng->shapedGlyphs(si);
3216 int from = qMax(itemStart, selection->start) - si->position;
3217 int to = qMin(itemEnd, selection->start + selection->length) - si->position;
3221 int start_glyph = logClusters[from];
3222 int end_glyph = (to == eng->length(item)) ? si->num_glyphs : logClusters[to];
3225 if (si->analysis.bidiLevel %2) {
3226 for (int g = glyphsEnd - 1; g >= end_glyph; --g)
3227 soff += glyphs.effectiveAdvance(g);
3228 for (int g = end_glyph - 1; g >= start_glyph; --g)
3229 swidth += glyphs.effectiveAdvance(g);
3231 for (int g = glyphsStart; g < start_glyph; ++g)
3232 soff += glyphs.effectiveAdvance(g);
3233 for (int g = start_glyph; g < end_glyph; ++g)
3234 swidth += glyphs.effectiveAdvance(g);
3237 // If the starting character is in the middle of a ligature,
3238 // selection should only contain the right part of that ligature
3239 // glyph, so we need to get the width of the left part here and
3240 // add it to *selectionX
3241 QFixed leftOffsetInLigature = eng->offsetInLigature(si, from, to, start_glyph);
3242 *selectionX = x + soff + leftOffsetInLigature;
3243 *selectionWidth = swidth - leftOffsetInLigature;
3244 // If the ending character is also part of a ligature, swidth does
3245 // not contain that part yet, we also need to find out the width of
3247 *selectionWidth += eng->offsetInLigature(si, to, eng->length(item), end_glyph);