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