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;
1313 e->underlinePositions = 0;
1315 e->stackEngine = false;
1318 QTextEngine::QTextEngine()
1323 QTextEngine::QTextEngine(const QString &str, const QFont &f)
1330 QTextEngine::~QTextEngine()
1337 const HB_CharAttributes *QTextEngine::attributes() const
1339 if (layoutData && layoutData->haveCharAttributes)
1340 return (HB_CharAttributes *) layoutData->memory;
1343 if (! ensureSpace(layoutData->string.length()))
1346 QVarLengthArray<HB_ScriptItem> hbScriptItems(layoutData->items.size());
1348 for (int i = 0; i < layoutData->items.size(); ++i) {
1349 const QScriptItem &si = layoutData->items[i];
1350 hbScriptItems[i].pos = si.position;
1351 hbScriptItems[i].length = length(i);
1352 hbScriptItems[i].bidiLevel = si.analysis.bidiLevel;
1353 hbScriptItems[i].script = (HB_Script)si.analysis.script;
1356 qGetCharAttributes(reinterpret_cast<const HB_UChar16 *>(layoutData->string.constData()),
1357 layoutData->string.length(),
1358 hbScriptItems.data(), hbScriptItems.size(),
1359 (HB_CharAttributes *)layoutData->memory);
1362 layoutData->haveCharAttributes = true;
1363 return (HB_CharAttributes *) layoutData->memory;
1366 void QTextEngine::shape(int item) const
1368 if (layoutData->items[item].analysis.flags == QScriptAnalysis::Object) {
1370 if (block.docHandle()) {
1371 QTextFormat format = formats()->format(formatIndex(&layoutData->items[item]));
1372 docLayout()->resizeInlineObject(QTextInlineObject(item, const_cast<QTextEngine *>(this)),
1373 layoutData->items[item].position + block.position(), format);
1375 } else if (layoutData->items[item].analysis.flags == QScriptAnalysis::Tab) {
1376 // set up at least the ascent/descent/leading of the script item for the tab
1377 fontEngine(layoutData->items[item],
1378 &layoutData->items[item].ascent,
1379 &layoutData->items[item].descent,
1380 &layoutData->items[item].leading);
1386 static inline void releaseCachedFontEngine(QFontEngine *fontEngine)
1389 fontEngine->ref.deref();
1390 if (fontEngine->cache_count == 0 && fontEngine->ref == 0)
1395 void QTextEngine::invalidate()
1401 specialData->resolvedFormatIndices.clear();
1403 releaseCachedFontEngine(feCache.prevFontEngine);
1404 releaseCachedFontEngine(feCache.prevScaledFontEngine);
1408 void QTextEngine::clearLineData()
1413 void QTextEngine::validate() const
1417 layoutData = new LayoutData();
1418 if (block.docHandle()) {
1419 layoutData->string = block.text();
1420 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators)
1421 layoutData->string += QLatin1Char(block.next().isValid() ? 0xb6 : 0x20);
1423 layoutData->string = text;
1425 if (specialData && specialData->preeditPosition != -1)
1426 layoutData->string.insert(specialData->preeditPosition, specialData->preeditText);
1429 void QTextEngine::itemize() const
1432 if (layoutData->items.size())
1435 int length = layoutData->string.length();
1438 #if defined(Q_WS_MAC) && !defined(QT_MAC_USE_COCOA)
1439 // ATSUI requires RTL flags to correctly identify the character stops.
1440 bool ignore = false;
1442 bool ignore = ignoreBidi;
1445 bool rtl = isRightToLeft();
1447 if (!ignore && !rtl) {
1449 const QChar *start = layoutData->string.unicode();
1450 const QChar * const end = start + length;
1451 while (start < end) {
1452 if (start->unicode() >= 0x590) {
1460 QVarLengthArray<QScriptAnalysis, 4096> scriptAnalysis(length);
1461 QScriptAnalysis *analysis = scriptAnalysis.data();
1463 QBidiControl control(rtl);
1466 memset(analysis, 0, length*sizeof(QScriptAnalysis));
1467 if (option.textDirection() == Qt::RightToLeft) {
1468 for (int i = 0; i < length; ++i)
1469 analysis[i].bidiLevel = 1;
1470 layoutData->hasBidi = true;
1473 layoutData->hasBidi = bidiItemize(const_cast<QTextEngine *>(this), analysis, control);
1476 const ushort *uc = reinterpret_cast<const ushort *>(layoutData->string.unicode());
1477 const ushort *e = uc + length;
1478 int lastScript = QUnicodeTables::Common;
1480 int script = QUnicodeTables::script(*uc);
1481 if (script == QUnicodeTables::Inherited)
1482 script = lastScript;
1483 analysis->flags = QScriptAnalysis::None;
1484 if (*uc == QChar::ObjectReplacementCharacter) {
1485 if (analysis->bidiLevel % 2)
1486 --analysis->bidiLevel;
1487 analysis->script = QUnicodeTables::Common;
1488 analysis->flags = QScriptAnalysis::Object;
1489 } else if (*uc == QChar::LineSeparator) {
1490 if (analysis->bidiLevel % 2)
1491 --analysis->bidiLevel;
1492 analysis->script = QUnicodeTables::Common;
1493 analysis->flags = QScriptAnalysis::LineOrParagraphSeparator;
1494 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators)
1495 *const_cast<ushort*>(uc) = 0x21B5; // visual line separator
1496 } else if (*uc == 9) {
1497 analysis->script = QUnicodeTables::Common;
1498 analysis->flags = QScriptAnalysis::Tab;
1499 analysis->bidiLevel = control.baseLevel();
1500 } else if ((*uc == 32 || *uc == QChar::Nbsp)
1501 && (option.flags() & QTextOption::ShowTabsAndSpaces)) {
1502 analysis->script = QUnicodeTables::Common;
1503 analysis->flags = QScriptAnalysis::Space;
1504 analysis->bidiLevel = control.baseLevel();
1506 analysis->script = script;
1508 lastScript = analysis->script;
1512 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators) {
1513 (analysis-1)->flags = QScriptAnalysis::LineOrParagraphSeparator; // to exclude it from width
1516 Itemizer itemizer(layoutData->string, scriptAnalysis.data(), layoutData->items);
1518 const QTextDocumentPrivate *p = block.docHandle();
1520 SpecialData *s = specialData;
1522 QTextDocumentPrivate::FragmentIterator it = p->find(block.position());
1523 QTextDocumentPrivate::FragmentIterator end = p->find(block.position() + block.length() - 1); // -1 to omit the block separator char
1524 int format = it.value()->format;
1526 int prevPosition = 0;
1527 int position = prevPosition;
1529 const QTextFragmentData * const frag = it.value();
1530 if (it == end || format != frag->format) {
1531 if (s && position >= s->preeditPosition) {
1532 position += s->preeditText.length();
1535 Q_ASSERT(position <= length);
1536 itemizer.generate(prevPosition, position - prevPosition,
1537 formats()->charFormat(format).fontCapitalization());
1539 if (position < length)
1540 itemizer.generate(position, length - position,
1541 formats()->charFormat(format).fontCapitalization());
1544 format = frag->format;
1545 prevPosition = position;
1547 position += frag->size_array[0];
1551 itemizer.generate(0, length, static_cast<QFont::Capitalization> (fnt.d->capital));
1554 addRequiredBoundaries();
1555 resolveAdditionalFormats();
1558 bool QTextEngine::isRightToLeft() const
1560 switch (option.textDirection()) {
1561 case Qt::LeftToRight:
1563 case Qt::RightToLeft:
1568 // this places the cursor in the right position depending on the keyboard layout
1569 if (layoutData->string.isEmpty())
1570 return QApplication::keyboardInputDirection() == Qt::RightToLeft;
1571 return layoutData->string.isRightToLeft();
1575 int QTextEngine::findItem(int strPos) const
1579 int right = layoutData->items.size()-1;
1580 while(left <= right) {
1581 int middle = ((right-left)/2)+left;
1582 if (strPos > layoutData->items[middle].position)
1584 else if(strPos < layoutData->items[middle].position)
1593 QFixed QTextEngine::width(int from, int len) const
1599 // qDebug("QTextEngine::width(from = %d, len = %d), numItems=%d, strleng=%d", from, len, items.size(), string.length());
1600 for (int i = 0; i < layoutData->items.size(); i++) {
1601 const QScriptItem *si = layoutData->items.constData() + i;
1602 int pos = si->position;
1603 int ilen = length(i);
1604 // qDebug("item %d: from %d len %d", i, pos, ilen);
1605 if (pos >= from + len)
1607 if (pos + ilen > from) {
1608 if (!si->num_glyphs)
1611 if (si->analysis.flags == QScriptAnalysis::Object) {
1614 } else if (si->analysis.flags == QScriptAnalysis::Tab) {
1615 w += calculateTabWidth(i, w);
1620 QGlyphLayout glyphs = shapedGlyphs(si);
1621 unsigned short *logClusters = this->logClusters(si);
1623 // fprintf(stderr, " logclusters:");
1624 // for (int k = 0; k < ilen; k++)
1625 // fprintf(stderr, " %d", logClusters[k]);
1626 // fprintf(stderr, "\n");
1627 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1628 int charFrom = from - pos;
1631 int glyphStart = logClusters[charFrom];
1632 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1633 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1635 if (charFrom < ilen) {
1636 glyphStart = logClusters[charFrom];
1637 int charEnd = from + len - 1 - pos;
1638 if (charEnd >= ilen)
1640 int glyphEnd = logClusters[charEnd];
1641 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1643 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1645 // qDebug("char: start=%d end=%d / glyph: start = %d, end = %d", charFrom, charEnd, glyphStart, glyphEnd);
1646 for (int i = glyphStart; i < glyphEnd; i++)
1647 w += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
1651 // qDebug(" --> w= %d ", w);
1655 glyph_metrics_t QTextEngine::boundingBox(int from, int len) const
1661 for (int i = 0; i < layoutData->items.size(); i++) {
1662 const QScriptItem *si = layoutData->items.constData() + i;
1664 int pos = si->position;
1665 int ilen = length(i);
1666 if (pos > from + len)
1668 if (pos + ilen > from) {
1669 if (!si->num_glyphs)
1672 if (si->analysis.flags == QScriptAnalysis::Object) {
1673 gm.width += si->width;
1675 } else if (si->analysis.flags == QScriptAnalysis::Tab) {
1676 gm.width += calculateTabWidth(i, gm.width);
1680 unsigned short *logClusters = this->logClusters(si);
1681 QGlyphLayout glyphs = shapedGlyphs(si);
1683 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1684 int charFrom = from - pos;
1687 int glyphStart = logClusters[charFrom];
1688 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1689 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1691 if (charFrom < ilen) {
1692 QFontEngine *fe = fontEngine(*si);
1693 glyphStart = logClusters[charFrom];
1694 int charEnd = from + len - 1 - pos;
1695 if (charEnd >= ilen)
1697 int glyphEnd = logClusters[charEnd];
1698 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1700 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1701 if (glyphStart <= glyphEnd ) {
1702 glyph_metrics_t m = fe->boundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
1703 gm.x = qMin(gm.x, m.x + gm.xoff);
1704 gm.y = qMin(gm.y, m.y + gm.yoff);
1705 gm.width = qMax(gm.width, m.width+gm.xoff);
1706 gm.height = qMax(gm.height, m.height+gm.yoff);
1716 glyph_metrics_t QTextEngine::tightBoundingBox(int from, int len) const
1722 for (int i = 0; i < layoutData->items.size(); i++) {
1723 const QScriptItem *si = layoutData->items.constData() + i;
1724 int pos = si->position;
1725 int ilen = length(i);
1726 if (pos > from + len)
1728 if (pos + len > from) {
1729 if (!si->num_glyphs)
1731 unsigned short *logClusters = this->logClusters(si);
1732 QGlyphLayout glyphs = shapedGlyphs(si);
1734 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1735 int charFrom = from - pos;
1738 int glyphStart = logClusters[charFrom];
1739 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1740 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1742 if (charFrom < ilen) {
1743 glyphStart = logClusters[charFrom];
1744 int charEnd = from + len - 1 - pos;
1745 if (charEnd >= ilen)
1747 int glyphEnd = logClusters[charEnd];
1748 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1750 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1751 if (glyphStart <= glyphEnd ) {
1752 QFontEngine *fe = fontEngine(*si);
1753 glyph_metrics_t m = fe->tightBoundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
1754 gm.x = qMin(gm.x, m.x + gm.xoff);
1755 gm.y = qMin(gm.y, m.y + gm.yoff);
1756 gm.width = qMax(gm.width, m.width+gm.xoff);
1757 gm.height = qMax(gm.height, m.height+gm.yoff);
1767 QFont QTextEngine::font(const QScriptItem &si) const
1771 QTextCharFormat f = format(&si);
1774 if (block.docHandle() && block.docHandle()->layout()) {
1775 // Make sure we get the right dpi on printers
1776 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
1778 font = QFont(font, pdev);
1780 font = font.resolve(fnt);
1782 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
1783 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
1784 if (font.pointSize() != -1)
1785 font.setPointSize((font.pointSize() * 2) / 3);
1787 font.setPixelSize((font.pixelSize() * 2) / 3);
1791 if (si.analysis.flags == QScriptAnalysis::SmallCaps)
1792 font = font.d->smallCapsFont();
1797 QTextEngine::FontEngineCache::FontEngineCache()
1802 //we cache the previous results of this function, as calling it numerous times with the same effective
1803 //input is common (and hard to cache at a higher level)
1804 QFontEngine *QTextEngine::fontEngine(const QScriptItem &si, QFixed *ascent, QFixed *descent, QFixed *leading) const
1806 QFontEngine *engine = 0;
1807 QFontEngine *scaledEngine = 0;
1808 int script = si.analysis.script;
1812 if (feCache.prevFontEngine && feCache.prevPosition == si.position && feCache.prevLength == length(&si) && feCache.prevScript == script) {
1813 engine = feCache.prevFontEngine;
1814 scaledEngine = feCache.prevScaledFontEngine;
1816 QTextCharFormat f = format(&si);
1819 if (block.docHandle() && block.docHandle()->layout()) {
1820 // Make sure we get the right dpi on printers
1821 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
1823 font = QFont(font, pdev);
1825 font = font.resolve(fnt);
1827 engine = font.d->engineForScript(script);
1828 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
1829 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
1830 if (font.pointSize() != -1)
1831 font.setPointSize((font.pointSize() * 2) / 3);
1833 font.setPixelSize((font.pixelSize() * 2) / 3);
1834 scaledEngine = font.d->engineForScript(script);
1836 feCache.prevFontEngine = engine;
1839 feCache.prevScaledFontEngine = scaledEngine;
1841 scaledEngine->ref.ref();
1842 feCache.prevScript = script;
1843 feCache.prevPosition = si.position;
1844 feCache.prevLength = length(&si);
1847 if (feCache.prevFontEngine && feCache.prevScript == script && feCache.prevPosition == -1)
1848 engine = feCache.prevFontEngine;
1850 engine = font.d->engineForScript(script);
1851 feCache.prevFontEngine = engine;
1854 feCache.prevScript = script;
1855 feCache.prevPosition = -1;
1856 feCache.prevLength = -1;
1857 feCache.prevScaledFontEngine = 0;
1861 if (si.analysis.flags == QScriptAnalysis::SmallCaps) {
1862 QFontPrivate *p = font.d->smallCapsFontPrivate();
1863 scaledEngine = p->engineForScript(script);
1867 *ascent = engine->ascent();
1868 *descent = engine->descent();
1869 *leading = engine->leading();
1873 return scaledEngine;
1877 struct QJustificationPoint {
1879 QFixed kashidaWidth;
1881 QFontEngine *fontEngine;
1884 Q_DECLARE_TYPEINFO(QJustificationPoint, Q_PRIMITIVE_TYPE);
1886 static void set(QJustificationPoint *point, int type, const QGlyphLayout &glyph, QFontEngine *fe)
1889 point->glyph = glyph;
1890 point->fontEngine = fe;
1892 if (type >= HB_Arabic_Normal) {
1893 QChar ch(0x640); // Kashida character
1894 QGlyphLayoutArray<8> glyphs;
1896 fe->stringToCMap(&ch, 1, &glyphs, &nglyphs, 0);
1897 if (glyphs.glyphs[0] && glyphs.advances_x[0] != 0) {
1898 point->kashidaWidth = glyphs.advances_x[0];
1900 point->type = HB_NoJustification;
1901 point->kashidaWidth = 0;
1907 void QTextEngine::justify(const QScriptLine &line)
1909 // qDebug("justify: line.gridfitted = %d, line.justified=%d", line.gridfitted, line.justified);
1910 if (line.gridfitted && line.justified)
1913 if (!line.gridfitted) {
1914 // redo layout in device metrics, then adjust
1915 const_cast<QScriptLine &>(line).gridfitted = true;
1918 if ((option.alignment() & Qt::AlignHorizontal_Mask) != Qt::AlignJustify)
1923 if (!forceJustification) {
1924 int end = line.from + (int)line.length;
1925 if (end == layoutData->string.length())
1926 return; // no justification at end of paragraph
1927 if (end && layoutData->items[findItem(end-1)].analysis.flags == QScriptAnalysis::LineOrParagraphSeparator)
1928 return; // no justification at the end of an explicitly separated line
1934 // don't include trailing white spaces when doing justification
1935 int line_length = line.length;
1936 const HB_CharAttributes *a = attributes();
1940 while (line_length && a[line_length-1].whiteSpace)
1942 // subtract one char more, as we can't justfy after the last character
1948 int firstItem = findItem(line.from);
1949 int nItems = findItem(line.from + line_length - 1) - firstItem + 1;
1951 QVarLengthArray<QJustificationPoint> justificationPoints;
1953 // 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());
1954 QFixed minKashida = 0x100000;
1956 // we need to do all shaping before we go into the next loop, as we there
1957 // store pointers to the glyph data that could get reallocated by the shaping
1959 for (int i = 0; i < nItems; ++i) {
1960 QScriptItem &si = layoutData->items[firstItem + i];
1962 shape(firstItem + i);
1965 for (int i = 0; i < nItems; ++i) {
1966 QScriptItem &si = layoutData->items[firstItem + i];
1968 int kashida_type = HB_Arabic_Normal;
1969 int kashida_pos = -1;
1971 int start = qMax(line.from - si.position, 0);
1972 int end = qMin(line.from + line_length - (int)si.position, length(firstItem+i));
1974 unsigned short *log_clusters = logClusters(&si);
1976 int gs = log_clusters[start];
1977 int ge = (end == length(firstItem+i) ? si.num_glyphs : log_clusters[end]);
1979 const QGlyphLayout g = shapedGlyphs(&si);
1981 for (int i = gs; i < ge; ++i) {
1982 g.justifications[i].type = QGlyphJustification::JustifyNone;
1983 g.justifications[i].nKashidas = 0;
1984 g.justifications[i].space_18d6 = 0;
1986 justificationPoints.resize(nPoints+3);
1987 int justification = g.attributes[i].justification;
1989 switch(justification) {
1990 case HB_NoJustification:
1994 case HB_Arabic_Space :
1995 if (kashida_pos >= 0) {
1996 // qDebug("kashida position at %d in word", kashida_pos);
1997 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
1998 if (justificationPoints[nPoints].kashidaWidth > 0) {
1999 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
2000 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
2005 kashida_type = HB_Arabic_Normal;
2008 set(&justificationPoints[nPoints++], justification, g.mid(i), fontEngine(si));
2009 maxJustify = qMax(maxJustify, justification);
2011 case HB_Arabic_Normal :
2012 case HB_Arabic_Waw :
2013 case HB_Arabic_BaRa :
2014 case HB_Arabic_Alef :
2015 case HB_Arabic_HaaDal :
2016 case HB_Arabic_Seen :
2017 case HB_Arabic_Kashida :
2018 if (justification >= kashida_type) {
2020 kashida_type = justification;
2024 if (kashida_pos >= 0) {
2025 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
2026 if (justificationPoints[nPoints].kashidaWidth > 0) {
2027 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
2028 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
2034 QFixed need = line.width - line.textWidth;
2036 // line overflows already!
2037 const_cast<QScriptLine &>(line).justified = true;
2041 // qDebug("doing justification: textWidth=%x, requested=%x, maxJustify=%d", line.textWidth.value(), line.width.value(), maxJustify);
2042 // qDebug(" minKashida=%f, need=%f", minKashida.toReal(), need.toReal());
2044 // distribute in priority order
2045 if (maxJustify >= HB_Arabic_Normal) {
2046 while (need >= minKashida) {
2047 for (int type = maxJustify; need >= minKashida && type >= HB_Arabic_Normal; --type) {
2048 for (int i = 0; need >= minKashida && i < nPoints; ++i) {
2049 if (justificationPoints[i].type == type && justificationPoints[i].kashidaWidth <= need) {
2050 justificationPoints[i].glyph.justifications->nKashidas++;
2052 justificationPoints[i].glyph.justifications->space_18d6 += justificationPoints[i].kashidaWidth.value();
2053 need -= justificationPoints[i].kashidaWidth;
2054 // qDebug("adding kashida type %d with width %x, neednow %x", type, justificationPoints[i].kashidaWidth, need.value());
2060 Q_ASSERT(need >= 0);
2064 maxJustify = qMin(maxJustify, (int)HB_Space);
2065 for (int type = maxJustify; need != 0 && type > 0; --type) {
2067 for (int i = 0; i < nPoints; ++i) {
2068 if (justificationPoints[i].type == type)
2071 // qDebug("number of points for justification type %d: %d", type, n);
2077 for (int i = 0; i < nPoints; ++i) {
2078 if (justificationPoints[i].type == type) {
2079 QFixed add = need/n;
2080 // qDebug("adding %x to glyph %x", add.value(), justificationPoints[i].glyph->glyph);
2081 justificationPoints[i].glyph.justifications[0].space_18d6 = add.value();
2090 const_cast<QScriptLine &>(line).justified = true;
2093 void QScriptLine::setDefaultHeight(QTextEngine *eng)
2098 if (eng->block.docHandle() && eng->block.docHandle()->layout()) {
2099 f = eng->block.charFormat().font();
2100 // Make sure we get the right dpi on printers
2101 QPaintDevice *pdev = eng->block.docHandle()->layout()->paintDevice();
2104 e = f.d->engineForScript(QUnicodeTables::Common);
2106 e = eng->fnt.d->engineForScript(QUnicodeTables::Common);
2109 QFixed other_ascent = e->ascent();
2110 QFixed other_descent = e->descent();
2111 QFixed other_leading = e->leading();
2112 leading = qMax(leading + ascent, other_leading + other_ascent) - qMax(ascent, other_ascent);
2113 ascent = qMax(ascent, other_ascent);
2114 descent = qMax(descent, other_descent);
2117 QTextEngine::LayoutData::LayoutData()
2121 memory_on_stack = false;
2124 layoutState = LayoutEmpty;
2125 haveCharAttributes = false;
2127 available_glyphs = 0;
2130 QTextEngine::LayoutData::LayoutData(const QString &str, void **stack_memory, int _allocated)
2133 allocated = _allocated;
2135 int space_charAttributes = sizeof(HB_CharAttributes)*string.length()/sizeof(void*) + 1;
2136 int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2137 available_glyphs = ((int)allocated - space_charAttributes - space_logClusters)*(int)sizeof(void*)/(int)QGlyphLayout::spaceNeededForGlyphLayout(1);
2139 if (available_glyphs < str.length()) {
2140 // need to allocate on the heap
2143 memory_on_stack = false;
2147 memory_on_stack = true;
2148 memory = stack_memory;
2149 logClustersPtr = (unsigned short *)(memory + space_charAttributes);
2151 void *m = memory + space_charAttributes + space_logClusters;
2152 glyphLayout = QGlyphLayout(reinterpret_cast<char *>(m), str.length());
2153 glyphLayout.clear();
2154 memset(memory, 0, space_charAttributes*sizeof(void *));
2158 layoutState = LayoutEmpty;
2159 haveCharAttributes = false;
2162 QTextEngine::LayoutData::~LayoutData()
2164 if (!memory_on_stack)
2169 bool QTextEngine::LayoutData::reallocate(int totalGlyphs)
2171 Q_ASSERT(totalGlyphs >= glyphLayout.numGlyphs);
2172 if (memory_on_stack && available_glyphs >= totalGlyphs) {
2173 glyphLayout.grow(glyphLayout.data(), totalGlyphs);
2177 int space_charAttributes = sizeof(HB_CharAttributes)*string.length()/sizeof(void*) + 1;
2178 int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2179 int space_glyphs = QGlyphLayout::spaceNeededForGlyphLayout(totalGlyphs)/sizeof(void*) + 2;
2181 int newAllocated = space_charAttributes + space_glyphs + space_logClusters;
2182 // These values can be negative if the length of string/glyphs causes overflow,
2183 // we can't layout such a long string all at once, so return false here to
2184 // indicate there is a failure
2185 if (space_charAttributes < 0 || space_logClusters < 0 || space_glyphs < 0 || newAllocated < allocated) {
2186 layoutState = LayoutFailed;
2190 void **newMem = memory;
2191 newMem = (void **)::realloc(memory_on_stack ? 0 : memory, newAllocated*sizeof(void *));
2193 layoutState = LayoutFailed;
2196 if (memory_on_stack)
2197 memcpy(newMem, memory, allocated*sizeof(void *));
2199 memory_on_stack = false;
2202 m += space_charAttributes;
2203 logClustersPtr = (unsigned short *) m;
2204 m += space_logClusters;
2206 const int space_preGlyphLayout = space_charAttributes + space_logClusters;
2207 if (allocated < space_preGlyphLayout)
2208 memset(memory + allocated, 0, (space_preGlyphLayout - allocated)*sizeof(void *));
2210 glyphLayout.grow(reinterpret_cast<char *>(m), totalGlyphs);
2212 allocated = newAllocated;
2216 // grow to the new size, copying the existing data to the new layout
2217 void QGlyphLayout::grow(char *address, int totalGlyphs)
2219 QGlyphLayout oldLayout(address, numGlyphs);
2220 QGlyphLayout newLayout(address, totalGlyphs);
2223 // move the existing data
2224 memmove(newLayout.attributes, oldLayout.attributes, numGlyphs * sizeof(HB_GlyphAttributes));
2225 memmove(newLayout.justifications, oldLayout.justifications, numGlyphs * sizeof(QGlyphJustification));
2226 memmove(newLayout.advances_y, oldLayout.advances_y, numGlyphs * sizeof(QFixed));
2227 memmove(newLayout.advances_x, oldLayout.advances_x, numGlyphs * sizeof(QFixed));
2228 memmove(newLayout.glyphs, oldLayout.glyphs, numGlyphs * sizeof(HB_Glyph));
2231 // clear the new data
2232 newLayout.clear(numGlyphs);
2237 void QTextEngine::freeMemory()
2243 layoutData->used = 0;
2244 layoutData->hasBidi = false;
2245 layoutData->layoutState = LayoutEmpty;
2246 layoutData->haveCharAttributes = false;
2248 for (int i = 0; i < lines.size(); ++i) {
2249 lines[i].justified = 0;
2250 lines[i].gridfitted = 0;
2254 int QTextEngine::formatIndex(const QScriptItem *si) const
2256 if (specialData && !specialData->resolvedFormatIndices.isEmpty())
2257 return specialData->resolvedFormatIndices.at(si - &layoutData->items[0]);
2258 QTextDocumentPrivate *p = block.docHandle();
2261 int pos = si->position;
2262 if (specialData && si->position >= specialData->preeditPosition) {
2263 if (si->position < specialData->preeditPosition + specialData->preeditText.length())
2264 pos = qMax(specialData->preeditPosition - 1, 0);
2266 pos -= specialData->preeditText.length();
2268 QTextDocumentPrivate::FragmentIterator it = p->find(block.position() + pos);
2269 return it.value()->format;
2273 QTextCharFormat QTextEngine::format(const QScriptItem *si) const
2275 QTextCharFormat format;
2276 const QTextFormatCollection *formats = 0;
2277 if (block.docHandle()) {
2278 formats = this->formats();
2279 format = formats->charFormat(formatIndex(si));
2281 if (specialData && specialData->resolvedFormatIndices.isEmpty()) {
2282 int end = si->position + length(si);
2283 for (int i = 0; i < specialData->addFormats.size(); ++i) {
2284 const QTextLayout::FormatRange &r = specialData->addFormats.at(i);
2285 if (r.start <= si->position && r.start + r.length >= end) {
2286 if (!specialData->addFormatIndices.isEmpty())
2287 format.merge(formats->format(specialData->addFormatIndices.at(i)));
2289 format.merge(r.format);
2296 void QTextEngine::addRequiredBoundaries() const
2299 for (int i = 0; i < specialData->addFormats.size(); ++i) {
2300 const QTextLayout::FormatRange &r = specialData->addFormats.at(i);
2301 setBoundary(r.start);
2302 setBoundary(r.start + r.length);
2303 //qDebug("adding boundaries %d %d", r.start, r.start+r.length);
2308 bool QTextEngine::atWordSeparator(int position) const
2310 const QChar c = layoutData->string.at(position);
2311 switch (c.toLatin1()) {
2348 bool QTextEngine::atSpace(int position) const
2350 const QChar c = layoutData->string.at(position);
2352 return c == QLatin1Char(' ')
2354 || c == QChar::LineSeparator
2355 || c == QLatin1Char('\t')
2360 void QTextEngine::indexAdditionalFormats()
2362 if (!block.docHandle())
2365 specialData->addFormatIndices.resize(specialData->addFormats.count());
2366 QTextFormatCollection * const formats = this->formats();
2368 for (int i = 0; i < specialData->addFormats.count(); ++i) {
2369 specialData->addFormatIndices[i] = formats->indexForFormat(specialData->addFormats.at(i).format);
2370 specialData->addFormats[i].format = QTextCharFormat();
2374 /* These two helper functions are used to determine whether we need to insert a ZWJ character
2375 between the text that gets truncated and the ellipsis. This is important to get
2376 correctly shaped results for arabic text.
2378 static bool nextCharJoins(const QString &string, int pos)
2380 while (pos < string.length() && string.at(pos).category() == QChar::Mark_NonSpacing)
2382 if (pos == string.length())
2384 return string.at(pos).joining() != QChar::OtherJoining;
2387 static bool prevCharJoins(const QString &string, int pos)
2389 while (pos > 0 && string.at(pos - 1).category() == QChar::Mark_NonSpacing)
2393 return (string.at(pos - 1).joining() == QChar::Dual || string.at(pos - 1).joining() == QChar::Center);
2396 QString QTextEngine::elidedText(Qt::TextElideMode mode, const QFixed &width, int flags) const
2398 // qDebug() << "elidedText; available width" << width.toReal() << "text width:" << this->width(0, layoutData->string.length()).toReal();
2400 if (flags & Qt::TextShowMnemonic) {
2402 HB_CharAttributes *attributes = const_cast<HB_CharAttributes *>(this->attributes());
2405 for (int i = 0; i < layoutData->items.size(); ++i) {
2406 QScriptItem &si = layoutData->items[i];
2410 unsigned short *logClusters = this->logClusters(&si);
2411 QGlyphLayout glyphs = shapedGlyphs(&si);
2413 const int end = si.position + length(&si);
2414 for (int i = si.position; i < end - 1; ++i) {
2415 if (layoutData->string.at(i) == QLatin1Char('&')) {
2416 const int gp = logClusters[i - si.position];
2417 glyphs.attributes[gp].dontPrint = true;
2418 attributes[i + 1].charStop = false;
2419 attributes[i + 1].whiteSpace = false;
2420 attributes[i + 1].lineBreakType = HB_NoBreak;
2421 if (layoutData->string.at(i + 1) == QLatin1Char('&'))
2430 if (mode == Qt::ElideNone
2431 || this->width(0, layoutData->string.length()) <= width
2432 || layoutData->string.length() <= 1)
2433 return layoutData->string;
2435 QFixed ellipsisWidth;
2436 QString ellipsisText;
2438 QChar ellipsisChar(0x2026);
2440 QFontEngine *fe = fnt.d->engineForScript(QUnicodeTables::Common);
2442 QGlyphLayoutArray<1> ellipsisGlyph;
2444 QFontEngine *feForEllipsis = (fe->type() == QFontEngine::Multi)
2445 ? static_cast<QFontEngineMulti *>(fe)->engine(0)
2448 if (feForEllipsis->type() == QFontEngine::Mac)
2451 // the lookup can be really slow when we use XLFD fonts
2452 if (feForEllipsis->type() != QFontEngine::XLFD
2453 && feForEllipsis->canRender(&ellipsisChar, 1)) {
2455 feForEllipsis->stringToCMap(&ellipsisChar, 1, &ellipsisGlyph, &nGlyphs, 0);
2459 if (ellipsisGlyph.glyphs[0]) {
2460 ellipsisWidth = ellipsisGlyph.advances_x[0];
2461 ellipsisText = ellipsisChar;
2463 QString dotDotDot(QLatin1String("..."));
2465 QGlyphLayoutArray<3> glyphs;
2467 if (!fe->stringToCMap(dotDotDot.constData(), 3, &glyphs, &nGlyphs, 0))
2468 // should never happen...
2469 return layoutData->string;
2470 for (int i = 0; i < nGlyphs; ++i)
2471 ellipsisWidth += glyphs.advances_x[i];
2472 ellipsisText = dotDotDot;
2476 const QFixed availableWidth = width - ellipsisWidth;
2477 if (availableWidth < 0)
2480 const HB_CharAttributes *attributes = this->attributes();
2484 if (mode == Qt::ElideRight) {
2485 QFixed currentWidth;
2493 while (nextBreak < layoutData->string.length() && !attributes[nextBreak].charStop)
2496 currentWidth += this->width(pos, nextBreak - pos);
2497 } while (nextBreak < layoutData->string.length()
2498 && currentWidth < availableWidth);
2500 if (nextCharJoins(layoutData->string, pos))
2501 ellipsisText.prepend(QChar(0x200d) /* ZWJ */);
2503 return layoutData->string.left(pos) + ellipsisText;
2504 } else if (mode == Qt::ElideLeft) {
2505 QFixed currentWidth;
2507 int nextBreak = layoutData->string.length();
2513 while (nextBreak > 0 && !attributes[nextBreak].charStop)
2516 currentWidth += this->width(nextBreak, pos - nextBreak);
2517 } while (nextBreak > 0
2518 && currentWidth < availableWidth);
2520 if (prevCharJoins(layoutData->string, pos))
2521 ellipsisText.append(QChar(0x200d) /* ZWJ */);
2523 return ellipsisText + layoutData->string.mid(pos);
2524 } else if (mode == Qt::ElideMiddle) {
2529 int nextLeftBreak = 0;
2531 int rightPos = layoutData->string.length();
2532 int nextRightBreak = layoutData->string.length();
2535 leftPos = nextLeftBreak;
2536 rightPos = nextRightBreak;
2539 while (nextLeftBreak < layoutData->string.length() && !attributes[nextLeftBreak].charStop)
2543 while (nextRightBreak > 0 && !attributes[nextRightBreak].charStop)
2546 leftWidth += this->width(leftPos, nextLeftBreak - leftPos);
2547 rightWidth += this->width(nextRightBreak, rightPos - nextRightBreak);
2548 } while (nextLeftBreak < layoutData->string.length()
2549 && nextRightBreak > 0
2550 && leftWidth + rightWidth < availableWidth);
2552 if (nextCharJoins(layoutData->string, leftPos))
2553 ellipsisText.prepend(QChar(0x200d) /* ZWJ */);
2554 if (prevCharJoins(layoutData->string, rightPos))
2555 ellipsisText.append(QChar(0x200d) /* ZWJ */);
2557 return layoutData->string.left(leftPos) + ellipsisText + layoutData->string.mid(rightPos);
2560 return layoutData->string;
2563 void QTextEngine::setBoundary(int strPos) const
2565 if (strPos <= 0 || strPos >= layoutData->string.length())
2568 int itemToSplit = 0;
2569 while (itemToSplit < layoutData->items.size() && layoutData->items.at(itemToSplit).position <= strPos)
2572 if (layoutData->items.at(itemToSplit).position == strPos) {
2573 // already a split at the requested position
2576 splitItem(itemToSplit, strPos - layoutData->items.at(itemToSplit).position);
2579 void QTextEngine::splitItem(int item, int pos) const
2584 layoutData->items.insert(item + 1, layoutData->items[item]);
2585 QScriptItem &oldItem = layoutData->items[item];
2586 QScriptItem &newItem = layoutData->items[item+1];
2587 newItem.position += pos;
2589 if (oldItem.num_glyphs) {
2590 // already shaped, break glyphs aswell
2591 int breakGlyph = logClusters(&oldItem)[pos];
2593 newItem.num_glyphs = oldItem.num_glyphs - breakGlyph;
2594 oldItem.num_glyphs = breakGlyph;
2595 newItem.glyph_data_offset = oldItem.glyph_data_offset + breakGlyph;
2597 for (int i = 0; i < newItem.num_glyphs; i++)
2598 logClusters(&newItem)[i] -= breakGlyph;
2601 const QGlyphLayout g = shapedGlyphs(&oldItem);
2602 for(int j = 0; j < breakGlyph; ++j)
2603 w += g.advances_x[j];
2605 newItem.width = oldItem.width - w;
2609 // qDebug("split at position %d itempos=%d", pos, item);
2612 QFixed QTextEngine::calculateTabWidth(int item, QFixed x) const
2614 const QScriptItem &si = layoutData->items[item];
2616 QFixed dpiScale = 1;
2617 if (block.docHandle() && block.docHandle()->layout()) {
2618 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
2620 dpiScale = QFixed::fromReal(pdev->logicalDpiY() / qreal(qt_defaultDpiY()));
2622 dpiScale = QFixed::fromReal(fnt.d->dpi / qreal(qt_defaultDpiY()));
2625 QList<QTextOption::Tab> tabArray = option.tabs();
2626 if (!tabArray.isEmpty()) {
2627 if (isRightToLeft()) { // rebase the tabArray positions.
2628 QList<QTextOption::Tab> newTabs;
2629 QList<QTextOption::Tab>::Iterator iter = tabArray.begin();
2630 while(iter != tabArray.end()) {
2631 QTextOption::Tab tab = *iter;
2632 if (tab.type == QTextOption::LeftTab)
2633 tab.type = QTextOption::RightTab;
2634 else if (tab.type == QTextOption::RightTab)
2635 tab.type = QTextOption::LeftTab;
2641 for (int i = 0; i < tabArray.size(); ++i) {
2642 QFixed tab = QFixed::fromReal(tabArray[i].position) * dpiScale;
2643 if (tab > x) { // this is the tab we need.
2644 QTextOption::Tab tabSpec = tabArray[i];
2645 int tabSectionEnd = layoutData->string.count();
2646 if (tabSpec.type == QTextOption::RightTab || tabSpec.type == QTextOption::CenterTab) {
2647 // find next tab to calculate the width required.
2648 tab = QFixed::fromReal(tabSpec.position);
2649 for (int i=item + 1; i < layoutData->items.count(); i++) {
2650 const QScriptItem &item = layoutData->items[i];
2651 if (item.analysis.flags == QScriptAnalysis::TabOrObject) { // found it.
2652 tabSectionEnd = item.position;
2657 else if (tabSpec.type == QTextOption::DelimiterTab)
2658 // find delimitor character to calculate the width required
2659 tabSectionEnd = qMax(si.position, layoutData->string.indexOf(tabSpec.delimiter, si.position) + 1);
2661 if (tabSectionEnd > si.position) {
2663 // Calculate the length of text between this tab and the tabSectionEnd
2664 for (int i=item; i < layoutData->items.count(); i++) {
2665 QScriptItem &item = layoutData->items[i];
2666 if (item.position > tabSectionEnd || item.position <= si.position)
2668 shape(i); // first, lets make sure relevant text is already shaped
2669 QGlyphLayout glyphs = this->shapedGlyphs(&item);
2670 const int end = qMin(item.position + item.num_glyphs, tabSectionEnd) - item.position;
2671 for (int i=0; i < end; i++)
2672 length += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
2673 if (end + item.position == tabSectionEnd && tabSpec.type == QTextOption::DelimiterTab) // remove half of matching char
2674 length -= glyphs.advances_x[end] / 2 * !glyphs.attributes[end].dontPrint;
2677 switch (tabSpec.type) {
2678 case QTextOption::CenterTab:
2681 case QTextOption::DelimiterTab:
2683 case QTextOption::RightTab:
2684 tab = QFixed::fromReal(tabSpec.position) * dpiScale - length;
2685 if (tab < 0) // default to tab taking no space
2688 case QTextOption::LeftTab:
2696 QFixed tab = QFixed::fromReal(option.tabStop());
2698 tab = 80; // default
2700 QFixed nextTabPos = ((x / tab).truncate() + 1) * tab;
2701 QFixed tabWidth = nextTabPos - x;
2706 void QTextEngine::resolveAdditionalFormats() const
2708 if (!specialData || specialData->addFormats.isEmpty()
2709 || !block.docHandle()
2710 || !specialData->resolvedFormatIndices.isEmpty())
2713 QTextFormatCollection *collection = this->formats();
2715 specialData->resolvedFormatIndices.clear();
2716 QVector<int> indices(layoutData->items.count());
2717 for (int i = 0; i < layoutData->items.count(); ++i) {
2718 QTextCharFormat f = format(&layoutData->items.at(i));
2719 indices[i] = collection->indexForFormat(f);
2721 specialData->resolvedFormatIndices = indices;
2724 QFixed QTextEngine::leadingSpaceWidth(const QScriptLine &line)
2726 if (!line.hasTrailingSpaces
2727 || (option.flags() & QTextOption::IncludeTrailingSpaces)
2728 || !isRightToLeft())
2731 int pos = line.length;
2732 const HB_CharAttributes *attributes = this->attributes();
2735 while (pos > 0 && attributes[line.from + pos - 1].whiteSpace)
2737 return width(line.from + pos, line.length - pos);
2740 QStackTextEngine::QStackTextEngine(const QString &string, const QFont &f)
2741 : QTextEngine(string, f),
2742 _layoutData(string, _memory, MemSize)
2745 layoutData = &_layoutData;
2748 QTextItemInt::QTextItemInt(const QScriptItem &si, QFont *font, const QTextCharFormat &format)
2749 : justified(false), underlineStyle(QTextCharFormat::NoUnderline), charFormat(format),
2750 num_chars(0), chars(0), logClusters(0), f(0), fontEngine(0)
2752 // explicitly initialize flags so that initFontAttributes can be called
2753 // multiple times on the same TextItem
2755 if (si.analysis.bidiLevel %2)
2756 flags |= QTextItem::RightToLeft;
2758 descent = si.descent;
2760 fontEngine = f->d->engineForScript(si.analysis.script);
2761 Q_ASSERT(fontEngine);
2763 if (format.hasProperty(QTextFormat::TextUnderlineStyle)) {
2764 underlineStyle = format.underlineStyle();
2765 } else if (format.boolProperty(QTextFormat::FontUnderline)
2766 || f->d->underline) {
2767 underlineStyle = QTextCharFormat::SingleUnderline;
2771 if (underlineStyle == QTextCharFormat::SingleUnderline)
2772 flags |= QTextItem::Underline;
2774 if (f->d->overline || format.fontOverline())
2775 flags |= QTextItem::Overline;
2776 if (f->d->strikeOut || format.fontStrikeOut())
2777 flags |= QTextItem::StrikeOut;
2780 QTextItemInt::QTextItemInt(const QGlyphLayout &g, QFont *font, const QChar *chars_, int numChars, QFontEngine *fe)
2781 : flags(0), justified(false), underlineStyle(QTextCharFormat::NoUnderline),
2782 num_chars(numChars), chars(chars_), logClusters(0), f(font), glyphs(g), fontEngine(fe)
2786 QTextItemInt QTextItemInt::midItem(QFontEngine *fontEngine, int firstGlyphIndex, int numGlyphs) const
2788 QTextItemInt ti = *this;
2789 const int end = firstGlyphIndex + numGlyphs;
2790 ti.glyphs = glyphs.mid(firstGlyphIndex, numGlyphs);
2791 ti.fontEngine = fontEngine;
2793 if (logClusters && chars) {
2794 const int logClusterOffset = logClusters[0];
2795 while (logClusters[ti.chars - chars] - logClusterOffset < firstGlyphIndex)
2798 ti.logClusters += (ti.chars - chars);
2801 int char_start = ti.chars - chars;
2802 while (char_start + ti.num_chars < num_chars && ti.logClusters[ti.num_chars] - logClusterOffset < end)
2809 QTransform qt_true_matrix(qreal w, qreal h, QTransform x)
2811 QRectF rect = x.mapRect(QRectF(0, 0, w, h));
2812 return x * QTransform::fromTranslate(-rect.x(), -rect.y());
2816 glyph_metrics_t glyph_metrics_t::transformed(const QTransform &matrix) const
2818 if (matrix.type() < QTransform::TxTranslate)
2821 glyph_metrics_t m = *this;
2823 qreal w = width.toReal();
2824 qreal h = height.toReal();
2825 QTransform xform = qt_true_matrix(w, h, matrix);
2827 QRectF rect(0, 0, w, h);
2828 rect = xform.mapRect(rect);
2829 m.width = QFixed::fromReal(rect.width());
2830 m.height = QFixed::fromReal(rect.height());
2832 QLineF l = xform.map(QLineF(x.toReal(), y.toReal(), xoff.toReal(), yoff.toReal()));
2834 m.x = QFixed::fromReal(l.x1());
2835 m.y = QFixed::fromReal(l.y1());
2837 // The offset is relative to the baseline which is why we use dx/dy of the line
2838 m.xoff = QFixed::fromReal(l.dx());
2839 m.yoff = QFixed::fromReal(l.dy());