summaryrefslogtreecommitdiffstats
path: root/src/declarative/graphicsitems/qdeclarativetextlayout.cpp
blob: 31819f5bd1aeb02f8f2faf80fe6fb66faadb418b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qdeclarativetextlayout_p.h"
#include <private/qstatictext_p.h>
#include <private/qfontengine_p.h>
#include <private/qtextengine_p.h>
#include <private/qpainter_p.h>
#include <private/qpaintengineex_p.h>

QT_BEGIN_NAMESPACE

class QDeclarativeTextLayoutPrivate
{
public:
    QDeclarativeTextLayoutPrivate() 
    : cached(false) {}

    QPointF position;

    bool cached;
    QVector<QStaticTextItem> items;
    QVector<QFixedPoint> positions;
    QVector<glyph_t> glyphs;
    QVector<QChar> chars;
};

Q_GUI_EXPORT extern int qt_defaultDpiX();
Q_GUI_EXPORT extern int qt_defaultDpiY();

namespace {
class DrawTextItemRecorder: public QPaintEngine
{
    public:
        DrawTextItemRecorder(bool untransformedCoordinates, bool useBackendOptimizations)
            : m_inertText(0), m_dirtyPen(false), m_useBackendOptimizations(useBackendOptimizations),
            m_untransformedCoordinates(untransformedCoordinates)
            {
            }

        virtual void updateState(const QPaintEngineState &newState)
        {
            if (newState.state() & QPaintEngine::DirtyPen)
                m_dirtyPen = true;
        }

        virtual void drawTextItem(const QPointF &position, const QTextItem &textItem)
        {
            int glyphOffset = m_inertText->glyphs.size(); // Store offset into glyph pool
            int positionOffset = m_inertText->glyphs.size(); // Offset into position pool
            int charOffset = m_inertText->chars.size();

            const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);

            bool needFreshCurrentItem = true;
            if (!m_inertText->items.isEmpty()) {
                QStaticTextItem &last = m_inertText->items[m_inertText->items.count() - 1];

                if (last.fontEngine() == ti.fontEngine && last.font == ti.font() &&
                    (!m_dirtyPen || last.color == state->pen().color())) {
                    needFreshCurrentItem = false;

                    last.numChars += ti.num_chars;

                }
            } 

            if (needFreshCurrentItem) {
                QStaticTextItem currentItem;

                currentItem.setFontEngine(ti.fontEngine);
                currentItem.font = ti.font();
                currentItem.charOffset = charOffset;
                currentItem.numChars = ti.num_chars;
                currentItem.numGlyphs = 0;
                currentItem.glyphOffset = glyphOffset;
                currentItem.positionOffset = positionOffset;
                currentItem.useBackendOptimizations = m_useBackendOptimizations;
                if (m_dirtyPen)
                    currentItem.color = state->pen().color();

                m_inertText->items.append(currentItem);
            }

            QStaticTextItem &currentItem = m_inertText->items.last();

            QTransform matrix = m_untransformedCoordinates ? QTransform() : state->transform();
            matrix.translate(position.x(), position.y());

            QVarLengthArray<glyph_t> glyphs;
            QVarLengthArray<QFixedPoint> positions;
            ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);

            int size = glyphs.size();
            Q_ASSERT(size == positions.size());
            currentItem.numGlyphs += size;

            m_inertText->glyphs.resize(m_inertText->glyphs.size() + size);
            m_inertText->positions.resize(m_inertText->glyphs.size());
            m_inertText->chars.resize(m_inertText->chars.size() + ti.num_chars);

            glyph_t *glyphsDestination = m_inertText->glyphs.data() + glyphOffset;
            qMemCopy(glyphsDestination, glyphs.constData(), sizeof(glyph_t) * size);

            QFixedPoint *positionsDestination = m_inertText->positions.data() + positionOffset;
            qMemCopy(positionsDestination, positions.constData(), sizeof(QFixedPoint) * size);

            QChar *charsDestination = m_inertText->chars.data() + charOffset;
            qMemCopy(charsDestination, ti.chars, sizeof(QChar) * ti.num_chars);

        }

        virtual void drawPolygon(const QPointF *, int , PolygonDrawMode )
        {
            /* intentionally empty */
        }

        virtual bool begin(QPaintDevice *)  { return true; }
        virtual bool end() { return true; }
        virtual void drawPixmap(const QRectF &, const QPixmap &, const QRectF &) {}
        virtual Type type() const
        {
            return User;
        }

        void begin(QDeclarativeTextLayoutPrivate *t) {
            m_inertText = t;
            m_dirtyPen = false;
        }

    private:
        QDeclarativeTextLayoutPrivate *m_inertText;

        bool m_dirtyPen;
        bool m_useBackendOptimizations;
        bool m_untransformedCoordinates;
};

class DrawTextItemDevice: public QPaintDevice
{
    public:
        DrawTextItemDevice(bool untransformedCoordinates, bool useBackendOptimizations)
        {
            m_paintEngine = new DrawTextItemRecorder(untransformedCoordinates,
                    useBackendOptimizations);
        }

        ~DrawTextItemDevice()
        {
            delete m_paintEngine;
        }

        void begin(QDeclarativeTextLayoutPrivate *t) {
            m_paintEngine->begin(t);
        }

        int metric(PaintDeviceMetric m) const
        {
            int val;
            switch (m) {
            case PdmWidth:
            case PdmHeight:
            case PdmWidthMM:
            case PdmHeightMM:
                val = 0;
                break;
            case PdmDpiX:
            case PdmPhysicalDpiX:
                val = qt_defaultDpiX();
                break;
            case PdmDpiY:
            case PdmPhysicalDpiY:
                val = qt_defaultDpiY();
                break;
            case PdmNumColors:
                val = 16777216;
                break;
            case PdmDepth:
                val = 24;
                break;
            default:
                val = 0;
                qWarning("DrawTextItemDevice::metric: Invalid metric command");
            }
            return val;
        }

        virtual QPaintEngine *paintEngine() const
        {
            return m_paintEngine;
        }

    private:
        DrawTextItemRecorder *m_paintEngine;
};

struct InertTextPainter {
    InertTextPainter()
    : device(true, true), painter(&device) {}

    DrawTextItemDevice device;
    QPainter painter;
};
}

Q_GLOBAL_STATIC(InertTextPainter, inertTextPainter);

/*!
\class QDeclarativeTextLayout
\brief The QDeclarativeTextLayout class is a version of QStaticText that works with QTextLayouts.
\internal

This class is basically a copy of the QStaticText code, but it is adapted to source its text from
QTextLayout.

It is also considerably faster to create a QDeclarativeTextLayout than a QStaticText because it uses 
a single, shared QPainter instance.  QStaticText by comparison creates a new QPainter per instance.
As a consequence this means that QDeclarativeTextLayout is not re-enterant.  Adding a lock around 
the shared painter solves this, and only introduces a minor performance penalty, but is unnecessary 
for QDeclarativeTextLayout's current use (QDeclarativeText is already tied to the GUI thread).
*/

QDeclarativeTextLayout::QDeclarativeTextLayout()
: d(0)
{
}

QDeclarativeTextLayout::QDeclarativeTextLayout(const QString &text)
: QTextLayout(text), d(0)
{
}

QDeclarativeTextLayout::~QDeclarativeTextLayout()
{
    if (d) delete d;
}

void QDeclarativeTextLayout::beginLayout()
{
    if (d && d->cached) {
        d->cached = false;
        d->items.clear();
        d->positions.clear();
        d->glyphs.clear();
        d->chars.clear();
        d->position = QPointF();
    }
    QTextLayout::beginLayout();
}

void QDeclarativeTextLayout::clearLayout()
{
    if (d && d->cached) {
        d->cached = false;
        d->items.clear();
        d->positions.clear();
        d->glyphs.clear();
        d->chars.clear();
        d->position = QPointF();
    }
    QTextLayout::clearLayout();
}

void QDeclarativeTextLayout::prepare()
{
    if (!d || !d->cached) {

        if (!d)  
            d = new QDeclarativeTextLayoutPrivate;

        InertTextPainter *itp = inertTextPainter();
        itp->device.begin(d);
        QTextLayout::draw(&itp->painter, QPointF(0, 0));

        glyph_t *glyphPool = d->glyphs.data();
        QFixedPoint *positionPool = d->positions.data();
        QChar *charPool = d->chars.data();

        int itemCount = d->items.count();
        for (int ii = 0; ii < itemCount; ++ii) {
            QStaticTextItem &item = d->items[ii];
            item.glyphs = glyphPool + item.glyphOffset;
            item.glyphPositions = positionPool + item.positionOffset;
            item.chars = charPool + item.charOffset;
        }

        d->cached = true;
    }
}

void QDeclarativeTextLayout::draw(QPainter *painter, const QPointF &p)
{
    QPainterPrivate *priv = QPainterPrivate::get(painter);

    bool paintEngineSupportsTransformations = priv->extended &&
                                              (priv->extended->type() == QPaintEngine::OpenGL2 ||
                                               priv->extended->type() == QPaintEngine::OpenVG ||
                                               priv->extended->type() == QPaintEngine::OpenGL);

    if (!paintEngineSupportsTransformations || !priv->state->matrix.isAffine()) {
        QTextLayout::draw(painter, p);
        return;
    }

    prepare();

    int itemCount = d->items.count();

    if (p != d->position) {
        QFixed fx = QFixed::fromReal(p.x());
        QFixed fy = QFixed::fromReal(p.y());
        QFixed oldX = QFixed::fromReal(d->position.x());
        QFixed oldY = QFixed::fromReal(d->position.y());
        for (int item = 0; item < itemCount; ++item) {
            QStaticTextItem &textItem = d->items[item];

            for (int ii = 0; ii < textItem.numGlyphs; ++ii) {
                textItem.glyphPositions[ii].x += fx - oldX;
                textItem.glyphPositions[ii].y += fy - oldY;
            }
            textItem.userDataNeedsUpdate = true;
        }

        d->position = p;
    }

    QPen oldPen = priv->state->pen;
    QColor currentColor = oldPen.color();
    for (int ii = 0; ii < itemCount; ++ii) {
        QStaticTextItem &item = d->items[ii];
        if (item.color.isValid() && currentColor != item.color) {
            painter->setPen(item.color);
            currentColor = item.color;
        }
        priv->extended->drawStaticTextItem(&item);
    }
    if (currentColor != oldPen.color())
        painter->setPen(oldPen);
}

QT_END_NAMESPACE