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