ab4bd979f83599f9757558c6c9abdab9ae522329
[profile/ivi/qtdeclarative.git] / src / quick / items / qquickrectangle.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: http://www.qt-project.org/
6 **
7 ** This file is part of the QtDeclarative 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 "qquickrectangle_p.h"
43 #include "qquickrectangle_p_p.h"
44
45 #include <QtQuick/private/qsgcontext_p.h>
46 #include <private/qsgadaptationlayer_p.h>
47
48 #include <QtGui/qpixmapcache.h>
49 #include <QtCore/qstringbuilder.h>
50 #include <QtCore/qmath.h>
51
52 QT_BEGIN_NAMESPACE
53
54 // XXX todo - should we change rectangle to draw entirely within its width/height?
55 /*!
56     \internal
57     \class QQuickPen
58     \brief The QQuickPen class provides a pen used for drawing rectangle borders on a QQuickView.
59
60     By default, the pen is invalid and nothing is drawn. You must either set a color (then the default
61     width is 1) or a width (then the default color is black).
62
63     A width of 1 indicates is a single-pixel line on the border of the item being painted.
64
65     Example:
66     \qml
67     Rectangle {
68         border.width: 2
69         border.color: "red"
70     }
71     \endqml
72 */
73
74 QQuickPen::QQuickPen(QObject *parent)
75     : QObject(parent)
76     , m_width(1)
77     , m_color("#000000")
78     , m_aligned(true)
79     , m_valid(false)
80 {
81 }
82
83 qreal QQuickPen::width() const
84 {
85     return m_width;
86 }
87
88 void QQuickPen::setWidth(qreal w)
89 {
90     if (m_width == w && m_valid)
91         return;
92
93     m_width = w;
94     m_valid = m_color.alpha() && (qRound(m_width) >= 1 || (!m_aligned && m_width > 0));
95     emit penChanged();
96 }
97
98 QColor QQuickPen::color() const
99 {
100     return m_color;
101 }
102
103 void QQuickPen::setColor(const QColor &c)
104 {
105     m_color = c;
106     m_valid = m_color.alpha() && (qRound(m_width) >= 1 || (!m_aligned && m_width > 0));
107     emit penChanged();
108 }
109
110 bool QQuickPen::aligned() const
111 {
112     return m_aligned;
113 }
114
115 void QQuickPen::setAligned(bool aligned)
116 {
117     if (aligned == m_aligned)
118         return;
119     m_aligned = aligned;
120     m_valid = m_color.alpha() && (qRound(m_width) >= 1 || (!m_aligned && m_width > 0));
121     emit penChanged();
122 }
123
124 bool QQuickPen::isValid() const
125 {
126     return m_valid;
127 }
128
129 /*!
130     \qmlclass GradientStop QQuickGradientStop
131     \inqmlmodule QtQuick 2
132     \ingroup qml-basic-visual-elements
133     \brief The GradientStop item defines the color at a position in a Gradient.
134
135     \sa Gradient
136 */
137
138 /*!
139     \qmlproperty real QtQuick2::GradientStop::position
140     \qmlproperty color QtQuick2::GradientStop::color
141
142     The position and color properties describe the color used at a given
143     position in a gradient, as represented by a gradient stop.
144
145     The default position is 0.0; the default color is black.
146
147     \sa Gradient
148 */
149 QQuickGradientStop::QQuickGradientStop(QObject *parent)
150     : QObject(parent)
151 {
152 }
153
154 qreal QQuickGradientStop::position() const
155 {
156     return m_position;
157 }
158
159 void QQuickGradientStop::setPosition(qreal position)
160 {
161     m_position = position; updateGradient();
162 }
163
164 QColor QQuickGradientStop::color() const
165 {
166     return m_color;
167 }
168
169 void QQuickGradientStop::setColor(const QColor &color)
170 {
171     m_color = color; updateGradient();
172 }
173
174 void QQuickGradientStop::updateGradient()
175 {
176     if (QQuickGradient *grad = qobject_cast<QQuickGradient*>(parent()))
177         grad->doUpdate();
178 }
179
180 /*!
181     \qmlclass Gradient QQuickGradient
182     \inqmlmodule QtQuick 2
183     \ingroup qml-basic-visual-elements
184     \brief The Gradient item defines a gradient fill.
185
186     A gradient is defined by two or more colors, which will be blended seamlessly.
187
188     The colors are specified as a set of GradientStop child items, each of
189     which defines a position on the gradient from 0.0 to 1.0 and a color.
190     The position of each GradientStop is defined by setting its
191     \l{GradientStop::}{position} property; its color is defined using its
192     \l{GradientStop::}{color} property.
193
194     A gradient without any gradient stops is rendered as a solid white fill.
195
196     Note that this item is not a visual representation of a gradient. To display a
197     gradient, use a visual element (like \l Rectangle) which supports the use
198     of gradients.
199
200     \section1 Example Usage
201
202     \div {class="float-right"}
203     \inlineimage qml-gradient.png
204     \enddiv
205
206     The following example declares a \l Rectangle item with a gradient starting
207     with red, blending to yellow at one third of the height of the rectangle,
208     and ending with green:
209
210     \snippet doc/src/snippets/declarative/gradient.qml code
211
212     \clearfloat
213     \section1 Performance and Limitations
214
215     Calculating gradients can be computationally expensive compared to the use
216     of solid color fills or images. Consider using gradients for static items
217     in a user interface.
218
219     In Qt 4.7, only vertical, linear gradients can be applied to items. If you
220     need to apply different orientations of gradients, a combination of rotation
221     and clipping will need to be applied to the relevant items. This can
222     introduce additional performance requirements for your application.
223
224     The use of animations involving gradient stops may not give the desired
225     result. An alternative way to animate gradients is to use pre-generated
226     images or SVG drawings containing gradients.
227
228     \sa GradientStop
229 */
230
231 /*!
232     \qmlproperty list<GradientStop> QtQuick2::Gradient::stops
233     \default
234
235     This property holds the gradient stops describing the gradient.
236
237     By default, this property contains an empty list.
238
239     To set the gradient stops, define them as children of the Gradient element.
240 */
241 QQuickGradient::QQuickGradient(QObject *parent)
242 : QObject(parent), m_gradient(0)
243 {
244 }
245
246 QQuickGradient::~QQuickGradient()
247 {
248     delete m_gradient;
249 }
250
251 QDeclarativeListProperty<QQuickGradientStop> QQuickGradient::stops()
252 {
253     return QDeclarativeListProperty<QQuickGradientStop>(this, m_stops);
254 }
255
256 const QGradient *QQuickGradient::gradient() const
257 {
258     if (!m_gradient && !m_stops.isEmpty()) {
259         m_gradient = new QLinearGradient(0,0,0,1.0);
260         for (int i = 0; i < m_stops.count(); ++i) {
261             const QQuickGradientStop *stop = m_stops.at(i);
262             m_gradient->setCoordinateMode(QGradient::ObjectBoundingMode);
263             m_gradient->setColorAt(stop->position(), stop->color());
264         }
265     }
266
267     return m_gradient;
268 }
269
270 void QQuickGradient::doUpdate()
271 {
272     delete m_gradient;
273     m_gradient = 0;
274     emit updated();
275 }
276
277 int QQuickRectanglePrivate::doUpdateSlotIdx = -1;
278
279 /*!
280     \qmlclass Rectangle QQuickRectangle
281     \inqmlmodule QtQuick 2
282     \ingroup qml-basic-visual-elements
283     \brief The Rectangle item provides a filled rectangle with an optional border.
284     \inherits Item
285
286     Rectangle items are used to fill areas with solid color or gradients, and are
287     often used to hold other items.
288
289     \section1 Appearance
290
291     Each Rectangle item is painted using either a solid fill color, specified using
292     the \l color property, or a gradient, defined using a Gradient element and set
293     using the \l gradient property. If both a color and a gradient are specified,
294     the gradient is used.
295
296     You can add an optional border to a rectangle with its own color and thickness
297     by setting the \l border.color and \l border.width properties.
298
299     You can also create rounded rectangles using the \l radius property. Since this
300     introduces curved edges to the corners of a rectangle, it may be appropriate to
301     set the \l smooth property to improve its appearance.
302
303     \section1 Example Usage
304
305     \div {class="float-right"}
306     \inlineimage declarative-rect.png
307     \enddiv
308
309     The following example shows the effects of some of the common properties on a
310     Rectangle item, which in this case is used to create a square:
311
312     \snippet doc/src/snippets/declarative/rectangle/rectangle.qml document
313
314     \clearfloat
315     \section1 Performance
316
317     Using the \l smooth property improves the appearance of a rounded rectangle at
318     the cost of rendering performance. You should consider unsetting this property
319     for rectangles in motion, and only set it when they are stationary.
320
321     \sa Image
322 */
323
324 QQuickRectangle::QQuickRectangle(QQuickItem *parent)
325 : QQuickItem(*(new QQuickRectanglePrivate), parent)
326 {
327     setFlag(ItemHasContents);
328 }
329
330 void QQuickRectangle::doUpdate()
331 {
332     Q_D(QQuickRectangle);
333     qreal penMargin = 0;
334     qreal penOffset = 0;
335     if (d->pen && d->pen->isValid()) {
336         if (d->pen->aligned()) {
337             const int pw = qRound(d->pen->width());
338             penMargin = qreal(0.5) * pw;
339             penOffset = (pw & 1) * qreal(0.5);
340         } else {
341             penMargin = qreal(0.5) * d->pen->width();
342         }
343     }
344     if (penMargin != d->penMargin || penOffset != d->penOffset) {
345         d->penMargin = penMargin;
346         d->penOffset = penOffset;
347         d->dirty(QQuickItemPrivate::Size); // update clip
348     }
349     update();
350 }
351
352 /*!
353     \qmlproperty int QtQuick2::Rectangle::border.width
354     \qmlproperty color QtQuick2::Rectangle::border.color
355
356     The width and color used to draw the border of the rectangle.
357
358     A width of 1 creates a thin line. For no line, use a width of 0 or a transparent color.
359
360     \note The width of the rectangle's border does not affect the geometry of the
361     rectangle itself or its position relative to other items if anchors are used.
362
363     If \c border.width is an odd number, the rectangle is painted at a half-pixel offset to retain
364     border smoothness. Also, the border is rendered evenly on either side of the
365     rectangle's boundaries, and the spare pixel is rendered to the right and below the
366     rectangle (as documented for QRect rendering). This can cause unintended effects if
367     \c border.width is 1 and the rectangle is \l{Item::clip}{clipped} by a parent item:
368
369     \div {class="float-right"}
370     \inlineimage rect-border-width.png
371     \enddiv
372
373     \snippet doc/src/snippets/declarative/rectangle/rect-border-width.qml 0
374
375     \clearfloat
376     Here, the innermost rectangle's border is clipped on the bottom and right edges by its
377     parent. To avoid this, the border width can be set to two instead of one.
378 */
379 QQuickPen *QQuickRectangle::border()
380 {
381     Q_D(QQuickRectangle);
382     return d->getPen();
383 }
384
385 /*!
386     \qmlproperty Gradient QtQuick2::Rectangle::gradient
387
388     The gradient to use to fill the rectangle.
389
390     This property allows for the construction of simple vertical gradients.
391     Other gradients may by formed by adding rotation to the rectangle.
392
393     \div {class="float-left"}
394     \inlineimage declarative-rect_gradient.png
395     \enddiv
396
397     \snippet doc/src/snippets/declarative/rectangle/rectangle-gradient.qml rectangles
398     \clearfloat
399
400     If both a gradient and a color are specified, the gradient will be used.
401
402     \sa Gradient, color
403 */
404 QQuickGradient *QQuickRectangle::gradient() const
405 {
406     Q_D(const QQuickRectangle);
407     return d->gradient;
408 }
409
410 void QQuickRectangle::setGradient(QQuickGradient *gradient)
411 {
412     Q_D(QQuickRectangle);
413     if (d->gradient == gradient)
414         return;
415     static int updatedSignalIdx = -1;
416     if (updatedSignalIdx < 0)
417         updatedSignalIdx = QQuickGradient::staticMetaObject.indexOfSignal("updated()");
418     if (d->doUpdateSlotIdx < 0)
419         d->doUpdateSlotIdx = QQuickRectangle::staticMetaObject.indexOfSlot("doUpdate()");
420     if (d->gradient)
421         QMetaObject::disconnect(d->gradient, updatedSignalIdx, this, d->doUpdateSlotIdx);
422     d->gradient = gradient;
423     if (d->gradient)
424         QMetaObject::connect(d->gradient, updatedSignalIdx, this, d->doUpdateSlotIdx);
425     update();
426 }
427
428 /*!
429     \qmlproperty real QtQuick2::Rectangle::radius
430     This property holds the corner radius used to draw a rounded rectangle.
431
432     If radius is non-zero, the rectangle will be painted as a rounded rectangle, otherwise it will be
433     painted as a normal rectangle. The same radius is used by all 4 corners; there is currently
434     no way to specify different radii for different corners.
435 */
436 qreal QQuickRectangle::radius() const
437 {
438     Q_D(const QQuickRectangle);
439     return d->radius;
440 }
441
442 void QQuickRectangle::setRadius(qreal radius)
443 {
444     Q_D(QQuickRectangle);
445     if (d->radius == radius)
446         return;
447
448     d->radius = radius;
449     update();
450     emit radiusChanged();
451 }
452
453 /*!
454     \qmlproperty color QtQuick2::Rectangle::color
455     This property holds the color used to fill the rectangle.
456
457     The default color is white.
458
459     \div {class="float-right"}
460     \inlineimage rect-color.png
461     \enddiv
462
463     The following example shows rectangles with colors specified
464     using hexadecimal and named color notation:
465
466     \snippet doc/src/snippets/declarative/rectangle/rectangle-colors.qml rectangles
467
468     \clearfloat
469     If both a gradient and a color are specified, the gradient will be used.
470
471     \sa gradient
472 */
473 QColor QQuickRectangle::color() const
474 {
475     Q_D(const QQuickRectangle);
476     return d->color;
477 }
478
479 void QQuickRectangle::setColor(const QColor &c)
480 {
481     Q_D(QQuickRectangle);
482     if (d->color == c)
483         return;
484
485     d->color = c;
486     update();
487     emit colorChanged();
488 }
489
490 QSGNode *QQuickRectangle::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *data)
491 {
492     Q_UNUSED(data);
493     Q_D(QQuickRectangle);
494
495     if (width() <= 0 || height() <= 0
496             || (d->color.alpha() == 0 && (!d->pen || d->pen->width() == 0 || d->pen->color().alpha() == 0))) {
497         delete oldNode;
498         return 0;
499     }
500
501     QSGRectangleNode *rectangle = static_cast<QSGRectangleNode *>(oldNode);
502     if (!rectangle) rectangle = d->sceneGraphContext()->createRectangleNode();
503
504     rectangle->setRect(QRectF(0, 0, width(), height()));
505     rectangle->setColor(d->color);
506
507     if (d->pen && d->pen->isValid()) {
508         rectangle->setPenColor(d->pen->color());
509         rectangle->setPenWidth(d->pen->width());
510         rectangle->setAligned(d->pen->aligned());
511     } else {
512         rectangle->setPenWidth(0);
513     }
514
515     rectangle->setRadius(d->radius);
516
517     QGradientStops stops;
518     if (d->gradient) {
519         QList<QQuickGradientStop *> qxstops = d->gradient->m_stops;
520         for (int i = 0; i < qxstops.size(); ++i){
521             int j = 0;
522             while (j < stops.size() && stops.at(j).first < qxstops[i]->position())
523                 j++;
524             stops.insert(j, QGradientStop(qxstops.at(i)->position(), qxstops.at(i)->color()));
525         }
526     }
527     rectangle->setGradientStops(stops);
528
529     rectangle->update();
530
531     return rectangle;
532 }
533 /*!
534     \qmlproperty bool QtQuick2::Rectangle::smooth
535
536     Set this property if you want the item to be smoothly scaled or
537     transformed.  Smooth filtering gives better visual quality, but is slower.  If
538     the item is displayed at its natural size, this property has no visual or
539     performance effect.
540
541     \note Generally scaling artifacts are only visible if the item is stationary on
542     the screen.  A common pattern when animating an item is to disable smooth
543     filtering at the beginning of the animation and reenable it at the conclusion.
544
545     \image rect-smooth.png
546     On this image, smooth is turned off for the top half and on for the bottom half.
547 */
548
549 QRectF QQuickRectangle::boundingRect() const
550 {
551     Q_D(const QQuickRectangle);
552     return QRectF(d->penOffset - d->penMargin, d->penOffset - d->penMargin,
553                   d->width + 2 * d->penMargin, d->height + 2 * d->penMargin);
554 }
555
556 QT_END_NAMESPACE