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