Take leading space width into account for painting and selection
[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     // this places the cursor in the right position depending on the keyboard layout
1602     if (layoutData->string.isEmpty())
1603         return QApplication::keyboardInputDirection() == Qt::RightToLeft;
1604     return layoutData->string.isRightToLeft();
1605 }
1606
1607
1608 int QTextEngine::findItem(int strPos) const
1609 {
1610     itemize();
1611     int left = 0;
1612     int right = layoutData->items.size()-1;
1613     while(left <= right) {
1614         int middle = ((right-left)/2)+left;
1615         if (strPos > layoutData->items[middle].position)
1616             left = middle+1;
1617         else if(strPos < layoutData->items[middle].position)
1618             right = middle-1;
1619         else {
1620             return middle;
1621         }
1622     }
1623     return right;
1624 }
1625
1626 QFixed QTextEngine::width(int from, int len) const
1627 {
1628     itemize();
1629
1630     QFixed w = 0;
1631
1632 //     qDebug("QTextEngine::width(from = %d, len = %d), numItems=%d, strleng=%d", from,  len, items.size(), string.length());
1633     for (int i = 0; i < layoutData->items.size(); i++) {
1634         const QScriptItem *si = layoutData->items.constData() + i;
1635         int pos = si->position;
1636         int ilen = length(i);
1637 //          qDebug("item %d: from %d len %d", i, pos, ilen);
1638         if (pos >= from + len)
1639             break;
1640         if (pos + ilen > from) {
1641             if (!si->num_glyphs)
1642                 shape(i);
1643
1644             if (si->analysis.flags == QScriptAnalysis::Object) {
1645                 w += si->width;
1646                 continue;
1647             } else if (si->analysis.flags == QScriptAnalysis::Tab) {
1648                 w += calculateTabWidth(i, w);
1649                 continue;
1650             }
1651
1652
1653             QGlyphLayout glyphs = shapedGlyphs(si);
1654             unsigned short *logClusters = this->logClusters(si);
1655
1656 //             fprintf(stderr, "  logclusters:");
1657 //             for (int k = 0; k < ilen; k++)
1658 //                 fprintf(stderr, " %d", logClusters[k]);
1659 //             fprintf(stderr, "\n");
1660             // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1661             int charFrom = from - pos;
1662             if (charFrom < 0)
1663                 charFrom = 0;
1664             int glyphStart = logClusters[charFrom];
1665             if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1666                 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1667                     charFrom++;
1668             if (charFrom < ilen) {
1669                 glyphStart = logClusters[charFrom];
1670                 int charEnd = from + len - 1 - pos;
1671                 if (charEnd >= ilen)
1672                     charEnd = ilen-1;
1673                 int glyphEnd = logClusters[charEnd];
1674                 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1675                     charEnd++;
1676                 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1677
1678 //                 qDebug("char: start=%d end=%d / glyph: start = %d, end = %d", charFrom, charEnd, glyphStart, glyphEnd);
1679                 for (int i = glyphStart; i < glyphEnd; i++)
1680                     w += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
1681             }
1682         }
1683     }
1684 //     qDebug("   --> w= %d ", w);
1685     return w;
1686 }
1687
1688 glyph_metrics_t QTextEngine::boundingBox(int from,  int len) const
1689 {
1690     itemize();
1691
1692     glyph_metrics_t gm;
1693
1694     for (int i = 0; i < layoutData->items.size(); i++) {
1695         const QScriptItem *si = layoutData->items.constData() + i;
1696
1697         int pos = si->position;
1698         int ilen = length(i);
1699         if (pos > from + len)
1700             break;
1701         if (pos + ilen > from) {
1702             if (!si->num_glyphs)
1703                 shape(i);
1704
1705             if (si->analysis.flags == QScriptAnalysis::Object) {
1706                 gm.width += si->width;
1707                 continue;
1708             } else if (si->analysis.flags == QScriptAnalysis::Tab) {
1709                 gm.width += calculateTabWidth(i, gm.width);
1710                 continue;
1711             }
1712
1713             unsigned short *logClusters = this->logClusters(si);
1714             QGlyphLayout glyphs = shapedGlyphs(si);
1715
1716             // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1717             int charFrom = from - pos;
1718             if (charFrom < 0)
1719                 charFrom = 0;
1720             int glyphStart = logClusters[charFrom];
1721             if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1722                 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1723                     charFrom++;
1724             if (charFrom < ilen) {
1725                 QFontEngine *fe = fontEngine(*si);
1726                 glyphStart = logClusters[charFrom];
1727                 int charEnd = from + len - 1 - pos;
1728                 if (charEnd >= ilen)
1729                     charEnd = ilen-1;
1730                 int glyphEnd = logClusters[charEnd];
1731                 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1732                     charEnd++;
1733                 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1734                 if (glyphStart <= glyphEnd ) {
1735                     glyph_metrics_t m = fe->boundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
1736                     gm.x = qMin(gm.x, m.x + gm.xoff);
1737                     gm.y = qMin(gm.y, m.y + gm.yoff);
1738                     gm.width = qMax(gm.width, m.width+gm.xoff);
1739                     gm.height = qMax(gm.height, m.height+gm.yoff);
1740                     gm.xoff += m.xoff;
1741                     gm.yoff += m.yoff;
1742                 }
1743             }
1744         }
1745     }
1746     return gm;
1747 }
1748
1749 glyph_metrics_t QTextEngine::tightBoundingBox(int from,  int len) const
1750 {
1751     itemize();
1752
1753     glyph_metrics_t gm;
1754
1755     for (int i = 0; i < layoutData->items.size(); i++) {
1756         const QScriptItem *si = layoutData->items.constData() + i;
1757         int pos = si->position;
1758         int ilen = length(i);
1759         if (pos > from + len)
1760             break;
1761         if (pos + len > from) {
1762             if (!si->num_glyphs)
1763                 shape(i);
1764             unsigned short *logClusters = this->logClusters(si);
1765             QGlyphLayout glyphs = shapedGlyphs(si);
1766
1767             // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1768             int charFrom = from - pos;
1769             if (charFrom < 0)
1770                 charFrom = 0;
1771             int glyphStart = logClusters[charFrom];
1772             if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1773                 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1774                     charFrom++;
1775             if (charFrom < ilen) {
1776                 glyphStart = logClusters[charFrom];
1777                 int charEnd = from + len - 1 - pos;
1778                 if (charEnd >= ilen)
1779                     charEnd = ilen-1;
1780                 int glyphEnd = logClusters[charEnd];
1781                 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1782                     charEnd++;
1783                 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1784                 if (glyphStart <= glyphEnd ) {
1785                     QFontEngine *fe = fontEngine(*si);
1786                     glyph_metrics_t m = fe->tightBoundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
1787                     gm.x = qMin(gm.x, m.x + gm.xoff);
1788                     gm.y = qMin(gm.y, m.y + gm.yoff);
1789                     gm.width = qMax(gm.width, m.width+gm.xoff);
1790                     gm.height = qMax(gm.height, m.height+gm.yoff);
1791                     gm.xoff += m.xoff;
1792                     gm.yoff += m.yoff;
1793                 }
1794             }
1795         }
1796     }
1797     return gm;
1798 }
1799
1800 QFont QTextEngine::font(const QScriptItem &si) const
1801 {
1802     QFont font = fnt;
1803     if (hasFormats()) {
1804         QTextCharFormat f = format(&si);
1805         font = f.font();
1806
1807         if (block.docHandle() && block.docHandle()->layout()) {
1808             // Make sure we get the right dpi on printers
1809             QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
1810             if (pdev)
1811                 font = QFont(font, pdev);
1812         } else {
1813             font = font.resolve(fnt);
1814         }
1815         QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
1816         if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
1817             if (font.pointSize() != -1)
1818                 font.setPointSize((font.pointSize() * 2) / 3);
1819             else
1820                 font.setPixelSize((font.pixelSize() * 2) / 3);
1821         }
1822     }
1823
1824     if (si.analysis.flags == QScriptAnalysis::SmallCaps)
1825         font = font.d->smallCapsFont();
1826
1827     return font;
1828 }
1829
1830 QTextEngine::FontEngineCache::FontEngineCache()
1831 {
1832     reset();
1833 }
1834
1835 //we cache the previous results of this function, as calling it numerous times with the same effective
1836 //input is common (and hard to cache at a higher level)
1837 QFontEngine *QTextEngine::fontEngine(const QScriptItem &si, QFixed *ascent, QFixed *descent, QFixed *leading) const
1838 {
1839     QFontEngine *engine = 0;
1840     QFontEngine *scaledEngine = 0;
1841     int script = si.analysis.script;
1842
1843     QFont font = fnt;
1844     if (hasFormats()) {
1845         if (feCache.prevFontEngine && feCache.prevPosition == si.position && feCache.prevLength == length(&si) && feCache.prevScript == script) {
1846             engine = feCache.prevFontEngine;
1847             scaledEngine = feCache.prevScaledFontEngine;
1848         } else {
1849             QTextCharFormat f = format(&si);
1850             font = f.font();
1851
1852             if (block.docHandle() && block.docHandle()->layout()) {
1853                 // Make sure we get the right dpi on printers
1854                 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
1855                 if (pdev)
1856                     font = QFont(font, pdev);
1857             } else {
1858                 font = font.resolve(fnt);
1859             }
1860             engine = font.d->engineForScript(script);
1861             QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
1862             if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
1863                 if (font.pointSize() != -1)
1864                     font.setPointSize((font.pointSize() * 2) / 3);
1865                 else
1866                     font.setPixelSize((font.pixelSize() * 2) / 3);
1867                 scaledEngine = font.d->engineForScript(script);
1868             }
1869             feCache.prevFontEngine = engine;
1870             if (engine)
1871                 engine->ref.ref();
1872             feCache.prevScaledFontEngine = scaledEngine;
1873             if (scaledEngine)
1874                 scaledEngine->ref.ref();
1875             feCache.prevScript = script;
1876             feCache.prevPosition = si.position;
1877             feCache.prevLength = length(&si);
1878         }
1879     } else {
1880         if (feCache.prevFontEngine && feCache.prevScript == script && feCache.prevPosition == -1)
1881             engine = feCache.prevFontEngine;
1882         else {
1883             engine = font.d->engineForScript(script);
1884             feCache.prevFontEngine = engine;
1885             if (engine)
1886                 engine->ref.ref();
1887             feCache.prevScript = script;
1888             feCache.prevPosition = -1;
1889             feCache.prevLength = -1;
1890             feCache.prevScaledFontEngine = 0;
1891         }
1892     }
1893
1894     if (si.analysis.flags == QScriptAnalysis::SmallCaps) {
1895         QFontPrivate *p = font.d->smallCapsFontPrivate();
1896         scaledEngine = p->engineForScript(script);
1897     }
1898
1899     if (ascent) {
1900         *ascent = engine->ascent();
1901         *descent = engine->descent();
1902         *leading = engine->leading();
1903     }
1904
1905     if (scaledEngine)
1906         return scaledEngine;
1907     return engine;
1908 }
1909
1910 struct QJustificationPoint {
1911     int type;
1912     QFixed kashidaWidth;
1913     QGlyphLayout glyph;
1914     QFontEngine *fontEngine;
1915 };
1916
1917 Q_DECLARE_TYPEINFO(QJustificationPoint, Q_PRIMITIVE_TYPE);
1918
1919 static void set(QJustificationPoint *point, int type, const QGlyphLayout &glyph, QFontEngine *fe)
1920 {
1921     point->type = type;
1922     point->glyph = glyph;
1923     point->fontEngine = fe;
1924
1925     if (type >= HB_Arabic_Normal) {
1926         QChar ch(0x640); // Kashida character
1927         QGlyphLayoutArray<8> glyphs;
1928         int nglyphs = 7;
1929         fe->stringToCMap(&ch, 1, &glyphs, &nglyphs, 0);
1930         if (glyphs.glyphs[0] && glyphs.advances_x[0] != 0) {
1931             point->kashidaWidth = glyphs.advances_x[0];
1932         } else {
1933             point->type = HB_NoJustification;
1934             point->kashidaWidth = 0;
1935         }
1936     }
1937 }
1938
1939
1940 void QTextEngine::justify(const QScriptLine &line)
1941 {
1942 //     qDebug("justify: line.gridfitted = %d, line.justified=%d", line.gridfitted, line.justified);
1943     if (line.gridfitted && line.justified)
1944         return;
1945
1946     if (!line.gridfitted) {
1947         // redo layout in device metrics, then adjust
1948         const_cast<QScriptLine &>(line).gridfitted = true;
1949     }
1950
1951     if ((option.alignment() & Qt::AlignHorizontal_Mask) != Qt::AlignJustify)
1952         return;
1953
1954     itemize();
1955
1956     if (!forceJustification) {
1957         int end = line.from + (int)line.length;
1958         if (end == layoutData->string.length())
1959             return; // no justification at end of paragraph
1960         if (end && layoutData->items[findItem(end-1)].analysis.flags == QScriptAnalysis::LineOrParagraphSeparator)
1961             return; // no justification at the end of an explicitly separated line
1962     }
1963
1964     // justify line
1965     int maxJustify = 0;
1966
1967     // don't include trailing white spaces when doing justification
1968     int line_length = line.length;
1969     const HB_CharAttributes *a = attributes();
1970     if (! a)
1971         return;
1972     a += line.from;
1973     while (line_length && a[line_length-1].whiteSpace)
1974         --line_length;
1975     // subtract one char more, as we can't justfy after the last character
1976     --line_length;
1977
1978     if (!line_length)
1979         return;
1980
1981     int firstItem = findItem(line.from);
1982     int nItems = findItem(line.from + line_length - 1) - firstItem + 1;
1983
1984     QVarLengthArray<QJustificationPoint> justificationPoints;
1985     int nPoints = 0;
1986 //     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());
1987     QFixed minKashida = 0x100000;
1988
1989     // we need to do all shaping before we go into the next loop, as we there
1990     // store pointers to the glyph data that could get reallocated by the shaping
1991     // process.
1992     for (int i = 0; i < nItems; ++i) {
1993         QScriptItem &si = layoutData->items[firstItem + i];
1994         if (!si.num_glyphs)
1995             shape(firstItem + i);
1996     }
1997
1998     for (int i = 0; i < nItems; ++i) {
1999         QScriptItem &si = layoutData->items[firstItem + i];
2000
2001         int kashida_type = HB_Arabic_Normal;
2002         int kashida_pos = -1;
2003
2004         int start = qMax(line.from - si.position, 0);
2005         int end = qMin(line.from + line_length - (int)si.position, length(firstItem+i));
2006
2007         unsigned short *log_clusters = logClusters(&si);
2008
2009         int gs = log_clusters[start];
2010         int ge = (end == length(firstItem+i) ? si.num_glyphs : log_clusters[end]);
2011
2012         const QGlyphLayout g = shapedGlyphs(&si);
2013
2014         for (int i = gs; i < ge; ++i) {
2015             g.justifications[i].type = QGlyphJustification::JustifyNone;
2016             g.justifications[i].nKashidas = 0;
2017             g.justifications[i].space_18d6 = 0;
2018
2019             justificationPoints.resize(nPoints+3);
2020             int justification = g.attributes[i].justification;
2021
2022             switch(justification) {
2023             case HB_NoJustification:
2024                 break;
2025             case HB_Space          :
2026                 // fall through
2027             case HB_Arabic_Space   :
2028                 if (kashida_pos >= 0) {
2029 //                     qDebug("kashida position at %d in word", kashida_pos);
2030                     set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
2031                     if (justificationPoints[nPoints].kashidaWidth > 0) {
2032                         minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
2033                         maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
2034                         ++nPoints;
2035                     }
2036                 }
2037                 kashida_pos = -1;
2038                 kashida_type = HB_Arabic_Normal;
2039                 // fall through
2040             case HB_Character      :
2041                 set(&justificationPoints[nPoints++], justification, g.mid(i), fontEngine(si));
2042                 maxJustify = qMax(maxJustify, justification);
2043                 break;
2044             case HB_Arabic_Normal  :
2045             case HB_Arabic_Waw     :
2046             case HB_Arabic_BaRa    :
2047             case HB_Arabic_Alef    :
2048             case HB_Arabic_HaaDal  :
2049             case HB_Arabic_Seen    :
2050             case HB_Arabic_Kashida :
2051                 if (justification >= kashida_type) {
2052                     kashida_pos = i;
2053                     kashida_type = justification;
2054                 }
2055             }
2056         }
2057         if (kashida_pos >= 0) {
2058             set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
2059             if (justificationPoints[nPoints].kashidaWidth > 0) {
2060                 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
2061                 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
2062                 ++nPoints;
2063             }
2064         }
2065     }
2066
2067     QFixed need = line.width - line.textWidth;
2068     if (need < 0) {
2069         // line overflows already!
2070         const_cast<QScriptLine &>(line).justified = true;
2071         return;
2072     }
2073
2074 //     qDebug("doing justification: textWidth=%x, requested=%x, maxJustify=%d", line.textWidth.value(), line.width.value(), maxJustify);
2075 //     qDebug("     minKashida=%f, need=%f", minKashida.toReal(), need.toReal());
2076
2077     // distribute in priority order
2078     if (maxJustify >= HB_Arabic_Normal) {
2079         while (need >= minKashida) {
2080             for (int type = maxJustify; need >= minKashida && type >= HB_Arabic_Normal; --type) {
2081                 for (int i = 0; need >= minKashida && i < nPoints; ++i) {
2082                     if (justificationPoints[i].type == type && justificationPoints[i].kashidaWidth <= need) {
2083                         justificationPoints[i].glyph.justifications->nKashidas++;
2084                         // ############
2085                         justificationPoints[i].glyph.justifications->space_18d6 += justificationPoints[i].kashidaWidth.value();
2086                         need -= justificationPoints[i].kashidaWidth;
2087 //                         qDebug("adding kashida type %d with width %x, neednow %x", type, justificationPoints[i].kashidaWidth, need.value());
2088                     }
2089                 }
2090             }
2091         }
2092     }
2093     Q_ASSERT(need >= 0);
2094     if (!need)
2095         goto end;
2096
2097     maxJustify = qMin(maxJustify, (int)HB_Space);
2098     for (int type = maxJustify; need != 0 && type > 0; --type) {
2099         int n = 0;
2100         for (int i = 0; i < nPoints; ++i) {
2101             if (justificationPoints[i].type == type)
2102                 ++n;
2103         }
2104 //          qDebug("number of points for justification type %d: %d", type, n);
2105
2106
2107         if (!n)
2108             continue;
2109
2110         for (int i = 0; i < nPoints; ++i) {
2111             if (justificationPoints[i].type == type) {
2112                 QFixed add = need/n;
2113 //                  qDebug("adding %x to glyph %x", add.value(), justificationPoints[i].glyph->glyph);
2114                 justificationPoints[i].glyph.justifications[0].space_18d6 = add.value();
2115                 need -= add;
2116                 --n;
2117             }
2118         }
2119
2120         Q_ASSERT(!need);
2121     }
2122  end:
2123     const_cast<QScriptLine &>(line).justified = true;
2124 }
2125
2126 void QScriptLine::setDefaultHeight(QTextEngine *eng)
2127 {
2128     QFont f;
2129     QFontEngine *e;
2130
2131     if (eng->block.docHandle() && eng->block.docHandle()->layout()) {
2132         f = eng->block.charFormat().font();
2133         // Make sure we get the right dpi on printers
2134         QPaintDevice *pdev = eng->block.docHandle()->layout()->paintDevice();
2135         if (pdev)
2136             f = QFont(f, pdev);
2137         e = f.d->engineForScript(QUnicodeTables::Common);
2138     } else {
2139         e = eng->fnt.d->engineForScript(QUnicodeTables::Common);
2140     }
2141
2142     QFixed other_ascent = e->ascent();
2143     QFixed other_descent = e->descent();
2144     QFixed other_leading = e->leading();
2145     leading = qMax(leading + ascent, other_leading + other_ascent) - qMax(ascent, other_ascent);
2146     ascent = qMax(ascent, other_ascent);
2147     descent = qMax(descent, other_descent);
2148 }
2149
2150 QTextEngine::LayoutData::LayoutData()
2151 {
2152     memory = 0;
2153     allocated = 0;
2154     memory_on_stack = false;
2155     used = 0;
2156     hasBidi = false;
2157     layoutState = LayoutEmpty;
2158     haveCharAttributes = false;
2159     logClustersPtr = 0;
2160     available_glyphs = 0;
2161 }
2162
2163 QTextEngine::LayoutData::LayoutData(const QString &str, void **stack_memory, int _allocated)
2164     : string(str)
2165 {
2166     allocated = _allocated;
2167
2168     int space_charAttributes = sizeof(HB_CharAttributes)*string.length()/sizeof(void*) + 1;
2169     int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2170     available_glyphs = ((int)allocated - space_charAttributes - space_logClusters)*(int)sizeof(void*)/(int)QGlyphLayout::spaceNeededForGlyphLayout(1);
2171
2172     if (available_glyphs < str.length()) {
2173         // need to allocate on the heap
2174         allocated = 0;
2175
2176         memory_on_stack = false;
2177         memory = 0;
2178         logClustersPtr = 0;
2179     } else {
2180         memory_on_stack = true;
2181         memory = stack_memory;
2182         logClustersPtr = (unsigned short *)(memory + space_charAttributes);
2183
2184         void *m = memory + space_charAttributes + space_logClusters;
2185         glyphLayout = QGlyphLayout(reinterpret_cast<char *>(m), str.length());
2186         glyphLayout.clear();
2187         memset(memory, 0, space_charAttributes*sizeof(void *));
2188     }
2189     used = 0;
2190     hasBidi = false;
2191     layoutState = LayoutEmpty;
2192     haveCharAttributes = false;
2193 }
2194
2195 QTextEngine::LayoutData::~LayoutData()
2196 {
2197     if (!memory_on_stack)
2198         free(memory);
2199     memory = 0;
2200 }
2201
2202 bool QTextEngine::LayoutData::reallocate(int totalGlyphs)
2203 {
2204     Q_ASSERT(totalGlyphs >= glyphLayout.numGlyphs);
2205     if (memory_on_stack && available_glyphs >= totalGlyphs) {
2206         glyphLayout.grow(glyphLayout.data(), totalGlyphs);
2207         return true;
2208     }
2209
2210     int space_charAttributes = sizeof(HB_CharAttributes)*string.length()/sizeof(void*) + 1;
2211     int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2212     int space_glyphs = QGlyphLayout::spaceNeededForGlyphLayout(totalGlyphs)/sizeof(void*) + 2;
2213
2214     int newAllocated = space_charAttributes + space_glyphs + space_logClusters;
2215     // These values can be negative if the length of string/glyphs causes overflow,
2216     // we can't layout such a long string all at once, so return false here to
2217     // indicate there is a failure
2218     if (space_charAttributes < 0 || space_logClusters < 0 || space_glyphs < 0 || newAllocated < allocated) {
2219         layoutState = LayoutFailed;
2220         return false;
2221     }
2222
2223     void **newMem = memory;
2224     newMem = (void **)::realloc(memory_on_stack ? 0 : memory, newAllocated*sizeof(void *));
2225     if (!newMem) {
2226         layoutState = LayoutFailed;
2227         return false;
2228     }
2229     if (memory_on_stack)
2230         memcpy(newMem, memory, allocated*sizeof(void *));
2231     memory = newMem;
2232     memory_on_stack = false;
2233
2234     void **m = memory;
2235     m += space_charAttributes;
2236     logClustersPtr = (unsigned short *) m;
2237     m += space_logClusters;
2238
2239     const int space_preGlyphLayout = space_charAttributes + space_logClusters;
2240     if (allocated < space_preGlyphLayout)
2241         memset(memory + allocated, 0, (space_preGlyphLayout - allocated)*sizeof(void *));
2242
2243     glyphLayout.grow(reinterpret_cast<char *>(m), totalGlyphs);
2244
2245     allocated = newAllocated;
2246     return true;
2247 }
2248
2249 // grow to the new size, copying the existing data to the new layout
2250 void QGlyphLayout::grow(char *address, int totalGlyphs)
2251 {
2252     QGlyphLayout oldLayout(address, numGlyphs);
2253     QGlyphLayout newLayout(address, totalGlyphs);
2254
2255     if (numGlyphs) {
2256         // move the existing data
2257         memmove(newLayout.attributes, oldLayout.attributes, numGlyphs * sizeof(HB_GlyphAttributes));
2258         memmove(newLayout.justifications, oldLayout.justifications, numGlyphs * sizeof(QGlyphJustification));
2259         memmove(newLayout.advances_y, oldLayout.advances_y, numGlyphs * sizeof(QFixed));
2260         memmove(newLayout.advances_x, oldLayout.advances_x, numGlyphs * sizeof(QFixed));
2261         memmove(newLayout.glyphs, oldLayout.glyphs, numGlyphs * sizeof(HB_Glyph));
2262     }
2263
2264     // clear the new data
2265     newLayout.clear(numGlyphs);
2266
2267     *this = newLayout;
2268 }
2269
2270 void QTextEngine::freeMemory()
2271 {
2272     if (!stackEngine) {
2273         delete layoutData;
2274         layoutData = 0;
2275     } else {
2276         layoutData->used = 0;
2277         layoutData->hasBidi = false;
2278         layoutData->layoutState = LayoutEmpty;
2279         layoutData->haveCharAttributes = false;
2280     }
2281     for (int i = 0; i < lines.size(); ++i) {
2282         lines[i].justified = 0;
2283         lines[i].gridfitted = 0;
2284     }
2285 }
2286
2287 int QTextEngine::formatIndex(const QScriptItem *si) const
2288 {
2289     if (specialData && !specialData->resolvedFormatIndices.isEmpty())
2290         return specialData->resolvedFormatIndices.at(si - &layoutData->items[0]);
2291     QTextDocumentPrivate *p = block.docHandle();
2292     if (!p)
2293         return -1;
2294     int pos = si->position;
2295     if (specialData && si->position >= specialData->preeditPosition) {
2296         if (si->position < specialData->preeditPosition + specialData->preeditText.length())
2297             pos = qMax(specialData->preeditPosition - 1, 0);
2298         else
2299             pos -= specialData->preeditText.length();
2300     }
2301     QTextDocumentPrivate::FragmentIterator it = p->find(block.position() + pos);
2302     return it.value()->format;
2303 }
2304
2305
2306 QTextCharFormat QTextEngine::format(const QScriptItem *si) const
2307 {
2308     QTextCharFormat format;
2309     const QTextFormatCollection *formats = 0;
2310     if (block.docHandle()) {
2311         formats = this->formats();
2312         format = formats->charFormat(formatIndex(si));
2313     }
2314     if (specialData && specialData->resolvedFormatIndices.isEmpty()) {
2315         int end = si->position + length(si);
2316         for (int i = 0; i < specialData->addFormats.size(); ++i) {
2317             const QTextLayout::FormatRange &r = specialData->addFormats.at(i);
2318             if (r.start <= si->position && r.start + r.length >= end) {
2319                 if (!specialData->addFormatIndices.isEmpty())
2320                     format.merge(formats->format(specialData->addFormatIndices.at(i)));
2321                 else
2322                     format.merge(r.format);
2323             }
2324         }
2325     }
2326     return format;
2327 }
2328
2329 void QTextEngine::addRequiredBoundaries() const
2330 {
2331     if (specialData) {
2332         for (int i = 0; i < specialData->addFormats.size(); ++i) {
2333             const QTextLayout::FormatRange &r = specialData->addFormats.at(i);
2334             setBoundary(r.start);
2335             setBoundary(r.start + r.length);
2336             //qDebug("adding boundaries %d %d", r.start, r.start+r.length);
2337         }
2338     }
2339 }
2340
2341 bool QTextEngine::atWordSeparator(int position) const
2342 {
2343     const QChar c = layoutData->string.at(position);
2344     switch (c.toLatin1()) {
2345     case '.':
2346     case ',':
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         return true;
2376     default:
2377         return false;
2378     }
2379 }
2380
2381 bool QTextEngine::atSpace(int position) const
2382 {
2383     const QChar c = layoutData->string.at(position);
2384
2385     return c == QLatin1Char(' ')
2386         || c == QChar::Nbsp
2387         || c == QChar::LineSeparator
2388         || c == QLatin1Char('\t')
2389         ;
2390 }
2391
2392
2393 void QTextEngine::indexAdditionalFormats()
2394 {
2395     if (!block.docHandle())
2396         return;
2397
2398     specialData->addFormatIndices.resize(specialData->addFormats.count());
2399     QTextFormatCollection * const formats = this->formats();
2400
2401     for (int i = 0; i < specialData->addFormats.count(); ++i) {
2402         specialData->addFormatIndices[i] = formats->indexForFormat(specialData->addFormats.at(i).format);
2403         specialData->addFormats[i].format = QTextCharFormat();
2404     }
2405 }
2406
2407 /* These two helper functions are used to determine whether we need to insert a ZWJ character
2408    between the text that gets truncated and the ellipsis. This is important to get
2409    correctly shaped results for arabic text.
2410 */
2411 static bool nextCharJoins(const QString &string, int pos)
2412 {
2413     while (pos < string.length() && string.at(pos).category() == QChar::Mark_NonSpacing)
2414         ++pos;
2415     if (pos == string.length())
2416         return false;
2417     return string.at(pos).joining() != QChar::OtherJoining;
2418 }
2419
2420 static bool prevCharJoins(const QString &string, int pos)
2421 {
2422     while (pos > 0 && string.at(pos - 1).category() == QChar::Mark_NonSpacing)
2423         --pos;
2424     if (pos == 0)
2425         return false;
2426     return (string.at(pos - 1).joining() == QChar::Dual || string.at(pos - 1).joining() == QChar::Center);
2427 }
2428
2429 QString QTextEngine::elidedText(Qt::TextElideMode mode, const QFixed &width, int flags) const
2430 {
2431 //    qDebug() << "elidedText; available width" << width.toReal() << "text width:" << this->width(0, layoutData->string.length()).toReal();
2432
2433     if (flags & Qt::TextShowMnemonic) {
2434         itemize();
2435         HB_CharAttributes *attributes = const_cast<HB_CharAttributes *>(this->attributes());
2436         if (!attributes)
2437             return QString();
2438         for (int i = 0; i < layoutData->items.size(); ++i) {
2439             QScriptItem &si = layoutData->items[i];
2440             if (!si.num_glyphs)
2441                 shape(i);
2442
2443             unsigned short *logClusters = this->logClusters(&si);
2444             QGlyphLayout glyphs = shapedGlyphs(&si);
2445
2446             const int end = si.position + length(&si);
2447             for (int i = si.position; i < end - 1; ++i) {
2448                 if (layoutData->string.at(i) == QLatin1Char('&')) {
2449                     const int gp = logClusters[i - si.position];
2450                     glyphs.attributes[gp].dontPrint = true;
2451                     attributes[i + 1].charStop = false;
2452                     attributes[i + 1].whiteSpace = false;
2453                     attributes[i + 1].lineBreakType = HB_NoBreak;
2454                     if (layoutData->string.at(i + 1) == QLatin1Char('&'))
2455                         ++i;
2456                 }
2457             }
2458         }
2459     }
2460
2461     validate();
2462
2463     if (mode == Qt::ElideNone
2464         || this->width(0, layoutData->string.length()) <= width
2465         || layoutData->string.length() <= 1)
2466         return layoutData->string;
2467
2468     QFixed ellipsisWidth;
2469     QString ellipsisText;
2470     {
2471         QChar ellipsisChar(0x2026);
2472
2473         QFontEngine *fe = fnt.d->engineForScript(QUnicodeTables::Common);
2474
2475         QGlyphLayoutArray<1> ellipsisGlyph;
2476         {
2477             QFontEngine *feForEllipsis = (fe->type() == QFontEngine::Multi)
2478                 ? static_cast<QFontEngineMulti *>(fe)->engine(0)
2479                 : fe;
2480
2481             if (feForEllipsis->type() == QFontEngine::Mac)
2482                 feForEllipsis = fe;
2483
2484             // the lookup can be really slow when we use XLFD fonts
2485             if (feForEllipsis->type() != QFontEngine::XLFD
2486                 && feForEllipsis->canRender(&ellipsisChar, 1)) {
2487                     int nGlyphs = 1;
2488                     feForEllipsis->stringToCMap(&ellipsisChar, 1, &ellipsisGlyph, &nGlyphs, 0);
2489                 }
2490         }
2491
2492         if (ellipsisGlyph.glyphs[0]) {
2493             ellipsisWidth = ellipsisGlyph.advances_x[0];
2494             ellipsisText = ellipsisChar;
2495         } else {
2496             QString dotDotDot(QLatin1String("..."));
2497
2498             QGlyphLayoutArray<3> glyphs;
2499             int nGlyphs = 3;
2500             if (!fe->stringToCMap(dotDotDot.constData(), 3, &glyphs, &nGlyphs, 0))
2501                 // should never happen...
2502                 return layoutData->string;
2503             for (int i = 0; i < nGlyphs; ++i)
2504                 ellipsisWidth += glyphs.advances_x[i];
2505             ellipsisText = dotDotDot;
2506         }
2507     }
2508
2509     const QFixed availableWidth = width - ellipsisWidth;
2510     if (availableWidth < 0)
2511         return QString();
2512
2513     const HB_CharAttributes *attributes = this->attributes();
2514     if (!attributes)
2515         return QString();
2516
2517     if (mode == Qt::ElideRight) {
2518         QFixed currentWidth;
2519         int pos;
2520         int nextBreak = 0;
2521
2522         do {
2523             pos = nextBreak;
2524
2525             ++nextBreak;
2526             while (nextBreak < layoutData->string.length() && !attributes[nextBreak].charStop)
2527                 ++nextBreak;
2528
2529             currentWidth += this->width(pos, nextBreak - pos);
2530         } while (nextBreak < layoutData->string.length()
2531                  && currentWidth < availableWidth);
2532
2533         if (nextCharJoins(layoutData->string, pos))
2534             ellipsisText.prepend(QChar(0x200d) /* ZWJ */);
2535
2536         return layoutData->string.left(pos) + ellipsisText;
2537     } else if (mode == Qt::ElideLeft) {
2538         QFixed currentWidth;
2539         int pos;
2540         int nextBreak = layoutData->string.length();
2541
2542         do {
2543             pos = nextBreak;
2544
2545             --nextBreak;
2546             while (nextBreak > 0 && !attributes[nextBreak].charStop)
2547                 --nextBreak;
2548
2549             currentWidth += this->width(nextBreak, pos - nextBreak);
2550         } while (nextBreak > 0
2551                  && currentWidth < availableWidth);
2552
2553         if (prevCharJoins(layoutData->string, pos))
2554             ellipsisText.append(QChar(0x200d) /* ZWJ */);
2555
2556         return ellipsisText + layoutData->string.mid(pos);
2557     } else if (mode == Qt::ElideMiddle) {
2558         QFixed leftWidth;
2559         QFixed rightWidth;
2560
2561         int leftPos = 0;
2562         int nextLeftBreak = 0;
2563
2564         int rightPos = layoutData->string.length();
2565         int nextRightBreak = layoutData->string.length();
2566
2567         do {
2568             leftPos = nextLeftBreak;
2569             rightPos = nextRightBreak;
2570
2571             ++nextLeftBreak;
2572             while (nextLeftBreak < layoutData->string.length() && !attributes[nextLeftBreak].charStop)
2573                 ++nextLeftBreak;
2574
2575             --nextRightBreak;
2576             while (nextRightBreak > 0 && !attributes[nextRightBreak].charStop)
2577                 --nextRightBreak;
2578
2579             leftWidth += this->width(leftPos, nextLeftBreak - leftPos);
2580             rightWidth += this->width(nextRightBreak, rightPos - nextRightBreak);
2581         } while (nextLeftBreak < layoutData->string.length()
2582                  && nextRightBreak > 0
2583                  && leftWidth + rightWidth < availableWidth);
2584
2585         if (nextCharJoins(layoutData->string, leftPos))
2586             ellipsisText.prepend(QChar(0x200d) /* ZWJ */);
2587         if (prevCharJoins(layoutData->string, rightPos))
2588             ellipsisText.append(QChar(0x200d) /* ZWJ */);
2589
2590         return layoutData->string.left(leftPos) + ellipsisText + layoutData->string.mid(rightPos);
2591     }
2592
2593     return layoutData->string;
2594 }
2595
2596 void QTextEngine::setBoundary(int strPos) const
2597 {
2598     if (strPos <= 0 || strPos >= layoutData->string.length())
2599         return;
2600
2601     int itemToSplit = 0;
2602     while (itemToSplit < layoutData->items.size() && layoutData->items.at(itemToSplit).position <= strPos)
2603         itemToSplit++;
2604     itemToSplit--;
2605     if (layoutData->items.at(itemToSplit).position == strPos) {
2606         // already a split at the requested position
2607         return;
2608     }
2609     splitItem(itemToSplit, strPos - layoutData->items.at(itemToSplit).position);
2610 }
2611
2612 void QTextEngine::splitItem(int item, int pos) const
2613 {
2614     if (pos <= 0)
2615         return;
2616
2617     layoutData->items.insert(item + 1, layoutData->items[item]);
2618     QScriptItem &oldItem = layoutData->items[item];
2619     QScriptItem &newItem = layoutData->items[item+1];
2620     newItem.position += pos;
2621
2622     if (oldItem.num_glyphs) {
2623         // already shaped, break glyphs aswell
2624         int breakGlyph = logClusters(&oldItem)[pos];
2625
2626         newItem.num_glyphs = oldItem.num_glyphs - breakGlyph;
2627         oldItem.num_glyphs = breakGlyph;
2628         newItem.glyph_data_offset = oldItem.glyph_data_offset + breakGlyph;
2629
2630         for (int i = 0; i < newItem.num_glyphs; i++)
2631             logClusters(&newItem)[i] -= breakGlyph;
2632
2633         QFixed w = 0;
2634         const QGlyphLayout g = shapedGlyphs(&oldItem);
2635         for(int j = 0; j < breakGlyph; ++j)
2636             w += g.advances_x[j];
2637
2638         newItem.width = oldItem.width - w;
2639         oldItem.width = w;
2640     }
2641
2642 //     qDebug("split at position %d itempos=%d", pos, item);
2643 }
2644
2645 QFixed QTextEngine::calculateTabWidth(int item, QFixed x) const
2646 {
2647     const QScriptItem &si = layoutData->items[item];
2648
2649     QFixed dpiScale = 1;
2650     if (block.docHandle() && block.docHandle()->layout()) {
2651         QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
2652         if (pdev)
2653             dpiScale = QFixed::fromReal(pdev->logicalDpiY() / qreal(qt_defaultDpiY()));
2654     } else {
2655         dpiScale = QFixed::fromReal(fnt.d->dpi / qreal(qt_defaultDpiY()));
2656     }
2657
2658     QList<QTextOption::Tab> tabArray = option.tabs();
2659     if (!tabArray.isEmpty()) {
2660         if (isRightToLeft()) { // rebase the tabArray positions.
2661             QList<QTextOption::Tab> newTabs;
2662             QList<QTextOption::Tab>::Iterator iter = tabArray.begin();
2663             while(iter != tabArray.end()) {
2664                 QTextOption::Tab tab = *iter;
2665                 if (tab.type == QTextOption::LeftTab)
2666                     tab.type = QTextOption::RightTab;
2667                 else if (tab.type == QTextOption::RightTab)
2668                     tab.type = QTextOption::LeftTab;
2669                 newTabs << tab;
2670                 ++iter;
2671             }
2672             tabArray = newTabs;
2673         }
2674         for (int i = 0; i < tabArray.size(); ++i) {
2675             QFixed tab = QFixed::fromReal(tabArray[i].position) * dpiScale;
2676             if (tab > x) {  // this is the tab we need.
2677                 QTextOption::Tab tabSpec = tabArray[i];
2678                 int tabSectionEnd = layoutData->string.count();
2679                 if (tabSpec.type == QTextOption::RightTab || tabSpec.type == QTextOption::CenterTab) {
2680                     // find next tab to calculate the width required.
2681                     tab = QFixed::fromReal(tabSpec.position);
2682                     for (int i=item + 1; i < layoutData->items.count(); i++) {
2683                         const QScriptItem &item = layoutData->items[i];
2684                         if (item.analysis.flags == QScriptAnalysis::TabOrObject) { // found it.
2685                             tabSectionEnd = item.position;
2686                             break;
2687                         }
2688                     }
2689                 }
2690                 else if (tabSpec.type == QTextOption::DelimiterTab)
2691                     // find delimitor character to calculate the width required
2692                     tabSectionEnd = qMax(si.position, layoutData->string.indexOf(tabSpec.delimiter, si.position) + 1);
2693
2694                 if (tabSectionEnd > si.position) {
2695                     QFixed length;
2696                     // Calculate the length of text between this tab and the tabSectionEnd
2697                     for (int i=item; i < layoutData->items.count(); i++) {
2698                         QScriptItem &item = layoutData->items[i];
2699                         if (item.position > tabSectionEnd || item.position <= si.position)
2700                             continue;
2701                         shape(i); // first, lets make sure relevant text is already shaped
2702                         QGlyphLayout glyphs = this->shapedGlyphs(&item);
2703                         const int end = qMin(item.position + item.num_glyphs, tabSectionEnd) - item.position;
2704                         for (int i=0; i < end; i++)
2705                             length += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
2706                         if (end + item.position == tabSectionEnd && tabSpec.type == QTextOption::DelimiterTab) // remove half of matching char
2707                             length -= glyphs.advances_x[end] / 2 * !glyphs.attributes[end].dontPrint;
2708                     }
2709
2710                     switch (tabSpec.type) {
2711                     case QTextOption::CenterTab:
2712                         length /= 2;
2713                         // fall through
2714                     case QTextOption::DelimiterTab:
2715                         // fall through
2716                     case QTextOption::RightTab:
2717                         tab = QFixed::fromReal(tabSpec.position) * dpiScale - length;
2718                         if (tab < 0) // default to tab taking no space
2719                             return QFixed();
2720                         break;
2721                     case QTextOption::LeftTab:
2722                         break;
2723                     }
2724                 }
2725                 return tab - x;
2726             }
2727         }
2728     }
2729     QFixed tab = QFixed::fromReal(option.tabStop());
2730     if (tab <= 0)
2731         tab = 80; // default
2732     tab *= dpiScale;
2733     QFixed nextTabPos = ((x / tab).truncate() + 1) * tab;
2734     QFixed tabWidth = nextTabPos - x;
2735
2736     return tabWidth;
2737 }
2738
2739 void QTextEngine::resolveAdditionalFormats() const
2740 {
2741     if (!specialData || specialData->addFormats.isEmpty()
2742         || !block.docHandle()
2743         || !specialData->resolvedFormatIndices.isEmpty())
2744         return;
2745
2746     QTextFormatCollection *collection = this->formats();
2747
2748     specialData->resolvedFormatIndices.clear();
2749     QVector<int> indices(layoutData->items.count());
2750     for (int i = 0; i < layoutData->items.count(); ++i) {
2751         QTextCharFormat f = format(&layoutData->items.at(i));
2752         indices[i] = collection->indexForFormat(f);
2753     }
2754     specialData->resolvedFormatIndices = indices;
2755 }
2756
2757 QFixed QTextEngine::leadingSpaceWidth(const QScriptLine &line)
2758 {
2759     if (!line.hasTrailingSpaces
2760         || (option.flags() & QTextOption::IncludeTrailingSpaces)
2761         || !isRightToLeft())
2762         return QFixed();
2763
2764     int pos = line.length;
2765     const HB_CharAttributes *attributes = this->attributes();
2766     if (!attributes)
2767         return QFixed();
2768     while (pos > 0 && attributes[line.from + pos - 1].whiteSpace)
2769         --pos;
2770     return width(line.from + pos, line.length - pos);
2771 }
2772
2773 QFixed QTextEngine::alignLine(const QScriptLine &line)
2774 {
2775     QFixed x = 0;
2776     justify(line);
2777     // if width is QFIXED_MAX that means we used setNumColumns() and that implicitly makes this line left aligned.
2778     if (!line.justified && line.width != QFIXED_MAX) {
2779         int align = option.alignment();
2780         if (align & Qt::AlignLeft)
2781             x -= leadingSpaceWidth(line);
2782         if (align & Qt::AlignJustify && isRightToLeft())
2783             align = Qt::AlignRight;
2784         if (align & Qt::AlignRight)
2785             x = line.width - (line.textAdvance + leadingSpaceWidth(line));
2786         else if (align & Qt::AlignHCenter)
2787             x = (line.width - (line.textAdvance + leadingSpaceWidth(line)))/2;
2788     }
2789     return x;
2790 }
2791
2792 QFixed QTextEngine::offsetInLigature(const QScriptItem *si, int pos, int max, int glyph_pos)
2793 {
2794     unsigned short *logClusters = this->logClusters(si);
2795     const QGlyphLayout &glyphs = shapedGlyphs(si);
2796
2797     int offsetInCluster = 0;
2798     for (int i = pos - 1; i >= 0; i--) {
2799         if (logClusters[i] == glyph_pos)
2800             offsetInCluster++;
2801         else
2802             break;
2803     }
2804
2805     // in the case that the offset is inside a (multi-character) glyph,
2806     // interpolate the position.
2807     if (offsetInCluster > 0) {
2808         int clusterLength = 0;
2809         for (int i = pos - offsetInCluster; i < max; i++) {
2810             if (logClusters[i] == glyph_pos)
2811                 clusterLength++;
2812             else
2813                 break;
2814         }
2815         if (clusterLength)
2816             return glyphs.advances_x[glyph_pos] * offsetInCluster / clusterLength;
2817     }
2818
2819     return 0;
2820 }
2821
2822 int QTextEngine::previousLogicalPosition(int oldPos) const
2823 {
2824     const HB_CharAttributes *attrs = attributes();
2825     if (!attrs || oldPos < 0)
2826         return oldPos;
2827
2828     if (oldPos <= 0)
2829         return 0;
2830     oldPos--;
2831     while (oldPos && !attrs[oldPos].charStop)
2832         oldPos--;
2833     return oldPos;
2834 }
2835
2836 int QTextEngine::nextLogicalPosition(int oldPos) const
2837 {
2838     const HB_CharAttributes *attrs = attributes();
2839     int len = block.isValid() ? block.length() - 1
2840                               : layoutData->string.length();
2841     Q_ASSERT(len <= layoutData->string.length());
2842     if (!attrs || oldPos < 0 || oldPos >= len)
2843         return oldPos;
2844
2845     oldPos++;
2846     while (oldPos < len && !attrs[oldPos].charStop)
2847         oldPos++;
2848     return oldPos;
2849 }
2850
2851 int QTextEngine::lineNumberForTextPosition(int pos)
2852 {
2853     if (!layoutData)
2854         itemize();
2855     if (pos == layoutData->string.length() && lines.size())
2856         return lines.size() - 1;
2857     for (int i = 0; i < lines.size(); ++i) {
2858         const QScriptLine& line = lines[i];
2859         if (line.from + line.length > pos)
2860             return i;
2861     }
2862     return -1;
2863 }
2864
2865 void QTextEngine::insertionPointsForLine(int lineNum, QVector<int> &insertionPoints)
2866 {
2867     QTextLineItemIterator iterator(this, lineNum);
2868     bool rtl = isRightToLeft();
2869     bool lastLine = lineNum >= lines.size() - 1;
2870
2871     while (!iterator.atEnd()) {
2872         iterator.next();
2873         const QScriptItem *si = &layoutData->items[iterator.item];
2874         if (si->analysis.bidiLevel % 2) {
2875             int i = iterator.itemEnd - 1, min = iterator.itemStart;
2876             if (lastLine && (rtl ? iterator.atBeginning() : iterator.atEnd()))
2877                 i++;
2878             for (; i >= min; i--)
2879                 insertionPoints.push_back(i);
2880         } else {
2881             int i = iterator.itemStart, max = iterator.itemEnd;
2882             if (lastLine && (rtl ? iterator.atBeginning() : iterator.atEnd()))
2883                 max++;
2884             for (; i < max; i++)
2885                 insertionPoints.push_back(i);
2886         }
2887     }
2888 }
2889
2890 int QTextEngine::endOfLine(int lineNum)
2891 {
2892     QVector<int> insertionPoints;
2893     insertionPointsForLine(lineNum, insertionPoints);
2894
2895     if (insertionPoints.size() > 0)
2896         return insertionPoints.last();
2897     return 0;
2898 }
2899
2900 int QTextEngine::beginningOfLine(int lineNum)
2901 {
2902     QVector<int> insertionPoints;
2903     insertionPointsForLine(lineNum, insertionPoints);
2904
2905     if (insertionPoints.size() > 0)
2906         return insertionPoints.first();
2907     return 0;
2908 }
2909
2910 int QTextEngine::positionAfterVisualMovement(int pos, QTextCursor::MoveOperation op)
2911 {
2912     if (!layoutData)
2913         itemize();
2914
2915     bool moveRight = (op == QTextCursor::Right);
2916     bool alignRight = isRightToLeft();
2917     if (!layoutData->hasBidi)
2918         return moveRight ^ alignRight ? nextLogicalPosition(pos) : previousLogicalPosition(pos);
2919
2920     int lineNum = lineNumberForTextPosition(pos);
2921     Q_ASSERT(lineNum >= 0);
2922
2923     QVector<int> insertionPoints;
2924     insertionPointsForLine(lineNum, insertionPoints);
2925     int i, max = insertionPoints.size();
2926     for (i = 0; i < max; i++)
2927         if (pos == insertionPoints[i]) {
2928             if (moveRight) {
2929                 if (i + 1 < max)
2930                     return insertionPoints[i + 1];
2931             } else {
2932                 if (i > 0)
2933                     return insertionPoints[i - 1];
2934             }
2935
2936             if (moveRight ^ alignRight) {
2937                 if (lineNum + 1 < lines.size())
2938                     return alignRight ? endOfLine(lineNum + 1) : beginningOfLine(lineNum + 1);
2939             }
2940             else {
2941                 if (lineNum > 0)
2942                     return alignRight ? beginningOfLine(lineNum - 1) : endOfLine(lineNum - 1);
2943             }
2944         }
2945
2946     return pos;
2947 }
2948
2949 QStackTextEngine::QStackTextEngine(const QString &string, const QFont &f)
2950     : QTextEngine(string, f),
2951       _layoutData(string, _memory, MemSize)
2952 {
2953     stackEngine = true;
2954     layoutData = &_layoutData;
2955 }
2956
2957 QTextItemInt::QTextItemInt(const QScriptItem &si, QFont *font, const QTextCharFormat &format)
2958     : justified(false), underlineStyle(QTextCharFormat::NoUnderline), charFormat(format),
2959       num_chars(0), chars(0), logClusters(0), f(0), fontEngine(0)
2960 {
2961     // explicitly initialize flags so that initFontAttributes can be called
2962     // multiple times on the same TextItem
2963     flags = 0;
2964     if (si.analysis.bidiLevel %2)
2965         flags |= QTextItem::RightToLeft;
2966     ascent = si.ascent;
2967     descent = si.descent;
2968     f = font;
2969     fontEngine = f->d->engineForScript(si.analysis.script);
2970     Q_ASSERT(fontEngine);
2971
2972     if (format.hasProperty(QTextFormat::TextUnderlineStyle)) {
2973         underlineStyle = format.underlineStyle();
2974     } else if (format.boolProperty(QTextFormat::FontUnderline)
2975                || f->d->underline) {
2976         underlineStyle = QTextCharFormat::SingleUnderline;
2977     }
2978
2979     // compat
2980     if (underlineStyle == QTextCharFormat::SingleUnderline)
2981         flags |= QTextItem::Underline;
2982
2983     if (f->d->overline || format.fontOverline())
2984         flags |= QTextItem::Overline;
2985     if (f->d->strikeOut || format.fontStrikeOut())
2986         flags |= QTextItem::StrikeOut;
2987 }
2988
2989 QTextItemInt::QTextItemInt(const QGlyphLayout &g, QFont *font, const QChar *chars_, int numChars, QFontEngine *fe)
2990     : flags(0), justified(false), underlineStyle(QTextCharFormat::NoUnderline),
2991       num_chars(numChars), chars(chars_), logClusters(0), f(font),  glyphs(g), fontEngine(fe)
2992 {
2993 }
2994
2995 QTextItemInt QTextItemInt::midItem(QFontEngine *fontEngine, int firstGlyphIndex, int numGlyphs) const
2996 {
2997     QTextItemInt ti = *this;
2998     const int end = firstGlyphIndex + numGlyphs;
2999     ti.glyphs = glyphs.mid(firstGlyphIndex, numGlyphs);
3000     ti.fontEngine = fontEngine;
3001
3002     if (logClusters && chars) {
3003         const int logClusterOffset = logClusters[0];
3004         while (logClusters[ti.chars - chars] - logClusterOffset < firstGlyphIndex)
3005             ++ti.chars;
3006
3007         ti.logClusters += (ti.chars - chars);
3008
3009         ti.num_chars = 0;
3010         int char_start = ti.chars - chars;
3011         while (char_start + ti.num_chars < num_chars && ti.logClusters[ti.num_chars] - logClusterOffset < end)
3012             ++ti.num_chars;
3013     }
3014     return ti;
3015 }
3016
3017
3018 QTransform qt_true_matrix(qreal w, qreal h, QTransform x)
3019 {
3020     QRectF rect = x.mapRect(QRectF(0, 0, w, h));
3021     return x * QTransform::fromTranslate(-rect.x(), -rect.y());
3022 }
3023
3024
3025 glyph_metrics_t glyph_metrics_t::transformed(const QTransform &matrix) const
3026 {
3027     if (matrix.type() < QTransform::TxTranslate)
3028         return *this;
3029
3030     glyph_metrics_t m = *this;
3031
3032     qreal w = width.toReal();
3033     qreal h = height.toReal();
3034     QTransform xform = qt_true_matrix(w, h, matrix);
3035
3036     QRectF rect(0, 0, w, h);
3037     rect = xform.mapRect(rect);
3038     m.width = QFixed::fromReal(rect.width());
3039     m.height = QFixed::fromReal(rect.height());
3040
3041     QLineF l = xform.map(QLineF(x.toReal(), y.toReal(), xoff.toReal(), yoff.toReal()));
3042
3043     m.x = QFixed::fromReal(l.x1());
3044     m.y = QFixed::fromReal(l.y1());
3045
3046     // The offset is relative to the baseline which is why we use dx/dy of the line
3047     m.xoff = QFixed::fromReal(l.dx());
3048     m.yoff = QFixed::fromReal(l.dy());
3049
3050     return m;
3051 }
3052
3053 QTextLineItemIterator::QTextLineItemIterator(QTextEngine *_eng, int _lineNum, const QPointF &pos,
3054                                              const QTextLayout::FormatRange *_selection)
3055     : eng(_eng),
3056       line(eng->lines[_lineNum]),
3057       si(0),
3058       lineNum(_lineNum),
3059       lineEnd(line.from + line.length),
3060       firstItem(eng->findItem(line.from)),
3061       lastItem(eng->findItem(lineEnd - 1)),
3062       nItems((firstItem >= 0 && lastItem >= firstItem)? (lastItem-firstItem+1) : 0),
3063       logicalItem(-1),
3064       item(-1),
3065       visualOrder(nItems),
3066       levels(nItems),
3067       selection(_selection)
3068 {
3069     pos_x = x = QFixed::fromReal(pos.x());
3070
3071     x += line.x;
3072
3073     x += eng->alignLine(line);
3074
3075     for (int i = 0; i < nItems; ++i)
3076         levels[i] = eng->layoutData->items[i+firstItem].analysis.bidiLevel;
3077     QTextEngine::bidiReorder(nItems, levels.data(), visualOrder.data());
3078
3079     eng->shapeLine(line);
3080 }
3081
3082 QScriptItem &QTextLineItemIterator::next()
3083 {
3084     x += itemWidth;
3085
3086     ++logicalItem;
3087     item = visualOrder[logicalItem] + firstItem;
3088     itemLength = eng->length(item);
3089     si = &eng->layoutData->items[item];
3090     if (!si->num_glyphs)
3091         eng->shape(item);
3092
3093     if (si->analysis.flags >= QScriptAnalysis::TabOrObject) {
3094         itemWidth = si->width;
3095         return *si;
3096     }
3097
3098     unsigned short *logClusters = eng->logClusters(si);
3099     QGlyphLayout glyphs = eng->shapedGlyphs(si);
3100
3101     itemStart = qMax(line.from, si->position);
3102     glyphsStart = logClusters[itemStart - si->position];
3103     if (lineEnd < si->position + itemLength) {
3104         itemEnd = lineEnd;
3105         glyphsEnd = logClusters[itemEnd-si->position];
3106     } else {
3107         itemEnd = si->position + itemLength;
3108         glyphsEnd = si->num_glyphs;
3109     }
3110     // show soft-hyphen at line-break
3111     if (si->position + itemLength >= lineEnd
3112         && eng->layoutData->string.at(lineEnd - 1) == 0x00ad)
3113         glyphs.attributes[glyphsEnd - 1].dontPrint = false;
3114
3115     itemWidth = 0;
3116     for (int g = glyphsStart; g < glyphsEnd; ++g)
3117         itemWidth += glyphs.effectiveAdvance(g);
3118
3119     return *si;
3120 }
3121
3122 bool QTextLineItemIterator::getSelectionBounds(QFixed *selectionX, QFixed *selectionWidth) const
3123 {
3124     *selectionX = *selectionWidth = 0;
3125
3126     if (!selection)
3127         return false;
3128
3129     if (si->analysis.flags >= QScriptAnalysis::TabOrObject) {
3130         if (si->position >= selection->start + selection->length
3131             || si->position + itemLength <= selection->start)
3132             return false;
3133
3134         *selectionX = x;
3135         *selectionWidth = itemWidth;
3136     } else {
3137         unsigned short *logClusters = eng->logClusters(si);
3138         QGlyphLayout glyphs = eng->shapedGlyphs(si);
3139
3140         int from = qMax(itemStart, selection->start) - si->position;
3141         int to = qMin(itemEnd, selection->start + selection->length) - si->position;
3142         if (from >= to)
3143             return false;
3144
3145         int start_glyph = logClusters[from];
3146         int end_glyph = (to == eng->length(item)) ? si->num_glyphs : logClusters[to];
3147         QFixed soff;
3148         QFixed swidth;
3149         if (si->analysis.bidiLevel %2) {
3150             for (int g = glyphsEnd - 1; g >= end_glyph; --g)
3151                 soff += glyphs.effectiveAdvance(g);
3152             for (int g = end_glyph - 1; g >= start_glyph; --g)
3153                 swidth += glyphs.effectiveAdvance(g);
3154         } else {
3155             for (int g = glyphsStart; g < start_glyph; ++g)
3156                 soff += glyphs.effectiveAdvance(g);
3157             for (int g = start_glyph; g < end_glyph; ++g)
3158                 swidth += glyphs.effectiveAdvance(g);
3159         }
3160
3161         // If the starting character is in the middle of a ligature,
3162         // selection should only contain the right part of that ligature
3163         // glyph, so we need to get the width of the left part here and
3164         // add it to *selectionX
3165         QFixed leftOffsetInLigature = eng->offsetInLigature(si, from, to, start_glyph);
3166         *selectionX = x + soff + leftOffsetInLigature;
3167         *selectionWidth = swidth - leftOffsetInLigature;
3168         // If the ending character is also part of a ligature, swidth does
3169         // not contain that part yet, we also need to find out the width of
3170         // that left part
3171         *selectionWidth += eng->offsetInLigature(si, to, eng->length(item), end_glyph);
3172     }
3173     return true;
3174 }
3175
3176 QT_END_NAMESPACE