DirectWrite font engine: don't leak the font table buffer
[profile/ivi/qtbase.git] / src / gui / text / qtextengine.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the QtGui module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
16 **
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
20 **
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
28 **
29 ** Other Usage
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qdebug.h"
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"
50 #include "qfont.h"
51 #include "qfont_p.h"
52 #include "qfontengine_p.h"
53 #include "qstring.h"
54 #include <private/qunicodetables_p.h>
55 #include <private/qunicodetools_p.h>
56 #include "qtextdocument_p.h"
57 #include "qrawfont.h"
58 #include "qrawfont_p.h"
59 #include <qguiapplication.h>
60 #include <qinputmethod.h>
61 #include <stdlib.h>
62
63 #include "qfontengine_qpa_p.h"
64
65 QT_BEGIN_NAMESPACE
66
67 static const float smallCapsFraction = 0.7f;
68
69 namespace {
70 // Helper class used in QTextEngine::itemize
71 // keep it out here to allow us to keep supporting various compilers.
72 class Itemizer {
73 public:
74     Itemizer(const QString &string, const QScriptAnalysis *analysis, QScriptItemArray &items)
75         : m_string(string),
76         m_analysis(analysis),
77         m_items(items),
78         m_splitter(0)
79     {
80     }
81     ~Itemizer()
82     {
83         delete m_splitter;
84     }
85
86     /// generate the script items
87     /// The caps parameter is used to choose the algoritm of splitting text and assiging roles to the textitems
88     void generate(int start, int length, QFont::Capitalization caps)
89     {
90         if ((int)caps == (int)QFont::SmallCaps)
91             generateScriptItemsSmallCaps(reinterpret_cast<const ushort *>(m_string.unicode()), start, length);
92         else if(caps == QFont::Capitalize)
93             generateScriptItemsCapitalize(start, length);
94         else if(caps != QFont::MixedCase) {
95             generateScriptItemsAndChangeCase(start, length,
96                 caps == QFont::AllLowercase ? QScriptAnalysis::Lowercase : QScriptAnalysis::Uppercase);
97         }
98         else
99             generateScriptItems(start, length);
100     }
101
102 private:
103     enum { MaxItemLength = 4096 };
104
105     void generateScriptItemsAndChangeCase(int start, int length, QScriptAnalysis::Flags flags)
106     {
107         generateScriptItems(start, length);
108         if (m_items.isEmpty()) // the next loop won't work in that case
109             return;
110         QScriptItemArray::Iterator iter = m_items.end();
111         do {
112             iter--;
113             if (iter->analysis.flags < QScriptAnalysis::LineOrParagraphSeparator)
114                 iter->analysis.flags = flags;
115         } while (iter->position > start);
116     }
117
118     void generateScriptItems(int start, int length)
119     {
120         if (!length)
121             return;
122         const int end = start + length;
123         for (int i = start + 1; i < end; ++i) {
124             // According to the unicode spec we should be treating characters in the Common script
125             // (punctuation, spaces, etc) as being the same script as the surrounding text for the
126             // purpose of splitting up text. This is important because, for example, a fullstop
127             // (0x2E) can be used to indicate an abbreviation and so must be treated as part of a
128             // word.  Thus it must be passed along with the word in languages that have to calculate
129             // word breaks.  For example the thai word "ครม." has no word breaks but the word "ครม"
130             // does.
131             // Unfortuntely because we split up the strings for both wordwrapping and for setting
132             // the font and because Japanese and Chinese are also aliases of the script "Common",
133             // doing this would break too many things.  So instead we only pass the full stop
134             // along, and nothing else.
135             if (m_analysis[i].bidiLevel == m_analysis[start].bidiLevel
136                 && m_analysis[i].flags == m_analysis[start].flags
137                 && (m_analysis[i].script == m_analysis[start].script || m_string[i] == QLatin1Char('.'))
138                 && m_analysis[i].flags < QScriptAnalysis::SpaceTabOrObject
139                 && i - start < MaxItemLength)
140                 continue;
141             m_items.append(QScriptItem(start, m_analysis[start]));
142             start = i;
143         }
144         m_items.append(QScriptItem(start, m_analysis[start]));
145     }
146
147     void generateScriptItemsCapitalize(int start, int length)
148     {
149         if (!length)
150             return;
151
152         if (!m_splitter)
153             m_splitter = new QTextBoundaryFinder(QTextBoundaryFinder::Word,
154                                                  m_string.constData(), m_string.length(),
155                                                  /*buffer*/0, /*buffer size*/0);
156
157         m_splitter->setPosition(start);
158         QScriptAnalysis itemAnalysis = m_analysis[start];
159
160         if (m_splitter->boundaryReasons() & QTextBoundaryFinder::StartWord) {
161             itemAnalysis.flags = QScriptAnalysis::Uppercase;
162             m_splitter->toNextBoundary();
163         }
164
165         const int end = start + length;
166         for (int i = start + 1; i < end; ++i) {
167
168             bool atWordBoundary = false;
169
170             if (i == m_splitter->position()) {
171                 if (m_splitter->boundaryReasons() & QTextBoundaryFinder::StartWord
172                     && m_analysis[i].flags < QScriptAnalysis::TabOrObject)
173                     atWordBoundary = true;
174
175                 m_splitter->toNextBoundary();
176             }
177
178             if (m_analysis[i] == itemAnalysis
179                 && m_analysis[i].flags < QScriptAnalysis::TabOrObject
180                 && !atWordBoundary
181                 && i - start < MaxItemLength)
182                 continue;
183
184             m_items.append(QScriptItem(start, itemAnalysis));
185             start = i;
186             itemAnalysis = m_analysis[start];
187
188             if (atWordBoundary)
189                 itemAnalysis.flags = QScriptAnalysis::Uppercase;
190         }
191         m_items.append(QScriptItem(start, itemAnalysis));
192     }
193
194     void generateScriptItemsSmallCaps(const ushort *uc, int start, int length)
195     {
196         if (!length)
197             return;
198         bool lower = (QChar::category(uc[start]) == QChar::Letter_Lowercase);
199         const int end = start + length;
200         // split text into parts that are already uppercase and parts that are lowercase, and mark the latter to be uppercased later.
201         for (int i = start + 1; i < end; ++i) {
202             bool l = (QChar::category(uc[i]) == QChar::Letter_Lowercase);
203             if ((m_analysis[i] == m_analysis[start])
204                 && m_analysis[i].flags < QScriptAnalysis::TabOrObject
205                 && l == lower
206                 && i - start < MaxItemLength)
207                 continue;
208             m_items.append(QScriptItem(start, m_analysis[start]));
209             if (lower)
210                 m_items.last().analysis.flags = QScriptAnalysis::SmallCaps;
211
212             start = i;
213             lower = l;
214         }
215         m_items.append(QScriptItem(start, m_analysis[start]));
216         if (lower)
217             m_items.last().analysis.flags = QScriptAnalysis::SmallCaps;
218     }
219
220     const QString &m_string;
221     const QScriptAnalysis * const m_analysis;
222     QScriptItemArray &m_items;
223     QTextBoundaryFinder *m_splitter;
224 };
225 }
226
227
228 // ----------------------------------------------------------------------------
229 //
230 // The BiDi algorithm
231 //
232 // ----------------------------------------------------------------------------
233
234 #define BIDI_DEBUG 0
235 #if (BIDI_DEBUG >= 1)
236 QT_BEGIN_INCLUDE_NAMESPACE
237 #include <iostream>
238 QT_END_INCLUDE_NAMESPACE
239 using namespace std;
240
241 static const char *directions[] = {
242     "DirL", "DirR", "DirEN", "DirES", "DirET", "DirAN", "DirCS", "DirB", "DirS", "DirWS", "DirON",
243     "DirLRE", "DirLRO", "DirAL", "DirRLE", "DirRLO", "DirPDF", "DirNSM", "DirBN"
244 };
245
246 #endif
247
248 struct QBidiStatus {
249     QBidiStatus() {
250         eor = QChar::DirON;
251         lastStrong = QChar::DirON;
252         last = QChar:: DirON;
253         dir = QChar::DirON;
254     }
255     QChar::Direction eor;
256     QChar::Direction lastStrong;
257     QChar::Direction last;
258     QChar::Direction dir;
259 };
260
261 enum { MaxBidiLevel = 61 };
262
263 struct QBidiControl {
264     inline QBidiControl(bool rtl)
265         : cCtx(0), base(rtl ? 1 : 0), level(rtl ? 1 : 0), override(false) {}
266
267     inline void embed(bool rtl, bool o = false) {
268         unsigned int toAdd = 1;
269         if((level%2 != 0) == rtl ) {
270             ++toAdd;
271         }
272         if (level + toAdd <= MaxBidiLevel) {
273             ctx[cCtx].level = level;
274             ctx[cCtx].override = override;
275             cCtx++;
276             override = o;
277             level += toAdd;
278         }
279     }
280     inline bool canPop() const { return cCtx != 0; }
281     inline void pdf() {
282         Q_ASSERT(cCtx);
283         --cCtx;
284         level = ctx[cCtx].level;
285         override = ctx[cCtx].override;
286     }
287
288     inline QChar::Direction basicDirection() const {
289         return (base ? QChar::DirR : QChar:: DirL);
290     }
291     inline unsigned int baseLevel() const {
292         return base;
293     }
294     inline QChar::Direction direction() const {
295         return ((level%2) ? QChar::DirR : QChar:: DirL);
296     }
297
298     struct {
299         unsigned int level;
300         bool override;
301     } ctx[MaxBidiLevel];
302     unsigned int cCtx;
303     const unsigned int base;
304     unsigned int level;
305     bool override;
306 };
307
308
309 static void appendItems(QScriptAnalysis *analysis, int &start, int &stop, const QBidiControl &control, QChar::Direction dir)
310 {
311     if (start > stop)
312         return;
313
314     int level = control.level;
315
316     if(dir != QChar::DirON && !control.override) {
317         // add level of run (cases I1 & I2)
318         if(level % 2) {
319             if(dir == QChar::DirL || dir == QChar::DirAN || dir == QChar::DirEN)
320                 level++;
321         } else {
322             if(dir == QChar::DirR)
323                 level++;
324             else if(dir == QChar::DirAN || dir == QChar::DirEN)
325                 level += 2;
326         }
327     }
328
329 #if (BIDI_DEBUG >= 1)
330     qDebug("new run: dir=%s from %d, to %d level = %d override=%d", directions[dir], start, stop, level, control.override);
331 #endif
332     QScriptAnalysis *s = analysis + start;
333     const QScriptAnalysis *e = analysis + stop;
334     while (s <= e) {
335         s->bidiLevel = level;
336         ++s;
337     }
338     ++stop;
339     start = stop;
340 }
341
342 static QChar::Direction skipBoundryNeutrals(QScriptAnalysis *analysis,
343                                             const ushort *unicode, int length,
344                                             int &sor, int &eor, QBidiControl &control)
345 {
346     QChar::Direction dir = control.basicDirection();
347     int level = sor > 0 ? analysis[sor - 1].bidiLevel : control.level;
348     while (sor < length) {
349         dir = QChar::direction(unicode[sor]);
350         // Keep skipping DirBN as if it doesn't exist
351         if (dir != QChar::DirBN)
352             break;
353         analysis[sor++].bidiLevel = level;
354     }
355
356     eor = sor;
357     if (eor == length)
358         dir = control.basicDirection();
359
360     return dir;
361 }
362
363 // creates the next QScript items.
364 static bool bidiItemize(QTextEngine *engine, QScriptAnalysis *analysis, QBidiControl &control)
365 {
366     bool rightToLeft = (control.basicDirection() == 1);
367     bool hasBidi = rightToLeft;
368 #if BIDI_DEBUG >= 2
369     qDebug() << "bidiItemize: rightToLeft=" << rightToLeft << engine->layoutData->string;
370 #endif
371
372     int sor = 0;
373     int eor = -1;
374
375
376     int length = engine->layoutData->string.length();
377
378     const ushort *unicode = (const ushort *)engine->layoutData->string.unicode();
379     int current = 0;
380
381     QChar::Direction dir = rightToLeft ? QChar::DirR : QChar::DirL;
382     QBidiStatus status;
383
384     QChar::Direction sdir = QChar::direction(*unicode);
385     if (sdir != QChar::DirL && sdir != QChar::DirR && sdir != QChar::DirEN && sdir != QChar::DirAN)
386         sdir = QChar::DirON;
387     else
388         dir = QChar::DirON;
389     status.eor = sdir;
390     status.lastStrong = rightToLeft ? QChar::DirR : QChar::DirL;
391     status.last = status.lastStrong;
392     status.dir = sdir;
393
394
395     while (current <= length) {
396
397         QChar::Direction dirCurrent;
398         if (current == (int)length)
399             dirCurrent = control.basicDirection();
400         else
401             dirCurrent = QChar::direction(unicode[current]);
402
403 #if (BIDI_DEBUG >= 2)
404 //         qDebug() << "pos=" << current << " dir=" << directions[dir]
405 //                  << " current=" << directions[dirCurrent] << " last=" << directions[status.last]
406 //                  << " eor=" << eor << '/' << directions[status.eor]
407 //                  << " sor=" << sor << " lastStrong="
408 //                  << directions[status.lastStrong]
409 //                  << " level=" << (int)control.level << " override=" << (bool)control.override;
410 #endif
411
412         switch(dirCurrent) {
413
414             // embedding and overrides (X1-X9 in the BiDi specs)
415         case QChar::DirRLE:
416         case QChar::DirRLO:
417         case QChar::DirLRE:
418         case QChar::DirLRO:
419             {
420                 bool rtl = (dirCurrent == QChar::DirRLE || dirCurrent == QChar::DirRLO);
421                 hasBidi |= rtl;
422                 bool override = (dirCurrent == QChar::DirLRO || dirCurrent == QChar::DirRLO);
423
424                 unsigned int level = control.level+1;
425                 if ((level%2 != 0) == rtl) ++level;
426                 if(level < MaxBidiLevel) {
427                     eor = current-1;
428                     appendItems(analysis, sor, eor, control, dir);
429                     eor = current;
430                     control.embed(rtl, override);
431                     QChar::Direction edir = (rtl ? QChar::DirR : QChar::DirL);
432                     dir = status.eor = edir;
433                     status.lastStrong = edir;
434                 }
435                 break;
436             }
437         case QChar::DirPDF:
438             {
439                 if (control.canPop()) {
440                     if (dir != control.direction()) {
441                         eor = current-1;
442                         appendItems(analysis, sor, eor, control, dir);
443                         dir = control.direction();
444                     }
445                     eor = current;
446                     appendItems(analysis, sor, eor, control, dir);
447                     control.pdf();
448                     dir = QChar::DirON; status.eor = QChar::DirON;
449                     status.last = control.direction();
450                     if (control.override)
451                         dir = control.direction();
452                     else
453                         dir = QChar::DirON;
454                     status.lastStrong = control.direction();
455                 }
456                 break;
457             }
458
459             // strong types
460         case QChar::DirL:
461             if(dir == QChar::DirON)
462                 dir = QChar::DirL;
463             switch(status.last)
464                 {
465                 case QChar::DirL:
466                     eor = current; status.eor = QChar::DirL; break;
467                 case QChar::DirR:
468                 case QChar::DirAL:
469                 case QChar::DirEN:
470                 case QChar::DirAN:
471                     if (eor >= 0) {
472                         appendItems(analysis, sor, eor, control, dir);
473                         status.eor = dir = skipBoundryNeutrals(analysis, unicode, length, sor, eor, control);
474                     } else {
475                         eor = current; status.eor = dir;
476                     }
477                     break;
478                 case QChar::DirES:
479                 case QChar::DirET:
480                 case QChar::DirCS:
481                 case QChar::DirBN:
482                 case QChar::DirB:
483                 case QChar::DirS:
484                 case QChar::DirWS:
485                 case QChar::DirON:
486                     if(dir != QChar::DirL) {
487                         //last stuff takes embedding dir
488                         if(control.direction() == QChar::DirR) {
489                             if(status.eor != QChar::DirR) {
490                                 // AN or EN
491                                 appendItems(analysis, sor, eor, control, dir);
492                                 status.eor = QChar::DirON;
493                                 dir = QChar::DirR;
494                             }
495                             eor = current - 1;
496                             appendItems(analysis, sor, eor, control, dir);
497                             status.eor = dir = skipBoundryNeutrals(analysis, unicode, length, sor, eor, control);
498                         } else {
499                             if(status.eor != QChar::DirL) {
500                                 appendItems(analysis, sor, eor, control, dir);
501                                 status.eor = QChar::DirON;
502                                 dir = QChar::DirL;
503                             } else {
504                                 eor = current; status.eor = QChar::DirL; break;
505                             }
506                         }
507                     } else {
508                         eor = current; status.eor = QChar::DirL;
509                     }
510                 default:
511                     break;
512                 }
513             status.lastStrong = QChar::DirL;
514             break;
515         case QChar::DirAL:
516         case QChar::DirR:
517             hasBidi = true;
518             if(dir == QChar::DirON) dir = QChar::DirR;
519             switch(status.last)
520                 {
521                 case QChar::DirL:
522                 case QChar::DirEN:
523                 case QChar::DirAN:
524                     if (eor >= 0)
525                         appendItems(analysis, sor, eor, control, dir);
526                     // fall through
527                 case QChar::DirR:
528                 case QChar::DirAL:
529                     dir = QChar::DirR; eor = current; status.eor = QChar::DirR; break;
530                 case QChar::DirES:
531                 case QChar::DirET:
532                 case QChar::DirCS:
533                 case QChar::DirBN:
534                 case QChar::DirB:
535                 case QChar::DirS:
536                 case QChar::DirWS:
537                 case QChar::DirON:
538                     if(status.eor != QChar::DirR && status.eor != QChar::DirAL) {
539                         //last stuff takes embedding dir
540                         if(control.direction() == QChar::DirR
541                            || status.lastStrong == QChar::DirR || status.lastStrong == QChar::DirAL) {
542                             appendItems(analysis, sor, eor, control, dir);
543                             dir = QChar::DirR; status.eor = QChar::DirON;
544                             eor = current;
545                         } else {
546                             eor = current - 1;
547                             appendItems(analysis, sor, eor, control, dir);
548                             dir = QChar::DirR; status.eor = QChar::DirON;
549                         }
550                     } else {
551                         eor = current; status.eor = QChar::DirR;
552                     }
553                 default:
554                     break;
555                 }
556             status.lastStrong = dirCurrent;
557             break;
558
559             // weak types:
560
561         case QChar::DirNSM:
562             if (eor == current-1)
563                 eor = current;
564             break;
565         case QChar::DirEN:
566             // if last strong was AL change EN to AN
567             if(status.lastStrong != QChar::DirAL) {
568                 if(dir == QChar::DirON) {
569                     if(status.lastStrong == QChar::DirL)
570                         dir = QChar::DirL;
571                     else
572                         dir = QChar::DirEN;
573                 }
574                 switch(status.last)
575                     {
576                     case QChar::DirET:
577                         if (status.lastStrong == QChar::DirR || status.lastStrong == QChar::DirAL) {
578                             appendItems(analysis, sor, eor, control, dir);
579                             status.eor = QChar::DirON;
580                             dir = QChar::DirAN;
581                         }
582                         // fall through
583                     case QChar::DirEN:
584                     case QChar::DirL:
585                         eor = current;
586                         status.eor = dirCurrent;
587                         break;
588                     case QChar::DirR:
589                     case QChar::DirAL:
590                     case QChar::DirAN:
591                         if (eor >= 0)
592                             appendItems(analysis, sor, eor, control, dir);
593                         else
594                             eor = current;
595                         status.eor = QChar::DirEN;
596                         dir = QChar::DirAN; break;
597                     case QChar::DirES:
598                     case QChar::DirCS:
599                         if(status.eor == QChar::DirEN || dir == QChar::DirAN) {
600                             eor = current; break;
601                         }
602                     case QChar::DirBN:
603                     case QChar::DirB:
604                     case QChar::DirS:
605                     case QChar::DirWS:
606                     case QChar::DirON:
607                         if(status.eor == QChar::DirR) {
608                             // neutrals go to R
609                             eor = current - 1;
610                             appendItems(analysis, sor, eor, control, dir);
611                             dir = QChar::DirON; status.eor = QChar::DirEN;
612                             dir = QChar::DirAN;
613                         }
614                         else if(status.eor == QChar::DirL ||
615                                  (status.eor == QChar::DirEN && status.lastStrong == QChar::DirL)) {
616                             eor = current; status.eor = dirCurrent;
617                         } else {
618                             // numbers on both sides, neutrals get right to left direction
619                             if(dir != QChar::DirL) {
620                                 appendItems(analysis, sor, eor, control, dir);
621                                 dir = QChar::DirON; status.eor = QChar::DirON;
622                                 eor = current - 1;
623                                 dir = QChar::DirR;
624                                 appendItems(analysis, sor, eor, control, dir);
625                                 dir = QChar::DirON; status.eor = QChar::DirON;
626                                 dir = QChar::DirAN;
627                             } else {
628                                 eor = current; status.eor = dirCurrent;
629                             }
630                         }
631                     default:
632                         break;
633                     }
634                 break;
635             }
636         case QChar::DirAN:
637             hasBidi = true;
638             dirCurrent = QChar::DirAN;
639             if(dir == QChar::DirON) dir = QChar::DirAN;
640             switch(status.last)
641                 {
642                 case QChar::DirL:
643                 case QChar::DirAN:
644                     eor = current; status.eor = QChar::DirAN; break;
645                 case QChar::DirR:
646                 case QChar::DirAL:
647                 case QChar::DirEN:
648                     if (eor >= 0){
649                         appendItems(analysis, sor, eor, control, dir);
650                     } else {
651                         eor = current;
652                     }
653                     dir = QChar::DirAN; status.eor = QChar::DirAN;
654                     break;
655                 case QChar::DirCS:
656                     if(status.eor == QChar::DirAN) {
657                         eor = current; break;
658                     }
659                 case QChar::DirES:
660                 case QChar::DirET:
661                 case QChar::DirBN:
662                 case QChar::DirB:
663                 case QChar::DirS:
664                 case QChar::DirWS:
665                 case QChar::DirON:
666                     if(status.eor == QChar::DirR) {
667                         // neutrals go to R
668                         eor = current - 1;
669                         appendItems(analysis, sor, eor, control, dir);
670                         status.eor = QChar::DirAN;
671                         dir = QChar::DirAN;
672                     } else if(status.eor == QChar::DirL ||
673                                (status.eor == QChar::DirEN && status.lastStrong == QChar::DirL)) {
674                         eor = current; status.eor = dirCurrent;
675                     } else {
676                         // numbers on both sides, neutrals get right to left direction
677                         if(dir != QChar::DirL) {
678                             appendItems(analysis, sor, eor, control, dir);
679                             status.eor = QChar::DirON;
680                             eor = current - 1;
681                             dir = QChar::DirR;
682                             appendItems(analysis, sor, eor, control, dir);
683                             status.eor = QChar::DirAN;
684                             dir = QChar::DirAN;
685                         } else {
686                             eor = current; status.eor = dirCurrent;
687                         }
688                     }
689                 default:
690                     break;
691                 }
692             break;
693         case QChar::DirES:
694         case QChar::DirCS:
695             break;
696         case QChar::DirET:
697             if(status.last == QChar::DirEN) {
698                 dirCurrent = QChar::DirEN;
699                 eor = current; status.eor = dirCurrent;
700             }
701             break;
702
703             // boundary neutrals should be ignored
704         case QChar::DirBN:
705             break;
706             // neutrals
707         case QChar::DirB:
708             // ### what do we do with newline and paragraph separators that come to here?
709             break;
710         case QChar::DirS:
711             // ### implement rule L1
712             break;
713         case QChar::DirWS:
714         case QChar::DirON:
715             break;
716         default:
717             break;
718         }
719
720         //qDebug() << "     after: dir=" << //        dir << " current=" << dirCurrent << " last=" << status.last << " eor=" << status.eor << " lastStrong=" << status.lastStrong << " embedding=" << control.direction();
721
722         if(current >= (int)length) break;
723
724         // set status.last as needed.
725         switch(dirCurrent) {
726         case QChar::DirET:
727         case QChar::DirES:
728         case QChar::DirCS:
729         case QChar::DirS:
730         case QChar::DirWS:
731         case QChar::DirON:
732             switch(status.last)
733             {
734             case QChar::DirL:
735             case QChar::DirR:
736             case QChar::DirAL:
737             case QChar::DirEN:
738             case QChar::DirAN:
739                 status.last = dirCurrent;
740                 break;
741             default:
742                 status.last = QChar::DirON;
743             }
744             break;
745         case QChar::DirNSM:
746         case QChar::DirBN:
747             // ignore these
748             break;
749         case QChar::DirLRO:
750         case QChar::DirLRE:
751             status.last = QChar::DirL;
752             break;
753         case QChar::DirRLO:
754         case QChar::DirRLE:
755             status.last = QChar::DirR;
756             break;
757         case QChar::DirEN:
758             if (status.last == QChar::DirL) {
759                 status.last = QChar::DirL;
760                 break;
761             }
762             // fall through
763         default:
764             status.last = dirCurrent;
765         }
766
767         ++current;
768     }
769
770 #if (BIDI_DEBUG >= 1)
771     qDebug() << "reached end of line current=" << current << ", eor=" << eor;
772 #endif
773     eor = current - 1; // remove dummy char
774
775     if (sor <= eor)
776         appendItems(analysis, sor, eor, control, dir);
777
778     return hasBidi;
779 }
780
781 void QTextEngine::bidiReorder(int numItems, const quint8 *levels, int *visualOrder)
782 {
783
784     // first find highest and lowest levels
785     quint8 levelLow = 128;
786     quint8 levelHigh = 0;
787     int i = 0;
788     while (i < numItems) {
789         //printf("level = %d\n", r->level);
790         if (levels[i] > levelHigh)
791             levelHigh = levels[i];
792         if (levels[i] < levelLow)
793             levelLow = levels[i];
794         i++;
795     }
796
797     // implements reordering of the line (L2 according to BiDi spec):
798     // L2. From the highest level found in the text to the lowest odd level on each line,
799     // reverse any contiguous sequence of characters that are at that level or higher.
800
801     // reversing is only done up to the lowest odd level
802     if(!(levelLow%2)) levelLow++;
803
804 #if (BIDI_DEBUG >= 1)
805 //     qDebug() << "reorderLine: lineLow = " << (uint)levelLow << ", lineHigh = " << (uint)levelHigh;
806 #endif
807
808     int count = numItems - 1;
809     for (i = 0; i < numItems; i++)
810         visualOrder[i] = i;
811
812     while(levelHigh >= levelLow) {
813         int i = 0;
814         while (i < count) {
815             while(i < count && levels[i] < levelHigh) i++;
816             int start = i;
817             while(i <= count && levels[i] >= levelHigh) i++;
818             int end = i-1;
819
820             if(start != end) {
821                 //qDebug() << "reversing from " << start << " to " << end;
822                 for(int j = 0; j < (end-start+1)/2; j++) {
823                     int tmp = visualOrder[start+j];
824                     visualOrder[start+j] = visualOrder[end-j];
825                     visualOrder[end-j] = tmp;
826                 }
827             }
828             i++;
829         }
830         levelHigh--;
831     }
832
833 #if (BIDI_DEBUG >= 1)
834 //     qDebug() << "visual order is:";
835 //     for (i = 0; i < numItems; i++)
836 //         qDebug() << visualOrder[i];
837 #endif
838 }
839
840 QT_BEGIN_INCLUDE_NAMESPACE
841
842
843 #include <private/qharfbuzz_p.h>
844
845 QT_END_INCLUDE_NAMESPACE
846
847 // ask the font engine to find out which glyphs (as an index in the specific font) to use for the text in one item.
848 static bool stringToGlyphs(HB_ShaperItem *item, QGlyphLayout *glyphs, QFontEngine *fontEngine)
849 {
850     int nGlyphs = item->num_glyphs;
851
852     QTextEngine::ShaperFlags shaperFlags(QTextEngine::GlyphIndicesOnly);
853     if (item->item.bidiLevel % 2)
854         shaperFlags |= QTextEngine::RightToLeft;
855
856     bool result = fontEngine->stringToCMap(reinterpret_cast<const QChar *>(item->string + item->item.pos), item->item.length, glyphs, &nGlyphs, shaperFlags);
857     item->num_glyphs = nGlyphs;
858     glyphs->numGlyphs = nGlyphs;
859     return result;
860 }
861
862 // shape all the items that intersect with the line, taking tab widths into account to find out what text actually fits in the line.
863 void QTextEngine::shapeLine(const QScriptLine &line)
864 {
865     QFixed x;
866     bool first = true;
867     const int end = findItem(line.from + line.length - 1);
868     int item = findItem(line.from);
869     if (item == -1)
870         return;
871     for (item = findItem(line.from); item <= end; ++item) {
872         QScriptItem &si = layoutData->items[item];
873         if (si.analysis.flags == QScriptAnalysis::Tab) {
874             ensureSpace(1);
875             si.width = calculateTabWidth(item, x);
876         } else {
877             shape(item);
878         }
879         if (first && si.position != line.from) { // that means our x position has to be offset
880             QGlyphLayout glyphs = shapedGlyphs(&si);
881             Q_ASSERT(line.from > si.position);
882             for (int i = line.from - si.position - 1; i >= 0; i--) {
883                 x -= glyphs.effectiveAdvance(i);
884             }
885         }
886         first = false;
887
888         x += si.width;
889     }
890 }
891
892
893 void QTextEngine::shapeText(int item) const
894 {
895     Q_ASSERT(item < layoutData->items.size());
896     QScriptItem &si = layoutData->items[item];
897
898     if (si.num_glyphs)
899         return;
900
901     shapeTextWithHarfbuzz(item);
902
903     si.width = 0;
904
905     if (!si.num_glyphs)
906         return;
907     QGlyphLayout glyphs = shapedGlyphs(&si);
908
909     bool letterSpacingIsAbsolute;
910     QFixed letterSpacing, wordSpacing;
911 #ifndef QT_NO_RAWFONT
912     if (useRawFont) {
913         QTextCharFormat f = format(&si);
914         wordSpacing = QFixed::fromReal(f.fontWordSpacing());
915         letterSpacing = QFixed::fromReal(f.fontLetterSpacing());
916         letterSpacingIsAbsolute = true;
917     } else
918 #endif
919     {
920         QFont font = this->font(si);
921         letterSpacingIsAbsolute = font.d->letterSpacingIsAbsolute;
922         letterSpacing = font.d->letterSpacing;
923         wordSpacing = font.d->wordSpacing;
924
925         if (letterSpacingIsAbsolute && letterSpacing.value())
926             letterSpacing *= font.d->dpi / qt_defaultDpiY();
927     }
928
929     if (letterSpacing != 0) {
930         for (int i = 1; i < si.num_glyphs; ++i) {
931             if (glyphs.attributes[i].clusterStart) {
932                 if (letterSpacingIsAbsolute)
933                     glyphs.advances_x[i-1] += letterSpacing;
934                 else {
935                     QFixed &advance = glyphs.advances_x[i-1];
936                     advance += (letterSpacing - 100) * advance / 100;
937                 }
938             }
939         }
940         if (letterSpacingIsAbsolute)
941             glyphs.advances_x[si.num_glyphs-1] += letterSpacing;
942         else {
943             QFixed &advance = glyphs.advances_x[si.num_glyphs-1];
944             advance += (letterSpacing - 100) * advance / 100;
945         }
946     }
947     if (wordSpacing != 0) {
948         for (int i = 0; i < si.num_glyphs; ++i) {
949             if (glyphs.attributes[i].justification == HB_Space
950                 || glyphs.attributes[i].justification == HB_Arabic_Space) {
951                 // word spacing only gets added once to a consecutive run of spaces (see CSS spec)
952                 if (i + 1 == si.num_glyphs
953                     ||(glyphs.attributes[i+1].justification != HB_Space
954                        && glyphs.attributes[i+1].justification != HB_Arabic_Space))
955                     glyphs.advances_x[i] += wordSpacing;
956             }
957         }
958     }
959
960     for (int i = 0; i < si.num_glyphs; ++i)
961         si.width += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
962 }
963
964 static inline bool hasCaseChange(const QScriptItem &si)
965 {
966     return si.analysis.flags == QScriptAnalysis::SmallCaps ||
967            si.analysis.flags == QScriptAnalysis::Uppercase ||
968            si.analysis.flags == QScriptAnalysis::Lowercase;
969 }
970
971
972 static inline void moveGlyphData(const QGlyphLayout &destination, const QGlyphLayout &source, int num)
973 {
974     if (num > 0 && destination.glyphs != source.glyphs) {
975         memmove(destination.glyphs, source.glyphs, num * sizeof(HB_Glyph));
976         memmove(destination.attributes, source.attributes, num * sizeof(HB_GlyphAttributes));
977         memmove(destination.advances_x, source.advances_x, num * sizeof(HB_Fixed));
978         memmove(destination.offsets, source.offsets, num * sizeof(HB_FixedPoint));
979     }
980 }
981
982 /// take the item from layoutData->items and
983 void QTextEngine::shapeTextWithHarfbuzz(int item) const
984 {
985     Q_ASSERT(sizeof(HB_Fixed) == sizeof(QFixed));
986     Q_ASSERT(sizeof(HB_FixedPoint) == sizeof(QFixedPoint));
987
988     QScriptItem &si = layoutData->items[item];
989
990     si.glyph_data_offset = layoutData->used;
991
992     QFontEngine *font = fontEngine(si, &si.ascent, &si.descent, &si.leading);
993
994     bool kerningEnabled;
995 #ifndef QT_NO_RAWFONT
996     if (useRawFont) {
997         QTextCharFormat f = format(&si);
998         kerningEnabled = f.fontKerning();
999     } else
1000 #endif
1001         kerningEnabled = this->font(si).d->kerning;
1002
1003     HB_ShaperItem entire_shaper_item;
1004     memset(&entire_shaper_item, 0, sizeof(entire_shaper_item));
1005     entire_shaper_item.string = reinterpret_cast<const HB_UChar16 *>(layoutData->string.constData());
1006     entire_shaper_item.stringLength = layoutData->string.length();
1007     entire_shaper_item.item.script = (HB_Script)si.analysis.script;
1008     entire_shaper_item.item.pos = si.position;
1009     entire_shaper_item.item.length = length(item);
1010     entire_shaper_item.item.bidiLevel = si.analysis.bidiLevel;
1011
1012     QVarLengthArray<HB_UChar16, 256> casedString;
1013     if (hasCaseChange(si)) {
1014         if (casedString.size() < static_cast<int>(entire_shaper_item.item.length))
1015             casedString.resize(entire_shaper_item.item.length);
1016         HB_UChar16 *uc = casedString.data();
1017         for (uint i = 0; i < entire_shaper_item.item.length; ++i) {
1018             if(si.analysis.flags == QScriptAnalysis::Lowercase)
1019                 uc[i] = QChar::toLower(entire_shaper_item.string[si.position + i]);
1020             else
1021                 uc[i] = QChar::toUpper(entire_shaper_item.string[si.position + i]);
1022         }
1023         entire_shaper_item.item.pos = 0;
1024         entire_shaper_item.string = uc;
1025         entire_shaper_item.stringLength = entire_shaper_item.item.length;
1026     }
1027
1028     entire_shaper_item.shaperFlags = 0;
1029     if (!kerningEnabled)
1030         entire_shaper_item.shaperFlags |= HB_ShaperFlag_NoKerning;
1031     if (option.useDesignMetrics())
1032         entire_shaper_item.shaperFlags |= HB_ShaperFlag_UseDesignMetrics;
1033
1034     entire_shaper_item.num_glyphs = qMax(layoutData->glyphLayout.numGlyphs - layoutData->used, int(entire_shaper_item.item.length));
1035     if (!ensureSpace(entire_shaper_item.num_glyphs))
1036         return;
1037     QGlyphLayout initialGlyphs = availableGlyphs(&si).mid(0, entire_shaper_item.num_glyphs);
1038
1039     if (!stringToGlyphs(&entire_shaper_item, &initialGlyphs, font)) {
1040         if (!ensureSpace(entire_shaper_item.num_glyphs))
1041             return;
1042         initialGlyphs = availableGlyphs(&si).mid(0, entire_shaper_item.num_glyphs);
1043         if (!stringToGlyphs(&entire_shaper_item, &initialGlyphs, font)) {
1044             // ############ if this happens there's a bug in the fontengine
1045             return;
1046         }
1047     }
1048
1049     // split up the item into parts that come from different font engines.
1050     QVarLengthArray<int> itemBoundaries(2);
1051     // k * 2 entries, array[k] == index in string, array[k + 1] == index in glyphs
1052     itemBoundaries[0] = entire_shaper_item.item.pos;
1053     itemBoundaries[1] = 0;
1054
1055     if (font->type() == QFontEngine::Multi) {
1056         uint lastEngine = 0;
1057         int charIdx = entire_shaper_item.item.pos;
1058         const int stringEnd = charIdx + entire_shaper_item.item.length;
1059         for (quint32 i = 0; i < entire_shaper_item.num_glyphs; ++i, ++charIdx) {
1060             uint engineIdx = initialGlyphs.glyphs[i] >> 24;
1061             if (engineIdx != lastEngine && i > 0) {
1062                 itemBoundaries.append(charIdx);
1063                 itemBoundaries.append(i);
1064             }
1065             lastEngine = engineIdx;
1066             if (HB_IsHighSurrogate(entire_shaper_item.string[charIdx])
1067                 && charIdx < stringEnd - 1
1068                 && HB_IsLowSurrogate(entire_shaper_item.string[charIdx + 1]))
1069                 ++charIdx;
1070         }
1071     }
1072
1073
1074
1075     int remaining_glyphs = entire_shaper_item.num_glyphs;
1076     int glyph_pos = 0;
1077     // for each item shape using harfbuzz and store the results in our layoutData's glyphs array.
1078     for (int k = 0; k < itemBoundaries.size(); k += 2) { // for the +2, see the comment at the definition of itemBoundaries
1079
1080         HB_ShaperItem shaper_item = entire_shaper_item;
1081
1082         shaper_item.item.pos = itemBoundaries[k];
1083         if (k < itemBoundaries.size() - 3) {
1084             shaper_item.item.length = itemBoundaries[k + 2] - shaper_item.item.pos;
1085             shaper_item.num_glyphs = itemBoundaries[k + 3] - itemBoundaries[k + 1];
1086         } else { // last combo in the list, avoid out of bounds access.
1087             shaper_item.item.length -= shaper_item.item.pos - entire_shaper_item.item.pos;
1088             shaper_item.num_glyphs -= itemBoundaries[k + 1];
1089         }
1090         shaper_item.initialGlyphCount = shaper_item.num_glyphs;
1091         if (shaper_item.num_glyphs < shaper_item.item.length)
1092             shaper_item.num_glyphs = shaper_item.item.length;
1093
1094         QFontEngine *actualFontEngine = font;
1095         uint engineIdx = 0;
1096         if (font->type() == QFontEngine::Multi) {
1097             engineIdx = uint(availableGlyphs(&si).glyphs[glyph_pos] >> 24);
1098
1099             actualFontEngine = static_cast<QFontEngineMulti *>(font)->engine(engineIdx);
1100         }
1101
1102         si.ascent = qMax(actualFontEngine->ascent(), si.ascent);
1103         si.descent = qMax(actualFontEngine->descent(), si.descent);
1104         si.leading = qMax(actualFontEngine->leading(), si.leading);
1105
1106         shaper_item.font = actualFontEngine->harfbuzzFont();
1107         shaper_item.face = actualFontEngine->initializedHarfbuzzFace();
1108
1109         shaper_item.glyphIndicesPresent = true;
1110
1111         remaining_glyphs -= shaper_item.initialGlyphCount;
1112
1113         do {
1114             if (!ensureSpace(glyph_pos + shaper_item.num_glyphs + remaining_glyphs))
1115                 return;
1116
1117             const QGlyphLayout g = availableGlyphs(&si).mid(glyph_pos);
1118             if (shaper_item.num_glyphs > shaper_item.item.length)
1119                 moveGlyphData(g.mid(shaper_item.num_glyphs), g.mid(shaper_item.initialGlyphCount), remaining_glyphs);
1120
1121             shaper_item.glyphs = g.glyphs;
1122             shaper_item.attributes = g.attributes;
1123             shaper_item.advances = reinterpret_cast<HB_Fixed *>(g.advances_x);
1124             shaper_item.offsets = reinterpret_cast<HB_FixedPoint *>(g.offsets);
1125
1126             if (engineIdx != 0 && shaper_item.glyphIndicesPresent) {
1127                 for (hb_uint32 i = 0; i < shaper_item.initialGlyphCount; ++i)
1128                     shaper_item.glyphs[i] &= 0x00ffffff;
1129             }
1130
1131             shaper_item.log_clusters = logClusters(&si) + shaper_item.item.pos - entire_shaper_item.item.pos;
1132
1133 //          qDebug("    .. num_glyphs=%d, used=%d, item.num_glyphs=%d", num_glyphs, used, shaper_item.num_glyphs);
1134         } while (!qShapeItem(&shaper_item)); // this does the actual shaping via harfbuzz.
1135
1136         QGlyphLayout g = availableGlyphs(&si).mid(glyph_pos, shaper_item.num_glyphs);
1137         moveGlyphData(g.mid(shaper_item.num_glyphs), g.mid(shaper_item.initialGlyphCount), remaining_glyphs);
1138
1139         for (hb_uint32 i = 0; i < shaper_item.item.length; ++i)
1140             shaper_item.log_clusters[i] += glyph_pos;
1141
1142         if (kerningEnabled && !shaper_item.kerning_applied)
1143             actualFontEngine->doKerning(&g, option.useDesignMetrics() ? QFlag(QTextEngine::DesignMetrics) : QFlag(0));
1144
1145         if (engineIdx != 0) {
1146             for (hb_uint32 i = 0; i < shaper_item.num_glyphs; ++i)
1147                 g.glyphs[i] |= (engineIdx << 24);
1148         }
1149
1150         glyph_pos += shaper_item.num_glyphs;
1151     }
1152
1153 //     qDebug("    -> item: script=%d num_glyphs=%d", shaper_item.script, shaper_item.num_glyphs);
1154     si.num_glyphs = glyph_pos;
1155
1156     layoutData->used += si.num_glyphs;
1157 }
1158
1159 static void init(QTextEngine *e)
1160 {
1161     e->ignoreBidi = false;
1162     e->cacheGlyphs = false;
1163     e->forceJustification = false;
1164     e->visualMovement = false;
1165     e->delayDecorations = false;
1166
1167     e->layoutData = 0;
1168
1169     e->minWidth = 0;
1170     e->maxWidth = 0;
1171
1172     e->underlinePositions = 0;
1173     e->specialData = 0;
1174     e->stackEngine = false;
1175 #ifndef QT_NO_RAWFONT
1176     e->useRawFont = false;
1177 #endif
1178 }
1179
1180 QTextEngine::QTextEngine()
1181 {
1182     init(this);
1183 }
1184
1185 QTextEngine::QTextEngine(const QString &str, const QFont &f)
1186     : text(str),
1187       fnt(f)
1188 {
1189     init(this);
1190 }
1191
1192 QTextEngine::~QTextEngine()
1193 {
1194     if (!stackEngine)
1195         delete layoutData;
1196     delete specialData;
1197     resetFontEngineCache();
1198 }
1199
1200 const HB_CharAttributes *QTextEngine::attributes() const
1201 {
1202     if (layoutData && layoutData->haveCharAttributes)
1203         return (HB_CharAttributes *) layoutData->memory;
1204
1205     itemize();
1206     if (! ensureSpace(layoutData->string.length()))
1207         return NULL;
1208
1209     QVarLengthArray<HB_ScriptItem> hbScriptItems(layoutData->items.size());
1210
1211     for (int i = 0; i < layoutData->items.size(); ++i) {
1212         const QScriptItem &si = layoutData->items[i];
1213         hbScriptItems[i].pos = si.position;
1214         hbScriptItems[i].length = length(i);
1215         hbScriptItems[i].bidiLevel = si.analysis.bidiLevel;
1216         hbScriptItems[i].script = (HB_Script)si.analysis.script;
1217     }
1218
1219     QUnicodeTools::initCharAttributes(reinterpret_cast<const HB_UChar16 *>(layoutData->string.constData()),
1220                                       layoutData->string.length(),
1221                                       hbScriptItems.data(), hbScriptItems.size(),
1222                                       (HB_CharAttributes *)layoutData->memory);
1223
1224
1225     layoutData->haveCharAttributes = true;
1226     return (HB_CharAttributes *) layoutData->memory;
1227 }
1228
1229 void QTextEngine::shape(int item) const
1230 {
1231     if (layoutData->items[item].analysis.flags == QScriptAnalysis::Object) {
1232         ensureSpace(1);
1233         if (block.docHandle()) {
1234             QTextFormat format = formats()->format(formatIndex(&layoutData->items[item]));
1235             docLayout()->resizeInlineObject(QTextInlineObject(item, const_cast<QTextEngine *>(this)),
1236                                             layoutData->items[item].position + block.position(), format);
1237         }
1238     } else if (layoutData->items[item].analysis.flags == QScriptAnalysis::Tab) {
1239         // set up at least the ascent/descent/leading of the script item for the tab
1240         fontEngine(layoutData->items[item],
1241                    &layoutData->items[item].ascent,
1242                    &layoutData->items[item].descent,
1243                    &layoutData->items[item].leading);
1244     } else {
1245         shapeText(item);
1246     }
1247 }
1248
1249 static inline void releaseCachedFontEngine(QFontEngine *fontEngine)
1250 {
1251     if (fontEngine) {
1252         fontEngine->ref.deref();
1253         if (fontEngine->cache_count == 0 && fontEngine->ref.load() == 0)
1254             delete fontEngine;
1255     }
1256 }
1257
1258 void QTextEngine::resetFontEngineCache()
1259 {
1260     releaseCachedFontEngine(feCache.prevFontEngine);
1261     releaseCachedFontEngine(feCache.prevScaledFontEngine);
1262     feCache.reset();
1263 }
1264
1265 void QTextEngine::invalidate()
1266 {
1267     freeMemory();
1268     minWidth = 0;
1269     maxWidth = 0;
1270     if (specialData)
1271         specialData->resolvedFormatIndices.clear();
1272
1273     resetFontEngineCache();
1274 }
1275
1276 void QTextEngine::clearLineData()
1277 {
1278     lines.clear();
1279 }
1280
1281 void QTextEngine::validate() const
1282 {
1283     if (layoutData)
1284         return;
1285     layoutData = new LayoutData();
1286     if (block.docHandle()) {
1287         layoutData->string = block.text();
1288         if (option.flags() & QTextOption::ShowLineAndParagraphSeparators)
1289             layoutData->string += QLatin1Char(block.next().isValid() ? 0xb6 : 0x20);
1290     } else {
1291         layoutData->string = text;
1292     }
1293     if (specialData && specialData->preeditPosition != -1)
1294         layoutData->string.insert(specialData->preeditPosition, specialData->preeditText);
1295 }
1296
1297 void QTextEngine::itemize() const
1298 {
1299     validate();
1300     if (layoutData->items.size())
1301         return;
1302
1303     int length = layoutData->string.length();
1304     if (!length)
1305         return;
1306
1307     bool ignore = ignoreBidi;
1308
1309     bool rtl = isRightToLeft();
1310
1311     if (!ignore && !rtl) {
1312         ignore = true;
1313         const QChar *start = layoutData->string.unicode();
1314         const QChar * const end = start + length;
1315         while (start < end) {
1316             if (start->unicode() >= 0x590) {
1317                 ignore = false;
1318                 break;
1319             }
1320             ++start;
1321         }
1322     }
1323
1324     QVarLengthArray<QScriptAnalysis, 4096> scriptAnalysis(length);
1325     QScriptAnalysis *analysis = scriptAnalysis.data();
1326
1327     QBidiControl control(rtl);
1328
1329     if (ignore) {
1330         memset(analysis, 0, length*sizeof(QScriptAnalysis));
1331         if (option.textDirection() == Qt::RightToLeft) {
1332             for (int i = 0; i < length; ++i)
1333                 analysis[i].bidiLevel = 1;
1334             layoutData->hasBidi = true;
1335         }
1336     } else {
1337         layoutData->hasBidi = bidiItemize(const_cast<QTextEngine *>(this), analysis, control);
1338     }
1339
1340     const ushort *uc = reinterpret_cast<const ushort *>(layoutData->string.unicode());
1341     const ushort *e = uc + length;
1342     int lastScript = QUnicodeTables::Common;
1343     while (uc < e) {
1344         switch (*uc) {
1345         case QChar::ObjectReplacementCharacter:
1346             analysis->script = QUnicodeTables::Common;
1347             analysis->flags = QScriptAnalysis::Object;
1348             break;
1349         case QChar::LineSeparator:
1350             if (analysis->bidiLevel % 2)
1351                 --analysis->bidiLevel;
1352             analysis->script = QUnicodeTables::Common;
1353             analysis->flags = QScriptAnalysis::LineOrParagraphSeparator;
1354             if (option.flags() & QTextOption::ShowLineAndParagraphSeparators)
1355                 *const_cast<ushort*>(uc) = 0x21B5; // visual line separator
1356             break;
1357         case QChar::Tabulation:
1358             analysis->script = QUnicodeTables::Common;
1359             analysis->flags = QScriptAnalysis::Tab;
1360             analysis->bidiLevel = control.baseLevel();
1361             break;
1362         case QChar::Space:
1363         case QChar::Nbsp:
1364             if (option.flags() & QTextOption::ShowTabsAndSpaces) {
1365                 analysis->script = QUnicodeTables::Common;
1366                 analysis->flags = QScriptAnalysis::Space;
1367                 analysis->bidiLevel = control.baseLevel();
1368                 break;
1369             }
1370         // fall through
1371         default:
1372             int script = QUnicodeTables::script(*uc);
1373             analysis->script = script == QUnicodeTables::Inherited ? lastScript : script;
1374             analysis->flags = QScriptAnalysis::None;
1375             break;
1376         }
1377         lastScript = analysis->script;
1378         ++uc;
1379         ++analysis;
1380     }
1381     if (option.flags() & QTextOption::ShowLineAndParagraphSeparators) {
1382         (analysis-1)->flags = QScriptAnalysis::LineOrParagraphSeparator; // to exclude it from width
1383     }
1384
1385     Itemizer itemizer(layoutData->string, scriptAnalysis.data(), layoutData->items);
1386
1387     const QTextDocumentPrivate *p = block.docHandle();
1388     if (p) {
1389         SpecialData *s = specialData;
1390
1391         QTextDocumentPrivate::FragmentIterator it = p->find(block.position());
1392         QTextDocumentPrivate::FragmentIterator end = p->find(block.position() + block.length() - 1); // -1 to omit the block separator char
1393         int format = it.value()->format;
1394
1395         int prevPosition = 0;
1396         int position = prevPosition;
1397         while (1) {
1398             const QTextFragmentData * const frag = it.value();
1399             if (it == end || format != frag->format) {
1400                 if (s && position >= s->preeditPosition) {
1401                     position += s->preeditText.length();
1402                     s = 0;
1403                 }
1404                 Q_ASSERT(position <= length);
1405                 QFont::Capitalization capitalization =
1406                         formats()->charFormat(format).hasProperty(QTextFormat::FontCapitalization)
1407                         ? formats()->charFormat(format).fontCapitalization()
1408                         : formats()->defaultFont().capitalization();
1409                 itemizer.generate(prevPosition, position - prevPosition, capitalization);
1410                 if (it == end) {
1411                     if (position < length)
1412                         itemizer.generate(position, length - position, capitalization);
1413                     break;
1414                 }
1415                 format = frag->format;
1416                 prevPosition = position;
1417             }
1418             position += frag->size_array[0];
1419             ++it;
1420         }
1421     } else {
1422 #ifndef QT_NO_RAWFONT
1423         if (useRawFont && specialData) {
1424             int lastIndex = 0;
1425             for (int i = 0; i < specialData->addFormats.size(); ++i) {
1426                 const QTextLayout::FormatRange &range = specialData->addFormats.at(i);
1427                 if (range.format.fontCapitalization()) {
1428                     itemizer.generate(lastIndex, range.start - lastIndex, QFont::MixedCase);
1429                     itemizer.generate(range.start, range.length, range.format.fontCapitalization());
1430                     lastIndex = range.start + range.length;
1431                 }
1432             }
1433             itemizer.generate(lastIndex, length - lastIndex, QFont::MixedCase);
1434         } else
1435 #endif
1436             itemizer.generate(0, length, static_cast<QFont::Capitalization> (fnt.d->capital));
1437     }
1438
1439     addRequiredBoundaries();
1440     resolveAdditionalFormats();
1441 }
1442
1443 bool QTextEngine::isRightToLeft() const
1444 {
1445     switch (option.textDirection()) {
1446     case Qt::LeftToRight:
1447         return false;
1448     case Qt::RightToLeft:
1449         return true;
1450     default:
1451         break;
1452     }
1453     if (!layoutData)
1454         itemize();
1455     // this places the cursor in the right position depending on the keyboard layout
1456     if (layoutData->string.isEmpty())
1457         return qApp ? qApp->inputMethod()->inputDirection() == Qt::RightToLeft : false;
1458     return layoutData->string.isRightToLeft();
1459 }
1460
1461
1462 int QTextEngine::findItem(int strPos) const
1463 {
1464     itemize();
1465     int left = 1;
1466     int right = layoutData->items.size()-1;
1467     while(left <= right) {
1468         int middle = ((right-left)/2)+left;
1469         if (strPos > layoutData->items[middle].position)
1470             left = middle+1;
1471         else if(strPos < layoutData->items[middle].position)
1472             right = middle-1;
1473         else {
1474             return middle;
1475         }
1476     }
1477     return right;
1478 }
1479
1480 QFixed QTextEngine::width(int from, int len) const
1481 {
1482     itemize();
1483
1484     QFixed w = 0;
1485
1486 //     qDebug("QTextEngine::width(from = %d, len = %d), numItems=%d, strleng=%d", from,  len, items.size(), string.length());
1487     for (int i = 0; i < layoutData->items.size(); i++) {
1488         const QScriptItem *si = layoutData->items.constData() + i;
1489         int pos = si->position;
1490         int ilen = length(i);
1491 //          qDebug("item %d: from %d len %d", i, pos, ilen);
1492         if (pos >= from + len)
1493             break;
1494         if (pos + ilen > from) {
1495             if (!si->num_glyphs)
1496                 shape(i);
1497
1498             if (si->analysis.flags == QScriptAnalysis::Object) {
1499                 w += si->width;
1500                 continue;
1501             } else if (si->analysis.flags == QScriptAnalysis::Tab) {
1502                 w += calculateTabWidth(i, w);
1503                 continue;
1504             }
1505
1506
1507             QGlyphLayout glyphs = shapedGlyphs(si);
1508             unsigned short *logClusters = this->logClusters(si);
1509
1510 //             fprintf(stderr, "  logclusters:");
1511 //             for (int k = 0; k < ilen; k++)
1512 //                 fprintf(stderr, " %d", logClusters[k]);
1513 //             fprintf(stderr, "\n");
1514             // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1515             int charFrom = from - pos;
1516             if (charFrom < 0)
1517                 charFrom = 0;
1518             int glyphStart = logClusters[charFrom];
1519             if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1520                 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1521                     charFrom++;
1522             if (charFrom < ilen) {
1523                 glyphStart = logClusters[charFrom];
1524                 int charEnd = from + len - 1 - pos;
1525                 if (charEnd >= ilen)
1526                     charEnd = ilen-1;
1527                 int glyphEnd = logClusters[charEnd];
1528                 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1529                     charEnd++;
1530                 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1531
1532 //                 qDebug("char: start=%d end=%d / glyph: start = %d, end = %d", charFrom, charEnd, glyphStart, glyphEnd);
1533                 for (int i = glyphStart; i < glyphEnd; i++)
1534                     w += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
1535             }
1536         }
1537     }
1538 //     qDebug("   --> w= %d ", w);
1539     return w;
1540 }
1541
1542 glyph_metrics_t QTextEngine::boundingBox(int from,  int len) const
1543 {
1544     itemize();
1545
1546     glyph_metrics_t gm;
1547
1548     for (int i = 0; i < layoutData->items.size(); i++) {
1549         const QScriptItem *si = layoutData->items.constData() + i;
1550
1551         int pos = si->position;
1552         int ilen = length(i);
1553         if (pos > from + len)
1554             break;
1555         if (pos + ilen > from) {
1556             if (!si->num_glyphs)
1557                 shape(i);
1558
1559             if (si->analysis.flags == QScriptAnalysis::Object) {
1560                 gm.width += si->width;
1561                 continue;
1562             } else if (si->analysis.flags == QScriptAnalysis::Tab) {
1563                 gm.width += calculateTabWidth(i, gm.width);
1564                 continue;
1565             }
1566
1567             unsigned short *logClusters = this->logClusters(si);
1568             QGlyphLayout glyphs = shapedGlyphs(si);
1569
1570             // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1571             int charFrom = from - pos;
1572             if (charFrom < 0)
1573                 charFrom = 0;
1574             int glyphStart = logClusters[charFrom];
1575             if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1576                 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1577                     charFrom++;
1578             if (charFrom < ilen) {
1579                 QFontEngine *fe = fontEngine(*si);
1580                 glyphStart = logClusters[charFrom];
1581                 int charEnd = from + len - 1 - pos;
1582                 if (charEnd >= ilen)
1583                     charEnd = ilen-1;
1584                 int glyphEnd = logClusters[charEnd];
1585                 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1586                     charEnd++;
1587                 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1588                 if (glyphStart <= glyphEnd ) {
1589                     glyph_metrics_t m = fe->boundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
1590                     gm.x = qMin(gm.x, m.x + gm.xoff);
1591                     gm.y = qMin(gm.y, m.y + gm.yoff);
1592                     gm.width = qMax(gm.width, m.width+gm.xoff);
1593                     gm.height = qMax(gm.height, m.height+gm.yoff);
1594                     gm.xoff += m.xoff;
1595                     gm.yoff += m.yoff;
1596                 }
1597             }
1598         }
1599     }
1600     return gm;
1601 }
1602
1603 glyph_metrics_t QTextEngine::tightBoundingBox(int from,  int len) const
1604 {
1605     itemize();
1606
1607     glyph_metrics_t gm;
1608
1609     for (int i = 0; i < layoutData->items.size(); i++) {
1610         const QScriptItem *si = layoutData->items.constData() + i;
1611         int pos = si->position;
1612         int ilen = length(i);
1613         if (pos > from + len)
1614             break;
1615         if (pos + len > from) {
1616             if (!si->num_glyphs)
1617                 shape(i);
1618             unsigned short *logClusters = this->logClusters(si);
1619             QGlyphLayout glyphs = shapedGlyphs(si);
1620
1621             // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1622             int charFrom = from - pos;
1623             if (charFrom < 0)
1624                 charFrom = 0;
1625             int glyphStart = logClusters[charFrom];
1626             if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1627                 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1628                     charFrom++;
1629             if (charFrom < ilen) {
1630                 glyphStart = logClusters[charFrom];
1631                 int charEnd = from + len - 1 - pos;
1632                 if (charEnd >= ilen)
1633                     charEnd = ilen-1;
1634                 int glyphEnd = logClusters[charEnd];
1635                 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1636                     charEnd++;
1637                 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1638                 if (glyphStart <= glyphEnd ) {
1639                     QFontEngine *fe = fontEngine(*si);
1640                     glyph_metrics_t m = fe->tightBoundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
1641                     gm.x = qMin(gm.x, m.x + gm.xoff);
1642                     gm.y = qMin(gm.y, m.y + gm.yoff);
1643                     gm.width = qMax(gm.width, m.width+gm.xoff);
1644                     gm.height = qMax(gm.height, m.height+gm.yoff);
1645                     gm.xoff += m.xoff;
1646                     gm.yoff += m.yoff;
1647                 }
1648             }
1649         }
1650     }
1651     return gm;
1652 }
1653
1654 QFont QTextEngine::font(const QScriptItem &si) const
1655 {
1656     QFont font = fnt;
1657     if (hasFormats()) {
1658         QTextCharFormat f = format(&si);
1659         font = f.font();
1660
1661         if (block.docHandle() && block.docHandle()->layout()) {
1662             // Make sure we get the right dpi on printers
1663             QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
1664             if (pdev)
1665                 font = QFont(font, pdev);
1666         } else {
1667             font = font.resolve(fnt);
1668         }
1669         QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
1670         if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
1671             if (font.pointSize() != -1)
1672                 font.setPointSize((font.pointSize() * 2) / 3);
1673             else
1674                 font.setPixelSize((font.pixelSize() * 2) / 3);
1675         }
1676     }
1677
1678     if (si.analysis.flags == QScriptAnalysis::SmallCaps)
1679         font = font.d->smallCapsFont();
1680
1681     return font;
1682 }
1683
1684 QTextEngine::FontEngineCache::FontEngineCache()
1685 {
1686     reset();
1687 }
1688
1689 //we cache the previous results of this function, as calling it numerous times with the same effective
1690 //input is common (and hard to cache at a higher level)
1691 QFontEngine *QTextEngine::fontEngine(const QScriptItem &si, QFixed *ascent, QFixed *descent, QFixed *leading) const
1692 {
1693     QFontEngine *engine = 0;
1694     QFontEngine *scaledEngine = 0;
1695     int script = si.analysis.script;
1696
1697     QFont font = fnt;
1698 #ifndef QT_NO_RAWFONT
1699     if (useRawFont && rawFont.isValid()) {
1700         if (feCache.prevFontEngine && feCache.prevFontEngine->type() == QFontEngine::Multi && feCache.prevScript == script) {
1701             engine = feCache.prevFontEngine;
1702         } else {
1703             engine = QFontEngineMultiQPA::createMultiFontEngine(rawFont.d->fontEngine, script);
1704             feCache.prevFontEngine = engine;
1705             feCache.prevScript = script;
1706             engine->ref.ref();
1707             if (feCache.prevScaledFontEngine)
1708                 releaseCachedFontEngine(feCache.prevScaledFontEngine);
1709         }
1710         if (si.analysis.flags & QFont::SmallCaps) {
1711             if (feCache.prevScaledFontEngine) {
1712                 scaledEngine = feCache.prevScaledFontEngine;
1713             } else {
1714                 QFontEngine *scEngine = rawFont.d->fontEngine->cloneWithSize(smallCapsFraction * rawFont.pixelSize());
1715                 scaledEngine = QFontEngineMultiQPA::createMultiFontEngine(scEngine, script);
1716                 scaledEngine->ref.ref();
1717                 feCache.prevScaledFontEngine = scaledEngine;
1718             }
1719         }
1720     } else
1721 #endif
1722     {
1723         if (hasFormats()) {
1724             if (feCache.prevFontEngine && feCache.prevPosition == si.position && feCache.prevLength == length(&si) && feCache.prevScript == script) {
1725                 engine = feCache.prevFontEngine;
1726                 scaledEngine = feCache.prevScaledFontEngine;
1727             } else {
1728                 QTextCharFormat f = format(&si);
1729                 font = f.font();
1730
1731                 if (block.docHandle() && block.docHandle()->layout()) {
1732                     // Make sure we get the right dpi on printers
1733                     QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
1734                     if (pdev)
1735                         font = QFont(font, pdev);
1736                 } else {
1737                     font = font.resolve(fnt);
1738                 }
1739                 engine = font.d->engineForScript(script);
1740                 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
1741                 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
1742                     if (font.pointSize() != -1)
1743                         font.setPointSize((font.pointSize() * 2) / 3);
1744                     else
1745                         font.setPixelSize((font.pixelSize() * 2) / 3);
1746                     scaledEngine = font.d->engineForScript(script);
1747                 }
1748
1749                 if (engine)
1750                     engine->ref.ref();
1751                 if (feCache.prevFontEngine)
1752                     releaseCachedFontEngine(feCache.prevFontEngine);
1753                 feCache.prevFontEngine = engine;
1754
1755                 if (scaledEngine)
1756                     scaledEngine->ref.ref();
1757                 if (feCache.prevScaledFontEngine)
1758                     releaseCachedFontEngine(feCache.prevScaledFontEngine);
1759                 feCache.prevScaledFontEngine = scaledEngine;
1760
1761                 feCache.prevScript = script;
1762                 feCache.prevPosition = si.position;
1763                 feCache.prevLength = length(&si);
1764             }
1765         } else {
1766             if (feCache.prevFontEngine && feCache.prevScript == script && feCache.prevPosition == -1)
1767                 engine = feCache.prevFontEngine;
1768             else {
1769                 engine = font.d->engineForScript(script);
1770
1771                 if (engine)
1772                     engine->ref.ref();
1773                 if (feCache.prevFontEngine)
1774                     releaseCachedFontEngine(feCache.prevFontEngine);
1775                 feCache.prevFontEngine = engine;
1776
1777                 feCache.prevScript = script;
1778                 feCache.prevPosition = -1;
1779                 feCache.prevLength = -1;
1780                 feCache.prevScaledFontEngine = 0;
1781             }
1782         }
1783
1784         if (si.analysis.flags == QScriptAnalysis::SmallCaps) {
1785             QFontPrivate *p = font.d->smallCapsFontPrivate();
1786             scaledEngine = p->engineForScript(script);
1787         }
1788     }
1789
1790     if (ascent) {
1791         *ascent = engine->ascent();
1792         *descent = engine->descent();
1793         *leading = engine->leading();
1794     }
1795
1796     if (scaledEngine)
1797         return scaledEngine;
1798     return engine;
1799 }
1800
1801 struct QJustificationPoint {
1802     int type;
1803     QFixed kashidaWidth;
1804     QGlyphLayout glyph;
1805     QFontEngine *fontEngine;
1806 };
1807
1808 Q_DECLARE_TYPEINFO(QJustificationPoint, Q_PRIMITIVE_TYPE);
1809
1810 static void set(QJustificationPoint *point, int type, const QGlyphLayout &glyph, QFontEngine *fe)
1811 {
1812     point->type = type;
1813     point->glyph = glyph;
1814     point->fontEngine = fe;
1815
1816     if (type >= HB_Arabic_Normal) {
1817         QChar ch(0x640); // Kashida character
1818         QGlyphLayoutArray<8> glyphs;
1819         int nglyphs = 7;
1820         fe->stringToCMap(&ch, 1, &glyphs, &nglyphs, 0);
1821         if (glyphs.glyphs[0] && glyphs.advances_x[0] != 0) {
1822             point->kashidaWidth = glyphs.advances_x[0];
1823         } else {
1824             point->type = HB_NoJustification;
1825             point->kashidaWidth = 0;
1826         }
1827     }
1828 }
1829
1830
1831 void QTextEngine::justify(const QScriptLine &line)
1832 {
1833 //     qDebug("justify: line.gridfitted = %d, line.justified=%d", line.gridfitted, line.justified);
1834     if (line.gridfitted && line.justified)
1835         return;
1836
1837     if (!line.gridfitted) {
1838         // redo layout in device metrics, then adjust
1839         const_cast<QScriptLine &>(line).gridfitted = true;
1840     }
1841
1842     if ((option.alignment() & Qt::AlignHorizontal_Mask) != Qt::AlignJustify)
1843         return;
1844
1845     itemize();
1846
1847     if (!forceJustification) {
1848         int end = line.from + (int)line.length;
1849         if (end == layoutData->string.length())
1850             return; // no justification at end of paragraph
1851         if (end && layoutData->items[findItem(end-1)].analysis.flags == QScriptAnalysis::LineOrParagraphSeparator)
1852             return; // no justification at the end of an explicitly separated line
1853     }
1854
1855     // justify line
1856     int maxJustify = 0;
1857
1858     // don't include trailing white spaces when doing justification
1859     int line_length = line.length;
1860     const HB_CharAttributes *a = attributes();
1861     if (! a)
1862         return;
1863     a += line.from;
1864     while (line_length && a[line_length-1].whiteSpace)
1865         --line_length;
1866     // subtract one char more, as we can't justfy after the last character
1867     --line_length;
1868
1869     if (!line_length)
1870         return;
1871
1872     int firstItem = findItem(line.from);
1873     int nItems = findItem(line.from + line_length - 1) - firstItem + 1;
1874
1875     QVarLengthArray<QJustificationPoint> justificationPoints;
1876     int nPoints = 0;
1877 //     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());
1878     QFixed minKashida = 0x100000;
1879
1880     // we need to do all shaping before we go into the next loop, as we there
1881     // store pointers to the glyph data that could get reallocated by the shaping
1882     // process.
1883     for (int i = 0; i < nItems; ++i) {
1884         QScriptItem &si = layoutData->items[firstItem + i];
1885         if (!si.num_glyphs)
1886             shape(firstItem + i);
1887     }
1888
1889     for (int i = 0; i < nItems; ++i) {
1890         QScriptItem &si = layoutData->items[firstItem + i];
1891
1892         int kashida_type = HB_Arabic_Normal;
1893         int kashida_pos = -1;
1894
1895         int start = qMax(line.from - si.position, 0);
1896         int end = qMin(line.from + line_length - (int)si.position, length(firstItem+i));
1897
1898         unsigned short *log_clusters = logClusters(&si);
1899
1900         int gs = log_clusters[start];
1901         int ge = (end == length(firstItem+i) ? si.num_glyphs : log_clusters[end]);
1902
1903         const QGlyphLayout g = shapedGlyphs(&si);
1904
1905         for (int i = gs; i < ge; ++i) {
1906             g.justifications[i].type = QGlyphJustification::JustifyNone;
1907             g.justifications[i].nKashidas = 0;
1908             g.justifications[i].space_18d6 = 0;
1909
1910             justificationPoints.resize(nPoints+3);
1911             int justification = g.attributes[i].justification;
1912
1913             switch(justification) {
1914             case HB_NoJustification:
1915                 break;
1916             case HB_Space          :
1917                 // fall through
1918             case HB_Arabic_Space   :
1919                 if (kashida_pos >= 0) {
1920 //                     qDebug("kashida position at %d in word", kashida_pos);
1921                     set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
1922                     if (justificationPoints[nPoints].kashidaWidth > 0) {
1923                         minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
1924                         maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
1925                         ++nPoints;
1926                     }
1927                 }
1928                 kashida_pos = -1;
1929                 kashida_type = HB_Arabic_Normal;
1930                 // fall through
1931             case HB_Character      :
1932                 set(&justificationPoints[nPoints++], justification, g.mid(i), fontEngine(si));
1933                 maxJustify = qMax(maxJustify, justification);
1934                 break;
1935             case HB_Arabic_Normal  :
1936             case HB_Arabic_Waw     :
1937             case HB_Arabic_BaRa    :
1938             case HB_Arabic_Alef    :
1939             case HB_Arabic_HaaDal  :
1940             case HB_Arabic_Seen    :
1941             case HB_Arabic_Kashida :
1942                 if (justification >= kashida_type) {
1943                     kashida_pos = i;
1944                     kashida_type = justification;
1945                 }
1946             }
1947         }
1948         if (kashida_pos >= 0) {
1949             set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
1950             if (justificationPoints[nPoints].kashidaWidth > 0) {
1951                 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
1952                 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
1953                 ++nPoints;
1954             }
1955         }
1956     }
1957
1958     QFixed leading = leadingSpaceWidth(line);
1959     QFixed need = line.width - line.textWidth - leading;
1960     if (need < 0) {
1961         // line overflows already!
1962         const_cast<QScriptLine &>(line).justified = true;
1963         return;
1964     }
1965
1966 //     qDebug("doing justification: textWidth=%x, requested=%x, maxJustify=%d", line.textWidth.value(), line.width.value(), maxJustify);
1967 //     qDebug("     minKashida=%f, need=%f", minKashida.toReal(), need.toReal());
1968
1969     // distribute in priority order
1970     if (maxJustify >= HB_Arabic_Normal) {
1971         while (need >= minKashida) {
1972             for (int type = maxJustify; need >= minKashida && type >= HB_Arabic_Normal; --type) {
1973                 for (int i = 0; need >= minKashida && i < nPoints; ++i) {
1974                     if (justificationPoints[i].type == type && justificationPoints[i].kashidaWidth <= need) {
1975                         justificationPoints[i].glyph.justifications->nKashidas++;
1976                         // ############
1977                         justificationPoints[i].glyph.justifications->space_18d6 += justificationPoints[i].kashidaWidth.value();
1978                         need -= justificationPoints[i].kashidaWidth;
1979 //                         qDebug("adding kashida type %d with width %x, neednow %x", type, justificationPoints[i].kashidaWidth, need.value());
1980                     }
1981                 }
1982             }
1983         }
1984     }
1985     Q_ASSERT(need >= 0);
1986     if (!need)
1987         goto end;
1988
1989     maxJustify = qMin(maxJustify, (int)HB_Space);
1990     for (int type = maxJustify; need != 0 && type > 0; --type) {
1991         int n = 0;
1992         for (int i = 0; i < nPoints; ++i) {
1993             if (justificationPoints[i].type == type)
1994                 ++n;
1995         }
1996 //          qDebug("number of points for justification type %d: %d", type, n);
1997
1998
1999         if (!n)
2000             continue;
2001
2002         for (int i = 0; i < nPoints; ++i) {
2003             if (justificationPoints[i].type == type) {
2004                 QFixed add = need/n;
2005 //                  qDebug("adding %x to glyph %x", add.value(), justificationPoints[i].glyph->glyph);
2006                 justificationPoints[i].glyph.justifications[0].space_18d6 = add.value();
2007                 need -= add;
2008                 --n;
2009             }
2010         }
2011
2012         Q_ASSERT(!need);
2013     }
2014  end:
2015     const_cast<QScriptLine &>(line).justified = true;
2016 }
2017
2018 void QScriptLine::setDefaultHeight(QTextEngine *eng)
2019 {
2020     QFont f;
2021     QFontEngine *e;
2022
2023     if (eng->block.docHandle() && eng->block.docHandle()->layout()) {
2024         f = eng->block.charFormat().font();
2025         // Make sure we get the right dpi on printers
2026         QPaintDevice *pdev = eng->block.docHandle()->layout()->paintDevice();
2027         if (pdev)
2028             f = QFont(f, pdev);
2029         e = f.d->engineForScript(QUnicodeTables::Common);
2030     } else {
2031         e = eng->fnt.d->engineForScript(QUnicodeTables::Common);
2032     }
2033
2034     QFixed other_ascent = e->ascent();
2035     QFixed other_descent = e->descent();
2036     QFixed other_leading = e->leading();
2037     leading = qMax(leading + ascent, other_leading + other_ascent) - qMax(ascent, other_ascent);
2038     ascent = qMax(ascent, other_ascent);
2039     descent = qMax(descent, other_descent);
2040 }
2041
2042 QTextEngine::LayoutData::LayoutData()
2043 {
2044     memory = 0;
2045     allocated = 0;
2046     memory_on_stack = false;
2047     used = 0;
2048     hasBidi = false;
2049     layoutState = LayoutEmpty;
2050     haveCharAttributes = false;
2051     logClustersPtr = 0;
2052     available_glyphs = 0;
2053 }
2054
2055 QTextEngine::LayoutData::LayoutData(const QString &str, void **stack_memory, int _allocated)
2056     : string(str)
2057 {
2058     allocated = _allocated;
2059
2060     int space_charAttributes = sizeof(HB_CharAttributes)*string.length()/sizeof(void*) + 1;
2061     int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2062     available_glyphs = ((int)allocated - space_charAttributes - space_logClusters)*(int)sizeof(void*)/(int)QGlyphLayout::spaceNeededForGlyphLayout(1);
2063
2064     if (available_glyphs < str.length()) {
2065         // need to allocate on the heap
2066         allocated = 0;
2067
2068         memory_on_stack = false;
2069         memory = 0;
2070         logClustersPtr = 0;
2071     } else {
2072         memory_on_stack = true;
2073         memory = stack_memory;
2074         logClustersPtr = (unsigned short *)(memory + space_charAttributes);
2075
2076         void *m = memory + space_charAttributes + space_logClusters;
2077         glyphLayout = QGlyphLayout(reinterpret_cast<char *>(m), str.length());
2078         glyphLayout.clear();
2079         memset(memory, 0, space_charAttributes*sizeof(void *));
2080     }
2081     used = 0;
2082     hasBidi = false;
2083     layoutState = LayoutEmpty;
2084     haveCharAttributes = false;
2085 }
2086
2087 QTextEngine::LayoutData::~LayoutData()
2088 {
2089     if (!memory_on_stack)
2090         free(memory);
2091     memory = 0;
2092 }
2093
2094 bool QTextEngine::LayoutData::reallocate(int totalGlyphs)
2095 {
2096     Q_ASSERT(totalGlyphs >= glyphLayout.numGlyphs);
2097     if (memory_on_stack && available_glyphs >= totalGlyphs) {
2098         glyphLayout.grow(glyphLayout.data(), totalGlyphs);
2099         return true;
2100     }
2101
2102     int space_charAttributes = sizeof(HB_CharAttributes)*string.length()/sizeof(void*) + 1;
2103     int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2104     int space_glyphs = QGlyphLayout::spaceNeededForGlyphLayout(totalGlyphs)/sizeof(void*) + 2;
2105
2106     int newAllocated = space_charAttributes + space_glyphs + space_logClusters;
2107     // These values can be negative if the length of string/glyphs causes overflow,
2108     // we can't layout such a long string all at once, so return false here to
2109     // indicate there is a failure
2110     if (space_charAttributes < 0 || space_logClusters < 0 || space_glyphs < 0 || newAllocated < allocated) {
2111         layoutState = LayoutFailed;
2112         return false;
2113     }
2114
2115     void **newMem = memory;
2116     newMem = (void **)::realloc(memory_on_stack ? 0 : memory, newAllocated*sizeof(void *));
2117     if (!newMem) {
2118         layoutState = LayoutFailed;
2119         return false;
2120     }
2121     if (memory_on_stack)
2122         memcpy(newMem, memory, allocated*sizeof(void *));
2123     memory = newMem;
2124     memory_on_stack = false;
2125
2126     void **m = memory;
2127     m += space_charAttributes;
2128     logClustersPtr = (unsigned short *) m;
2129     m += space_logClusters;
2130
2131     const int space_preGlyphLayout = space_charAttributes + space_logClusters;
2132     if (allocated < space_preGlyphLayout)
2133         memset(memory + allocated, 0, (space_preGlyphLayout - allocated)*sizeof(void *));
2134
2135     glyphLayout.grow(reinterpret_cast<char *>(m), totalGlyphs);
2136
2137     allocated = newAllocated;
2138     return true;
2139 }
2140
2141 // grow to the new size, copying the existing data to the new layout
2142 void QGlyphLayout::grow(char *address, int totalGlyphs)
2143 {
2144     QGlyphLayout oldLayout(address, numGlyphs);
2145     QGlyphLayout newLayout(address, totalGlyphs);
2146
2147     if (numGlyphs) {
2148         // move the existing data
2149         memmove(newLayout.attributes, oldLayout.attributes, numGlyphs * sizeof(HB_GlyphAttributes));
2150         memmove(newLayout.justifications, oldLayout.justifications, numGlyphs * sizeof(QGlyphJustification));
2151         memmove(newLayout.advances_y, oldLayout.advances_y, numGlyphs * sizeof(QFixed));
2152         memmove(newLayout.advances_x, oldLayout.advances_x, numGlyphs * sizeof(QFixed));
2153         memmove(newLayout.glyphs, oldLayout.glyphs, numGlyphs * sizeof(HB_Glyph));
2154     }
2155
2156     // clear the new data
2157     newLayout.clear(numGlyphs);
2158
2159     *this = newLayout;
2160 }
2161
2162 void QTextEngine::freeMemory()
2163 {
2164     if (!stackEngine) {
2165         delete layoutData;
2166         layoutData = 0;
2167     } else {
2168         layoutData->used = 0;
2169         layoutData->hasBidi = false;
2170         layoutData->layoutState = LayoutEmpty;
2171         layoutData->haveCharAttributes = false;
2172     }
2173     for (int i = 0; i < lines.size(); ++i) {
2174         lines[i].justified = 0;
2175         lines[i].gridfitted = 0;
2176     }
2177 }
2178
2179 int QTextEngine::formatIndex(const QScriptItem *si) const
2180 {
2181     if (specialData && !specialData->resolvedFormatIndices.isEmpty())
2182         return specialData->resolvedFormatIndices.at(si - &layoutData->items[0]);
2183     QTextDocumentPrivate *p = block.docHandle();
2184     if (!p)
2185         return -1;
2186     int pos = si->position;
2187     if (specialData && si->position >= specialData->preeditPosition) {
2188         if (si->position < specialData->preeditPosition + specialData->preeditText.length())
2189             pos = qMax(qMin(block.length(), specialData->preeditPosition) - 1, 0);
2190         else
2191             pos -= specialData->preeditText.length();
2192     }
2193     QTextDocumentPrivate::FragmentIterator it = p->find(block.position() + pos);
2194     return it.value()->format;
2195 }
2196
2197
2198 QTextCharFormat QTextEngine::format(const QScriptItem *si) const
2199 {
2200     QTextCharFormat format;
2201     const QTextFormatCollection *formats = 0;
2202     if (block.docHandle()) {
2203         formats = this->formats();
2204         format = formats->charFormat(formatIndex(si));
2205     }
2206     if (specialData && specialData->resolvedFormatIndices.isEmpty()) {
2207         int end = si->position + length(si);
2208         for (int i = 0; i < specialData->addFormats.size(); ++i) {
2209             const QTextLayout::FormatRange &r = specialData->addFormats.at(i);
2210             if (r.start <= si->position && r.start + r.length >= end) {
2211                 if (!specialData->addFormatIndices.isEmpty())
2212                     format.merge(formats->format(specialData->addFormatIndices.at(i)));
2213                 else
2214                     format.merge(r.format);
2215             }
2216         }
2217     }
2218     return format;
2219 }
2220
2221 void QTextEngine::addRequiredBoundaries() const
2222 {
2223     if (specialData) {
2224         for (int i = 0; i < specialData->addFormats.size(); ++i) {
2225             const QTextLayout::FormatRange &r = specialData->addFormats.at(i);
2226             setBoundary(r.start);
2227             setBoundary(r.start + r.length);
2228             //qDebug("adding boundaries %d %d", r.start, r.start+r.length);
2229         }
2230     }
2231 }
2232
2233 bool QTextEngine::atWordSeparator(int position) const
2234 {
2235     const QChar c = layoutData->string.at(position);
2236     switch (c.unicode()) {
2237     case '.':
2238     case ',':
2239     case '?':
2240     case '!':
2241     case '@':
2242     case '#':
2243     case '$':
2244     case ':':
2245     case ';':
2246     case '-':
2247     case '<':
2248     case '>':
2249     case '[':
2250     case ']':
2251     case '(':
2252     case ')':
2253     case '{':
2254     case '}':
2255     case '=':
2256     case '/':
2257     case '+':
2258     case '%':
2259     case '&':
2260     case '^':
2261     case '*':
2262     case '\'':
2263     case '"':
2264     case '`':
2265     case '~':
2266     case '|':
2267         return true;
2268     default:
2269         break;
2270     }
2271     return false;
2272 }
2273
2274 bool QTextEngine::atSpace(int position) const
2275 {
2276     const QChar c = layoutData->string.at(position);
2277     switch (c.unicode()) {
2278     case QChar::Tabulation:
2279     case QChar::Space:
2280     case QChar::Nbsp:
2281     case QChar::LineSeparator:
2282         return true;
2283     default:
2284         break;
2285     }
2286     return false;
2287 }
2288
2289
2290 void QTextEngine::indexAdditionalFormats()
2291 {
2292     if (!block.docHandle())
2293         return;
2294
2295     specialData->addFormatIndices.resize(specialData->addFormats.count());
2296     QTextFormatCollection * const formats = this->formats();
2297
2298     for (int i = 0; i < specialData->addFormats.count(); ++i) {
2299         specialData->addFormatIndices[i] = formats->indexForFormat(specialData->addFormats.at(i).format);
2300         specialData->addFormats[i].format = QTextCharFormat();
2301     }
2302 }
2303
2304 /* These two helper functions are used to determine whether we need to insert a ZWJ character
2305    between the text that gets truncated and the ellipsis. This is important to get
2306    correctly shaped results for arabic text.
2307 */
2308 static inline bool nextCharJoins(const QString &string, int pos)
2309 {
2310     while (pos < string.length() && string.at(pos).category() == QChar::Mark_NonSpacing)
2311         ++pos;
2312     if (pos == string.length())
2313         return false;
2314     return string.at(pos).joining() != QChar::OtherJoining;
2315 }
2316
2317 static inline bool prevCharJoins(const QString &string, int pos)
2318 {
2319     while (pos > 0 && string.at(pos - 1).category() == QChar::Mark_NonSpacing)
2320         --pos;
2321     if (pos == 0)
2322         return false;
2323     QChar::Joining joining = string.at(pos - 1).joining();
2324     return (joining == QChar::Dual || joining == QChar::Center);
2325 }
2326
2327 static inline bool isRetainableControlCode(QChar c)
2328 {
2329     return (c.unicode() == 0x202a       // LRE
2330             || c.unicode() == 0x202b    // LRE
2331             || c.unicode() == 0x202c    // PDF
2332             || c.unicode() == 0x202d    // LRO
2333             || c.unicode() == 0x202e    // RLO
2334             || c.unicode() == 0x200e    // LRM
2335             || c.unicode() == 0x200f);  // RLM
2336 }
2337
2338 static QString stringMidRetainingBidiCC(const QString &string,
2339                                         const QString &ellidePrefix,
2340                                         const QString &ellideSuffix,
2341                                         int subStringFrom,
2342                                         int subStringTo,
2343                                         int midStart,
2344                                         int midLength)
2345 {
2346     QString prefix;
2347     for (int i=subStringFrom; i<midStart; ++i) {
2348         QChar c = string.at(i);
2349         if (isRetainableControlCode(c))
2350             prefix += c;
2351     }
2352
2353     QString suffix;
2354     for (int i=midStart + midLength; i<subStringTo; ++i) {
2355         QChar c = string.at(i);
2356         if (isRetainableControlCode(c))
2357             suffix += c;
2358     }
2359
2360     return prefix + ellidePrefix + string.mid(midStart, midLength) + ellideSuffix + suffix;
2361 }
2362
2363 QString QTextEngine::elidedText(Qt::TextElideMode mode, const QFixed &width, int flags, int from, int count) const
2364 {
2365 //    qDebug() << "elidedText; available width" << width.toReal() << "text width:" << this->width(0, layoutData->string.length()).toReal();
2366
2367     if (flags & Qt::TextShowMnemonic) {
2368         itemize();
2369         HB_CharAttributes *attributes = const_cast<HB_CharAttributes *>(this->attributes());
2370         if (!attributes)
2371             return QString();
2372         for (int i = 0; i < layoutData->items.size(); ++i) {
2373             QScriptItem &si = layoutData->items[i];
2374             if (!si.num_glyphs)
2375                 shape(i);
2376
2377             unsigned short *logClusters = this->logClusters(&si);
2378             QGlyphLayout glyphs = shapedGlyphs(&si);
2379
2380             const int end = si.position + length(&si);
2381             for (int i = si.position; i < end - 1; ++i) {
2382                 if (layoutData->string.at(i) == QLatin1Char('&')) {
2383                     const int gp = logClusters[i - si.position];
2384                     glyphs.attributes[gp].dontPrint = true;
2385                     attributes[i + 1].charStop = false;
2386                     attributes[i + 1].whiteSpace = false;
2387                     attributes[i + 1].lineBreakType = HB_NoBreak;
2388                     if (layoutData->string.at(i + 1) == QLatin1Char('&'))
2389                         ++i;
2390                 }
2391             }
2392         }
2393     }
2394
2395     validate();
2396
2397     const int to = count >= 0 && count <= layoutData->string.length() - from
2398             ? from + count
2399             : layoutData->string.length();
2400
2401     if (mode == Qt::ElideNone
2402         || this->width(from, layoutData->string.length()) <= width
2403         || to - from <= 1)
2404         return layoutData->string.mid(from, from - to);
2405
2406     QFixed ellipsisWidth;
2407     QString ellipsisText;
2408     {
2409         QChar ellipsisChar(0x2026);
2410
2411         QFontEngine *fe = fnt.d->engineForScript(QUnicodeTables::Common);
2412
2413         QGlyphLayoutArray<1> ellipsisGlyph;
2414         {
2415             QFontEngine *feForEllipsis = (fe->type() == QFontEngine::Multi)
2416                 ? static_cast<QFontEngineMulti *>(fe)->engine(0)
2417                 : fe;
2418
2419             if (feForEllipsis->type() == QFontEngine::Mac)
2420                 feForEllipsis = fe;
2421
2422             if (feForEllipsis->canRender(&ellipsisChar, 1)) {
2423                 int nGlyphs = 1;
2424                 feForEllipsis->stringToCMap(&ellipsisChar, 1, &ellipsisGlyph, &nGlyphs, 0);
2425             }
2426         }
2427
2428         if (ellipsisGlyph.glyphs[0]) {
2429             ellipsisWidth = ellipsisGlyph.advances_x[0];
2430             ellipsisText = ellipsisChar;
2431         } else {
2432             QString dotDotDot(QLatin1String("..."));
2433
2434             QGlyphLayoutArray<3> glyphs;
2435             int nGlyphs = 3;
2436             if (!fe->stringToCMap(dotDotDot.constData(), 3, &glyphs, &nGlyphs, 0))
2437                 // should never happen...
2438                 return layoutData->string;
2439             for (int i = 0; i < nGlyphs; ++i)
2440                 ellipsisWidth += glyphs.advances_x[i];
2441             ellipsisText = dotDotDot;
2442         }
2443     }
2444
2445     const QFixed availableWidth = width - ellipsisWidth;
2446     if (availableWidth < 0)
2447         return QString();
2448
2449     const HB_CharAttributes *attributes = this->attributes();
2450     if (!attributes)
2451         return QString();
2452
2453     if (mode == Qt::ElideRight) {
2454         QFixed currentWidth;
2455         int pos;
2456         int nextBreak = from;
2457
2458         do {
2459             pos = nextBreak;
2460
2461             ++nextBreak;
2462             while (nextBreak < layoutData->string.length() && !attributes[nextBreak].charStop)
2463                 ++nextBreak;
2464
2465             currentWidth += this->width(pos, nextBreak - pos);
2466         } while (nextBreak < to
2467                  && currentWidth < availableWidth);
2468
2469         if (nextCharJoins(layoutData->string, pos))
2470             ellipsisText.prepend(QChar(0x200d) /* ZWJ */);
2471
2472         return stringMidRetainingBidiCC(layoutData->string,
2473                                         QString(), ellipsisText,
2474                                         from, to,
2475                                         from, pos - from);
2476     } else if (mode == Qt::ElideLeft) {
2477         QFixed currentWidth;
2478         int pos;
2479         int nextBreak = to;
2480
2481         do {
2482             pos = nextBreak;
2483
2484             --nextBreak;
2485             while (nextBreak > 0 && !attributes[nextBreak].charStop)
2486                 --nextBreak;
2487
2488             currentWidth += this->width(nextBreak, pos - nextBreak);
2489         } while (nextBreak > from
2490                  && currentWidth < availableWidth);
2491
2492         if (prevCharJoins(layoutData->string, pos))
2493             ellipsisText.append(QChar(0x200d) /* ZWJ */);
2494
2495         return stringMidRetainingBidiCC(layoutData->string,
2496                                         ellipsisText, QString(),
2497                                         from, to,
2498                                         pos, to - pos);
2499     } else if (mode == Qt::ElideMiddle) {
2500         QFixed leftWidth;
2501         QFixed rightWidth;
2502
2503         int leftPos = from;
2504         int nextLeftBreak = from;
2505
2506         int rightPos = to;
2507         int nextRightBreak = to;
2508
2509         do {
2510             leftPos = nextLeftBreak;
2511             rightPos = nextRightBreak;
2512
2513             ++nextLeftBreak;
2514             while (nextLeftBreak < layoutData->string.length() && !attributes[nextLeftBreak].charStop)
2515                 ++nextLeftBreak;
2516
2517             --nextRightBreak;
2518             while (nextRightBreak > from && !attributes[nextRightBreak].charStop)
2519                 --nextRightBreak;
2520
2521             leftWidth += this->width(leftPos, nextLeftBreak - leftPos);
2522             rightWidth += this->width(nextRightBreak, rightPos - nextRightBreak);
2523         } while (nextLeftBreak < to
2524                  && nextRightBreak > from
2525                  && leftWidth + rightWidth < availableWidth);
2526
2527         if (nextCharJoins(layoutData->string, leftPos))
2528             ellipsisText.prepend(QChar(0x200d) /* ZWJ */);
2529         if (prevCharJoins(layoutData->string, rightPos))
2530             ellipsisText.append(QChar(0x200d) /* ZWJ */);
2531
2532         return layoutData->string.mid(from, leftPos - from) + ellipsisText + layoutData->string.mid(rightPos, to - rightPos);
2533     }
2534
2535     return layoutData->string.mid(from, to - from);
2536 }
2537
2538 void QTextEngine::setBoundary(int strPos) const
2539 {
2540     if (strPos <= 0 || strPos >= layoutData->string.length())
2541         return;
2542
2543     int itemToSplit = 0;
2544     while (itemToSplit < layoutData->items.size() && layoutData->items.at(itemToSplit).position <= strPos)
2545         itemToSplit++;
2546     itemToSplit--;
2547     if (layoutData->items.at(itemToSplit).position == strPos) {
2548         // already a split at the requested position
2549         return;
2550     }
2551     splitItem(itemToSplit, strPos - layoutData->items.at(itemToSplit).position);
2552 }
2553
2554 void QTextEngine::splitItem(int item, int pos) const
2555 {
2556     if (pos <= 0)
2557         return;
2558
2559     layoutData->items.insert(item + 1, layoutData->items[item]);
2560     QScriptItem &oldItem = layoutData->items[item];
2561     QScriptItem &newItem = layoutData->items[item+1];
2562     newItem.position += pos;
2563
2564     if (oldItem.num_glyphs) {
2565         // already shaped, break glyphs aswell
2566         int breakGlyph = logClusters(&oldItem)[pos];
2567
2568         newItem.num_glyphs = oldItem.num_glyphs - breakGlyph;
2569         oldItem.num_glyphs = breakGlyph;
2570         newItem.glyph_data_offset = oldItem.glyph_data_offset + breakGlyph;
2571
2572         for (int i = 0; i < newItem.num_glyphs; i++)
2573             logClusters(&newItem)[i] -= breakGlyph;
2574
2575         QFixed w = 0;
2576         const QGlyphLayout g = shapedGlyphs(&oldItem);
2577         for(int j = 0; j < breakGlyph; ++j)
2578             w += g.advances_x[j] * !g.attributes[j].dontPrint;
2579
2580         newItem.width = oldItem.width - w;
2581         oldItem.width = w;
2582     }
2583
2584 //     qDebug("split at position %d itempos=%d", pos, item);
2585 }
2586
2587 QFixed QTextEngine::calculateTabWidth(int item, QFixed x) const
2588 {
2589     const QScriptItem &si = layoutData->items[item];
2590
2591     QFixed dpiScale = 1;
2592     if (block.docHandle() && block.docHandle()->layout()) {
2593         QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
2594         if (pdev)
2595             dpiScale = QFixed::fromReal(pdev->logicalDpiY() / qreal(qt_defaultDpiY()));
2596     } else {
2597         dpiScale = QFixed::fromReal(fnt.d->dpi / qreal(qt_defaultDpiY()));
2598     }
2599
2600     QList<QTextOption::Tab> tabArray = option.tabs();
2601     if (!tabArray.isEmpty()) {
2602         if (isRightToLeft()) { // rebase the tabArray positions.
2603             QList<QTextOption::Tab> newTabs;
2604             QList<QTextOption::Tab>::Iterator iter = tabArray.begin();
2605             while(iter != tabArray.end()) {
2606                 QTextOption::Tab tab = *iter;
2607                 if (tab.type == QTextOption::LeftTab)
2608                     tab.type = QTextOption::RightTab;
2609                 else if (tab.type == QTextOption::RightTab)
2610                     tab.type = QTextOption::LeftTab;
2611                 newTabs << tab;
2612                 ++iter;
2613             }
2614             tabArray = newTabs;
2615         }
2616         for (int i = 0; i < tabArray.size(); ++i) {
2617             QFixed tab = QFixed::fromReal(tabArray[i].position) * dpiScale;
2618             if (tab > x) {  // this is the tab we need.
2619                 QTextOption::Tab tabSpec = tabArray[i];
2620                 int tabSectionEnd = layoutData->string.count();
2621                 if (tabSpec.type == QTextOption::RightTab || tabSpec.type == QTextOption::CenterTab) {
2622                     // find next tab to calculate the width required.
2623                     tab = QFixed::fromReal(tabSpec.position);
2624                     for (int i=item + 1; i < layoutData->items.count(); i++) {
2625                         const QScriptItem &item = layoutData->items[i];
2626                         if (item.analysis.flags == QScriptAnalysis::TabOrObject) { // found it.
2627                             tabSectionEnd = item.position;
2628                             break;
2629                         }
2630                     }
2631                 }
2632                 else if (tabSpec.type == QTextOption::DelimiterTab)
2633                     // find delimitor character to calculate the width required
2634                     tabSectionEnd = qMax(si.position, layoutData->string.indexOf(tabSpec.delimiter, si.position) + 1);
2635
2636                 if (tabSectionEnd > si.position) {
2637                     QFixed length;
2638                     // Calculate the length of text between this tab and the tabSectionEnd
2639                     for (int i=item; i < layoutData->items.count(); i++) {
2640                         QScriptItem &item = layoutData->items[i];
2641                         if (item.position > tabSectionEnd || item.position <= si.position)
2642                             continue;
2643                         shape(i); // first, lets make sure relevant text is already shaped
2644                         QGlyphLayout glyphs = this->shapedGlyphs(&item);
2645                         const int end = qMin(item.position + item.num_glyphs, tabSectionEnd) - item.position;
2646                         for (int i=0; i < end; i++)
2647                             length += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
2648                         if (end + item.position == tabSectionEnd && tabSpec.type == QTextOption::DelimiterTab) // remove half of matching char
2649                             length -= glyphs.advances_x[end] / 2 * !glyphs.attributes[end].dontPrint;
2650                     }
2651
2652                     switch (tabSpec.type) {
2653                     case QTextOption::CenterTab:
2654                         length /= 2;
2655                         // fall through
2656                     case QTextOption::DelimiterTab:
2657                         // fall through
2658                     case QTextOption::RightTab:
2659                         tab = QFixed::fromReal(tabSpec.position) * dpiScale - length;
2660                         if (tab < x) // default to tab taking no space
2661                             return QFixed();
2662                         break;
2663                     case QTextOption::LeftTab:
2664                         break;
2665                     }
2666                 }
2667                 return tab - x;
2668             }
2669         }
2670     }
2671     QFixed tab = QFixed::fromReal(option.tabStop());
2672     if (tab <= 0)
2673         tab = 80; // default
2674     tab *= dpiScale;
2675     QFixed nextTabPos = ((x / tab).truncate() + 1) * tab;
2676     QFixed tabWidth = nextTabPos - x;
2677
2678     return tabWidth;
2679 }
2680
2681 void QTextEngine::resolveAdditionalFormats() const
2682 {
2683     if (!specialData || specialData->addFormats.isEmpty()
2684         || !block.docHandle()
2685         || !specialData->resolvedFormatIndices.isEmpty())
2686         return;
2687
2688     QTextFormatCollection *collection = this->formats();
2689
2690     specialData->resolvedFormatIndices.clear();
2691     QVector<int> indices(layoutData->items.count());
2692     for (int i = 0; i < layoutData->items.count(); ++i) {
2693         QTextCharFormat f = format(&layoutData->items.at(i));
2694         indices[i] = collection->indexForFormat(f);
2695     }
2696     specialData->resolvedFormatIndices = indices;
2697 }
2698
2699 QFixed QTextEngine::leadingSpaceWidth(const QScriptLine &line)
2700 {
2701     if (!line.hasTrailingSpaces
2702         || (option.flags() & QTextOption::IncludeTrailingSpaces)
2703         || !isRightToLeft())
2704         return QFixed();
2705
2706     return width(line.from + line.length, line.trailingSpaces);
2707 }
2708
2709 QFixed QTextEngine::alignLine(const QScriptLine &line)
2710 {
2711     QFixed x = 0;
2712     justify(line);
2713     // if width is QFIXED_MAX that means we used setNumColumns() and that implicitly makes this line left aligned.
2714     if (!line.justified && line.width != QFIXED_MAX) {
2715         int align = option.alignment();
2716         if (align & Qt::AlignJustify && isRightToLeft())
2717             align = Qt::AlignRight;
2718         if (align & Qt::AlignRight)
2719             x = line.width - (line.textAdvance);
2720         else if (align & Qt::AlignHCenter)
2721             x = (line.width - line.textAdvance)/2;
2722     }
2723     return x;
2724 }
2725
2726 QFixed QTextEngine::offsetInLigature(const QScriptItem *si, int pos, int max, int glyph_pos)
2727 {
2728     unsigned short *logClusters = this->logClusters(si);
2729     const QGlyphLayout &glyphs = shapedGlyphs(si);
2730
2731     int offsetInCluster = 0;
2732     for (int i = pos - 1; i >= 0; i--) {
2733         if (logClusters[i] == glyph_pos)
2734             offsetInCluster++;
2735         else
2736             break;
2737     }
2738
2739     // in the case that the offset is inside a (multi-character) glyph,
2740     // interpolate the position.
2741     if (offsetInCluster > 0) {
2742         int clusterLength = 0;
2743         for (int i = pos - offsetInCluster; i < max; i++) {
2744             if (logClusters[i] == glyph_pos)
2745                 clusterLength++;
2746             else
2747                 break;
2748         }
2749         if (clusterLength)
2750             return glyphs.advances_x[glyph_pos] * offsetInCluster / clusterLength;
2751     }
2752
2753     return 0;
2754 }
2755
2756 // Scan in logClusters[from..to-1] for glyph_pos
2757 int QTextEngine::getClusterLength(unsigned short *logClusters,
2758                                   const HB_CharAttributes *attributes,
2759                                   int from, int to, int glyph_pos, int *start)
2760 {
2761     int clusterLength = 0;
2762     for (int i = from; i < to; i++) {
2763         if (logClusters[i] == glyph_pos && attributes[i].charStop) {
2764             if (*start < 0)
2765                 *start = i;
2766             clusterLength++;
2767         }
2768         else if (clusterLength)
2769             break;
2770     }
2771     return clusterLength;
2772 }
2773
2774 int QTextEngine::positionInLigature(const QScriptItem *si, int end,
2775                                     QFixed x, QFixed edge, int glyph_pos,
2776                                     bool cursorOnCharacter)
2777 {
2778     unsigned short *logClusters = this->logClusters(si);
2779     int clusterStart = -1;
2780     int clusterLength = 0;
2781
2782     if (si->analysis.script != QUnicodeTables::Common &&
2783         si->analysis.script != QUnicodeTables::Greek) {
2784         if (glyph_pos == -1)
2785             return si->position + end;
2786         else {
2787             int i;
2788             for (i = 0; i < end; i++)
2789                 if (logClusters[i] == glyph_pos)
2790                     break;
2791             return si->position + i;
2792         }
2793     }
2794
2795     if (glyph_pos == -1 && end > 0)
2796         glyph_pos = logClusters[end - 1];
2797     else {
2798         if (x <= edge)
2799             glyph_pos--;
2800     }
2801
2802     const HB_CharAttributes *attrs = attributes();
2803     logClusters = this->logClusters(si);
2804     clusterLength = getClusterLength(logClusters, attrs, 0, end, glyph_pos, &clusterStart);
2805
2806     if (clusterLength) {
2807         const QGlyphLayout &glyphs = shapedGlyphs(si);
2808         QFixed glyphWidth = glyphs.effectiveAdvance(glyph_pos);
2809         // the approximate width of each individual element of the ligature
2810         QFixed perItemWidth = glyphWidth / clusterLength;
2811         if (perItemWidth <= 0)
2812             return si->position + clusterStart;
2813         QFixed left = x > edge ? edge : edge - glyphWidth;
2814         int n = ((x - left) / perItemWidth).floor().toInt();
2815         QFixed dist = x - left - n * perItemWidth;
2816         int closestItem = dist > (perItemWidth / 2) ? n + 1 : n;
2817         if (cursorOnCharacter && closestItem > 0)
2818             closestItem--;
2819         int pos = si->position + clusterStart + closestItem;
2820         // Jump to the next charStop
2821         while (pos < end && !attrs[pos].charStop)
2822             pos++;
2823         return pos;
2824     }
2825     return si->position + end;
2826 }
2827
2828 int QTextEngine::previousLogicalPosition(int oldPos) const
2829 {
2830     const HB_CharAttributes *attrs = attributes();
2831     if (!attrs || oldPos < 0)
2832         return oldPos;
2833
2834     if (oldPos <= 0)
2835         return 0;
2836     oldPos--;
2837     while (oldPos && !attrs[oldPos].charStop)
2838         oldPos--;
2839     return oldPos;
2840 }
2841
2842 int QTextEngine::nextLogicalPosition(int oldPos) const
2843 {
2844     const HB_CharAttributes *attrs = attributes();
2845     int len = block.isValid() ? block.length() - 1
2846                               : layoutData->string.length();
2847     Q_ASSERT(len <= layoutData->string.length());
2848     if (!attrs || oldPos < 0 || oldPos >= len)
2849         return oldPos;
2850
2851     oldPos++;
2852     while (oldPos < len && !attrs[oldPos].charStop)
2853         oldPos++;
2854     return oldPos;
2855 }
2856
2857 int QTextEngine::lineNumberForTextPosition(int pos)
2858 {
2859     if (!layoutData)
2860         itemize();
2861     if (pos == layoutData->string.length() && lines.size())
2862         return lines.size() - 1;
2863     for (int i = 0; i < lines.size(); ++i) {
2864         const QScriptLine& line = lines[i];
2865         if (line.from + line.length + line.trailingSpaces > pos)
2866             return i;
2867     }
2868     return -1;
2869 }
2870
2871 void QTextEngine::insertionPointsForLine(int lineNum, QVector<int> &insertionPoints)
2872 {
2873     QTextLineItemIterator iterator(this, lineNum);
2874     bool rtl = isRightToLeft();
2875     bool lastLine = lineNum >= lines.size() - 1;
2876
2877     while (!iterator.atEnd()) {
2878         iterator.next();
2879         const QScriptItem *si = &layoutData->items[iterator.item];
2880         if (si->analysis.bidiLevel % 2) {
2881             int i = iterator.itemEnd - 1, min = iterator.itemStart;
2882             if (lastLine && (rtl ? iterator.atBeginning() : iterator.atEnd()))
2883                 i++;
2884             for (; i >= min; i--)
2885                 insertionPoints.push_back(i);
2886         } else {
2887             int i = iterator.itemStart, max = iterator.itemEnd;
2888             if (lastLine && (rtl ? iterator.atBeginning() : iterator.atEnd()))
2889                 max++;
2890             for (; i < max; i++)
2891                 insertionPoints.push_back(i);
2892         }
2893     }
2894 }
2895
2896 int QTextEngine::endOfLine(int lineNum)
2897 {
2898     QVector<int> insertionPoints;
2899     insertionPointsForLine(lineNum, insertionPoints);
2900
2901     if (insertionPoints.size() > 0)
2902         return insertionPoints.last();
2903     return 0;
2904 }
2905
2906 int QTextEngine::beginningOfLine(int lineNum)
2907 {
2908     QVector<int> insertionPoints;
2909     insertionPointsForLine(lineNum, insertionPoints);
2910
2911     if (insertionPoints.size() > 0)
2912         return insertionPoints.first();
2913     return 0;
2914 }
2915
2916 int QTextEngine::positionAfterVisualMovement(int pos, QTextCursor::MoveOperation op)
2917 {
2918     if (!layoutData)
2919         itemize();
2920
2921     bool moveRight = (op == QTextCursor::Right);
2922     bool alignRight = isRightToLeft();
2923     if (!layoutData->hasBidi)
2924         return moveRight ^ alignRight ? nextLogicalPosition(pos) : previousLogicalPosition(pos);
2925
2926     int lineNum = lineNumberForTextPosition(pos);
2927     Q_ASSERT(lineNum >= 0);
2928
2929     QVector<int> insertionPoints;
2930     insertionPointsForLine(lineNum, insertionPoints);
2931     int i, max = insertionPoints.size();
2932     for (i = 0; i < max; i++)
2933         if (pos == insertionPoints[i]) {
2934             if (moveRight) {
2935                 if (i + 1 < max)
2936                     return insertionPoints[i + 1];
2937             } else {
2938                 if (i > 0)
2939                     return insertionPoints[i - 1];
2940             }
2941
2942             if (moveRight ^ alignRight) {
2943                 if (lineNum + 1 < lines.size())
2944                     return alignRight ? endOfLine(lineNum + 1) : beginningOfLine(lineNum + 1);
2945             }
2946             else {
2947                 if (lineNum > 0)
2948                     return alignRight ? beginningOfLine(lineNum - 1) : endOfLine(lineNum - 1);
2949             }
2950         }
2951
2952     return pos;
2953 }
2954
2955 void QTextEngine::addItemDecoration(QPainter *painter, const QLineF &line, ItemDecorationList *decorationList)
2956 {
2957     if (delayDecorations) {
2958         decorationList->append(ItemDecoration(line.x1(), line.x2(), line.y1(), painter->pen()));
2959     } else {
2960         painter->drawLine(line);
2961     }
2962 }
2963
2964 void QTextEngine::addUnderline(QPainter *painter, const QLineF &line)
2965 {
2966     // qDebug() << "Adding underline:" << line;
2967     addItemDecoration(painter, line, &underlineList);
2968 }
2969
2970 void QTextEngine::addStrikeOut(QPainter *painter, const QLineF &line)
2971 {
2972     addItemDecoration(painter, line, &strikeOutList);
2973 }
2974
2975 void QTextEngine::addOverline(QPainter *painter, const QLineF &line)
2976 {
2977     addItemDecoration(painter, line, &overlineList);
2978 }
2979
2980 void QTextEngine::drawItemDecorationList(QPainter *painter, const ItemDecorationList &decorationList)
2981 {
2982     // qDebug() << "Drawing" << decorationList.size() << "decorations";
2983     if (decorationList.isEmpty())
2984         return;
2985
2986     foreach (const ItemDecoration &decoration, decorationList) {
2987         painter->setPen(decoration.pen);
2988         QLineF line(decoration.x1, decoration.y, decoration.x2, decoration.y);
2989         painter->drawLine(line);
2990     }
2991 }
2992
2993 void QTextEngine::drawDecorations(QPainter *painter)
2994 {
2995     QPen oldPen = painter->pen();
2996
2997     adjustUnderlines();
2998     drawItemDecorationList(painter, underlineList);
2999     drawItemDecorationList(painter, strikeOutList);
3000     drawItemDecorationList(painter, overlineList);
3001
3002     painter->setPen(oldPen);
3003     clearDecorations();
3004 }
3005
3006 void QTextEngine::clearDecorations()
3007 {
3008     underlineList.clear();
3009     strikeOutList.clear();
3010     overlineList.clear();
3011 }
3012
3013 void QTextEngine::adjustUnderlines()
3014 {
3015     // qDebug() << __PRETTY_FUNCTION__ << underlineList.count() << "underlines";
3016     if (underlineList.isEmpty())
3017         return;
3018
3019     ItemDecorationList::iterator start = underlineList.begin();
3020     ItemDecorationList::iterator end   = underlineList.end();
3021     ItemDecorationList::iterator it = start;
3022     qreal underlinePos = start->y;
3023     qreal penWidth = start->pen.widthF();
3024     qreal lastLineEnd = start->x1;
3025
3026     while (it != end) {
3027         if (qFuzzyCompare(lastLineEnd, it->x1)) { // no gap between underlines
3028             underlinePos = qMax(underlinePos, it->y);
3029             penWidth = qMax(penWidth, it->pen.widthF());
3030         } else { // gap between this and the last underline
3031             adjustUnderlines(start, it, underlinePos, penWidth);
3032             start = it;
3033             underlinePos = start->y;
3034             penWidth = start->pen.widthF();
3035         }
3036         lastLineEnd = it->x2;
3037         ++it;
3038     }
3039
3040     adjustUnderlines(start, end, underlinePos, penWidth);
3041 }
3042
3043 void QTextEngine::adjustUnderlines(ItemDecorationList::iterator start,
3044                                    ItemDecorationList::iterator end,
3045                                    qreal underlinePos, qreal penWidth)
3046 {
3047     for (ItemDecorationList::iterator it = start; it != end; ++it) {
3048         it->y = underlinePos;
3049         it->pen.setWidthF(penWidth);
3050     }
3051 }
3052
3053 QStackTextEngine::QStackTextEngine(const QString &string, const QFont &f)
3054     : QTextEngine(string, f),
3055       _layoutData(string, _memory, MemSize)
3056 {
3057     stackEngine = true;
3058     layoutData = &_layoutData;
3059 }
3060
3061 QTextItemInt::QTextItemInt(const QScriptItem &si, QFont *font, const QTextCharFormat &format)
3062     : justified(false), underlineStyle(QTextCharFormat::NoUnderline), charFormat(format),
3063       num_chars(0), chars(0), logClusters(0), f(0), fontEngine(0)
3064 {
3065     f = font;
3066     fontEngine = f->d->engineForScript(si.analysis.script);
3067     Q_ASSERT(fontEngine);
3068
3069     initWithScriptItem(si);
3070 }
3071
3072 QTextItemInt::QTextItemInt(const QGlyphLayout &g, QFont *font, const QChar *chars_, int numChars, QFontEngine *fe, const QTextCharFormat &format)
3073     : flags(0), justified(false), underlineStyle(QTextCharFormat::NoUnderline), charFormat(format),
3074       num_chars(numChars), chars(chars_), logClusters(0), f(font),  glyphs(g), fontEngine(fe)
3075 {
3076 }
3077
3078 // Fix up flags and underlineStyle with given info
3079 void QTextItemInt::initWithScriptItem(const QScriptItem &si)
3080 {
3081     // explicitly initialize flags so that initFontAttributes can be called
3082     // multiple times on the same TextItem
3083     flags = 0;
3084     if (si.analysis.bidiLevel %2)
3085         flags |= QTextItem::RightToLeft;
3086     ascent = si.ascent;
3087     descent = si.descent;
3088
3089     if (charFormat.hasProperty(QTextFormat::TextUnderlineStyle)) {
3090         underlineStyle = charFormat.underlineStyle();
3091     } else if (charFormat.boolProperty(QTextFormat::FontUnderline)
3092                || f->d->underline) {
3093         underlineStyle = QTextCharFormat::SingleUnderline;
3094     }
3095
3096     // compat
3097     if (underlineStyle == QTextCharFormat::SingleUnderline)
3098         flags |= QTextItem::Underline;
3099
3100     if (f->d->overline || charFormat.fontOverline())
3101         flags |= QTextItem::Overline;
3102     if (f->d->strikeOut || charFormat.fontStrikeOut())
3103         flags |= QTextItem::StrikeOut;
3104 }
3105
3106 QTextItemInt QTextItemInt::midItem(QFontEngine *fontEngine, int firstGlyphIndex, int numGlyphs) const
3107 {
3108     QTextItemInt ti = *this;
3109     const int end = firstGlyphIndex + numGlyphs;
3110     ti.glyphs = glyphs.mid(firstGlyphIndex, numGlyphs);
3111     ti.fontEngine = fontEngine;
3112
3113     if (logClusters && chars) {
3114         const int logClusterOffset = logClusters[0];
3115         while (logClusters[ti.chars - chars] - logClusterOffset < firstGlyphIndex)
3116             ++ti.chars;
3117
3118         ti.logClusters += (ti.chars - chars);
3119
3120         ti.num_chars = 0;
3121         int char_start = ti.chars - chars;
3122         while (char_start + ti.num_chars < num_chars && ti.logClusters[ti.num_chars] - logClusterOffset < end)
3123             ++ti.num_chars;
3124     }
3125     return ti;
3126 }
3127
3128
3129 QTransform qt_true_matrix(qreal w, qreal h, QTransform x)
3130 {
3131     QRectF rect = x.mapRect(QRectF(0, 0, w, h));
3132     return x * QTransform::fromTranslate(-rect.x(), -rect.y());
3133 }
3134
3135
3136 glyph_metrics_t glyph_metrics_t::transformed(const QTransform &matrix) const
3137 {
3138     if (matrix.type() < QTransform::TxTranslate)
3139         return *this;
3140
3141     glyph_metrics_t m = *this;
3142
3143     qreal w = width.toReal();
3144     qreal h = height.toReal();
3145     QTransform xform = qt_true_matrix(w, h, matrix);
3146
3147     QRectF rect(0, 0, w, h);
3148     rect = xform.mapRect(rect);
3149     m.width = QFixed::fromReal(rect.width());
3150     m.height = QFixed::fromReal(rect.height());
3151
3152     QLineF l = xform.map(QLineF(x.toReal(), y.toReal(), xoff.toReal(), yoff.toReal()));
3153
3154     m.x = QFixed::fromReal(l.x1());
3155     m.y = QFixed::fromReal(l.y1());
3156
3157     // The offset is relative to the baseline which is why we use dx/dy of the line
3158     m.xoff = QFixed::fromReal(l.dx());
3159     m.yoff = QFixed::fromReal(l.dy());
3160
3161     return m;
3162 }
3163
3164 QTextLineItemIterator::QTextLineItemIterator(QTextEngine *_eng, int _lineNum, const QPointF &pos,
3165                                              const QTextLayout::FormatRange *_selection)
3166     : eng(_eng),
3167       line(eng->lines[_lineNum]),
3168       si(0),
3169       lineNum(_lineNum),
3170       lineEnd(line.from + line.length),
3171       firstItem(eng->findItem(line.from)),
3172       lastItem(eng->findItem(lineEnd - 1)),
3173       nItems((firstItem >= 0 && lastItem >= firstItem)? (lastItem-firstItem+1) : 0),
3174       logicalItem(-1),
3175       item(-1),
3176       visualOrder(nItems),
3177       levels(nItems),
3178       selection(_selection)
3179 {
3180     pos_x = x = QFixed::fromReal(pos.x());
3181
3182     x += line.x;
3183
3184     x += eng->alignLine(line);
3185
3186     for (int i = 0; i < nItems; ++i)
3187         levels[i] = eng->layoutData->items[i+firstItem].analysis.bidiLevel;
3188     QTextEngine::bidiReorder(nItems, levels.data(), visualOrder.data());
3189
3190     eng->shapeLine(line);
3191 }
3192
3193 QScriptItem &QTextLineItemIterator::next()
3194 {
3195     x += itemWidth;
3196
3197     ++logicalItem;
3198     item = visualOrder[logicalItem] + firstItem;
3199     itemLength = eng->length(item);
3200     si = &eng->layoutData->items[item];
3201     if (!si->num_glyphs)
3202         eng->shape(item);
3203
3204     if (si->analysis.flags >= QScriptAnalysis::TabOrObject) {
3205         itemWidth = si->width;
3206         return *si;
3207     }
3208
3209     unsigned short *logClusters = eng->logClusters(si);
3210     QGlyphLayout glyphs = eng->shapedGlyphs(si);
3211
3212     itemStart = qMax(line.from, si->position);
3213     glyphsStart = logClusters[itemStart - si->position];
3214     if (lineEnd < si->position + itemLength) {
3215         itemEnd = lineEnd;
3216         glyphsEnd = logClusters[itemEnd-si->position];
3217     } else {
3218         itemEnd = si->position + itemLength;
3219         glyphsEnd = si->num_glyphs;
3220     }
3221     // show soft-hyphen at line-break
3222     if (si->position + itemLength >= lineEnd
3223         && eng->layoutData->string.at(lineEnd - 1) == 0x00ad)
3224         glyphs.attributes[glyphsEnd - 1].dontPrint = false;
3225
3226     itemWidth = 0;
3227     for (int g = glyphsStart; g < glyphsEnd; ++g)
3228         itemWidth += glyphs.effectiveAdvance(g);
3229
3230     return *si;
3231 }
3232
3233 bool QTextLineItemIterator::getSelectionBounds(QFixed *selectionX, QFixed *selectionWidth) const
3234 {
3235     *selectionX = *selectionWidth = 0;
3236
3237     if (!selection)
3238         return false;
3239
3240     if (si->analysis.flags >= QScriptAnalysis::TabOrObject) {
3241         if (si->position >= selection->start + selection->length
3242             || si->position + itemLength <= selection->start)
3243             return false;
3244
3245         *selectionX = x;
3246         *selectionWidth = itemWidth;
3247     } else {
3248         unsigned short *logClusters = eng->logClusters(si);
3249         QGlyphLayout glyphs = eng->shapedGlyphs(si);
3250
3251         int from = qMax(itemStart, selection->start) - si->position;
3252         int to = qMin(itemEnd, selection->start + selection->length) - si->position;
3253         if (from >= to)
3254             return false;
3255
3256         int start_glyph = logClusters[from];
3257         int end_glyph = (to == eng->length(item)) ? si->num_glyphs : logClusters[to];
3258         QFixed soff;
3259         QFixed swidth;
3260         if (si->analysis.bidiLevel %2) {
3261             for (int g = glyphsEnd - 1; g >= end_glyph; --g)
3262                 soff += glyphs.effectiveAdvance(g);
3263             for (int g = end_glyph - 1; g >= start_glyph; --g)
3264                 swidth += glyphs.effectiveAdvance(g);
3265         } else {
3266             for (int g = glyphsStart; g < start_glyph; ++g)
3267                 soff += glyphs.effectiveAdvance(g);
3268             for (int g = start_glyph; g < end_glyph; ++g)
3269                 swidth += glyphs.effectiveAdvance(g);
3270         }
3271
3272         // If the starting character is in the middle of a ligature,
3273         // selection should only contain the right part of that ligature
3274         // glyph, so we need to get the width of the left part here and
3275         // add it to *selectionX
3276         QFixed leftOffsetInLigature = eng->offsetInLigature(si, from, to, start_glyph);
3277         *selectionX = x + soff + leftOffsetInLigature;
3278         *selectionWidth = swidth - leftOffsetInLigature;
3279         // If the ending character is also part of a ligature, swidth does
3280         // not contain that part yet, we also need to find out the width of
3281         // that left part
3282         *selectionWidth += eng->offsetInLigature(si, to, eng->length(item), end_glyph);
3283     }
3284     return true;
3285 }
3286
3287 QT_END_NAMESPACE