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 void QTextEngine::shapeText(int item) const
861 Q_ASSERT(item < layoutData->items.size());
862 QScriptItem &si = layoutData->items[item];
867 #if defined(Q_WS_MAC)
869 #elif defined(Q_WS_WINCE)
870 shapeTextWithCE(item);
872 shapeTextWithHarfbuzz(item);
879 QGlyphLayout glyphs = shapedGlyphs(&si);
881 QFont font = this->font(si);
882 bool letterSpacingIsAbsolute = font.d->letterSpacingIsAbsolute;
883 QFixed letterSpacing = font.d->letterSpacing;
884 QFixed wordSpacing = font.d->wordSpacing;
886 if (letterSpacingIsAbsolute && letterSpacing.value())
887 letterSpacing *= font.d->dpi / qt_defaultDpiY();
889 if (letterSpacing != 0) {
890 for (int i = 1; i < si.num_glyphs; ++i) {
891 if (glyphs.attributes[i].clusterStart) {
892 if (letterSpacingIsAbsolute)
893 glyphs.advances_x[i-1] += letterSpacing;
895 QFixed &advance = glyphs.advances_x[i-1];
896 advance += (letterSpacing - 100) * advance / 100;
900 if (letterSpacingIsAbsolute)
901 glyphs.advances_x[si.num_glyphs-1] += letterSpacing;
903 QFixed &advance = glyphs.advances_x[si.num_glyphs-1];
904 advance += (letterSpacing - 100) * advance / 100;
907 if (wordSpacing != 0) {
908 for (int i = 0; i < si.num_glyphs; ++i) {
909 if (glyphs.attributes[i].justification == HB_Space
910 || glyphs.attributes[i].justification == HB_Arabic_Space) {
911 // word spacing only gets added once to a consecutive run of spaces (see CSS spec)
912 if (i + 1 == si.num_glyphs
913 ||(glyphs.attributes[i+1].justification != HB_Space
914 && glyphs.attributes[i+1].justification != HB_Arabic_Space))
915 glyphs.advances_x[i] += wordSpacing;
920 for (int i = 0; i < si.num_glyphs; ++i)
921 si.width += glyphs.advances_x[i];
924 static inline bool hasCaseChange(const QScriptItem &si)
926 return si.analysis.flags == QScriptAnalysis::SmallCaps ||
927 si.analysis.flags == QScriptAnalysis::Uppercase ||
928 si.analysis.flags == QScriptAnalysis::Lowercase;
931 #if defined(Q_WS_WINCE) //TODO
932 // set the glyph attributes heuristically. Assumes a 1 to 1 relationship between chars and glyphs
933 // and no reordering.
934 // also computes logClusters heuristically
935 static void heuristicSetGlyphAttributes(const QChar *uc, int length, QGlyphLayout *glyphs, unsigned short *logClusters, int num_glyphs)
937 // ### zeroWidth and justification are missing here!!!!!
939 Q_UNUSED(num_glyphs);
940 Q_ASSERT(num_glyphs <= length);
942 // qDebug("QScriptEngine::heuristicSetGlyphAttributes, num_glyphs=%d", item->num_glyphs);
945 for (int i = 0; i < length; i++) {
946 if (uc[i].unicode() >= 0xd800 && uc[i].unicode() < 0xdc00 && i < length-1
947 && uc[i+1].unicode() >= 0xdc00 && uc[i+1].unicode() < 0xe000) {
948 logClusters[i] = glyph_pos;
949 logClusters[++i] = glyph_pos;
951 logClusters[i] = glyph_pos;
956 // first char in a run is never (treated as) a mark
959 const bool symbolFont = false; // ####
960 glyphs->attributes[0].mark = false;
961 glyphs->attributes[0].clusterStart = true;
962 glyphs->attributes[0].dontPrint = (!symbolFont && uc[0].unicode() == 0x00ad) || qIsControlChar(uc[0].unicode());
965 int lastCat = QChar::category(uc[0].unicode());
966 for (int i = 1; i < length; ++i) {
967 if (logClusters[i] == pos)
971 while (pos < logClusters[i]) {
972 glyphs[pos].attributes = glyphs[pos-1].attributes;
975 // hide soft-hyphens by default
976 if ((!symbolFont && uc[i].unicode() == 0x00ad) || qIsControlChar(uc[i].unicode()))
977 glyphs->attributes[pos].dontPrint = true;
978 const QUnicodeTables::Properties *prop = QUnicodeTables::properties(uc[i].unicode());
979 int cat = prop->category;
980 if (cat != QChar::Mark_NonSpacing) {
981 glyphs->attributes[pos].mark = false;
982 glyphs->attributes[pos].clusterStart = true;
983 glyphs->attributes[pos].combiningClass = 0;
984 cStart = logClusters[i];
986 int cmb = prop->combiningClass;
989 // Fix 0 combining classes
990 if ((uc[pos].unicode() & 0xff00) == 0x0e00) {
992 unsigned char col = uc[pos].cell();
1002 cmb = QChar::Combining_AboveRight;
1003 } else if (col == 0xb1 ||
1011 cmb = QChar::Combining_Above;
1012 } else if (col == 0xbc) {
1013 cmb = QChar::Combining_Below;
1018 glyphs->attributes[pos].mark = true;
1019 glyphs->attributes[pos].clusterStart = false;
1020 glyphs->attributes[pos].combiningClass = cmb;
1021 logClusters[i] = cStart;
1022 glyphs->advances_x[pos] = 0;
1023 glyphs->advances_y[pos] = 0;
1026 // one gets an inter character justification point if the current char is not a non spacing mark.
1027 // as then the current char belongs to the last one and one gets a space justification point
1028 // after the space char.
1029 if (lastCat == QChar::Separator_Space)
1030 glyphs->attributes[pos-1].justification = HB_Space;
1031 else if (cat != QChar::Mark_NonSpacing)
1032 glyphs->attributes[pos-1].justification = HB_Character;
1034 glyphs->attributes[pos-1].justification = HB_NoJustification;
1038 pos = logClusters[length-1];
1039 if (lastCat == QChar::Separator_Space)
1040 glyphs->attributes[pos].justification = HB_Space;
1042 glyphs->attributes[pos].justification = HB_Character;
1045 void QTextEngine::shapeTextWithCE(int item) const
1047 QScriptItem &si = layoutData->items[item];
1048 si.glyph_data_offset = layoutData->used;
1050 QFontEngine *fe = fontEngine(si, &si.ascent, &si.descent, &si.leading);
1052 QTextEngine::ShaperFlags flags;
1053 if (si.analysis.bidiLevel % 2)
1054 flags |= RightToLeft;
1055 if (option.useDesignMetrics())
1056 flags |= DesignMetrics;
1058 // pre-initialize char attributes
1062 const int len = length(item);
1063 int num_glyphs = length(item);
1064 const QChar *str = layoutData->string.unicode() + si.position;
1065 ushort upperCased[256];
1066 if (hasCaseChange(si)) {
1067 ushort *uc = upperCased;
1069 uc = new ushort[len];
1070 for (int i = 0; i < len; ++i) {
1071 if(si.analysis.flags == QScriptAnalysis::Lowercase)
1072 uc[i] = str[i].toLower().unicode();
1074 uc[i] = str[i].toUpper().unicode();
1076 str = reinterpret_cast<const QChar *>(uc);
1080 if (! ensureSpace(num_glyphs)) {
1081 // If str is converted to uppercase/lowercase form with a new buffer,
1082 // we need to delete that buffer before return for error
1083 const ushort *uc = reinterpret_cast<const ushort *>(str);
1084 if (hasCaseChange(si) && uc != upperCased)
1088 num_glyphs = layoutData->glyphLayout.numGlyphs - layoutData->used;
1090 QGlyphLayout g = availableGlyphs(&si);
1091 unsigned short *log_clusters = logClusters(&si);
1093 if (fe->stringToCMap(str,
1098 heuristicSetGlyphAttributes(str, len, &g, log_clusters, num_glyphs);
1103 si.num_glyphs = num_glyphs;
1105 layoutData->used += si.num_glyphs;
1107 const ushort *uc = reinterpret_cast<const ushort *>(str);
1108 if (hasCaseChange(si) && uc != upperCased)
1113 static inline void moveGlyphData(const QGlyphLayout &destination, const QGlyphLayout &source, int num)
1115 if (num > 0 && destination.glyphs != source.glyphs) {
1116 memmove(destination.glyphs, source.glyphs, num * sizeof(HB_Glyph));
1117 memmove(destination.attributes, source.attributes, num * sizeof(HB_GlyphAttributes));
1118 memmove(destination.advances_x, source.advances_x, num * sizeof(HB_Fixed));
1119 memmove(destination.offsets, source.offsets, num * sizeof(HB_FixedPoint));
1123 /// take the item from layoutData->items and
1124 void QTextEngine::shapeTextWithHarfbuzz(int item) const
1126 Q_ASSERT(sizeof(HB_Fixed) == sizeof(QFixed));
1127 Q_ASSERT(sizeof(HB_FixedPoint) == sizeof(QFixedPoint));
1129 QScriptItem &si = layoutData->items[item];
1131 si.glyph_data_offset = layoutData->used;
1133 QFontEngine *font = fontEngine(si, &si.ascent, &si.descent, &si.leading);
1135 bool kerningEnabled = this->font(si).d->kerning;
1137 HB_ShaperItem entire_shaper_item;
1138 qMemSet(&entire_shaper_item, 0, sizeof(entire_shaper_item));
1139 entire_shaper_item.string = reinterpret_cast<const HB_UChar16 *>(layoutData->string.constData());
1140 entire_shaper_item.stringLength = layoutData->string.length();
1141 entire_shaper_item.item.script = (HB_Script)si.analysis.script;
1142 entire_shaper_item.item.pos = si.position;
1143 entire_shaper_item.item.length = length(item);
1144 entire_shaper_item.item.bidiLevel = si.analysis.bidiLevel;
1146 HB_UChar16 upperCased[256]; // XXX what about making this 4096, so we don't have to extend it ever.
1147 if (hasCaseChange(si)) {
1148 HB_UChar16 *uc = upperCased;
1149 if (entire_shaper_item.item.length > 256)
1150 uc = new HB_UChar16[entire_shaper_item.item.length];
1151 for (uint i = 0; i < entire_shaper_item.item.length; ++i) {
1152 if(si.analysis.flags == QScriptAnalysis::Lowercase)
1153 uc[i] = QChar::toLower(entire_shaper_item.string[si.position + i]);
1155 uc[i] = QChar::toUpper(entire_shaper_item.string[si.position + i]);
1157 entire_shaper_item.item.pos = 0;
1158 entire_shaper_item.string = uc;
1159 entire_shaper_item.stringLength = entire_shaper_item.item.length;
1162 entire_shaper_item.shaperFlags = 0;
1163 if (!kerningEnabled)
1164 entire_shaper_item.shaperFlags |= HB_ShaperFlag_NoKerning;
1165 if (option.useDesignMetrics())
1166 entire_shaper_item.shaperFlags |= HB_ShaperFlag_UseDesignMetrics;
1168 entire_shaper_item.num_glyphs = qMax(layoutData->glyphLayout.numGlyphs - layoutData->used, int(entire_shaper_item.item.length));
1169 if (! ensureSpace(entire_shaper_item.num_glyphs)) {
1170 if (hasCaseChange(si))
1171 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1174 QGlyphLayout initialGlyphs = availableGlyphs(&si).mid(0, entire_shaper_item.num_glyphs);
1176 if (!stringToGlyphs(&entire_shaper_item, &initialGlyphs, font)) {
1177 if (! ensureSpace(entire_shaper_item.num_glyphs)) {
1178 if (hasCaseChange(si))
1179 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1182 initialGlyphs = availableGlyphs(&si).mid(0, entire_shaper_item.num_glyphs);
1184 if (!stringToGlyphs(&entire_shaper_item, &initialGlyphs, font)) {
1185 // ############ if this happens there's a bug in the fontengine
1186 if (hasCaseChange(si) && entire_shaper_item.string != upperCased)
1187 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1192 // split up the item into parts that come from different font engines.
1193 QVarLengthArray<int> itemBoundaries(2);
1194 // k * 2 entries, array[k] == index in string, array[k + 1] == index in glyphs
1195 itemBoundaries[0] = entire_shaper_item.item.pos;
1196 itemBoundaries[1] = 0;
1198 if (font->type() == QFontEngine::Multi) {
1199 uint lastEngine = 0;
1200 int charIdx = entire_shaper_item.item.pos;
1201 const int stringEnd = charIdx + entire_shaper_item.item.length;
1202 for (quint32 i = 0; i < entire_shaper_item.num_glyphs; ++i, ++charIdx) {
1203 uint engineIdx = initialGlyphs.glyphs[i] >> 24;
1204 if (engineIdx != lastEngine && i > 0) {
1205 itemBoundaries.append(charIdx);
1206 itemBoundaries.append(i);
1208 lastEngine = engineIdx;
1209 if (HB_IsHighSurrogate(entire_shaper_item.string[charIdx])
1210 && charIdx < stringEnd - 1
1211 && HB_IsLowSurrogate(entire_shaper_item.string[charIdx + 1]))
1218 int remaining_glyphs = entire_shaper_item.num_glyphs;
1220 // for each item shape using harfbuzz and store the results in our layoutData's glyphs array.
1221 for (int k = 0; k < itemBoundaries.size(); k += 2) { // for the +2, see the comment at the definition of itemBoundaries
1223 HB_ShaperItem shaper_item = entire_shaper_item;
1225 shaper_item.item.pos = itemBoundaries[k];
1226 if (k < itemBoundaries.size() - 3) {
1227 shaper_item.item.length = itemBoundaries[k + 2] - shaper_item.item.pos;
1228 shaper_item.num_glyphs = itemBoundaries[k + 3] - itemBoundaries[k + 1];
1229 } else { // last combo in the list, avoid out of bounds access.
1230 shaper_item.item.length -= shaper_item.item.pos - entire_shaper_item.item.pos;
1231 shaper_item.num_glyphs -= itemBoundaries[k + 1];
1233 shaper_item.initialGlyphCount = shaper_item.num_glyphs;
1234 if (shaper_item.num_glyphs < shaper_item.item.length)
1235 shaper_item.num_glyphs = shaper_item.item.length;
1237 QFontEngine *actualFontEngine = font;
1239 if (font->type() == QFontEngine::Multi) {
1240 engineIdx = uint(availableGlyphs(&si).glyphs[glyph_pos] >> 24);
1242 actualFontEngine = static_cast<QFontEngineMulti *>(font)->engine(engineIdx);
1245 shaper_item.font = actualFontEngine->harfbuzzFont();
1246 shaper_item.face = actualFontEngine->harfbuzzFace();
1248 shaper_item.glyphIndicesPresent = true;
1250 remaining_glyphs -= shaper_item.initialGlyphCount;
1253 if (! ensureSpace(glyph_pos + shaper_item.num_glyphs + remaining_glyphs)) {
1254 if (hasCaseChange(si))
1255 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1259 const QGlyphLayout g = availableGlyphs(&si).mid(glyph_pos);
1260 if (shaper_item.num_glyphs > shaper_item.item.length)
1261 moveGlyphData(g.mid(shaper_item.num_glyphs), g.mid(shaper_item.initialGlyphCount), remaining_glyphs);
1263 shaper_item.glyphs = g.glyphs;
1264 shaper_item.attributes = g.attributes;
1265 shaper_item.advances = reinterpret_cast<HB_Fixed *>(g.advances_x);
1266 shaper_item.offsets = reinterpret_cast<HB_FixedPoint *>(g.offsets);
1268 if (shaper_item.glyphIndicesPresent) {
1269 for (hb_uint32 i = 0; i < shaper_item.initialGlyphCount; ++i)
1270 shaper_item.glyphs[i] &= 0x00ffffff;
1273 shaper_item.log_clusters = logClusters(&si) + shaper_item.item.pos - entire_shaper_item.item.pos;
1275 // qDebug(" .. num_glyphs=%d, used=%d, item.num_glyphs=%d", num_glyphs, used, shaper_item.num_glyphs);
1276 } while (!qShapeItem(&shaper_item)); // this does the actual shaping via harfbuzz.
1278 QGlyphLayout g = availableGlyphs(&si).mid(glyph_pos, shaper_item.num_glyphs);
1279 moveGlyphData(g.mid(shaper_item.num_glyphs), g.mid(shaper_item.initialGlyphCount), remaining_glyphs);
1281 for (hb_uint32 i = 0; i < shaper_item.num_glyphs; ++i)
1282 g.glyphs[i] = g.glyphs[i] | (engineIdx << 24);
1284 for (hb_uint32 i = 0; i < shaper_item.item.length; ++i)
1285 shaper_item.log_clusters[i] += glyph_pos;
1287 if (kerningEnabled && !shaper_item.kerning_applied)
1288 font->doKerning(&g, option.useDesignMetrics() ? QFlag(QTextEngine::DesignMetrics) : QFlag(0));
1290 glyph_pos += shaper_item.num_glyphs;
1293 // qDebug(" -> item: script=%d num_glyphs=%d", shaper_item.script, shaper_item.num_glyphs);
1294 si.num_glyphs = glyph_pos;
1296 layoutData->used += si.num_glyphs;
1298 if (hasCaseChange(si) && entire_shaper_item.string != upperCased)
1299 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1302 static void init(QTextEngine *e)
1304 e->ignoreBidi = false;
1305 e->cacheGlyphs = false;
1306 e->forceJustification = false;
1307 e->visualMovement = false;
1314 e->underlinePositions = 0;
1316 e->stackEngine = false;
1319 QTextEngine::QTextEngine()
1324 QTextEngine::QTextEngine(const QString &str, const QFont &f)
1331 QTextEngine::~QTextEngine()
1338 const HB_CharAttributes *QTextEngine::attributes() const
1340 if (layoutData && layoutData->haveCharAttributes)
1341 return (HB_CharAttributes *) layoutData->memory;
1344 if (! ensureSpace(layoutData->string.length()))
1347 QVarLengthArray<HB_ScriptItem> hbScriptItems(layoutData->items.size());
1349 for (int i = 0; i < layoutData->items.size(); ++i) {
1350 const QScriptItem &si = layoutData->items[i];
1351 hbScriptItems[i].pos = si.position;
1352 hbScriptItems[i].length = length(i);
1353 hbScriptItems[i].bidiLevel = si.analysis.bidiLevel;
1354 hbScriptItems[i].script = (HB_Script)si.analysis.script;
1357 qGetCharAttributes(reinterpret_cast<const HB_UChar16 *>(layoutData->string.constData()),
1358 layoutData->string.length(),
1359 hbScriptItems.data(), hbScriptItems.size(),
1360 (HB_CharAttributes *)layoutData->memory);
1363 layoutData->haveCharAttributes = true;
1364 return (HB_CharAttributes *) layoutData->memory;
1367 void QTextEngine::shape(int item) const
1369 if (layoutData->items[item].analysis.flags == QScriptAnalysis::Object) {
1371 if (block.docHandle()) {
1372 QTextFormat format = formats()->format(formatIndex(&layoutData->items[item]));
1373 docLayout()->resizeInlineObject(QTextInlineObject(item, const_cast<QTextEngine *>(this)),
1374 layoutData->items[item].position + block.position(), format);
1376 } else if (layoutData->items[item].analysis.flags == QScriptAnalysis::Tab) {
1377 // set up at least the ascent/descent/leading of the script item for the tab
1378 fontEngine(layoutData->items[item],
1379 &layoutData->items[item].ascent,
1380 &layoutData->items[item].descent,
1381 &layoutData->items[item].leading);
1387 static inline void releaseCachedFontEngine(QFontEngine *fontEngine)
1390 fontEngine->ref.deref();
1391 if (fontEngine->cache_count == 0 && fontEngine->ref == 0)
1396 void QTextEngine::invalidate()
1402 specialData->resolvedFormatIndices.clear();
1404 releaseCachedFontEngine(feCache.prevFontEngine);
1405 releaseCachedFontEngine(feCache.prevScaledFontEngine);
1409 void QTextEngine::clearLineData()
1414 void QTextEngine::validate() const
1418 layoutData = new LayoutData();
1419 if (block.docHandle()) {
1420 layoutData->string = block.text();
1421 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators)
1422 layoutData->string += QLatin1Char(block.next().isValid() ? 0xb6 : 0x20);
1424 layoutData->string = text;
1426 if (specialData && specialData->preeditPosition != -1)
1427 layoutData->string.insert(specialData->preeditPosition, specialData->preeditText);
1430 void QTextEngine::itemize() const
1433 if (layoutData->items.size())
1436 int length = layoutData->string.length();
1439 #if defined(Q_WS_MAC) && !defined(QT_MAC_USE_COCOA)
1440 // ATSUI requires RTL flags to correctly identify the character stops.
1441 bool ignore = false;
1443 bool ignore = ignoreBidi;
1446 bool rtl = isRightToLeft();
1448 if (!ignore && !rtl) {
1450 const QChar *start = layoutData->string.unicode();
1451 const QChar * const end = start + length;
1452 while (start < end) {
1453 if (start->unicode() >= 0x590) {
1461 QVarLengthArray<QScriptAnalysis, 4096> scriptAnalysis(length);
1462 QScriptAnalysis *analysis = scriptAnalysis.data();
1464 QBidiControl control(rtl);
1467 memset(analysis, 0, length*sizeof(QScriptAnalysis));
1468 if (option.textDirection() == Qt::RightToLeft) {
1469 for (int i = 0; i < length; ++i)
1470 analysis[i].bidiLevel = 1;
1471 layoutData->hasBidi = true;
1474 layoutData->hasBidi = bidiItemize(const_cast<QTextEngine *>(this), analysis, control);
1477 const ushort *uc = reinterpret_cast<const ushort *>(layoutData->string.unicode());
1478 const ushort *e = uc + length;
1479 int lastScript = QUnicodeTables::Common;
1481 int script = QUnicodeTables::script(*uc);
1482 if (script == QUnicodeTables::Inherited)
1483 script = lastScript;
1484 analysis->flags = QScriptAnalysis::None;
1485 if (*uc == QChar::ObjectReplacementCharacter) {
1486 if (analysis->bidiLevel % 2)
1487 --analysis->bidiLevel;
1488 analysis->script = QUnicodeTables::Common;
1489 analysis->flags = QScriptAnalysis::Object;
1490 } else if (*uc == QChar::LineSeparator) {
1491 if (analysis->bidiLevel % 2)
1492 --analysis->bidiLevel;
1493 analysis->script = QUnicodeTables::Common;
1494 analysis->flags = QScriptAnalysis::LineOrParagraphSeparator;
1495 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators)
1496 *const_cast<ushort*>(uc) = 0x21B5; // visual line separator
1497 } else if (*uc == 9) {
1498 analysis->script = QUnicodeTables::Common;
1499 analysis->flags = QScriptAnalysis::Tab;
1500 analysis->bidiLevel = control.baseLevel();
1501 } else if ((*uc == 32 || *uc == QChar::Nbsp)
1502 && (option.flags() & QTextOption::ShowTabsAndSpaces)) {
1503 analysis->script = QUnicodeTables::Common;
1504 analysis->flags = QScriptAnalysis::Space;
1505 analysis->bidiLevel = control.baseLevel();
1507 analysis->script = script;
1509 lastScript = analysis->script;
1513 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators) {
1514 (analysis-1)->flags = QScriptAnalysis::LineOrParagraphSeparator; // to exclude it from width
1517 Itemizer itemizer(layoutData->string, scriptAnalysis.data(), layoutData->items);
1519 const QTextDocumentPrivate *p = block.docHandle();
1521 SpecialData *s = specialData;
1523 QTextDocumentPrivate::FragmentIterator it = p->find(block.position());
1524 QTextDocumentPrivate::FragmentIterator end = p->find(block.position() + block.length() - 1); // -1 to omit the block separator char
1525 int format = it.value()->format;
1527 int prevPosition = 0;
1528 int position = prevPosition;
1530 const QTextFragmentData * const frag = it.value();
1531 if (it == end || format != frag->format) {
1532 if (s && position >= s->preeditPosition) {
1533 position += s->preeditText.length();
1536 Q_ASSERT(position <= length);
1537 itemizer.generate(prevPosition, position - prevPosition,
1538 formats()->charFormat(format).fontCapitalization());
1540 if (position < length)
1541 itemizer.generate(position, length - position,
1542 formats()->charFormat(format).fontCapitalization());
1545 format = frag->format;
1546 prevPosition = position;
1548 position += frag->size_array[0];
1552 itemizer.generate(0, length, static_cast<QFont::Capitalization> (fnt.d->capital));
1555 addRequiredBoundaries();
1556 resolveAdditionalFormats();
1559 bool QTextEngine::isRightToLeft() const
1561 switch (option.textDirection()) {
1562 case Qt::LeftToRight:
1564 case Qt::RightToLeft:
1569 // this places the cursor in the right position depending on the keyboard layout
1570 if (layoutData->string.isEmpty())
1571 return QApplication::keyboardInputDirection() == Qt::RightToLeft;
1572 return layoutData->string.isRightToLeft();
1576 int QTextEngine::findItem(int strPos) const
1580 int right = layoutData->items.size()-1;
1581 while(left <= right) {
1582 int middle = ((right-left)/2)+left;
1583 if (strPos > layoutData->items[middle].position)
1585 else if(strPos < layoutData->items[middle].position)
1594 QFixed QTextEngine::width(int from, int len) const
1600 // qDebug("QTextEngine::width(from = %d, len = %d), numItems=%d, strleng=%d", from, len, items.size(), string.length());
1601 for (int i = 0; i < layoutData->items.size(); i++) {
1602 const QScriptItem *si = layoutData->items.constData() + i;
1603 int pos = si->position;
1604 int ilen = length(i);
1605 // qDebug("item %d: from %d len %d", i, pos, ilen);
1606 if (pos >= from + len)
1608 if (pos + ilen > from) {
1609 if (!si->num_glyphs)
1612 if (si->analysis.flags == QScriptAnalysis::Object) {
1615 } else if (si->analysis.flags == QScriptAnalysis::Tab) {
1616 w += calculateTabWidth(i, w);
1621 QGlyphLayout glyphs = shapedGlyphs(si);
1622 unsigned short *logClusters = this->logClusters(si);
1624 // fprintf(stderr, " logclusters:");
1625 // for (int k = 0; k < ilen; k++)
1626 // fprintf(stderr, " %d", logClusters[k]);
1627 // fprintf(stderr, "\n");
1628 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1629 int charFrom = from - pos;
1632 int glyphStart = logClusters[charFrom];
1633 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1634 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1636 if (charFrom < ilen) {
1637 glyphStart = logClusters[charFrom];
1638 int charEnd = from + len - 1 - pos;
1639 if (charEnd >= ilen)
1641 int glyphEnd = logClusters[charEnd];
1642 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1644 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1646 // qDebug("char: start=%d end=%d / glyph: start = %d, end = %d", charFrom, charEnd, glyphStart, glyphEnd);
1647 for (int i = glyphStart; i < glyphEnd; i++)
1648 w += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
1652 // qDebug(" --> w= %d ", w);
1656 glyph_metrics_t QTextEngine::boundingBox(int from, int len) const
1662 for (int i = 0; i < layoutData->items.size(); i++) {
1663 const QScriptItem *si = layoutData->items.constData() + i;
1665 int pos = si->position;
1666 int ilen = length(i);
1667 if (pos > from + len)
1669 if (pos + ilen > from) {
1670 if (!si->num_glyphs)
1673 if (si->analysis.flags == QScriptAnalysis::Object) {
1674 gm.width += si->width;
1676 } else if (si->analysis.flags == QScriptAnalysis::Tab) {
1677 gm.width += calculateTabWidth(i, gm.width);
1681 unsigned short *logClusters = this->logClusters(si);
1682 QGlyphLayout glyphs = shapedGlyphs(si);
1684 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1685 int charFrom = from - pos;
1688 int glyphStart = logClusters[charFrom];
1689 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1690 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1692 if (charFrom < ilen) {
1693 QFontEngine *fe = fontEngine(*si);
1694 glyphStart = logClusters[charFrom];
1695 int charEnd = from + len - 1 - pos;
1696 if (charEnd >= ilen)
1698 int glyphEnd = logClusters[charEnd];
1699 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1701 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1702 if (glyphStart <= glyphEnd ) {
1703 glyph_metrics_t m = fe->boundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
1704 gm.x = qMin(gm.x, m.x + gm.xoff);
1705 gm.y = qMin(gm.y, m.y + gm.yoff);
1706 gm.width = qMax(gm.width, m.width+gm.xoff);
1707 gm.height = qMax(gm.height, m.height+gm.yoff);
1717 glyph_metrics_t QTextEngine::tightBoundingBox(int from, int len) const
1723 for (int i = 0; i < layoutData->items.size(); i++) {
1724 const QScriptItem *si = layoutData->items.constData() + i;
1725 int pos = si->position;
1726 int ilen = length(i);
1727 if (pos > from + len)
1729 if (pos + len > from) {
1730 if (!si->num_glyphs)
1732 unsigned short *logClusters = this->logClusters(si);
1733 QGlyphLayout glyphs = shapedGlyphs(si);
1735 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1736 int charFrom = from - pos;
1739 int glyphStart = logClusters[charFrom];
1740 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1741 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1743 if (charFrom < ilen) {
1744 glyphStart = logClusters[charFrom];
1745 int charEnd = from + len - 1 - pos;
1746 if (charEnd >= ilen)
1748 int glyphEnd = logClusters[charEnd];
1749 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1751 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1752 if (glyphStart <= glyphEnd ) {
1753 QFontEngine *fe = fontEngine(*si);
1754 glyph_metrics_t m = fe->tightBoundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
1755 gm.x = qMin(gm.x, m.x + gm.xoff);
1756 gm.y = qMin(gm.y, m.y + gm.yoff);
1757 gm.width = qMax(gm.width, m.width+gm.xoff);
1758 gm.height = qMax(gm.height, m.height+gm.yoff);
1768 QFont QTextEngine::font(const QScriptItem &si) const
1772 QTextCharFormat f = format(&si);
1775 if (block.docHandle() && block.docHandle()->layout()) {
1776 // Make sure we get the right dpi on printers
1777 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
1779 font = QFont(font, pdev);
1781 font = font.resolve(fnt);
1783 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
1784 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
1785 if (font.pointSize() != -1)
1786 font.setPointSize((font.pointSize() * 2) / 3);
1788 font.setPixelSize((font.pixelSize() * 2) / 3);
1792 if (si.analysis.flags == QScriptAnalysis::SmallCaps)
1793 font = font.d->smallCapsFont();
1798 QTextEngine::FontEngineCache::FontEngineCache()
1803 //we cache the previous results of this function, as calling it numerous times with the same effective
1804 //input is common (and hard to cache at a higher level)
1805 QFontEngine *QTextEngine::fontEngine(const QScriptItem &si, QFixed *ascent, QFixed *descent, QFixed *leading) const
1807 QFontEngine *engine = 0;
1808 QFontEngine *scaledEngine = 0;
1809 int script = si.analysis.script;
1813 if (feCache.prevFontEngine && feCache.prevPosition == si.position && feCache.prevLength == length(&si) && feCache.prevScript == script) {
1814 engine = feCache.prevFontEngine;
1815 scaledEngine = feCache.prevScaledFontEngine;
1817 QTextCharFormat f = format(&si);
1820 if (block.docHandle() && block.docHandle()->layout()) {
1821 // Make sure we get the right dpi on printers
1822 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
1824 font = QFont(font, pdev);
1826 font = font.resolve(fnt);
1828 engine = font.d->engineForScript(script);
1829 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
1830 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
1831 if (font.pointSize() != -1)
1832 font.setPointSize((font.pointSize() * 2) / 3);
1834 font.setPixelSize((font.pixelSize() * 2) / 3);
1835 scaledEngine = font.d->engineForScript(script);
1837 feCache.prevFontEngine = engine;
1840 feCache.prevScaledFontEngine = scaledEngine;
1842 scaledEngine->ref.ref();
1843 feCache.prevScript = script;
1844 feCache.prevPosition = si.position;
1845 feCache.prevLength = length(&si);
1848 if (feCache.prevFontEngine && feCache.prevScript == script && feCache.prevPosition == -1)
1849 engine = feCache.prevFontEngine;
1851 engine = font.d->engineForScript(script);
1852 feCache.prevFontEngine = engine;
1855 feCache.prevScript = script;
1856 feCache.prevPosition = -1;
1857 feCache.prevLength = -1;
1858 feCache.prevScaledFontEngine = 0;
1862 if (si.analysis.flags == QScriptAnalysis::SmallCaps) {
1863 QFontPrivate *p = font.d->smallCapsFontPrivate();
1864 scaledEngine = p->engineForScript(script);
1868 *ascent = engine->ascent();
1869 *descent = engine->descent();
1870 *leading = engine->leading();
1874 return scaledEngine;
1878 struct QJustificationPoint {
1880 QFixed kashidaWidth;
1882 QFontEngine *fontEngine;
1885 Q_DECLARE_TYPEINFO(QJustificationPoint, Q_PRIMITIVE_TYPE);
1887 static void set(QJustificationPoint *point, int type, const QGlyphLayout &glyph, QFontEngine *fe)
1890 point->glyph = glyph;
1891 point->fontEngine = fe;
1893 if (type >= HB_Arabic_Normal) {
1894 QChar ch(0x640); // Kashida character
1895 QGlyphLayoutArray<8> glyphs;
1897 fe->stringToCMap(&ch, 1, &glyphs, &nglyphs, 0);
1898 if (glyphs.glyphs[0] && glyphs.advances_x[0] != 0) {
1899 point->kashidaWidth = glyphs.advances_x[0];
1901 point->type = HB_NoJustification;
1902 point->kashidaWidth = 0;
1908 void QTextEngine::justify(const QScriptLine &line)
1910 // qDebug("justify: line.gridfitted = %d, line.justified=%d", line.gridfitted, line.justified);
1911 if (line.gridfitted && line.justified)
1914 if (!line.gridfitted) {
1915 // redo layout in device metrics, then adjust
1916 const_cast<QScriptLine &>(line).gridfitted = true;
1919 if ((option.alignment() & Qt::AlignHorizontal_Mask) != Qt::AlignJustify)
1924 if (!forceJustification) {
1925 int end = line.from + (int)line.length;
1926 if (end == layoutData->string.length())
1927 return; // no justification at end of paragraph
1928 if (end && layoutData->items[findItem(end-1)].analysis.flags == QScriptAnalysis::LineOrParagraphSeparator)
1929 return; // no justification at the end of an explicitly separated line
1935 // don't include trailing white spaces when doing justification
1936 int line_length = line.length;
1937 const HB_CharAttributes *a = attributes();
1941 while (line_length && a[line_length-1].whiteSpace)
1943 // subtract one char more, as we can't justfy after the last character
1949 int firstItem = findItem(line.from);
1950 int nItems = findItem(line.from + line_length - 1) - firstItem + 1;
1952 QVarLengthArray<QJustificationPoint> justificationPoints;
1954 // 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());
1955 QFixed minKashida = 0x100000;
1957 // we need to do all shaping before we go into the next loop, as we there
1958 // store pointers to the glyph data that could get reallocated by the shaping
1960 for (int i = 0; i < nItems; ++i) {
1961 QScriptItem &si = layoutData->items[firstItem + i];
1963 shape(firstItem + i);
1966 for (int i = 0; i < nItems; ++i) {
1967 QScriptItem &si = layoutData->items[firstItem + i];
1969 int kashida_type = HB_Arabic_Normal;
1970 int kashida_pos = -1;
1972 int start = qMax(line.from - si.position, 0);
1973 int end = qMin(line.from + line_length - (int)si.position, length(firstItem+i));
1975 unsigned short *log_clusters = logClusters(&si);
1977 int gs = log_clusters[start];
1978 int ge = (end == length(firstItem+i) ? si.num_glyphs : log_clusters[end]);
1980 const QGlyphLayout g = shapedGlyphs(&si);
1982 for (int i = gs; i < ge; ++i) {
1983 g.justifications[i].type = QGlyphJustification::JustifyNone;
1984 g.justifications[i].nKashidas = 0;
1985 g.justifications[i].space_18d6 = 0;
1987 justificationPoints.resize(nPoints+3);
1988 int justification = g.attributes[i].justification;
1990 switch(justification) {
1991 case HB_NoJustification:
1995 case HB_Arabic_Space :
1996 if (kashida_pos >= 0) {
1997 // qDebug("kashida position at %d in word", kashida_pos);
1998 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
1999 if (justificationPoints[nPoints].kashidaWidth > 0) {
2000 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
2001 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
2006 kashida_type = HB_Arabic_Normal;
2009 set(&justificationPoints[nPoints++], justification, g.mid(i), fontEngine(si));
2010 maxJustify = qMax(maxJustify, justification);
2012 case HB_Arabic_Normal :
2013 case HB_Arabic_Waw :
2014 case HB_Arabic_BaRa :
2015 case HB_Arabic_Alef :
2016 case HB_Arabic_HaaDal :
2017 case HB_Arabic_Seen :
2018 case HB_Arabic_Kashida :
2019 if (justification >= kashida_type) {
2021 kashida_type = justification;
2025 if (kashida_pos >= 0) {
2026 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
2027 if (justificationPoints[nPoints].kashidaWidth > 0) {
2028 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
2029 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
2035 QFixed need = line.width - line.textWidth;
2037 // line overflows already!
2038 const_cast<QScriptLine &>(line).justified = true;
2042 // qDebug("doing justification: textWidth=%x, requested=%x, maxJustify=%d", line.textWidth.value(), line.width.value(), maxJustify);
2043 // qDebug(" minKashida=%f, need=%f", minKashida.toReal(), need.toReal());
2045 // distribute in priority order
2046 if (maxJustify >= HB_Arabic_Normal) {
2047 while (need >= minKashida) {
2048 for (int type = maxJustify; need >= minKashida && type >= HB_Arabic_Normal; --type) {
2049 for (int i = 0; need >= minKashida && i < nPoints; ++i) {
2050 if (justificationPoints[i].type == type && justificationPoints[i].kashidaWidth <= need) {
2051 justificationPoints[i].glyph.justifications->nKashidas++;
2053 justificationPoints[i].glyph.justifications->space_18d6 += justificationPoints[i].kashidaWidth.value();
2054 need -= justificationPoints[i].kashidaWidth;
2055 // qDebug("adding kashida type %d with width %x, neednow %x", type, justificationPoints[i].kashidaWidth, need.value());
2061 Q_ASSERT(need >= 0);
2065 maxJustify = qMin(maxJustify, (int)HB_Space);
2066 for (int type = maxJustify; need != 0 && type > 0; --type) {
2068 for (int i = 0; i < nPoints; ++i) {
2069 if (justificationPoints[i].type == type)
2072 // qDebug("number of points for justification type %d: %d", type, n);
2078 for (int i = 0; i < nPoints; ++i) {
2079 if (justificationPoints[i].type == type) {
2080 QFixed add = need/n;
2081 // qDebug("adding %x to glyph %x", add.value(), justificationPoints[i].glyph->glyph);
2082 justificationPoints[i].glyph.justifications[0].space_18d6 = add.value();
2091 const_cast<QScriptLine &>(line).justified = true;
2094 void QScriptLine::setDefaultHeight(QTextEngine *eng)
2099 if (eng->block.docHandle() && eng->block.docHandle()->layout()) {
2100 f = eng->block.charFormat().font();
2101 // Make sure we get the right dpi on printers
2102 QPaintDevice *pdev = eng->block.docHandle()->layout()->paintDevice();
2105 e = f.d->engineForScript(QUnicodeTables::Common);
2107 e = eng->fnt.d->engineForScript(QUnicodeTables::Common);
2110 QFixed other_ascent = e->ascent();
2111 QFixed other_descent = e->descent();
2112 QFixed other_leading = e->leading();
2113 leading = qMax(leading + ascent, other_leading + other_ascent) - qMax(ascent, other_ascent);
2114 ascent = qMax(ascent, other_ascent);
2115 descent = qMax(descent, other_descent);
2118 QTextEngine::LayoutData::LayoutData()
2122 memory_on_stack = false;
2125 layoutState = LayoutEmpty;
2126 haveCharAttributes = false;
2128 available_glyphs = 0;
2131 QTextEngine::LayoutData::LayoutData(const QString &str, void **stack_memory, int _allocated)
2134 allocated = _allocated;
2136 int space_charAttributes = sizeof(HB_CharAttributes)*string.length()/sizeof(void*) + 1;
2137 int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2138 available_glyphs = ((int)allocated - space_charAttributes - space_logClusters)*(int)sizeof(void*)/(int)QGlyphLayout::spaceNeededForGlyphLayout(1);
2140 if (available_glyphs < str.length()) {
2141 // need to allocate on the heap
2144 memory_on_stack = false;
2148 memory_on_stack = true;
2149 memory = stack_memory;
2150 logClustersPtr = (unsigned short *)(memory + space_charAttributes);
2152 void *m = memory + space_charAttributes + space_logClusters;
2153 glyphLayout = QGlyphLayout(reinterpret_cast<char *>(m), str.length());
2154 glyphLayout.clear();
2155 memset(memory, 0, space_charAttributes*sizeof(void *));
2159 layoutState = LayoutEmpty;
2160 haveCharAttributes = false;
2163 QTextEngine::LayoutData::~LayoutData()
2165 if (!memory_on_stack)
2170 bool QTextEngine::LayoutData::reallocate(int totalGlyphs)
2172 Q_ASSERT(totalGlyphs >= glyphLayout.numGlyphs);
2173 if (memory_on_stack && available_glyphs >= totalGlyphs) {
2174 glyphLayout.grow(glyphLayout.data(), totalGlyphs);
2178 int space_charAttributes = sizeof(HB_CharAttributes)*string.length()/sizeof(void*) + 1;
2179 int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2180 int space_glyphs = QGlyphLayout::spaceNeededForGlyphLayout(totalGlyphs)/sizeof(void*) + 2;
2182 int newAllocated = space_charAttributes + space_glyphs + space_logClusters;
2183 // These values can be negative if the length of string/glyphs causes overflow,
2184 // we can't layout such a long string all at once, so return false here to
2185 // indicate there is a failure
2186 if (space_charAttributes < 0 || space_logClusters < 0 || space_glyphs < 0 || newAllocated < allocated) {
2187 layoutState = LayoutFailed;
2191 void **newMem = memory;
2192 newMem = (void **)::realloc(memory_on_stack ? 0 : memory, newAllocated*sizeof(void *));
2194 layoutState = LayoutFailed;
2197 if (memory_on_stack)
2198 memcpy(newMem, memory, allocated*sizeof(void *));
2200 memory_on_stack = false;
2203 m += space_charAttributes;
2204 logClustersPtr = (unsigned short *) m;
2205 m += space_logClusters;
2207 const int space_preGlyphLayout = space_charAttributes + space_logClusters;
2208 if (allocated < space_preGlyphLayout)
2209 memset(memory + allocated, 0, (space_preGlyphLayout - allocated)*sizeof(void *));
2211 glyphLayout.grow(reinterpret_cast<char *>(m), totalGlyphs);
2213 allocated = newAllocated;
2217 // grow to the new size, copying the existing data to the new layout
2218 void QGlyphLayout::grow(char *address, int totalGlyphs)
2220 QGlyphLayout oldLayout(address, numGlyphs);
2221 QGlyphLayout newLayout(address, totalGlyphs);
2224 // move the existing data
2225 memmove(newLayout.attributes, oldLayout.attributes, numGlyphs * sizeof(HB_GlyphAttributes));
2226 memmove(newLayout.justifications, oldLayout.justifications, numGlyphs * sizeof(QGlyphJustification));
2227 memmove(newLayout.advances_y, oldLayout.advances_y, numGlyphs * sizeof(QFixed));
2228 memmove(newLayout.advances_x, oldLayout.advances_x, numGlyphs * sizeof(QFixed));
2229 memmove(newLayout.glyphs, oldLayout.glyphs, numGlyphs * sizeof(HB_Glyph));
2232 // clear the new data
2233 newLayout.clear(numGlyphs);
2238 void QTextEngine::freeMemory()
2244 layoutData->used = 0;
2245 layoutData->hasBidi = false;
2246 layoutData->layoutState = LayoutEmpty;
2247 layoutData->haveCharAttributes = false;
2249 for (int i = 0; i < lines.size(); ++i) {
2250 lines[i].justified = 0;
2251 lines[i].gridfitted = 0;
2255 int QTextEngine::formatIndex(const QScriptItem *si) const
2257 if (specialData && !specialData->resolvedFormatIndices.isEmpty())
2258 return specialData->resolvedFormatIndices.at(si - &layoutData->items[0]);
2259 QTextDocumentPrivate *p = block.docHandle();
2262 int pos = si->position;
2263 if (specialData && si->position >= specialData->preeditPosition) {
2264 if (si->position < specialData->preeditPosition + specialData->preeditText.length())
2265 pos = qMax(specialData->preeditPosition - 1, 0);
2267 pos -= specialData->preeditText.length();
2269 QTextDocumentPrivate::FragmentIterator it = p->find(block.position() + pos);
2270 return it.value()->format;
2274 QTextCharFormat QTextEngine::format(const QScriptItem *si) const
2276 QTextCharFormat format;
2277 const QTextFormatCollection *formats = 0;
2278 if (block.docHandle()) {
2279 formats = this->formats();
2280 format = formats->charFormat(formatIndex(si));
2282 if (specialData && specialData->resolvedFormatIndices.isEmpty()) {
2283 int end = si->position + length(si);
2284 for (int i = 0; i < specialData->addFormats.size(); ++i) {
2285 const QTextLayout::FormatRange &r = specialData->addFormats.at(i);
2286 if (r.start <= si->position && r.start + r.length >= end) {
2287 if (!specialData->addFormatIndices.isEmpty())
2288 format.merge(formats->format(specialData->addFormatIndices.at(i)));
2290 format.merge(r.format);
2297 void QTextEngine::addRequiredBoundaries() const
2300 for (int i = 0; i < specialData->addFormats.size(); ++i) {
2301 const QTextLayout::FormatRange &r = specialData->addFormats.at(i);
2302 setBoundary(r.start);
2303 setBoundary(r.start + r.length);
2304 //qDebug("adding boundaries %d %d", r.start, r.start+r.length);
2309 bool QTextEngine::atWordSeparator(int position) const
2311 const QChar c = layoutData->string.at(position);
2312 switch (c.toLatin1()) {
2349 bool QTextEngine::atSpace(int position) const
2351 const QChar c = layoutData->string.at(position);
2353 return c == QLatin1Char(' ')
2355 || c == QChar::LineSeparator
2356 || c == QLatin1Char('\t')
2361 void QTextEngine::indexAdditionalFormats()
2363 if (!block.docHandle())
2366 specialData->addFormatIndices.resize(specialData->addFormats.count());
2367 QTextFormatCollection * const formats = this->formats();
2369 for (int i = 0; i < specialData->addFormats.count(); ++i) {
2370 specialData->addFormatIndices[i] = formats->indexForFormat(specialData->addFormats.at(i).format);
2371 specialData->addFormats[i].format = QTextCharFormat();
2375 /* These two helper functions are used to determine whether we need to insert a ZWJ character
2376 between the text that gets truncated and the ellipsis. This is important to get
2377 correctly shaped results for arabic text.
2379 static bool nextCharJoins(const QString &string, int pos)
2381 while (pos < string.length() && string.at(pos).category() == QChar::Mark_NonSpacing)
2383 if (pos == string.length())
2385 return string.at(pos).joining() != QChar::OtherJoining;
2388 static bool prevCharJoins(const QString &string, int pos)
2390 while (pos > 0 && string.at(pos - 1).category() == QChar::Mark_NonSpacing)
2394 return (string.at(pos - 1).joining() == QChar::Dual || string.at(pos - 1).joining() == QChar::Center);
2397 QString QTextEngine::elidedText(Qt::TextElideMode mode, const QFixed &width, int flags) const
2399 // qDebug() << "elidedText; available width" << width.toReal() << "text width:" << this->width(0, layoutData->string.length()).toReal();
2401 if (flags & Qt::TextShowMnemonic) {
2403 HB_CharAttributes *attributes = const_cast<HB_CharAttributes *>(this->attributes());
2406 for (int i = 0; i < layoutData->items.size(); ++i) {
2407 QScriptItem &si = layoutData->items[i];
2411 unsigned short *logClusters = this->logClusters(&si);
2412 QGlyphLayout glyphs = shapedGlyphs(&si);
2414 const int end = si.position + length(&si);
2415 for (int i = si.position; i < end - 1; ++i) {
2416 if (layoutData->string.at(i) == QLatin1Char('&')) {
2417 const int gp = logClusters[i - si.position];
2418 glyphs.attributes[gp].dontPrint = true;
2419 attributes[i + 1].charStop = false;
2420 attributes[i + 1].whiteSpace = false;
2421 attributes[i + 1].lineBreakType = HB_NoBreak;
2422 if (layoutData->string.at(i + 1) == QLatin1Char('&'))
2431 if (mode == Qt::ElideNone
2432 || this->width(0, layoutData->string.length()) <= width
2433 || layoutData->string.length() <= 1)
2434 return layoutData->string;
2436 QFixed ellipsisWidth;
2437 QString ellipsisText;
2439 QChar ellipsisChar(0x2026);
2441 QFontEngine *fe = fnt.d->engineForScript(QUnicodeTables::Common);
2443 QGlyphLayoutArray<1> ellipsisGlyph;
2445 QFontEngine *feForEllipsis = (fe->type() == QFontEngine::Multi)
2446 ? static_cast<QFontEngineMulti *>(fe)->engine(0)
2449 if (feForEllipsis->type() == QFontEngine::Mac)
2452 // the lookup can be really slow when we use XLFD fonts
2453 if (feForEllipsis->type() != QFontEngine::XLFD
2454 && feForEllipsis->canRender(&ellipsisChar, 1)) {
2456 feForEllipsis->stringToCMap(&ellipsisChar, 1, &ellipsisGlyph, &nGlyphs, 0);
2460 if (ellipsisGlyph.glyphs[0]) {
2461 ellipsisWidth = ellipsisGlyph.advances_x[0];
2462 ellipsisText = ellipsisChar;
2464 QString dotDotDot(QLatin1String("..."));
2466 QGlyphLayoutArray<3> glyphs;
2468 if (!fe->stringToCMap(dotDotDot.constData(), 3, &glyphs, &nGlyphs, 0))
2469 // should never happen...
2470 return layoutData->string;
2471 for (int i = 0; i < nGlyphs; ++i)
2472 ellipsisWidth += glyphs.advances_x[i];
2473 ellipsisText = dotDotDot;
2477 const QFixed availableWidth = width - ellipsisWidth;
2478 if (availableWidth < 0)
2481 const HB_CharAttributes *attributes = this->attributes();
2485 if (mode == Qt::ElideRight) {
2486 QFixed currentWidth;
2494 while (nextBreak < layoutData->string.length() && !attributes[nextBreak].charStop)
2497 currentWidth += this->width(pos, nextBreak - pos);
2498 } while (nextBreak < layoutData->string.length()
2499 && currentWidth < availableWidth);
2501 if (nextCharJoins(layoutData->string, pos))
2502 ellipsisText.prepend(QChar(0x200d) /* ZWJ */);
2504 return layoutData->string.left(pos) + ellipsisText;
2505 } else if (mode == Qt::ElideLeft) {
2506 QFixed currentWidth;
2508 int nextBreak = layoutData->string.length();
2514 while (nextBreak > 0 && !attributes[nextBreak].charStop)
2517 currentWidth += this->width(nextBreak, pos - nextBreak);
2518 } while (nextBreak > 0
2519 && currentWidth < availableWidth);
2521 if (prevCharJoins(layoutData->string, pos))
2522 ellipsisText.append(QChar(0x200d) /* ZWJ */);
2524 return ellipsisText + layoutData->string.mid(pos);
2525 } else if (mode == Qt::ElideMiddle) {
2530 int nextLeftBreak = 0;
2532 int rightPos = layoutData->string.length();
2533 int nextRightBreak = layoutData->string.length();
2536 leftPos = nextLeftBreak;
2537 rightPos = nextRightBreak;
2540 while (nextLeftBreak < layoutData->string.length() && !attributes[nextLeftBreak].charStop)
2544 while (nextRightBreak > 0 && !attributes[nextRightBreak].charStop)
2547 leftWidth += this->width(leftPos, nextLeftBreak - leftPos);
2548 rightWidth += this->width(nextRightBreak, rightPos - nextRightBreak);
2549 } while (nextLeftBreak < layoutData->string.length()
2550 && nextRightBreak > 0
2551 && leftWidth + rightWidth < availableWidth);
2553 if (nextCharJoins(layoutData->string, leftPos))
2554 ellipsisText.prepend(QChar(0x200d) /* ZWJ */);
2555 if (prevCharJoins(layoutData->string, rightPos))
2556 ellipsisText.append(QChar(0x200d) /* ZWJ */);
2558 return layoutData->string.left(leftPos) + ellipsisText + layoutData->string.mid(rightPos);
2561 return layoutData->string;
2564 void QTextEngine::setBoundary(int strPos) const
2566 if (strPos <= 0 || strPos >= layoutData->string.length())
2569 int itemToSplit = 0;
2570 while (itemToSplit < layoutData->items.size() && layoutData->items.at(itemToSplit).position <= strPos)
2573 if (layoutData->items.at(itemToSplit).position == strPos) {
2574 // already a split at the requested position
2577 splitItem(itemToSplit, strPos - layoutData->items.at(itemToSplit).position);
2580 void QTextEngine::splitItem(int item, int pos) const
2585 layoutData->items.insert(item + 1, layoutData->items[item]);
2586 QScriptItem &oldItem = layoutData->items[item];
2587 QScriptItem &newItem = layoutData->items[item+1];
2588 newItem.position += pos;
2590 if (oldItem.num_glyphs) {
2591 // already shaped, break glyphs aswell
2592 int breakGlyph = logClusters(&oldItem)[pos];
2594 newItem.num_glyphs = oldItem.num_glyphs - breakGlyph;
2595 oldItem.num_glyphs = breakGlyph;
2596 newItem.glyph_data_offset = oldItem.glyph_data_offset + breakGlyph;
2598 for (int i = 0; i < newItem.num_glyphs; i++)
2599 logClusters(&newItem)[i] -= breakGlyph;
2602 const QGlyphLayout g = shapedGlyphs(&oldItem);
2603 for(int j = 0; j < breakGlyph; ++j)
2604 w += g.advances_x[j];
2606 newItem.width = oldItem.width - w;
2610 // qDebug("split at position %d itempos=%d", pos, item);
2613 QFixed QTextEngine::calculateTabWidth(int item, QFixed x) const
2615 const QScriptItem &si = layoutData->items[item];
2617 QFixed dpiScale = 1;
2618 if (block.docHandle() && block.docHandle()->layout()) {
2619 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
2621 dpiScale = QFixed::fromReal(pdev->logicalDpiY() / qreal(qt_defaultDpiY()));
2623 dpiScale = QFixed::fromReal(fnt.d->dpi / qreal(qt_defaultDpiY()));
2626 QList<QTextOption::Tab> tabArray = option.tabs();
2627 if (!tabArray.isEmpty()) {
2628 if (isRightToLeft()) { // rebase the tabArray positions.
2629 QList<QTextOption::Tab> newTabs;
2630 QList<QTextOption::Tab>::Iterator iter = tabArray.begin();
2631 while(iter != tabArray.end()) {
2632 QTextOption::Tab tab = *iter;
2633 if (tab.type == QTextOption::LeftTab)
2634 tab.type = QTextOption::RightTab;
2635 else if (tab.type == QTextOption::RightTab)
2636 tab.type = QTextOption::LeftTab;
2642 for (int i = 0; i < tabArray.size(); ++i) {
2643 QFixed tab = QFixed::fromReal(tabArray[i].position) * dpiScale;
2644 if (tab > x) { // this is the tab we need.
2645 QTextOption::Tab tabSpec = tabArray[i];
2646 int tabSectionEnd = layoutData->string.count();
2647 if (tabSpec.type == QTextOption::RightTab || tabSpec.type == QTextOption::CenterTab) {
2648 // find next tab to calculate the width required.
2649 tab = QFixed::fromReal(tabSpec.position);
2650 for (int i=item + 1; i < layoutData->items.count(); i++) {
2651 const QScriptItem &item = layoutData->items[i];
2652 if (item.analysis.flags == QScriptAnalysis::TabOrObject) { // found it.
2653 tabSectionEnd = item.position;
2658 else if (tabSpec.type == QTextOption::DelimiterTab)
2659 // find delimitor character to calculate the width required
2660 tabSectionEnd = qMax(si.position, layoutData->string.indexOf(tabSpec.delimiter, si.position) + 1);
2662 if (tabSectionEnd > si.position) {
2664 // Calculate the length of text between this tab and the tabSectionEnd
2665 for (int i=item; i < layoutData->items.count(); i++) {
2666 QScriptItem &item = layoutData->items[i];
2667 if (item.position > tabSectionEnd || item.position <= si.position)
2669 shape(i); // first, lets make sure relevant text is already shaped
2670 QGlyphLayout glyphs = this->shapedGlyphs(&item);
2671 const int end = qMin(item.position + item.num_glyphs, tabSectionEnd) - item.position;
2672 for (int i=0; i < end; i++)
2673 length += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
2674 if (end + item.position == tabSectionEnd && tabSpec.type == QTextOption::DelimiterTab) // remove half of matching char
2675 length -= glyphs.advances_x[end] / 2 * !glyphs.attributes[end].dontPrint;
2678 switch (tabSpec.type) {
2679 case QTextOption::CenterTab:
2682 case QTextOption::DelimiterTab:
2684 case QTextOption::RightTab:
2685 tab = QFixed::fromReal(tabSpec.position) * dpiScale - length;
2686 if (tab < 0) // default to tab taking no space
2689 case QTextOption::LeftTab:
2697 QFixed tab = QFixed::fromReal(option.tabStop());
2699 tab = 80; // default
2701 QFixed nextTabPos = ((x / tab).truncate() + 1) * tab;
2702 QFixed tabWidth = nextTabPos - x;
2707 void QTextEngine::resolveAdditionalFormats() const
2709 if (!specialData || specialData->addFormats.isEmpty()
2710 || !block.docHandle()
2711 || !specialData->resolvedFormatIndices.isEmpty())
2714 QTextFormatCollection *collection = this->formats();
2716 specialData->resolvedFormatIndices.clear();
2717 QVector<int> indices(layoutData->items.count());
2718 for (int i = 0; i < layoutData->items.count(); ++i) {
2719 QTextCharFormat f = format(&layoutData->items.at(i));
2720 indices[i] = collection->indexForFormat(f);
2722 specialData->resolvedFormatIndices = indices;
2725 QFixed QTextEngine::leadingSpaceWidth(const QScriptLine &line)
2727 if (!line.hasTrailingSpaces
2728 || (option.flags() & QTextOption::IncludeTrailingSpaces)
2729 || !isRightToLeft())
2732 int pos = line.length;
2733 const HB_CharAttributes *attributes = this->attributes();
2736 while (pos > 0 && attributes[line.from + pos - 1].whiteSpace)
2738 return width(line.from + pos, line.length - pos);
2741 QFixed QTextEngine::alignLine(const QScriptLine &line)
2745 // if width is QFIXED_MAX that means we used setNumColumns() and that implicitly makes this line left aligned.
2746 if (!line.justified && line.width != QFIXED_MAX) {
2747 int align = option.alignment();
2748 if (align & Qt::AlignJustify && isRightToLeft())
2749 align = Qt::AlignRight;
2750 if (align & Qt::AlignRight)
2751 x = line.width - (line.textAdvance + leadingSpaceWidth(line));
2752 else if (align & Qt::AlignHCenter)
2753 x = (line.width - line.textAdvance)/2;
2758 QFixed QTextEngine::offsetInLigature(const QScriptItem *si, int pos, int max, int glyph_pos)
2760 unsigned short *logClusters = this->logClusters(si);
2761 const QGlyphLayout &glyphs = shapedGlyphs(si);
2763 int offsetInCluster = 0;
2764 for (int i = pos - 1; i >= 0; i--) {
2765 if (logClusters[i] == glyph_pos)
2771 // in the case that the offset is inside a (multi-character) glyph,
2772 // interpolate the position.
2773 if (offsetInCluster > 0) {
2774 int clusterLength = 0;
2775 for (int i = pos - offsetInCluster; i < max; i++) {
2776 if (logClusters[i] == glyph_pos)
2782 return glyphs.advances_x[glyph_pos] * offsetInCluster / clusterLength;
2788 int QTextEngine::previousLogicalPosition(int oldPos) const
2790 const HB_CharAttributes *attrs = attributes();
2791 if (!attrs || oldPos < 0)
2797 while (oldPos && !attrs[oldPos].charStop)
2802 int QTextEngine::nextLogicalPosition(int oldPos) const
2804 const HB_CharAttributes *attrs = attributes();
2805 int len = block.isValid() ? block.length() - 1
2806 : layoutData->string.length();
2807 Q_ASSERT(len <= layoutData->string.length());
2808 if (!attrs || oldPos < 0 || oldPos >= len)
2812 while (oldPos < len && !attrs[oldPos].charStop)
2817 int QTextEngine::lineNumberForTextPosition(int pos)
2821 if (pos == layoutData->string.length() && lines.size())
2822 return lines.size() - 1;
2823 for (int i = 0; i < lines.size(); ++i) {
2824 const QScriptLine& line = lines[i];
2825 if (line.from + line.length > pos)
2831 void QTextEngine::insertionPointsForLine(int lineNum, QVector<int> &insertionPoints)
2833 QTextLineItemIterator iterator(this, lineNum);
2834 bool rtl = isRightToLeft();
2835 bool lastLine = lineNum >= lines.size() - 1;
2837 while (!iterator.atEnd()) {
2839 const QScriptItem *si = &layoutData->items[iterator.item];
2840 if (si->analysis.bidiLevel % 2) {
2841 int i = iterator.itemEnd - 1, min = iterator.itemStart;
2842 if (lastLine && (rtl ? iterator.atBeginning() : iterator.atEnd()))
2844 for (; i >= min; i--)
2845 insertionPoints.push_back(i);
2847 int i = iterator.itemStart, max = iterator.itemEnd;
2848 if (lastLine && (rtl ? iterator.atBeginning() : iterator.atEnd()))
2850 for (; i < max; i++)
2851 insertionPoints.push_back(i);
2856 int QTextEngine::endOfLine(int lineNum)
2858 QVector<int> insertionPoints;
2859 insertionPointsForLine(lineNum, insertionPoints);
2861 if (insertionPoints.size() > 0)
2862 return insertionPoints.last();
2866 int QTextEngine::beginningOfLine(int lineNum)
2868 QVector<int> insertionPoints;
2869 insertionPointsForLine(lineNum, insertionPoints);
2871 if (insertionPoints.size() > 0)
2872 return insertionPoints.first();
2876 int QTextEngine::positionAfterVisualMovement(int pos, QTextCursor::MoveOperation op)
2881 bool moveRight = (op == QTextCursor::Right);
2882 bool alignRight = isRightToLeft();
2883 if (!layoutData->hasBidi)
2884 return moveRight ^ alignRight ? nextLogicalPosition(pos) : previousLogicalPosition(pos);
2886 int lineNum = lineNumberForTextPosition(pos);
2887 Q_ASSERT(lineNum >= 0);
2889 QVector<int> insertionPoints;
2890 insertionPointsForLine(lineNum, insertionPoints);
2891 int i, max = insertionPoints.size();
2892 for (i = 0; i < max; i++)
2893 if (pos == insertionPoints[i]) {
2896 return insertionPoints[i + 1];
2899 return insertionPoints[i - 1];
2902 if (moveRight ^ alignRight) {
2903 if (lineNum + 1 < lines.size())
2904 return alignRight ? endOfLine(lineNum + 1) : beginningOfLine(lineNum + 1);
2908 return alignRight ? beginningOfLine(lineNum - 1) : endOfLine(lineNum - 1);
2915 QStackTextEngine::QStackTextEngine(const QString &string, const QFont &f)
2916 : QTextEngine(string, f),
2917 _layoutData(string, _memory, MemSize)
2920 layoutData = &_layoutData;
2923 QTextItemInt::QTextItemInt(const QScriptItem &si, QFont *font, const QTextCharFormat &format)
2924 : justified(false), underlineStyle(QTextCharFormat::NoUnderline), charFormat(format),
2925 num_chars(0), chars(0), logClusters(0), f(0), fontEngine(0)
2927 // explicitly initialize flags so that initFontAttributes can be called
2928 // multiple times on the same TextItem
2930 if (si.analysis.bidiLevel %2)
2931 flags |= QTextItem::RightToLeft;
2933 descent = si.descent;
2935 fontEngine = f->d->engineForScript(si.analysis.script);
2936 Q_ASSERT(fontEngine);
2938 if (format.hasProperty(QTextFormat::TextUnderlineStyle)) {
2939 underlineStyle = format.underlineStyle();
2940 } else if (format.boolProperty(QTextFormat::FontUnderline)
2941 || f->d->underline) {
2942 underlineStyle = QTextCharFormat::SingleUnderline;
2946 if (underlineStyle == QTextCharFormat::SingleUnderline)
2947 flags |= QTextItem::Underline;
2949 if (f->d->overline || format.fontOverline())
2950 flags |= QTextItem::Overline;
2951 if (f->d->strikeOut || format.fontStrikeOut())
2952 flags |= QTextItem::StrikeOut;
2955 QTextItemInt::QTextItemInt(const QGlyphLayout &g, QFont *font, const QChar *chars_, int numChars, QFontEngine *fe)
2956 : flags(0), justified(false), underlineStyle(QTextCharFormat::NoUnderline),
2957 num_chars(numChars), chars(chars_), logClusters(0), f(font), glyphs(g), fontEngine(fe)
2961 QTextItemInt QTextItemInt::midItem(QFontEngine *fontEngine, int firstGlyphIndex, int numGlyphs) const
2963 QTextItemInt ti = *this;
2964 const int end = firstGlyphIndex + numGlyphs;
2965 ti.glyphs = glyphs.mid(firstGlyphIndex, numGlyphs);
2966 ti.fontEngine = fontEngine;
2968 if (logClusters && chars) {
2969 const int logClusterOffset = logClusters[0];
2970 while (logClusters[ti.chars - chars] - logClusterOffset < firstGlyphIndex)
2973 ti.logClusters += (ti.chars - chars);
2976 int char_start = ti.chars - chars;
2977 while (char_start + ti.num_chars < num_chars && ti.logClusters[ti.num_chars] - logClusterOffset < end)
2984 QTransform qt_true_matrix(qreal w, qreal h, QTransform x)
2986 QRectF rect = x.mapRect(QRectF(0, 0, w, h));
2987 return x * QTransform::fromTranslate(-rect.x(), -rect.y());
2991 glyph_metrics_t glyph_metrics_t::transformed(const QTransform &matrix) const
2993 if (matrix.type() < QTransform::TxTranslate)
2996 glyph_metrics_t m = *this;
2998 qreal w = width.toReal();
2999 qreal h = height.toReal();
3000 QTransform xform = qt_true_matrix(w, h, matrix);
3002 QRectF rect(0, 0, w, h);
3003 rect = xform.mapRect(rect);
3004 m.width = QFixed::fromReal(rect.width());
3005 m.height = QFixed::fromReal(rect.height());
3007 QLineF l = xform.map(QLineF(x.toReal(), y.toReal(), xoff.toReal(), yoff.toReal()));
3009 m.x = QFixed::fromReal(l.x1());
3010 m.y = QFixed::fromReal(l.y1());
3012 // The offset is relative to the baseline which is why we use dx/dy of the line
3013 m.xoff = QFixed::fromReal(l.dx());
3014 m.yoff = QFixed::fromReal(l.dy());
3019 QTextLineItemIterator::QTextLineItemIterator(QTextEngine *_eng, int _lineNum, const QPointF &pos,
3020 const QTextLayout::FormatRange *_selection)
3022 line(eng->lines[_lineNum]),
3025 lineEnd(line.from + line.length),
3026 firstItem(eng->findItem(line.from)),
3027 lastItem(eng->findItem(lineEnd - 1)),
3028 nItems((firstItem >= 0 && lastItem >= firstItem)? (lastItem-firstItem+1) : 0),
3031 visualOrder(nItems),
3033 selection(_selection)
3035 pos_x = x = QFixed::fromReal(pos.x());
3039 x += eng->alignLine(line);
3041 for (int i = 0; i < nItems; ++i)
3042 levels[i] = eng->layoutData->items[i+firstItem].analysis.bidiLevel;
3043 QTextEngine::bidiReorder(nItems, levels.data(), visualOrder.data());
3045 eng->shapeLine(line);
3048 QScriptItem &QTextLineItemIterator::next()
3053 item = visualOrder[logicalItem] + firstItem;
3054 itemLength = eng->length(item);
3055 si = &eng->layoutData->items[item];
3056 if (!si->num_glyphs)
3059 if (si->analysis.flags >= QScriptAnalysis::TabOrObject) {
3060 itemWidth = si->width;
3064 unsigned short *logClusters = eng->logClusters(si);
3065 QGlyphLayout glyphs = eng->shapedGlyphs(si);
3067 itemStart = qMax(line.from, si->position);
3068 glyphsStart = logClusters[itemStart - si->position];
3069 if (lineEnd < si->position + itemLength) {
3071 glyphsEnd = logClusters[itemEnd-si->position];
3073 itemEnd = si->position + itemLength;
3074 glyphsEnd = si->num_glyphs;
3076 // show soft-hyphen at line-break
3077 if (si->position + itemLength >= lineEnd
3078 && eng->layoutData->string.at(lineEnd - 1) == 0x00ad)
3079 glyphs.attributes[glyphsEnd - 1].dontPrint = false;
3082 for (int g = glyphsStart; g < glyphsEnd; ++g)
3083 itemWidth += glyphs.effectiveAdvance(g);
3088 bool QTextLineItemIterator::getSelectionBounds(QFixed *selectionX, QFixed *selectionWidth) const
3090 *selectionX = *selectionWidth = 0;
3095 if (si->analysis.flags >= QScriptAnalysis::TabOrObject) {
3096 if (si->position >= selection->start + selection->length
3097 || si->position + itemLength <= selection->start)
3101 *selectionWidth = itemWidth;
3103 unsigned short *logClusters = eng->logClusters(si);
3104 QGlyphLayout glyphs = eng->shapedGlyphs(si);
3106 int from = qMax(itemStart, selection->start) - si->position;
3107 int to = qMin(itemEnd, selection->start + selection->length) - si->position;
3111 int start_glyph = logClusters[from];
3112 int end_glyph = (to == eng->length(item)) ? si->num_glyphs : logClusters[to];
3115 if (si->analysis.bidiLevel %2) {
3116 for (int g = glyphsEnd - 1; g >= end_glyph; --g)
3117 soff += glyphs.effectiveAdvance(g);
3118 for (int g = end_glyph - 1; g >= start_glyph; --g)
3119 swidth += glyphs.effectiveAdvance(g);
3121 for (int g = glyphsStart; g < start_glyph; ++g)
3122 soff += glyphs.effectiveAdvance(g);
3123 for (int g = start_glyph; g < end_glyph; ++g)
3124 swidth += glyphs.effectiveAdvance(g);
3127 // If the starting character is in the middle of a ligature,
3128 // selection should only contain the right part of that ligature
3129 // glyph, so we need to get the width of the left part here and
3130 // add it to *selectionX
3131 QFixed leftOffsetInLigature = eng->offsetInLigature(si, from, to, start_glyph);
3132 *selectionX = x + soff + leftOffsetInLigature;
3133 *selectionWidth = swidth - leftOffsetInLigature;
3134 // If the ending character is also part of a ligature, swidth does
3135 // not contain that part yet, we also need to find out the width of
3137 *selectionWidth += eng->offsetInLigature(si, to, eng->length(item), end_glyph);