aboutsummaryrefslogtreecommitdiffstats
path: root/src/imports/controls/imagine/qquickninepatchimage.cpp
blob: 7d5e4f719b43aa04c098f2ff0162266ac6210fc8 (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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
/****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Quick Controls 2 module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information to
** ensure the GNU General Public License version 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qquickninepatchimage_p.h"

#include <QtCore/qfileinfo.h>
#include <QtQuick/qsggeometry.h>
#include <QtQuick/qsgtexturematerial.h>
#include <QtQuick/private/qsgnode_p.h>
#include <QtQuick/private/qquickimage_p_p.h>

QT_BEGIN_NAMESPACE

struct QQuickNinePatchData
{
    QVector<qreal> coordsForSize(qreal count) const;

    inline bool isNull() const { return data.isEmpty(); }
    inline int count() const { return data.size(); }
    inline qreal at(int index) const { return data.at(index); }
    inline qreal size() const { return data.last(); }

    void fill(const QVector<qreal> &coords, qreal count);
    void clear();

private:
    bool inverted = false;
    QVector<qreal> data;
};

QVector<qreal> QQuickNinePatchData::coordsForSize(qreal size) const
{
    // n = number of stretchable sections
    // We have to compensate when adding 0 and/or
    // the source image width to the divs vector.
    const int l = data.size();
    const int n = (inverted ? l - 1 : l) / 2;
    const qreal stretch = (size - data.last()) / n;

    QVector<qreal> coords;
    coords.reserve(l);
    coords.append(0);

    bool stretched = !inverted;
    for (int i = 1; i < l; ++i) {
        qreal advance = data[i] - data[i - 1];
        if (stretched)
            advance += stretch;
        coords.append(coords.last() + advance);

        stretched = !stretched;
    }

    return coords;
}

void QQuickNinePatchData::fill(const QVector<qreal> &coords, qreal size)
{
    data.clear();
    inverted = coords.isEmpty() || coords.first() != 0;

    // Reserve an extra item in case we need to add the image width/height
    if (inverted) {
        data.reserve(coords.size() + 2);
        data.append(0);
    } else {
        data.reserve(coords.size() + 1);
    }

    data += coords;
    data.append(size);
}

void QQuickNinePatchData::clear()
{
    data.clear();
}

class QQuickNinePatchNode : public QSGGeometryNode
{
public:
    QQuickNinePatchNode();
    ~QQuickNinePatchNode();

    void initialize(QSGTexture *texture, const QSizeF &targetSize, const QSize &sourceSize,
                    const QQuickNinePatchData &xDivs, const QQuickNinePatchData &yDivs, qreal dpr);

private:
    QSGGeometry m_geometry;
    QSGTextureMaterial m_material;
};

QQuickNinePatchNode::QQuickNinePatchNode()
    : m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4)
{
    m_geometry.setDrawingMode(QSGGeometry::DrawTriangles);
    setGeometry(&m_geometry);
    setMaterial(&m_material);
}

QQuickNinePatchNode::~QQuickNinePatchNode()
{
    delete m_material.texture();
}

void QQuickNinePatchNode::initialize(QSGTexture *texture, const QSizeF &targetSize, const QSize &sourceSize,
                                     const QQuickNinePatchData &xDivs, const QQuickNinePatchData &yDivs, qreal dpr)
{
    delete m_material.texture();
    m_material.setTexture(texture);

    const int xlen = xDivs.count();
    const int ylen = yDivs.count();

    if (xlen > 0 && ylen > 0) {
        const int quads = (xlen - 1) * (ylen - 1);
        static const int verticesPerQuad = 6;
        m_geometry.allocate(xlen * ylen, verticesPerQuad * quads);

        QSGGeometry::TexturedPoint2D *vertices = m_geometry.vertexDataAsTexturedPoint2D();
        QVector<qreal> xCoords = xDivs.coordsForSize(targetSize.width());
        QVector<qreal> yCoords = yDivs.coordsForSize(targetSize.height());

        for (int y = 0; y < ylen; ++y) {
            for (int x = 0; x < xlen; ++x, ++vertices)
                vertices->set(xCoords[x] / dpr, yCoords[y] / dpr,
                              xDivs.at(x) / sourceSize.width(),
                              yDivs.at(y) / sourceSize.height());
        }

        quint16 *indices = m_geometry.indexDataAsUShort();
        int n = quads;
        for (int q = 0; n--; ++q) {
            if ((q + 1) % xlen == 0) // next row
                ++q;
            // Bottom-left half quad triangle
            indices[0] = q;
            indices[1] = q + xlen;
            indices[2] = q + xlen + 1;

            // Top-right half quad triangle
            indices[3] = q;
            indices[4] = q + xlen + 1;
            indices[5] = q + 1;

            indices += verticesPerQuad;
        }
    }

    markDirty(QSGNode::DirtyGeometry | QSGNode::DirtyMaterial);
}

class QQuickNinePatchImagePrivate : public QQuickImagePrivate
{
    Q_DECLARE_PUBLIC(QQuickNinePatchImage)

public:
    void updatePatches();
    void updatePaddings(const QSizeF &size, const QVector<qreal> &horizontal, const QVector<qreal> &vertical);
    void updateInsets(const QVector<qreal> &horizontal, const QVector<qreal> &vertical);

    bool resetNode = false;
    qreal topPadding = 0;
    qreal leftPadding = 0;
    qreal rightPadding = 0;
    qreal bottomPadding = 0;
    qreal topInset = 0;
    qreal leftInset = 0;
    qreal rightInset = 0;
    qreal bottomInset = 0;

    QImage ninePatch;
    QQuickNinePatchData xDivs;
    QQuickNinePatchData yDivs;
};

static QVector<qreal> readCoords(const QRgb *data, int from, int count, int offset, QRgb color)
{
    int p1 = -1;
    QVector<qreal> coords;
    for (int i = 0; i < count; ++i) {
        int p2 = from + i * offset;
        if (data[p2] == color) {
            // colored pixel
            if (p1 == -1)
                p1 = i;
        } else {
            // empty pixel
            if (p1 != -1) {
                coords << p1 << i;
                p1 = -1;
            }
        }
    }
    return coords;
}

void QQuickNinePatchImagePrivate::updatePatches()
{
    if (ninePatch.isNull())
        return;

    int w = ninePatch.width();
    int h = ninePatch.height();
    const QRgb *data = reinterpret_cast<const QRgb *>(ninePatch.constBits());

    const QRgb black = qRgb(0,0,0);
    const QRgb red = qRgb(255,0,0);

    xDivs.fill(readCoords(data, 1, w - 1, 1, black), w - 2); // top left -> top right
    yDivs.fill(readCoords(data, w, h - 1, w, black), h - 2); // top left -> bottom left

    QVector<qreal> hInsets = readCoords(data, (h - 1) * w + 1, w - 1, 1, red); // bottom left -> bottom right
    QVector<qreal> vInsets = readCoords(data, 2 * w - 1, h - 1, w, red); // top right -> bottom right
    updateInsets(hInsets, vInsets);

    const QSizeF sz(w - leftInset - rightInset, h - topInset - bottomInset);
    QVector<qreal> hPaddings = readCoords(data, (h - 1) * w + leftInset + 1, sz.width() - 2, 1, black); // bottom left -> bottom right
    QVector<qreal> vPaddings = readCoords(data, (2 + topInset) * w - 1, sz.height() - 2, w, black); // top right -> bottom right
    updatePaddings(sz, hPaddings, vPaddings);
}

void QQuickNinePatchImagePrivate::updatePaddings(const QSizeF &size, const QVector<qreal> &horizontal, const QVector<qreal> &vertical)
{
    Q_Q(QQuickNinePatchImage);
    qreal oldTopPadding = topPadding;
    qreal oldLeftPadding = leftPadding;
    qreal oldRightPadding = rightPadding;
    qreal oldBottomPadding = bottomPadding;

    if (horizontal.count() >= 2) {
        leftPadding = horizontal.first();
        rightPadding = size.width() - horizontal.last() - 2;
    } else {
        leftPadding = 0;
        rightPadding = 0;
    }

    if (vertical.count() >= 2) {
        topPadding = vertical.first();
        bottomPadding = size.height() - vertical.last() - 2;
    } else {
        topPadding = 0;
        bottomPadding = 0;
    }

    if (!qFuzzyCompare(oldTopPadding, topPadding))
        emit q->topPaddingChanged();
    if (!qFuzzyCompare(oldBottomPadding, bottomPadding))
        emit q->bottomPaddingChanged();
    if (!qFuzzyCompare(oldLeftPadding, leftPadding))
        emit q->leftPaddingChanged();
    if (!qFuzzyCompare(oldRightPadding, rightPadding))
        emit q->rightPaddingChanged();
}

void QQuickNinePatchImagePrivate::updateInsets(const QVector<qreal> &horizontal, const QVector<qreal> &vertical)
{
    Q_Q(QQuickNinePatchImage);
    qreal oldTopInset = topInset;
    qreal oldLeftInset = leftInset;
    qreal oldRightInset = rightInset;
    qreal oldBottomInset = bottomInset;

    if (horizontal.count() >= 2 && horizontal.first() == 0)
        leftInset = horizontal.at(1);
    else
        leftInset = 0;

    if (horizontal.count() == 2 && horizontal.first() > 0)
        rightInset = horizontal.last() - horizontal.first();
    else if (horizontal.count() == 4)
        rightInset = horizontal.last() - horizontal.at(2);
    else
        rightInset = 0;

    if (vertical.count() >= 2 && vertical.first() == 0)
        topInset = vertical.at(1);
    else
        topInset = 0;

    if (vertical.count() == 2 && vertical.first() > 0)
        bottomInset = vertical.last() - vertical.first();
    else if (vertical.count() == 4)
        bottomInset = vertical.last() - vertical.at(2);
    else
        bottomInset = 0;

    if (!qFuzzyCompare(oldTopInset, topInset))
        emit q->topInsetChanged();
    if (!qFuzzyCompare(oldBottomInset, bottomInset))
        emit q->bottomInsetChanged();
    if (!qFuzzyCompare(oldLeftInset, leftInset))
        emit q->leftInsetChanged();
    if (!qFuzzyCompare(oldRightInset, rightInset))
        emit q->rightInsetChanged();
}

QQuickNinePatchImage::QQuickNinePatchImage(QQuickItem *parent)
    : QQuickImage(*(new QQuickNinePatchImagePrivate), parent)
{
}

qreal QQuickNinePatchImage::topPadding() const
{
    Q_D(const QQuickNinePatchImage);
    return d->topPadding / d->devicePixelRatio;
}

qreal QQuickNinePatchImage::leftPadding() const
{
    Q_D(const QQuickNinePatchImage);
    return d->leftPadding / d->devicePixelRatio;
}

qreal QQuickNinePatchImage::rightPadding() const
{
    Q_D(const QQuickNinePatchImage);
    return d->rightPadding / d->devicePixelRatio;
}

qreal QQuickNinePatchImage::bottomPadding() const
{
    Q_D(const QQuickNinePatchImage);
    return d->bottomPadding / d->devicePixelRatio;
}

qreal QQuickNinePatchImage::topInset() const
{
    Q_D(const QQuickNinePatchImage);
    return d->topInset / d->devicePixelRatio;
}

qreal QQuickNinePatchImage::leftInset() const
{
    Q_D(const QQuickNinePatchImage);
    return d->leftInset / d->devicePixelRatio;
}

qreal QQuickNinePatchImage::rightInset() const
{
    Q_D(const QQuickNinePatchImage);
    return d->rightInset / d->devicePixelRatio;
}

qreal QQuickNinePatchImage::bottomInset() const
{
    Q_D(const QQuickNinePatchImage);
    return d->bottomInset / d->devicePixelRatio;
}

void QQuickNinePatchImage::pixmapChange()
{
    Q_D(QQuickNinePatchImage);
    if (QFileInfo(d->url.fileName()).completeSuffix().toLower() == QLatin1String("9.png")) {
        d->resetNode = d->ninePatch.isNull();
        d->ninePatch = d->pix.image();
        if (d->ninePatch.depth() != 32)
            d->ninePatch = d->ninePatch.convertToFormat(QImage::Format_ARGB32);

        int w = d->ninePatch.width();
        int h = d->ninePatch.height();
        d->pix.setImage(QImage(d->ninePatch.constBits() + 4 * (w + 1), w - 2, h - 2, d->ninePatch.bytesPerLine(), d->ninePatch.format()));

        d->updatePatches();
    } else {
        /*
            Only change resetNode when it's false; i.e. when no reset is pending.
            updatePaintNode() will take care of setting it to false if it's true.

            Consider the following changes in source:

                normal.png => press.9.png => normal.png => focus.png

            If the last two events happen quickly, pixmapChange() can be called
            twice with no call to updatePaintNode() inbetween. On the first call,
            resetNode will be true (because ninePatch is not null since it is still
            in the process of going from a 9-patch image to a regular image),
            and on the second call, resetNode would be false if we didn't have this check.
            This results in the oldNode never being deleted, and QQuickImage
            tries to static_cast a QQuickNinePatchImage to a QSGInternalImageNode.
        */
        if (!d->resetNode)
            d->resetNode = !d->ninePatch.isNull();
        d->ninePatch = QImage();
    }
    QQuickImage::pixmapChange();
}

QSGNode *QQuickNinePatchImage::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *data)
{
    Q_D(QQuickNinePatchImage);
    Q_UNUSED(data);

    if (d->resetNode) {
        delete oldNode;
        oldNode = nullptr;
        d->resetNode = false;
    }

    QSizeF sz = size();
    QImage image = d->pix.image();
    if (!sz.isValid() || image.isNull()) {
        delete oldNode;
        return nullptr;
    }

    if (d->ninePatch.isNull())
        return QQuickImage::updatePaintNode(oldNode, data);

    QQuickNinePatchNode *patchNode = static_cast<QQuickNinePatchNode *>(oldNode);
    if (!patchNode)
        patchNode = new QQuickNinePatchNode;

#ifdef QSG_RUNTIME_DESCRIPTION
    qsgnode_set_description(patchNode, QString::fromLatin1("QQuickNinePatchImage: '%1'").arg(d->url.toString()));
#endif

    QSGTexture *texture = window()->createTextureFromImage(image);
    patchNode->initialize(texture, sz * d->devicePixelRatio, image.size(), d->xDivs, d->yDivs, d->devicePixelRatio);
    return patchNode;
}

QT_END_NAMESPACE