Doc: Moving Qt Quick docs for new doc structure
[profile/ivi/qtdeclarative.git] / src / quick / items / qquickborderimage.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the QtQml module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
16 **
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
20 **
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
28 **
29 ** Other Usage
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qquickborderimage_p.h"
43 #include "qquickborderimage_p_p.h"
44 #include "qquickninepatchnode_p.h"
45
46 #include <QtQml/qqmlinfo.h>
47 #include <QtQml/qqmlfile.h>
48 #include <QtQml/qqmlengine.h>
49 #include <QtNetwork/qnetworkreply.h>
50 #include <QtCore/qfile.h>
51
52 #include <private/qqmlglobal_p.h>
53
54 QT_BEGIN_NAMESPACE
55
56
57 /*!
58     \qmlclass BorderImage QQuickBorderImage
59     \inqmlmodule QtQuick 2
60     \brief The BorderImage element provides an image that can be used as a border.
61     \inherits Item
62     \ingroup qml-basic-visual-elements
63
64     The BorderImage element is used to create borders out of images by scaling or tiling
65     parts of each image.
66
67     A BorderImage element breaks a source image, specified using the \l url property,
68     into 9 regions, as shown below:
69
70     \image declarative-scalegrid.png
71
72     When the image is scaled, regions of the source image are scaled or tiled to
73     create the displayed border image in the following way:
74
75     \list
76     \li The corners (regions 1, 3, 7, and 9) are not scaled at all.
77     \li Regions 2 and 8 are scaled according to
78        \l{BorderImage::horizontalTileMode}{horizontalTileMode}.
79     \li Regions 4 and 6 are scaled according to
80        \l{BorderImage::verticalTileMode}{verticalTileMode}.
81     \li The middle (region 5) is scaled according to both
82        \l{BorderImage::horizontalTileMode}{horizontalTileMode} and
83        \l{BorderImage::verticalTileMode}{verticalTileMode}.
84     \endlist
85
86     The regions of the image are defined using the \l border property group, which
87     describes the distance from each edge of the source image to use as a border.
88
89     \section1 Example Usage
90
91     The following examples show the effects of the different modes on an image.
92     Guide lines are overlaid onto the image to show the different regions of the
93     image as described above.
94
95     \beginfloatleft
96     \image qml-borderimage-normal-image.png
97     \endfloat
98
99     An unscaled image is displayed using an Image element. The \l border property is
100     used to determine the parts of the image that will lie inside the unscaled corner
101     areas and the parts that will be stretched horizontally and vertically.
102
103     \snippet doc/snippets/qml/borderimage/normal-image.qml normal image
104
105     \clearfloat
106     \beginfloatleft
107     \image qml-borderimage-scaled.png
108     \endfloat
109
110     A BorderImage element is used to display the image, and it is given a size that is
111     larger than the original image. Since the \l horizontalTileMode property is set to
112     \l{BorderImage::horizontalTileMode}{BorderImage.Stretch}, the parts of image in
113     regions 2 and 8 are stretched horizontally. Since the \l verticalTileMode property
114     is set to \l{BorderImage::verticalTileMode}{BorderImage.Stretch}, the parts of image
115     in regions 4 and 6 are stretched vertically.
116
117     \snippet doc/snippets/qml/borderimage/borderimage-scaled.qml scaled border image
118
119     \clearfloat
120     \beginfloatleft
121     \image qml-borderimage-tiled.png
122     \endfloat
123
124     Again, a large BorderImage element is used to display the image. With the
125     \l horizontalTileMode property set to \l{BorderImage::horizontalTileMode}{BorderImage.Repeat},
126     the parts of image in regions 2 and 8 are tiled so that they fill the space at the
127     top and bottom of the element. Similarly, the \l verticalTileMode property is set to
128     \l{BorderImage::verticalTileMode}{BorderImage.Repeat}, the parts of image in regions
129     4 and 6 are tiled so that they fill the space at the left and right of the element.
130
131     \snippet doc/snippets/qml/borderimage/borderimage-tiled.qml tiled border image
132
133     \clearfloat
134     In some situations, the width of regions 2 and 8 may not be an exact multiple of the width
135     of the corresponding regions in the source image. Similarly, the height of regions 4 and 6
136     may not be an exact multiple of the height of the corresponding regions. It can be useful
137     to use \l{BorderImage::horizontalTileMode}{BorderImage.Round} instead of
138     \l{BorderImage::horizontalTileMode}{BorderImage.Repeat} in cases like these.
139
140     The \l{declarative/imageelements/borderimage}{BorderImage example} shows how a BorderImage
141     can be used to simulate a shadow effect on a rectangular item.
142
143     \section1 Quality and Performance
144
145     By default, any scaled regions of the image are rendered without smoothing to improve
146     rendering speed. Setting the \l smooth property improves rendering quality of scaled
147     regions, but may slow down rendering.
148
149     The source image may not be loaded instantaneously, depending on its original location.
150     Loading progress can be monitored with the \l progress property.
151
152     \sa Image, AnimatedImage
153  */
154
155 /*!
156     \qmlproperty bool QtQuick2::BorderImage::asynchronous
157
158     Specifies that images on the local filesystem should be loaded
159     asynchronously in a separate thread.  The default value is
160     false, causing the user interface thread to block while the
161     image is loaded.  Setting \a asynchronous to true is useful where
162     maintaining a responsive user interface is more desirable
163     than having images immediately visible.
164
165     Note that this property is only valid for images read from the
166     local filesystem.  Images loaded via a network resource (e.g. HTTP)
167     are always loaded asynchronously.
168 */
169 QQuickBorderImage::QQuickBorderImage(QQuickItem *parent)
170 : QQuickImageBase(*(new QQuickBorderImagePrivate), parent)
171 {
172 }
173
174 QQuickBorderImage::~QQuickBorderImage()
175 {
176     Q_D(QQuickBorderImage);
177     if (d->sciReply)
178         d->sciReply->deleteLater();
179 }
180
181 /*!
182     \qmlproperty enumeration QtQuick2::BorderImage::status
183
184     This property describes the status of image loading.  It can be one of:
185
186     \list
187     \li BorderImage.Null - no image has been set
188     \li BorderImage.Ready - the image has been loaded
189     \li BorderImage.Loading - the image is currently being loaded
190     \li BorderImage.Error - an error occurred while loading the image
191     \endlist
192
193     \sa progress
194 */
195
196 /*!
197     \qmlproperty real QtQuick2::BorderImage::progress
198
199     This property holds the progress of image loading, from 0.0 (nothing loaded)
200     to 1.0 (finished).
201
202     \sa status
203 */
204
205 /*!
206     \qmlproperty bool QtQuick2::BorderImage::smooth
207
208     Set this property if you want the image to be smoothly filtered when scaled or
209     transformed.  Smooth filtering gives better visual quality, but is slower.  If
210     the image is displayed at its natural size, this property has no visual or
211     performance effect.
212
213     By default, this property is set to false.
214
215     \note Generally scaling artifacts are only visible if the image is stationary on
216     the screen.  A common pattern when animating an image is to disable smooth
217     filtering at the beginning of the animation and enable it at the conclusion.
218 */
219
220 /*!
221     \qmlproperty bool QtQuick2::BorderImage::cache
222
223     Specifies whether the image should be cached. The default value is
224     true. Setting \a cache to false is useful when dealing with large images,
225     to make sure that they aren't cached at the expense of small 'ui element' images.
226 */
227
228 /*!
229     \qmlproperty bool QtQuick2::BorderImage::mirror
230
231     This property holds whether the image should be horizontally inverted
232     (effectively displaying a mirrored image).
233
234     The default value is false.
235 */
236
237 /*!
238     \qmlproperty url QtQuick2::BorderImage::source
239
240     This property holds the URL that refers to the source image.
241
242     BorderImage can handle any image format supported by Qt, loaded from any
243     URL scheme supported by Qt.
244
245     This property can also be used to refer to .sci files, which are
246     written in a QML-specific, text-based format that specifies the
247     borders, the image file and the tile rules for a given border image.
248
249     The following .sci file sets the borders to 10 on each side for the
250     image \c picture.png:
251
252     \code
253     border.left: 10
254     border.top: 10
255     border.bottom: 10
256     border.right: 10
257     source: "picture.png"
258     \endcode
259
260     The URL may be absolute, or relative to the URL of the component.
261
262     \sa QQuickImageProvider
263 */
264
265 /*!
266     \qmlproperty QSize QtQuick2::BorderImage::sourceSize
267
268     This property holds the actual width and height of the loaded image.
269
270     In BorderImage, this property is read-only.
271
272     \sa Image::sourceSize
273 */
274 void QQuickBorderImage::setSource(const QUrl &url)
275 {
276     Q_D(QQuickBorderImage);
277     //equality is fairly expensive, so we bypass for simple, common case
278     if ((d->url.isEmpty() == url.isEmpty()) && url == d->url)
279         return;
280
281     if (d->sciReply) {
282         d->sciReply->deleteLater();
283         d->sciReply = 0;
284     }
285
286     d->url = url;
287     d->sciurl = QUrl();
288     emit sourceChanged(d->url);
289
290     if (isComponentComplete())
291         load();
292 }
293
294 void QQuickBorderImage::load()
295 {
296     Q_D(QQuickBorderImage);
297     if (d->progress != 0.0) {
298         d->progress = 0.0;
299         emit progressChanged(d->progress);
300     }
301
302     if (d->url.isEmpty()) {
303         d->pix.clear(this);
304         d->status = Null;
305         setImplicitSize(0, 0);
306         emit statusChanged(d->status);
307         update();
308     } else {
309         d->status = Loading;
310         if (d->url.path().endsWith(QLatin1String("sci"))) {
311             QString lf = QQmlFile::urlToLocalFileOrQrc(d->url);
312             if (!lf.isEmpty()) {
313                 QFile file(lf);
314                 file.open(QIODevice::ReadOnly);
315                 setGridScaledImage(QQuickGridScaledImage(&file));
316             } else {
317                 QNetworkRequest req(d->url);
318                 d->sciReply = qmlEngine(this)->networkAccessManager()->get(req);
319                 FAST_CONNECT(d->sciReply, SIGNAL(finished()), this, SLOT(sciRequestFinished()))
320             }
321         } else {
322
323             QQuickPixmap::Options options;
324             if (d->async)
325                 options |= QQuickPixmap::Asynchronous;
326             if (d->cache)
327                 options |= QQuickPixmap::Cache;
328             d->pix.clear(this);
329             d->pix.load(qmlEngine(this), d->url, options);
330
331             if (d->pix.isLoading()) {
332                 d->pix.connectFinished(this, SLOT(requestFinished()));
333                 d->pix.connectDownloadProgress(this, SLOT(requestProgress(qint64,qint64)));
334             } else {
335                 QSize impsize = d->pix.implicitSize();
336                 setImplicitSize(impsize.width(), impsize.height());
337
338                 if (d->pix.isReady()) {
339                     d->status = Ready;
340                 } else {
341                     d->status = Error;
342                     qmlInfo(this) << d->pix.error();
343                 }
344
345                 d->progress = 1.0;
346                 emit statusChanged(d->status);
347                 emit progressChanged(d->progress);
348                 update();
349             }
350         }
351     }
352
353     emit statusChanged(d->status);
354 }
355
356 /*!
357     \qmlproperty int QtQuick2::BorderImage::border.left
358     \qmlproperty int QtQuick2::BorderImage::border.right
359     \qmlproperty int QtQuick2::BorderImage::border.top
360     \qmlproperty int QtQuick2::BorderImage::border.bottom
361
362     The 4 border lines (2 horizontal and 2 vertical) break the image into 9 sections,
363     as shown below:
364
365     \image declarative-scalegrid.png
366
367     Each border line (left, right, top, and bottom) specifies an offset in pixels
368     from the respective edge of the source image. By default, each border line has
369     a value of 0.
370
371     For example, the following definition sets the bottom line 10 pixels up from
372     the bottom of the image:
373
374     \qml
375     BorderImage {
376         border.bottom: 10
377         // ...
378     }
379     \endqml
380
381     The border lines can also be specified using a
382     \l {BorderImage::source}{.sci file}.
383 */
384
385 QQuickScaleGrid *QQuickBorderImage::border()
386 {
387     Q_D(QQuickBorderImage);
388     return d->getScaleGrid();
389 }
390
391 /*!
392     \qmlproperty enumeration QtQuick2::BorderImage::horizontalTileMode
393     \qmlproperty enumeration QtQuick2::BorderImage::verticalTileMode
394
395     This property describes how to repeat or stretch the middle parts of the border image.
396
397     \list
398     \li BorderImage.Stretch - Scales the image to fit to the available area.
399     \li BorderImage.Repeat - Tile the image until there is no more space. May crop the last image.
400     \li BorderImage.Round - Like Repeat, but scales the images down to ensure that the last image is not cropped.
401     \endlist
402
403     The default tile mode for each property is BorderImage.Stretch.
404 */
405 QQuickBorderImage::TileMode QQuickBorderImage::horizontalTileMode() const
406 {
407     Q_D(const QQuickBorderImage);
408     return d->horizontalTileMode;
409 }
410
411 void QQuickBorderImage::setHorizontalTileMode(TileMode t)
412 {
413     Q_D(QQuickBorderImage);
414     if (t != d->horizontalTileMode) {
415         d->horizontalTileMode = t;
416         emit horizontalTileModeChanged();
417         update();
418     }
419 }
420
421 QQuickBorderImage::TileMode QQuickBorderImage::verticalTileMode() const
422 {
423     Q_D(const QQuickBorderImage);
424     return d->verticalTileMode;
425 }
426
427 void QQuickBorderImage::setVerticalTileMode(TileMode t)
428 {
429     Q_D(QQuickBorderImage);
430     if (t != d->verticalTileMode) {
431         d->verticalTileMode = t;
432         emit verticalTileModeChanged();
433         update();
434     }
435 }
436
437 void QQuickBorderImage::setGridScaledImage(const QQuickGridScaledImage& sci)
438 {
439     Q_D(QQuickBorderImage);
440     if (!sci.isValid()) {
441         d->status = Error;
442         emit statusChanged(d->status);
443     } else {
444         QQuickScaleGrid *sg = border();
445         sg->setTop(sci.gridTop());
446         sg->setBottom(sci.gridBottom());
447         sg->setLeft(sci.gridLeft());
448         sg->setRight(sci.gridRight());
449         d->horizontalTileMode = sci.horizontalTileRule();
450         d->verticalTileMode = sci.verticalTileRule();
451
452         d->sciurl = d->url.resolved(QUrl(sci.pixmapUrl()));
453
454         QQuickPixmap::Options options;
455         if (d->async)
456             options |= QQuickPixmap::Asynchronous;
457         if (d->cache)
458             options |= QQuickPixmap::Cache;
459         d->pix.clear(this);
460         d->pix.load(qmlEngine(this), d->sciurl, options);
461
462         if (d->pix.isLoading()) {
463             static int thisRequestProgress = -1;
464             static int thisRequestFinished = -1;
465             if (thisRequestProgress == -1) {
466                 thisRequestProgress =
467                     QQuickBorderImage::staticMetaObject.indexOfSlot("requestProgress(qint64,qint64)");
468                 thisRequestFinished =
469                     QQuickBorderImage::staticMetaObject.indexOfSlot("requestFinished()");
470             }
471
472             d->pix.connectFinished(this, thisRequestFinished);
473             d->pix.connectDownloadProgress(this, thisRequestProgress);
474
475         } else {
476
477             QSize impsize = d->pix.implicitSize();
478             setImplicitSize(impsize.width(), impsize.height());
479
480             if (d->pix.isReady()) {
481                 d->status = Ready;
482             } else {
483                 d->status = Error;
484                 qmlInfo(this) << d->pix.error();
485             }
486
487             d->progress = 1.0;
488             emit statusChanged(d->status);
489             emit progressChanged(1.0);
490             update();
491
492         }
493     }
494 }
495
496 void QQuickBorderImage::requestFinished()
497 {
498     Q_D(QQuickBorderImage);
499
500     QSize impsize = d->pix.implicitSize();
501     if (d->pix.isError()) {
502         d->status = Error;
503         qmlInfo(this) << d->pix.error();
504     } else {
505         d->status = Ready;
506     }
507
508     setImplicitSize(impsize.width(), impsize.height());
509
510     if (d->sourcesize.width() != d->pix.width() || d->sourcesize.height() != d->pix.height())
511         emit sourceSizeChanged();
512
513     d->progress = 1.0;
514     emit statusChanged(d->status);
515     emit progressChanged(1.0);
516     update();
517 }
518
519 #define BORDERIMAGE_MAX_REDIRECT 16
520
521 void QQuickBorderImage::sciRequestFinished()
522 {
523     Q_D(QQuickBorderImage);
524
525     d->redirectCount++;
526     if (d->redirectCount < BORDERIMAGE_MAX_REDIRECT) {
527         QVariant redirect = d->sciReply->attribute(QNetworkRequest::RedirectionTargetAttribute);
528         if (redirect.isValid()) {
529             QUrl url = d->sciReply->url().resolved(redirect.toUrl());
530             setSource(url);
531             return;
532         }
533     }
534     d->redirectCount=0;
535
536     if (d->sciReply->error() != QNetworkReply::NoError) {
537         d->status = Error;
538         d->sciReply->deleteLater();
539         d->sciReply = 0;
540         emit statusChanged(d->status);
541     } else {
542         QQuickGridScaledImage sci(d->sciReply);
543         d->sciReply->deleteLater();
544         d->sciReply = 0;
545         setGridScaledImage(sci);
546     }
547 }
548
549 void QQuickBorderImage::doUpdate()
550 {
551     update();
552 }
553
554 QSGNode *QQuickBorderImage::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
555 {
556     Q_D(QQuickBorderImage);
557
558     QSGTexture *texture = d->sceneGraphContext()->textureForFactory(d->pix.textureFactory(), canvas());
559
560     if (!texture || width() <= 0 || height() <= 0) {
561         delete oldNode;
562         return 0;
563     }
564
565     QQuickNinePatchNode *node = static_cast<QQuickNinePatchNode *>(oldNode);
566
567     if (!node) {
568         node = new QQuickNinePatchNode();
569     }
570
571     node->setTexture(texture);
572
573     // Don't implicitly create the scalegrid in the rendering thread...
574     if (d->border) {
575         const QQuickScaleGrid *border = d->getScaleGrid();
576         node->setInnerRect(QRectF(border->left(),
577                                   border->top(),
578                                   qMax(1, d->pix.width() - border->right() - border->left()),
579                                   qMax(1, d->pix.height() - border->bottom() - border->top())));
580     } else {
581         node->setInnerRect(QRectF(0, 0, d->pix.width(), d->pix.height()));
582     }
583     node->setRect(QRectF(0, 0, width(), height()));
584     node->setFiltering(d->smooth ? QSGTexture::Linear : QSGTexture::Nearest);
585     node->setHorzontalTileMode(d->horizontalTileMode);
586     node->setVerticalTileMode(d->verticalTileMode);
587     node->setMirror(d->mirror);
588     node->update();
589
590     return node;
591 }
592
593 void QQuickBorderImage::pixmapChange()
594 {
595     Q_D(QQuickBorderImage);
596
597     d->pixmapChanged = true;
598
599     // When the pixmap changes, such as being deleted, we need to update the textures
600     update();
601 }
602
603 QT_END_NAMESPACE