summaryrefslogtreecommitdiffstats
path: root/src/declarative/fx/qfximage.cpp
blob: 738809c7fd80b6003a8d92f3b080931baeca685a (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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (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 either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** 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.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 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 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qfximage.h"
#include "qfximage_p.h"
#include <private/qfxperf_p.h>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QFile>
#include <QtDeclarative/qmlengine.h>

#include <QKeyEvent>
#include <QPainter>

QT_BEGIN_NAMESPACE


QML_DEFINE_TYPE(Qt,4.6,Image,QFxImage)

/*!
    \qmlclass Image QFxImage
    \brief The Image element allows you to add bitmaps to a scene.
    \inherits Item

    The Image element supports untransformed, stretched, grid-scaled and tiled images.
    For an explanation of grid-scaling see the scaleGrid property description
    or the QFxScaleGrid class description.

    Examples:
    \table
    \row
    \o \image declarative-qtlogo1.png
    \o Untransformed
    \qml
    Image { source: "pics/qtlogo.png" }
    \endqml
    \row
    \o \image declarative-qtlogo2.png
    \o Stretched
    \qml
    Image { width: 160; height: 160; source: "pics/qtlogo.png" }
    \endqml
    \row
    \o \image declarative-qtlogo4.png
    \o Grid-scaled
    \qml
    Image { scaleGrid.left: 20; scaleGrid.right: 10
            scaleGrid.top: 14; scaleGrid.bottom: 14
            width: 160; height: 160; source: "pics/qtlogo.png" }
    \endqml
    \row
    \o \image declarative-qtlogo3.png
    \o Tiled
    \qml
    Image { tile: true; width: 160; height: 160; source: "pics/qtlogo.png" }
    \endqml
    \endtable
 */

/*!
    \internal
    \class QFxImage Image
    \brief The QFxImage class provides an image item that you can add to a QFxView.

    \ingroup group_coreitems

    Example:
    \qml
    Image { source: "pics/star.png" }
    \endqml

    A QFxImage object can be instantiated in Qml using the tag \l Image.
*/

QFxImage::QFxImage(QFxItem *parent)
  : QFxItem(*(new QFxImagePrivate), parent)
{
    setOptions(SimpleItem | HasContents, true);
}

QFxImage::QFxImage(QFxImagePrivate &dd, QFxItem *parent)
  : QFxItem(dd, parent)
{
    setOptions(SimpleItem | HasContents, true);
}

QFxImage::~QFxImage()
{
    Q_D(QFxImage);
    if (d->sciReply)
        d->sciReply->deleteLater();
    if (!d->url.isEmpty())
        QFxPixmap::cancelGet(d->url, this);
    if (!d->sciurl.isEmpty())
        QFxPixmap::cancelGet(d->sciurl, this);
}

/*!
    \property QFxImage::pixmap
    \brief the image displayed in this item.

    This property contains the image currently being displayed by this item,
    which may be an empty pixmap if nothing is currently displayed. If this
    property is set, the source property will be unset. This property is intended
    to be used only in C++, not in QML.
*/
QPixmap QFxImage::pixmap() const
{
    Q_D(const QFxImage);
    return d->pix;
}

void QFxImage::setPixmap(const QPixmap &pix)
{
    Q_D(QFxImage);
    d->url = QUrl();
    d->pix = pix;
    d->opaque=false;

    setImplicitWidth(d->pix.width());
    setImplicitHeight(d->pix.height());

    update();
}

/*!
    \qmlproperty int Image::scaleGrid.left
    \qmlproperty int Image::scaleGrid.right
    \qmlproperty int Image::scaleGrid.top
    \qmlproperty int Image::scaleGrid.bottom

    \target ImagexmlpropertiesscaleGrid

    A scale grid uses 4 grid lines (2 horizontal and 2 vertical) to break an image into 9 sections, as shown below:

    \image declarative-scalegrid.png

    When the image is scaled:
    \list
    \i the corners (sections 1, 3, 7, and 9) are not scaled at all
    \i the middle (section 5) is scaled both horizontally and vertically
    \i sections 2 and 8 are scaled horizontally
    \i sections 4 and 6 are scaled vertically
    \endlist

    Each scale grid property (left, right, top, and bottom) specifies an offset from the respective side. For example, \c scaleGrid.bottom="10" sets the bottom scale grid line 10 pixels up from the bottom of the image.

    A scale grid can also be specified using a
    \l {Image::source}{.sci file}.
*/
QFxScaleGrid *QFxImage::scaleGrid()
{
    Q_D(QFxImage);
    return d->getScaleGrid();
}

/*!
    \qmlproperty bool Image::tile

    Set this property to enable image tiling.  Normally the Image element scales the
    bitmap file to its size.  If tiling is enabled, the bitmap is repeated as a set
    of unscaled tiles, clipped to the size of the Image.

    \qml
    Item {
        Image { source: "tile.png" }
        Image { x: 80; width: 100; height: 100; source: "tile.png" }
        Image { x: 190; width: 100; height: 100; tile: true; source: "tile.png" }
    }
    \endqml
    \image declarative-image_tile.png

    If both tiling and the scaleGrid are set, tiling takes precedence.
*/
bool QFxImage::isTiled() const
{
    Q_D(const QFxImage);
    return d->tiled;
}

void QFxImage::setTiled(bool tile)
{
    Q_D(QFxImage);
    d->tiled = tile;
}

void QFxImage::componentComplete()
{
    QFxItem::componentComplete();
}

/*!
    \property QFxImage::scaleGrid
    \brief the 3x3 grid used to scale an image, excluding the corners.
*/

/*!
    \qmlproperty bool Image::smooth

    Set this property if you want the image to be smoothly filtered when scaled or
    transformed.  Smooth filtering gives better visual quality, but is slower.  If
    the Image is displayed at its natural size, this property has no visual or
    performance effect.

    \note Generally scaling artifacts are only visible if the image is stationary on
    the screen.  A common pattern when animating an image is to disable smooth
    filtering at the beginning of the animation and reenable it at the conclusion.
 */

/*!
    \property QFxImage::smooth
    \brief whether the image is smoothly transformed.

    This property is provided purely for the purpose of optimization. Turning
    smooth transforms off is faster, but looks worse; turning smooth
    transformations on is slower, but looks better.

    By default smooth transformations are off.
*/
bool QFxImage::smoothTransform() const
{
    Q_D(const QFxImage);
    return d->smooth;
}

void QFxImage::setSmoothTransform(bool s)
{
    Q_D(QFxImage);
    if (d->smooth == s)
        return;
    d->smooth = s;
    update();
}

void QFxImage::paintContents(QPainter &p)
{
    Q_D(QFxImage);
    if (d->pix.isNull())
        return;

    bool oldAA = p.testRenderHint(QPainter::Antialiasing);
    bool oldSmooth = p.testRenderHint(QPainter::SmoothPixmapTransform);
    if (d->smooth)
        p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform, d->smooth);

    QPixmap pix = d->pix;

    if (d->tiled) {
        p.save();
        p.setClipRect(0, 0, width(), height(), Qt::IntersectClip);
        QRect me = QRect(0, 0, width(), height());

        int pw = pix.width();
        int ph = pix.height();
        int yy = 0;

        while(yy < height()) {
            int xx = 0;
            while(xx < width()) {
                p.drawPixmap(xx, yy, pix);
                xx += pw;
            }
            yy += ph;
        }

        p.restore();
    } else if (!d->scaleGrid || d->scaleGrid->isNull()) {
        if (width() != pix.width() || height() != pix.height()) {
            qreal widthScale = width() / qreal(pix.width());
            qreal heightScale = height() / qreal(pix.height());

            QTransform scale;

            if (d->preserveAspect) {
                if (widthScale < heightScale) {
                    heightScale = widthScale;
                    scale.translate(0, (height() - heightScale * pix.height()) / 2);
                } else if(heightScale < widthScale) {
                    widthScale = heightScale;
                    scale.translate((width() - widthScale * pix.width()) / 2, 0);
                }
            }

            scale.scale(widthScale, heightScale);
            QTransform old = p.transform();
            p.setWorldTransform(scale * old);
            p.drawPixmap(0, 0, pix);
            p.setWorldTransform(old);
        } else {
            p.drawPixmap(0, 0, pix);
        }
    } else {
        int sgl = d->scaleGrid->left();
        int sgr = d->scaleGrid->right();
        int sgt = d->scaleGrid->top();
        int sgb = d->scaleGrid->bottom();

        int w = width();
        int h = height();
        if (sgt + sgb > h)
            sgt = sgb = h/2;
        if (sgl + sgr > w)
            sgl = sgr = w/2;

        const int xSide = sgl + sgr;
        const int ySide = sgt + sgb;

        // Upper left
        if (sgt && sgl)
            p.drawPixmap(QRect(0, 0, sgl, sgt), pix, QRect(0, 0, sgl, sgt));
        // Upper middle
        if (pix.width() - xSide && sgt)
            p.drawPixmap(QRect(sgl, 0, w - xSide, sgt), pix,
                        QRect(sgl, 0, pix.width() - xSide, sgt));
        // Upper right
        if (sgt && pix.width() - sgr)
            p.drawPixmap(QPoint(w-sgr, 0), pix,
                        QRect(pix.width()-sgr, 0, sgr, sgt));
        // Middle left
        if (sgl && pix.height() - ySide)
            p.drawPixmap(QRect(0, sgt, sgl, h - ySide), pix,
                        QRect(0, sgt, sgl, pix.height() - ySide));

        // Middle
        if (pix.width() - xSide && pix.height() - ySide)
            p.drawPixmap(QRect(sgl, sgt, w - xSide, h - ySide),
                        pix,
                        QRect(sgl, sgt, pix.width() - xSide, pix.height() - ySide));
        // Middle right
        if (sgr && pix.height() - ySide)
            p.drawPixmap(QRect(w-sgr, sgt, sgr, h - ySide), pix,
                        QRect(pix.width()-sgr, sgt, sgr, pix.height() - ySide));
        // Lower left
        if (sgl && sgr)
            p.drawPixmap(QPoint(0, h - sgb), pix,
                        QRect(0, pix.height() - sgb, sgl, sgb));
        // Lower Middle
        if (pix.width() - xSide && sgb)
            p.drawPixmap(QRect(sgl, h - sgb, w - xSide, sgb), pix,
                        QRect(sgl, pix.height() - sgb, pix.width() - xSide, sgb));
        // Lower Right
        if (sgr && sgb)
            p.drawPixmap(QPoint(w-sgr, h - sgb), pix,
                        QRect(pix.width()-sgr, pix.height() - sgb, sgr, sgb));
    }

    if (d->smooth) {
        p.setRenderHint(QPainter::Antialiasing, oldAA);
        p.setRenderHint(QPainter::SmoothPixmapTransform, oldSmooth);
    }
}

/*!
    \qmlproperty enum Image::status

    This property holds the status of image loading.  It can be one of:
    \list
    \o Idle - no image has been set, or the image has been loaded
    \o Loading - the images is currently being loaded
    \o Error - an error occurred while loading the image
    \endlist

    \sa progress
*/

QFxImage::Status QFxImage::status() const
{
    Q_D(const QFxImage);
    return d->status;
}

/*!
    \qmlproperty real Image::progress

    This property holds the progress of image loading, from 0.0 (nothing loaded)
    to 1.0 (finished).

    \sa status
*/

qreal QFxImage::progress() const
{
    Q_D(const QFxImage);
    return d->progress;
}

/*!
    \qmlproperty string Image::source

    Image can handle any image format supported by Qt, loaded from any URL scheme supported by Qt.

    It can also handle .sci files, which are a Qml-specific format. A .sci file uses a simple text-based format that specifies
    \list
    \i the grid lines describing a \l {Image::scaleGrid.left}{scale grid}.
    \i an image file.
    \endlist

    The following .sci file sets grid line offsets of 10 on each side for the image \c picture.png:
    \code
    gridLeft: 10
    gridTop: 10
    gridBottom: 10
    gridRight: 10
    imageFile: picture.png
    \endcode

    The URL may be absolute, or relative to the URL of the component.
*/

/*!
    \property QFxImage::source
    \brief the url of the image to be displayed in this item.

    The content specified can be of any image type loadable by QImage. Alternatively,
    you can specify an sci format file, which specifies both an image and it's scale grid.
*/
QUrl QFxImage::source() const
{
    Q_D(const QFxImage);
    return d->url;
}

/*!
    \qmlproperty bool Image::preserveAspect

    Whether the image's aspect ratio should be preserved when resizing. By default this
    is false.
*/
bool QFxImage::preserveAspect() const
{
    Q_D(const QFxImage);
    return d->preserveAspect;
}

void QFxImage::setPreserveAspect(bool p)
{
    Q_D(QFxImage);

    if (p == d->preserveAspect)
        return;
    d->preserveAspect = p;
    update();
}

void QFxImage::setSource(const QUrl &url)
{
#ifdef Q_ENABLE_PERFORMANCE_LOG
    QFxPerfTimer<QFxPerf::PixmapLoad> perf;
#endif
    Q_D(QFxImage);
    if (url == d->url)
        return;

    if (d->sciReply) {
        d->sciReply->deleteLater();
        d->sciReply = 0;
    }

    if (!d->url.isEmpty())
        QFxPixmap::cancelGet(d->url, this);
    if (!d->sciurl.isEmpty())
        QFxPixmap::cancelGet(d->sciurl, this);

    d->url = url;
    d->sciurl = QUrl();
    if (d->progress != 0.0) {
        d->progress = 0.0;
        emit progressChanged(d->progress);
    }

    if (url.isEmpty()) {
        setPixmap(QPixmap());
        d->status = Idle;
        d->progress = 1.0;
        setImplicitWidth(0);
        setImplicitHeight(0);
        emit statusChanged(d->status);
        emit sourceChanged(d->url);
        emit progressChanged(1.0);
        update();
    } else {
        d->status = Loading;
        if (d->url.path().endsWith(QLatin1String(".sci"))) {
#ifndef QT_NO_LOCALFILE_OPTIMIZED_QML
            if (d->url.scheme() == QLatin1String("file")) {
                QFile file(d->url.toLocalFile());
                file.open(QIODevice::ReadOnly);
                setGridScaledImage(QFxGridScaledImage(&file));
            } else
#endif
            {
                QNetworkRequest req(d->url);
                req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);
                d->sciReply = qmlEngine(this)->networkAccessManager()->get(req);
                QObject::connect(d->sciReply, SIGNAL(finished()),
                                 this, SLOT(sciRequestFinished()));
            }
        } else {
            d->reply = QFxPixmap::get(qmlEngine(this), d->url, this, SLOT(requestFinished()));
            if (d->reply) {
                connect(d->reply, SIGNAL(downloadProgress(qint64,qint64)),
                        this, SLOT(requestProgress(qint64,qint64)));
            } else {
                d->progress = 1.0;
                emit progressChanged(d->progress);
            }
        }
    }

    emit statusChanged(d->status);
}

void QFxImage::requestFinished()
{
    Q_D(QFxImage);
    if (d->url.path().endsWith(QLatin1String(".sci"))) {
        d->pix = QFxPixmap(d->sciurl);
    } else {
        if (d->reply) {
            disconnect(d->reply, SIGNAL(downloadProgress(qint64,qint64)),
                       this, SLOT(requestProgress(qint64,qint64)));
            if (d->reply->error() != QNetworkReply::NoError)
                d->status = Error;
        }
        d->pix = QFxPixmap(d->url);
        setOptions(QFxImage::SimpleItem, true);
    }
    setImplicitWidth(d->pix.width());
    setImplicitHeight(d->pix.height());

    if (d->status == Loading)
        d->status = Idle;
    d->progress = 1.0;
    emit statusChanged(d->status);
    emit sourceChanged(d->url);
    emit progressChanged(1.0);
    update();
}

void QFxImage::sciRequestFinished()
{
    Q_D(QFxImage);
    if (d->sciReply->error() != QNetworkReply::NoError) {
        d->status = Error;
        d->sciReply->deleteLater();
        d->sciReply = 0;
        emit statusChanged(d->status);
    } else {
        QFxGridScaledImage sci(d->sciReply);
        d->sciReply->deleteLater();
        d->sciReply = 0;
        setGridScaledImage(sci);
    }
}

void QFxImage::requestProgress(qint64 received, qint64 total)
{
    Q_D(QFxImage);
    if (d->status == Loading && total > 0) {
        d->progress = qreal(received)/total;
        emit progressChanged(d->progress);
    }
}

void QFxImage::setGridScaledImage(const QFxGridScaledImage& sci)
{
    Q_D(QFxImage);
    if (!sci.isValid()) {
        d->status = Error;
        emit statusChanged(d->status);
    } else {
        QFxScaleGrid *sg = scaleGrid();
        sg->setTop(sci.gridTop());
        sg->setBottom(sci.gridBottom());
        sg->setLeft(sci.gridLeft());
        sg->setRight(sci.gridRight());
        setOptions(QFxImage::SimpleItem, false);

        d->sciurl = d->url.resolved(QUrl(sci.pixmapUrl()));
        d->reply = QFxPixmap::get(qmlEngine(this), d->sciurl, this, SLOT(requestFinished()));
        if (d->reply) {
            connect(d->reply, SIGNAL(downloadProgress(qint64,qint64)),
                    this, SLOT(requestProgress(qint64,qint64)));
        } else {
            d->progress = 1.0;
            emit progressChanged(d->progress);
        }
    }
}


QT_END_NAMESPACE